StreamVault is a TV-first free IPTV player for Android TV built with Kotlin, Jetpack Compose, Room, Hilt, and Media3.
Kotlin iptv-player
feat: Add provider capability registry and configuration models
David Nashash95fd85571e8f
diff --git a/app/src/main/java/com/streamvault/app/di/DatabaseModule.kt b/app/src/main/java/com/streamvault/app/di/DatabaseModule.ktindex f75b897b..de29fffe 100644--- a/app/src/main/java/com/streamvault/app/di/DatabaseModule.kt+++ b/app/src/main/java/com/streamvault/app/di/DatabaseModule.kt@@ -112,7 +112,9 @@ object DatabaseModule {StreamVaultDatabase.MIGRATION_68_69,StreamVaultDatabase.MIGRATION_69_70,StreamVaultDatabase.MIGRATION_70_71,- StreamVaultDatabase.MIGRATION_71_72+ StreamVaultDatabase.MIGRATION_71_72,+ StreamVaultDatabase.MIGRATION_72_73,+ StreamVaultDatabase.MIGRATION_73_74)// NOTE: fallbackToDestructiveMigration() intentionally removed.// All future schema changes MUST add a corresponding Migration in StreamVaultDatabase.@@ -122,6 +124,7 @@ object DatabaseModule {fun provideJellyfinProvider(okHttpClient: OkHttpClient, gson: Gson): JellyfinProvider = JellyfinProvider(okHttpClient, gson)@Provides fun provideProviderDao(db: StreamVaultDatabase): ProviderDao = db.providerDao()+ @Provides fun provideProviderSnapshotDao(db: StreamVaultDatabase): ProviderSnapshotDao = db.providerSnapshotDao()@Provides fun provideChannelDao(db: StreamVaultDatabase): ChannelDao = db.channelDao()@Provides fun provideChannelPreferenceDao(db: StreamVaultDatabase): ChannelPreferenceDao = db.channelPreferenceDao()@Provides fun provideMovieDao(db: StreamVaultDatabase): MovieDao = db.movieDao()diff --git a/app/src/main/java/com/streamvault/app/di/RepositoryModule.kt b/app/src/main/java/com/streamvault/app/di/RepositoryModule.ktindex 16fbe1d4..2c9736ee 100644--- a/app/src/main/java/com/streamvault/app/di/RepositoryModule.kt+++ b/app/src/main/java/com/streamvault/app/di/RepositoryModule.kt@@ -7,6 +7,12 @@ import com.streamvault.data.preferences.PreferencesRepositoryimport com.streamvault.data.security.AndroidKeystoreCredentialCryptoimport com.streamvault.data.security.CredentialCryptoimport com.streamvault.data.sync.ProviderSyncStateReaderImpl+import com.streamvault.data.provider.RoomProviderSnapshotRepository+import com.streamvault.data.provider.DefaultProviderCapabilityRegistry+import com.streamvault.data.provider.JellyfinCapabilityFactory+import com.streamvault.data.provider.M3uCapabilityFactory+import com.streamvault.data.provider.StalkerCapabilityFactory+import com.streamvault.data.provider.XtreamCapabilityFactoryimport com.streamvault.data.validation.ProviderSetupInputValidatorImplimport com.streamvault.domain.manager.ParentalPinVerifierimport com.streamvault.domain.manager.ProviderSetupInputValidator@@ -14,6 +20,7 @@ import com.streamvault.domain.manager.ProviderSyncStateReaderimport com.streamvault.data.repository.*import com.streamvault.domain.manager.ParentalControlSessionStoreimport com.streamvault.domain.repository.*+import com.streamvault.domain.provider.ProviderCapabilityRegistryimport dagger.Bindsimport dagger.Moduleimport dagger.Provides@@ -31,6 +38,9 @@ abstract class RepositoryModule {@Binds @Singletonabstract fun bindProviderRepository(impl: ProviderRepositoryImpl): ProviderRepository+ @Binds @Singleton+ abstract fun bindProviderSnapshotRepository(impl: RoomProviderSnapshotRepository): ProviderSnapshotRepository+@Binds @Singletonabstract fun bindChannelRepository(impl: ChannelRepositoryImpl): ChannelRepository@@ -118,5 +128,16 @@ abstract class RepositoryModule {fun provideM3uParser(): com.streamvault.data.parser.M3uParser {return com.streamvault.data.parser.M3uParser()}++ @Provides+ @Singleton+ fun provideProviderCapabilityRegistry(+ xtream: XtreamCapabilityFactory,+ stalker: StalkerCapabilityFactory,+ m3u: M3uCapabilityFactory,+ jellyfin: JellyfinCapabilityFactory+ ): ProviderCapabilityRegistry = DefaultProviderCapabilityRegistry(+ listOf(xtream, stalker, m3u, jellyfin)+ )}}diff --git a/app/src/main/java/com/streamvault/app/plugins/StreamVaultPluginManager.kt b/app/src/main/java/com/streamvault/app/plugins/StreamVaultPluginManager.ktindex 5e41872c..5d720d1c 100644--- a/app/src/main/java/com/streamvault/app/plugins/StreamVaultPluginManager.kt+++ b/app/src/main/java/com/streamvault/app/plugins/StreamVaultPluginManager.kt@@ -23,13 +23,15 @@ import com.streamvault.data.remote.http.useCancellableResponseimport com.streamvault.domain.model.ActiveLiveSourceimport com.streamvault.domain.model.DrmInfoimport com.streamvault.domain.model.DrmScheme-import com.streamvault.domain.model.Provider+import com.streamvault.domain.model.M3uConfig+import com.streamvault.domain.model.LegacyProvider as Providerimport com.streamvault.domain.model.ProviderEpgSyncModeimport com.streamvault.domain.model.Resultimport com.streamvault.domain.model.StreamInfoimport com.streamvault.domain.model.StreamTypeimport com.streamvault.domain.repository.CombinedM3uRepositoryimport com.streamvault.domain.repository.ProviderRepository+import com.streamvault.domain.repository.ProviderSetupRequestimport dagger.hilt.android.qualifiers.ApplicationContextimport java.io.Fileimport java.net.URI@@ -586,11 +588,15 @@ class StreamVaultPluginManager @Inject constructor(}updatedProvider} else {- when (val createResult = providerRepository.validateM3u(- url = providerUrl,- name = providerName,- epgSyncMode = ProviderEpgSyncMode.BACKGROUND,- m3uVodClassificationEnabled = false,+ when (val createResult = providerRepository.setupProvider(+ request = ProviderSetupRequest.Configured(+ name = providerName,+ configuration = M3uConfig(+ playlistUrl = providerUrl,+ epgSyncMode = ProviderEpgSyncMode.BACKGROUND,+ vodClassificationEnabled = false+ )+ ),onProgress = onProgress)) {is Result.Error -> return PluginActionResult(false, createResult.message)diff --git a/app/src/main/java/com/streamvault/app/tv/LauncherRecommendationsManager.kt b/app/src/main/java/com/streamvault/app/tv/LauncherRecommendationsManager.ktindex 158df00b..a53ef9a3 100644--- a/app/src/main/java/com/streamvault/app/tv/LauncherRecommendationsManager.kt+++ b/app/src/main/java/com/streamvault/app/tv/LauncherRecommendationsManager.kt@@ -19,7 +19,7 @@ import com.streamvault.app.navigation.toPlayerNavigationRequestimport com.streamvault.domain.model.ActiveLiveSourceimport com.streamvault.domain.model.ContentTypeimport com.streamvault.domain.model.PlaybackHistory-import com.streamvault.domain.model.Provider+import com.streamvault.domain.model.LegacyProvider as Providerimport com.streamvault.domain.repository.CombinedM3uRepositoryimport com.streamvault.domain.repository.MovieRepositoryimport com.streamvault.domain.repository.PlaybackHistoryRepositorydiff --git a/app/src/main/java/com/streamvault/app/tvinput/TvInputSetupActivity.kt b/app/src/main/java/com/streamvault/app/tvinput/TvInputSetupActivity.ktindex 020d48d3..13a7bd3f 100644--- a/app/src/main/java/com/streamvault/app/tvinput/TvInputSetupActivity.kt+++ b/app/src/main/java/com/streamvault/app/tvinput/TvInputSetupActivity.kt@@ -45,7 +45,7 @@ import com.streamvault.app.ui.theme.OnSurfaceDimimport com.streamvault.app.ui.theme.Primaryimport com.streamvault.app.ui.theme.StreamVaultThemeimport com.streamvault.app.ui.theme.SurfaceElevated-import com.streamvault.domain.model.Provider+import com.streamvault.domain.model.LegacyProvider as Providerimport com.streamvault.domain.repository.ProviderRepositoryimport dagger.hilt.android.AndroidEntryPointimport dagger.hilt.android.lifecycle.HiltViewModeldiff --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 be790680..2136d337 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@@ -17,7 +17,7 @@ import com.streamvault.domain.model.ContentTypeimport com.streamvault.domain.model.Favoriteimport com.streamvault.domain.model.Movieimport com.streamvault.domain.model.PlaybackHistory-import com.streamvault.domain.model.Provider+import com.streamvault.domain.model.LegacyProvider as Providerimport com.streamvault.domain.model.ProviderStatusimport com.streamvault.domain.model.ProviderTypeimport com.streamvault.domain.model.Seriesdiff --git a/app/src/main/java/com/streamvault/app/ui/screens/epg/EpgViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/epg/EpgViewModel.ktindex d6c1f633..f93bacda 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/epg/EpgViewModel.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/epg/EpgViewModel.kt@@ -1074,7 +1074,7 @@ class EpgViewModel @Inject constructor(}}- private suspend fun observeSingleProviderGuide(provider: com.streamvault.domain.model.Provider) {+ private suspend fun observeSingleProviderGuide(provider: com.streamvault.domain.model.LegacyProvider) {combine(channelRepository.getCategories(provider.id),getCustomCategories(provider.id, ContentType.LIVE),@@ -1533,7 +1533,7 @@ class EpgViewModel @Inject constructor(}}- private fun buildProviderSourceLabel(provider: com.streamvault.domain.model.Provider): String {+ private fun buildProviderSourceLabel(provider: com.streamvault.domain.model.LegacyProvider): String {return when (provider.type) {com.streamvault.domain.model.ProviderType.XTREAM_CODES -> "Xtream Codes"com.streamvault.domain.model.ProviderType.M3U -> "M3U Playlist"@@ -1542,7 +1542,7 @@ class EpgViewModel @Inject constructor(}}- private fun buildProviderArchiveSummary(provider: com.streamvault.domain.model.Provider): String {+ private fun buildProviderArchiveSummary(provider: com.streamvault.domain.model.LegacyProvider): String {return when (provider.type) {com.streamvault.domain.model.ProviderType.XTREAM_CODES ->"Xtream replay depends on archive-enabled channels and valid replay stream ids from the provider."@@ -1805,7 +1805,7 @@ class EpgViewModel @Inject constructor(}private suspend fun fetchXtreamGuideFallback(- provider: com.streamvault.domain.model.Provider,+ provider: com.streamvault.domain.model.LegacyProvider,providerId: Long,channels: List<Channel>,existingProgramsByChannel: Map<String, List<Program>>,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 de1b169a..f0b5e493 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@@ -9,7 +9,7 @@ import com.streamvault.domain.model.Channelimport com.streamvault.domain.model.ContentTypeimport com.streamvault.domain.model.Favoriteimport com.streamvault.domain.model.PlaybackHistory-import com.streamvault.domain.model.Provider+import com.streamvault.domain.model.LegacyProvider as Providerimport com.streamvault.domain.model.Resultimport com.streamvault.domain.model.VirtualCategoryIdsimport com.streamvault.domain.model.VirtualGroupdiff --git a/app/src/main/java/com/streamvault/app/ui/screens/home/HomeScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/home/HomeScreen.ktindex 00bdbafb..332a9bc7 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/home/HomeScreen.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/home/HomeScreen.kt@@ -73,7 +73,7 @@ import com.streamvault.app.ui.theme.*import com.streamvault.domain.model.ActiveLiveSourceimport com.streamvault.domain.model.Categoryimport com.streamvault.domain.model.Channel-import com.streamvault.domain.model.Provider+import com.streamvault.domain.model.LegacyProvider as Providerimport kotlinx.coroutines.launchimport kotlinx.coroutines.flow.distinctUntilChangedimport kotlinx.coroutines.flow.filterdiff --git a/app/src/main/java/com/streamvault/app/ui/screens/home/HomeScreenDialogs.kt b/app/src/main/java/com/streamvault/app/ui/screens/home/HomeScreenDialogs.ktindex a10f6758..3ca531f7 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/home/HomeScreenDialogs.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/home/HomeScreenDialogs.kt@@ -26,7 +26,7 @@ import com.streamvault.app.ui.screens.multiview.MultiViewViewModelimport com.streamvault.domain.model.ActiveLiveSourceimport com.streamvault.domain.model.Categoryimport com.streamvault.domain.model.Channel-import com.streamvault.domain.model.Provider+import com.streamvault.domain.model.LegacyProvider as Providerimport com.streamvault.domain.model.Resultimport com.streamvault.domain.model.VirtualCategoryIdsimport com.streamvault.domain.repository.ChannelRepositorydiff --git a/app/src/main/java/com/streamvault/app/ui/screens/home/HomeViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/home/HomeViewModel.ktindex 1a29ce7e..41e38528 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/home/HomeViewModel.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/home/HomeViewModel.kt@@ -28,7 +28,7 @@ import com.streamvault.domain.model.ContentTypeimport com.streamvault.domain.model.Favoriteimport com.streamvault.domain.model.PlaybackHistoryimport com.streamvault.domain.model.Program-import com.streamvault.domain.model.Provider+import com.streamvault.domain.model.LegacyProvider as Providerimport com.streamvault.domain.model.ProviderTypeimport com.streamvault.domain.model.Resultimport com.streamvault.domain.model.StreamInfodiff --git a/app/src/main/java/com/streamvault/app/ui/screens/search/SearchScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/search/SearchScreen.ktindex aee0c4b3..22bd427b 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/search/SearchScreen.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/search/SearchScreen.kt@@ -315,7 +315,7 @@ class SearchViewModel @Inject constructor(}private data class SearchFilterParams(- val provider: com.streamvault.domain.model.Provider?,+ val provider: com.streamvault.domain.model.LegacyProvider?,val query: String,val tab: SearchTab,val level: Int,diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsCombinedM3uComponents.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsCombinedM3uComponents.ktindex 2eaa3938..58fcac42 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsCombinedM3uComponents.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsCombinedM3uComponents.kt@@ -47,7 +47,7 @@ import com.streamvault.app.ui.theme.Primaryimport com.streamvault.app.ui.theme.SurfaceElevatedimport com.streamvault.domain.model.ActiveLiveSourceimport com.streamvault.domain.model.CombinedM3uProfile-import com.streamvault.domain.model.Provider+import com.streamvault.domain.model.LegacyProvider as Providerimport com.streamvault.domain.model.ProviderType@Composablediff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsContentPane.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsContentPane.ktindex 9031ebbc..a6beaffd 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsContentPane.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsContentPane.kt@@ -9,7 +9,7 @@ import androidx.compose.foundation.lazy.LazyColumnimport androidx.compose.runtime.Composableimport androidx.compose.ui.Modifierimport androidx.compose.ui.unit.dp-import com.streamvault.domain.model.Provider+import com.streamvault.domain.model.LegacyProvider as Provider@Composableinternal fun SettingsContentPane(diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsDerivedStateObservers.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsDerivedStateObservers.ktindex caae8141..67598381 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsDerivedStateObservers.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsDerivedStateObservers.kt@@ -8,7 +8,7 @@ import com.streamvault.data.local.dao.ProgramDaoimport com.streamvault.domain.model.Categoryimport com.streamvault.domain.model.CategorySortModeimport com.streamvault.domain.model.ContentType-import com.streamvault.domain.model.Provider+import com.streamvault.domain.model.LegacyProvider as Providerimport com.streamvault.domain.model.ProviderTypeimport com.streamvault.domain.model.VodSyncModeimport com.streamvault.domain.repository.CategoryRepositorydiff --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 690ccca2..777bef58 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@@ -23,7 +23,7 @@ import com.streamvault.domain.model.VodDuplicateHandlingModeimport com.streamvault.domain.model.VodHttpProtocolModeimport com.streamvault.domain.model.VodVariantPreferenceModeimport com.streamvault.domain.model.PlayerSurfaceMode-import com.streamvault.domain.model.Provider+import com.streamvault.domain.model.LegacyProvider as Providerimport com.streamvault.domain.model.RemoteShortcutPreferencesimport com.streamvault.domain.model.TimeshiftBackendPreferencediff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsProviderComponents.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsProviderComponents.ktindex acd3e561..f54ac375 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsProviderComponents.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsProviderComponents.kt@@ -48,7 +48,7 @@ import com.streamvault.app.ui.time.LocalAppTimeFormatimport com.streamvault.app.ui.time.createDateTimeFormatimport com.streamvault.domain.model.ActiveLiveSourceimport com.streamvault.domain.model.CombinedM3uProfile-import com.streamvault.domain.model.Provider+import com.streamvault.domain.model.LegacyProvider as Providerimport com.streamvault.domain.model.ProviderStatusimport com.streamvault.domain.model.ProviderTypeimport kotlinx.coroutines.launchdiff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsProviderDiagnosticsPanel.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsProviderDiagnosticsPanel.ktindex 46575e5a..59cdcac5 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsProviderDiagnosticsPanel.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsProviderDiagnosticsPanel.kt@@ -22,7 +22,7 @@ import com.streamvault.app.ui.theme.OnSurfaceDimimport com.streamvault.app.ui.theme.Primaryimport com.streamvault.app.ui.time.LocalAppTimeFormatimport com.streamvault.app.ui.time.createDateTimeFormat-import com.streamvault.domain.model.Provider+import com.streamvault.domain.model.LegacyProvider as Providerimport com.streamvault.domain.model.ProviderTypeimport java.text.DateFormatimport java.util.Localediff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsProviderSection.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsProviderSection.ktindex 0e69cb64..16b38447 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsProviderSection.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsProviderSection.kt@@ -29,7 +29,7 @@ import com.streamvault.app.ui.components.TvEmptyStateimport com.streamvault.app.ui.interaction.TvClickableSurfaceimport com.streamvault.app.ui.theme.OnSurfaceDimimport com.streamvault.app.ui.theme.Primary-import com.streamvault.domain.model.Provider+import com.streamvault.domain.model.LegacyProvider as Providerimport com.streamvault.domain.model.ProviderTypeinternal fun LazyListScope.providerSection(diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsProviderSyncDialogs.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsProviderSyncDialogs.ktindex 4585dc6b..fb5cd2d3 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsProviderSyncDialogs.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsProviderSyncDialogs.kt@@ -21,7 +21,7 @@ import com.streamvault.app.ui.components.dialogs.PremiumDialogFooterButtonimport com.streamvault.app.ui.interaction.TvButtonimport com.streamvault.app.ui.theme.OnBackgroundimport com.streamvault.app.ui.theme.OnSurface-import com.streamvault.domain.model.Provider+import com.streamvault.domain.model.LegacyProvider as Providerimport com.streamvault.domain.model.ProviderTypeprivate fun availableSyncSelections(provider: Provider): List<ProviderSyncSelection> = buildList {diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsProviderUiComponents.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsProviderUiComponents.ktindex dcc6ebb7..2e2cdf7e 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsProviderUiComponents.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsProviderUiComponents.kt@@ -29,7 +29,7 @@ import com.streamvault.app.ui.theme.OnSurfaceDimimport com.streamvault.app.ui.theme.Primaryimport com.streamvault.app.ui.theme.Secondaryimport com.streamvault.app.ui.theme.SurfaceElevated-import com.streamvault.domain.model.Provider+import com.streamvault.domain.model.LegacyProvider as Providerimport com.streamvault.domain.model.ProviderStatusimport androidx.compose.foundation.BorderStrokeimport androidx.compose.ui.focus.FocusRequesterdiff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsScreen.ktindex 1e3ef8d8..d1f5be09 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsScreen.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsScreen.kt@@ -36,7 +36,7 @@ import com.streamvault.app.ui.components.shell.AppTopBarCloseActionimport com.streamvault.app.ui.components.shell.AppNavigationChromeimport com.streamvault.app.ui.components.shell.AppScreenScaffoldimport com.streamvault.app.ui.theme.*-import com.streamvault.domain.model.Provider+import com.streamvault.domain.model.LegacyProvider as Providerimport androidx.compose.ui.res.stringResourceimport com.streamvault.app.Rimport com.streamvault.app.ui.design.requestFocusSafelydiff --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 88ec0b63..fe755813 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@@ -31,7 +31,7 @@ import com.streamvault.domain.model.VodDuplicateHandlingModeimport com.streamvault.domain.model.VodHttpProtocolModeimport com.streamvault.domain.model.ExternalPlaybackModeimport com.streamvault.domain.model.PlayerSurfaceMode-import com.streamvault.domain.model.Provider+import com.streamvault.domain.model.LegacyProvider as Providerimport com.streamvault.domain.model.RecordingItemimport com.streamvault.domain.model.RecordingStorageStateimport com.streamvault.domain.model.RemoteShortcutPreferencesdiff --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.ktindex ebf6338f..db5d4178 100644--- 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.kt@@ -9,7 +9,7 @@ import com.streamvault.domain.model.Categoryimport com.streamvault.domain.model.LibraryFilterTypeimport com.streamvault.domain.model.LibrarySortByimport com.streamvault.domain.model.PlaybackHistory-import com.streamvault.domain.model.Provider+import com.streamvault.domain.model.LegacyProvider as Providerimport com.streamvault.domain.model.VodCatalogItemimport com.streamvault.domain.model.VodCategoryKindimport com.streamvault.domain.model.VodCategoryHydrationdiff --git a/app/src/test/java/com/streamvault/app/ui/screens/epg/EpgViewModelTest.kt b/app/src/test/java/com/streamvault/app/ui/screens/epg/EpgViewModelTest.ktindex 765d4e7d..9d55445c 100644--- a/app/src/test/java/com/streamvault/app/ui/screens/epg/EpgViewModelTest.kt+++ b/app/src/test/java/com/streamvault/app/ui/screens/epg/EpgViewModelTest.kt@@ -18,7 +18,7 @@ import com.streamvault.domain.model.ContentTypeimport com.streamvault.domain.model.Favoriteimport com.streamvault.domain.model.ActiveLiveSourceimport com.streamvault.domain.model.Program-import com.streamvault.domain.model.Provider+import com.streamvault.domain.model.LegacyProvider as Providerimport com.streamvault.domain.model.ProviderTypeimport com.streamvault.domain.model.CombinedCategoryimport com.streamvault.domain.model.CombinedCategoryBindingdiff --git a/app/src/test/java/com/streamvault/app/ui/screens/home/HomeViewModelTest.kt b/app/src/test/java/com/streamvault/app/ui/screens/home/HomeViewModelTest.ktindex bfb6b70d..1eb18fa1 100644--- a/app/src/test/java/com/streamvault/app/ui/screens/home/HomeViewModelTest.kt+++ b/app/src/test/java/com/streamvault/app/ui/screens/home/HomeViewModelTest.kt@@ -16,7 +16,7 @@ import com.streamvault.domain.model.Channelimport com.streamvault.domain.model.ChannelNumberingModeimport com.streamvault.domain.model.ContentTypeimport com.streamvault.domain.model.PlaybackHistory-import com.streamvault.domain.model.Provider+import com.streamvault.domain.model.LegacyProvider as Providerimport com.streamvault.domain.model.ProviderTypeimport com.streamvault.domain.model.Resultimport com.streamvault.domain.model.StreamInfodiff --git a/app/src/test/java/com/streamvault/app/ui/screens/movies/MovieDetailViewModelCastingTest.kt b/app/src/test/java/com/streamvault/app/ui/screens/movies/MovieDetailViewModelCastingTest.ktindex fc568fb6..d699630e 100644--- a/app/src/test/java/com/streamvault/app/ui/screens/movies/MovieDetailViewModelCastingTest.kt+++ b/app/src/test/java/com/streamvault/app/ui/screens/movies/MovieDetailViewModelCastingTest.kt@@ -15,7 +15,7 @@ import com.streamvault.app.plugins.StreamVaultPluginManagerimport com.streamvault.data.preferences.PreferencesRepositoryimport com.streamvault.domain.model.ExternalRatingsimport com.streamvault.domain.model.Movie-import com.streamvault.domain.model.Provider+import com.streamvault.domain.model.LegacyProvider as Providerimport com.streamvault.domain.model.ProviderTypeimport com.streamvault.domain.model.Resultimport com.streamvault.domain.model.StreamInfodiff --git a/app/src/test/java/com/streamvault/app/ui/screens/provider/ProviderSetupViewModelTest.kt b/app/src/test/java/com/streamvault/app/ui/screens/provider/ProviderSetupViewModelTest.ktindex 5b6bd033..8a467c05 100644--- a/app/src/test/java/com/streamvault/app/ui/screens/provider/ProviderSetupViewModelTest.kt+++ b/app/src/test/java/com/streamvault/app/ui/screens/provider/ProviderSetupViewModelTest.kt@@ -5,7 +5,7 @@ import com.streamvault.app.pairing.ProviderQrPairingManagerimport com.streamvault.app.pairing.ProviderQrPairingStateimport com.streamvault.domain.model.ActiveLiveSourceimport com.streamvault.domain.model.CombinedM3uProfile-import com.streamvault.domain.model.Provider+import com.streamvault.domain.model.LegacyProvider as Providerimport com.streamvault.domain.model.ProviderEpgSyncModeimport com.streamvault.domain.model.ProviderTypeimport com.streamvault.domain.model.StalkerAuthModediff --git a/app/src/test/java/com/streamvault/app/ui/screens/search/SearchViewModelTest.kt b/app/src/test/java/com/streamvault/app/ui/screens/search/SearchViewModelTest.ktindex e224a356..48d3110d 100644--- a/app/src/test/java/com/streamvault/app/ui/screens/search/SearchViewModelTest.kt+++ b/app/src/test/java/com/streamvault/app/ui/screens/search/SearchViewModelTest.kt@@ -3,7 +3,7 @@ package com.streamvault.app.ui.screens.searchimport com.google.common.truth.Truth.assertThatimport com.streamvault.domain.model.Channelimport com.streamvault.domain.model.Movie-import com.streamvault.domain.model.Provider+import com.streamvault.domain.model.LegacyProvider as Providerimport com.streamvault.domain.model.ProviderTypeimport com.streamvault.domain.model.SearchHistoryScopeimport com.streamvault.domain.model.Seriesdiff --git a/app/src/test/java/com/streamvault/app/ui/screens/series/SeriesDetailViewModelCastingTest.kt b/app/src/test/java/com/streamvault/app/ui/screens/series/SeriesDetailViewModelCastingTest.ktindex d3433180..ce1ef9d7 100644--- a/app/src/test/java/com/streamvault/app/ui/screens/series/SeriesDetailViewModelCastingTest.kt+++ b/app/src/test/java/com/streamvault/app/ui/screens/series/SeriesDetailViewModelCastingTest.kt@@ -15,7 +15,7 @@ import com.streamvault.app.plugins.StreamVaultPluginManagerimport com.streamvault.data.preferences.PreferencesRepositoryimport com.streamvault.domain.model.Episodeimport com.streamvault.domain.model.ExternalRatings-import com.streamvault.domain.model.Provider+import com.streamvault.domain.model.LegacyProvider as Providerimport com.streamvault.domain.model.ProviderTypeimport com.streamvault.domain.model.Resultimport com.streamvault.domain.model.Seasondiff --git a/app/src/test/java/com/streamvault/app/ui/screens/settings/SettingsDerivedStateObserversTest.kt b/app/src/test/java/com/streamvault/app/ui/screens/settings/SettingsDerivedStateObserversTest.ktindex 79767282..ed096a5b 100644--- a/app/src/test/java/com/streamvault/app/ui/screens/settings/SettingsDerivedStateObserversTest.kt+++ b/app/src/test/java/com/streamvault/app/ui/screens/settings/SettingsDerivedStateObserversTest.kt@@ -4,7 +4,7 @@ import android.app.Applicationimport com.google.common.truth.Truth.assertThatimport com.streamvault.app.Rimport com.streamvault.data.local.dao.ProgramDao-import com.streamvault.domain.model.Provider+import com.streamvault.domain.model.LegacyProvider as Providerimport com.streamvault.domain.model.ProviderTypeimport com.streamvault.domain.model.SyncMetadataimport com.streamvault.domain.repository.MovieRepositorydiff --git a/app/src/test/java/com/streamvault/app/ui/screens/settings/SettingsProviderActionsTest.kt b/app/src/test/java/com/streamvault/app/ui/screens/settings/SettingsProviderActionsTest.ktindex 6475ec99..c3d9b140 100644--- a/app/src/test/java/com/streamvault/app/ui/screens/settings/SettingsProviderActionsTest.kt+++ b/app/src/test/java/com/streamvault/app/ui/screens/settings/SettingsProviderActionsTest.kt@@ -7,7 +7,7 @@ import com.streamvault.app.tvinput.TvInputChannelSyncManagerimport com.streamvault.data.preferences.PreferencesRepositoryimport com.streamvault.data.sync.SyncManagerimport com.streamvault.domain.model.ActiveLiveSource-import com.streamvault.domain.model.Provider+import com.streamvault.domain.model.LegacyProvider as Providerimport com.streamvault.domain.model.ProviderTypeimport com.streamvault.domain.model.Resultimport com.streamvault.domain.repository.CombinedM3uRepositorydiff --git a/data/schemas/com.streamvault.data.local.StreamVaultDatabase/73.json b/data/schemas/com.streamvault.data.local.StreamVaultDatabase/73.jsonnew file mode 100644index 00000000..438cd79f--- /dev/null+++ b/data/schemas/com.streamvault.data.local.StreamVaultDatabase/73.json@@ -0,0 +1,7249 @@+{+ "formatVersion": 1,+ "database": {+ "version": 73,+ "identityHash": "8d62567b42b846bca4e08ea05c935c8f",+ "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": "provider_configs",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `type` TEXT NOT NULL, `schema_version` INTEGER NOT NULL, `configuration_generation` INTEGER NOT NULL, `identity_key` TEXT NOT NULL, `encrypted_config_json` TEXT NOT NULL, `updated_at` 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": "type",+ "columnName": "type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "schemaVersion",+ "columnName": "schema_version",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "configurationGeneration",+ "columnName": "configuration_generation",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "identityKey",+ "columnName": "identity_key",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "encryptedConfigJson",+ "columnName": "encrypted_config_json",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "provider_id"+ ]+ },+ "indices": [+ {+ "name": "index_provider_configs_provider_id",+ "unique": true,+ "columnNames": [+ "provider_id"+ ],+ "orders": [++ ],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_provider_configs_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_provider_configs_identity_key",+ "unique": true,+ "columnNames": [+ "identity_key"+ ],+ "orders": [++ ],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_provider_configs_identity_key` ON `${TABLE_NAME}` (`identity_key`)"+ },+ {+ "name": "index_provider_configs_type",+ "unique": false,+ "columnNames": [+ "type"+ ],+ "orders": [++ ],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_provider_configs_type` ON `${TABLE_NAME}` (`type`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "provider_account_runtime",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `max_connections` INTEGER NOT NULL, `expiration_date` INTEGER, `api_version` TEXT, `allowed_output_formats_json` TEXT NOT NULL, `catalog_layout` TEXT NOT NULL, `catalog_layout_detection_version` INTEGER NOT NULL, `observed_at` 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": "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": "catalogLayout",+ "columnName": "catalog_layout",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "catalogLayoutDetectionVersion",+ "columnName": "catalog_layout_detection_version",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "observedAt",+ "columnName": "observed_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "provider_id"+ ]+ },+ "indices": [+ {+ "name": "index_provider_account_runtime_provider_id",+ "unique": true,+ "columnNames": [+ "provider_id"+ ],+ "orders": [++ ],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_provider_account_runtime_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "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, `timezone_policy` TEXT NOT NULL, `timezone_id` 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"+ },+ {+ "fieldPath": "timezonePolicy",+ "columnName": "timezone_policy",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "timezoneId",+ "columnName": "timezone_id",+ "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, `exact_alarm_armed` INTEGER NOT NULL, `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": "exactAlarmArmed",+ "columnName": "exact_alarm_armed",+ "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": [+ "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, `exact_alarm_armed` INTEGER NOT NULL, `delivery_state` TEXT NOT NULL, `delivery_attempt_token` TEXT, `delivery_attempted_at` INTEGER, `delivery_attempt_count` INTEGER NOT NULL, `delivery_failure_reason` TEXT, `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": "exactAlarmArmed",+ "columnName": "exact_alarm_armed",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "deliveryState",+ "columnName": "delivery_state",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "deliveryAttemptToken",+ "columnName": "delivery_attempt_token",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "deliveryAttemptedAt",+ "columnName": "delivery_attempted_at",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "deliveryAttemptCount",+ "columnName": "delivery_attempt_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "deliveryFailureReason",+ "columnName": "delivery_failure_reason",+ "affinity": "TEXT"+ },+ {+ "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, `configuration_generation` INTEGER NOT NULL, `learning_json` TEXT NOT NULL, `observation_source` TEXT NOT NULL, `observed_at` 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+ },+ {+ "fieldPath": "configurationGeneration",+ "columnName": "configuration_generation",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "learningJson",+ "columnName": "learning_json",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "observationSource",+ "columnName": "observation_source",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "observedAt",+ "columnName": "observed_at",+ "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, `owner_id` TEXT, `owner_epoch` INTEGER NOT NULL, `heartbeat_at` INTEGER, `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": "ownerId",+ "columnName": "owner_id",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "ownerEpoch",+ "columnName": "owner_epoch",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "heartbeatAt",+ "columnName": "heartbeat_at",+ "affinity": "INTEGER"+ },+ {+ "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`)"+ }+ ]+ },+ {+ "tableName": "provider_deletion_cleanup",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `action` TEXT NOT NULL, `target_id` TEXT NOT NULL, `created_at` INTEGER NOT NULL, `attempt_count` INTEGER NOT NULL, `last_error` TEXT)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "action",+ "columnName": "action",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "targetId",+ "columnName": "target_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "attemptCount",+ "columnName": "attempt_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastError",+ "columnName": "last_error",+ "affinity": "TEXT"+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_provider_deletion_cleanup_provider_id_action_target_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "action",+ "target_id"+ ],+ "orders": [++ ],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_provider_deletion_cleanup_provider_id_action_target_id` ON `${TABLE_NAME}` (`provider_id`, `action`, `target_id`)"+ }+ ]+ },+ {+ "tableName": "plugin_provider_ownership",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`package_name` TEXT NOT NULL, `service_class_name` TEXT NOT NULL, `manifest_id` TEXT NOT NULL, `provider_id` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, PRIMARY KEY(`package_name`, `service_class_name`, `manifest_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "packageName",+ "columnName": "package_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "serviceClassName",+ "columnName": "service_class_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "manifestId",+ "columnName": "manifest_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "package_name",+ "service_class_name",+ "manifest_id"+ ]+ },+ "indices": [+ {+ "name": "index_plugin_provider_ownership_provider_id",+ "unique": true,+ "columnNames": [+ "provider_id"+ ],+ "orders": [++ ],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_plugin_provider_ownership_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "provider_config_revisions",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `revision` INTEGER NOT NULL, `config_json` TEXT NOT NULL, `state` TEXT NOT NULL, `attempt_count` INTEGER NOT NULL, `last_error` TEXT, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, PRIMARY KEY(`provider_id`, `revision`), 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": "revision",+ "columnName": "revision",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "configJson",+ "columnName": "config_json",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "state",+ "columnName": "state",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "attemptCount",+ "columnName": "attempt_count",+ "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+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "provider_id",+ "revision"+ ]+ },+ "indices": [+ {+ "name": "index_provider_config_revisions_provider_id_state",+ "unique": false,+ "columnNames": [+ "provider_id",+ "state"+ ],+ "orders": [++ ],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_provider_config_revisions_provider_id_state` ON `${TABLE_NAME}` (`provider_id`, `state`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "backup_restore_checkpoints",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`restore_key` TEXT NOT NULL, `room_complete` INTEGER NOT NULL, `preferences_complete` INTEGER NOT NULL, `presets_complete` INTEGER NOT NULL, `schedules_complete` INTEGER NOT NULL, `state` TEXT NOT NULL, `preference_snapshot_json` TEXT, `last_error` TEXT, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, PRIMARY KEY(`restore_key`))",+ "fields": [+ {+ "fieldPath": "restoreKey",+ "columnName": "restore_key",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "roomComplete",+ "columnName": "room_complete",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "preferencesComplete",+ "columnName": "preferences_complete",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "presetsComplete",+ "columnName": "presets_complete",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "schedulesComplete",+ "columnName": "schedules_complete",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "state",+ "columnName": "state",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "preferenceSnapshotJson",+ "columnName": "preference_snapshot_json",+ "affinity": "TEXT"+ },+ {+ "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+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "restore_key"+ ]+ }+ },+ {+ "tableName": "provider_workflows",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `generation` INTEGER NOT NULL, `state` TEXT NOT NULL, `reason` TEXT NOT NULL, `priority` INTEGER NOT NULL, `force` INTEGER NOT NULL, `current_phase` TEXT, `lease_token` TEXT, `lease_expires_at` INTEGER, `heartbeat_at` INTEGER, `progress_message` TEXT, `last_error_code` TEXT, `last_error_message` 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": "generation",+ "columnName": "generation",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "state",+ "columnName": "state",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "reason",+ "columnName": "reason",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "priority",+ "columnName": "priority",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "force",+ "columnName": "force",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "currentPhase",+ "columnName": "current_phase",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "leaseToken",+ "columnName": "lease_token",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "leaseExpiresAt",+ "columnName": "lease_expires_at",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "heartbeatAt",+ "columnName": "heartbeat_at",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "progressMessage",+ "columnName": "progress_message",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lastErrorCode",+ "columnName": "last_error_code",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lastErrorMessage",+ "columnName": "last_error_message",+ "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_provider_workflows_state",+ "unique": false,+ "columnNames": [+ "state"+ ],+ "orders": [++ ],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_provider_workflows_state` ON `${TABLE_NAME}` (`state`)"+ },+ {+ "name": "index_provider_workflows_updated_at",+ "unique": false,+ "columnNames": [+ "updated_at"+ ],+ "orders": [++ ],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_provider_workflows_updated_at` ON `${TABLE_NAME}` (`updated_at`)"+ },+ {+ "name": "index_provider_workflows_lease_expires_at",+ "unique": false,+ "columnNames": [+ "lease_expires_at"+ ],+ "orders": [++ ],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_provider_workflows_lease_expires_at` ON `${TABLE_NAME}` (`lease_expires_at`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "provider_workflow_phases",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `generation` INTEGER NOT NULL, `phase` TEXT NOT NULL, `state` TEXT NOT NULL, `attempt_count` INTEGER NOT NULL, `checkpoint` TEXT, `last_error_code` TEXT, `last_error_message` TEXT, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, `completed_at` INTEGER, PRIMARY KEY(`provider_id`, `generation`, `phase`), 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": "generation",+ "columnName": "generation",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "phase",+ "columnName": "phase",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "state",+ "columnName": "state",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "attemptCount",+ "columnName": "attempt_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "checkpoint",+ "columnName": "checkpoint",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lastErrorCode",+ "columnName": "last_error_code",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lastErrorMessage",+ "columnName": "last_error_message",+ "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",+ "generation",+ "phase"+ ]+ },+ "indices": [+ {+ "name": "index_provider_workflow_phases_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [++ ],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_provider_workflow_phases_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_provider_workflow_phases_state",+ "unique": false,+ "columnNames": [+ "state"+ ],+ "orders": [++ ],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_provider_workflow_phases_state` ON `${TABLE_NAME}` (`state`)"+ },+ {+ "name": "index_provider_workflow_phases_updated_at",+ "unique": false,+ "columnNames": [+ "updated_at"+ ],+ "orders": [++ ],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_provider_workflow_phases_updated_at` ON `${TABLE_NAME}` (`updated_at`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ }+ ],+ "setupQueries": [+ "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",+ "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, \u00273f53d52bafe56253d01401c4844f8d44\u0027)"+ ]+ }+}\ No newline at end of filediff --git a/data/schemas/com.streamvault.data.local.StreamVaultDatabase/74.json b/data/schemas/com.streamvault.data.local.StreamVaultDatabase/74.jsonnew file mode 100644index 00000000..cd798b1c--- /dev/null+++ b/data/schemas/com.streamvault.data.local.StreamVaultDatabase/74.json@@ -0,0 +1,6629 @@+{+ "formatVersion": 1,+ "database": {+ "version": 74,+ "identityHash": "3f53d52bafe56253d01401c4844f8d44",+ "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, `is_active` 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": "isActive",+ "columnName": "is_active",+ "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_type",+ "unique": false,+ "columnNames": [+ "type"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_providers_type` ON `${TABLE_NAME}` (`type`)"+ },+ {+ "name": "index_providers_is_active",+ "unique": false,+ "columnNames": [+ "is_active"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_providers_is_active` ON `${TABLE_NAME}` (`is_active`)"+ }+ ]+ },+ {+ "tableName": "provider_configs",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `type` TEXT NOT NULL, `schema_version` INTEGER NOT NULL, `configuration_generation` INTEGER NOT NULL, `identity_key` TEXT NOT NULL, `encrypted_config_json` TEXT NOT NULL, `guide_source_policy` TEXT NOT NULL, `channel_logo_source_policy` TEXT NOT NULL, `updated_at` 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": "type",+ "columnName": "type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "schemaVersion",+ "columnName": "schema_version",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "configurationGeneration",+ "columnName": "configuration_generation",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "identityKey",+ "columnName": "identity_key",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "encryptedConfigJson",+ "columnName": "encrypted_config_json",+ "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": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "provider_id"+ ]+ },+ "indices": [+ {+ "name": "index_provider_configs_provider_id",+ "unique": true,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_provider_configs_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_provider_configs_identity_key",+ "unique": true,+ "columnNames": [+ "identity_key"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_provider_configs_identity_key` ON `${TABLE_NAME}` (`identity_key`)"+ },+ {+ "name": "index_provider_configs_type",+ "unique": false,+ "columnNames": [+ "type"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_provider_configs_type` ON `${TABLE_NAME}` (`type`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "provider_account_runtime",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `max_connections` INTEGER NOT NULL, `expiration_date` INTEGER, `api_version` TEXT, `allowed_output_formats_json` TEXT NOT NULL, `catalog_layout` TEXT NOT NULL, `catalog_layout_detection_version` INTEGER NOT NULL, `observed_at` 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": "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": "catalogLayout",+ "columnName": "catalog_layout",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "catalogLayoutDetectionVersion",+ "columnName": "catalog_layout_detection_version",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "observedAt",+ "columnName": "observed_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "provider_id"+ ]+ },+ "indices": [+ {+ "name": "index_provider_account_runtime_provider_id",+ "unique": true,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_provider_account_runtime_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "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, `timezone_policy` TEXT NOT NULL, `timezone_id` 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"+ },+ {+ "fieldPath": "timezonePolicy",+ "columnName": "timezone_policy",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "timezoneId",+ "columnName": "timezone_id",+ "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, `exact_alarm_armed` INTEGER NOT NULL, `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": "exactAlarmArmed",+ "columnName": "exact_alarm_armed",+ "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": [+ "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, `exact_alarm_armed` INTEGER NOT NULL, `delivery_state` TEXT NOT NULL, `delivery_attempt_token` TEXT, `delivery_attempted_at` INTEGER, `delivery_attempt_count` INTEGER NOT NULL, `delivery_failure_reason` TEXT, `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": "exactAlarmArmed",+ "columnName": "exact_alarm_armed",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "deliveryState",+ "columnName": "delivery_state",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "deliveryAttemptToken",+ "columnName": "delivery_attempt_token",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "deliveryAttemptedAt",+ "columnName": "delivery_attempted_at",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "deliveryAttemptCount",+ "columnName": "delivery_attempt_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "deliveryFailureReason",+ "columnName": "delivery_failure_reason",+ "affinity": "TEXT"+ },+ {+ "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, `configuration_generation` INTEGER NOT NULL, `learning_json` TEXT NOT NULL, `observation_source` TEXT NOT NULL, `observed_at` 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+ },+ {+ "fieldPath": "configurationGeneration",+ "columnName": "configuration_generation",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "learningJson",+ "columnName": "learning_json",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "observationSource",+ "columnName": "observation_source",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "observedAt",+ "columnName": "observed_at",+ "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, `owner_id` TEXT, `owner_epoch` INTEGER NOT NULL, `heartbeat_at` INTEGER, `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": "ownerId",+ "columnName": "owner_id",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "ownerEpoch",+ "columnName": "owner_epoch",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "heartbeatAt",+ "columnName": "heartbeat_at",+ "affinity": "INTEGER"+ },+ {+ "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`)"+ }+ ]+ },+ {+ "tableName": "provider_deletion_cleanup",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `action` TEXT NOT NULL, `target_id` TEXT NOT NULL, `created_at` INTEGER NOT NULL, `attempt_count` INTEGER NOT NULL, `last_error` TEXT)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "action",+ "columnName": "action",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "targetId",+ "columnName": "target_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "attemptCount",+ "columnName": "attempt_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastError",+ "columnName": "last_error",+ "affinity": "TEXT"+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_provider_deletion_cleanup_provider_id_action_target_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "action",+ "target_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_provider_deletion_cleanup_provider_id_action_target_id` ON `${TABLE_NAME}` (`provider_id`, `action`, `target_id`)"+ }+ ]+ },+ {+ "tableName": "plugin_provider_ownership",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`package_name` TEXT NOT NULL, `service_class_name` TEXT NOT NULL, `manifest_id` TEXT NOT NULL, `provider_id` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, PRIMARY KEY(`package_name`, `service_class_name`, `manifest_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "packageName",+ "columnName": "package_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "serviceClassName",+ "columnName": "service_class_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "manifestId",+ "columnName": "manifest_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "package_name",+ "service_class_name",+ "manifest_id"+ ]+ },+ "indices": [+ {+ "name": "index_plugin_provider_ownership_provider_id",+ "unique": true,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_plugin_provider_ownership_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "provider_config_revisions",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `revision` INTEGER NOT NULL, `config_json` TEXT NOT NULL, `state` TEXT NOT NULL, `attempt_count` INTEGER NOT NULL, `last_error` TEXT, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, PRIMARY KEY(`provider_id`, `revision`), 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": "revision",+ "columnName": "revision",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "configJson",+ "columnName": "config_json",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "state",+ "columnName": "state",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "attemptCount",+ "columnName": "attempt_count",+ "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+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "provider_id",+ "revision"+ ]+ },+ "indices": [+ {+ "name": "index_provider_config_revisions_provider_id_state",+ "unique": false,+ "columnNames": [+ "provider_id",+ "state"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_provider_config_revisions_provider_id_state` ON `${TABLE_NAME}` (`provider_id`, `state`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "backup_restore_checkpoints",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`restore_key` TEXT NOT NULL, `room_complete` INTEGER NOT NULL, `preferences_complete` INTEGER NOT NULL, `presets_complete` INTEGER NOT NULL, `schedules_complete` INTEGER NOT NULL, `state` TEXT NOT NULL, `preference_snapshot_json` TEXT, `last_error` TEXT, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, PRIMARY KEY(`restore_key`))",+ "fields": [+ {+ "fieldPath": "restoreKey",+ "columnName": "restore_key",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "roomComplete",+ "columnName": "room_complete",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "preferencesComplete",+ "columnName": "preferences_complete",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "presetsComplete",+ "columnName": "presets_complete",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "schedulesComplete",+ "columnName": "schedules_complete",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "state",+ "columnName": "state",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "preferenceSnapshotJson",+ "columnName": "preference_snapshot_json",+ "affinity": "TEXT"+ },+ {+ "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+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "restore_key"+ ]+ }+ },+ {+ "tableName": "provider_workflows",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `generation` INTEGER NOT NULL, `state` TEXT NOT NULL, `reason` TEXT NOT NULL, `priority` INTEGER NOT NULL, `force` INTEGER NOT NULL, `current_phase` TEXT, `lease_token` TEXT, `lease_expires_at` INTEGER, `heartbeat_at` INTEGER, `progress_message` TEXT, `last_error_code` TEXT, `last_error_message` 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": "generation",+ "columnName": "generation",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "state",+ "columnName": "state",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "reason",+ "columnName": "reason",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "priority",+ "columnName": "priority",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "force",+ "columnName": "force",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "currentPhase",+ "columnName": "current_phase",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "leaseToken",+ "columnName": "lease_token",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "leaseExpiresAt",+ "columnName": "lease_expires_at",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "heartbeatAt",+ "columnName": "heartbeat_at",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "progressMessage",+ "columnName": "progress_message",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lastErrorCode",+ "columnName": "last_error_code",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lastErrorMessage",+ "columnName": "last_error_message",+ "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_provider_workflows_state",+ "unique": false,+ "columnNames": [+ "state"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_provider_workflows_state` ON `${TABLE_NAME}` (`state`)"+ },+ {+ "name": "index_provider_workflows_updated_at",+ "unique": false,+ "columnNames": [+ "updated_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_provider_workflows_updated_at` ON `${TABLE_NAME}` (`updated_at`)"+ },+ {+ "name": "index_provider_workflows_lease_expires_at",+ "unique": false,+ "columnNames": [+ "lease_expires_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_provider_workflows_lease_expires_at` ON `${TABLE_NAME}` (`lease_expires_at`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "provider_workflow_phases",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `generation` INTEGER NOT NULL, `phase` TEXT NOT NULL, `state` TEXT NOT NULL, `attempt_count` INTEGER NOT NULL, `checkpoint` TEXT, `last_error_code` TEXT, `last_error_message` TEXT, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, `completed_at` INTEGER, PRIMARY KEY(`provider_id`, `generation`, `phase`), 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": "generation",+ "columnName": "generation",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "phase",+ "columnName": "phase",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "state",+ "columnName": "state",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "attemptCount",+ "columnName": "attempt_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "checkpoint",+ "columnName": "checkpoint",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lastErrorCode",+ "columnName": "last_error_code",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lastErrorMessage",+ "columnName": "last_error_message",+ "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",+ "generation",+ "phase"+ ]+ },+ "indices": [+ {+ "name": "index_provider_workflow_phases_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_provider_workflow_phases_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_provider_workflow_phases_state",+ "unique": false,+ "columnNames": [+ "state"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_provider_workflow_phases_state` ON `${TABLE_NAME}` (`state`)"+ },+ {+ "name": "index_provider_workflow_phases_updated_at",+ "unique": false,+ "columnNames": [+ "updated_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_provider_workflow_phases_updated_at` ON `${TABLE_NAME}` (`updated_at`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ }+ ],+ "setupQueries": [+ "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",+ "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '3f53d52bafe56253d01401c4844f8d44')"+ ]+ }+}\ No newline at end of filediff --git a/data/src/androidTest/java/com/streamvault/data/local/BrowseQueryPlanTest.kt b/data/src/androidTest/java/com/streamvault/data/local/BrowseQueryPlanTest.ktindex 07ff0898..036d3dc7 100644--- a/data/src/androidTest/java/com/streamvault/data/local/BrowseQueryPlanTest.kt+++ b/data/src/androidTest/java/com/streamvault/data/local/BrowseQueryPlanTest.kt@@ -85,8 +85,7 @@ class BrowseQueryPlanTest {ProviderEntity(id = 1L,name = "Provider",- type = ProviderType.XTREAM_CODES,- serverUrl = "https://provider.example.com"+ type = ProviderType.XTREAM_CODES))db.movieDao().insertAll(@@ -147,4 +146,4 @@ class BrowseQueryPlanTest {private fun assertNoTempSort(plan: List<String>) {assertThat(plan.none { it.contains("USE TEMP B-TREE FOR ORDER BY") }).isTrue()}-}\ No newline at end of file+}diff --git a/data/src/androidTest/java/com/streamvault/data/local/CatalogSyncDaoSeriesStageTest.kt b/data/src/androidTest/java/com/streamvault/data/local/CatalogSyncDaoSeriesStageTest.ktindex 7ecff002..9df7d2c3 100644--- a/data/src/androidTest/java/com/streamvault/data/local/CatalogSyncDaoSeriesStageTest.kt+++ b/data/src/androidTest/java/com/streamvault/data/local/CatalogSyncDaoSeriesStageTest.kt@@ -169,7 +169,6 @@ class CatalogSyncDaoSeriesStageTest {private fun provider(id: Long) = ProviderEntity(id = id,name = "Provider $id",- type = ProviderType.STALKER_PORTAL,- serverUrl = "https://provider$id.example.com"+ type = ProviderType.STALKER_PORTAL)}diff --git a/data/src/androidTest/java/com/streamvault/data/local/FavoriteDaoTest.kt b/data/src/androidTest/java/com/streamvault/data/local/FavoriteDaoTest.ktindex e7b766ad..605006df 100644--- a/data/src/androidTest/java/com/streamvault/data/local/FavoriteDaoTest.kt+++ b/data/src/androidTest/java/com/streamvault/data/local/FavoriteDaoTest.kt@@ -189,7 +189,6 @@ class FavoriteDaoTest {private fun provider(id: Long, name: String) = ProviderEntity(id = id,name = name,- type = ProviderType.M3U,- serverUrl = "https://$name.example.com"+ type = ProviderType.M3U)-}\ No newline at end of file+}diff --git a/data/src/androidTest/java/com/streamvault/data/local/ProviderDaoTest.kt b/data/src/androidTest/java/com/streamvault/data/local/ProviderDaoTest.ktindex a715c803..a286b6a6 100644--- a/data/src/androidTest/java/com/streamvault/data/local/ProviderDaoTest.kt+++ b/data/src/androidTest/java/com/streamvault/data/local/ProviderDaoTest.kt@@ -72,8 +72,6 @@ class ProviderDaoTest {id = id,name = name,type = ProviderType.M3U,- serverUrl = "https://example.com/$id.m3u",- m3uUrl = "https://example.com/$id.m3u",isActive = isActive)-}\ No newline at end of file+}diff --git a/data/src/androidTest/java/com/streamvault/data/local/ProviderWorkflowIntegrationTest.kt b/data/src/androidTest/java/com/streamvault/data/local/ProviderWorkflowIntegrationTest.ktindex 4a323048..8723ef20 100644--- a/data/src/androidTest/java/com/streamvault/data/local/ProviderWorkflowIntegrationTest.kt+++ b/data/src/androidTest/java/com/streamvault/data/local/ProviderWorkflowIntegrationTest.kt@@ -178,8 +178,7 @@ class ProviderWorkflowIntegrationTest {private fun provider(id: Long) = ProviderEntity(id = id,name = "Provider $id",- type = ProviderType.M3U,- serverUrl = "https://example.com/$id"+ type = ProviderType.M3U)private companion object {diff --git a/data/src/androidTest/java/com/streamvault/data/local/StreamVaultDatabaseMigrationTest.kt b/data/src/androidTest/java/com/streamvault/data/local/StreamVaultDatabaseMigrationTest.ktindex 08d70c35..27d68aae 100644--- a/data/src/androidTest/java/com/streamvault/data/local/StreamVaultDatabaseMigrationTest.kt+++ b/data/src/androidTest/java/com/streamvault/data/local/StreamVaultDatabaseMigrationTest.kt@@ -1,6 +1,7 @@package com.streamvault.data.localimport androidx.room.testing.MigrationTestHelper+import androidx.sqlite.db.SupportSQLiteDatabaseimport androidx.sqlite.db.framework.FrameworkSQLiteOpenHelperFactoryimport androidx.test.ext.junit.runners.AndroidJUnit4import androidx.test.platform.app.InstrumentationRegistry@@ -1562,7 +1563,145 @@ class StreamVaultDatabaseMigrationTest {migratedDb.close()}- private fun countRows(db: androidx.sqlite.db.SupportSQLiteDatabase, sql: String): Int {+ @Test+ fun migrate72To73_backfillsTypedSnapshotsForEveryProviderTypeWithoutIdOrFkLoss() {+ val name = "streamvault-72-73-provider-snapshots"+ migrationTestHelper.createDatabase(name, 72).apply {+ insertProvider72(1, "Xtream", "XTREAM_CODES")+ insertProvider72(2, "M3U", "M3U")+ insertProvider72(3, "Stalker", "STALKER_PORTAL")+ insertProvider72(4, "Jellyfin", "JELLYFIN")+ execSQL("UPDATE providers SET server_url='https://x.test',username='alice',password='enc:v1:xtream',is_active=1 WHERE id=1")+ execSQL("UPDATE providers SET server_url='https://m.test/list.m3u',m3u_url='https://m.test/list.m3u',epg_url='https://m.test/epg.xml' WHERE id=2")+ execSQL("UPDATE providers SET server_url='https://s.test',username='bob',password='enc:v1:stalker',stalker_mac_address='00:11:22:33:44:55',stalker_configuration_generation=4 WHERE id=3")+ execSQL("UPDATE providers SET server_url='https://j.test',username='carol',password='enc:v1:jellyfin' WHERE id=4")+ insertChannel72(10, 100, "News", 1)+ insertStalkerPortalState72(3)+ close()+ }++ val migrated = migrationTestHelper.runMigrationsAndValidate(+ name,+ 73,+ true,+ StreamVaultDatabase.MIGRATION_72_73+ )++ assertEquals(4, countRows(migrated, "SELECT COUNT(*) FROM provider_configs"))+ assertEquals(4, countRows(migrated, "SELECT COUNT(*) FROM provider_account_runtime"))+ assertEquals(4, countRows(migrated, "SELECT COUNT(*) FROM provider_configs WHERE length(identity_key)=64"))+ assertEquals(1, countRows(migrated, "SELECT COUNT(*) FROM provider_configs WHERE provider_id=3 AND configuration_generation=4 AND encrypted_config_json LIKE '%enc:v1:stalker%'"))+ assertEquals(1, countRows(migrated, "SELECT COUNT(*) FROM channels WHERE id=10 AND provider_id=1"))+ assertEquals(1, countRows(migrated, "SELECT COUNT(*) FROM stalker_portal_state WHERE provider_id=3 AND configuration_generation=4"))+ assertEquals(1, countRows(migrated, "SELECT COUNT(*) FROM stalker_portal_state WHERE provider_id=3 AND learning_json LIKE '%\"portalFingerprint\"%' AND learning_json LIKE '%\"configurationGeneration\":4%'"))+ assertEquals(0, countRows(migrated, "SELECT COUNT(*) FROM pragma_foreign_key_check"))+ migrated.close()+ }++ @Test+ fun migrate72To74_rebuildsStableProvidersWithoutCatalogOrForeignKeyLoss() {+ val name = "streamvault-72-74-stable-provider-identity"+ migrationTestHelper.createDatabase(name, 72).apply {+ insertProvider72(1, "Xtream", "XTREAM_CODES")+ insertProvider72(2, "M3U", "M3U")+ insertProvider72(3, "Stalker", "STALKER_PORTAL")+ insertProvider72(4, "Jellyfin", "JELLYFIN")+ execSQL("UPDATE providers SET server_url='https://x.test',username='alice',password='enc:v1:xtream',is_active=1,guide_source_policy='EXTERNAL_ONLY',channel_logo_source_policy='EPG_PREFERRED',status='ACTIVE',last_synced_at=123,created_at=456 WHERE id=1")+ execSQL("UPDATE providers SET server_url='https://m.test/list.m3u',m3u_url='https://m.test/list.m3u',epg_url='https://m.test/epg.xml' WHERE id=2")+ execSQL("UPDATE providers SET server_url='https://s.test',username='bob',password='enc:v1:stalker',stalker_mac_address='00:11:22:33:44:55',stalker_configuration_generation=4,status='PARTIAL' WHERE id=3")+ execSQL("UPDATE providers SET server_url='https://j.test',username='carol',password='enc:v1:jellyfin' WHERE id=4")+ insertChannel72(10, 100, "News", 1)+ execSQL("INSERT INTO categories(id,category_id,name,type,provider_id,is_adult,is_user_protected,sync_fingerprint) VALUES(20,200,'Live','LIVE',1,0,0,'category-20')")+ insertStalkerPortalState72(3)+ execSQL("INSERT INTO provider_config_revisions(provider_id,revision,config_json,state,attempt_count,last_error,created_at,updated_at) VALUES(1,7,'{\"legacy\":true}','PENDING',2,NULL,700,701)")+ close()+ }++ val migrated = migrationTestHelper.runMigrationsAndValidate(+ name,+ 74,+ true,+ StreamVaultDatabase.MIGRATION_72_73,+ StreamVaultDatabase.MIGRATION_73_74+ )++ assertEquals(4, countRows(migrated, "SELECT COUNT(*) FROM providers"))+ assertEquals(4, countRows(migrated, "SELECT COUNT(*) FROM provider_configs"))+ assertEquals(1, countRows(migrated, "SELECT COUNT(*) FROM providers WHERE id=1 AND is_active=1 AND status='ACTIVE' AND last_synced_at=123 AND created_at=456"))+ assertEquals(0, countRows(migrated, "SELECT COUNT(*) FROM pragma_table_info('providers') WHERE name IN ('server_url','username','password','stalker_mac_address')"))+ assertEquals(1, countRows(migrated, "SELECT COUNT(*) FROM provider_configs WHERE provider_id=1 AND guide_source_policy='EXTERNAL_ONLY' AND channel_logo_source_policy='EPG_PREFERRED'"))+ assertEquals(1, countRows(migrated, "SELECT COUNT(*) FROM channels WHERE id=10 AND provider_id=1"))+ assertEquals(1, countRows(migrated, "SELECT COUNT(*) FROM categories WHERE id=20 AND provider_id=1"))+ assertEquals(1, countRows(migrated, "SELECT COUNT(*) FROM stalker_portal_state WHERE provider_id=3 AND configuration_generation=4"))+ assertEquals(1, countRows(migrated, "SELECT COUNT(*) FROM provider_config_revisions WHERE provider_id=1 AND revision=7 AND state='PENDING' AND config_json='{\"legacy\":true}'"))+ assertEquals(0, countRows(migrated, "SELECT COUNT(*) FROM pragma_foreign_key_check"))+ migrated.close()+ }++ private fun SupportSQLiteDatabase.insertProvider72(id: Long, name: String, type: String) {+ execSQL(+ """+ INSERT INTO providers (+ id,name,type,server_url,username,password,m3u_url,epg_url,http_user_agent,http_headers,+ stalker_mac_address,stalker_device_profile,stalker_device_timezone,stalker_device_locale,+ stalker_serial_number,stalker_device_id,stalker_device_id2,stalker_signature,+ stalker_advanced_options_json,stalker_auth_mode,stalker_portal_profile,+ stalker_portal_fingerprint,stalker_mag_preset,stalker_protocol_preference,+ stalker_transport_mode,stalker_transport_origin,stalker_tls_spki_sha256,+ stalker_transport_consent_at,stalker_configuration_generation,stalker_discovery_summary,+ stalker_capabilities_json,stalker_requested_profile_id,stalker_learned_profile_id,+ stalker_profile_revision,stalker_profile_verification,stalker_protocol_family,+ stalker_last_bootstrap_recipe,stalker_endpoint_preference,stalker_cookie_mode,+ stalker_playback_backend_hint,stalker_last_playback_mode,stalker_credentials_required,+ stalker_mac_required,stalker_uses_temp_links,stalker_module_restricted,+ stalker_strict_fingerprint_required,stalker_recipe_fallback_used,+ stalker_recipe_rediscovery_attempts,is_active,max_connections,expiration_date,api_version,+ allowed_output_formats_json,epg_sync_mode,stalker_catalog_mode,guide_source_policy,+ channel_logo_source_policy,xtream_fast_sync_enabled,xtream_live_sync_mode,+ m3u_vod_classification_enabled,catalog_layout,catalog_layout_detection_version,status,+ last_synced_at,created_at+ ) VALUES (+ ?,?,?,?,?,'','','','','',?,'','','','','','','','','AUTO','MAG_BASIC','BASIC_MAC',+ 'GENERIC_SAFE','AUTO','AUTO_STRICT','','',0,0,'','','auto','',0,'UNVERIFIED',+ 'CLASSIC_MAG','GENERIC_SAFE','AUTO','NONE','AUTO',NULL,0,1,0,0,0,0,0,0,1,NULL,NULL,+ '[]','BACKGROUND','ON_DEMAND','AUTO','SUPPLIER_PREFERRED',1,'AUTO',0,'SPLIT',0,+ 'UNKNOWN',0,0+ )+ """.trimIndent(),+ arrayOf(id, name, type, "seed://$id", "seed-$id", "seed-mac-$id")+ )+ }++ private fun SupportSQLiteDatabase.insertChannel72(+ id: Long,+ streamId: Long,+ name: String,+ providerId: Long+ ) {+ execSQL(+ """+ INSERT INTO channels (+ id,stream_id,name,stream_url,number,catch_up_supported,catch_up_days,provider_id,+ is_adult,is_user_protected,logical_group_id,error_count,sync_fingerprint+ ) VALUES (?,?,?,'https://stream.test/live',0,0,0,?,0,0,'',0,'channel-test')+ """.trimIndent(),+ arrayOf(id, streamId, name, providerId)+ )+ }++ private fun SupportSQLiteDatabase.insertStalkerPortalState72(providerId: Long) {+ execSQL(+ """+ INSERT INTO stalker_portal_state (+ provider_id,working_endpoint,safe_metadata_concurrency,stress_cooldown_until,+ endpoint_health_json,endpoint_failed_until,validated_at,schema_version+ ) VALUES (?,'https://s.test/load.php',1,0,'{}',0,100,1)+ """.trimIndent(),+ arrayOf(providerId)+ )+ }++ private fun countRows(db: SupportSQLiteDatabase, sql: String): Int {db.query(sql).use { cursor ->if (!cursor.moveToFirst()) return 0return cursor.getInt(0)diff --git a/data/src/main/java/com/streamvault/data/epg/EpgResolutionEngine.kt b/data/src/main/java/com/streamvault/data/epg/EpgResolutionEngine.ktindex de6263dd..06ca198c 100644--- a/data/src/main/java/com/streamvault/data/epg/EpgResolutionEngine.kt+++ b/data/src/main/java/com/streamvault/data/epg/EpgResolutionEngine.kt@@ -6,7 +6,7 @@ import com.streamvault.data.local.dao.ChannelEpgMappingDaoimport com.streamvault.data.local.dao.EpgChannelDaoimport com.streamvault.data.local.dao.EpgProgrammeDaoimport com.streamvault.data.local.dao.ProgramDao-import com.streamvault.data.local.dao.ProviderDao+import com.streamvault.data.local.dao.ProviderSnapshotDaoimport com.streamvault.data.local.dao.ProviderEpgSourceDaoimport com.streamvault.data.local.entity.ChannelEpgMappingEntityimport com.streamvault.data.mapper.toDomain@@ -41,7 +41,7 @@ class EpgResolutionEngine @Inject constructor(private val epgChannelDao: EpgChannelDao,private val epgProgrammeDao: EpgProgrammeDao,private val programDao: ProgramDao,- private val providerDao: ProviderDao+ private val providerSnapshotDao: ProviderSnapshotDao) {companion object {private const val TAG = "EpgResolutionEngine"@@ -64,7 +64,7 @@ class EpgResolutionEngine @Inject constructor(): EpgResolutionSummary = withContext(Dispatchers.Default) {val channels = channelDao.getByProviderSync(providerId).filterNot { channel -> channel.categoryId != null && channel.categoryId in hiddenLiveCategoryIds }- val guideSourcePolicy = providerDao.getById(providerId)?.guideSourcePolicy ?: GuideSourcePolicy.AUTO+ val guideSourcePolicy = providerSnapshotDao.getConfig(providerId)?.guideSourcePolicy ?: GuideSourcePolicy.AUTOif (channels.isEmpty()) {channelEpgMappingDao.deleteByProvider(providerId)return@withContext EpgResolutionSummary()@@ -266,7 +266,7 @@ class EpgResolutionEngine @Inject constructor(endTime: Long): Map<String, List<Program>> = withContext(Dispatchers.IO) {if (channelIds.isEmpty()) return@withContext emptyMap()- val guideSourcePolicy = providerDao.getById(providerId)?.guideSourcePolicy ?: GuideSourcePolicy.AUTO+ val guideSourcePolicy = providerSnapshotDao.getConfig(providerId)?.guideSourcePolicy ?: GuideSourcePolicy.AUTOif (guideSourcePolicy == GuideSourcePolicy.DISABLED) return@withContext emptyMap()val mappings = if (channelIds.size <= 500) {diff --git a/data/src/main/java/com/streamvault/data/local/StreamVaultDatabase.kt b/data/src/main/java/com/streamvault/data/local/StreamVaultDatabase.ktindex 41efe80d..8fd262fa 100644--- a/data/src/main/java/com/streamvault/data/local/StreamVaultDatabase.kt+++ b/data/src/main/java/com/streamvault/data/local/StreamVaultDatabase.kt@@ -7,10 +7,15 @@ import androidx.room.migration.Migrationimport androidx.sqlite.db.SupportSQLiteDatabaseimport com.streamvault.data.local.dao.*import com.streamvault.data.local.entity.*+import org.json.JSONObject+import java.net.URI+import java.security.MessageDigest@Database(entities = [ProviderEntity::class,+ ProviderConfigEntity::class,+ ProviderAccountRuntimeEntity::class,ChannelEntity::class,ChannelPreferenceEntity::class,ChannelFtsEntity::class,@@ -62,12 +67,13 @@ import com.streamvault.data.local.entity.*ProviderWorkflowEntity::class,ProviderWorkflowPhaseEntity::class],- version = 72,+ version = 74,exportSchema = true // ← was false; schema JSON now tracked in version control)@TypeConverters(RoomEnumConverters::class)abstract class StreamVaultDatabase : RoomDatabase() {abstract fun providerDao(): ProviderDao+ abstract fun providerSnapshotDao(): ProviderSnapshotDaoabstract fun channelDao(): ChannelDaoabstract fun channelPreferenceDao(): ChannelPreferenceDaoabstract fun movieDao(): MovieDao@@ -3210,6 +3216,232 @@ abstract class StreamVaultDatabase : RoomDatabase() {}}+ /** Migration 72 -> 73: add the typed provider snapshot boundary alongside legacy rows. */+ val MIGRATION_72_73 = object : Migration(72, 73) {+ override fun migrate(database: SupportSQLiteDatabase) {+ database.execSQL(+ """+ CREATE TABLE IF NOT EXISTS provider_configs (+ provider_id INTEGER NOT NULL,+ type TEXT NOT NULL,+ schema_version INTEGER NOT NULL,+ configuration_generation INTEGER NOT NULL,+ identity_key TEXT NOT NULL,+ encrypted_config_json TEXT NOT NULL,+ updated_at INTEGER NOT NULL,+ PRIMARY KEY(provider_id),+ FOREIGN KEY(provider_id) REFERENCES providers(id) ON UPDATE NO ACTION ON DELETE CASCADE+ )+ """.trimIndent()+ )+ database.execSQL("CREATE UNIQUE INDEX IF NOT EXISTS index_provider_configs_provider_id ON provider_configs(provider_id)")+ database.execSQL("CREATE UNIQUE INDEX IF NOT EXISTS index_provider_configs_identity_key ON provider_configs(identity_key)")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_provider_configs_type ON provider_configs(type)")+ database.execSQL(+ """+ CREATE TABLE IF NOT EXISTS provider_account_runtime (+ provider_id INTEGER NOT NULL,+ max_connections INTEGER NOT NULL,+ expiration_date INTEGER,+ api_version TEXT,+ allowed_output_formats_json TEXT NOT NULL,+ catalog_layout TEXT NOT NULL,+ catalog_layout_detection_version INTEGER NOT NULL,+ observed_at INTEGER NOT NULL,+ PRIMARY KEY(provider_id),+ FOREIGN KEY(provider_id) REFERENCES providers(id) ON UPDATE NO ACTION ON DELETE CASCADE+ )+ """.trimIndent()+ )+ database.execSQL("CREATE UNIQUE INDEX IF NOT EXISTS index_provider_account_runtime_provider_id ON provider_account_runtime(provider_id)")++ addColumnIfMissing(database, "stalker_portal_state", "configuration_generation", "INTEGER NOT NULL DEFAULT 0")+ addColumnIfMissing(database, "stalker_portal_state", "learning_json", "TEXT NOT NULL DEFAULT '{}'")+ addColumnIfMissing(database, "stalker_portal_state", "observation_source", "TEXT NOT NULL DEFAULT 'DISCOVERY'")+ addColumnIfMissing(database, "stalker_portal_state", "observed_at", "INTEGER NOT NULL DEFAULT 0")++ backfillTypedProviderSnapshots(database)+ validateForeignKeys(database, "provider_configs", "provider_account_runtime", "stalker_portal_state")+ }+ }++ /** Migration 73 -> 74: make providers a stable identity/status row. */+ val MIGRATION_73_74 = object : Migration(73, 74) {+ override fun migrate(database: SupportSQLiteDatabase) {+ addColumnIfMissing(+ database,+ "provider_configs",+ "guide_source_policy",+ "TEXT NOT NULL DEFAULT 'AUTO'"+ )+ addColumnIfMissing(+ database,+ "provider_configs",+ "channel_logo_source_policy",+ "TEXT NOT NULL DEFAULT 'SUPPLIER_PREFERRED'"+ )+ database.execSQL(+ """+ UPDATE provider_configs+ SET guide_source_policy = COALESCE(+ (SELECT guide_source_policy FROM providers WHERE providers.id = provider_configs.provider_id),+ 'AUTO'+ ),+ channel_logo_source_policy = COALESCE(+ (SELECT channel_logo_source_policy FROM providers WHERE providers.id = provider_configs.provider_id),+ 'SUPPLIER_PREFERRED'+ )+ """.trimIndent()+ )++ // Room runs migrations in a transaction with foreign keys enabled. SQLite ignores+ // PRAGMA foreign_keys changes inside that transaction, and dropping the parent+ // table would therefore cascade-delete the complete provider catalog. Preserve the+ // full transitive provider-owned FK graph in temporary shadow tables and restore it+ // after the stable parent row has been rebuilt.+ val providerDependents = backupProviderDependentTables(database)+ clearProviderDependentTables(database, providerDependents)+ database.execSQL(+ """+ CREATE TABLE providers_new (+ id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,+ name TEXT NOT NULL,+ type TEXT NOT NULL,+ is_active INTEGER NOT NULL,+ status TEXT NOT NULL,+ last_synced_at INTEGER NOT NULL,+ created_at INTEGER NOT NULL+ )+ """.trimIndent()+ )+ database.execSQL(+ """+ INSERT INTO providers_new (+ id, name, type, is_active, status, last_synced_at, created_at+ )+ SELECT id, name, type, is_active, status, last_synced_at, created_at+ FROM providers+ """.trimIndent()+ )+ database.execSQL("DROP TABLE providers")+ database.execSQL("ALTER TABLE providers_new RENAME TO providers")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_providers_type ON providers(type)")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_providers_is_active ON providers(is_active)")+ restoreProviderDependentTables(database, providerDependents)+ validateAllForeignKeys(database)+ }+ }++ private data class ProviderDependentBackup(+ val table: String,+ val temporaryTable: String+ )++ private fun backupProviderDependentTables(+ database: SupportSQLiteDatabase+ ): List<ProviderDependentBackup> {+ val tables = buildList {+ database.query(+ "SELECT name FROM sqlite_master " ++ "WHERE type='table' AND name NOT LIKE 'sqlite_%' " ++ "AND name NOT IN ('providers','room_master_table','android_metadata')"+ ).use { cursor ->+ while (cursor.moveToNext()) add(cursor.getString(0))+ }+ }+ val parentsByTable = tables.associateWith { table ->+ buildSet {+ database.query("PRAGMA foreign_key_list(${quoteSqlIdentifier(table)})").use { cursor ->+ while (cursor.moveToNext()) add(cursor.getString(2))+ }+ }+ }+ val affected = linkedSetOf("providers")+ var changed: Boolean+ do {+ changed = false+ parentsByTable.forEach { (table, parents) ->+ if (table !in affected && parents.any(affected::contains)) {+ affected += table+ changed = true+ }+ }+ } while (changed)++ val dependentTables = affected - "providers"+ val pending = dependentTables.toMutableSet()+ val ordered = mutableListOf<String>()+ val restoredParents = mutableSetOf("providers")+ while (pending.isNotEmpty()) {+ val ready = pending.filter { table ->+ parentsByTable.getValue(table)+ .filter { parent -> parent in dependentTables && parent != table }+ .all(restoredParents::contains)+ }+ check(ready.isNotEmpty()) {+ "Provider-dependent foreign-key cycle cannot be rebuilt safely: $pending"+ }+ ready.sorted().forEach { table ->+ ordered += table+ restoredParents += table+ pending -= table+ }+ }++ return ordered.mapIndexed { index, table ->+ val temporaryTable = "provider_rebuild_backup_$index"+ database.execSQL("DROP TABLE IF EXISTS ${quoteSqlIdentifier(temporaryTable)}")+ database.execSQL(+ "CREATE TEMP TABLE ${quoteSqlIdentifier(temporaryTable)} AS " ++ "SELECT * FROM ${quoteSqlIdentifier(table)}"+ )+ ProviderDependentBackup(+ table = table,+ temporaryTable = temporaryTable+ )+ }+ }++ private fun clearProviderDependentTables(+ database: SupportSQLiteDatabase,+ backups: List<ProviderDependentBackup>+ ) {+ // Every row is already present in a temporary shadow table. Clear children first so+ // rows outside the provider cascade are not left behind and inserted a second time.+ backups.asReversed().forEach { backup ->+ database.execSQL("DELETE FROM ${quoteSqlIdentifier(backup.table)}")+ }+ }++ private fun restoreProviderDependentTables(+ database: SupportSQLiteDatabase,+ backups: List<ProviderDependentBackup>+ ) {+ backups.forEach { backup ->+ database.execSQL(+ "INSERT INTO ${quoteSqlIdentifier(backup.table)} " ++ "SELECT * FROM ${quoteSqlIdentifier(backup.temporaryTable)}"+ )+ database.execSQL("DROP TABLE ${quoteSqlIdentifier(backup.temporaryTable)}")+ }+ }++ private fun quoteSqlIdentifier(value: String): String =+ "\"${value.replace("\"", "\"\"")}\""++ private fun validateAllForeignKeys(database: SupportSQLiteDatabase) {+ database.query("PRAGMA foreign_key_check").use { cursor ->+ if (cursor.moveToFirst()) {+ val table = if (!cursor.isNull(0)) cursor.getString(0) else "<unknown>"+ val rowId = if (!cursor.isNull(1)) cursor.getLong(1) else -1L+ val parent = if (!cursor.isNull(2)) cursor.getString(2) else "<unknown>"+ throw IllegalStateException(+ "Foreign key violation after provider rebuild: table=$table rowId=$rowId parent=$parent"+ )+ }+ }+ }+private fun imageUrlMigrationSql(table: String, column: String): String = """UPDATE $table SET $column = CASEWHEN instr($column, 'streamvault_provider_id=') > 0 THEN $column@@ -3272,6 +3504,202 @@ abstract class StreamVaultDatabase : RoomDatabase() {database.execSQL("ALTER TABLE $tableName ADD COLUMN $columnName $columnDefinition")}+ private fun backfillTypedProviderSnapshots(database: SupportSQLiteDatabase) {+ database.query("SELECT * FROM providers ORDER BY id").use { cursor ->+ fun text(name: String): String = cursor.getString(cursor.getColumnIndexOrThrow(name)) ?: ""+ fun long(name: String): Long = cursor.getLong(cursor.getColumnIndexOrThrow(name))+ fun int(name: String): Int = cursor.getInt(cursor.getColumnIndexOrThrow(name))+ fun nullableText(name: String): String? {+ val index = cursor.getColumnIndexOrThrow(name)+ return if (cursor.isNull(index)) null else cursor.getString(index)+ }+ fun nullableLong(name: String): Long? {+ val index = cursor.getColumnIndexOrThrow(name)+ return if (cursor.isNull(index)) null else cursor.getLong(index)+ }++ while (cursor.moveToNext()) {+ val providerId = long("id")+ val type = text("type")+ val generation = if (type == "STALKER_PORTAL") long("stalker_configuration_generation") else 0L+ val config = when (type) {+ "XTREAM_CODES" -> JSONObject()+ .put("serverUrl", text("server_url"))+ .put("username", text("username"))+ .put("password", text("password"))+ .put("httpUserAgent", text("http_user_agent"))+ .put("httpHeaders", text("http_headers"))+ .put("epgSyncMode", text("epg_sync_mode"))+ .put("guideSourcePolicy", text("guide_source_policy"))+ .put("channelLogoSourcePolicy", text("channel_logo_source_policy"))+ .put("fastSyncEnabled", int("xtream_fast_sync_enabled") != 0)+ .put("liveSyncMode", text("xtream_live_sync_mode"))+ .put("schemaVersion", 1)+ "M3U" -> JSONObject()+ .put("playlistUrl", text("m3u_url").ifBlank { text("server_url") })+ .put("epgUrl", text("epg_url"))+ .put("httpUserAgent", text("http_user_agent"))+ .put("httpHeaders", text("http_headers"))+ .put("epgSyncMode", text("epg_sync_mode"))+ .put("guideSourcePolicy", text("guide_source_policy"))+ .put("channelLogoSourcePolicy", text("channel_logo_source_policy"))+ .put("vodClassificationEnabled", int("m3u_vod_classification_enabled") != 0)+ .put("schemaVersion", 1)+ "STALKER_PORTAL" -> JSONObject()+ .put("portalUrl", text("server_url"))+ .put("device", JSONObject()+ .put("macAddress", text("stalker_mac_address"))+ .put("deviceProfile", text("stalker_device_profile"))+ .put("timezone", text("stalker_device_timezone"))+ .put("locale", text("stalker_device_locale"))+ .put("serialNumber", text("stalker_serial_number"))+ .put("deviceId", text("stalker_device_id"))+ .put("deviceId2", text("stalker_device_id2"))+ .put("signature", text("stalker_signature")))+ .put("username", text("username"))+ .put("password", text("password"))+ .put("httpUserAgent", text("http_user_agent"))+ .put("httpHeaders", text("http_headers"))+ .put("advancedOptionsJson", text("stalker_advanced_options_json"))+ .put("authMode", text("stalker_auth_mode"))+ .put("requestedProfileId", text("stalker_requested_profile_id"))+ .put("protocolPreference", text("stalker_protocol_preference"))+ .put("transportGrant", legacyTransportGrant(cursor))+ .put("epgSyncMode", text("epg_sync_mode"))+ .put("catalogMode", text("stalker_catalog_mode"))+ .put("guideSourcePolicy", text("guide_source_policy"))+ .put("channelLogoSourcePolicy", text("channel_logo_source_policy"))+ .put("schemaVersion", 1)+ "JELLYFIN" -> JSONObject()+ .put("serverUrl", text("server_url"))+ .put("username", text("username"))+ .put("credential", text("password"))+ .put("schemaVersion", 1)+ else -> throw IllegalStateException("Unknown provider type during migration: $type")+ }+ val identity = when (type) {+ "XTREAM_CODES", "JELLYFIN" -> listOf(type, migrationNormalizeOrigin(text("server_url")), text("username").trim())+ "M3U" -> listOf(type, text("m3u_url").ifBlank { text("server_url") }.trim())+ "STALKER_PORTAL" -> listOf(+ type,+ migrationNormalizeOrigin(text("server_url")),+ text("stalker_mac_address").trim().uppercase(),+ text("username").trim()+ )+ else -> error("unreachable")+ }.joinToString("\u0000")+ val identityKey = MessageDigest.getInstance("SHA-256")+ .digest(identity.toByteArray(Charsets.UTF_8))+ .joinToString("") { "%02x".format(it) }+ val updatedAt = long("last_synced_at").takeIf { it > 0L } ?: long("created_at")++ database.execSQL(+ "INSERT INTO provider_configs(provider_id,type,schema_version,configuration_generation,identity_key,encrypted_config_json,updated_at) VALUES(?,?,?,?,?,?,?)",+ arrayOf(providerId, type, 1, generation, identityKey, config.toString(), updatedAt)+ )+ database.execSQL(+ "INSERT INTO provider_account_runtime(provider_id,max_connections,expiration_date,api_version,allowed_output_formats_json,catalog_layout,catalog_layout_detection_version,observed_at) VALUES(?,?,?,?,?,?,?,?)",+ arrayOf(+ providerId,+ int("max_connections"),+ nullableLong("expiration_date"),+ nullableText("api_version"),+ text("allowed_output_formats_json"),+ text("catalog_layout"),+ int("catalog_layout_detection_version"),+ updatedAt+ )+ )+ if (type == "STALKER_PORTAL") {+ database.execSQL(+ "UPDATE stalker_portal_state SET configuration_generation=?, learning_json=?, observation_source='DISCOVERY', observed_at=CASE WHEN validated_at > 0 THEN validated_at ELSE ? END WHERE provider_id=?",+ arrayOf(+ generation,+ legacyStalkerLearning(cursor, generation, updatedAt).toString(),+ updatedAt,+ providerId+ )+ )+ }+ }+ }+ }++ private fun legacyStalkerLearning(+ cursor: android.database.Cursor,+ generation: Long,+ observedAt: Long+ ): JSONObject {+ fun text(name: String): String = cursor.getString(cursor.getColumnIndexOrThrow(name)) ?: ""+ fun int(name: String): Int = cursor.getInt(cursor.getColumnIndexOrThrow(name))+ fun observation(value: Any): JSONObject = JSONObject()+ .put("value", value)+ .put("configurationGeneration", generation)+ .put("source", "DISCOVERY")+ .put("observedAt", observedAt)+ val identity = JSONObject()+ .put("macAddress", text("stalker_mac_address"))+ .put("deviceProfile", text("stalker_device_profile"))+ .put("timezone", text("stalker_device_timezone"))+ .put("locale", text("stalker_device_locale"))+ .put("serialNumber", text("stalker_serial_number"))+ .put("deviceId", text("stalker_device_id"))+ .put("deviceId2", text("stalker_device_id2"))+ .put("signature", text("stalker_signature"))+ return JSONObject()+ .put("configurationGeneration", generation)+ .put("effectiveIdentity", observation(identity))+ .apply {+ text("stalker_learned_profile_id").takeIf(String::isNotBlank)+ ?.let { put("profileId", observation(it)) }+ put("profileRevision", observation(int("stalker_profile_revision")))+ put("profileVerification", observation(text("stalker_profile_verification")))+ put("portalProfile", observation(text("stalker_portal_profile")))+ put("portalFingerprint", observation(text("stalker_portal_fingerprint")))+ put("magPreset", observation(text("stalker_mag_preset")))+ put("protocolFamily", observation(text("stalker_protocol_family")))+ put("bootstrapRecipe", observation(text("stalker_last_bootstrap_recipe")))+ put("endpointPreference", observation(text("stalker_endpoint_preference")))+ put("cookieMode", observation(text("stalker_cookie_mode")))+ put("playbackBackendHint", observation(text("stalker_playback_backend_hint")))+ val lastPlaybackModeIndex = cursor.getColumnIndexOrThrow("stalker_last_playback_mode")+ if (!cursor.isNull(lastPlaybackModeIndex)) {+ put("lastPlaybackMode", observation(cursor.getString(lastPlaybackModeIndex)))+ }+ put("capabilities", JSONObject())+ put("discoveryEvidence", org.json.JSONArray())+ }+ }++ private fun legacyTransportGrant(cursor: android.database.Cursor): Any {+ fun text(name: String): String = cursor.getString(cursor.getColumnIndexOrThrow(name)) ?: ""+ val mode = text("stalker_transport_mode")+ val consentedAt = cursor.getLong(cursor.getColumnIndexOrThrow("stalker_transport_consent_at"))+ if (mode == "AUTO_STRICT" || consentedAt <= 0L) return JSONObject.NULL+ val originValue = text("stalker_transport_origin")+ val uri = runCatching { URI(originValue) }.getOrNull() ?: return JSONObject.NULL+ val scheme = uri.scheme?.lowercase() ?: return JSONObject.NULL+ val host = uri.host ?: return JSONObject.NULL+ val port = uri.port.takeIf { it >= 0 } ?: if (scheme == "https") 443 else 80+ return JSONObject()+ .put("mode", mode)+ .put("origin", JSONObject().put("scheme", scheme).put("host", host).put("port", port))+ .put("spkiSha256", text("stalker_tls_spki_sha256").takeIf { it.isNotBlank() })+ .put("consentedAt", consentedAt)+ }++ private fun migrationNormalizeOrigin(value: String): String = runCatching {+ val uri = URI(value.trim())+ val scheme = uri.scheme?.lowercase().orEmpty()+ val host = uri.host?.lowercase().orEmpty()+ val port = uri.port.takeIf { it >= 0 } ?: when (scheme) {+ "https" -> 443+ "http" -> 80+ else -> -1+ }+ "$scheme://$host:$port${uri.path.orEmpty().trimEnd('/')}"+ }.getOrElse { value.trim().trimEnd('/').lowercase() }+private fun tableHasColumn(database: SupportSQLiteDatabase,tableName: String,diff --git a/data/src/main/java/com/streamvault/data/local/dao/Daos.kt b/data/src/main/java/com/streamvault/data/local/dao/Daos.ktindex cfc5c272..c06a9007 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@@ -30,13 +30,6 @@ abstract class ProviderDao {@Query("SELECT * FROM providers WHERE is_active = 1 LIMIT 1")abstract fun getActive(): Flow<ProviderEntity?>- @Query("SELECT * FROM providers WHERE server_url = :serverUrl AND username = :username AND stalker_mac_address = :stalkerMacAddress")- abstract suspend fun getByUrlAndUser(- serverUrl: String,- username: String,- stalkerMacAddress: String = ""- ): ProviderEntity?-@Query("SELECT * FROM providers WHERE id = :id")abstract suspend fun getById(id: Long): ProviderEntity?@@ -67,19 +60,6 @@ abstract class ProviderDao {@Query("UPDATE providers SET last_synced_at = :timestamp WHERE id = :id")abstract suspend fun updateSyncTime(id: Long, timestamp: Long)- @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) {@@ -110,7 +90,10 @@ abstract class ChannelDao {"""SELECT c.id, c.stream_id, c.name, c.logo_url, c.group_title, c.category_id, c.category_name, c.stream_url,c.epg_channel_id, c.number, c.catch_up_supported, c.catch_up_days, c.catchUpSource,- c.provider_id, p.guide_source_policy, p.channel_logo_source_policy, ec.icon_url AS epg_icon_url,+ c.provider_id,+ (SELECT guide_source_policy FROM provider_configs WHERE provider_id = c.provider_id) AS guide_source_policy,+ (SELECT channel_logo_source_policy FROM provider_configs WHERE provider_id = c.provider_id) AS channel_logo_source_policy,+ ec.icon_url AS epg_icon_url,c.is_adult, c.is_user_protected, c.logical_group_id, c.error_countFROM channels cJOIN providers p ON p.id = c.provider_id@@ -126,7 +109,10 @@ abstract class ChannelDao {"""SELECT c.id, c.stream_id, c.name, c.logo_url, c.group_title, c.category_id, c.category_name, c.stream_url,c.epg_channel_id, c.number, c.catch_up_supported, c.catch_up_days, c.catchUpSource,- c.provider_id, p.guide_source_policy, p.channel_logo_source_policy, ec.icon_url AS epg_icon_url,+ c.provider_id,+ (SELECT guide_source_policy FROM provider_configs WHERE provider_id = c.provider_id) AS guide_source_policy,+ (SELECT channel_logo_source_policy FROM provider_configs WHERE provider_id = c.provider_id) AS channel_logo_source_policy,+ ec.icon_url AS epg_icon_url,c.is_adult, c.is_user_protected, c.logical_group_id, c.error_countFROM channels cJOIN providers p ON p.id = c.provider_id@@ -142,7 +128,10 @@ abstract class ChannelDao {"""SELECT c.id, c.stream_id, c.name, c.logo_url, c.group_title, c.category_id, c.category_name, c.stream_url,c.epg_channel_id, c.number, c.catch_up_supported, c.catch_up_days, c.catchUpSource,- c.provider_id, p.guide_source_policy, p.channel_logo_source_policy, ec.icon_url AS epg_icon_url,+ c.provider_id,+ (SELECT guide_source_policy FROM provider_configs WHERE provider_id = c.provider_id) AS guide_source_policy,+ (SELECT channel_logo_source_policy FROM provider_configs WHERE provider_id = c.provider_id) AS channel_logo_source_policy,+ ec.icon_url AS epg_icon_url,c.is_adult, c.is_user_protected, c.logical_group_id, c.error_countFROM channels cJOIN providers p ON p.id = c.provider_id@@ -159,7 +148,10 @@ abstract class ChannelDao {"""SELECT c.id, c.stream_id, c.name, c.logo_url, c.group_title, c.category_id, c.category_name, c.stream_url,c.epg_channel_id, c.number, c.catch_up_supported, c.catch_up_days, c.catchUpSource,- c.provider_id, p.guide_source_policy, p.channel_logo_source_policy, ec.icon_url AS epg_icon_url,+ c.provider_id,+ (SELECT guide_source_policy FROM provider_configs WHERE provider_id = c.provider_id) AS guide_source_policy,+ (SELECT channel_logo_source_policy FROM provider_configs WHERE provider_id = c.provider_id) AS channel_logo_source_policy,+ ec.icon_url AS epg_icon_url,c.is_adult, c.is_user_protected, c.logical_group_id, c.error_countFROM channels cJOIN providers p ON p.id = c.provider_id@@ -176,7 +168,10 @@ abstract class ChannelDao {"""SELECT c.id, c.stream_id, c.name, c.logo_url, c.group_title, c.category_id, c.category_name, c.stream_url,c.epg_channel_id, c.number, c.catch_up_supported, c.catch_up_days, c.catchUpSource,- c.provider_id, p.guide_source_policy, p.channel_logo_source_policy, ec.icon_url AS epg_icon_url,+ c.provider_id,+ (SELECT guide_source_policy FROM provider_configs WHERE provider_id = c.provider_id) AS guide_source_policy,+ (SELECT channel_logo_source_policy FROM provider_configs WHERE provider_id = c.provider_id) AS channel_logo_source_policy,+ ec.icon_url AS epg_icon_url,c.is_adult, c.is_user_protected, c.logical_group_id, c.error_countFROM channels cJOIN providers p ON p.id = c.provider_id@@ -196,7 +191,10 @@ abstract class ChannelDao {"""SELECT c.id, c.stream_id, c.name, c.logo_url, c.group_title, c.category_id, c.category_name, c.stream_url,c.epg_channel_id, c.number, c.catch_up_supported, c.catch_up_days, c.catchUpSource,- c.provider_id, p.guide_source_policy, p.channel_logo_source_policy, ec.icon_url AS epg_icon_url,+ c.provider_id,+ (SELECT guide_source_policy FROM provider_configs WHERE provider_id = c.provider_id) AS guide_source_policy,+ (SELECT channel_logo_source_policy FROM provider_configs WHERE provider_id = c.provider_id) AS channel_logo_source_policy,+ ec.icon_url AS epg_icon_url,c.is_adult, c.is_user_protected, c.logical_group_id, c.error_countFROM channels cJOIN providers p ON p.id = c.provider_id@@ -212,7 +210,10 @@ abstract class ChannelDao {"""SELECT c.id, c.stream_id, c.name, c.logo_url, c.group_title, c.category_id, c.category_name, c.stream_url,c.epg_channel_id, c.number, c.catch_up_supported, c.catch_up_days, c.catchUpSource,- c.provider_id, p.guide_source_policy, p.channel_logo_source_policy, ec.icon_url AS epg_icon_url,+ c.provider_id,+ (SELECT guide_source_policy FROM provider_configs WHERE provider_id = c.provider_id) AS guide_source_policy,+ (SELECT channel_logo_source_policy FROM provider_configs WHERE provider_id = c.provider_id) AS channel_logo_source_policy,+ ec.icon_url AS epg_icon_url,c.is_adult, c.is_user_protected, c.logical_group_id, c.error_countFROM channels cJOIN providers p ON p.id = c.provider_id@@ -228,7 +229,10 @@ abstract class ChannelDao {"""SELECT c.id, c.stream_id, c.name, c.logo_url, c.group_title, c.category_id, c.category_name, c.stream_url,c.epg_channel_id, c.number, c.catch_up_supported, c.catch_up_days, c.catchUpSource,- c.provider_id, p.guide_source_policy, p.channel_logo_source_policy, ec.icon_url AS epg_icon_url,+ c.provider_id,+ (SELECT guide_source_policy FROM provider_configs WHERE provider_id = c.provider_id) AS guide_source_policy,+ (SELECT channel_logo_source_policy FROM provider_configs WHERE provider_id = c.provider_id) AS channel_logo_source_policy,+ ec.icon_url AS epg_icon_url,c.is_adult, c.is_user_protected, c.logical_group_id, c.error_countFROM channels cJOIN providers p ON p.id = c.provider_id@@ -249,7 +253,10 @@ abstract class ChannelDao {"""SELECT c.id, c.stream_id, c.name, c.logo_url, c.group_title, c.category_id, c.category_name, c.stream_url,c.epg_channel_id, c.number, c.catch_up_supported, c.catch_up_days, c.catchUpSource,- c.provider_id, p.guide_source_policy, p.channel_logo_source_policy, ec.icon_url AS epg_icon_url,+ c.provider_id,+ (SELECT guide_source_policy FROM provider_configs WHERE provider_id = c.provider_id) AS guide_source_policy,+ (SELECT channel_logo_source_policy FROM provider_configs WHERE provider_id = c.provider_id) AS channel_logo_source_policy,+ ec.icon_url AS epg_icon_url,c.is_adult, c.is_user_protected, c.logical_group_id, c.error_countFROM channels cJOIN providers p ON p.id = c.provider_id@@ -266,7 +273,10 @@ abstract class ChannelDao {"""SELECT c.id, c.stream_id, c.name, c.logo_url, c.group_title, c.category_id, c.category_name, c.stream_url,c.epg_channel_id, c.number, c.catch_up_supported, c.catch_up_days, c.catchUpSource,- c.provider_id, p.guide_source_policy, p.channel_logo_source_policy, ec.icon_url AS epg_icon_url,+ c.provider_id,+ (SELECT guide_source_policy FROM provider_configs WHERE provider_id = c.provider_id) AS guide_source_policy,+ (SELECT channel_logo_source_policy FROM provider_configs WHERE provider_id = c.provider_id) AS channel_logo_source_policy,+ ec.icon_url AS epg_icon_url,c.is_adult, c.is_user_protected, c.logical_group_id, c.error_countFROM channels cJOIN providers p ON p.id = c.provider_id@@ -283,7 +293,10 @@ abstract class ChannelDao {"""SELECT c.id, c.stream_id, c.name, c.logo_url, c.group_title, c.category_id, c.category_name, c.stream_url,c.epg_channel_id, c.number, c.catch_up_supported, c.catch_up_days, c.catchUpSource,- c.provider_id, p.guide_source_policy, p.channel_logo_source_policy, ec.icon_url AS epg_icon_url,+ c.provider_id,+ (SELECT guide_source_policy FROM provider_configs WHERE provider_id = c.provider_id) AS guide_source_policy,+ (SELECT channel_logo_source_policy FROM provider_configs WHERE provider_id = c.provider_id) AS channel_logo_source_policy,+ ec.icon_url AS epg_icon_url,c.is_adult, c.is_user_protected, c.logical_group_id, c.error_countFROM channels cJOIN providers p ON p.id = c.provider_id@@ -300,7 +313,10 @@ abstract class ChannelDao {"""SELECT c.id, c.stream_id, c.name, c.logo_url, c.group_title, c.category_id, c.category_name, c.stream_url,c.epg_channel_id, c.number, c.catch_up_supported, c.catch_up_days, c.catchUpSource,- c.provider_id, p.guide_source_policy, p.channel_logo_source_policy, ec.icon_url AS epg_icon_url,+ c.provider_id,+ (SELECT guide_source_policy FROM provider_configs WHERE provider_id = c.provider_id) AS guide_source_policy,+ (SELECT channel_logo_source_policy FROM provider_configs WHERE provider_id = c.provider_id) AS channel_logo_source_policy,+ ec.icon_url AS epg_icon_url,c.is_adult, c.is_user_protected, c.logical_group_id, c.error_countFROM channels cJOIN providers p ON p.id = c.provider_id@@ -320,7 +336,10 @@ abstract class ChannelDao {"""SELECT c.id, c.stream_id, c.name, c.logo_url, c.group_title, c.category_id, c.category_name, c.stream_url,c.epg_channel_id, c.number, c.catch_up_supported, c.catch_up_days, c.catchUpSource,- c.provider_id, p.guide_source_policy, p.channel_logo_source_policy, ec.icon_url AS epg_icon_url,+ c.provider_id,+ (SELECT guide_source_policy FROM provider_configs WHERE provider_id = c.provider_id) AS guide_source_policy,+ (SELECT channel_logo_source_policy FROM provider_configs WHERE provider_id = c.provider_id) AS channel_logo_source_policy,+ ec.icon_url AS epg_icon_url,c.is_adult, c.is_user_protected, c.logical_group_id, c.error_countFROM channels cJOIN providers p ON p.id = c.provider_id@@ -339,7 +358,10 @@ abstract class ChannelDao {"""SELECT c.id, c.stream_id, c.name, c.logo_url, c.group_title, c.category_id, c.category_name, c.stream_url,c.epg_channel_id, c.number, c.catch_up_supported, c.catch_up_days, c.catchUpSource,- c.provider_id, p.guide_source_policy, p.channel_logo_source_policy, ec.icon_url AS epg_icon_url,+ c.provider_id,+ (SELECT guide_source_policy FROM provider_configs WHERE provider_id = c.provider_id) AS guide_source_policy,+ (SELECT channel_logo_source_policy FROM provider_configs WHERE provider_id = c.provider_id) AS channel_logo_source_policy,+ ec.icon_url AS epg_icon_url,c.is_adult, c.is_user_protected, c.logical_group_id, c.error_countFROM channels cJOIN providers p ON p.id = c.provider_id@@ -361,7 +383,10 @@ abstract class ChannelDao {"""SELECT c.id, c.stream_id, c.name, c.logo_url, c.group_title, c.category_id, c.category_name, c.stream_url,c.epg_channel_id, c.number, c.catch_up_supported, c.catch_up_days, c.catchUpSource,- c.provider_id, p.guide_source_policy, p.channel_logo_source_policy, ec.icon_url AS epg_icon_url,+ c.provider_id,+ (SELECT guide_source_policy FROM provider_configs WHERE provider_id = c.provider_id) AS guide_source_policy,+ (SELECT channel_logo_source_policy FROM provider_configs WHERE provider_id = c.provider_id) AS channel_logo_source_policy,+ ec.icon_url AS epg_icon_url,c.is_adult, c.is_user_protected, c.logical_group_id, c.error_countFROM channels cJOIN providers p ON p.id = c.provider_id@@ -381,7 +406,10 @@ abstract class ChannelDao {"""SELECT c.id, c.stream_id, c.name, c.logo_url, c.group_title, c.category_id, c.category_name, c.stream_url,c.epg_channel_id, c.number, c.catch_up_supported, c.catch_up_days, c.catchUpSource,- c.provider_id, p.guide_source_policy, p.channel_logo_source_policy, ec.icon_url AS epg_icon_url,+ c.provider_id,+ (SELECT guide_source_policy FROM provider_configs WHERE provider_id = c.provider_id) AS guide_source_policy,+ (SELECT channel_logo_source_policy FROM provider_configs WHERE provider_id = c.provider_id) AS channel_logo_source_policy,+ ec.icon_url AS epg_icon_url,c.is_adult, c.is_user_protected, c.logical_group_id, c.error_countFROM channels cJOIN providers p ON p.id = c.provider_id@@ -407,7 +435,10 @@ abstract class ChannelDao {"""SELECT c.id, c.stream_id, c.name, c.logo_url, c.group_title, c.category_id, c.category_name, c.stream_url,c.epg_channel_id, c.number, c.catch_up_supported, c.catch_up_days, c.catchUpSource,- c.provider_id, p.guide_source_policy, p.channel_logo_source_policy, ec.icon_url AS epg_icon_url,+ c.provider_id,+ (SELECT guide_source_policy FROM provider_configs WHERE provider_id = c.provider_id) AS guide_source_policy,+ (SELECT channel_logo_source_policy FROM provider_configs WHERE provider_id = c.provider_id) AS channel_logo_source_policy,+ ec.icon_url AS epg_icon_url,c.is_adult, c.is_user_protected, c.logical_group_id, c.error_countFROM channels cJOIN providers p ON p.id = c.provider_id@@ -473,7 +504,10 @@ abstract class ChannelDao {"""SELECT c.id, c.stream_id, c.name, c.logo_url, c.group_title, c.category_id, c.category_name, c.stream_url,c.epg_channel_id, c.number, c.catch_up_supported, c.catch_up_days, c.catchUpSource,- c.provider_id, p.guide_source_policy, p.channel_logo_source_policy, ec.icon_url AS epg_icon_url,+ c.provider_id,+ (SELECT guide_source_policy FROM provider_configs WHERE provider_id = c.provider_id) AS guide_source_policy,+ (SELECT channel_logo_source_policy FROM provider_configs WHERE provider_id = c.provider_id) AS channel_logo_source_policy,+ ec.icon_url AS epg_icon_url,c.is_adult, c.is_user_protected, c.logical_group_id, c.error_countFROM channels cJOIN providers p ON p.id = c.provider_id@@ -488,7 +522,10 @@ abstract class ChannelDao {"""SELECT c.id, c.stream_id, c.name, c.logo_url, c.group_title, c.category_id, c.category_name, c.stream_url,c.epg_channel_id, c.number, c.catch_up_supported, c.catch_up_days, c.catchUpSource,- c.provider_id, p.guide_source_policy, p.channel_logo_source_policy, ec.icon_url AS epg_icon_url,+ c.provider_id,+ (SELECT guide_source_policy FROM provider_configs WHERE provider_id = c.provider_id) AS guide_source_policy,+ (SELECT channel_logo_source_policy FROM provider_configs WHERE provider_id = c.provider_id) AS channel_logo_source_policy,+ ec.icon_url AS epg_icon_url,c.is_adult, c.is_user_protected, c.logical_group_id, c.error_countFROM channels cJOIN providers p ON p.id = c.provider_id@@ -504,7 +541,10 @@ abstract class ChannelDao {"""SELECT c.id, c.stream_id, c.name, c.logo_url, c.group_title, c.category_id, c.category_name, c.stream_url,c.epg_channel_id, c.number, c.catch_up_supported, c.catch_up_days, c.catchUpSource,- c.provider_id, p.guide_source_policy, p.channel_logo_source_policy, ec.icon_url AS epg_icon_url,+ c.provider_id,+ (SELECT guide_source_policy FROM provider_configs WHERE provider_id = c.provider_id) AS guide_source_policy,+ (SELECT channel_logo_source_policy FROM provider_configs WHERE provider_id = c.provider_id) AS channel_logo_source_policy,+ ec.icon_url AS epg_icon_url,c.is_adult, c.is_user_protected, c.logical_group_id, c.error_countFROM channels cJOIN providers p ON p.id = c.provider_iddiff --git a/data/src/main/java/com/streamvault/data/local/dao/ProviderSnapshotDao.kt b/data/src/main/java/com/streamvault/data/local/dao/ProviderSnapshotDao.ktnew file mode 100644index 00000000..a0ae894b--- /dev/null+++ b/data/src/main/java/com/streamvault/data/local/dao/ProviderSnapshotDao.kt@@ -0,0 +1,77 @@+package com.streamvault.data.local.dao++import androidx.room.Dao+import androidx.room.Insert+import androidx.room.OnConflictStrategy+import androidx.room.Query+import androidx.room.Transaction+import com.streamvault.data.local.entity.ProviderAccountRuntimeEntity+import com.streamvault.data.local.entity.ProviderConfigEntity+import com.streamvault.data.local.entity.StalkerPortalStateEntity+import kotlinx.coroutines.flow.Flow++@Dao+abstract class ProviderSnapshotDao {+ @Query("SELECT * FROM provider_configs WHERE provider_id = :providerId LIMIT 1")+ abstract suspend fun getConfig(providerId: Long): ProviderConfigEntity?++ @Query("SELECT * FROM provider_configs WHERE provider_id = :providerId LIMIT 1")+ abstract fun getConfigSync(providerId: Long): ProviderConfigEntity?++ @Query("SELECT * FROM provider_configs")+ abstract fun observeConfigs(): Flow<List<ProviderConfigEntity>>++ @Query("SELECT * FROM provider_account_runtime WHERE provider_id = :providerId LIMIT 1")+ abstract suspend fun getRuntime(providerId: Long): ProviderAccountRuntimeEntity?++ @Query("SELECT * FROM provider_account_runtime")+ abstract fun observeRuntimes(): Flow<List<ProviderAccountRuntimeEntity>>++ @Query("SELECT * FROM stalker_portal_state")+ abstract fun observeStalkerPortalStates(): Flow<List<StalkerPortalStateEntity>>++ @Query("SELECT provider_id FROM provider_configs WHERE identity_key = :identityKey LIMIT 1")+ abstract suspend fun findProviderIdByIdentityKey(identityKey: String): Long?++ @Insert(onConflict = OnConflictStrategy.REPLACE)+ protected abstract suspend fun upsertConfigDirect(entity: ProviderConfigEntity)++ @Insert(onConflict = OnConflictStrategy.REPLACE)+ abstract suspend fun upsertRuntime(entity: ProviderAccountRuntimeEntity)++ @Query("UPDATE provider_account_runtime SET catalog_layout_detection_version = 0 WHERE provider_id = :providerId")+ abstract suspend fun invalidateCatalogLayoutDetection(providerId: Long)++ @Query("UPDATE provider_account_runtime SET catalog_layout = :layout, catalog_layout_detection_version = :version WHERE provider_id = :providerId")+ abstract suspend fun updateCatalogLayout(+ providerId: Long,+ layout: com.streamvault.domain.model.CatalogLayout,+ version: Int+ )++ @Query("SELECT configuration_generation FROM provider_configs WHERE provider_id = :providerId")+ protected abstract suspend fun generation(providerId: Long): Long?++ @Insert(onConflict = OnConflictStrategy.REPLACE)+ protected abstract suspend fun upsertLearningDirect(entity: StalkerPortalStateEntity)++ /**+ * Configuration edits are monotonic. A stale caller cannot roll back a newer generation.+ */+ @Transaction+ open suspend fun commitConfiguration(entity: ProviderConfigEntity): Boolean {+ val current = generation(entity.providerId)+ if (current != null && entity.configurationGeneration <= current) return false+ upsertConfigDirect(entity)+ return true+ }++ /** Room holds one database transaction across the generation check and learning write. */+ @Transaction+ open suspend fun compareAndSetStalkerLearning(entity: StalkerPortalStateEntity): Boolean {+ val current = generation(entity.providerId) ?: return false+ if (current != entity.configurationGeneration) return false+ upsertLearningDirect(entity)+ return true+ }+}diff --git a/data/src/main/java/com/streamvault/data/local/entity/Entities.kt b/data/src/main/java/com/streamvault/data/local/entity/Entities.ktindex 4dfb1454..922fb0d5 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@@ -33,75 +33,69 @@ import com.streamvault.domain.model.XmltvTimezonePolicy@Entity(tableName = "providers",- indices = [Index(value = ["server_url", "username", "stalker_mac_address"], unique = true)]+ indices = [Index(value = ["type"]), Index(value = ["is_active"])])data class ProviderEntity(@PrimaryKey(autoGenerate = true)val id: Long = 0,val name: String,val type: ProviderType,- @ColumnInfo(name = "server_url") val serverUrl: String,- val username: String = "",- val password: String = "",- @ColumnInfo(name = "m3u_url") val m3uUrl: String = "",- @ColumnInfo(name = "epg_url") val epgUrl: String = "",- @ColumnInfo(name = "http_user_agent") val httpUserAgent: String = "",- @ColumnInfo(name = "http_headers") val httpHeaders: String = "",- @ColumnInfo(name = "stalker_mac_address") val stalkerMacAddress: String = "",- @ColumnInfo(name = "stalker_device_profile") val stalkerDeviceProfile: String = "",- @ColumnInfo(name = "stalker_device_timezone") val stalkerDeviceTimezone: String = "",- @ColumnInfo(name = "stalker_device_locale") val stalkerDeviceLocale: String = "",- @ColumnInfo(name = "stalker_serial_number") val stalkerSerialNumber: String = "",- @ColumnInfo(name = "stalker_device_id") val stalkerDeviceId: String = "",- @ColumnInfo(name = "stalker_device_id2") val stalkerDeviceId2: String = "",- @ColumnInfo(name = "stalker_signature") val stalkerSignature: String = "",- @ColumnInfo(name = "stalker_advanced_options_json") val stalkerAdvancedOptionsJson: String = "",- @ColumnInfo(name = "stalker_auth_mode") val stalkerAuthMode: StalkerAuthMode = StalkerAuthMode.AUTO,- @ColumnInfo(name = "stalker_portal_profile") val stalkerPortalProfile: StalkerPortalProfile = StalkerPortalProfile.MAG_BASIC,- @ColumnInfo(name = "stalker_portal_fingerprint") val stalkerPortalFingerprint: StalkerPortalFingerprint = StalkerPortalFingerprint.BASIC_MAC,- @ColumnInfo(name = "stalker_mag_preset") val stalkerMagPreset: StalkerMagPreset = StalkerMagPreset.GENERIC_SAFE,- @ColumnInfo(name = "stalker_protocol_preference") val stalkerProtocolPreference: StalkerProtocolPreference = StalkerProtocolPreference.AUTO,- @ColumnInfo(name = "stalker_transport_mode") val stalkerTransportMode: StalkerTransportMode = StalkerTransportMode.AUTO_STRICT,- @ColumnInfo(name = "stalker_transport_origin") val stalkerTransportOrigin: String = "",- @ColumnInfo(name = "stalker_tls_spki_sha256") val stalkerTlsSpkiSha256: String = "",- @ColumnInfo(name = "stalker_transport_consent_at") val stalkerTransportConsentAt: Long = 0L,- @ColumnInfo(name = "stalker_configuration_generation") val stalkerConfigurationGeneration: Long = 0L,- @ColumnInfo(name = "stalker_discovery_summary") val stalkerDiscoverySummary: String = "",- @ColumnInfo(name = "stalker_capabilities_json") val stalkerCapabilitiesJson: String = "",- @ColumnInfo(name = "stalker_requested_profile_id") val stalkerRequestedProfileId: String = StalkerCompatibilityProfileIds.AUTO,- @ColumnInfo(name = "stalker_learned_profile_id") val stalkerLearnedProfileId: String = "",- @ColumnInfo(name = "stalker_profile_revision") val stalkerProfileRevision: Int = 0,- @ColumnInfo(name = "stalker_profile_verification") val stalkerProfileVerification: StalkerProfileVerification = StalkerProfileVerification.UNVERIFIED,- @ColumnInfo(name = "stalker_protocol_family") val stalkerProtocolFamily: StalkerProtocolFamily = StalkerProtocolFamily.CLASSIC_MAG,- @ColumnInfo(name = "stalker_last_bootstrap_recipe") val stalkerLastBootstrapRecipe: StalkerBootstrapRecipe = StalkerBootstrapRecipe.GENERIC_SAFE,- @ColumnInfo(name = "stalker_endpoint_preference") val stalkerEndpointPreference: StalkerEndpointPreference = StalkerEndpointPreference.AUTO,- @ColumnInfo(name = "stalker_cookie_mode") val stalkerCookieMode: StalkerCookieMode = StalkerCookieMode.NONE,- @ColumnInfo(name = "stalker_playback_backend_hint") val stalkerPlaybackBackendHint: StalkerPlaybackBackendHint = StalkerPlaybackBackendHint.AUTO,- @ColumnInfo(name = "stalker_last_playback_mode") val stalkerLastPlaybackMode: String? = null,- @ColumnInfo(name = "stalker_credentials_required") val stalkerCredentialsRequired: Boolean = false,- @ColumnInfo(name = "stalker_mac_required") val stalkerMacRequired: Boolean = true,- @ColumnInfo(name = "stalker_uses_temp_links") val stalkerUsesTemporaryLinks: Boolean = false,- @ColumnInfo(name = "stalker_module_restricted") val stalkerModuleRestricted: Boolean = false,- @ColumnInfo(name = "stalker_strict_fingerprint_required") val stalkerStrictFingerprintRequired: Boolean = false,- @ColumnInfo(name = "stalker_recipe_fallback_used") val stalkerRecipeFallbackUsed: Boolean = false,- @ColumnInfo(name = "stalker_recipe_rediscovery_attempts") val stalkerRecipeRediscoveryAttempts: Int = 0,@ColumnInfo(name = "is_active") val isActive: Boolean = true,+ val status: ProviderStatus = ProviderStatus.UNKNOWN,+ @ColumnInfo(name = "last_synced_at") val lastSyncedAt: Long = 0,+ @ColumnInfo(name = "created_at") val createdAt: Long = System.currentTimeMillis()+)++/** Authoritative typed configuration payload introduced in schema 73. */+@Entity(+ tableName = "provider_configs",+ foreignKeys = [ForeignKey(+ entity = ProviderEntity::class,+ parentColumns = ["id"],+ childColumns = ["provider_id"],+ onDelete = ForeignKey.CASCADE+ )],+ indices = [+ Index(value = ["provider_id"], unique = true),+ Index(value = ["identity_key"], unique = true),+ Index(value = ["type"])+ ]+)+data class ProviderConfigEntity(+ @PrimaryKey+ @ColumnInfo(name = "provider_id") val providerId: Long,+ val type: ProviderType,+ @ColumnInfo(name = "schema_version") val schemaVersion: Int,+ @ColumnInfo(name = "configuration_generation") val configurationGeneration: Long,+ @ColumnInfo(name = "identity_key") val identityKey: String,+ /** JSON with credential values encrypted before serialization. */+ @ColumnInfo(name = "encrypted_config_json") val encryptedConfigJson: String,+ @ColumnInfo(name = "guide_source_policy") val guideSourcePolicy: GuideSourcePolicy = GuideSourcePolicy.AUTO,+ @ColumnInfo(name = "channel_logo_source_policy") val channelLogoSourcePolicy: ChannelLogoSourcePolicy = ChannelLogoSourcePolicy.SUPPLIER_PREFERRED,+ @ColumnInfo(name = "updated_at") val updatedAt: Long+)++/** Account and catalog observations, intentionally separate from user configuration. */+@Entity(+ tableName = "provider_account_runtime",+ foreignKeys = [ForeignKey(+ entity = ProviderEntity::class,+ parentColumns = ["id"],+ childColumns = ["provider_id"],+ onDelete = ForeignKey.CASCADE+ )],+ indices = [Index(value = ["provider_id"], unique = true)]+)+data class ProviderAccountRuntimeEntity(+ @PrimaryKey+ @ColumnInfo(name = "provider_id") val providerId: Long,@ColumnInfo(name = "max_connections") val maxConnections: Int = 1,@ColumnInfo(name = "expiration_date") val expirationDate: Long? = null,@ColumnInfo(name = "api_version") val apiVersion: String? = null,@ColumnInfo(name = "allowed_output_formats_json") val allowedOutputFormatsJson: String = "[]",- @ColumnInfo(name = "epg_sync_mode") val epgSyncMode: ProviderEpgSyncMode = ProviderEpgSyncMode.UPFRONT,- @ColumnInfo(name = "stalker_catalog_mode") val stalkerCatalogMode: StalkerCatalogMode = StalkerCatalogMode.ON_DEMAND,- @ColumnInfo(name = "guide_source_policy") val guideSourcePolicy: GuideSourcePolicy = GuideSourcePolicy.AUTO,- @ColumnInfo(name = "channel_logo_source_policy") val channelLogoSourcePolicy: ChannelLogoSourcePolicy = ChannelLogoSourcePolicy.SUPPLIER_PREFERRED,- @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()+ @ColumnInfo(name = "observed_at") val observedAt: Long = 0L)/** Lifecycle of a provider configuration which has not yet replaced the committed row. */diff --git a/data/src/main/java/com/streamvault/data/local/entity/StalkerSyncEntities.kt b/data/src/main/java/com/streamvault/data/local/entity/StalkerSyncEntities.ktindex 6499aaaa..410d8b73 100644--- a/data/src/main/java/com/streamvault/data/local/entity/StalkerSyncEntities.kt+++ b/data/src/main/java/com/streamvault/data/local/entity/StalkerSyncEntities.kt@@ -65,7 +65,12 @@ data class StalkerPortalStateEntity(@ColumnInfo(name = "endpoint_health_json") val endpointHealthJson: String = "{}",@ColumnInfo(name = "endpoint_failed_until") val endpointFailedUntil: Long = 0L,@ColumnInfo(name = "validated_at") val validatedAt: Long = 0L,- @ColumnInfo(name = "schema_version") val schemaVersion: Int = 1+ @ColumnInfo(name = "schema_version") val schemaVersion: Int = 1,+ /** Learning is accepted only while this matches provider_configs.configuration_generation. */+ @ColumnInfo(name = "configuration_generation") val configurationGeneration: Long = 0L,+ @ColumnInfo(name = "learning_json") val learningJson: String = "{}",+ @ColumnInfo(name = "observation_source") val observationSource: String = "DISCOVERY",+ @ColumnInfo(name = "observed_at") val observedAt: Long = 0L)@Entity(diff --git a/data/src/main/java/com/streamvault/data/manager/BackupManagerImpl.kt b/data/src/main/java/com/streamvault/data/manager/BackupManagerImpl.ktindex bb58ddf8..9e8b5f5f 100644--- a/data/src/main/java/com/streamvault/data/manager/BackupManagerImpl.kt+++ b/data/src/main/java/com/streamvault/data/manager/BackupManagerImpl.kt@@ -1,5 +1,7 @@package com.streamvault.data.manager+import com.streamvault.domain.model.Provider as StableProvider+import android.content.Contextimport android.net.Uriimport com.google.gson.Gson@@ -18,9 +20,12 @@ import com.streamvault.data.local.dao.FavoriteDaoimport com.streamvault.data.local.dao.MovieDaoimport com.streamvault.data.local.dao.PlaybackHistoryDaoimport com.streamvault.data.local.dao.ProviderDao+import com.streamvault.data.local.dao.ProviderSnapshotDaoimport com.streamvault.data.local.dao.RecordingScheduleDaoimport com.streamvault.data.local.dao.VirtualGroupDaoimport com.streamvault.data.local.entity.ProviderEntity+import com.streamvault.data.local.entity.ProviderAccountRuntimeEntity+import com.streamvault.data.local.entity.ProviderConfigEntityimport com.streamvault.data.local.entity.BackupRestoreCheckpointEntityimport com.streamvault.data.local.entity.RecordingScheduleEntityimport com.streamvault.data.mapper.toDomain@@ -28,6 +33,12 @@ import com.streamvault.data.mapper.toEntityimport com.streamvault.data.preferences.ParentalPinBackupDataimport com.streamvault.data.preferences.PreferencesRepositoryimport com.streamvault.data.security.CredentialCrypto+import com.streamvault.data.provider.toTypedConfiguration+import com.streamvault.data.provider.toLegacyProvider+import com.streamvault.data.provider.ProviderConfigurationCodec+import com.streamvault.data.provider.guidePolicy+import com.streamvault.data.provider.logoPolicy+import com.streamvault.data.provider.toAccountRuntimeimport com.streamvault.data.remote.stalker.StalkerCompatibilityRegistryimport com.streamvault.domain.manager.BackupDataimport com.streamvault.domain.manager.BackupConflictStrategy@@ -41,6 +52,7 @@ import com.streamvault.domain.manager.RecordingScheduleImportOutcomeimport com.streamvault.domain.manager.RecordingScheduleImportSummaryimport com.streamvault.domain.manager.ProtectedCategoryBackupimport com.streamvault.domain.manager.BackupProviderReference+import com.streamvault.domain.manager.ProviderBackupSnapshotimport com.streamvault.domain.manager.PortableCategoryReferenceimport com.streamvault.domain.manager.PortableChannelReferenceimport com.streamvault.domain.manager.PortableProviderPreferencesBackup@@ -56,6 +68,9 @@ import com.streamvault.domain.model.RecordingStatusimport com.streamvault.domain.model.Resultimport com.streamvault.domain.model.ProviderStatusimport com.streamvault.domain.model.ProviderType+import com.streamvault.domain.model.ProviderAccountRuntime+import com.streamvault.domain.model.LegacyProvider as Provider+import com.streamvault.domain.repository.ProviderSnapshotRepositoryimport com.streamvault.domain.model.StalkerBootstrapRecipeimport com.streamvault.domain.model.StalkerCatalogModeimport com.streamvault.domain.model.StalkerProfileVerification@@ -101,6 +116,9 @@ class BackupManagerImpl @Inject constructor(private val recordingManager: RecordingManager,private val transactionRunner: DatabaseTransactionRunner,private val gson: Gson,+ private val providerSnapshotRepository: ProviderSnapshotRepository? = null,+ private val providerSnapshotDao: ProviderSnapshotDao? = null,+ private val providerConfigurationCodec: ProviderConfigurationCodec? = null,private val backupRestoreCheckpointDao: BackupRestoreCheckpointDao? = null,private val channelDao: ChannelDao,private val epgSourceDao: EpgSourceDao? = null@@ -168,10 +186,9 @@ class BackupManagerImpl @Inject constructor(}}- val providers = providerEntities.map { entity ->- entity.toDomain().copy(+ val providers = providerEntities.mapNotNull { entity ->+ providerSnapshotRepository?.getSnapshot(entity.id)?.toLegacyProvider()?.copy(password = "", // Strip credentials from backup export- username = entity.toDomain().username, // Keep username for provider identificationstalkerLastBootstrapRecipe = StalkerBootstrapRecipe.GENERIC_SAFE,stalkerLastPlaybackMode = null,// Transport consent is device-local. A restore must verify or ask again.@@ -181,6 +198,34 @@ class BackupManagerImpl @Inject constructor(stalkerTransportConsentAt = 0L)}+ if (providers.size != providerEntities.size) {+ return@withContext com.streamvault.domain.model.Result.error(+ "Cannot export backup because one or more providers have no typed configuration snapshot"+ )+ }+ val providerSnapshots = providers.map { provider ->+ val configuration = when (val config = provider.toTypedConfiguration()) {+ is com.streamvault.domain.model.XtreamConfig -> config.copy(password = "")+ is com.streamvault.domain.model.M3uConfig -> config+ is com.streamvault.domain.model.StalkerConfig -> config.copy(+ password = "",+ transportGrant = null+ )+ is com.streamvault.domain.model.JellyfinConfig -> config.copy(credential = "")+ }+ configuration.toBackupSnapshot(+ StableProvider(+ id = provider.id,+ name = provider.name,+ type = provider.type,+ isActive = provider.isActive,+ status = provider.status,+ lastSyncedAt = provider.lastSyncedAt,+ createdAt = provider.createdAt+ ),+ accountRuntime = provider.toAccountRuntime()+ )+ }val providerIds = providerEntities.map { it.id }val providersById = providers.associateBy { it.id }@@ -242,14 +287,15 @@ class BackupManagerImpl @Inject constructor(val backupData = BackupData(version = CURRENT_BACKUP_VERSION,preferences = prefs,- providers = providers,+ providers = null,+ providerSnapshots = providerSnapshots,favorites = allFavorites,virtualGroups = allGroups,playbackHistory = playbackHistory,multiViewPresets = multiViewPresets,protectedCategories = protectedCategories,scheduledRecordings = scheduledRecordings,- portableProviderPreferences = buildPortableProviderPreferences(providerEntities),+ portableProviderPreferences = buildPortableProviderPreferences(providers),epgSources = epgSourceDao?.getAllSync()?.map { it.toDomain() })@@ -271,19 +317,20 @@ class BackupManagerImpl @Inject constructor(override suspend fun inspectBackup(uriString: String): Result<BackupPreview> = withContext(Dispatchers.IO) {try {- val backupData = readBackupData(uriString)+ val rawBackupData = readBackupData(uriString)?: return@withContext Result.error("Failed to open input stream")- if (backupData.version > CURRENT_BACKUP_VERSION) {+ if (rawBackupData.version > CURRENT_BACKUP_VERSION) {return@withContext Result.error("Unsupported backup version")}- if (backupData.isStructurallyEmpty()) {+ if (rawBackupData.isStructurallyEmpty()) {return@withContext Result.error("Backup file does not contain any importable data")}- if (!verifyChecksum(backupData)) {+ if (!verifyChecksum(rawBackupData)) {return@withContext Result.error("Backup file is corrupted (checksum mismatch)")}+ val backupData = rawBackupData.withLegacyProviderProjection()- val existingProviders = providerDao.getAll().first()+ val existingProviders = loadStoredProviders()val existingProviderIds = existingProviders.map { it.id }val existingGroups = buildList {existingProviderIds.forEach { providerId ->@@ -364,20 +411,21 @@ class BackupManagerImpl @Inject constructor(plan: BackupImportPlan): com.streamvault.domain.model.Result<BackupImportResult> = withContext(Dispatchers.IO) {try {- val backupData = readBackupData(uriString)+ val rawBackupData = readBackupData(uriString)?: return@withContext com.streamvault.domain.model.Result.error("Failed to open input stream")- if (backupData.version > CURRENT_BACKUP_VERSION) {+ if (rawBackupData.version > CURRENT_BACKUP_VERSION) {return@withContext com.streamvault.domain.model.Result.error("Unsupported backup version")}- if (backupData.isStructurallyEmpty()) {+ if (rawBackupData.isStructurallyEmpty()) {return@withContext com.streamvault.domain.model.Result.error("Backup file does not contain any importable data")}- if (!verifyChecksum(backupData)) {+ if (!verifyChecksum(rawBackupData)) {return@withContext com.streamvault.domain.model.Result.error("Backup file is corrupted (checksum mismatch)")}+ val backupData = rawBackupData.withLegacyProviderProjection()- val restoreKey = buildRestoreKey(backupData, plan)+ val restoreKey = buildRestoreKey(rawBackupData, plan)var checkpoint = loadOrCreateCheckpoint(restoreKey)if (checkpoint.state == RESTORE_STATE_COMPLETE) {return@withContext com.streamvault.domain.model.Result.success(@@ -385,7 +433,7 @@ class BackupManagerImpl @Inject constructor()}- var storedProviders = providerDao.getAllSync()+ var storedProviders = loadStoredProviders()val importedSections = mutableListOf<String>()val skippedSections = mutableListOf<String>()val failedSections = mutableListOf<String>()@@ -721,6 +769,7 @@ class BackupManagerImpl @Inject constructor(}writeNamedJsonField(jsonWriter, "preferences", backupData.preferences, MAP_STRING_STRING_TYPE)writeNamedJsonField(jsonWriter, "providers", backupData.providers, PROVIDER_LIST_TYPE)+ writeNamedJsonField(jsonWriter, "providerSnapshots", backupData.providerSnapshots, PROVIDER_SNAPSHOT_LIST_TYPE)writeNamedJsonField(jsonWriter, "favorites", backupData.favorites, FAVORITE_LIST_TYPE)writeNamedJsonField(jsonWriter, "virtualGroups", backupData.virtualGroups, VIRTUAL_GROUP_LIST_TYPE)writeNamedJsonField(jsonWriter, "playbackHistory", backupData.playbackHistory, PLAYBACK_HISTORY_LIST_TYPE)@@ -806,7 +855,8 @@ class BackupManagerImpl @Inject constructor(var version = 0var checksum: String? = nullvar preferences: Map<String, String>? = null- var providers: List<com.streamvault.domain.model.Provider>? = null+ var providers: List<com.streamvault.domain.model.LegacyProvider>? = null+ var providerSnapshots: List<ProviderBackupSnapshot>? = nullvar favorites: List<com.streamvault.domain.model.Favorite>? = nullvar virtualGroups: List<com.streamvault.domain.model.VirtualGroup>? = nullvar playbackHistory: List<com.streamvault.domain.model.PlaybackHistory>? = null@@ -847,6 +897,8 @@ class BackupManagerImpl @Inject constructor("checksum" -> checksum = reader.nextString()"preferences" -> preferences = readStringMap(reader, MAX_PREFERENCES, "preferences")"providers" -> providers = readLimitedArray(reader, PROVIDER_TYPE, MAX_PROVIDERS, "providers")+ "providerSnapshots" -> providerSnapshots =+ readLimitedArray(reader, PROVIDER_SNAPSHOT_TYPE, MAX_PROVIDERS, "provider snapshots")"favorites" -> favorites = readLimitedArray(reader, FAVORITE_TYPE, MAX_SECTION_ITEMS, "favorites")"virtualGroups" -> virtualGroups =readLimitedArray(reader, VIRTUAL_GROUP_TYPE, MAX_SECTION_ITEMS, "groups")@@ -883,6 +935,7 @@ class BackupManagerImpl @Inject constructor(checksum = checksum,preferences = preferences,providers = providers,+ providerSnapshots = providerSnapshots,favorites = favorites,virtualGroups = virtualGroups,playbackHistory = playbackHistory,@@ -1087,6 +1140,8 @@ class BackupManagerImpl @Inject constructor(private fun validateBackupDataLimits(data: BackupData) {require(data.preferences.orEmpty().size <= MAX_PREFERENCES) { "Backup has too many preferences" }require(data.providers.orEmpty().size <= MAX_PROVIDERS) { "Backup has too many providers" }+ require(data.providerSnapshots.orEmpty().size <= MAX_PROVIDERS) { "Backup has too many provider snapshots" }+ data.providerSnapshots.orEmpty().forEach { it.configuration() }require(data.favorites.orEmpty().size <= MAX_SECTION_ITEMS) { "Backup has too many favorites" }require(data.virtualGroups.orEmpty().size <= MAX_SECTION_ITEMS) { "Backup has too many groups" }require(data.playbackHistory.orEmpty().size <= MAX_SECTION_ITEMS) { "Backup has too much playback history" }@@ -1140,7 +1195,7 @@ class BackupManagerImpl @Inject constructor(?: Uri.parse(this).path?.let(::File)internal suspend fun buildPortableProviderPreferences(- providers: List<ProviderEntity>+ providers: List<Provider>): PortableProviderPreferencesBackup {val channels = channelDaoval referencesById = providers.associate { it.id to it.toBackupProviderReference() }@@ -1242,9 +1297,30 @@ class BackupManagerImpl @Inject constructor()}+ /**+ * v11 stores typed snapshots as the authoritative provider section. Keep the legacy+ * projection out of parsing/checksum verification, then materialize it only for the older+ * restore code that still expects the compatibility envelope.+ */+ private fun BackupData.withLegacyProviderProjection(): BackupData {+ val snapshots = providerSnapshots ?: return this+ // Treat an explicitly empty legacy projection like an omitted one. This keeps v11's+ // typed section authoritative while still honoring non-empty v0-10 provider payloads.+ if (!providers.isNullOrEmpty()) return this+ return copy(+ providers = snapshots.map { snapshot ->+ snapshot.configuration().toLegacyProvider(+ snapshot.provider,+ snapshot.accountRuntime ?: ProviderAccountRuntime()+ )+ }+ )+ }+private fun BackupData.isStructurallyEmpty(): Boolean =preferences.isNullOrEmpty() &&providers.isNullOrEmpty() &&+ providerSnapshots.isNullOrEmpty() &&favorites.isNullOrEmpty() &&virtualGroups.isNullOrEmpty() &&playbackHistory.isNullOrEmpty() &&@@ -1334,7 +1410,7 @@ class BackupManagerImpl @Inject constructor(private suspend fun restorePortableProviderPreferences(portable: PortableProviderPreferencesBackup,- storedProviders: List<ProviderEntity>+ storedProviders: List<Provider>): List<String> {val unresolved = portable.unresolvedReferences.toMutableList()val channels = channelDao@@ -1562,7 +1638,7 @@ class BackupManagerImpl @Inject constructor(private suspend fun restoreRoomBackedSections(backupData: BackupData,plan: BackupImportPlan,- initialStoredProviders: List<ProviderEntity>,+ initialStoredProviders: List<Provider>,onRoomCommitted: suspend () -> Unit = {}): RoomRestoreResult {if (!plan.importProviders && !plan.importSavedLibrary && !plan.importPlaybackHistory) {@@ -1593,7 +1669,7 @@ class BackupManagerImpl @Inject constructor(if (existing != null && plan.conflictStrategy == BackupConflictStrategy.KEEP_EXISTING) {return@forEach}- val entity = provider.copy(+ val restoredProvider = provider.copy(id = existing?.id ?: 0L,stalkerCatalogMode = if (backupData.version < 9) {StalkerCatalogMode.ON_DEMAND@@ -1640,10 +1716,13 @@ class BackupManagerImpl @Inject constructor(} else {provider.status}- ).toSecureEntityForBackup(credentialCrypto)- providerDao.insert(entity)+ )+ val restoredId = providerDao.insert(+ restoredProvider.toSecureEntityForBackup(credentialCrypto)+ )+ persistRestoredProvider(restoredId, restoredProvider.copy(id = restoredId))}- storedProviders = providerDao.getAllSync()+ storedProviders = loadStoredProviders()backupData.preferences?.get("lastActiveProviderId")?.toLongOrNull()@@ -1719,7 +1798,7 @@ class BackupManagerImpl @Inject constructor(private suspend fun restoreSavedLibrary(backupData: BackupData,- storedProviders: List<ProviderEntity>,+ storedProviders: List<Provider>,conflictStrategy: BackupConflictStrategy) {val providerIdMap = resolveProviderIdMap(storedProviders, backupData.providers.orEmpty())@@ -1805,8 +1884,8 @@ class BackupManagerImpl @Inject constructor(}private fun resolveProviderIdMap(- storedProviders: List<ProviderEntity>,- backupProviders: List<com.streamvault.domain.model.Provider>+ storedProviders: List<Provider>,+ backupProviders: List<com.streamvault.domain.model.LegacyProvider>): Map<Long, Long> = backupProviders.mapNotNull { provider ->storedProviders.findMatchingProvider(serverUrl = provider.serverUrl,@@ -1819,8 +1898,8 @@ class BackupManagerImpl @Inject constructor(private suspend fun restorePlaybackHistory(history: List<com.streamvault.domain.model.PlaybackHistory>,- storedProviders: List<ProviderEntity>,- backupProviders: List<com.streamvault.domain.model.Provider>,+ storedProviders: List<Provider>,+ backupProviders: List<com.streamvault.domain.model.LegacyProvider>,conflictStrategy: BackupConflictStrategy) {val providerIdMap = resolveProviderIdMap(storedProviders, backupProviders)@@ -1861,11 +1940,51 @@ class BackupManagerImpl @Inject constructor(}private data class RoomRestoreResult(- val storedProviders: List<ProviderEntity>,+ val storedProviders: List<Provider>,val importedSections: List<String>,val skippedSections: List<String>)+ private suspend fun loadStoredProviders(): List<Provider> = providerDao.getAllSync().mapNotNull { entity ->+ providerSnapshotRepository?.getSnapshot(entity.id)?.toLegacyProvider()+ }++ /** Backup restore deliberately writes configuration/runtime only; learned Stalker state stays absent. */+ private suspend fun persistRestoredProvider(providerId: Long, provider: Provider) {+ val configuration = provider.toTypedConfiguration()+ val snapshotDao = requireNotNull(providerSnapshotDao) { "Typed provider snapshot DAO is required for restore" }+ val configurationCodec = requireNotNull(providerConfigurationCodec) { "Typed provider configuration codec is required for restore" }+ val nextGeneration = (snapshotDao.getConfig(providerId)?.configurationGeneration ?: 0L) + 1L+ check(+ snapshotDao.commitConfiguration(+ ProviderConfigEntity(+ providerId = providerId,+ type = configuration.type,+ schemaVersion = configuration.schemaVersion,+ configurationGeneration = nextGeneration,+ identityKey = configurationCodec.identityKey(configuration),+ encryptedConfigJson = configurationCodec.encode(configuration),+ guideSourcePolicy = configuration.guidePolicy(),+ channelLogoSourcePolicy = configuration.logoPolicy(),+ updatedAt = System.currentTimeMillis()+ )+ )+ ) { "Restored provider configuration was superseded" }+ val runtime = provider.toAccountRuntime()+ snapshotDao.upsertRuntime(+ ProviderAccountRuntimeEntity(+ providerId = providerId,+ maxConnections = runtime.maxConnections,+ expirationDate = runtime.expirationDate,+ apiVersion = runtime.apiVersion,+ allowedOutputFormatsJson = gson.toJson(runtime.allowedOutputFormats),+ catalogLayout = runtime.catalogLayout,+ catalogLayoutDetectionVersion = runtime.catalogLayoutDetectionVersion,+ observedAt = runtime.observedAt+ )+ )+ }+private data class RecordingChannelConflictKey(val providerId: Long,val startMs: Long,@@ -1880,7 +1999,7 @@ private data class RecordingUrlConflictKey(internal fun countScheduledRecordingConflicts(incoming: List<ScheduledRecordingBackup>,- providersByIdentity: Map<Triple<String, String, String>, ProviderEntity>,+ providersByIdentity: Map<Triple<String, String, String>, Provider>,existing: List<com.streamvault.domain.model.RecordingItem>): Int {val channelKeys = existing.mapTo(hashSetOf()) {@@ -2015,22 +2134,22 @@ internal class BackupAdmissionException(message: String) : IOException(message)-private fun ProviderEntity.backupIdentity(): Triple<String, String, String> =+private fun Provider.backupIdentity(): Triple<String, String, String> =Triple(serverUrl, username, stalkerMacAddress)-private fun ProviderEntity.toBackupProviderReference() = BackupProviderReference(+private fun Provider.toBackupProviderReference() = BackupProviderReference(serverUrl = serverUrl,username = username,stalkerMacAddress = stalkerMacAddress.takeIf { it.isNotBlank() })-private fun Iterable<ProviderEntity>.findUnambiguousPortableProvider(+private fun Iterable<Provider>.findUnambiguousPortableProvider(reference: BackupProviderReference-): ProviderEntity? {+): Provider? {val normalizedMac = reference.stalkerMacAddress.normalizedIdentity()return filter { provider ->provider.serverUrl == reference.serverUrl &&- provider.username == reference.username &&+ (provider.type == ProviderType.M3U || provider.username == reference.username) &&provider.stalkerMacAddress.normalizedIdentity() == normalizedMac}.singleOrNull()}@@ -2079,9 +2198,6 @@ private fun PortableChannelReference.unresolvedLabel(kind: String): String =private fun String?.normalizedIdentity(): String = orEmpty().trim().lowercase()-private fun com.streamvault.domain.model.Provider.backupIdentity(): Triple<String, String, String> =- Triple(serverUrl, username, stalkerMacAddress)-private fun ProtectedCategoryBackup.backupIdentity(): Triple<String, String, String> =Triple(providerServerUrl, providerUsername, providerStalkerMacAddress.orEmpty())@@ -2089,7 +2205,7 @@ private fun ScheduledRecordingBackup.backupIdentity(): Triple<String, String, StTriple(providerServerUrl, providerUsername, providerStalkerMacAddress.orEmpty())internal fun com.streamvault.domain.model.RecordingItem.toScheduledRecordingBackup(- provider: com.streamvault.domain.model.Provider,+ provider: com.streamvault.domain.model.LegacyProvider,schedule: RecordingScheduleEntity?): ScheduledRecordingBackup {val requestedStart = schedule?.requestedStartMs ?: scheduledStartMs@@ -2155,7 +2271,7 @@ internal fun List<ScheduledRecordingBackup>.normalizedRecurringBackups(): List<Sinternal suspend fun importScheduledRecordingBackups(recordings: List<ScheduledRecordingBackup>,- storedProviders: List<ProviderEntity>,+ storedProviders: List<Provider>,existingSchedules: MutableList<com.streamvault.domain.model.RecordingItem>,conflictStrategy: BackupConflictStrategy,recordingManager: RecordingManager,@@ -2263,18 +2379,18 @@ private fun ScheduledRecordingBackup.toImportOutcome(private fun ScheduledRecordingBackup.hasStableRecurringIdentity(): Boolean =recurrence != RecordingRecurrence.NONE && !recurringRuleId.isNullOrBlank()-private fun com.streamvault.domain.model.Provider.toSecureEntityForBackup(+private fun com.streamvault.domain.model.LegacyProvider.toSecureEntityForBackup(credentialCrypto: CredentialCrypto) = copy(password = credentialCrypto.encryptIfNeeded(password)).toEntity()-private fun Iterable<ProviderEntity>.findMatchingProvider(+private fun Iterable<Provider>.findMatchingProvider(serverUrl: String,username: String,stalkerMacAddress: String?-): ProviderEntity? {+): Provider? {val candidates = filter {it.serverUrl == serverUrl &&- it.username == username+ (it.type == ProviderType.M3U || it.username == username)}val normalizedMacAddress = stalkerMacAddress?.trim()@@ -2290,6 +2406,17 @@ private fun Iterable<ProviderEntity>.findMatchingProvider(}private const val SHA256_PREFIX = "sha256:"++ private fun com.streamvault.domain.model.ProviderConfiguration.toBackupSnapshot(+ provider: StableProvider,+ accountRuntime: ProviderAccountRuntime+): ProviderBackupSnapshot = when (this) {+ is com.streamvault.domain.model.XtreamConfig -> ProviderBackupSnapshot(provider, accountRuntime, xtreamConfig = this)+ is com.streamvault.domain.model.M3uConfig -> ProviderBackupSnapshot(provider, accountRuntime, m3uConfig = this)+ is com.streamvault.domain.model.StalkerConfig -> ProviderBackupSnapshot(provider, accountRuntime, stalkerConfig = this)+ is com.streamvault.domain.model.JellyfinConfig -> ProviderBackupSnapshot(provider, accountRuntime, jellyfinConfig = this)+}+private const val RESTORE_STATE_RUNNING = "RUNNING"private const val RESTORE_STATE_COMPLETE = "COMPLETE"private const val RESTORE_STATE_PARTIAL = "PARTIAL"@@ -2297,11 +2424,12 @@ private const val RESTORE_STATE_FAILED_BEFORE_COMMIT = "FAILED_BEFORE_COMMIT"private const val RESTORE_SNAPSHOT_PRESET_1 = "__restore_snapshot_preset_1"private const val RESTORE_SNAPSHOT_PRESET_2 = "__restore_snapshot_preset_2"private const val RESTORE_SNAPSHOT_PRESET_3 = "__restore_snapshot_preset_3"-private const val CURRENT_BACKUP_VERSION = 10+private const val CURRENT_BACKUP_VERSION = 11private const val FILE_URI_SCHEME = "file"private val PORTABLE_VIRTUAL_CATEGORY_IDS = setOf(-998L, -999L)private val MAP_STRING_STRING_TYPE: Type = object : TypeToken<Map<String, String>>() {}.type-private val PROVIDER_TYPE: Type = com.streamvault.domain.model.Provider::class.java+private val PROVIDER_TYPE: Type = com.streamvault.domain.model.LegacyProvider::class.java+private val PROVIDER_SNAPSHOT_TYPE: Type = ProviderBackupSnapshot::class.javaprivate val FAVORITE_TYPE: Type = com.streamvault.domain.model.Favorite::class.javaprivate val VIRTUAL_GROUP_TYPE: Type = com.streamvault.domain.model.VirtualGroup::class.javaprivate val PLAYBACK_HISTORY_TYPE: Type = com.streamvault.domain.model.PlaybackHistory::class.java@@ -2313,7 +2441,8 @@ private val PORTABLE_GROUP_REFERENCE_TYPE: Type = PortableVirtualGroupReference:private val PORTABLE_CHANNEL_REFERENCE_TYPE: Type = PortableChannelReference::class.javaprivate val LONG_TYPE: Type = java.lang.Long::class.javaprivate val STRING_TYPE: Type = String::class.java-private val PROVIDER_LIST_TYPE: Type = object : TypeToken<List<com.streamvault.domain.model.Provider>>() {}.type+private val PROVIDER_LIST_TYPE: Type = object : TypeToken<List<com.streamvault.domain.model.LegacyProvider>>() {}.type+private val PROVIDER_SNAPSHOT_LIST_TYPE: Type = object : TypeToken<List<ProviderBackupSnapshot>>() {}.typeprivate val EPG_SOURCE_TYPE: Type = com.streamvault.domain.model.EpgSource::class.javaprivate val EPG_SOURCE_LIST_TYPE: Type =object : TypeToken<List<com.streamvault.domain.model.EpgSource>>() {}.typediff --git a/data/src/main/java/com/streamvault/data/manager/RecordingManagerImpl.kt b/data/src/main/java/com/streamvault/data/manager/RecordingManagerImpl.ktindex 57310880..e9b71e6f 100644--- a/data/src/main/java/com/streamvault/data/manager/RecordingManagerImpl.kt+++ b/data/src/main/java/com/streamvault/data/manager/RecordingManagerImpl.kt@@ -9,6 +9,7 @@ import com.google.gson.Gsonimport com.google.gson.reflect.TypeTokenimport com.streamvault.data.local.DatabaseTransactionRunnerimport com.streamvault.data.local.dao.ProviderDao+import com.streamvault.data.local.dao.ProviderSnapshotDaoimport com.streamvault.data.local.dao.RecordingRunDaoimport com.streamvault.data.local.dao.RecordingScheduleDaoimport com.streamvault.data.local.dao.RecordingStorageDao@@ -121,7 +122,8 @@ class RecordingManagerImpl @Inject constructor(private val hlsLiveCaptureEngine: HlsLiveCaptureEngine,private val alarmScheduler: RecordingAlarmScheduler,private val preferencesRepository: PreferencesRepository,- private val recordingServiceLauncher: RecordingServiceLauncher+ private val recordingServiceLauncher: RecordingServiceLauncher,+ private val providerSnapshotDao: ProviderSnapshotDao? = null) : RecordingManager {private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)@@ -1198,7 +1200,7 @@ class RecordingManagerImpl @Inject constructor(}val provider = providerDao.getById(providerId)?: return "Recording provider no longer exists."- val providerMaxConnections = provider.maxConnections+ val providerMaxConnections = providerSnapshotDao?.getRuntime(providerId)?.maxConnections ?: 1if (overlapping.count { it.providerId == providerId } >= providerMaxConnections) {return "Recording exceeds the provider connection limit for this account."}diff --git a/data/src/main/java/com/streamvault/data/mapper/EntityMappers.kt b/data/src/main/java/com/streamvault/data/mapper/EntityMappers.ktindex 40020389..8d4ac0e2 100644--- a/data/src/main/java/com/streamvault/data/mapper/EntityMappers.kt+++ b/data/src/main/java/com/streamvault/data/mapper/EntityMappers.kt@@ -8,6 +8,7 @@ import com.streamvault.data.remote.stalker.StalkerUrlFactoryimport com.streamvault.data.remote.xtream.XtreamStreamKindimport com.streamvault.data.remote.xtream.XtreamUrlFactoryimport com.streamvault.domain.model.*+import com.streamvault.domain.model.LegacyProvider as Providerprivate val qualityOptionsGson = Gson()private val channelQualityOptionsType = object : TypeToken<List<ChannelQualityOption>>() {}.type@@ -19,65 +20,8 @@ fun ProviderEntity.toDomain() = Provider(id = id,name = name,type = type,- serverUrl = serverUrl,- username = username,- password = password,- m3uUrl = m3uUrl,- epgUrl = epgUrl,- httpUserAgent = httpUserAgent,- httpHeaders = httpHeaders,- stalkerMacAddress = stalkerMacAddress,- stalkerDeviceProfile = stalkerDeviceProfile,- stalkerDeviceTimezone = stalkerDeviceTimezone,- stalkerDeviceLocale = stalkerDeviceLocale,- stalkerSerialNumber = stalkerSerialNumber,- stalkerDeviceId = stalkerDeviceId,- stalkerDeviceId2 = stalkerDeviceId2,- stalkerSignature = stalkerSignature,- stalkerAdvancedOptionsJson = stalkerAdvancedOptionsJson,- stalkerAuthMode = stalkerAuthMode,- stalkerPortalProfile = stalkerPortalProfile,- stalkerPortalFingerprint = stalkerPortalFingerprint,- stalkerMagPreset = stalkerMagPreset,- stalkerProtocolPreference = stalkerProtocolPreference,- stalkerTransportMode = stalkerTransportMode,- stalkerTransportOrigin = stalkerTransportOrigin,- stalkerTlsSpkiSha256 = stalkerTlsSpkiSha256,- stalkerTransportConsentAt = stalkerTransportConsentAt,- stalkerConfigurationGeneration = stalkerConfigurationGeneration,- stalkerDiscoverySummary = stalkerDiscoverySummary,- stalkerCapabilitiesJson = stalkerCapabilitiesJson,- stalkerRequestedProfileId = stalkerRequestedProfileId,- stalkerLearnedProfileId = stalkerLearnedProfileId,- stalkerProfileRevision = stalkerProfileRevision,- stalkerProfileVerification = stalkerProfileVerification,- stalkerProtocolFamily = stalkerProtocolFamily,- stalkerLastBootstrapRecipe = stalkerLastBootstrapRecipe,- stalkerEndpointPreference = stalkerEndpointPreference,- stalkerCookieMode = stalkerCookieMode,- stalkerPlaybackBackendHint = stalkerPlaybackBackendHint,- stalkerLastPlaybackMode = stalkerLastPlaybackMode,- stalkerCredentialsRequired = stalkerCredentialsRequired,- stalkerMacRequired = stalkerMacRequired,- stalkerUsesTemporaryLinks = stalkerUsesTemporaryLinks,- stalkerModuleRestricted = stalkerModuleRestricted,- stalkerStrictFingerprintRequired = stalkerStrictFingerprintRequired,- stalkerRecipeFallbackUsed = stalkerRecipeFallbackUsed,- stalkerRecipeRediscoveryAttempts = stalkerRecipeRediscoveryAttempts,+ serverUrl = "",isActive = isActive,- maxConnections = maxConnections,- expirationDate = expirationDate,- apiVersion = apiVersion,- allowedOutputFormats = decodeAllowedOutputFormats(allowedOutputFormatsJson),- epgSyncMode = epgSyncMode,- stalkerCatalogMode = stalkerCatalogMode,- guideSourcePolicy = guideSourcePolicy,- channelLogoSourcePolicy = channelLogoSourcePolicy,- xtreamFastSyncEnabled = xtreamFastSyncEnabled,- xtreamLiveSyncMode = xtreamLiveSyncMode,- m3uVodClassificationEnabled = m3uVodClassificationEnabled,- catalogLayout = catalogLayout,- catalogLayoutDetectionVersion = catalogLayoutDetectionVersion,status = status,lastSyncedAt = lastSyncedAt,createdAt = createdAt@@ -87,65 +31,7 @@ fun Provider.toEntity() = ProviderEntity(id = id,name = name,type = type,- serverUrl = serverUrl,- username = username,- password = password,- m3uUrl = m3uUrl,- epgUrl = epgUrl,- httpUserAgent = httpUserAgent,- httpHeaders = httpHeaders,- stalkerMacAddress = stalkerMacAddress,- stalkerDeviceProfile = stalkerDeviceProfile,- stalkerDeviceTimezone = stalkerDeviceTimezone,- stalkerDeviceLocale = stalkerDeviceLocale,- stalkerSerialNumber = stalkerSerialNumber,- stalkerDeviceId = stalkerDeviceId,- stalkerDeviceId2 = stalkerDeviceId2,- stalkerSignature = stalkerSignature,- stalkerAdvancedOptionsJson = stalkerAdvancedOptionsJson,- stalkerAuthMode = stalkerAuthMode,- stalkerPortalProfile = stalkerPortalProfile,- stalkerPortalFingerprint = stalkerPortalFingerprint,- stalkerMagPreset = stalkerMagPreset,- stalkerProtocolPreference = stalkerProtocolPreference,- stalkerTransportMode = stalkerTransportMode,- stalkerTransportOrigin = stalkerTransportOrigin,- stalkerTlsSpkiSha256 = stalkerTlsSpkiSha256,- stalkerTransportConsentAt = stalkerTransportConsentAt,- stalkerConfigurationGeneration = stalkerConfigurationGeneration,- stalkerDiscoverySummary = stalkerDiscoverySummary,- stalkerCapabilitiesJson = stalkerCapabilitiesJson,- stalkerRequestedProfileId = stalkerRequestedProfileId,- stalkerLearnedProfileId = stalkerLearnedProfileId,- stalkerProfileRevision = stalkerProfileRevision,- stalkerProfileVerification = stalkerProfileVerification,- stalkerProtocolFamily = stalkerProtocolFamily,- stalkerLastBootstrapRecipe = stalkerLastBootstrapRecipe,- stalkerEndpointPreference = stalkerEndpointPreference,- stalkerCookieMode = stalkerCookieMode,- stalkerPlaybackBackendHint = stalkerPlaybackBackendHint,- stalkerLastPlaybackMode = stalkerLastPlaybackMode,- stalkerCredentialsRequired = stalkerCredentialsRequired,- stalkerMacRequired = stalkerMacRequired,- stalkerUsesTemporaryLinks = stalkerUsesTemporaryLinks,- stalkerModuleRestricted = stalkerModuleRestricted,- stalkerStrictFingerprintRequired = stalkerStrictFingerprintRequired,- stalkerRecipeFallbackUsed = stalkerRecipeFallbackUsed,- stalkerRecipeRediscoveryAttempts = stalkerRecipeRediscoveryAttempts,isActive = isActive,- maxConnections = maxConnections,- expirationDate = expirationDate,- apiVersion = apiVersion,- allowedOutputFormatsJson = encodeAllowedOutputFormats(allowedOutputFormats),- epgSyncMode = epgSyncMode,- stalkerCatalogMode = stalkerCatalogMode,- guideSourcePolicy = guideSourcePolicy,- channelLogoSourcePolicy = channelLogoSourcePolicy,- xtreamFastSyncEnabled = xtreamFastSyncEnabled,- xtreamLiveSyncMode = xtreamLiveSyncMode,- m3uVodClassificationEnabled = m3uVodClassificationEnabled,- catalogLayout = catalogLayout,- catalogLayoutDetectionVersion = catalogLayoutDetectionVersion,status = status,lastSyncedAt = lastSyncedAt,createdAt = createdAtdiff --git a/data/src/main/java/com/streamvault/data/provider/DefaultProviderCapabilityRegistry.kt b/data/src/main/java/com/streamvault/data/provider/DefaultProviderCapabilityRegistry.ktnew file mode 100644index 00000000..b3e3a2d5--- /dev/null+++ b/data/src/main/java/com/streamvault/data/provider/DefaultProviderCapabilityRegistry.kt@@ -0,0 +1,41 @@+package com.streamvault.data.provider++import com.streamvault.domain.model.ProviderSnapshot+import com.streamvault.domain.model.ProviderType+import com.streamvault.domain.provider.CapabilityResolution+import com.streamvault.domain.provider.ProviderCapabilityFactory+import com.streamvault.domain.provider.ProviderCapabilityRegistry+import com.streamvault.domain.provider.ProviderCapabilitySet++/** Immutable registry: invalid factory topology fails at composition time, not mid-sync. */+class DefaultProviderCapabilityRegistry(+ factories: Collection<ProviderCapabilityFactory>+) : ProviderCapabilityRegistry {+ private val factoriesByType: Map<ProviderType, ProviderCapabilityFactory>++ init {+ val duplicates = factories.groupingBy { it.providerType }.eachCount().filterValues { it != 1 }.keys+ require(duplicates.isEmpty()) { "Duplicate provider capability factories: $duplicates" }+ val registered = factories.mapTo(mutableSetOf()) { it.providerType }+ val missing = ProviderType.entries.toSet() - registered+ require(missing.isEmpty()) { "Missing provider capability factories: $missing" }+ factoriesByType = factories.associateBy { it.providerType }+ }++ override fun resolve(snapshot: ProviderSnapshot): CapabilityResolution<ProviderCapabilitySet> {+ if (snapshot.provider.type != snapshot.configuration.type) {+ return CapabilityResolution.ConfigurationError(+ "Provider type ${snapshot.provider.type} does not match ${snapshot.configuration.type} configuration"+ )+ }+ val factory = factoriesByType.getValue(snapshot.provider.type)+ if (factory.providerType != snapshot.configuration.type) {+ return CapabilityResolution.ConfigurationError("Factory/configuration type mismatch")+ }+ return try {+ CapabilityResolution.Available(factory.create(snapshot))+ } catch (error: IllegalArgumentException) {+ CapabilityResolution.ConfigurationError(error.message ?: "Invalid provider configuration")+ }+ }+}diff --git a/data/src/main/java/com/streamvault/data/provider/LegacyProviderSnapshotMapper.kt b/data/src/main/java/com/streamvault/data/provider/LegacyProviderSnapshotMapper.ktnew file mode 100644index 00000000..1622471d--- /dev/null+++ b/data/src/main/java/com/streamvault/data/provider/LegacyProviderSnapshotMapper.kt@@ -0,0 +1,152 @@+package com.streamvault.data.provider++import com.streamvault.domain.model.Provider as StableProvider++import com.streamvault.domain.model.*+import com.streamvault.domain.model.LegacyProvider as Provider++fun ProviderConfiguration.guidePolicy(): GuideSourcePolicy = when (this) {+ is XtreamConfig -> guideSourcePolicy+ is M3uConfig -> guideSourcePolicy+ is StalkerConfig -> guideSourcePolicy+ is JellyfinConfig -> GuideSourcePolicy.DISABLED+}++fun ProviderConfiguration.logoPolicy(): ChannelLogoSourcePolicy = when (this) {+ is XtreamConfig -> channelLogoSourcePolicy+ is M3uConfig -> channelLogoSourcePolicy+ is StalkerConfig -> channelLogoSourcePolicy+ is JellyfinConfig -> ChannelLogoSourcePolicy.SUPPLIER_PREFERRED+}++/** Temporary compatibility mapper used while schema-72 rows and backup v0-10 remain readable. */+fun Provider.toTypedConfiguration(): ProviderConfiguration = when (type) {+ ProviderType.XTREAM_CODES -> XtreamConfig(+ serverUrl = serverUrl,+ username = username,+ password = password,+ httpUserAgent = httpUserAgent,+ httpHeaders = httpHeaders,+ epgSyncMode = epgSyncMode,+ guideSourcePolicy = guideSourcePolicy,+ channelLogoSourcePolicy = channelLogoSourcePolicy,+ fastSyncEnabled = xtreamFastSyncEnabled,+ liveSyncMode = xtreamLiveSyncMode+ )+ ProviderType.M3U -> M3uConfig(+ playlistUrl = m3uUrl.ifBlank { serverUrl },+ epgUrl = epgUrl,+ httpUserAgent = httpUserAgent,+ httpHeaders = httpHeaders,+ epgSyncMode = epgSyncMode,+ guideSourcePolicy = guideSourcePolicy,+ channelLogoSourcePolicy = channelLogoSourcePolicy,+ vodClassificationEnabled = m3uVodClassificationEnabled+ )+ ProviderType.STALKER_PORTAL -> StalkerConfig(+ portalUrl = serverUrl,+ device = StalkerDeviceIdentity(+ macAddress = stalkerMacAddress,+ deviceProfile = stalkerDeviceProfile,+ timezone = stalkerDeviceTimezone,+ locale = stalkerDeviceLocale,+ serialNumber = stalkerSerialNumber,+ deviceId = stalkerDeviceId,+ deviceId2 = stalkerDeviceId2,+ signature = stalkerSignature+ ),+ username = username,+ password = password,+ httpUserAgent = httpUserAgent,+ httpHeaders = httpHeaders,+ advancedOptionsJson = stalkerAdvancedOptionsJson,+ authMode = stalkerAuthMode,+ requestedProfileId = stalkerRequestedProfileId,+ protocolPreference = stalkerProtocolPreference,+ transportGrant = toLegacyTransportGrant(),+ epgSyncMode = epgSyncMode,+ catalogMode = stalkerCatalogMode,+ guideSourcePolicy = guideSourcePolicy,+ channelLogoSourcePolicy = channelLogoSourcePolicy+ )+ ProviderType.JELLYFIN -> JellyfinConfig(+ serverUrl = serverUrl,+ username = username,+ credential = password+ )+}++fun Provider.toAccountRuntime() = ProviderAccountRuntime(+ maxConnections = maxConnections,+ expirationDate = expirationDate,+ apiVersion = apiVersion,+ allowedOutputFormats = allowedOutputFormats,+ catalogLayout = catalogLayout,+ catalogLayoutDetectionVersion = catalogLayoutDetectionVersion,+ observedAt = lastSyncedAt+)++fun Provider.toProviderSnapshot(): ProviderSnapshot {+ val generation = if (type == ProviderType.STALKER_PORTAL) stalkerConfigurationGeneration else 0L+ return ProviderSnapshot(+ provider = StableProvider(+ id = id,+ name = name,+ type = type,+ isActive = isActive,+ status = status,+ lastSyncedAt = lastSyncedAt,+ createdAt = createdAt+ ),+ configuration = toTypedConfiguration(),+ configurationGeneration = generation,+ accountRuntime = toAccountRuntime(),+ stalkerLearning = if (type == ProviderType.STALKER_PORTAL) toLegacyStalkerLearning(generation) else null+ )+}++private fun Provider.toLegacyStalkerLearning(generation: Long): StalkerPortalLearning {+ val observedAt = lastSyncedAt.takeIf { it > 0L } ?: createdAt+ fun <T> observation(value: T, source: StalkerObservationSource = StalkerObservationSource.DISCOVERY) =+ StalkerObservation(value, generation, source, observedAt)+ return StalkerPortalLearning(+ configurationGeneration = generation,+ effectiveIdentity = observation(+ StalkerDeviceIdentity(+ macAddress = stalkerMacAddress,+ deviceProfile = stalkerDeviceProfile,+ timezone = stalkerDeviceTimezone,+ locale = stalkerDeviceLocale,+ serialNumber = stalkerSerialNumber,+ deviceId = stalkerDeviceId,+ deviceId2 = stalkerDeviceId2,+ signature = stalkerSignature+ )+ ),+ profileId = stalkerLearnedProfileId.takeIf { it.isNotBlank() }?.let(::observation),+ profileRevision = observation(stalkerProfileRevision),+ profileVerification = observation(stalkerProfileVerification),+ portalProfile = observation(stalkerPortalProfile),+ portalFingerprint = observation(stalkerPortalFingerprint),+ magPreset = observation(stalkerMagPreset),+ protocolFamily = observation(stalkerProtocolFamily),+ bootstrapRecipe = observation(stalkerLastBootstrapRecipe),+ endpointPreference = observation(stalkerEndpointPreference),+ cookieMode = observation(stalkerCookieMode),+ playbackBackendHint = observation(stalkerPlaybackBackendHint),+ lastPlaybackMode = stalkerLastPlaybackMode?.let { observation(it, StalkerObservationSource.PLAYBACK) }+ )+}++private fun Provider.toLegacyTransportGrant(): StalkerTransportGrant? {+ if (stalkerTransportMode == StalkerTransportMode.AUTO_STRICT || stalkerTransportConsentAt <= 0L) return null+ val match = Regex("^(https?)://([^/:]+)(?::(\\d+))?$").matchEntire(stalkerTransportOrigin.trim()) ?: return null+ val scheme = match.groupValues[1].lowercase()+ val port = match.groupValues[3].toIntOrNull() ?: if (scheme == "https") 443 else 80+ return StalkerTransportGrant(+ mode = stalkerTransportMode,+ origin = StalkerTransportOrigin(scheme, match.groupValues[2], port),+ spkiSha256 = stalkerTlsSpkiSha256.takeIf { it.isNotBlank() },+ consentedAt = stalkerTransportConsentAt+ )+}diff --git a/data/src/main/java/com/streamvault/data/provider/ProductionProviderCapabilityFactories.kt b/data/src/main/java/com/streamvault/data/provider/ProductionProviderCapabilityFactories.ktnew file mode 100644index 00000000..ec775a35--- /dev/null+++ b/data/src/main/java/com/streamvault/data/provider/ProductionProviderCapabilityFactories.kt@@ -0,0 +1,453 @@+package com.streamvault.data.provider++import com.streamvault.data.mapper.toDomain+import com.streamvault.data.local.dao.CategoryDao+import com.streamvault.data.local.dao.ChannelDao+import com.streamvault.data.local.dao.MovieDao+import com.streamvault.data.local.dao.ProgramDao+import com.streamvault.data.remote.http.buildGenericProviderRequestProfile+import com.streamvault.data.remote.jellyfin.JellyfinPage+import com.streamvault.data.remote.jellyfin.buildJellyfinAuthorizationHeader+import com.streamvault.data.remote.xtream.XtreamStreamKind+import com.streamvault.data.remote.xtream.XtreamUrlFactory+import com.streamvault.data.remote.xtream.extractStreamExpirationTime+import com.streamvault.data.repository.buildM3uCatchUpUrls+import com.streamvault.data.util.UrlSecurityPolicy+import com.streamvault.domain.model.CapabilityState+import com.streamvault.domain.model.Category+import com.streamvault.domain.model.Channel+import com.streamvault.domain.model.ContentType+import com.streamvault.domain.model.JellyfinConfig+import com.streamvault.domain.model.M3uConfig+import com.streamvault.domain.model.Movie+import com.streamvault.domain.model.Program+import com.streamvault.domain.model.LegacyProvider as Provider+import com.streamvault.domain.model.ProviderSnapshot+import com.streamvault.domain.model.ProviderType+import com.streamvault.domain.model.Result+import com.streamvault.domain.model.Season+import com.streamvault.domain.model.Series+import com.streamvault.domain.model.XtreamConfig+import com.streamvault.domain.provider.CatchUpRequest+import com.streamvault.domain.provider.CatchUpSource+import com.streamvault.domain.provider.CapabilityResolution+import com.streamvault.domain.provider.GuideSource+import com.streamvault.domain.provider.GuideRequest+import com.streamvault.domain.provider.LiveCatalogSource+import com.streamvault.domain.provider.PlaybackResolver+import com.streamvault.domain.provider.PlaybackRequest+import com.streamvault.domain.provider.ProviderAuthenticator+import com.streamvault.domain.provider.ProviderCapabilityFactory+import com.streamvault.domain.provider.ProviderCapabilitySet+import com.streamvault.domain.provider.ProviderContentReference+import com.streamvault.domain.provider.SeriesCatalogSource+import com.streamvault.domain.provider.VodCatalogSource+import com.streamvault.domain.provider.ResolvedPlayback+import javax.inject.Inject+import javax.inject.Singleton+import kotlinx.coroutines.withTimeoutOrNull+import kotlinx.coroutines.flow.first++class ProviderCapabilityTimeoutException(message: String) : RuntimeException(message)++@Singleton+class XtreamCapabilityFactory @Inject constructor(+ private val clients: TypedProviderClientFactory+) : ProviderCapabilityFactory {+ override val providerType = ProviderType.XTREAM_CODES+ override fun create(snapshot: ProviderSnapshot): ProviderCapabilitySet {+ require(snapshot.configuration.type == providerType) { "Xtream factory requires XtreamConfig" }+ val adapter = XtreamCapabilityAdapter(snapshot, clients)+ return FixedProviderCapabilitySet(+ snapshot = snapshot,+ authentication = available(adapter),+ liveCatalog = available(adapter),+ vodCatalog = available(adapter),+ seriesCatalog = available(adapter),+ guide = available(adapter),+ playback = available(adapter),+ catchUp = available(adapter)+ )+ }+}++@Singleton+class StalkerCapabilityFactory @Inject constructor(+ private val clients: TypedProviderClientFactory,+ private val playbackCache: StalkerPlaybackCapabilityCache+) : ProviderCapabilityFactory {+ override val providerType = ProviderType.STALKER_PORTAL+ override fun create(snapshot: ProviderSnapshot): ProviderCapabilitySet {+ val client = when (val result = clients.stalker(snapshot)) {+ is CapabilityResolution.Available -> result.capability+ is CapabilityResolution.ConfigurationError -> throw IllegalArgumentException(result.reason)+ is CapabilityResolution.Restricted -> throw IllegalArgumentException(result.reason)+ is CapabilityResolution.Unsupported -> throw IllegalArgumentException(result.reason)+ }+ fun <T> learned(key: String, capability: T): CapabilityResolution<T> =+ when (snapshot.stalkerLearning?.capabilities?.get(key)?.value) {+ CapabilityState.UNSUPPORTED -> CapabilityResolution.Unsupported("Portal reports $key as unsupported")+ CapabilityState.RESTRICTED -> CapabilityResolution.Restricted("Portal restricts $key")+ else -> available(capability)+ }+ return FixedProviderCapabilitySet(+ snapshot = snapshot,+ authentication = available(client),+ liveCatalog = learned("live", client),+ vodCatalog = learned("vod", client),+ seriesCatalog = learned("series", client),+ guide = learned("epg", client),+ playback = when (val playback = playbackCache.resolve(snapshot)) {+ is CapabilityResolution.Available -> learned("playback", playback.capability)+ is CapabilityResolution.ConfigurationError -> playback+ is CapabilityResolution.Restricted -> playback+ is CapabilityResolution.Unsupported -> playback+ },+ catchUp = learned("catch_up", client)+ )+ }+}++@Singleton+class M3uCapabilityFactory @Inject constructor(+ private val categoryDao: CategoryDao,+ private val channelDao: ChannelDao,+ private val movieDao: MovieDao,+ private val programDao: ProgramDao+) : ProviderCapabilityFactory {+ override val providerType = ProviderType.M3U+ override fun create(snapshot: ProviderSnapshot): ProviderCapabilitySet {+ val config = snapshot.configuration as? M3uConfig+ ?: throw IllegalArgumentException("M3U factory requires M3uConfig")+ val adapter = M3uCapabilityAdapter(+ providerId = snapshot.provider.id,+ config = config,+ categoryDao = categoryDao,+ channelDao = channelDao,+ movieDao = movieDao,+ programDao = programDao+ )+ val guide = if (config.epgUrl.isBlank()) {+ CapabilityResolution.Unsupported("M3U guide requires a configured XMLTV source")+ } else {+ available(adapter)+ }+ return FixedProviderCapabilitySet(+ snapshot = snapshot,+ authentication = CapabilityResolution.Unsupported("M3U does not authenticate"),+ liveCatalog = available(adapter),+ vodCatalog = available(adapter),+ seriesCatalog = CapabilityResolution.Unsupported("M3U has no native series catalog"),+ guide = guide,+ playback = available(adapter),+ catchUp = available(adapter)+ )+ }+}++@Singleton+class JellyfinCapabilityFactory @Inject constructor(+ private val clients: TypedProviderClientFactory+) : ProviderCapabilityFactory {+ override val providerType = ProviderType.JELLYFIN+ override fun create(snapshot: ProviderSnapshot): ProviderCapabilitySet {+ val context = when (val result = clients.jellyfin(snapshot)) {+ is CapabilityResolution.Available -> result.capability+ is CapabilityResolution.ConfigurationError -> throw IllegalArgumentException(result.reason)+ is CapabilityResolution.Restricted -> throw IllegalArgumentException(result.reason)+ is CapabilityResolution.Unsupported -> throw IllegalArgumentException(result.reason)+ }+ val adapter = JellyfinCapabilityAdapter(context)+ return FixedProviderCapabilitySet(+ snapshot = snapshot,+ authentication = available(adapter),+ liveCatalog = CapabilityResolution.Unsupported("Jellyfin has no live catalog"),+ vodCatalog = available(adapter),+ seriesCatalog = available(adapter),+ guide = CapabilityResolution.Unsupported("Jellyfin has no IPTV guide"),+ playback = available(adapter),+ catchUp = CapabilityResolution.Unsupported("Jellyfin has no IPTV catch-up")+ )+ }+}++private fun <T> available(value: T): CapabilityResolution<T> = CapabilityResolution.Available(value)++private class FixedProviderCapabilitySet(+ override val snapshot: ProviderSnapshot,+ private val authentication: CapabilityResolution<ProviderAuthenticator>,+ private val liveCatalog: CapabilityResolution<LiveCatalogSource>,+ private val vodCatalog: CapabilityResolution<VodCatalogSource>,+ private val seriesCatalog: CapabilityResolution<SeriesCatalogSource>,+ private val guide: CapabilityResolution<GuideSource>,+ private val playback: CapabilityResolution<PlaybackResolver>,+ private val catchUp: CapabilityResolution<CatchUpSource>+) : ProviderCapabilitySet {+ override fun authentication() = authentication+ override fun liveCatalog() = liveCatalog+ override fun vodCatalog() = vodCatalog+ override fun seriesCatalog() = seriesCatalog+ override fun guide() = guide+ override fun playback() = playback+ override fun catchUp() = catchUp+}++private class XtreamCapabilityAdapter(+ private val snapshot: ProviderSnapshot,+ private val clients: TypedProviderClientFactory+) : ProviderAuthenticator, LiveCatalogSource, VodCatalogSource, SeriesCatalogSource, GuideSource,+ PlaybackResolver, CatchUpSource {+ private suspend fun <T> execute(block: suspend (com.streamvault.data.remote.xtream.XtreamProvider) -> Result<T>): Result<T> =+ when (val resolved = clients.xtream(snapshot)) {+ is CapabilityResolution.Available -> block(resolved.capability)+ is CapabilityResolution.ConfigurationError -> Result.error(resolved.reason)+ is CapabilityResolution.Restricted -> Result.error(resolved.reason)+ is CapabilityResolution.Unsupported -> Result.error(resolved.reason)+ }++ override suspend fun authenticate(): Result<Provider> = execute { it.authenticate() }+ override suspend fun getLiveCategories(): Result<List<Category>> = execute { it.getLiveCategories() }+ override suspend fun getLiveStreams(categoryId: Long?): Result<List<Channel>> = execute { it.getLiveStreams(categoryId) }+ override suspend fun getVodCategories(): Result<List<Category>> = execute { it.getVodCategories() }+ override suspend fun getVodStreams(categoryId: Long?): Result<List<Movie>> = execute { it.getVodStreams(categoryId) }+ override suspend fun getVodInfo(vodId: Long): Result<Movie> = execute { it.getVodInfo(vodId) }+ override suspend fun getSeriesCategories(): Result<List<Category>> = execute { it.getSeriesCategories() }+ override suspend fun getSeriesList(categoryId: Long?): Result<List<Series>> = execute { it.getSeriesList(categoryId) }+ override suspend fun getSeriesInfo(seriesId: Long): Result<Series> = execute { it.getSeriesInfo(seriesId) }+ override suspend fun hydrateSeries(reference: ProviderContentReference, current: Series): Result<Series> =+ withTimeoutOrNull(8_000L) { execute { it.hydrateSeries(reference, current) } }+ ?: Result.error(+ "Xtream series detail hydration timed out",+ ProviderCapabilityTimeoutException("Xtream series detail hydration timed out")+ )+ override suspend fun getEpg(channelId: String): Result<List<Program>> = execute { it.getEpg(channelId) }+ override suspend fun getShortEpg(channelId: String, limit: Int): Result<List<Program>> = execute { it.getShortEpg(channelId, limit) }+ override suspend fun getEpg(request: GuideRequest): Result<List<Program>> =+ execute { it.getEpg(request.streamId.toString()) }+ override suspend fun getShortEpg(request: GuideRequest): Result<List<Program>> =+ execute { it.getShortEpg(request.streamId.toString(), request.limit) }+ override suspend fun buildStreamUrl(streamId: Long, containerExtension: String?): String =+ when (val resolved = clients.xtream(snapshot)) {+ is CapabilityResolution.Available -> resolved.capability.buildStreamUrl(streamId, containerExtension)+ else -> ""+ }+ override suspend fun resolve(request: PlaybackRequest): Result<ResolvedPlayback> {+ val config = snapshot.configuration as XtreamConfig+ val token = XtreamUrlFactory.parseInternalStreamUrl(request.sourceUrl)+ val directToken = token ?: XtreamUrlFactory.parseCredentialedStreamUrl(+ request.sourceUrl,+ snapshot.provider.id+ )+ val kind = directToken?.kind ?: XtreamUrlFactory.kindForContentType(request.contentType)+ ?: return Result.error("Xtream content type is not playable")+ val streamId = directToken?.streamId ?: request.content.numericRemoteId()+ ?: return Result.error("Xtream playback stream ID is missing")+ val resolvedExtension = clients.resolveLiveContainerExtension(+ kind,+ directToken?.containerExtension ?: request.containerExtension+ )+ val directSource = token?.directSource+ ?.takeIf { kind != XtreamStreamKind.LIVE }+ ?.takeIf(UrlSecurityPolicy::isAllowedStreamEntryUrl)+ val stableUrl = XtreamUrlFactory.buildPlaybackUrl(+ serverUrl = config.serverUrl,+ username = config.username,+ password = config.password,+ kind = kind,+ streamId = streamId,+ containerExtension = resolvedExtension+ )+ val sourceIsInternal = token != null+ val resolvedUrl = when {+ request.preferStableUrl -> stableUrl+ directSource != null -> directSource+ sourceIsInternal -> stableUrl+ kind == XtreamStreamKind.LIVE -> stableUrl+ request.sourceUrl.isNotBlank() -> request.sourceUrl+ else -> stableUrl+ }+ val profile = buildGenericProviderRequestProfile(+ ownerTag = "provider:${snapshot.provider.id}/playback",+ httpUserAgent = config.httpUserAgent,+ httpHeaders = config.httpHeaders+ )+ return Result.success(+ ResolvedPlayback(+ url = resolvedUrl,+ expirationTime = extractStreamExpirationTime(resolvedUrl),+ containerExtension = resolvedExtension,+ headers = profile.headers,+ userAgent = profile.userAgent+ )+ )+ }+ override suspend fun buildCatchUpUrl(streamId: Long, start: Long, end: Long): String? =+ buildCatchUpUrls(streamId, start, end).firstOrNull()+ override suspend fun buildCatchUpUrls(streamId: Long, start: Long, end: Long): List<String> =+ when (val resolved = clients.xtream(snapshot)) {+ is CapabilityResolution.Available -> resolved.capability.buildCatchUpUrls(streamId, start, end)+ else -> emptyList()+ }+}++private class M3uCapabilityAdapter(+ private val providerId: Long,+ private val config: M3uConfig,+ private val categoryDao: CategoryDao,+ private val channelDao: ChannelDao,+ private val movieDao: MovieDao,+ private val programDao: ProgramDao+) : LiveCatalogSource, VodCatalogSource, GuideSource, PlaybackResolver, CatchUpSource {+ override suspend fun getLiveCategories(): Result<List<Category>> = Result.success(+ categoryDao.getByProviderAndTypeSync(providerId, ContentType.LIVE.name).map { it.toDomain() }+ )+ override suspend fun getLiveStreams(categoryId: Long?): Result<List<Channel>> = Result.success(+ channelDao.getByProviderSync(providerId)+ .asSequence()+ .filter { categoryId == null || it.categoryId == categoryId }+ .map { it.toDomain() }+ .toList()+ )+ override suspend fun getVodCategories(): Result<List<Category>> = Result.success(+ categoryDao.getByProviderAndTypeSync(providerId, ContentType.MOVIE.name).map { it.toDomain() }+ )+ override suspend fun getVodStreams(categoryId: Long?): Result<List<Movie>> = Result.success(+ movieDao.getByProviderSync(providerId)+ .asSequence()+ .filter { categoryId == null || it.categoryId == categoryId }+ .map { it.toDomain() }+ .toList()+ )+ override suspend fun getVodInfo(vodId: Long): Result<Movie> =+ movieDao.getByStreamId(providerId, vodId)?.toDomain()?.let(Result.Companion::success)+ ?: Result.error("M3U movie was not found in the imported catalog")+ override suspend fun hydrateVod(reference: ProviderContentReference, current: Movie): Result<Movie> = Result.success(current)+ override suspend fun getEpg(channelId: String): Result<List<Program>> {+ val now = System.currentTimeMillis()+ return Result.success(+ programDao.getForChannel(+ providerId,+ channelId,+ now - GUIDE_LOOKBACK_MILLIS,+ now + GUIDE_LOOKAHEAD_MILLIS+ ).first().map { it.toDomain() }+ )+ }+ override suspend fun getShortEpg(channelId: String, limit: Int): Result<List<Program>> =+ getEpg(channelId).map { it.take(limit.coerceAtLeast(0)) }+ override suspend fun buildStreamUrl(streamId: Long, containerExtension: String?): String = ""+ override suspend fun resolve(request: PlaybackRequest): Result<ResolvedPlayback> {+ if (request.sourceUrl.isBlank()) return Result.error("M3U playback URL is missing")+ val profile = buildGenericProviderRequestProfile(+ ownerTag = "provider:${request.content.providerId}/playback",+ httpUserAgent = config.httpUserAgent,+ httpHeaders = config.httpHeaders+ )+ return Result.success(+ ResolvedPlayback(+ url = request.sourceUrl,+ expirationTime = extractStreamExpirationTime(request.sourceUrl),+ containerExtension = request.containerExtension,+ headers = profile.headers,+ userAgent = profile.userAgent+ )+ )+ }+ override suspend fun buildCatchUpUrl(streamId: Long, start: Long, end: Long): String? = null+ override suspend fun buildCatchUpUrls(request: CatchUpRequest): List<String> =+ request.sourceCatchUpTemplate?.let { buildM3uCatchUpUrls(it, request.start, request.end) }.orEmpty()++ private companion object {+ const val GUIDE_LOOKBACK_MILLIS = 12L * 60L * 60L * 1000L+ const val GUIDE_LOOKAHEAD_MILLIS = 7L * 24L * 60L * 60L * 1000L+ }+}++private class JellyfinCapabilityAdapter(+ private val context: JellyfinClientContext+) : ProviderAuthenticator, VodCatalogSource, SeriesCatalogSource, PlaybackResolver {+ override suspend fun authenticate(): Result<Provider> = Result.success(context.provider)+ override suspend fun getVodCategories(): Result<List<Category>> = Result.success(+ listOf(Category(id = 1L, name = "Movies", type = ContentType.MOVIE))+ )+ override suspend fun getVodStreams(categoryId: Long?): Result<List<Movie>> =+ collectPages { context.client.fetchMoviesPage(context.provider, it) }.map { rows -> rows.map { it.toDomain() } }+ override suspend fun getVodInfo(vodId: Long): Result<Movie> =+ getVodStreams().map { movies -> movies.firstOrNull { it.id == vodId } }+ .let { result ->+ when (result) {+ is Result.Success -> result.data?.let(Result.Companion::success)+ ?: Result.error("Jellyfin movie not found")+ is Result.Error -> result+ is Result.Loading -> Result.Loading+ }+ }+ override suspend fun hydrateVod(reference: ProviderContentReference, current: Movie): Result<Movie> = Result.success(current)++ override suspend fun getSeriesCategories(): Result<List<Category>> = Result.success(+ listOf(Category(id = 2L, name = "Series", type = ContentType.SERIES))+ )+ override suspend fun getSeriesList(categoryId: Long?): Result<List<Series>> =+ collectPages { context.client.fetchSeriesPage(context.provider, it) }.map { rows -> rows.map { it.toDomain() } }+ override suspend fun getSeriesInfo(seriesId: Long): Result<Series> = Result.error("Jellyfin series requires its opaque remote ID")+ override suspend fun hydrateSeries(reference: ProviderContentReference, current: Series): Result<Series> {+ val remoteId = reference.remoteId?.takeIf(String::isNotBlank)+ ?: return Result.error("Jellyfin series remote ID is missing")+ val localId = reference.localId ?: current.id+ return context.client.fetchEpisodes(context.provider, remoteId, localId).map { rows ->+ val episodes = rows.map { it.toDomain() }+ current.copy(+ seasons = episodes.groupBy { it.seasonNumber }+ .toSortedMap()+ .map { (number, seasonEpisodes) ->+ Season(+ seasonNumber = number,+ episodes = seasonEpisodes.sortedBy { it.episodeNumber },+ episodeCount = seasonEpisodes.size+ )+ }+ )+ }+ }++ override suspend fun buildStreamUrl(streamId: Long, containerExtension: String?): String = ""+ override suspend fun resolve(request: PlaybackRequest): Result<ResolvedPlayback> {+ if (request.sourceUrl.isBlank()) return Result.error("Jellyfin playback URL is missing")+ val config = context.provider+ return Result.success(+ ResolvedPlayback(+ url = request.sourceUrl,+ expirationTime = extractStreamExpirationTime(request.sourceUrl),+ containerExtension = request.containerExtension,+ headers = mapOf(+ "Authorization" to buildJellyfinAuthorizationHeader(+ config.serverUrl,+ config.username,+ config.password+ )+ )+ )+ )+ }+}++private suspend fun <T> collectPages(+ fetch: suspend (Int) -> Result<JellyfinPage<T>>+): Result<List<T>> {+ val rows = ArrayList<T>()+ var offset = 0+ do {+ when (val pageResult = fetch(offset)) {+ is Result.Success -> {+ val page = pageResult.data+ rows += page.items+ if (page.items.isEmpty() || page.nextStartIndex >= page.totalRecordCount) {+ return Result.success(rows)+ }+ offset = page.nextStartIndex+ }+ is Result.Error -> return pageResult+ is Result.Loading -> return Result.error("Unexpected loading state")+ }+ } while (true)+}diff --git a/data/src/main/java/com/streamvault/data/provider/ProviderCapabilityResolver.kt b/data/src/main/java/com/streamvault/data/provider/ProviderCapabilityResolver.ktnew file mode 100644index 00000000..2a400bd1--- /dev/null+++ b/data/src/main/java/com/streamvault/data/provider/ProviderCapabilityResolver.kt@@ -0,0 +1,23 @@+package com.streamvault.data.provider++import com.streamvault.domain.provider.CapabilityResolution+import com.streamvault.domain.provider.ProviderCapabilityRegistry+import com.streamvault.domain.provider.ProviderCapabilitySet+import com.streamvault.domain.repository.ProviderSnapshotRepository+import javax.inject.Inject+import javax.inject.Singleton++/** Loads one immutable snapshot before selecting any provider execution capability. */+@Singleton+class ProviderCapabilityResolver @Inject constructor(+ private val snapshots: ProviderSnapshotRepository,+ private val registry: ProviderCapabilityRegistry+) {+ suspend fun snapshot(providerId: Long) = snapshots.getSnapshot(providerId)++ suspend fun resolve(providerId: Long): CapabilityResolution<ProviderCapabilitySet> {+ val snapshot = snapshots.getSnapshot(providerId)+ ?: return CapabilityResolution.ConfigurationError("Provider $providerId has no typed configuration")+ return registry.resolve(snapshot)+ }+}diff --git a/data/src/main/java/com/streamvault/data/provider/ProviderConfigRevisionCodec.kt b/data/src/main/java/com/streamvault/data/provider/ProviderConfigRevisionCodec.ktnew file mode 100644index 00000000..d0159343--- /dev/null+++ b/data/src/main/java/com/streamvault/data/provider/ProviderConfigRevisionCodec.kt@@ -0,0 +1,213 @@+package com.streamvault.data.provider++import com.streamvault.domain.model.Provider as StableProvider++import com.google.gson.Gson+import com.streamvault.data.local.entity.ProviderEntity+import com.streamvault.data.mapper.toEntity+import com.streamvault.data.security.CredentialCrypto+import com.streamvault.domain.model.*+import com.streamvault.domain.model.LegacyProvider as Provider++data class ProviderConfigRevisionEnvelope(+ val envelopeVersion: Int = CURRENT_VERSION,+ val provider: StableProvider,+ val configurationGeneration: Long,+ val configurationType: ProviderType,+ val configurationSchemaVersion: Int,+ val identityKey: String,+ val encryptedConfigurationJson: String,+ val accountRuntime: ProviderAccountRuntime+) {+ companion object {+ const val CURRENT_VERSION = 2+ }+}++data class DecodedProviderConfigRevision(+ val candidate: Provider,+ val secureEntity: ProviderEntity,+ val configurationGeneration: Long,+ val wasLegacy: Boolean+)++/** Versioned candidate codec with a legacy ProviderEntity fallback for process-death upgrades. */+class ProviderConfigRevisionCodec(+ private val gson: Gson,+ private val configurationCodec: ProviderConfigurationCodec,+ private val credentialCrypto: CredentialCrypto+) {+ fun encode(candidate: Provider, generation: Long): String {+ val configuration = candidate.toTypedConfiguration()+ return gson.toJson(+ ProviderConfigRevisionEnvelope(+ provider = StableProvider(+ id = candidate.id,+ name = candidate.name,+ type = candidate.type,+ isActive = candidate.isActive,+ status = candidate.status,+ lastSyncedAt = candidate.lastSyncedAt,+ createdAt = candidate.createdAt+ ),+ configurationGeneration = generation,+ configurationType = configuration.type,+ configurationSchemaVersion = configuration.schemaVersion,+ identityKey = configurationCodec.identityKey(configuration),+ encryptedConfigurationJson = configurationCodec.encode(configuration),+ accountRuntime = candidate.toAccountRuntime()+ )+ )+ }++ fun decode(payload: String): DecodedProviderConfigRevision {+ val envelope = runCatching { gson.fromJson(payload, ProviderConfigRevisionEnvelope::class.java) }+ .getOrNull()+ ?.takeIf { it.envelopeVersion == ProviderConfigRevisionEnvelope.CURRENT_VERSION }+ if (envelope != null) {+ require(envelope.provider.type == envelope.configurationType) { "Revision provider/configuration type mismatch" }+ val configuration = configurationCodec.decode(envelope.configurationType, envelope.encryptedConfigurationJson)+ require(configurationCodec.identityKey(configuration) == envelope.identityKey) {+ "Revision configuration identity is invalid"+ }+ val candidate = configuration.toLegacyProvider(envelope.provider, envelope.accountRuntime).let { provider ->+ if (provider.type == ProviderType.STALKER_PORTAL) {+ provider.copy(stalkerConfigurationGeneration = envelope.configurationGeneration)+ } else {+ provider+ }+ }+ val secure = candidate.toEntity()+ return DecodedProviderConfigRevision(candidate, secure, envelope.configurationGeneration, wasLegacy = false)+ }++ val legacyJson = gson.fromJson(payload, com.google.gson.JsonObject::class.java)+ ?: throw IllegalArgumentException("Saved provider edit was empty")+ val serializedProvider = gson.fromJson(payload, Provider::class.java)+ ?: throw IllegalArgumentException("Saved provider edit was empty")+ val allowedFormats = legacyJson.get("allowedOutputFormatsJson")+ ?.asString+ ?.let { runCatching { gson.fromJson(it, Array<String>::class.java).toList() }.getOrNull() }+ .orEmpty()+ val candidate = serializedProvider.copy(+ password = credentialCrypto.decryptIfNeeded(serializedProvider.password),+ allowedOutputFormats = allowedFormats+ )+ val secure = candidate.toEntity()+ return DecodedProviderConfigRevision(+ candidate = candidate,+ secureEntity = secure,+ configurationGeneration = candidate.stalkerConfigurationGeneration,+ wasLegacy = true+ )+ }+}++fun ProviderConfiguration.toLegacyProvider(+ identity: StableProvider,+ runtime: ProviderAccountRuntime+): Provider {+ val common = Provider(+ id = identity.id,+ name = identity.name,+ type = identity.type,+ serverUrl = when (this) {+ is XtreamConfig -> serverUrl+ is M3uConfig -> playlistUrl+ is StalkerConfig -> portalUrl+ is JellyfinConfig -> serverUrl+ },+ isActive = identity.isActive,+ maxConnections = runtime.maxConnections,+ expirationDate = runtime.expirationDate,+ apiVersion = runtime.apiVersion,+ allowedOutputFormats = runtime.allowedOutputFormats,+ catalogLayout = runtime.catalogLayout,+ catalogLayoutDetectionVersion = runtime.catalogLayoutDetectionVersion,+ status = identity.status,+ lastSyncedAt = identity.lastSyncedAt,+ createdAt = identity.createdAt+ )+ return when (this) {+ is XtreamConfig -> common.copy(+ username = username,+ password = password,+ httpUserAgent = httpUserAgent,+ httpHeaders = httpHeaders,+ epgSyncMode = epgSyncMode,+ guideSourcePolicy = guideSourcePolicy,+ channelLogoSourcePolicy = channelLogoSourcePolicy,+ xtreamFastSyncEnabled = fastSyncEnabled,+ xtreamLiveSyncMode = liveSyncMode+ )+ is M3uConfig -> common.copy(+ m3uUrl = playlistUrl,+ epgUrl = epgUrl,+ httpUserAgent = httpUserAgent,+ httpHeaders = httpHeaders,+ epgSyncMode = epgSyncMode,+ guideSourcePolicy = guideSourcePolicy,+ channelLogoSourcePolicy = channelLogoSourcePolicy,+ m3uVodClassificationEnabled = vodClassificationEnabled+ )+ is StalkerConfig -> common.copy(+ username = username,+ password = password,+ httpUserAgent = httpUserAgent,+ httpHeaders = httpHeaders,+ stalkerMacAddress = device.macAddress,+ stalkerDeviceProfile = device.deviceProfile,+ stalkerDeviceTimezone = device.timezone,+ stalkerDeviceLocale = device.locale,+ stalkerSerialNumber = device.serialNumber,+ stalkerDeviceId = device.deviceId,+ stalkerDeviceId2 = device.deviceId2,+ stalkerSignature = device.signature,+ stalkerAdvancedOptionsJson = advancedOptionsJson,+ stalkerAuthMode = authMode,+ stalkerProtocolPreference = protocolPreference,+ stalkerTransportMode = transportGrant?.mode ?: StalkerTransportMode.AUTO_STRICT,+ stalkerTransportOrigin = transportGrant?.origin?.authority.orEmpty(),+ stalkerTlsSpkiSha256 = transportGrant?.spkiSha256.orEmpty(),+ stalkerTransportConsentAt = transportGrant?.consentedAt ?: 0L,+ stalkerConfigurationGeneration = 0L,+ stalkerRequestedProfileId = requestedProfileId,+ epgSyncMode = epgSyncMode,+ stalkerCatalogMode = catalogMode,+ guideSourcePolicy = guideSourcePolicy,+ channelLogoSourcePolicy = channelLogoSourcePolicy+ )+ is JellyfinConfig -> common.copy(username = username, password = credential)+ }+}++/** Temporary compatibility projection used only inside data-layer adapters during schema 74 cutover. */+fun ProviderSnapshot.toLegacyProvider(): Provider =+ configuration.toLegacyProvider(provider, accountRuntime).let { legacy ->+ if (provider.type != ProviderType.STALKER_PORTAL) return@let legacy+ val learning = stalkerLearning+ legacy.copy(+ // Generation is part of the configuration snapshot even when no learning has been+ // observed yet. Leaving this at the legacy mapper's zero default makes a fresh edit+ // appear stale and can attach later observations to the wrong configuration.+ stalkerConfigurationGeneration = configurationGeneration,+ stalkerLearnedProfileId = learning?.profileId?.value ?: legacy.stalkerLearnedProfileId,+ stalkerProfileRevision = learning?.profileRevision?.value ?: legacy.stalkerProfileRevision,+ stalkerProfileVerification = learning?.profileVerification?.value+ ?: legacy.stalkerProfileVerification,+ stalkerPortalProfile = learning?.portalProfile?.value ?: legacy.stalkerPortalProfile,+ stalkerPortalFingerprint = learning?.portalFingerprint?.value+ ?: legacy.stalkerPortalFingerprint,+ stalkerMagPreset = learning?.magPreset?.value ?: legacy.stalkerMagPreset,+ stalkerProtocolFamily = learning?.protocolFamily?.value ?: legacy.stalkerProtocolFamily,+ stalkerLastBootstrapRecipe = learning?.bootstrapRecipe?.value+ ?: legacy.stalkerLastBootstrapRecipe,+ stalkerEndpointPreference = learning?.endpointPreference?.value+ ?: legacy.stalkerEndpointPreference,+ stalkerCookieMode = learning?.cookieMode?.value ?: legacy.stalkerCookieMode,+ stalkerPlaybackBackendHint = learning?.playbackBackendHint?.value+ ?: legacy.stalkerPlaybackBackendHint,+ stalkerLastPlaybackMode = learning?.lastPlaybackMode?.value+ ?: legacy.stalkerLastPlaybackMode+ )+ }diff --git a/data/src/main/java/com/streamvault/data/provider/ProviderConfigurationCodec.kt b/data/src/main/java/com/streamvault/data/provider/ProviderConfigurationCodec.ktnew file mode 100644index 00000000..22aab6f4--- /dev/null+++ b/data/src/main/java/com/streamvault/data/provider/ProviderConfigurationCodec.kt@@ -0,0 +1,80 @@+package com.streamvault.data.provider++import com.google.gson.Gson+import com.streamvault.data.security.CredentialCrypto+import com.streamvault.domain.model.JellyfinConfig+import com.streamvault.domain.model.M3uConfig+import com.streamvault.domain.model.ProviderConfiguration+import com.streamvault.domain.model.ProviderType+import com.streamvault.domain.model.StalkerConfig+import com.streamvault.domain.model.XtreamConfig+import java.net.URI+import java.security.MessageDigest+import javax.inject.Inject+import javax.inject.Singleton++/** Keeps secret handling at the data boundary; plaintext credentials never enter Room JSON. */+@Singleton+class ProviderConfigurationCodec @Inject constructor(+ private val gson: Gson,+ private val credentialCrypto: CredentialCrypto+) {+ fun encode(configuration: ProviderConfiguration): String = gson.toJson(configuration.encryptSecrets())++ fun decode(type: ProviderType, payload: String): ProviderConfiguration {+ val encrypted = when (type) {+ ProviderType.XTREAM_CODES -> gson.fromJson(payload, XtreamConfig::class.java)+ ProviderType.M3U -> gson.fromJson(payload, M3uConfig::class.java)+ ProviderType.STALKER_PORTAL -> gson.fromJson(payload, StalkerConfig::class.java)+ ProviderType.JELLYFIN -> gson.fromJson(payload, JellyfinConfig::class.java)+ } ?: throw IllegalArgumentException("Provider configuration payload is empty")+ require(encrypted.type == type) { "Configuration payload does not match stored provider type" }+ return encrypted.decryptSecrets()+ }++ fun identityKey(configuration: ProviderConfiguration): String {+ val canonical = when (configuration) {+ is XtreamConfig -> listOf(configuration.type.name, normalizeOrigin(configuration.serverUrl), configuration.username.trim())+ is M3uConfig -> listOf(configuration.type.name, normalizeUrl(configuration.playlistUrl))+ is StalkerConfig -> listOf(+ configuration.type.name,+ normalizeOrigin(configuration.portalUrl),+ configuration.device.macAddress.trim().uppercase(),+ configuration.username.trim()+ )+ is JellyfinConfig -> listOf(configuration.type.name, normalizeOrigin(configuration.serverUrl), configuration.username.trim())+ }.joinToString("\u0000")+ return MessageDigest.getInstance("SHA-256")+ .digest(canonical.toByteArray(Charsets.UTF_8))+ .joinToString("") { "%02x".format(it) }+ }++ private fun ProviderConfiguration.encryptSecrets(): ProviderConfiguration = when (this) {+ is XtreamConfig -> copy(password = credentialCrypto.encryptIfNeeded(password))+ is M3uConfig -> this+ is StalkerConfig -> copy(password = credentialCrypto.encryptIfNeeded(password))+ is JellyfinConfig -> copy(credential = credentialCrypto.encryptIfNeeded(credential))+ }++ private fun ProviderConfiguration.decryptSecrets(): ProviderConfiguration = when (this) {+ is XtreamConfig -> copy(password = credentialCrypto.decryptIfNeeded(password))+ is M3uConfig -> this+ is StalkerConfig -> copy(password = credentialCrypto.decryptIfNeeded(password))+ is JellyfinConfig -> copy(credential = credentialCrypto.decryptIfNeeded(credential))+ }++ private fun normalizeOrigin(value: String): String = runCatching {+ val uri = URI(value.trim())+ val scheme = uri.scheme?.lowercase().orEmpty()+ val host = uri.host?.lowercase().orEmpty()+ val port = when {+ uri.port >= 0 -> uri.port+ scheme == "https" -> 443+ scheme == "http" -> 80+ else -> -1+ }+ "$scheme://$host:$port${uri.path.orEmpty().trimEnd('/')}"+ }.getOrElse { value.trim().trimEnd('/').lowercase() }++ private fun normalizeUrl(value: String): String = value.trim()+}diff --git a/data/src/main/java/com/streamvault/data/provider/RoomProviderSnapshotRepository.kt b/data/src/main/java/com/streamvault/data/provider/RoomProviderSnapshotRepository.ktnew file mode 100644index 00000000..b21639ee--- /dev/null+++ b/data/src/main/java/com/streamvault/data/provider/RoomProviderSnapshotRepository.kt@@ -0,0 +1,87 @@+package com.streamvault.data.provider++import com.streamvault.domain.model.Provider as StableProvider++import com.google.gson.Gson+import com.google.gson.reflect.TypeToken+import com.streamvault.data.local.dao.ProviderDao+import com.streamvault.data.local.dao.ProviderSnapshotDao+import com.streamvault.data.local.dao.StalkerPortalStateDao+import com.streamvault.data.local.entity.StalkerPortalStateEntity+import com.streamvault.domain.model.*+import com.streamvault.domain.repository.ProviderSnapshotRepository+import javax.inject.Inject+import javax.inject.Singleton++@Singleton+class RoomProviderSnapshotRepository @Inject constructor(+ private val providerDao: ProviderDao,+ private val snapshotDao: ProviderSnapshotDao,+ private val stalkerPortalStateDao: StalkerPortalStateDao,+ private val codec: ProviderConfigurationCodec,+ private val gson: Gson+) : ProviderSnapshotRepository {+ private val stringListType = object : TypeToken<List<String>>() {}.type++ override suspend fun getSnapshot(providerId: Long): ProviderSnapshot? {+ val provider = providerDao.getById(providerId) ?: return null+ val storedConfig = snapshotDao.getConfig(providerId) ?: return null+ if (storedConfig.type != provider.type) {+ throw IllegalStateException("Provider/configuration type mismatch for $providerId")+ }+ val runtime = snapshotDao.getRuntime(providerId)+ val learning = if (provider.type == ProviderType.STALKER_PORTAL) {+ stalkerPortalStateDao.get(providerId)?.toGenerationValidLearning(+ gson,+ storedConfig.configurationGeneration+ )+ } else null+ return ProviderSnapshot(+ provider = StableProvider(+ id = provider.id,+ name = provider.name,+ type = provider.type,+ isActive = provider.isActive,+ status = provider.status,+ lastSyncedAt = provider.lastSyncedAt,+ createdAt = provider.createdAt+ ),+ configuration = codec.decode(storedConfig.type, storedConfig.encryptedConfigJson),+ configurationGeneration = storedConfig.configurationGeneration,+ accountRuntime = runtime?.let {+ ProviderAccountRuntime(+ maxConnections = it.maxConnections,+ expirationDate = it.expirationDate,+ apiVersion = it.apiVersion,+ allowedOutputFormats = gson.fromJson(it.allowedOutputFormatsJson, stringListType),+ catalogLayout = it.catalogLayout,+ catalogLayoutDetectionVersion = it.catalogLayoutDetectionVersion,+ observedAt = it.observedAt+ )+ } ?: ProviderAccountRuntime(),+ stalkerLearning = learning+ )+ }++ override suspend fun compareAndSetStalkerLearning(+ providerId: Long,+ learning: StalkerPortalLearning+ ): Boolean {+ val existing = stalkerPortalStateDao.get(providerId)+ val observedAt = learning.latestObservedAtForSnapshot()+ return snapshotDao.compareAndSetStalkerLearning(+ (existing ?: StalkerPortalStateEntity(providerId)).copy(+ configurationGeneration = learning.configurationGeneration,+ learningJson = gson.toJson(learning),+ observationSource = learning.latestSourceForSnapshot().name,+ observedAt = observedAt,+ validatedAt = maxOf(existing?.validatedAt ?: 0L, observedAt)+ )+ )+ }++ override suspend fun updateCatalogLayout(providerId: Long, layout: CatalogLayout, detectionVersion: Int) {+ snapshotDao.updateCatalogLayout(providerId, layout, detectionVersion)+ }++}diff --git a/data/src/main/java/com/streamvault/data/provider/StalkerLearningMapper.kt b/data/src/main/java/com/streamvault/data/provider/StalkerLearningMapper.ktnew file mode 100644index 00000000..3ce5015f--- /dev/null+++ b/data/src/main/java/com/streamvault/data/provider/StalkerLearningMapper.kt@@ -0,0 +1,59 @@+package com.streamvault.data.provider++import com.google.gson.Gson+import com.streamvault.data.local.entity.StalkerPortalStateEntity+import com.streamvault.domain.model.*++/** Decode persisted learning only when every observation belongs to the requested generation. */+internal fun StalkerPortalStateEntity.toGenerationValidLearning(+ gson: Gson,+ expectedGeneration: Long+): StalkerPortalLearning? {+ if (configurationGeneration != expectedGeneration) return null+ if (learningJson.isNotBlank() && learningJson != "{}") {+ return runCatching { gson.fromJson(learningJson, StalkerPortalLearning::class.java) }+ .getOrNull()+ ?.takeIf { it.configurationGeneration == expectedGeneration }+ }+ val source = runCatching { StalkerObservationSource.valueOf(observationSource) }+ .getOrDefault(StalkerObservationSource.DISCOVERY)+ val time = observedAt.takeIf { it > 0L } ?: validatedAt+ fun <T> observed(value: T) = StalkerObservation(value, expectedGeneration, source, time)+ val capabilities = buildMap {+ bulkLiveSupported?.let { put("live", observed(if (it) CapabilityState.SUPPORTED else CapabilityState.UNSUPPORTED)) }+ movieWildcardSupported?.let { put("vod", observed(if (it) CapabilityState.SUPPORTED else CapabilityState.UNSUPPORTED)) }+ seriesWildcardSupported?.let { put("series", observed(if (it) CapabilityState.SUPPORTED else CapabilityState.UNSUPPORTED)) }+ epgSupported?.let { put("epg", observed(if (it) CapabilityState.SUPPORTED else CapabilityState.UNSUPPORTED)) }+ }+ return StalkerPortalLearning(+ configurationGeneration = expectedGeneration,+ workingEndpoint = workingEndpoint?.let(::observed),+ bootstrapRecipe = bootstrapRecipe+ ?.let { runCatching { StalkerBootstrapRecipe.valueOf(it) }.getOrNull() }+ ?.let(::observed),+ capabilities = capabilities+ )+}++internal fun StalkerPortalLearning.latestObservedAtForSnapshot(): Long = buildList {+ add(effectiveIdentity?.observedAt)+ add(profileId?.observedAt)+ add(portalProfile?.observedAt)+ add(portalFingerprint?.observedAt)+ add(magPreset?.observedAt)+ add(workingEndpoint?.observedAt)+ add(lastPlaybackMode?.observedAt)+ addAll(capabilities.values.map { it.observedAt })+ addAll(discoveryEvidence.map { it.observedAt })+}.filterNotNull().maxOrNull() ?: 0L++internal fun StalkerPortalLearning.latestSourceForSnapshot(): StalkerObservationSource = buildList {+ add(lastPlaybackMode)+ add(workingEndpoint)+ add(profileId)+ add(portalProfile)+ add(portalFingerprint)+ add(magPreset)+ addAll(capabilities.values)+ addAll(discoveryEvidence)+}.filterNotNull().maxByOrNull { it.observedAt }?.source ?: StalkerObservationSource.DISCOVERYdiff --git a/data/src/main/java/com/streamvault/data/provider/StalkerPlaybackCapabilityCache.kt b/data/src/main/java/com/streamvault/data/provider/StalkerPlaybackCapabilityCache.ktnew file mode 100644index 00000000..f84ed0a7--- /dev/null+++ b/data/src/main/java/com/streamvault/data/provider/StalkerPlaybackCapabilityCache.kt@@ -0,0 +1,49 @@+package com.streamvault.data.provider++import com.streamvault.domain.model.ProviderSnapshot+import com.streamvault.domain.provider.CapabilityResolution+import com.streamvault.domain.provider.PlaybackResolver+import java.util.concurrent.ConcurrentHashMap+import javax.inject.Inject+import javax.inject.Singleton++/** Temporary ARCH-004 compatibility boundary for Stalker playback client lifetime. */+@Singleton+class StalkerPlaybackCapabilityCache @Inject constructor(+ private val clients: TypedProviderClientFactory+) {+ private data class Entry(+ val generation: Long,+ val resolver: PlaybackResolver+ )++ private val entries = ConcurrentHashMap<Long, Entry>()++ fun resolve(snapshot: ProviderSnapshot): CapabilityResolution<PlaybackResolver> {+ entries[snapshot.provider.id]+ ?.takeIf { it.generation == snapshot.configurationGeneration }+ ?.let { return CapabilityResolution.Available(it.resolver) }+ val resolver = when (val result = clients.stalker(snapshot)) {+ is CapabilityResolution.Available -> result.capability+ is CapabilityResolution.ConfigurationError -> return result+ is CapabilityResolution.Restricted -> return result+ is CapabilityResolution.Unsupported -> return result+ }+ entries[snapshot.provider.id] = Entry(snapshot.configurationGeneration, resolver)+ trimToBound()+ return CapabilityResolution.Available(resolver)+ }++ fun invalidate(providerId: Long) {+ entries.remove(providerId)+ }++ private fun trimToBound() {+ if (entries.size <= MAX_ENTRIES) return+ entries.keys.sorted().take(entries.size - MAX_ENTRIES).forEach(entries::remove)+ }++ private companion object {+ const val MAX_ENTRIES = 32+ }+}diff --git a/data/src/main/java/com/streamvault/data/provider/TypedProviderClientFactory.kt b/data/src/main/java/com/streamvault/data/provider/TypedProviderClientFactory.ktnew file mode 100644index 00000000..8f4dfebf--- /dev/null+++ b/data/src/main/java/com/streamvault/data/provider/TypedProviderClientFactory.kt@@ -0,0 +1,182 @@+package com.streamvault.data.provider++import com.streamvault.data.preferences.PreferencesRepository+import com.streamvault.data.remote.http.buildGenericProviderRequestProfile+import com.streamvault.data.remote.jellyfin.JellyfinProvider+import com.streamvault.data.remote.stalker.StalkerApiService+import com.streamvault.data.remote.stalker.StalkerPlaybackMode+import com.streamvault.data.remote.stalker.StalkerPortalStateStore+import com.streamvault.data.remote.stalker.StalkerProvider+import com.streamvault.data.remote.stalker.StalkerRemoteIdentityResolver+import com.streamvault.data.remote.xtream.XtreamApiService+import com.streamvault.data.remote.xtream.XtreamProvider+import com.streamvault.domain.model.JellyfinConfig+import com.streamvault.domain.model.LiveStreamFormatMode+import com.streamvault.domain.model.LegacyProvider as Provider+import com.streamvault.domain.model.ProviderSnapshot+import com.streamvault.domain.model.StalkerBootstrapRecipe+import com.streamvault.domain.model.StalkerConfig+import com.streamvault.domain.model.StalkerCookieMode+import com.streamvault.domain.model.StalkerEndpointPreference+import com.streamvault.domain.model.StalkerMagPreset+import com.streamvault.domain.model.StalkerPlaybackBackendHint+import com.streamvault.domain.model.StalkerPortalFingerprint+import com.streamvault.domain.model.StalkerPortalProfile+import com.streamvault.domain.model.XtreamConfig+import com.streamvault.domain.provider.CapabilityResolution+import javax.inject.Inject+import javax.inject.Singleton+import kotlinx.coroutines.flow.first+import com.streamvault.data.remote.xtream.XtreamStreamKind++/**+ * Constructs provider protocol clients from the typed snapshot boundary.+ *+ * This is deliberately stateless. Playback's existing Stalker cache and learning side effects+ * remain owned by its resolver adapter until ARCH-004 is handled in WP5.+ */+@Singleton+class TypedProviderClientFactory @Inject constructor(+ private val xtreamApiService: XtreamApiService,+ private val stalkerApiService: StalkerApiService,+ private val jellyfinProvider: JellyfinProvider,+ private val preferencesRepository: PreferencesRepository,+ private val stalkerRemoteIdentityResolver: StalkerRemoteIdentityResolver,+ private val stalkerPortalStateStore: StalkerPortalStateStore+) {+ suspend fun xtream(+ snapshot: ProviderSnapshot,+ options: XtreamClientOptions = XtreamClientOptions()+ ): CapabilityResolution<XtreamProvider> {+ val config = snapshot.configuration as? XtreamConfig+ ?: return CapabilityResolution.ConfigurationError("Xtream capability requires XtreamConfig")+ if (config.serverUrl.isBlank() || config.username.isBlank() || config.password.isBlank()) {+ return CapabilityResolution.ConfigurationError("Xtream server URL and credentials are required")+ }+ return CapabilityResolution.Available(+ XtreamProvider(+ providerId = snapshot.provider.id,+ api = xtreamApiService,+ serverUrl = config.serverUrl,+ username = config.username,+ password = config.password,+ allowedOutputFormats = snapshot.accountRuntime.allowedOutputFormats,+ useTextClassification = options.useTextClassification,+ enableBase64TextCompatibility = options.enableBase64TextCompatibility+ ?: preferencesRepository.xtreamBase64TextCompatibility.first(),+ requestProfile = buildGenericProviderRequestProfile(+ ownerTag = "provider:${snapshot.provider.id}/xtream",+ httpUserAgent = config.httpUserAgent,+ httpHeaders = config.httpHeaders+ )+ )+ )+ }++ fun stalker(+ snapshot: ProviderSnapshot,+ options: StalkerClientOptions = StalkerClientOptions()+ ): CapabilityResolution<StalkerProvider> {+ val config = snapshot.configuration as? StalkerConfig+ ?: return CapabilityResolution.ConfigurationError("Stalker capability requires StalkerConfig")+ if (config.portalUrl.isBlank() || config.device.macAddress.isBlank()) {+ return CapabilityResolution.ConfigurationError("Stalker portal URL and MAC address are required")+ }+ val learning = snapshot.stalkerLearning+ val identity = learning?.effectiveIdentity?.value ?: config.device+ return CapabilityResolution.Available(+ StalkerProvider(+ providerId = snapshot.provider.id,+ api = stalkerApiService,+ portalUrl = config.portalUrl,+ macAddress = identity.macAddress,+ authMode = config.authMode,+ username = config.username,+ password = config.password,+ httpUserAgent = config.httpUserAgent,+ httpHeaders = config.httpHeaders,+ portalFingerprintHint = learning?.portalFingerprint?.value+ ?: StalkerPortalFingerprint.BASIC_MAC,+ magPresetHint = learning?.magPreset?.value ?: StalkerMagPreset.GENERIC_SAFE,+ bootstrapRecipeHint = learning?.bootstrapRecipe?.value+ ?: StalkerBootstrapRecipe.GENERIC_SAFE,+ endpointPreferenceHint = learning?.endpointPreference?.value+ ?: StalkerEndpointPreference.AUTO,+ cookieModeHint = learning?.cookieMode?.value ?: StalkerCookieMode.NONE,+ playbackBackendHint = learning?.playbackBackendHint?.value+ ?: StalkerPlaybackBackendHint.AUTO,+ portalProfileHint = learning?.portalProfile?.value ?: StalkerPortalProfile.MAG_BASIC,+ preferredPlaybackMode = learning?.lastPlaybackMode?.value+ ?.let { runCatching { StalkerPlaybackMode.valueOf(it) }.getOrNull() },+ deviceProfile = identity.deviceProfile,+ timezone = identity.timezone,+ locale = identity.locale,+ serialNumber = identity.serialNumber,+ deviceId = identity.deviceId,+ deviceId2 = identity.deviceId2,+ signature = identity.signature,+ stalkerAdvancedOptionsJson = config.advancedOptionsJson,+ protocolPreference = config.protocolPreference,+ transportGrant = config.transportGrant,+ requestedProfileId = config.requestedProfileId,+ learnedProfileId = learning?.profileId?.value.orEmpty(),+ configurationGeneration = snapshot.configurationGeneration,+ requireCatalogValidation = options.requireCatalogValidation,+ catalogLayoutHint = snapshot.accountRuntime.catalogLayout,+ catalogLayoutDetectionVersionHint = snapshot.accountRuntime.catalogLayoutDetectionVersion,+ identityResolver = stalkerRemoteIdentityResolver,+ portalStateStore = stalkerPortalStateStore,+ onProgress = options.onProgress+ )+ )+ }++ fun jellyfin(snapshot: ProviderSnapshot): CapabilityResolution<JellyfinClientContext> {+ val config = snapshot.configuration as? JellyfinConfig+ ?: return CapabilityResolution.ConfigurationError("Jellyfin capability requires JellyfinConfig")+ if (config.serverUrl.isBlank() || config.credential.isBlank()) {+ return CapabilityResolution.ConfigurationError("Jellyfin server URL and credential are required")+ }+ return CapabilityResolution.Available(+ JellyfinClientContext(+ client = jellyfinProvider,+ provider = Provider(+ id = snapshot.provider.id,+ name = snapshot.provider.name,+ type = snapshot.provider.type,+ serverUrl = config.serverUrl,+ username = config.username,+ password = config.credential,+ isActive = snapshot.provider.isActive,+ status = snapshot.provider.status,+ lastSyncedAt = snapshot.provider.lastSyncedAt,+ createdAt = snapshot.provider.createdAt+ )+ )+ )+ }++ suspend fun resolveLiveContainerExtension(kind: XtreamStreamKind, value: String?): String? {+ if (kind != XtreamStreamKind.LIVE) return value+ return when (preferencesRepository.playerLiveStreamFormatMode.first()) {+ LiveStreamFormatMode.AUTO -> value+ LiveStreamFormatMode.HLS -> "m3u8"+ LiveStreamFormatMode.MPEG_TS -> "ts"+ }+ }+}++data class XtreamClientOptions(+ val useTextClassification: Boolean = true,+ val enableBase64TextCompatibility: Boolean? = null+)++data class StalkerClientOptions(+ val requireCatalogValidation: Boolean = true,+ val onProgress: ((String) -> Unit)? = null+)++data class JellyfinClientContext(+ val client: JellyfinProvider,+ val provider: Provider+)diff --git a/data/src/main/java/com/streamvault/data/remote/http/RequestIdentity.kt b/data/src/main/java/com/streamvault/data/remote/http/RequestIdentity.ktindex bd0ddd2c..7e2a5f4a 100644--- a/data/src/main/java/com/streamvault/data/remote/http/RequestIdentity.kt+++ b/data/src/main/java/com/streamvault/data/remote/http/RequestIdentity.kt@@ -1,7 +1,7 @@package com.streamvault.data.remote.httpimport com.streamvault.data.local.entity.ProviderEntity-import com.streamvault.domain.model.Provider+import com.streamvault.domain.model.LegacyProvider as Providerimport okhttp3.Interceptorimport okhttp3.Request@@ -91,9 +91,6 @@ fun buildAppRequestProfile(fun Provider.toGenericRequestProfile(ownerTag: String): HttpRequestProfile =buildGenericProviderRequestProfile(ownerTag, httpUserAgent, httpHeaders)-fun ProviderEntity.toGenericRequestProfile(ownerTag: String): HttpRequestProfile =- buildGenericProviderRequestProfile(ownerTag, httpUserAgent, httpHeaders)-fun buildGenericProviderRequestProfile(ownerTag: String,httpUserAgent: String,@@ -126,4 +123,4 @@ private fun parseProviderHttpHeaders(httpHeaders: String): Map<String, String> {put(name, value)}}-}\ No newline at end of file+}diff --git a/data/src/main/java/com/streamvault/data/remote/jellyfin/JellyfinImageAuthInterceptor.kt b/data/src/main/java/com/streamvault/data/remote/jellyfin/JellyfinImageAuthInterceptor.ktindex c20276b7..e27e49e5 100644--- a/data/src/main/java/com/streamvault/data/remote/jellyfin/JellyfinImageAuthInterceptor.kt+++ b/data/src/main/java/com/streamvault/data/remote/jellyfin/JellyfinImageAuthInterceptor.kt@@ -1,8 +1,9 @@package com.streamvault.data.remote.jellyfinimport com.streamvault.data.local.dao.ProviderDao-import com.streamvault.data.local.entity.ProviderEntity-import com.streamvault.data.security.CredentialCrypto+import com.streamvault.data.local.dao.ProviderSnapshotDao+import com.streamvault.data.provider.ProviderConfigurationCodec+import com.streamvault.domain.model.JellyfinConfigimport com.streamvault.domain.model.ProviderTypeimport javax.inject.Injectimport javax.inject.Singleton@@ -13,7 +14,8 @@ import okhttp3.Interceptor@Singletonclass JellyfinImageAuthInterceptor @Inject constructor(private val providerDao: ProviderDao,- private val credentialCrypto: CredentialCrypto+ private val providerSnapshotDao: ProviderSnapshotDao,+ private val providerConfigurationCodec: ProviderConfigurationCodec) : Interceptor {override fun intercept(chain: Interceptor.Chain): okhttp3.Response {val request = chain.request()@@ -33,14 +35,16 @@ class JellyfinImageAuthInterceptor @Inject constructor(val providerId = marker.toLongOrNull() ?: return chain.proceed(sanitizedRequest)// Query the exact account on every request. Provider edits and deletes must take effect// immediately; a short-lived list cache can otherwise attach a revoked account token.- val provider = runCatching { providerDao.getByIdSync(providerId) }- .getOrNull()- ?.takeIf { it.type == ProviderType.JELLYFIN }+ val identity = runCatching { providerDao.getByIdSync(providerId) }+ .getOrNull()?.takeIf { it.type == ProviderType.JELLYFIN }?: return chain.proceed(sanitizedRequest)+ val stored = providerSnapshotDao.getConfigSync(identity.id)+ ?: return chain.proceed(sanitizedRequest)+ val provider = runCatching {+ providerConfigurationCodec.decode(stored.type, stored.encryptedConfigJson) as? JellyfinConfig+ }.getOrNull() ?: return chain.proceed(sanitizedRequest)if (!provider.matches(request.url)) return chain.proceed(sanitizedRequest)- val accessToken = runCatching { credentialCrypto.decryptIfNeeded(provider.password) }- .getOrNull()- ?.takeIf { it.isNotBlank() }+ val accessToken = provider.credential.takeIf { it.isNotBlank() }?: return chain.proceed(sanitizedRequest)return chain.proceed(@@ -53,7 +57,7 @@ class JellyfinImageAuthInterceptor @Inject constructor()}- private fun ProviderEntity.matches(url: HttpUrl): Boolean {+ private fun JellyfinConfig.matches(url: HttpUrl): Boolean {val baseUrl = serverUrl.toHttpUrlOrNull() ?: return falseif (url.scheme != baseUrl.scheme || url.host != baseUrl.host || url.port != baseUrl.port) {return falsediff --git a/data/src/main/java/com/streamvault/data/remote/jellyfin/JellyfinProvider.kt b/data/src/main/java/com/streamvault/data/remote/jellyfin/JellyfinProvider.ktindex 4d192b8f..484d199f 100644--- a/data/src/main/java/com/streamvault/data/remote/jellyfin/JellyfinProvider.kt+++ b/data/src/main/java/com/streamvault/data/remote/jellyfin/JellyfinProvider.kt@@ -7,7 +7,7 @@ import com.streamvault.data.local.entity.EpisodeEntityimport com.streamvault.data.local.entity.MovieEntityimport com.streamvault.data.local.entity.SeriesEntityimport com.streamvault.data.remote.http.useCancellableResponse-import com.streamvault.domain.model.Provider+import com.streamvault.domain.model.LegacyProvider as Providerimport com.streamvault.domain.model.Resultimport okhttp3.MediaType.Companion.toMediaTypeimport okhttp3.OkHttpClientdiff --git a/data/src/main/java/com/streamvault/data/remote/stalker/MinistraApiV3Provider.kt b/data/src/main/java/com/streamvault/data/remote/stalker/MinistraApiV3Provider.ktindex 8e469876..06b9fbe6 100644--- a/data/src/main/java/com/streamvault/data/remote/stalker/MinistraApiV3Provider.kt+++ b/data/src/main/java/com/streamvault/data/remote/stalker/MinistraApiV3Provider.kt@@ -7,7 +7,7 @@ import com.streamvault.domain.model.Channelimport com.streamvault.domain.model.ContentTypeimport com.streamvault.domain.model.Movieimport com.streamvault.domain.model.Program-import com.streamvault.domain.model.Provider+import com.streamvault.domain.model.LegacyProvider as Providerimport com.streamvault.domain.model.ProviderStatusimport com.streamvault.domain.model.ProviderTypeimport com.streamvault.domain.model.Result@@ -16,7 +16,7 @@ import com.streamvault.domain.model.StalkerCompatibilityProfileIdsimport com.streamvault.domain.model.StalkerProfileVerificationimport com.streamvault.domain.model.StalkerProtocolFamilyimport com.streamvault.domain.model.StalkerProtocolPreference-import com.streamvault.domain.provider.IptvProvider+import com.streamvault.domain.provider.*import java.io.IOExceptionimport dagger.hilt.android.qualifiers.ApplicationContextimport javax.inject.Inject@@ -110,12 +110,18 @@ class MinistraApiV3CompatibilityException(message: String, cause: Throwable? = n* generation. A concrete client is enabled only for a provider-documented API-v3 contract.*/class MinistraApiV3Provider(- override val providerId: Long,+ val providerId: Long,private val credentials: MinistraApiV3Credentials,private val requestedProfileId: String,private val client: MinistraApiV3Client,private val tokenStore: MinistraApiV3TokenStore-) : IptvProvider {+) : ProviderAuthenticator,+ LiveCatalogSource,+ VodCatalogSource,+ SeriesCatalogSource,+ GuideSource,+ PlaybackResolver,+ CatchUpSource {private var memoryToken: MinistraApiV3Token? = nulloverride suspend fun authenticate(): Result<Provider> = apiCall("Ministra API-v3 authentication failed") {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 b81084de..4aadd9bc 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@@ -19,6 +19,7 @@ import com.streamvault.domain.model.StalkerProtocolPreferenceimport com.streamvault.domain.model.StalkerTransportGrantimport com.streamvault.domain.model.DiscoveryBudgetimport com.streamvault.domain.util.StreamEntryUrlPolicy+import com.streamvault.data.util.runSuspendCatchingimport java.io.ByteArrayOutputStreamimport java.io.IOExceptionimport java.io.InputStream@@ -44,6 +45,7 @@ import java.util.Base64import java.util.ArrayDequeimport java.util.Localeimport java.util.concurrent.ConcurrentHashMap+import java.util.concurrent.atomic.AtomicLongimport java.util.concurrent.TimeUnitimport javax.inject.Injectimport javax.inject.Singleton@@ -99,14 +101,21 @@ class OkHttpStalkerApiService @Inject constructor(private val sessionScopes = ConcurrentHashMap<String, SessionScope>()private val stalkerHttpClients = ConcurrentHashMap<String, OkHttpClient>()private val resolvedLoadUrls = ConcurrentHashMap<String, String>()+ private val scopeAliases = ConcurrentHashMap<String, String>()+ private val nextAuthEpoch = AtomicLong(System.currentTimeMillis())override suspend fun authenticate(profile: StalkerDeviceProfile): Result<Pair<StalkerSession, StalkerProviderProfile>> {profile.discoveryRuntime.begin()+ val authProfile = profile.copy(authEpoch = nextAuthEpoch.incrementAndGet())return try {// Each network call is capped by the remaining wall-time and consumeRequest checks// elapsed time before dispatch. Avoid a second coroutine timer here: virtual-time// dispatchers can otherwise race an already-completed OkHttp callback.- authenticateWithinBudget(profile)+ authenticateWithinBudget(authProfile).also { result ->+ if (result is Result.Success) {+ scopeAliases[sessionScopeAliasKey(profile)] = result.data.first.sessionScopeKey+ }+ }} catch (error: CancellationException) {throw error} catch (error: StalkerApiError) {@@ -253,6 +262,7 @@ class OkHttpStalkerApiService @Inject constructor(loadUrl = loadUrl,portalReferer = referer,token = token,+ authEpoch = attemptProfile.authEpoch,sessionScopeKey = sessionScopeKey(attemptProfile))if (recipe.preferLocalizationBeforeProfile) {@@ -582,6 +592,11 @@ class OkHttpStalkerApiService @Inject constructor()session = session.copy(serverCookieHeader = cookieJar.cookieHeaderFor(loadUrl),+ authenticatedAtMillis = System.currentTimeMillis(),+ expiresAtMillis = listOfNotNull(+ System.currentTimeMillis() + STALKER_SESSION_MAX_AGE_MILLIS,+ providerProfile.expirationDate?.takeIf { it > System.currentTimeMillis() }+ ).minOrNull(),effectiveAuthMode = effectiveAuthMode,portalProfile = portalProfile,portalFingerprint = fingerprint,@@ -856,7 +871,7 @@ class OkHttpStalkerApiService @Inject constructor(if (pageEntries.isEmpty()) break}}- val seriesItems = seriesPayload.toItemRecords()+ val seriesItems = seriesPayload.toItemRecords(profile.timezone.toPortalZoneId())val series = seriesItems.firstOrNull { item -> !item.looksLikeSeasonShell() }?: StalkerItemRecord(id = seriesId,@@ -1222,6 +1237,16 @@ class OkHttpStalkerApiService @Inject constructor(.orEmpty().ifBlank { session.serverCookieHeader }+ override fun invalidateSessionScopes(providerId: Long) {+ val prefix = "provider:$providerId|"+ sessionScopes.keys.filter { it.startsWith(prefix) }.forEach { key ->+ sessionScopes.remove(key)+ stalkerHttpClients.keys.removeIf { clientKey -> clientKey.startsWith("$key|") }+ resolvedLoadUrls.keys.removeIf { resolvedKey -> resolvedKey.startsWith("$key|") }+ }+ scopeAliases.keys.filter { it.startsWith(prefix) }.forEach(scopeAliases::remove)+ }+private suspend fun fetchPagedItems(session: StalkerSession,profile: StalkerDeviceProfile,@@ -1235,7 +1260,8 @@ class OkHttpStalkerApiService @Inject constructor(query = baseQuery + ("p" to "1"))val items = mutableListOf<StalkerItemRecord>()- items += firstPage.toItemRecords()+ val zoneId = profile.timezone.toPortalZoneId()+ items += firstPage.toItemRecords(zoneId)val advertisedTotalPages = firstPage.advertisedTotalPages()// Huge catalogs (e.g. 218k items at 14/page = 15,600 pages) are common on// Flussonic/NFS-backed Stalker portals. Instead of aborting the entire@@ -1250,7 +1276,7 @@ class OkHttpStalkerApiService @Inject constructor(token = session.token,query = baseQuery + ("p" to page.toString()))- items += pagePayload.toItemRecords()+ items += pagePayload.toItemRecords(zoneId)}return items}@@ -1269,7 +1295,7 @@ class OkHttpStalkerApiService @Inject constructor(token = session.token,query = baseQuery + ("p" to safePage.toString()))- val items = payload.toItemRecords()+ val items = payload.toItemRecords(profile.timezone.toPortalZoneId())val pageSize = payload.pageSize(items.size)val advertisedTotalItems = payload.advertisedTotalItems()val advertisedTotalPages = payload.advertisedTotalPages()@@ -1300,7 +1326,7 @@ class OkHttpStalkerApiService @Inject constructor("action" to "get_all_channels","JsHttpRequest" to "1-xml")- ).toItemRecords()+ ).toItemRecords(profile.timezone.toPortalZoneId())}.onFailure { error ->if (error is CancellationException) throw errorLog.w(TAG, "Stalker get_all_channels failed; falling back to paged live catalog", error)@@ -1418,8 +1444,6 @@ class OkHttpStalkerApiService @Inject constructor(profile.discoveryRuntime.consumeRequest()val startedAt = System.currentTimeMillis()return withTransportAwareStalkerCall(request, profile) { response ->- recordResolvedLoadUrl(request, response, profile)- captureResponseCookies(response, profile)if (!response.isSuccessful) {StalkerTelemetry.httpResponse(providerId = profile.providerId,@@ -1433,11 +1457,12 @@ class OkHttpStalkerApiService @Inject constructor(// A 401/403 served as an HTML page comes from an edge/WAF (e.g. Cloudflare)// or a misconfigured endpoint, not from the portal's JSON auth layer; do not// classify it as a portal authorization verdict.- val htmlErrorPage = runCatching {- looksLikeHtml(response.peekBody(HTML_ERROR_SNIFF_BYTES).string())- }.getOrDefault(false)+ val errorBody = runCatching {+ response.peekBody(HTML_ERROR_SNIFF_BYTES).string()+ }.getOrDefault("")+ val htmlErrorPage = looksLikeHtml(errorBody)response.body?.close()- throw response.toStalkerHttpError(htmlErrorPage)+ throw response.toStalkerHttpError(htmlErrorPage, errorBody)}val responseBody = response.body?: throw StalkerApiError.EmptyBody("Portal returned an empty response${actionSuffix(action)}.")@@ -1463,6 +1488,8 @@ class OkHttpStalkerApiService @Inject constructor(// the trailing diagnostic text is not part of the playback contract.val parsed = parseCreateLinkEnvelope(responseBody.byteStream(), charset.name(), action)parsed.ensureNoPortalError()+ recordResolvedLoadUrl(request, response, profile)+ captureResponseCookies(response, profile)StalkerTelemetry.httpResponse(providerId = profile.providerId,endpointFamily = endpointFamily(request),@@ -1485,6 +1512,8 @@ class OkHttpStalkerApiService @Inject constructor(}val parsed = parsePortalJson(raw, action)parsed.ensureNoPortalError()+ recordResolvedLoadUrl(request, response, profile)+ captureResponseCookies(response, profile)StalkerTelemetry.httpResponse(providerId = profile.providerId,endpointFamily = endpointFamily(request),@@ -1633,7 +1662,6 @@ class OkHttpStalkerApiService @Inject constructor(profile.discoveryRuntime.consumeRequest()val startedAt = System.currentTimeMillis()return withTransportAwareStalkerCall(request, profile) { response ->- captureResponseCookies(response, profile)if (!response.isSuccessful) {throw response.toStalkerHttpError()}@@ -1642,7 +1670,9 @@ class OkHttpStalkerApiService @Inject constructor(val reader = JsonReader(InputStreamReader(body.byteStream(), charset))reader.isLenient = truetry {- streamStalkerItems(reader, onItem).also { itemCount ->+ streamStalkerItems(reader, profile.timezone.toPortalZoneId(), onItem).also { itemCount ->+ recordResolvedLoadUrl(request, response, profile)+ captureResponseCookies(response, profile)StalkerTelemetry.httpResponse(providerId = profile.providerId,endpointFamily = endpointFamily(request),@@ -1661,11 +1691,12 @@ class OkHttpStalkerApiService @Inject constructor(private suspend fun streamStalkerItems(reader: JsonReader,+ zoneId: ZoneId,onItem: suspend (StalkerItemRecord) -> Unit): Int {return when (reader.peek()) {- JsonToken.BEGIN_ARRAY -> streamItemArray(reader, onItem)- JsonToken.BEGIN_OBJECT -> streamItemObject(reader, onItem)+ JsonToken.BEGIN_ARRAY -> streamItemArray(reader, zoneId, onItem)+ JsonToken.BEGIN_OBJECT -> streamItemObject(reader, zoneId, onItem)JsonToken.NULL -> {reader.nextNull()0@@ -1679,6 +1710,7 @@ class OkHttpStalkerApiService @Inject constructor(private suspend fun streamItemObject(reader: JsonReader,+ zoneId: ZoneId,onItem: suspend (StalkerItemRecord) -> Unit): Int {var count = 0@@ -1695,7 +1727,7 @@ class OkHttpStalkerApiService @Inject constructor(throw invalidTokenError()}}- "js", "data", "items" -> count += streamStalkerItems(reader, onItem)+ "js", "data", "items" -> count += streamStalkerItems(reader, zoneId, onItem)else -> {// Object-keyed catalogs (e.g. `{"data":{"100":{...},"200":{...}}}`) use// numeric string keys for each item. Attempt to parse any object value as@@ -1703,7 +1735,7 @@ class OkHttpStalkerApiService @Inject constructor(// silently dropped on the streaming path.if (reader.peek() == JsonToken.BEGIN_OBJECT) {val element = JsonParser.parseReader(reader)- val item = element.asJsonObjectOrNull()?.toItemRecord()+ val item = element.asJsonObjectOrNull()?.toItemRecord(zoneId)if (item != null) {onItem(item)count++@@ -1720,6 +1752,7 @@ class OkHttpStalkerApiService @Inject constructor(private suspend fun streamItemArray(reader: JsonReader,+ zoneId: ZoneId,onItem: suspend (StalkerItemRecord) -> Unit): Int {var count = 0@@ -1727,13 +1760,13 @@ class OkHttpStalkerApiService @Inject constructor(while (reader.hasNext()) {if (reader.peek() == JsonToken.BEGIN_OBJECT) {val element = JsonParser.parseReader(reader)- val item = element.asJsonObjectOrNull()?.toItemRecord()+ val item = element.asJsonObjectOrNull()?.toItemRecord(zoneId)if (item != null) {onItem(item)count++}} else {- count += streamStalkerItems(reader, onItem)+ count += streamStalkerItems(reader, zoneId, onItem)}}reader.endArray()@@ -1784,7 +1817,6 @@ class OkHttpStalkerApiService @Inject constructor(): Int {profile.discoveryRuntime.consumeRequest()return withTransportAwareStalkerCall(request, profile) { response ->- captureResponseCookies(response, profile)if (!response.isSuccessful) {throw response.toStalkerHttpError()}@@ -1800,7 +1832,10 @@ class OkHttpStalkerApiService @Inject constructor(val reader = JsonReader(InputStreamReader(limited, charset))reader.isLenient = truetry {- streamStalkerPrograms(reader, channelIdOverride, profile.timezone.toPortalZoneId(), onProgram)+ streamStalkerPrograms(reader, channelIdOverride, profile.timezone.toPortalZoneId(), onProgram).also {+ recordResolvedLoadUrl(request, response, profile)+ captureResponseCookies(response, profile)+ }} catch (error: IllegalStateException) {throw IOException("Portal returned unreadable JSON${actionSuffix(action)}.", error)}@@ -2141,7 +2176,7 @@ class OkHttpStalkerApiService @Inject constructor(lastPageFailure = errorcontinue}- channels = pagePayload.toItemRecords()+ channels = pagePayload.toItemRecords(profile.timezone.toPortalZoneId())if (channels.isNotEmpty()) break}if (channels.isEmpty()) {@@ -2637,7 +2672,7 @@ class OkHttpStalkerApiService @Inject constructor("action" to "do_auth","JsHttpRequest" to "1-xml")- return runCatching {+ return runSuspendCatching {requestJson(url = url,profile = profile,@@ -2700,7 +2735,10 @@ class OkHttpStalkerApiService @Inject constructor(private fun resolvedLoadUrlKey(loadUrl: String, profile: StalkerDeviceProfile): String ="${sessionScopeKey(profile)}|${StalkerUrlFactory.normalizePortalUrl(loadUrl)}"- private fun Response.toStalkerHttpError(htmlErrorPage: Boolean = false): StalkerApiError {+ private fun Response.toStalkerHttpError(+ htmlErrorPage: Boolean = false,+ bodySnippet: String = ""+ ): StalkerApiError {val retryAfterMillis = header("Retry-After")?.trim()?.let { raw ->@@ -2714,14 +2752,19 @@ class OkHttpStalkerApiService @Inject constructor(}.getOrNull()}return when (code) {- 401, 403 -> if (htmlErrorPage) {+ 401 -> StalkerApiError.SessionExpired(+ message = "Portal session expired with HTTP 401.",+ httpStatus = 401,+ reason = "http_401"+ )+ 403 -> if (htmlErrorPage || !bodySnippet.isSessionAuthorizationBody()) {StalkerApiError.BlockedOrConfiguration(message = "Portal request was blocked with HTTP $code.",- portalReason = "html_error_page"+ portalReason = if (htmlErrorPage) "html_error_page" else "http_403_forbidden")} else {- StalkerApiError.Authorization(- message = "Portal authorization failed with HTTP $code.",+ StalkerApiError.SessionExpired(+ message = "Portal session expired with HTTP 403.",httpStatus = code)}@@ -2739,9 +2782,25 @@ class OkHttpStalkerApiService @Inject constructor(}}+ private fun String.isSessionAuthorizationBody(): Boolean {+ val normalized = lowercase(Locale.ROOT)+ return listOf(+ "not_valid_token",+ "invalid token",+ "token expired",+ "session expired",+ "authorization failed",+ "unauthorized"+ ).any(normalized::contains)+ }+private fun sessionScopeFor(profile: StalkerDeviceProfile): SessionScope {val now = System.currentTimeMillis()- val key = sessionScopeKey(profile)+ val key = if (profile.authEpoch > 0L) {+ sessionScopeKey(profile)+ } else {+ scopeAliases[sessionScopeAliasKey(profile)] ?: sessionScopeKey(profile)+ }val scope = sessionScopes.computeIfAbsent(key) { SessionScope(lastAccessAt = now) }scope.lastAccessAt = nowif (sessionScopes.size > MAX_SESSION_SCOPES) {@@ -2779,9 +2838,30 @@ class OkHttpStalkerApiService @Inject constructor(profile.compatibilityProfileId,profile.advancedOptions.proxy?.let { "${it.host}:${it.port}" }.orEmpty()).joinToString("\u001f")- return MessageDigest.getInstance("SHA-256")+ val digest = MessageDigest.getInstance("SHA-256")+ .digest(normalized.toByteArray(Charsets.UTF_8))+ .joinToString("") { byte -> "%02x".format(byte.toInt() and 0xff) }+ return "provider:${profile.providerId}|epoch:${profile.authEpoch}|$digest"+ }++ private fun sessionScopeAliasKey(profile: StalkerDeviceProfile): String {+ val normalized = listOf(+ profile.providerId,+ StalkerUrlFactory.normalizePortalUrl(profile.portalUrl),+ profile.macAddress.trim().uppercase(Locale.ROOT),+ profile.username.trim(),+ profile.password,+ profile.deviceProfile.trim(),+ profile.deviceId.trim(),+ profile.deviceId2.trim(),+ profile.serialNumber.trim(),+ profile.compatibilityProfileId,+ profile.advancedOptions.proxy?.let { "${it.host}:${it.port}" }.orEmpty()+ ).joinToString("\u001f")+ val digest = MessageDigest.getInstance("SHA-256").digest(normalized.toByteArray(Charsets.UTF_8)).joinToString("") { byte -> "%02x".format(byte.toInt() and 0xff) }+ return "provider:${profile.providerId}|alias|$digest"}private fun hashDiscoveryHeaderPolicy(profile: StalkerDeviceProfile): String {@@ -2954,13 +3034,13 @@ class OkHttpStalkerApiService @Inject constructor(}}- private fun JsonElement.toItemRecords(): List<StalkerItemRecord> =- extractItemEntries().mapNotNull { entry -> entry.toItemRecord() }+ private fun JsonElement.toItemRecords(zoneId: ZoneId): List<StalkerItemRecord> =+ extractItemEntries().mapNotNull { entry -> entry.toItemRecord(zoneId) }private fun JsonElement.extractItemEntries(): List<JsonObject> =extractListElements().mapNotNull { it.jsonObjectOrNull() }- private fun JsonObject.toItemRecord(): StalkerItemRecord? {+ private fun JsonObject.toItemRecord(zoneId: ZoneId): StalkerItemRecord? {val id = findString("id")?: findString("ch_id")?: findString("video_id")@@ -3030,7 +3110,7 @@ class OkHttpStalkerApiService @Inject constructor(findString("cmd"),findString("container_extension")),- addedAt = parseDateTime(findString("added")) ?: 0L,+ addedAt = parseDateTime(findString("added"), zoneId) ?: 0L,isAdult = findBoolean("censored") == true,isSeries = findBoolean("is_series") == true || findString("is_series") == "1",hasSeriesMarker = findString("is_series")?.trim()?.lowercase() in@@ -3038,7 +3118,7 @@ class OkHttpStalkerApiService @Inject constructor()}- private fun GsonJsonObject.toItemRecord(): StalkerItemRecord? {+ private fun GsonJsonObject.toItemRecord(zoneId: ZoneId): StalkerItemRecord? {val id = findString("id")?: findString("ch_id")?: findString("video_id")@@ -3108,7 +3188,7 @@ class OkHttpStalkerApiService @Inject constructor(findString("cmd"),findString("container_extension")),- addedAt = parseDateTime(findString("added")) ?: 0L,+ addedAt = parseDateTime(findString("added"), zoneId) ?: 0L,isAdult = findBoolean("censored") == true,isSeries = findBoolean("is_series") == true || findString("is_series") == "1",hasSeriesMarker = findString("is_series")?.trim()?.lowercase() in@@ -4137,6 +4217,9 @@ private fun StalkerDeviceProfile.withRecipe(discoveryBudget = discoveryBudget,discoveryRuntime = discoveryRuntime,onProgress = onProgress+ ).copy(+ providerId = providerId,+ authEpoch = authEpoch)}diff --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 22f58b48..5d6295f0 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@@ -17,6 +17,13 @@ sealed class StalkerApiError(override val portalReason: String? = null) : StalkerApiError(message, cause, httpStatus = httpStatus, portalReason = portalReason)+ class SessionExpired(+ message: String = "The portal session expired; authentication is required again.",+ cause: Throwable? = null,+ httpStatus: Int? = null,+ reason: String? = null+ ) : Authorization(message, cause = cause, httpStatus = httpStatus, portalReason = reason)+class PartialAuthorization(message: String = "Portal accepted the device profile but denied catalog access.",cause: Throwable? = null,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 1f0ed007..e54032b6 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@@ -45,6 +45,8 @@ data class StalkerDeviceProfile(val headerOverrides: Map<String, String?> = emptyMap(),val advancedOptions: StalkerAdvancedOptions = StalkerAdvancedOptions(),val providerId: Long = 0L,+ /** Authentication generation used to isolate cookies and learned endpoint state. */+ val authEpoch: Long = 0L,val protocolPreference: StalkerProtocolPreference = StalkerProtocolPreference.AUTO,val transportGrant: StalkerTransportGrant? = null,val requestedProfileId: String = StalkerCompatibilityProfileIds.AUTO,@@ -79,13 +81,13 @@ class StalkerDiscoveryRuntime(val request = requests.incrementAndGet()if (request > budget.maxRequests) {throw StalkerApiError.DiscoveryBudgetExceeded(- "Portal discovery stopped after ${budget.maxRequests} network requests."+ "Portal discovery exceeded its ${budget.maxRequests}-request budget.")}val elapsedMillis = (System.nanoTime() - startedAtNanos) / 1_000_000Lif (elapsedMillis > budget.maxElapsedMillis) {throw StalkerApiError.DiscoveryBudgetExceeded(- "Portal discovery stopped after ${budget.maxElapsedMillis / 1_000L} seconds."+ "Portal discovery exceeded its ${budget.maxElapsedMillis}ms time budget.")}}@@ -105,6 +107,9 @@ data class StalkerSession(val portalReferer: String,val token: String,val sessionScopeKey: String = "",+ val authEpoch: Long = 0L,+ val authenticatedAtMillis: Long = System.currentTimeMillis(),+ val expiresAtMillis: Long? = null,val serverCookieHeader: String = "",val effectiveAuthMode: StalkerAuthMode = StalkerAuthMode.AUTO,val portalProfile: StalkerPortalProfile = StalkerPortalProfile.MAG_BASIC,@@ -116,7 +121,12 @@ data class StalkerSession(val recipeEvidence: List<String> = emptyList(),val rediscoveryAttempted: Boolean = false,val compatibilityProfileId: String = StalkerCompatibilityProfileIds.CLASSIC_MAG250_GENERIC-)+) {+ fun isExpired(nowMillis: Long = System.currentTimeMillis()): Boolean =+ nowMillis >= (expiresAtMillis ?: (authenticatedAtMillis + STALKER_SESSION_MAX_AGE_MILLIS))+}++internal const val STALKER_SESSION_MAX_AGE_MILLIS = 30L * 60L * 1000Ldata class StalkerFingerprintEvidence(val endpointPreference: StalkerEndpointPreference = StalkerEndpointPreference.AUTO,@@ -277,6 +287,9 @@ data class StalkerProgramRecord(interface StalkerApiService {suspend fun authenticate(profile: StalkerDeviceProfile): Result<Pair<StalkerSession, StalkerProviderProfile>>+ /** Removes all in-memory transport/session state owned by one provider. */+ fun invalidateSessionScopes(providerId: Long) = Unit+suspend fun getLiveCategories(session: StalkerSession,profile: StalkerDeviceProfilediff --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 ab50be99..fe4bf868 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@@ -1,17 +1,25 @@package com.streamvault.data.remote.stalkerimport com.streamvault.data.local.dao.StalkerPortalStateDao+import com.streamvault.data.local.dao.ProviderSnapshotDaoimport com.streamvault.data.local.entity.StalkerPortalStateEntityimport com.streamvault.domain.model.ContentType+import com.streamvault.domain.model.StalkerCookieMode+import com.streamvault.domain.model.StalkerEndpointPreference+import com.streamvault.domain.model.StalkerPlaybackBackendHintimport java.security.MessageDigestimport javax.inject.Injectimport javax.inject.Singletonimport kotlinx.serialization.encodeToStringimport kotlinx.serialization.json.Json+import kotlinx.serialization.json.JsonElement+import kotlinx.serialization.json.JsonObject+import kotlinx.serialization.json.JsonPrimitive@Singletonclass StalkerPortalStateStore @Inject constructor(- private val dao: StalkerPortalStateDao+ private val dao: StalkerPortalStateDao,+ private val providerSnapshotDao: ProviderSnapshotDao? = null) {private val json = Json { ignoreUnknownKeys = true }@@ -26,11 +34,12 @@ class StalkerPortalStateStore @Inject constructor(providerId: Long,session: StalkerSession,profile: StalkerProviderProfile,- now: Long = System.currentTimeMillis()+ now: Long = System.currentTimeMillis(),+ configurationGeneration: Long? = null) {if (providerId <= 0L) returnval existing = dao.get(providerId)- dao.upsert(+ persist((existing ?: StalkerPortalStateEntity(providerId)).copy(workingEndpoint = session.loadUrl,bootstrapRecipe = profile.bootstrapRecipe.name,@@ -43,8 +52,21 @@ class StalkerPortalStateStore @Inject constructor(recipeKey(profile.bootstrapRecipe.name)),endpointFailedUntil = 0L,- validatedAt = now- )+ validatedAt = now,+ configurationGeneration = configurationGeneration+ ?: existing?.configurationGeneration+ ?: 0L,+ learningJson = authenticationLearningJson(+ existing?.learningJson,+ configurationGeneration ?: existing?.configurationGeneration ?: 0L,+ session,+ profile,+ now+ ),+ observationSource = "AUTHENTICATION",+ observedAt = now+ ),+ configurationGeneration)StalkerTelemetry.capabilityChanged(providerId, "AUTH_RECIPE", "VALIDATED")}@@ -53,9 +75,10 @@ class StalkerPortalStateStore @Inject constructor(providerId: Long,supported: Boolean,categoryFidelity: Boolean? = null,- now: Long = System.currentTimeMillis()- ) = update(providerId) { state ->- state.copy(+ now: Long = System.currentTimeMillis(),+ configurationGeneration: Long? = null+ ) = update(providerId, configurationGeneration) { state ->+ withCapability(state, "live", supported, configurationGeneration, now, "CATALOG").copy(bulkLiveSupported = supported,bulkLiveCategoryFidelity = categoryFidelity ?: state.bulkLiveCategoryFidelity,validatedAt = now@@ -68,11 +91,20 @@ class StalkerPortalStateStore @Inject constructor(providerId: Long,contentType: ContentType,supported: Boolean,- now: Long = System.currentTimeMillis()- ) = update(providerId) { state ->+ now: Long = System.currentTimeMillis(),+ configurationGeneration: Long? = null+ ) = update(providerId, configurationGeneration) { state ->+ val capability = when (contentType) {+ ContentType.MOVIE -> "vod"+ ContentType.SERIES -> "series"+ else -> null+ }+ val learned = capability?.let {+ withCapability(state, it, supported, configurationGeneration, now, "CATALOG")+ } ?: statewhen (contentType) {- ContentType.MOVIE -> state.copy(movieWildcardSupported = supported, validatedAt = now)- ContentType.SERIES -> state.copy(seriesWildcardSupported = supported, validatedAt = now)+ ContentType.MOVIE -> learned.copy(movieWildcardSupported = supported, validatedAt = now)+ ContentType.SERIES -> learned.copy(seriesWildcardSupported = supported, validatedAt = now)else -> state}}.also {@@ -86,13 +118,40 @@ class StalkerPortalStateStore @Inject constructor(suspend fun recordEpg(providerId: Long,supported: Boolean,- now: Long = System.currentTimeMillis()- ) = update(providerId) { state ->- state.copy(epgSupported = supported, validatedAt = now)+ now: Long = System.currentTimeMillis(),+ configurationGeneration: Long? = null+ ) = update(providerId, configurationGeneration) { state ->+ withCapability(state, "epg", supported, configurationGeneration, now, "GUIDE")+ .copy(epgSupported = supported, validatedAt = now)}.also {StalkerTelemetry.capabilityChanged(providerId, "EPG", if (supported) "SUPPORTED" else "UNSUPPORTED")}+ suspend fun recordPlayback(+ providerId: Long,+ playbackMode: String,+ endpointPreference: StalkerEndpointPreference,+ cookieMode: StalkerCookieMode,+ backendHint: StalkerPlaybackBackendHint,+ now: Long = System.currentTimeMillis(),+ configurationGeneration: Long? = null+ ) = update(providerId, configurationGeneration) { state ->+ val generation = configurationGeneration ?: state.configurationGeneration+ val learning = mutableLearning(state.learningJson)+ learning["configurationGeneration"] = JsonPrimitive(generation)+ learning["lastPlaybackMode"] = observationJson(playbackMode, generation, now)+ learning["endpointPreference"] = observationJson(endpointPreference.name, generation, now)+ learning["cookieMode"] = observationJson(cookieMode.name, generation, now)+ learning["playbackBackendHint"] = observationJson(backendHint.name, generation, now)+ state.copy(+ configurationGeneration = generation,+ learningJson = JsonObject(learning).toString(),+ observationSource = "PLAYBACK",+ observedAt = now,+ validatedAt = maxOf(state.validatedAt, now)+ )+ }+suspend fun recordStressCooldown(providerId: Long,cooldownUntil: Long,@@ -150,11 +209,12 @@ class StalkerPortalStateStore @Inject constructor(suspend fun markEndpointUnhealthy(providerId: Long,endpoint: String,- now: Long = System.currentTimeMillis()+ now: Long = System.currentTimeMillis(),+ configurationGeneration: Long? = null) {if (providerId <= 0L || endpoint.isBlank()) returnval until = now + ENDPOINT_COOLDOWN_MILLIS- update(providerId) { state ->+ update(providerId, configurationGeneration) { state ->val health = decodeEndpointHealth(state.endpointHealthJson).filterValues { expiry -> expiry > now }.toMutableMap()@@ -177,11 +237,12 @@ class StalkerPortalStateStore @Inject constructor(suspend fun markRecipeUnhealthy(providerId: Long,recipe: String,- now: Long = System.currentTimeMillis()+ now: Long = System.currentTimeMillis(),+ configurationGeneration: Long? = null) {if (providerId <= 0L || recipe.isBlank()) returnval until = now + RECIPE_COOLDOWN_MILLIS- update(providerId) { state ->+ update(providerId, configurationGeneration) { state ->val health = decodeEndpointHealth(state.endpointHealthJson).filterValues { expiry -> expiry > now }.toMutableMap()@@ -229,10 +290,34 @@ class StalkerPortalStateStore @Inject constructor(private suspend fun update(providerId: Long,+ configurationGeneration: Long? = null,transform: (StalkerPortalStateEntity) -> StalkerPortalStateEntity) {if (providerId <= 0L) return- dao.upsert(transform(dao.get(providerId) ?: StalkerPortalStateEntity(providerId)))+ val existing = dao.get(providerId)+ persist(+ transform(existing ?: StalkerPortalStateEntity(providerId)),+ configurationGeneration ?: existing?.configurationGeneration?.takeIf { it > 0L }+ )+ }++ private suspend fun persist(+ entity: StalkerPortalStateEntity,+ expectedGeneration: Long?+ ): Boolean {+ val snapshotDao = providerSnapshotDao+ if (snapshotDao == null) {+ dao.upsert(entity)+ return true+ }+ val currentGeneration = snapshotDao.getConfig(entity.providerId)?.configurationGeneration ?: return false+ val generation = expectedGeneration ?: currentGeneration+ return snapshotDao.compareAndSetStalkerLearning(+ entity.copy(+ configurationGeneration = generation,+ observedAt = entity.observedAt.takeIf { it > 0L } ?: System.currentTimeMillis()+ )+ )}private fun clearHealthFailures(jsonValue: String?, vararg keys: String): String {@@ -241,6 +326,78 @@ class StalkerPortalStateStore @Inject constructor(return json.encodeToString(health)}+ private fun observationJson(+ value: Any,+ generation: Long,+ observedAt: Long,+ source: String = "PLAYBACK"+ ): JsonObject = JsonObject(+ mapOf(+ "value" to value.toJsonPrimitive(),+ "configurationGeneration" to JsonPrimitive(generation),+ "source" to JsonPrimitive(source),+ "observedAt" to JsonPrimitive(observedAt)+ )+ )++ private fun authenticationLearningJson(+ existingJson: String?,+ generation: Long,+ session: StalkerSession,+ profile: StalkerProviderProfile,+ observedAt: Long+ ): String {+ val learning = mutableLearning(existingJson)+ learning["configurationGeneration"] = JsonPrimitive(generation)+ learning["profileId"] = observationJson(profile.compatibilityProfileId, generation, observedAt, "AUTHENTICATION")+ learning["profileRevision"] = observationJson(profile.profileRevision, generation, observedAt, "AUTHENTICATION")+ learning["profileVerification"] = observationJson(profile.profileVerification.name, generation, observedAt, "AUTHENTICATION")+ learning["portalProfile"] = observationJson(profile.portalProfile.name, generation, observedAt, "AUTHENTICATION")+ learning["portalFingerprint"] = observationJson(profile.portalFingerprint.name, generation, observedAt, "AUTHENTICATION")+ learning["magPreset"] = observationJson(profile.magPreset.name, generation, observedAt, "AUTHENTICATION")+ learning["protocolFamily"] = observationJson(profile.protocolFamily.name, generation, observedAt, "AUTHENTICATION")+ learning["bootstrapRecipe"] = observationJson(profile.bootstrapRecipe.name, generation, observedAt, "AUTHENTICATION")+ learning["workingEndpoint"] = observationJson(session.loadUrl, generation, observedAt, "AUTHENTICATION")+ return JsonObject(learning).toString()+ }++ private fun withCapability(+ state: StalkerPortalStateEntity,+ key: String,+ supported: Boolean,+ generationOverride: Long?,+ observedAt: Long,+ source: String+ ): StalkerPortalStateEntity {+ val generation = generationOverride ?: state.configurationGeneration+ val learning = mutableLearning(state.learningJson)+ learning["configurationGeneration"] = JsonPrimitive(generation)+ val capabilities = (learning["capabilities"] as? JsonObject)?.toMutableMap() ?: mutableMapOf()+ capabilities[key] = observationJson(+ if (supported) "SUPPORTED" else "UNSUPPORTED",+ generation,+ observedAt,+ source+ )+ learning["capabilities"] = JsonObject(capabilities)+ return state.copy(+ configurationGeneration = generation,+ learningJson = JsonObject(learning).toString(),+ observationSource = source,+ observedAt = observedAt+ )+ }++ private fun mutableLearning(value: String?): MutableMap<String, JsonElement> = runCatching {+ json.parseToJsonElement(value.orEmpty().ifBlank { "{}" }).let { it as JsonObject }.toMutableMap()+ }.getOrElse { mutableMapOf() }++ private fun Any.toJsonPrimitive(): JsonPrimitive = when (this) {+ is Boolean -> JsonPrimitive(this)+ is Number -> JsonPrimitive(this)+ else -> JsonPrimitive(toString())+ }+private fun encodeBoundedHealth(health: Map<String, Long>): String {val rateKey = rateLimitKey()val rateEntry = health[rateKey]?.let { mapOf(rateKey to it) }.orEmpty()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 ee2038a2..a65e1680 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@@ -12,7 +12,7 @@ import com.streamvault.domain.model.Movieimport com.streamvault.domain.model.PlaybackTransportModeimport com.streamvault.domain.model.PlaybackTransportPolicyimport com.streamvault.domain.model.Program-import com.streamvault.domain.model.Provider+import com.streamvault.domain.model.LegacyProvider as Providerimport com.streamvault.domain.model.ProviderStatusimport com.streamvault.domain.model.ProviderTypeimport com.streamvault.domain.model.Result@@ -35,7 +35,7 @@ import com.streamvault.domain.model.StalkerTransportChallengeReasonimport com.streamvault.domain.model.StalkerTransportGrantimport com.streamvault.domain.model.StalkerTransportModeimport com.streamvault.domain.model.StalkerTransportOrigin-import com.streamvault.domain.provider.IptvProvider+import com.streamvault.domain.provider.*import com.streamvault.domain.util.ChannelNormalizerimport com.streamvault.data.remote.xtream.extractStreamExpirationTimeimport java.io.IOException@@ -81,7 +81,7 @@ data class StalkerVodCatalogItem()class StalkerProvider(- override val providerId: Long,+ val providerId: Long,private val api: StalkerApiService,private val portalUrl: String,private val macAddress: String,@@ -110,6 +110,7 @@ class StalkerProvider(private val transportGrant: StalkerTransportGrant? = null,private val requestedProfileId: String = StalkerCompatibilityProfileIds.AUTO,private val learnedProfileId: String = "",+ private val configurationGeneration: Long = 0L,private val requireCatalogValidation: Boolean = true,private val catalogLayoutHint: CatalogLayout = CatalogLayout.UNKNOWN,private val catalogLayoutDetectionVersionHint: Int = 0,@@ -118,7 +119,13 @@ class StalkerProvider(private val discoveryCoordinator: StalkerDiscoveryCoordinator =StalkerDiscoveryCoordinator(api),private val onProgress: ((String) -> Unit)? = null-) : IptvProvider {+) : ProviderAuthenticator,+ LiveCatalogSource,+ VodCatalogSource,+ SeriesCatalogSource,+ GuideSource,+ PlaybackResolver,+ CatchUpSource {internal companion object {private const val TAG = "StalkerProvider"private const val DEFAULT_PLAYER_USER_AGENT = "Lavf53.32.100"@@ -127,6 +134,7 @@ internal companion object {private const val RESOLVED_URL_CACHE_MIN_TTL_MILLIS = 5_000Lprivate const val RESOLVED_URL_CACHE_MAX_TTL_MILLIS = 300_000Lprivate const val AUTH_FAILURE_COOLDOWN_MILLIS = 2_000L+ private const val FALLBACK_SURROGATE_FLOOR = 4_000_000_000Lconst val CATALOG_LAYOUT_DETECTION_VERSION = 1private val sharedAuthCache = ConcurrentHashMap<String, CachedAuth>()private val sharedAuthFailureCache = ConcurrentHashMap<String, CachedAuthFailure>()@@ -183,6 +191,7 @@ internal companion object {sharedAuthCache.remove(authCacheKey())sharedAuthFailureCache.remove(authCacheKey())clearResolvedStreamUrlCache()+ api.invalidateSessionScopes(providerId)}}@@ -447,7 +456,7 @@ internal companion object {providerId,ContentType.SERIES,listOf(rawId to name)- )?.get(rawId) ?: legacyStableId(ContentType.SERIES, rawId)+ )?.get(rawId) ?: fallbackStableId(ContentType.SERIES, rawId)categoryCache[ContentType.SERIES] = categoryCache[ContentType.SERIES].orEmpty().filterNot { it.rawId == rawId } + CategorySeed(projectedId, rawId, name)@@ -465,7 +474,7 @@ internal companion object {providerId,ContentType.MOVIE,listOf(rawId to name)- )?.get(rawId) ?: legacyStableId(ContentType.MOVIE, rawId)+ )?.get(rawId) ?: fallbackStableId(ContentType.MOVIE, rawId)categoryCache[ContentType.MOVIE] = categoryCache[ContentType.MOVIE].orEmpty().filterNot { it.rawId == rawId } + CategorySeed(projectedId, rawId, name)@@ -604,6 +613,18 @@ internal companion object {override suspend fun getSeriesInfo(seriesId: Long): Result<Series> =getSeriesInfo(identityResolver?.reverse(providerId, ContentType.SERIES, seriesId) ?: seriesId.toString())+ override suspend fun hydrateSeries(+ reference: com.streamvault.domain.provider.ProviderContentReference,+ current: Series+ ): Result<Series> = getSeriesInfo(+ providerSeriesId = reference.remoteId?.takeIf(String::isNotBlank)+ ?: identityResolver?.reverse(providerId, ContentType.SERIES, reference.streamId ?: current.seriesId)+ ?: (reference.streamId ?: current.seriesId).toString(),+ catalogOrigin = reference.seriesCatalogOrigin ?: current.catalogOrigin,+ episodePlaybackTemplateUrl = reference.episodePlaybackTemplateUrl+ ?: current.episodePlaybackTemplateUrl+ )+suspend fun getSeriesInfo(providerSeriesId: String,catalogOrigin: SeriesCatalogOrigin = SeriesCatalogOrigin.NATIVE,@@ -1028,12 +1049,109 @@ is Result.Success -> {throw UnsupportedOperationException("Stalker stream URLs require a command token context.")}+ override suspend fun resolve(+ request: com.streamvault.domain.provider.PlaybackRequest+ ): Result<com.streamvault.domain.provider.ResolvedPlayback> {+ val token = StalkerUrlFactory.parseInternalStreamUrl(request.sourceUrl)+ val directKind = when (request.contentType) {+ ContentType.LIVE -> StalkerStreamKind.LIVE+ ContentType.VOD,+ ContentType.MOVIE -> StalkerStreamKind.MOVIE+ ContentType.SERIES_EPISODE,+ ContentType.SERIES -> StalkerStreamKind.EPISODE+ }+ val directUrl = token?.let { request.sourceUrl } ?: repairDirectPlaybackUrl(+ request.sourceUrl,+ directKind,+ request.content.streamId+ )+ if (token == null && !UrlSecurityPolicy.isAllowedStreamEntryUrl(directUrl)) {+ return Result.error("Stalker playback URL is not allowed")+ }+ val descriptor = token?.playbackDescriptor+ ?: buildStalkerPlaybackDescriptor(+ primaryCmd = directUrl,+ capabilities = StalkerPortalCapabilities()+ )+ return when (val result = resolvePlaybackInfo(+ kind = token?.kind ?: directKind,+ descriptor = descriptor,+ seriesNumber = token?.seriesNumber,+ archiveStartSeconds = token?.archiveStartSeconds,+ archiveEndSeconds = token?.archiveEndSeconds+ )) {+ is Result.Success -> {+ val info = result.data+ portalStateStore?.recordPlayback(+ providerId = providerId,+ playbackMode = info.playbackMode.name,+ endpointPreference = info.endpointPreference,+ cookieMode = info.cookieMode,+ backendHint = info.backendHint,+ configurationGeneration = configurationGeneration+ )+ Result.success(+ com.streamvault.domain.provider.ResolvedPlayback(+ url = info.url,+ containerExtension = token?.containerExtension ?: request.containerExtension,+ headers = info.headers,+ userAgent = info.userAgent,+ playbackTransportPolicy = info.transportPolicy,+ allowInvalidSsl = info.allowInvalidSsl,+ proxyHost = info.proxyHost,+ proxyPort = info.proxyPort+ )+ )+ }+ is Result.Error -> Result.error(result.message, result.exception)+ is Result.Loading -> Result.error("Unexpected loading state")+ }+ }++ private fun repairDirectPlaybackUrl(+ url: String,+ kind: StalkerStreamKind,+ fallbackStreamId: Long?+ ): String {+ if (kind != StalkerStreamKind.LIVE || fallbackStreamId == null || fallbackStreamId <= 0L) return url+ val uri = runCatching { URI(url) }.getOrNull() ?: return url+ if (!uri.path.orEmpty().lowercase().endsWith("/play/live.php")) return url+ val rawQuery = uri.rawQuery ?: return url+ val parts = rawQuery.split('&').filter(String::isNotBlank)+ if (parts.isEmpty()) return url+ var hasStream = false+ var changed = false+ val repaired = parts.map { part ->+ if (part.substringBefore('=', "").lowercase() != "stream") return@map part+ hasStream = true+ if (part.substringAfter('=', "").isNotBlank()) return@map part+ changed = true+ "stream=$fallbackStreamId"+ }.toMutableList()+ if (!hasStream && rawQuery.contains("play_token=")) {+ repaired += "stream=$fallbackStreamId"+ changed = true+ }+ if (!changed) return url+ return URI(uri.scheme, uri.authority, uri.path, repaired.joinToString("&"), uri.fragment).toString()+ }+override suspend fun buildCatchUpUrl(streamId: Long, start: Long, end: Long): String? =buildCatchUpUrls(streamId, start, end).firstOrNull()override suspend fun buildCatchUpUrls(streamId: Long, start: Long, end: Long): List<String> =buildCatchUpUrls(streamId, start, end, sourceStreamUrl = null, sourceCatchUpSource = null)+ override suspend fun buildCatchUpUrls(+ request: com.streamvault.domain.provider.CatchUpRequest+ ): List<String> = buildCatchUpUrls(+ streamId = request.streamId,+ start = request.start,+ end = request.end,+ sourceStreamUrl = request.sourceStreamUrl,+ sourceCatchUpSource = request.sourceCatchUpTemplate+ )+suspend fun buildCatchUpUrls(streamId: Long,start: Long,@@ -1185,7 +1303,7 @@ is Result.Success -> {if (ids.isEmpty()) returnval resolved = identityResolver?.resolveAll(providerId, type, ids)?: ids.associateWith { rawId ->- rawId.toLongOrNull()?.takeIf { it > 0L } ?: legacyStableId(type, rawId)+ rawId.toLongOrNull()?.takeIf { it > 0L } ?: fallbackStableId(type, rawId)}resolved.forEach { (rawId, surrogateId) ->remoteIdentityCache[type to rawId] = surrogateId@@ -1201,7 +1319,7 @@ is Result.Success -> {if (resolved == null) {records.forEach { record ->val rawId = record.id.ifBlank { record.name }.trim()- remoteIdentityCache[type to rawId] = legacyStableId(type, rawId)+ remoteIdentityCache[type to rawId] = fallbackStableId(type, rawId)}} else {resolved.forEach { (rawId, surrogateId) -> remoteIdentityCache[type to rawId] = surrogateId }@@ -1235,9 +1353,18 @@ is Result.Success -> {authMutex.withLock {val cachedSession = sessionCacheval cachedProfile = accountProfileCache- if (cachedSession != null && cachedProfile != null) {+ if (cachedSession != null && cachedProfile != null &&+ !cachedSession.isExpired() &&+ cachedProfile.expirationDate?.let { it > System.currentTimeMillis() } != false+ ) {return@withLock Result.success(cachedSession to cachedProfile)}+ if (cachedSession != null || cachedProfile != null) {+ sessionCache = null+ accountProfileCache = null+ sharedAuthCache.remove(authCacheKey())+ api.invalidateSessionScopes(providerId)+ }(authFailureCache ?: sharedAuthFailureCache[authCacheKey()])?.let { failure ->if (failure.expiresAt > System.currentTimeMillis()) {return@withLock Result.error(failure.message, failure.exception)@@ -1246,9 +1373,15 @@ is Result.Success -> {sharedAuthFailureCache.remove(authCacheKey(), failure)}sharedAuthCache[authCacheKey()]?.let { cachedAuth ->- sessionCache = cachedAuth.session- accountProfileCache = cachedAuth.profile- return@withLock Result.success(cachedAuth.session to cachedAuth.profile)+ if (!cachedAuth.session.isExpired() &&+ cachedAuth.profile.expirationDate?.let { it > System.currentTimeMillis() } != false+ ) {+ sessionCache = cachedAuth.session+ accountProfileCache = cachedAuth.profile+ return@withLock Result.success(cachedAuth.session to cachedAuth.profile)+ }+ sharedAuthCache.remove(authCacheKey(), cachedAuth)+ api.invalidateSessionScopes(providerId)}val persistedState = portalStateStore?.getValidated(providerId)@@ -1316,7 +1449,11 @@ is Result.Success -> {val finalAuthResult = when {initialAuthResult !is Result.Error -> initialAuthResultpersistedEndpointUrl != null -> {- portalStateStore?.markEndpointUnhealthy(providerId, persistedEndpointUrl)+ portalStateStore?.markEndpointUnhealthy(+ providerId,+ persistedEndpointUrl,+ configurationGeneration = configurationGeneration+ )StalkerTelemetry.strategySelected(providerId, "AUTH_ENDPOINT_AUTO", "CACHED_ENDPOINT_FAILED")discoveryCoordinator.authenticate(profile.copy(@@ -1359,13 +1496,18 @@ is Result.Success -> {portalStateStore?.recordAuthentication(providerId = providerId,session = authResult.data.first,- profile = authResult.data.second+ profile = authResult.data.second,+ configurationGeneration = configurationGeneration)Result.success(authResult.data)}is Result.Error -> {rawPersistedRecipe?.let { failedRecipe ->- portalStateStore?.markRecipeUnhealthy(providerId, failedRecipe.name)+ portalStateStore?.markRecipeUnhealthy(+ providerId,+ failedRecipe.name,+ configurationGeneration = configurationGeneration+ )}authFailureCache = CachedAuthFailure(expiresAt = System.currentTimeMillis() + AUTH_FAILURE_COOLDOWN_MILLIS,@@ -1383,19 +1525,35 @@ is Result.Success -> {portalStateStore?.getValidated(providerId)suspend fun recordBulkLiveCapability(supported: Boolean, categoryFidelity: Boolean? = null) {- portalStateStore?.recordBulkLive(providerId, supported, categoryFidelity)+ portalStateStore?.recordBulkLive(+ providerId,+ supported,+ categoryFidelity,+ configurationGeneration = configurationGeneration+ )}suspend fun recordWildcardCapability(contentType: ContentType, supported: Boolean) {- portalStateStore?.recordWildcard(providerId, contentType, supported)+ portalStateStore?.recordWildcard(+ providerId,+ contentType,+ supported,+ configurationGeneration = configurationGeneration+ )}suspend fun recordEpgCapability(supported: Boolean) {- portalStateStore?.recordEpg(providerId, supported)+ portalStateStore?.recordEpg(+ providerId,+ supported,+ configurationGeneration = configurationGeneration+ )}private fun currentDeviceProfile(): StalkerDeviceProfile {- accountProfileCache?.let { learned -> return buildLearnedDeviceProfile(learned) }+ accountProfileCache?.let { learned ->+ return buildLearnedDeviceProfile(learned).copy(authEpoch = sessionCache?.authEpoch ?: 0L)+ }return buildStalkerDeviceProfile(portalUrl = portalUrl,macAddress = normalizedMacAddress(),@@ -1425,7 +1583,10 @@ is Result.Success -> {requireCatalogValidation = requireCatalogValidation,allowCompatibilityDiscovery = providerId <= 0L,onProgress = onProgress- ).copy(providerId = providerId)+ ).copy(+ providerId = providerId,+ authEpoch = sessionCache?.authEpoch ?: 0L+ )}private fun buildLearnedDeviceProfile(profile: StalkerProviderProfile): StalkerDeviceProfile {@@ -1459,7 +1620,10 @@ is Result.Success -> {requireCatalogValidation = requireCatalogValidation,allowCompatibilityDiscovery = providerId <= 0L,onProgress = onProgress- ).copy(providerId = providerId)+ ).copy(+ providerId = providerId,+ authEpoch = sessionCache?.authEpoch ?: 0L+ )}private fun learnedCompatibilityProfileId(profile: StalkerProviderProfile): String =@@ -2267,16 +2431,38 @@ private fun playbackTransportChallengeFor(url: String): StalkerTransportChallengprivate fun stableItemId(type: ContentType, rawId: String): Long =remoteIdentityCache[type to rawId.trim()]?: rawId.trim().toLongOrNull()?.takeIf { it > 0L }- ?: legacyStableId(type, rawId)+ ?: fallbackStableId(type, rawId)private fun syntheticCategoryId(type: ContentType, seed: String): Long {remoteIdentityCache[type to seed.trim()]?.let { return it }- return legacyStableId(type, seed)+ return fallbackStableId(type, seed)}- private fun legacyStableId(type: ContentType, seed: String): Long {- val normalized = "$providerId/${type.name}/${seed.trim().lowercase(Locale.ROOT)}"- return (normalized.hashCode().toLong() and 0x7fff_ffffL).coerceAtLeast(1L)+ /**+ * Test/fallback path used when a provider is created without the persistent resolver.+ * Keep the SHA-derived value for stability, but resolve collisions in this provider+ * instance instead of allowing two remote records to share a local Long ID.+ */+ private fun fallbackStableId(type: ContentType, rawId: String): Long {+ val normalized = rawId.trim()+ val key = type to normalized+ return synchronized(remoteIdentityCache) {+ remoteIdentityCache[key] ?: run {+ val preferred = stalkerStableHashId(providerId, type, normalized)+ val used = remoteIdentityCache+ .filterKeys { (existingType, _) -> existingType == type }+ .values+ .toSet()+ val candidate = if (preferred !in used) {+ preferred+ } else {+ generateSequence(FALLBACK_SURROGATE_FLOOR) { it + 1L }+ .first { it !in used }+ }+ remoteIdentityCache[key] = candidate+ candidate+ }+ }}private fun normalizedMacAddress(): String =diff --git a/data/src/main/java/com/streamvault/data/remote/stalker/StalkerRemoteIdentityResolver.kt b/data/src/main/java/com/streamvault/data/remote/stalker/StalkerRemoteIdentityResolver.ktindex 286e62d0..575a621a 100644--- a/data/src/main/java/com/streamvault/data/remote/stalker/StalkerRemoteIdentityResolver.kt+++ b/data/src/main/java/com/streamvault/data/remote/stalker/StalkerRemoteIdentityResolver.kt@@ -121,8 +121,7 @@ class StalkerRemoteIdentityResolver private constructor(?: (HIGH_SURROGATE_FLOOR - 1L)) + 1L).coerceAtMost(Long.MAX_VALUE - 1L)private fun legacyId(providerId: Long, contentType: ContentType, rawId: String): Long {- val normalized = "$providerId/${contentType.name}/${rawId.trim().lowercase(Locale.ROOT)}"- return (normalized.hashCode().toLong() and 0x7fff_ffffL).coerceAtLeast(1L)+ return stalkerStableHashId(providerId, contentType, rawId)}private companion object {diff --git a/data/src/main/java/com/streamvault/data/remote/stalker/StalkerSupport.kt b/data/src/main/java/com/streamvault/data/remote/stalker/StalkerSupport.ktindex 494d8556..bab022bb 100644--- a/data/src/main/java/com/streamvault/data/remote/stalker/StalkerSupport.kt+++ b/data/src/main/java/com/streamvault/data/remote/stalker/StalkerSupport.kt@@ -2,11 +2,22 @@ package com.streamvault.data.remote.stalkerimport com.streamvault.data.local.entity.CategoryEntityimport com.streamvault.domain.model.ContentType+import java.security.MessageDigestimport java.util.Localeinternal fun stalkerSyntheticId(providerId: Long, type: ContentType, seed: String): Long {+ return stalkerStableHashId(providerId, type, seed)+}++internal fun stalkerStableHashId(providerId: Long, type: ContentType, seed: String): Long {val normalized = "$providerId/${type.name}/${seed.trim().lowercase(Locale.ROOT)}"- return (normalized.hashCode().toLong() and 0x7fff_ffffL).coerceAtLeast(1L)+ val digest = MessageDigest.getInstance("SHA-256")+ .digest(normalized.toByteArray(Charsets.UTF_8))+ var value = 0L+ repeat(Long.SIZE_BYTES) { index ->+ value = (value shl 8) or (digest[index].toLong() and 0xffL)+ }+ return (value and Long.MAX_VALUE).coerceAtLeast(1L)}internal fun StalkerCategoryRecord.toCategoryEntity(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.ktindex 5b39fb94..8b67be4f 100644--- a/data/src/main/java/com/streamvault/data/remote/stalker/StalkerTransportGrantFactory.kt+++ b/data/src/main/java/com/streamvault/data/remote/stalker/StalkerTransportGrantFactory.kt@@ -1,13 +1,13 @@package com.streamvault.data.remote.stalker-import com.streamvault.data.local.entity.ProviderEntity+import com.streamvault.domain.model.LegacyProvider as Providerimport com.streamvault.domain.model.StalkerTransportGrantimport com.streamvault.domain.model.StalkerTransportModeimport com.streamvault.domain.model.StalkerTransportOriginimport java.net.URI/** Rebuilds the persisted user-approved transport policy for lazy Stalker requests. */-internal fun ProviderEntity.stalkerTransportGrantOrNull(): StalkerTransportGrant? {+internal fun Provider.stalkerTransportGrantOrNull(): StalkerTransportGrant? {if (stalkerTransportMode != StalkerTransportMode.USER_ACCEPTED_HTTP &&stalkerTransportMode != StalkerTransportMode.USER_ACCEPTED_UNVERIFIED_HTTPS &&stalkerTransportMode != StalkerTransportMode.VERIFIED_HTTPSdiff --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 34949818..cf10da10 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@@ -6,7 +6,8 @@ import com.streamvault.data.remote.dto.*import com.streamvault.data.util.AdultContentClassifierimport com.streamvault.data.util.runSuspendCatchingimport com.streamvault.domain.model.*-import com.streamvault.domain.provider.IptvProvider+import com.streamvault.domain.model.LegacyProvider as Provider+import com.streamvault.domain.provider.*import com.streamvault.domain.util.ChannelNormalizerimport java.time.Instantimport java.time.LocalDate@@ -27,7 +28,7 @@ import kotlinx.coroutines.sync.withLock* Converts Xtream API responses to domain models.*/class XtreamProvider(- override val providerId: Long,+ val providerId: Long,private val api: XtreamApiService,private val serverUrl: String,private val username: String,@@ -36,7 +37,13 @@ class XtreamProvider(private val useTextClassification: Boolean = true,private val enableBase64TextCompatibility: Boolean = false,private val requestProfile: HttpRequestProfile = HttpRequestProfile(ownerTag = "provider:$providerId/xtream")-) : IptvProvider {+) : ProviderAuthenticator,+ LiveCatalogSource,+ VodCatalogSource,+ SeriesCatalogSource,+ GuideSource,+ PlaybackResolver,+ CatchUpSource {companion object {private const val TAG = "XtreamProvider"private const val STREAM_SUMMARY_BATCH_SIZE = 500diff --git a/data/src/main/java/com/streamvault/data/remote/xtream/XtreamStreamUrlResolver.kt b/data/src/main/java/com/streamvault/data/remote/xtream/XtreamStreamUrlResolver.ktindex ddc54ead..735b4ef3 100644--- a/data/src/main/java/com/streamvault/data/remote/xtream/XtreamStreamUrlResolver.kt+++ b/data/src/main/java/com/streamvault/data/remote/xtream/XtreamStreamUrlResolver.kt@@ -1,39 +1,18 @@package com.streamvault.data.remote.xtream-import com.streamvault.data.local.dao.ProviderDao-import com.streamvault.data.local.entity.ProviderEntity-import com.streamvault.data.preferences.PreferencesRepository-import com.streamvault.data.remote.jellyfin.buildJellyfinAuthorizationHeader-import com.streamvault.data.remote.http.toGenericRequestProfile-import com.streamvault.data.remote.stalker.StalkerProvider-import com.streamvault.data.remote.stalker.StalkerApiService-import com.streamvault.data.remote.stalker.StalkerPlaybackMode+import com.streamvault.data.provider.ProviderCapabilityResolverimport com.streamvault.data.remote.stalker.StalkerPlaybackResolutionExceptionimport com.streamvault.data.remote.stalker.StalkerStreamKind-import com.streamvault.data.remote.stalker.StalkerTrafficCoordinatorimport com.streamvault.data.remote.stalker.StalkerUrlFactory-import com.streamvault.data.remote.stalker.buildStalkerPlaybackDescriptor-import com.streamvault.data.security.CredentialCrypto-import com.streamvault.data.util.UrlSecurityPolicyimport com.streamvault.domain.model.ContentType-import com.streamvault.domain.model.LiveStreamFormatModeimport com.streamvault.domain.model.PlaybackTransportPolicy-import com.streamvault.domain.model.StalkerAuthMode-import com.streamvault.domain.model.StalkerBootstrapRecipe-import com.streamvault.domain.model.StalkerCookieMode-import com.streamvault.domain.model.StalkerEndpointPreference-import com.streamvault.domain.model.StalkerMagPreset-import com.streamvault.domain.model.StalkerPlaybackBackendHint-import com.streamvault.domain.model.StalkerPortalFingerprint-import com.streamvault.domain.model.ProviderType-import com.streamvault.domain.model.StalkerTransportGrant-import com.streamvault.domain.model.StalkerTransportMode-import com.streamvault.domain.model.StalkerTransportOrigin+import com.streamvault.domain.model.Result+import com.streamvault.domain.provider.CapabilityResolution+import com.streamvault.domain.provider.PlaybackRequest+import com.streamvault.domain.provider.ProviderContentReferenceimport java.net.URI-import java.util.concurrent.ConcurrentHashMapimport javax.inject.Injectimport javax.inject.Singleton-import kotlinx.coroutines.flow.firstdata class ResolvedStreamUrl(val url: String,@@ -47,44 +26,11 @@ data class ResolvedStreamUrl(val proxyPort: Int? = null)+/** Provider-neutral playback entry point. Provider selection is owned by the capability registry. */@Singletonclass XtreamStreamUrlResolver @Inject constructor(- private val providerDao: ProviderDao,- private val credentialCrypto: CredentialCrypto,- private val stalkerApiService: StalkerApiService,- private val preferencesRepository: PreferencesRepository+ private val providerCapabilities: ProviderCapabilityResolver) {- private data class CachedStalkerProvider(- val serverUrl: String,- val macAddress: String,- val authMode: StalkerAuthMode,- val username: String,- val password: String,- val httpUserAgent: String,- val httpHeaders: String,- val portalFingerprint: StalkerPortalFingerprint,- val magPreset: StalkerMagPreset,- val bootstrapRecipe: StalkerBootstrapRecipe,- val endpointPreference: StalkerEndpointPreference,- val cookieMode: StalkerCookieMode,- val playbackBackendHint: StalkerPlaybackBackendHint,- val deviceProfile: String,- val timezone: String,- val locale: String,- val serialNumber: String,- val deviceId: String,- val deviceId2: String,- val signature: String,- val stalkerAdvancedOptionsJson: String,- val transportMode: StalkerTransportMode,- val transportOrigin: String,- val tlsSpkiSha256: String,- val transportConsentAt: Long,- val provider: StalkerProvider- )-- private val stalkerProviders = ConcurrentHashMap<Long, CachedStalkerProvider>()-fun isInternalStreamUrl(url: String?): Boolean =XtreamUrlFactory.isInternalStreamUrl(url) || StalkerUrlFactory.isInternalStreamUrl(url)@@ -104,11 +50,6 @@ class XtreamStreamUrlResolver @Inject constructor(preferStableUrl = preferStableUrl)?.url- /**- * @param preferStableUrl when true, skip the tokenized direct-source URL and return- * the credential-based portal URL instead. Use this for long-lived sessions (e.g.- * Chromecast) where the token may expire before the session ends.- */suspend fun resolveWithMetadata(url: String,fallbackProviderId: Long? = null,@@ -119,480 +60,112 @@ class XtreamStreamUrlResolver @Inject constructor(): ResolvedStreamUrl? {val xtreamToken = XtreamUrlFactory.parseInternalStreamUrl(url)val stalkerToken = StalkerUrlFactory.parseInternalStreamUrl(url)- val providerId = xtreamToken?.providerId ?: stalkerToken?.providerId ?: fallbackProviderId?.takeIf { it > 0 }- val provider = providerId?.let { id -> providerDao.getById(id) }-- if (url.isNotBlank() && !XtreamUrlFactory.isInternalStreamUrl(url) && !StalkerUrlFactory.isInternalStreamUrl(url)) {- if (provider?.type == ProviderType.XTREAM_CODES) {- resolveDirectXtreamUrl(- provider = provider,- url = url,- fallbackStreamId = fallbackStreamId,- fallbackContentType = fallbackContentType,- fallbackContainerExtension = fallbackContainerExtension- )?.let { return it }- }- if (provider?.type == ProviderType.STALKER_PORTAL) {- resolveDirectStalkerUrl(- provider = provider,- url = url,- fallbackStreamId = fallbackStreamId,- fallbackContentType = fallbackContentType,- fallbackContainerExtension = fallbackContainerExtension- )?.let { return it }- }- if (provider?.type == ProviderType.JELLYFIN) {- resolveDirectJellyfinUrl(- provider = provider,- url = url,- fallbackContainerExtension = fallbackContainerExtension- )?.let { return it }- }- return provider.applyPlaybackRequestProfile(- ResolvedStreamUrl(- url = url,- expirationTime = extractStreamExpirationTime(url)- )+ val providerId = xtreamToken?.providerId+ ?: stalkerToken?.providerId+ ?: fallbackProviderId?.takeIf { it > 0L }+ ?: return url.takeIf(String::isNotBlank)?.toPassthrough(fallbackContainerExtension)+ val contentType = fallbackContentType+ ?: xtreamToken?.kind?.toContentType()+ ?: stalkerToken?.kind?.toContentType()+ ?: ContentType.LIVE+ val streamId = xtreamToken?.streamId+ ?: stalkerToken?.itemId+ ?: fallbackStreamId?.takeIf { it > 0L }++ val capabilitySet = when (val resolution = providerCapabilities.resolve(providerId)) {+ is CapabilityResolution.Available -> resolution.capability+ is CapabilityResolution.ConfigurationError -> return unavailable(url, resolution.reason, stalkerToken != null)+ is CapabilityResolution.Restricted -> return unavailable(url, resolution.reason, stalkerToken != null)+ is CapabilityResolution.Unsupported -> return unavailable(url, resolution.reason, stalkerToken != null)+ }+ val playback = when (val resolution = capabilitySet.playback()) {+ is CapabilityResolution.Available -> resolution.capability+ is CapabilityResolution.ConfigurationError -> return unavailable(url, resolution.reason, stalkerToken != null)+ is CapabilityResolution.Restricted -> return unavailable(url, resolution.reason, stalkerToken != null)+ is CapabilityResolution.Unsupported -> return unavailable(url, resolution.reason, stalkerToken != null)+ }+ return when (val result = playback.resolve(+ PlaybackRequest(+ sourceUrl = url,+ content = ProviderContentReference(+ providerId = providerId,+ streamId = streamId+ ),+ contentType = contentType,+ containerExtension = xtreamToken?.containerExtension+ ?: stalkerToken?.containerExtension+ ?: fallbackContainerExtension,+ preferStableUrl = preferStableUrl)- }-- val resolvedProviderId = providerId ?: return null- val resolvedProvider = provider ?: return null- return when (resolvedProvider.type) {- ProviderType.XTREAM_CODES -> {- val kind = xtreamToken?.kind ?: fallbackContentType?.let(XtreamUrlFactory::kindForContentType) ?: return null- val streamId = xtreamToken?.streamId ?: fallbackStreamId?.takeIf { it > 0 } ?: return null- val ext = xtreamToken?.containerExtension ?: fallbackContainerExtension- val resolvedExt = resolveLiveContainerExtension(kind, ext)- val directSource = xtreamToken?.directSource- ?.takeIf { kind != XtreamStreamKind.LIVE }- ?.takeIf(UrlSecurityPolicy::isAllowedStreamEntryUrl)- val decryptedPassword = credentialCrypto.decryptIfNeeded(resolvedProvider.password)-- val fallbackResolvedUrl = XtreamUrlFactory.buildPlaybackUrl(- serverUrl = resolvedProvider.serverUrl,- username = resolvedProvider.username,- password = decryptedPassword,- kind = kind,- streamId = streamId,- containerExtension = resolvedExt- )- val resolvedUrl = if (preferStableUrl) fallbackResolvedUrl else (directSource ?: fallbackResolvedUrl)-- resolvedProvider.applyPlaybackRequestProfile(- ResolvedStreamUrl(- url = resolvedUrl,- expirationTime = extractStreamExpirationTime(resolvedUrl),- containerExtension = resolvedExt- )- )- }- ProviderType.STALKER_PORTAL -> {- val token = stalkerToken ?: return url.takeIf { it.isNotBlank() }?.let { passthroughUrl ->- ResolvedStreamUrl(- url = passthroughUrl,- expirationTime = extractStreamExpirationTime(passthroughUrl)- )- }- val playbackInfo = when (- val resolvedResult = getOrCreateStalkerProvider(resolvedProvider)- .resolvePlaybackInfo(- kind = token.kind,- descriptor = token.playbackDescriptor,- seriesNumber = token.seriesNumber,- archiveStartSeconds = token.archiveStartSeconds,- archiveEndSeconds = token.archiveEndSeconds- )- ) {- is com.streamvault.domain.model.Result.Success -> resolvedResult.data- is com.streamvault.domain.model.Result.Error -> throw StalkerPlaybackResolutionException(- resolvedResult.message,- resolvedResult.exception- )- else -> return null- }- persistStalkerPlaybackLearning(resolvedProvider, playbackInfo)+ )) {+ is Result.Success -> result.data.let { resolved ->ResolvedStreamUrl(- url = playbackInfo.url,- expirationTime = extractStreamExpirationTime(playbackInfo.url),- containerExtension = token.containerExtension ?: fallbackContainerExtension,- headers = playbackInfo.headers,- userAgent = playbackInfo.userAgent,- playbackTransportPolicy = playbackInfo.transportPolicy,- allowInvalidSsl = playbackInfo.allowInvalidSsl,- proxyHost = playbackInfo.proxyHost,- proxyPort = playbackInfo.proxyPort- )- }- ProviderType.M3U -> url.takeIf { it.isNotBlank() }?.let { passthroughUrl ->- resolvedProvider.applyPlaybackRequestProfile(- ResolvedStreamUrl(- url = passthroughUrl,- expirationTime = extractStreamExpirationTime(passthroughUrl)- )- )- }- ProviderType.M3U,- ProviderType.JELLYFIN -> null- }- }-- private fun ProviderEntity?.applyPlaybackRequestProfile(resolved: ResolvedStreamUrl): ResolvedStreamUrl {- if (this == null || type == ProviderType.STALKER_PORTAL) {- return resolved- }- val requestProfile = toGenericRequestProfile(ownerTag = "provider:$id/playback")- return resolved.copy(- headers = requestProfile.headers + resolved.headers,- userAgent = resolved.userAgent?.takeIf { it.isNotBlank() } ?: requestProfile.userAgent- )- }-- private suspend fun resolveDirectXtreamUrl(- provider: ProviderEntity,- url: String,- fallbackStreamId: Long?,- fallbackContentType: ContentType?,- fallbackContainerExtension: String?- ): ResolvedStreamUrl? {- val parsed = XtreamUrlFactory.parseCredentialedStreamUrl(url, provider.id)- val kind = parsed?.kind ?: fallbackContentType?.let(XtreamUrlFactory::kindForContentType) ?: return null- if (kind != XtreamStreamKind.LIVE) {- return null- }- val streamId = parsed?.streamId ?: fallbackStreamId?.takeIf { it > 0L } ?: return null- val ext = parsed?.containerExtension ?: fallbackContainerExtension- val resolvedExt = resolveLiveContainerExtension(kind, ext)- val decryptedPassword = credentialCrypto.decryptIfNeeded(provider.password)- val resolvedUrl = XtreamUrlFactory.buildPlaybackUrl(- serverUrl = provider.serverUrl,- username = provider.username,- password = decryptedPassword,- kind = kind,- streamId = streamId,- containerExtension = resolvedExt- )- return provider.applyPlaybackRequestProfile(- ResolvedStreamUrl(- url = resolvedUrl,- expirationTime = extractStreamExpirationTime(resolvedUrl),- containerExtension = resolvedExt- )- )- }-- private suspend fun resolveLiveContainerExtension(- kind: XtreamStreamKind,- containerExtension: String?- ): String? {- if (kind != XtreamStreamKind.LIVE) {- return containerExtension- }- return when (preferencesRepository.playerLiveStreamFormatMode.first()) {- LiveStreamFormatMode.AUTO -> containerExtension- LiveStreamFormatMode.HLS -> "m3u8"- LiveStreamFormatMode.MPEG_TS -> "ts"- }- }-- private fun resolveDirectJellyfinUrl(- provider: ProviderEntity,- url: String,- fallbackContainerExtension: String?- ): ResolvedStreamUrl? {- if (url.isBlank()) {- return null- }- val decryptedPassword = credentialCrypto.decryptIfNeeded(provider.password)- return provider.applyPlaybackRequestProfile(- ResolvedStreamUrl(- url = url,- expirationTime = extractStreamExpirationTime(url),- containerExtension = fallbackContainerExtension,- headers = mapOf(- "Authorization" to buildJellyfinAuthorizationHeader(- provider.serverUrl,- provider.username,- decryptedPassword- )+ url = resolved.url,+ expirationTime = resolved.expirationTime ?: extractStreamExpirationTime(resolved.url),+ containerExtension = resolved.containerExtension,+ headers = resolved.headers,+ userAgent = resolved.userAgent,+ playbackTransportPolicy = resolved.playbackTransportPolicy,+ allowInvalidSsl = resolved.allowInvalidSsl,+ proxyHost = resolved.proxyHost,+ proxyPort = resolved.proxyPort)- )- )- }-- private suspend fun resolveDirectStalkerUrl(- provider: ProviderEntity,- url: String,- fallbackStreamId: Long?,- fallbackContentType: ContentType?,- fallbackContainerExtension: String?- ): ResolvedStreamUrl? {- val kind = when (fallbackContentType) {- ContentType.LIVE -> StalkerStreamKind.LIVE- ContentType.MOVIE -> StalkerStreamKind.MOVIE- ContentType.SERIES_EPISODE -> StalkerStreamKind.EPISODE- else -> return null- }- val repairedUrl = repairDirectStalkerUrl(url, kind, fallbackStreamId)- if (!UrlSecurityPolicy.isAllowedStreamEntryUrl(repairedUrl)) {- return null- }- val descriptor = buildStalkerPlaybackDescriptor(- primaryCmd = repairedUrl,- capabilities = com.streamvault.data.remote.stalker.StalkerPortalCapabilities()- )- val playbackInfo = when (val resolvedResult = getOrCreateStalkerProvider(provider).resolvePlaybackInfo(kind, descriptor)) {- is com.streamvault.domain.model.Result.Success -> resolvedResult.data- is com.streamvault.domain.model.Result.Error -> throw StalkerPlaybackResolutionException(- resolvedResult.message,- resolvedResult.exception- )- else -> return null- }- persistStalkerPlaybackLearning(provider, playbackInfo)- return ResolvedStreamUrl(- url = playbackInfo.url,- expirationTime = extractStreamExpirationTime(playbackInfo.url),- containerExtension = fallbackContainerExtension,- headers = playbackInfo.headers,- userAgent = playbackInfo.userAgent,- playbackTransportPolicy = playbackInfo.transportPolicy,- allowInvalidSsl = playbackInfo.allowInvalidSsl,- proxyHost = playbackInfo.proxyHost,- proxyPort = playbackInfo.proxyPort- )- }-- private fun repairDirectStalkerUrl(- url: String,- kind: StalkerStreamKind,- fallbackStreamId: Long?- ): String {- if (kind != StalkerStreamKind.LIVE || fallbackStreamId == null || fallbackStreamId <= 0L) {- return url- }- val uri = runCatching { URI(url) }.getOrNull() ?: return url- val path = uri.path?.lowercase() ?: return url- if (!path.endsWith("/play/live.php")) {- return url- }-- val rawQuery = uri.rawQuery ?: return url- val parts = rawQuery.split('&').filter { it.isNotBlank() }- if (parts.isEmpty()) {- return url- }-- var hasStream = false- var changed = false- val repairedParts = parts.map { part ->- val key = part.substringBefore('=', missingDelimiterValue = "").lowercase()- if (key != "stream") {- return@map part}- hasStream = true- val value = part.substringAfter('=', missingDelimiterValue = "")- if (value.isNotBlank()) {- return@map part+ is Result.Error -> {+ if (stalkerToken != null) {+ throw StalkerPlaybackResolutionException(result.message, result.exception)+ }+ null}- changed = true- "stream=$fallbackStreamId"- }.toMutableList()-- if (!hasStream && rawQuery.contains("play_token=")) {- repairedParts += "stream=$fallbackStreamId"- changed = true+ is Result.Loading -> null}-- if (!changed) {- return url- }-- return URI(- uri.scheme,- uri.authority,- uri.path,- repairedParts.joinToString("&"),- uri.fragment- ).toString()}- private fun getOrCreateStalkerProvider(provider: ProviderEntity): StalkerProvider {- val providerId = provider.id- val cached = stalkerProviders[providerId]- if (cached != null &&- cached.serverUrl == provider.serverUrl &&- cached.macAddress == provider.stalkerMacAddress &&- cached.authMode == provider.stalkerAuthMode &&- cached.username == provider.username &&- cached.password == provider.password &&- cached.httpUserAgent == provider.httpUserAgent &&- cached.httpHeaders == provider.httpHeaders &&- cached.portalFingerprint == provider.stalkerPortalFingerprint &&- cached.magPreset == provider.stalkerMagPreset &&- cached.bootstrapRecipe == provider.stalkerLastBootstrapRecipe &&- cached.endpointPreference == provider.stalkerEndpointPreference &&- cached.cookieMode == provider.stalkerCookieMode &&- cached.playbackBackendHint == provider.stalkerPlaybackBackendHint &&- cached.deviceProfile == provider.stalkerDeviceProfile &&- cached.timezone == provider.stalkerDeviceTimezone &&- cached.locale == provider.stalkerDeviceLocale &&- cached.serialNumber == provider.stalkerSerialNumber &&- cached.deviceId == provider.stalkerDeviceId &&- cached.deviceId2 == provider.stalkerDeviceId2 &&- cached.signature == provider.stalkerSignature &&- cached.stalkerAdvancedOptionsJson == provider.stalkerAdvancedOptionsJson &&- cached.transportMode == provider.stalkerTransportMode &&- cached.transportOrigin == provider.stalkerTransportOrigin &&- cached.tlsSpkiSha256 == provider.stalkerTlsSpkiSha256 &&- cached.transportConsentAt == provider.stalkerTransportConsentAt- ) {- return cached.provider- }-- val decryptedPassword = credentialCrypto.decryptIfNeeded(provider.password)- val resolvedProvider = StalkerProvider(- providerId = provider.id,- api = stalkerApiService,- portalUrl = provider.serverUrl,- macAddress = provider.stalkerMacAddress,- authMode = provider.stalkerAuthMode,- username = provider.username,- password = decryptedPassword,- httpUserAgent = provider.httpUserAgent,- httpHeaders = provider.httpHeaders,- portalFingerprintHint = provider.stalkerPortalFingerprint,- magPresetHint = provider.stalkerMagPreset,- bootstrapRecipeHint = provider.stalkerLastBootstrapRecipe,- endpointPreferenceHint = provider.stalkerEndpointPreference,- cookieModeHint = provider.stalkerCookieMode,- playbackBackendHint = provider.stalkerPlaybackBackendHint,- portalProfileHint = provider.stalkerPortalProfile,- preferredPlaybackMode = provider.stalkerLastPlaybackMode- ?.let { value -> runCatching { StalkerPlaybackMode.valueOf(value) }.getOrNull() },- deviceProfile = provider.stalkerDeviceProfile,- timezone = provider.stalkerDeviceTimezone,- locale = provider.stalkerDeviceLocale,- serialNumber = provider.stalkerSerialNumber,- deviceId = provider.stalkerDeviceId,- deviceId2 = provider.stalkerDeviceId2,- signature = provider.stalkerSignature,- stalkerAdvancedOptionsJson = provider.stalkerAdvancedOptionsJson,- protocolPreference = provider.stalkerProtocolPreference,- transportGrant = provider.toStalkerTransportGrant(),- requestedProfileId = provider.stalkerRequestedProfileId,- learnedProfileId = provider.stalkerLearnedProfileId- )- stalkerProviders[providerId] = CachedStalkerProvider(- serverUrl = provider.serverUrl,- macAddress = provider.stalkerMacAddress,- authMode = provider.stalkerAuthMode,- username = provider.username,- password = provider.password,- httpUserAgent = provider.httpUserAgent,- httpHeaders = provider.httpHeaders,- portalFingerprint = provider.stalkerPortalFingerprint,- magPreset = provider.stalkerMagPreset,- bootstrapRecipe = provider.stalkerLastBootstrapRecipe,- endpointPreference = provider.stalkerEndpointPreference,- cookieMode = provider.stalkerCookieMode,- playbackBackendHint = provider.stalkerPlaybackBackendHint,- deviceProfile = provider.stalkerDeviceProfile,- timezone = provider.stalkerDeviceTimezone,- locale = provider.stalkerDeviceLocale,- serialNumber = provider.stalkerSerialNumber,- deviceId = provider.stalkerDeviceId,- deviceId2 = provider.stalkerDeviceId2,- signature = provider.stalkerSignature,- stalkerAdvancedOptionsJson = provider.stalkerAdvancedOptionsJson,- transportMode = provider.stalkerTransportMode,- transportOrigin = provider.stalkerTransportOrigin,- tlsSpkiSha256 = provider.stalkerTlsSpkiSha256,- transportConsentAt = provider.stalkerTransportConsentAt,- provider = resolvedProvider- )- return resolvedProvider+ private fun unavailable(url: String, reason: String, stalker: Boolean): ResolvedStreamUrl? {+ if (stalker) throw StalkerPlaybackResolutionException(reason)+ return url.takeIf { it.isNotBlank() && !isInternalStreamUrl(it) }?.toPassthrough(null)}- private suspend fun persistStalkerPlaybackLearning(- provider: ProviderEntity,- playbackInfo: com.streamvault.data.remote.stalker.StalkerPlaybackInfo- ) {- val updated = provider.copy(- stalkerLastPlaybackMode = playbackInfo.playbackMode.name,- stalkerEndpointPreference = playbackInfo.endpointPreference,- stalkerCookieMode = playbackInfo.cookieMode,- stalkerPlaybackBackendHint = playbackInfo.backendHint+ private fun String.toPassthrough(containerExtension: String?): ResolvedStreamUrl =+ ResolvedStreamUrl(+ url = this,+ expirationTime = extractStreamExpirationTime(this),+ containerExtension = containerExtension)- if (updated == provider) {- return- }- providerDao.update(updated)- }}-private fun ProviderEntity.toStalkerTransportGrant(): 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 XtreamStreamKind.toContentType(): ContentType = when (this) {+ XtreamStreamKind.LIVE -> ContentType.LIVE+ XtreamStreamKind.MOVIE -> ContentType.MOVIE+ XtreamStreamKind.SERIES -> ContentType.SERIES_EPISODE}-private fun String.toStalkerTransportOrigin(): StalkerTransportOrigin? {- val normalized = trim()- val uri = runCatching { URI(normalized) }.getOrNull()- ?.takeIf { it.scheme != null }- ?: 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 = uri.port.takeIf { it > 0 } ?: if (scheme == "https") 443 else 80- return StalkerTransportOrigin(scheme, host, port)+private fun StalkerStreamKind.toContentType(): ContentType = when (this) {+ StalkerStreamKind.LIVE,+ StalkerStreamKind.ARCHIVE -> ContentType.LIVE+ StalkerStreamKind.MOVIE -> ContentType.MOVIE+ StalkerStreamKind.EPISODE -> ContentType.SERIES_EPISODE}internal fun extractStreamExpirationTime(url: String): Long? {val query = runCatching { URI(url).rawQuery }.getOrNull()?: url.substringAfter('?', missingDelimiterValue = "").takeIf { it.isNotBlank() }?: return null-val expirationKeys = setOf(- "expire",- "expires",- "expiry",- "expiration",- "expires_at",- "exp",- "token_exp",- "token_expires",- "token_expiry"+ "expire", "expires", "expiry", "expiration", "expires_at", "exp",+ "token_exp", "token_expires", "token_expiry")-return query.split('&').asSequence().mapNotNull { part ->val key = part.substringBefore('=', missingDelimiterValue = "").lowercase()- .takeIf { it.isNotBlank() }+ .takeIf(String::isNotBlank)?: return@mapNotNull nullif (key !in expirationKeys) return@mapNotNull null-- val rawValue = part.substringAfter('=', missingDelimiterValue = "")- val decodedValue = XtreamUrlCodec.decode(rawValue)- parseXtreamExpirationDate(decodedValue)+ parseXtreamExpirationDate(+ XtreamUrlCodec.decode(part.substringAfter('=', missingDelimiterValue = ""))+ )}.firstOrNull()}diff --git a/data/src/main/java/com/streamvault/data/repository/CombinedM3uRepositoryImpl.kt b/data/src/main/java/com/streamvault/data/repository/CombinedM3uRepositoryImpl.ktindex 243d93de..4ac0b778 100644--- a/data/src/main/java/com/streamvault/data/repository/CombinedM3uRepositoryImpl.kt+++ b/data/src/main/java/com/streamvault/data/repository/CombinedM3uRepositoryImpl.kt@@ -2,7 +2,6 @@ package com.streamvault.data.repositoryimport com.streamvault.data.local.dao.CombinedM3uProfileDaoimport com.streamvault.data.local.dao.CombinedM3uProfileMemberDao-import com.streamvault.data.local.dao.ProviderDaoimport com.streamvault.data.local.entity.CombinedM3uProfileEntityimport com.streamvault.data.local.entity.CombinedM3uProfileMemberEntityimport com.streamvault.data.mapper.toDomain@@ -15,11 +14,12 @@ import com.streamvault.domain.model.CombinedCategoryimport com.streamvault.domain.model.CombinedCategoryBindingimport com.streamvault.domain.model.CombinedM3uProfileimport com.streamvault.domain.model.ContentType-import com.streamvault.domain.model.Provider+import com.streamvault.domain.model.LegacyProvider as Providerimport com.streamvault.domain.model.ProviderTypeimport com.streamvault.domain.model.Resultimport com.streamvault.domain.repository.ChannelRepositoryimport com.streamvault.domain.repository.CombinedM3uRepository+import com.streamvault.domain.repository.ProviderRepositoryimport java.util.Localeimport javax.inject.Injectimport javax.inject.Singleton@@ -34,9 +34,9 @@ import kotlinx.coroutines.flow.mapclass CombinedM3uRepositoryImpl @Inject constructor(private val profileDao: CombinedM3uProfileDao,private val memberDao: CombinedM3uProfileMemberDao,- private val providerDao: ProviderDao,private val channelRepository: ChannelRepository,- private val preferencesRepository: PreferencesRepository+ private val preferencesRepository: PreferencesRepository,+ private val providerRepository: ProviderRepository) : CombinedM3uRepository {override fun getProfiles(): Flow<List<CombinedM3uProfile>> =@@ -67,10 +67,8 @@ class CombinedM3uRepositoryImpl @Inject constructor(if (distinctProviderIds.isEmpty()) {return Result.error("Select at least one M3U provider.")}- val providersById = providerDao.getByIds(distinctProviderIds)- .associateBy { it.id }val providers = distinctProviderIds.mapNotNull { providerId ->- providersById[providerId]?.toDomain()+ providerRepository.getProvider(providerId)}if (providers.size != distinctProviderIds.size || providers.any { it.type != ProviderType.M3U }) {return Result.error("Combined profiles support M3U providers only.")@@ -130,7 +128,7 @@ class CombinedM3uRepositoryImpl @Inject constructor(override suspend fun addProvider(profileId: Long, providerId: Long): Result<Unit> {return try {val profile = profileDao.getById(profileId) ?: return Result.error("Combined profile not found.")- val provider = providerDao.getById(providerId)?.toDomain()+ val provider = providerRepository.getProvider(providerId)?: return Result.error("Provider not found.")if (provider.type != ProviderType.M3U) {return Result.error("Only M3U providers can be added to a combined profile.")@@ -203,9 +201,8 @@ class CombinedM3uRepositoryImpl @Inject constructor(}override fun getAvailableM3uProviders(): Flow<List<Provider>> =- providerDao.getAll().map { providers ->- providers.map { it.toDomain().copy(password = "") }- .filter { it.type == ProviderType.M3U }+ providerRepository.getProviders().map { providers ->+ providers.filter { it.type == ProviderType.M3U }}override fun getActiveLiveSource(): Flow<ActiveLiveSource?> =diff --git a/data/src/main/java/com/streamvault/data/repository/EpgRepositoryImpl.kt b/data/src/main/java/com/streamvault/data/repository/EpgRepositoryImpl.ktindex f3e0fc51..914cd5be 100644--- a/data/src/main/java/com/streamvault/data/repository/EpgRepositoryImpl.kt+++ b/data/src/main/java/com/streamvault/data/repository/EpgRepositoryImpl.kt@@ -18,6 +18,9 @@ import com.streamvault.data.remote.http.withRequestProfileimport com.streamvault.data.util.rankSearchResultsimport com.streamvault.domain.model.Programimport com.streamvault.domain.model.Result+import com.streamvault.domain.model.StalkerConfig+import com.streamvault.data.provider.ProviderCapabilityResolver+import com.streamvault.data.provider.toLegacyProviderimport com.streamvault.domain.repository.EpgRepositoryimport com.streamvault.domain.repository.EpgSourceRepositoryimport kotlinx.coroutines.CoroutineScope@@ -60,6 +63,7 @@ class EpgRepositoryImpl @Inject constructor(private val transactionRunner: DatabaseTransactionRunner,private val epgSourceRepository: EpgSourceRepository,private val preferencesRepository: PreferencesRepository,+ private val providerCapabilityResolver: ProviderCapabilityResolver? = null,private val externalScope: CoroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.Default)) : EpgRepository {@@ -265,8 +269,9 @@ class EpgRepositoryImpl @Inject constructor(withContext(Dispatchers.IO) {providerRefreshMutex(providerId).withLock {val stagingProviderId = -providerId- val providerTimezoneId = providerDao.getById(providerId)- ?.stalkerDeviceTimezone+ val providerTimezoneId = (providerCapabilityResolver?.snapshot(providerId)?.configuration as? StalkerConfig)+ ?.device+ ?.timezone?.trim()?.takeIf(String::isNotEmpty)val batch = ArrayList<ProgramEntity>(EPG_PROGRAM_BATCH_SIZE)@@ -280,7 +285,9 @@ class EpgRepositoryImpl @Inject constructor(yield()}try {- val providerRequestProfile = providerDao.getById(providerId)+ val providerRequestProfile = providerCapabilityResolver+ ?.snapshot(providerId)+ ?.toLegacyProvider()?.toGenericRequestProfile(ownerTag = "provider:$providerId/epg")?: HttpRequestProfile(ownerTag = "provider:$providerId/epg")val request = Request.Builder()diff --git a/data/src/main/java/com/streamvault/data/repository/MovieRepositoryImpl.kt b/data/src/main/java/com/streamvault/data/repository/MovieRepositoryImpl.ktindex 5663bb6f..b9dc9cd3 100644--- a/data/src/main/java/com/streamvault/data/repository/MovieRepositoryImpl.kt+++ b/data/src/main/java/com/streamvault/data/repository/MovieRepositoryImpl.kt@@ -11,28 +11,21 @@ import com.streamvault.data.local.dao.PlaybackHistoryDaoimport com.streamvault.data.local.dao.ProviderDaoimport com.streamvault.data.local.dao.XtreamContentIndexDaoimport com.streamvault.data.local.dao.XtreamIndexJobDao-import com.streamvault.data.local.entity.ProviderEntityimport com.streamvault.data.local.entity.CategoryEntityimport com.streamvault.data.local.entity.MovieBrowseEntityimport com.streamvault.data.local.entity.MovieCategoryHydrationEntityimport com.streamvault.data.mapper.toEntityimport com.streamvault.data.mapper.toDomainimport com.streamvault.data.preferences.PreferencesRepository-import com.streamvault.data.remote.http.toGenericRequestProfile-import com.streamvault.data.remote.stalker.StalkerApiService-import com.streamvault.data.remote.stalker.StalkerPlaybackMode+import com.streamvault.data.provider.ProviderCapabilityResolver+import com.streamvault.data.provider.TypedProviderClientFactory+import com.streamvault.data.provider.toLegacyProviderimport com.streamvault.data.remote.stalker.StalkerProvider-import com.streamvault.data.remote.stalker.StalkerRemoteIdentityResolverimport com.streamvault.data.remote.stalker.StalkerRequestCoordinatorimport com.streamvault.data.remote.stalker.StalkerRequestDescriptorimport com.streamvault.data.remote.stalker.StalkerResponseMetrics-import com.streamvault.data.remote.stalker.StalkerPortalStateStoreimport com.streamvault.data.remote.stalker.StalkerTrafficCoordinator-import com.streamvault.data.remote.stalker.stalkerTransportGrantOrNull-import com.streamvault.data.remote.xtream.XtreamApiServiceimport com.streamvault.data.remote.xtream.XtreamStreamUrlResolver-import com.streamvault.data.remote.xtream.XtreamProvider-import com.streamvault.data.security.CredentialCryptoimport com.streamvault.data.sync.ContentCachePolicyimport com.streamvault.data.sync.SyncManagerimport com.streamvault.data.util.MoviePresentationSettings@@ -49,6 +42,7 @@ import com.streamvault.domain.model.MovieDetailPresentationHintimport com.streamvault.domain.model.Movieimport com.streamvault.domain.model.PagedResultimport com.streamvault.domain.model.PlaybackHistory+import com.streamvault.domain.model.LegacyProvider as Providerimport com.streamvault.domain.model.ProviderTypeimport com.streamvault.domain.model.Resultimport com.streamvault.domain.model.Result.Success@@ -64,6 +58,8 @@ import com.streamvault.domain.model.VodCategoryLoadModeimport com.streamvault.domain.repository.MovieRepositoryimport com.streamvault.domain.repository.PlaybackHistoryRepositoryimport com.streamvault.domain.repository.SyncMetadataRepository+import com.streamvault.domain.provider.CapabilityResolution+import com.streamvault.domain.provider.ProviderContentReferenceimport kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.ExperimentalCoroutinesApi@@ -92,9 +88,6 @@ class MovieRepositoryImpl @Inject constructor(private val movieDao: MovieDao,private val categoryDao: CategoryDao,private val providerDao: ProviderDao,- private val stalkerApiService: StalkerApiService,- private val xtreamApiService: XtreamApiService,- private val credentialCrypto: CredentialCrypto,private val preferencesRepository: PreferencesRepository,private val favoriteDao: FavoriteDao,private val playbackHistoryDao: PlaybackHistoryDao,@@ -106,9 +99,9 @@ class MovieRepositoryImpl @Inject constructor(private val xtreamIndexJobDao: XtreamIndexJobDao,private val syncManager: SyncManager,private val transactionRunner: DatabaseTransactionRunner,- private val stalkerRemoteIdentityResolver: StalkerRemoteIdentityResolver,private val stalkerRequestCoordinator: StalkerRequestCoordinator,- private val stalkerPortalStateStore: StalkerPortalStateStore+ private val providerCapabilityResolver: ProviderCapabilityResolver,+ private val typedProviderClientFactory: TypedProviderClientFactory) : MovieRepository {private companion object {const val TAG = "MovieRepository"@@ -129,11 +122,6 @@ class MovieRepositoryImpl @Inject constructor(val DETAIL_YEAR_REGEX = Regex("""(19|20)\\d{2}""")}- private data class CachedXtreamProvider(- val signature: String,- val provider: XtreamProvider- )-private data class NameCursor(val name: String,val id: Long@@ -151,7 +139,6 @@ class MovieRepositoryImpl @Inject constructor(val id: Long)- private val xtreamProviderCache = ConcurrentHashMap<Long, CachedXtreamProvider>()private val xtreamCategoryLoadLocks = ConcurrentHashMap<String, Mutex>()private val freshXtreamCategories = ConcurrentHashMap.newKeySet<String>()private val backgroundRefreshes = ConcurrentHashMap.newKeySet<String>()@@ -261,9 +248,9 @@ class MovieRepositoryImpl @Inject constructor(if (filteredCategories.isEmpty()) {flowOf(emptyMap())} else channelFlow {- val provider = providerDao.getById(providerId)+ val provider = loadCompatibilityProvider(providerId)val previewCategories = if (provider?.type == ProviderType.STALKER_PORTAL) {- val stalkerProvider = createStalkerProvider(providerId, provider)+ val stalkerProvider = createStalkerProvider(providerId)filteredCategories.filterNot { category ->stalkerProvider.isWildcardCategory(ContentType.MOVIE, category.categoryId)}@@ -414,7 +401,7 @@ class MovieRepositoryImpl @Inject constructor(}}query.categoryId?.takeIf { normalizedSearch.length < MIN_SEARCH_QUERY_LENGTH }?.let {- val provider = providerDao.getById(query.providerId)+ val provider = loadCompatibilityProvider(query.providerId)if (provider?.type == ProviderType.XTREAM_CODES) {ensureXtreamCategoryLoaded(query.providerId,@@ -451,7 +438,7 @@ class MovieRepositoryImpl @Inject constructor(categoryId: Long,request: VodCategoryHydrationRequest): Result<Unit> {- val provider = providerDao.getById(providerId) ?: return Result.error("Provider not found")+ val provider = loadCompatibilityProvider(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 (@@ -490,7 +477,7 @@ class MovieRepositoryImpl @Inject constructor(private fun scheduleMoviePrefetch(providerId: Long, categoryId: Long, loadMode: VodCategoryLoadMode) {if (loadMode != VodCategoryLoadMode.PAGED) returnrepositoryScope.launch {- val provider = providerDao.getById(providerId) ?: return@launch+ val provider = loadCompatibilityProvider(providerId) ?: return@launchval current = movieCategoryHydrationDao.get(providerId, categoryId)if (current?.isComplete == true) return@launchif (provider.catalogLayout == CatalogLayout.SPLIT && provider.catalogLayoutDetectionVersion > 0) {@@ -562,7 +549,7 @@ class MovieRepositoryImpl @Inject constructor(val movieEntity = movieDao.getById(movieId)?: return Result.error("Movie not found")- val provider = providerDao.getById(providerId)+ val provider = loadCompatibilityProvider(providerId)?: return Result.error("Provider not found")if (provider.type == ProviderType.XTREAM_CODES && movieEntity.hasFreshXtreamDetails()) {@@ -570,12 +557,34 @@ class MovieRepositoryImpl @Inject constructor(}val remoteMovieResult = try {- when (provider.type) {- ProviderType.XTREAM_CODES -> getOrCreateXtreamProvider(providerId, provider).getVodInfo(movieEntity.streamId)- ProviderType.STALKER_PORTAL -> return Result.success(attachMoviePresentation(movieEntity.toDomain(), knownPresentation))- ProviderType.M3U -> return Result.success(attachMoviePresentation(movieEntity.toDomain(), knownPresentation))- ProviderType.JELLYFIN -> return Result.success(attachMoviePresentation(movieEntity.toDomain(), knownPresentation))+ val capabilitySet = when (val resolution = providerCapabilityResolver.resolve(providerId)) {+ is CapabilityResolution.Available -> resolution.capability+ is CapabilityResolution.ConfigurationError -> return Result.success(+ attachMoviePresentation(movieEntity.toDomain(), knownPresentation)+ )+ is CapabilityResolution.Restricted -> return Result.success(+ attachMoviePresentation(movieEntity.toDomain(), knownPresentation)+ )+ is CapabilityResolution.Unsupported -> return Result.success(+ attachMoviePresentation(movieEntity.toDomain(), knownPresentation)+ )}+ val vodSource = when (val resolution = capabilitySet.vodCatalog()) {+ is CapabilityResolution.Available -> resolution.capability+ is CapabilityResolution.ConfigurationError,+ is CapabilityResolution.Restricted,+ is CapabilityResolution.Unsupported -> return Result.success(+ attachMoviePresentation(movieEntity.toDomain(), knownPresentation)+ )+ }+ vodSource.hydrateVod(+ reference = ProviderContentReference(+ providerId = providerId,+ localId = movieEntity.id,+ streamId = movieEntity.streamId+ ),+ current = movieEntity.toDomain()+ )} catch (e: Exception) {if (provider.type == ProviderType.XTREAM_CODES) {xtreamContentIndexDao.markDetailHydrationError(@@ -1263,7 +1272,7 @@ class MovieRepositoryImpl @Inject constructor(}val hasMoreRemote = query.categoryId?.let { categoryId ->- val provider = providerDao.getById(query.providerId)+ val provider = loadCompatibilityProvider(query.providerId)if (provider?.type == ProviderType.STALKER_PORTAL) {movieCategoryHydrationDao.get(query.providerId, categoryId)?.let { !it.isComplete } ?: false} else {@@ -1570,7 +1579,7 @@ class MovieRepositoryImpl @Inject constructor(loadStalkerCategoryCompletely: Boolean = false) {val key = "$providerId:$categoryId"- val provider = providerDao.getById(providerId) ?: return+ val provider = loadCompatibilityProvider(providerId) ?: returnif (provider.type != ProviderType.XTREAM_CODES && provider.type != ProviderType.STALKER_PORTAL) returnval localCount = movieDao.getCountByCategory(providerId, categoryId).first()@@ -1631,7 +1640,7 @@ class MovieRepositoryImpl @Inject constructor(if (!backgroundRefreshes.add(key)) returnrepositoryScope.launch {try {- val provider = providerDao.getById(providerId) ?: return@launch+ val provider = loadCompatibilityProvider(providerId) ?: return@launchif (provider.type != ProviderType.XTREAM_CODES && provider.type != ProviderType.STALKER_PORTAL) {return@launch}@@ -1691,7 +1700,7 @@ class MovieRepositoryImpl @Inject constructor(private suspend fun hydrateStalkerMovieCategoryToCount(providerId: Long,categoryId: Long,- provider: ProviderEntity,+ provider: Provider,requiredCount: Int,localCount: Int? = null,hydration: MovieCategoryHydrationEntity? = null,@@ -1704,7 +1713,7 @@ class MovieRepositoryImpl @Inject constructor(lock.withLock {val persistedHydration = movieCategoryHydrationDao.get(providerId, categoryId)if (requestedPage != null && (persistedHydration?.lastSuccessfulPage ?: 0) >= requestedPage) return- val stalkerProvider = createStalkerProvider(providerId, provider)+ val stalkerProvider = createStalkerProvider(providerId)if (!allowWildcard && stalkerProvider.isWildcardCategory(ContentType.MOVIE, categoryId)) returnvar currentCount = localCount ?: movieDao.getCountByCategory(providerId, categoryId).first()var currentHydration = persistedHydration ?: hydration@@ -1887,81 +1896,23 @@ class MovieRepositoryImpl @Inject constructor(private fun movieAddedScore(movie: Movie): Long =movie.addedAt.takeIf { it > 0L } ?: 0L- private suspend fun getOrCreateXtreamProvider(providerId: Long, provider: ProviderEntity): XtreamProvider {- val enableBase64TextCompatibility = preferencesRepository.xtreamBase64TextCompatibility.first()- val signature = listOf(- provider.serverUrl,- provider.username,- provider.password,- provider.httpUserAgent,- provider.httpHeaders,- provider.allowedOutputFormatsJson,- enableBase64TextCompatibility.toString()- ).joinToString("\u0000")- return requireNotNull(- xtreamProviderCache.compute(providerId) { _, cached ->- if (cached != null && cached.signature == signature) {- cached- } else {- val decryptedPassword = credentialCrypto.decryptIfNeeded(provider.password)- CachedXtreamProvider(- signature = signature,- provider = XtreamProvider(- providerId = providerId,- api = xtreamApiService,- serverUrl = provider.serverUrl,- username = provider.username,- password = decryptedPassword,- allowedOutputFormats = provider.toDomain().allowedOutputFormats,- enableBase64TextCompatibility = enableBase64TextCompatibility,- requestProfile = provider.toGenericRequestProfile(ownerTag = "provider:$providerId/xtream")- )- )- }- }- ) { "Provider cache compute returned null for providerId=$providerId" }.provider- }-- private fun createStalkerProvider(providerId: Long, provider: ProviderEntity): StalkerProvider {- return StalkerProvider(- providerId = providerId,- api = stalkerApiService,- portalUrl = provider.serverUrl,- macAddress = provider.stalkerMacAddress,- authMode = provider.stalkerAuthMode,- username = provider.username,- password = credentialCrypto.decryptIfNeeded(provider.password),- httpUserAgent = provider.httpUserAgent,- httpHeaders = provider.httpHeaders,- portalFingerprintHint = provider.stalkerPortalFingerprint,- magPresetHint = provider.stalkerMagPreset,- bootstrapRecipeHint = provider.stalkerLastBootstrapRecipe,- endpointPreferenceHint = provider.stalkerEndpointPreference,- cookieModeHint = provider.stalkerCookieMode,- playbackBackendHint = provider.stalkerPlaybackBackendHint,- portalProfileHint = provider.stalkerPortalProfile,- preferredPlaybackMode = provider.stalkerLastPlaybackMode- ?.let { value -> runCatching { StalkerPlaybackMode.valueOf(value) }.getOrNull() },- deviceProfile = provider.stalkerDeviceProfile,- timezone = provider.stalkerDeviceTimezone,- locale = provider.stalkerDeviceLocale,- serialNumber = provider.stalkerSerialNumber,- deviceId = provider.stalkerDeviceId,- deviceId2 = provider.stalkerDeviceId2,- signature = provider.stalkerSignature,- stalkerAdvancedOptionsJson = provider.stalkerAdvancedOptionsJson,- protocolPreference = provider.stalkerProtocolPreference,- transportGrant = provider.stalkerTransportGrantOrNull(),- requestedProfileId = provider.stalkerRequestedProfileId,- learnedProfileId = provider.stalkerLearnedProfileId,- identityResolver = stalkerRemoteIdentityResolver,- portalStateStore = stalkerPortalStateStore- )+ private suspend fun createStalkerProvider(providerId: Long): StalkerProvider {+ val snapshot = providerCapabilityResolver.snapshot(providerId)+ ?: throw IllegalStateException("Provider $providerId has no typed configuration")+ return when (val resolution = typedProviderClientFactory.stalker(snapshot)) {+ is CapabilityResolution.Available -> resolution.capability+ is CapabilityResolution.ConfigurationError -> throw IllegalStateException(resolution.reason)+ is CapabilityResolution.Restricted -> throw IllegalStateException(resolution.reason)+ is CapabilityResolution.Unsupported -> throw IllegalStateException(resolution.reason)+ }}private fun moviePlaybackComplete(progressMs: Long, totalDurationMs: Long): Boolean {if (progressMs <= 0L || totalDurationMs <= 0L) return falsereturn progressMs >= (totalDurationMs * 0.95f).toLong()}++ private suspend fun loadCompatibilityProvider(providerId: Long): Provider? =+ providerCapabilityResolver.snapshot(providerId)?.toLegacyProvider()}diff --git a/data/src/main/java/com/streamvault/data/repository/ProviderRepositoryImpl.kt b/data/src/main/java/com/streamvault/data/repository/ProviderRepositoryImpl.ktindex 774db35e..2b73aff0 100644--- a/data/src/main/java/com/streamvault/data/repository/ProviderRepositoryImpl.kt+++ b/data/src/main/java/com/streamvault/data/repository/ProviderRepositoryImpl.kt@@ -1,5 +1,7 @@package com.streamvault.data.repository+import com.streamvault.domain.model.Provider as StableProvider+import android.content.Contextimport com.google.gson.Gsonimport com.streamvault.data.local.dao.ProviderDeletionCleanupDao@@ -10,22 +12,33 @@ import com.streamvault.data.local.entity.ProviderConfigRevisionStateimport com.streamvault.data.local.DatabaseTransactionRunnerimport com.streamvault.data.local.dao.*import com.streamvault.data.local.entity.ProviderEntity+import com.streamvault.data.local.entity.ProviderConfigEntity+import com.streamvault.data.local.entity.ProviderAccountRuntimeEntityimport com.streamvault.data.local.entity.StalkerDiscoveryStageEntity+import com.streamvault.data.local.entity.StalkerPortalStateEntityimport com.streamvault.data.local.entity.StalkerIndexJobEntityimport com.streamvault.data.manager.recording.RecordingAlarmSchedulerimport com.streamvault.data.manager.reminder.ProgramReminderAlarmSchedulerimport com.streamvault.data.mapper.*import com.streamvault.data.preferences.PreferencesRepository-import com.streamvault.data.remote.http.buildGenericProviderRequestProfile+import com.streamvault.data.provider.ProviderConfigurationCodec+import com.streamvault.data.provider.ProviderConfigRevisionCodec+import com.streamvault.data.provider.ProviderCapabilityResolver+import com.streamvault.data.provider.StalkerClientOptions+import com.streamvault.data.provider.TypedProviderClientFactory+import com.streamvault.data.provider.toAccountRuntime+import com.streamvault.data.provider.toTypedConfiguration+import com.streamvault.data.provider.toLegacyProvider+import com.streamvault.data.provider.toGenerationValidLearning+import com.streamvault.data.provider.guidePolicy+import com.streamvault.data.provider.logoPolicyimport com.streamvault.data.remote.jellyfin.JellyfinProviderimport com.streamvault.data.remote.stalker.StalkerApiServiceimport com.streamvault.data.remote.stalker.StalkerPlaybackModeimport com.streamvault.data.remote.stalker.StalkerProvider-import com.streamvault.data.remote.stalker.StalkerRemoteIdentityResolverimport com.streamvault.data.remote.stalker.StalkerPortalStateStoreimport com.streamvault.data.remote.stalker.StalkerCompatibilityRegistryimport com.streamvault.data.remote.stalker.StalkerApiError-import com.streamvault.data.remote.xtream.XtreamApiServiceimport com.streamvault.data.remote.xtream.XtreamProviderimport com.streamvault.data.security.CredentialCryptoimport com.streamvault.data.security.CredentialDecryptionException@@ -42,24 +55,32 @@ import com.streamvault.data.util.ProviderInputSanitizerimport com.streamvault.data.util.UrlSecurityPolicyimport com.streamvault.domain.manager.ProviderCredentialsimport com.streamvault.domain.model.*-import com.streamvault.domain.provider.IptvProvider+import com.streamvault.domain.model.LegacyProvider as Providerimport com.streamvault.domain.repository.LiveStreamProgramRequestimport com.streamvault.domain.repository.ProviderDeleteOutcomeimport com.streamvault.domain.repository.ProviderDeleteProgressimport com.streamvault.domain.repository.ProviderRepository+import com.streamvault.domain.repository.ProviderSetupRequestimport com.streamvault.domain.repository.SyncMetadataRepository+import com.streamvault.domain.provider.CapabilityResolution+import com.streamvault.domain.provider.CatchUpRequest+import com.streamvault.domain.provider.GuideRequest+import com.streamvault.domain.provider.GuideSourceimport kotlinx.coroutines.asyncimport kotlinx.coroutines.awaitAllimport kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.SupervisorJobimport kotlinx.coroutines.CancellationException+import kotlinx.coroutines.NonCancellableimport kotlinx.coroutines.coroutineScopeimport kotlinx.coroutines.delayimport kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.combineimport kotlinx.coroutines.flow.firstimport kotlinx.coroutines.flow.mapimport kotlinx.coroutines.launch+import kotlinx.coroutines.withContextimport java.io.IOExceptionimport java.net.URIimport java.util.UUID@@ -71,6 +92,7 @@ import dagger.hilt.android.qualifiers.ApplicationContext@Singletonclass ProviderRepositoryImpl @Inject constructor(private val providerDao: ProviderDao,+ private val providerSnapshotDao: ProviderSnapshotDao,private val categoryDao: CategoryDao,private val channelDao: ChannelDao,private val movieDao: MovieDao,@@ -79,8 +101,8 @@ class ProviderRepositoryImpl @Inject constructor(private val recordingRunDao: RecordingRunDao,private val programReminderDao: ProgramReminderDao,private val stalkerApiService: StalkerApiService,- private val xtreamApiService: XtreamApiService,private val credentialCrypto: CredentialCrypto,+ private val providerConfigurationCodec: ProviderConfigurationCodec,private val preferencesRepository: PreferencesRepository,private val syncManager: SyncManager,private val syncMetadataRepository: SyncMetadataRepository,@@ -88,7 +110,6 @@ class ProviderRepositoryImpl @Inject constructor(private val recordingAlarmScheduler: RecordingAlarmScheduler,private val programReminderAlarmScheduler: ProgramReminderAlarmScheduler,private val jellyfinProvider: JellyfinProvider,- private val stalkerRemoteIdentityResolver: StalkerRemoteIdentityResolver,private val stalkerIndexJobDao: StalkerIndexJobDao,private val stalkerPortalStateStore: StalkerPortalStateStore,private val movieCategoryHydrationDao: MovieCategoryHydrationDao,@@ -100,6 +121,8 @@ class ProviderRepositoryImpl @Inject constructor(private val gson: Gson,private val providerWorkflowRunner: ProviderWorkflowRunner,private val providerWorkflowCommitFence: ProviderWorkflowCommitFence,+ private val providerCapabilityResolver: ProviderCapabilityResolver,+ private val typedProviderClientFactory: TypedProviderClientFactory,@param:ApplicationContext private val appContext: Context) : ProviderRepository {private companion object {@@ -130,24 +153,80 @@ class ProviderRepositoryImpl @Inject constructor(val pendingEdit: PendingProviderEdit? = null)- override fun getProviders(): Flow<List<Provider>> =- providerDao.getAll().map { entities -> entities.map { it.toPublicDomain() } }+ override fun getProviders(): Flow<List<Provider>> = combine(+ providerDao.getAll(),+ providerSnapshotDao.observeConfigs(),+ providerSnapshotDao.observeRuntimes(),+ providerSnapshotDao.observeStalkerPortalStates()+ ) { identities, configs, runtimes, portalStates ->+ val configsByProvider = configs.associateBy { it.providerId }+ val runtimesByProvider = runtimes.associateBy { it.providerId }+ val portalStatesByProvider = portalStates.associateBy { it.providerId }+ identities.map { identity ->+ val stored = configsByProvider[identity.id]+ if (stored == null) {+ identity.toPublicDomain()+ } else {+ val stableIdentity = StableProvider(+ id = identity.id,+ name = identity.name,+ type = identity.type,+ isActive = identity.isActive,+ status = identity.status,+ lastSyncedAt = identity.lastSyncedAt,+ createdAt = identity.createdAt+ )+ val runtime = runtimesByProvider[identity.id]?.toDomainRuntime()+ ?: ProviderAccountRuntime()+ val learning = if (identity.type == ProviderType.STALKER_PORTAL) {+ portalStatesByProvider[identity.id]?.toGenerationValidLearning(+ gson,+ stored.configurationGeneration+ )+ } else {+ null+ }+ ProviderSnapshot(+ provider = stableIdentity,+ configuration = providerConfigurationCodec.decode(+ stored.type,+ stored.encryptedConfigJson+ ),+ configurationGeneration = stored.configurationGeneration,+ accountRuntime = runtime,+ stalkerLearning = learning+ ).toLegacyProvider().redactedCredentials()+ }+ }+ }override fun getActiveProvider(): Flow<Provider?> =- providerDao.getActive().map { it?.toPublicDomain() }+ getProviders().map { providers -> providers.firstOrNull { it.isActive } }override suspend fun getProvider(id: Long): Provider? =- providerDao.getById(id)?.toPublicDomain()+ loadLegacyProvider(id)?.redactedCredentials()override suspend fun addProvider(provider: Provider): Result<Long> = try {- val id = providerDao.insert(provider.toSecureEntity())+ val id = transactionRunner.inTransaction {+ val insertedId = providerDao.insert(provider.toSecureEntity())+ persistTypedSnapshot(insertedId, provider, currentGeneration = null)+ insertedId+ }Result.success(id)} catch (e: Exception) {Result.error("Failed to add provider: ${e.message}", e)}override suspend fun updateProvider(provider: Provider): Result<Unit> = try {- providerDao.update(provider.toSecureEntity())+ transactionRunner.inTransaction {+ val current = providerSnapshotDao.getConfig(provider.id)+ val currentConfiguration = current?.let { stored ->+ providerConfigurationCodec.decode(stored.type, stored.encryptedConfigJson)+ }+ val persistedProvider = provider.withPersistedCredential(currentConfiguration)+ providerDao.update(persistedProvider.toSecureEntity())+ persistTypedSnapshot(provider.id, persistedProvider, current?.configurationGeneration)+ }if (provider.type == ProviderType.STALKER_PORTAL) {stalkerPortalStateStore.invalidate(provider.id)}@@ -196,15 +275,12 @@ class ProviderRepositoryImpl @Inject constructor(override suspend fun getAllProviderCredentials(): List<ProviderCredentials> {return providerDao.getAllSync()- .map { entity ->+ .mapNotNull { entity -> loadLegacyProvider(entity.id) }+ .map { provider ->ProviderCredentials(- serverUrl = entity.serverUrl,- username = entity.username,- password = try {- credentialCrypto.decryptIfNeeded(entity.password)- } catch (e: Throwable) {- ""- },+ serverUrl = provider.serverUrl,+ username = provider.username,+ password = provider.password,)}.filter { it.username.isNotBlank() && it.password.isNotBlank() }@@ -215,15 +291,45 @@ class ProviderRepositoryImpl @Inject constructor(username: String,cleartextPassword: String,): Boolean {- val entity = providerDao.getAllSync().firstOrNull {- it.serverUrl == serverUrl && it.username == username- } ?: return false- val encrypted = credentialCrypto.encryptIfNeeded(cleartextPassword)- providerDao.update(entity.copy(password = encrypted))- if (entity.type == ProviderType.STALKER_PORTAL) {- stalkerPortalStateStore.invalidate(entity.id)- }- return true+ var matchedSnapshot: ProviderSnapshot? = null+ for (identity in providerDao.getAllSync()) {+ val candidate = providerCapabilityResolver.snapshot(identity.id) ?: continue+ val matches =+ when (val config = candidate.configuration) {+ is XtreamConfig -> config.serverUrl == serverUrl && config.username == username+ is StalkerConfig -> config.portalUrl == serverUrl && config.username == username+ is JellyfinConfig -> config.serverUrl == serverUrl && config.username == username+ is M3uConfig -> false+ }+ if (matches) {+ matchedSnapshot = candidate+ break+ }+ }+ val snapshot = matchedSnapshot ?: return false+ val updatedConfiguration = when (val config = snapshot.configuration) {+ is XtreamConfig -> config.copy(password = cleartextPassword)+ is StalkerConfig -> config.copy(password = cleartextPassword)+ is JellyfinConfig -> config.copy(credential = cleartextPassword)+ is M3uConfig -> return false+ }+ val committed = providerSnapshotDao.commitConfiguration(+ ProviderConfigEntity(+ providerId = snapshot.provider.id,+ type = updatedConfiguration.type,+ schemaVersion = updatedConfiguration.schemaVersion,+ configurationGeneration = snapshot.configurationGeneration + 1L,+ identityKey = providerConfigurationCodec.identityKey(updatedConfiguration),+ encryptedConfigJson = providerConfigurationCodec.encode(updatedConfiguration),+ guideSourcePolicy = updatedConfiguration.guidePolicy(),+ channelLogoSourcePolicy = updatedConfiguration.logoPolicy(),+ updatedAt = System.currentTimeMillis()+ )+ )+ if (committed && snapshot.provider.type == ProviderType.STALKER_PORTAL) {+ stalkerPortalStateStore.invalidate(snapshot.provider.id)+ }+ return committed}override suspend fun deleteProvider(@@ -291,6 +397,7 @@ class ProviderRepositoryImpl @Inject constructor(completedWeight += PROVIDER_ROW_STEP_WEIGHTpendingCleanupActions = providerDeletionCleanupDao.countByProvider(id)}+ stalkerApiService.invalidateSessionScopes(id)reportProgress("Provider library removed.")reportProgress("Finalizing provider cleanup...")val reconciliationRequested = runCatching {@@ -336,20 +443,100 @@ class ProviderRepositoryImpl @Inject constructor(}}- override suspend fun loginXtream(+ override suspend fun setupProvider(+ request: ProviderSetupRequest,+ onProgress: ((String) -> Unit)?,+ onCode: ((String) -> Unit)?+ ): Result<Provider> = when (request) {+ is ProviderSetupRequest.Configured -> when (val config = request.configuration) {+ is XtreamConfig -> loginXtream(+ serverUrl = config.serverUrl,+ username = config.username,+ password = config.password,+ name = request.name,+ httpUserAgent = config.httpUserAgent,+ httpHeaders = config.httpHeaders,+ xtreamFastSyncEnabled = config.fastSyncEnabled,+ epgSyncMode = config.epgSyncMode,+ xtreamLiveSyncMode = config.liveSyncMode,+ guideSourcePolicy = config.guideSourcePolicy,+ channelLogoSourcePolicy = config.channelLogoSourcePolicy,+ onProgress = onProgress,+ id = request.existingProviderId+ )+ is M3uConfig -> validateM3u(+ url = config.playlistUrl,+ name = request.name,+ httpUserAgent = config.httpUserAgent,+ httpHeaders = config.httpHeaders,+ epgSyncMode = config.epgSyncMode,+ m3uVodClassificationEnabled = config.vodClassificationEnabled,+ guideSourcePolicy = config.guideSourcePolicy,+ channelLogoSourcePolicy = config.channelLogoSourcePolicy,+ onProgress = onProgress,+ id = request.existingProviderId+ )+ is StalkerConfig -> loginStalker(+ portalUrl = config.portalUrl,+ macAddress = config.device.macAddress,+ name = request.name,+ authMode = config.authMode,+ username = config.username,+ password = config.password,+ httpUserAgent = config.httpUserAgent,+ httpHeaders = config.httpHeaders,+ deviceProfile = config.device.deviceProfile,+ timezone = config.device.timezone,+ locale = config.device.locale,+ serialNumber = config.device.serialNumber,+ deviceId = config.device.deviceId,+ deviceId2 = config.device.deviceId2,+ signature = config.device.signature,+ stalkerAdvancedOptionsJson = config.advancedOptionsJson,+ protocolPreference = config.protocolPreference,+ transportGrant = config.transportGrant,+ saveWithoutVerification = request.saveWithoutVerification,+ repairConnection = request.repairConnection,+ requestedProfileId = config.requestedProfileId,+ epgSyncMode = config.epgSyncMode,+ catalogMode = config.catalogMode,+ guideSourcePolicy = config.guideSourcePolicy,+ channelLogoSourcePolicy = config.channelLogoSourcePolicy,+ onProgress = onProgress,+ id = request.existingProviderId+ )+ is JellyfinConfig -> loginJellyfin(+ serverUrl = config.serverUrl,+ username = config.username,+ password = config.credential,+ name = request.name,+ onProgress = onProgress,+ id = request.existingProviderId+ )+ }+ is ProviderSetupRequest.JellyfinQuickConnect -> loginJellyfinQuickConnect(+ serverUrl = request.serverUrl,+ name = request.name,+ onCode = onCode,+ onProgress = onProgress,+ id = request.existingProviderId+ )+ }++ internal suspend fun loginXtream(serverUrl: String,username: String,password: String,name: String,- httpUserAgent: String,- httpHeaders: String,+ httpUserAgent: String = "",+ httpHeaders: String = "",xtreamFastSyncEnabled: Boolean,- epgSyncMode: ProviderEpgSyncMode,- xtreamLiveSyncMode: com.streamvault.domain.model.ProviderXtreamLiveSyncMode,- guideSourcePolicy: GuideSourcePolicy,- channelLogoSourcePolicy: ChannelLogoSourcePolicy,- onProgress: ((String) -> Unit)?,- id: Long?+ epgSyncMode: ProviderEpgSyncMode = ProviderEpgSyncMode.BACKGROUND,+ xtreamLiveSyncMode: com.streamvault.domain.model.ProviderXtreamLiveSyncMode = ProviderXtreamLiveSyncMode.AUTO,+ guideSourcePolicy: GuideSourcePolicy = GuideSourcePolicy.AUTO,+ channelLogoSourcePolicy: ChannelLogoSourcePolicy = ChannelLogoSourcePolicy.SUPPLIER_PREFERRED,+ onProgress: ((String) -> Unit)? = null,+ id: Long? = null): Result<Provider> {val normalizedServerUrl = ProviderInputSanitizer.normalizeUrl(serverUrl)val normalizedUsername = ProviderInputSanitizer.normalizeUsername(username)@@ -366,29 +553,55 @@ class ProviderRepositoryImpl @Inject constructor(val existingProvider = if (id != null) {// Edit path: check that the new normalized identity does not collide with a// different provider before we commit the update.- val collision = providerDao.getByUrlAndUser(resolvedServerUrl, normalizedUsername)+ val collision = findProviderByConfigurationIdentity(+ XtreamConfig(resolvedServerUrl, normalizedUsername, "")+ )if (collision != null && collision.id != id) {return Result.error("A provider with this server URL and username already exists.")}- providerDao.getById(id)+ loadLegacyProvider(id)} else {- providerDao.getByUrlAndUser(resolvedServerUrl, normalizedUsername)+ findProviderByConfigurationIdentity(XtreamConfig(resolvedServerUrl, normalizedUsername, ""))+ ?.let { loadLegacyProvider(it.id) }}val effectivePassword = try {password.takeIf { it.isNotBlank() }- ?: existingProvider?.password?.let(credentialCrypto::decryptIfNeeded)+ ?: existingProvider?.password?: ""} catch (e: CredentialDecryptionException) {return Result.error(e.message ?: CredentialDecryptionException.MESSAGE, e)}- val provider = createXtreamProvider(- providerId = 0,- serverUrl = resolvedServerUrl,- username = normalizedUsername,- password = effectivePassword,- httpUserAgent = httpUserAgent,- httpHeaders = httpHeaders- )+ val candidateGeneration = existingProvider+ ?.let { providerCapabilityResolver.snapshot(it.id)?.configurationGeneration }+ ?.plus(1L)+ ?: 1L+ val provider = when (val resolution = typedProviderClientFactory.xtream(+ ProviderSnapshot(+ provider = StableProvider(+ id = 0L,+ name = normalizedName.ifBlank { "Xtream" },+ type = ProviderType.XTREAM_CODES+ ),+ configuration = XtreamConfig(+ serverUrl = resolvedServerUrl,+ username = normalizedUsername,+ password = effectivePassword,+ httpUserAgent = httpUserAgent,+ httpHeaders = httpHeaders,+ epgSyncMode = epgSyncMode,+ guideSourcePolicy = guideSourcePolicy,+ channelLogoSourcePolicy = channelLogoSourcePolicy,+ fastSyncEnabled = xtreamFastSyncEnabled,+ liveSyncMode = xtreamLiveSyncMode+ ),+ configurationGeneration = candidateGeneration+ )+ )) {+ is CapabilityResolution.Available -> resolution.capability+ is CapabilityResolution.ConfigurationError -> return Result.error(resolution.reason)+ is CapabilityResolution.Restricted -> return Result.error(resolution.reason)+ is CapabilityResolution.Unsupported -> return Result.error(resolution.reason)+ }return when (val authResult = provider.authenticate()) {is Result.Success -> {onProgress?.invoke("Profile accepted; catalog validated")@@ -430,7 +643,7 @@ class ProviderRepositoryImpl @Inject constructor(isActive = false,status = ProviderStatus.PARTIAL)- val newId = providerDao.insert(newData.toSecureEntity())+ val newId = insertConfiguredProvider(newData)InitialOnboardingTarget(providerData = newData.copy(id = newId, password = ""),providerForSync = newData.copy(id = newId)@@ -458,17 +671,17 @@ class ProviderRepositoryImpl @Inject constructor(}}- override suspend fun validateM3u(+ internal suspend fun validateM3u(url: String,name: String,- httpUserAgent: String,- httpHeaders: String,- epgSyncMode: ProviderEpgSyncMode,- m3uVodClassificationEnabled: Boolean,- guideSourcePolicy: GuideSourcePolicy,- channelLogoSourcePolicy: ChannelLogoSourcePolicy,- onProgress: ((String) -> Unit)?,- id: Long?+ httpUserAgent: String = "",+ httpHeaders: String = "",+ epgSyncMode: ProviderEpgSyncMode = ProviderEpgSyncMode.BACKGROUND,+ m3uVodClassificationEnabled: Boolean = false,+ guideSourcePolicy: GuideSourcePolicy = GuideSourcePolicy.AUTO,+ channelLogoSourcePolicy: ChannelLogoSourcePolicy = ChannelLogoSourcePolicy.SUPPLIER_PREFERRED,+ onProgress: ((String) -> Unit)? = null,+ id: Long? = null): Result<Provider> = try {val normalizedUrl = ProviderInputSanitizer.resolveUrlProtocol(ProviderInputSanitizer.normalizeUrl(url)@@ -489,13 +702,14 @@ class ProviderRepositoryImpl @Inject constructor(val existingProvider = if (id != null) {// Edit path: check that the new normalized URL does not collide with a different// provider before we commit the update.- val collision = providerDao.getByUrlAndUser(normalizedUrl, "")+ val collision = findProviderByConfigurationIdentity(M3uConfig(normalizedUrl))if (collision != null && collision.id != id) {return Result.error("A playlist provider with this URL already exists.")}- providerDao.getById(id)+ loadLegacyProvider(id)} else {- providerDao.getByUrlAndUser(normalizedUrl, "")+ findProviderByConfigurationIdentity(M3uConfig(normalizedUrl))+ ?.let { loadLegacyProvider(it.id) }}val onboardingTarget = if (existingProvider != null) {@@ -514,9 +728,9 @@ class ProviderRepositoryImpl @Inject constructor(lastSyncedAt = 0)InitialOnboardingTarget(- providerData = updated.toPublicDomain(),- providerForSync = updated.toDomain(),- pendingEdit = stageProviderEdit(updated.toDomain())+ providerData = updated.copy(password = ""),+ providerForSync = updated,+ pendingEdit = stageProviderEdit(updated))} else {val provider = Provider(@@ -533,7 +747,7 @@ class ProviderRepositoryImpl @Inject constructor(isActive = false,status = ProviderStatus.PARTIAL)- val newId = providerDao.insert(provider.toSecureEntity())+ val newId = insertConfiguredProvider(provider)InitialOnboardingTarget(providerData = provider.copy(id = newId, password = ""),providerForSync = provider.copy(id = newId)@@ -550,13 +764,13 @@ class ProviderRepositoryImpl @Inject constructor(Result.error("Failed to add M3U provider: ${e.message}", e)}- override suspend fun loginJellyfin(+ internal suspend fun loginJellyfin(serverUrl: String,username: String,password: String,name: String,- onProgress: ((String) -> Unit)?,- id: Long?+ onProgress: ((String) -> Unit)? = null,+ id: Long? = null): Result<Provider> {return try {val normalizedServerUrl = ProviderInputSanitizer.resolveUrlProtocol(@@ -571,13 +785,17 @@ class ProviderRepositoryImpl @Inject constructor(normalizedServerUrl.substringAfter("//").substringBefore("/").ifBlank { "Jellyfin" }}val existingProviderEntity = if (id != null) {- val collision = providerDao.getByUrlAndUser(normalizedServerUrl, normalizedUsername)+ val collision = findProviderByConfigurationIdentity(+ JellyfinConfig(normalizedServerUrl, normalizedUsername, "")+ )if (collision != null && collision.id != id) return Result.error("A Jellyfin provider with this server URL and username already exists.")- providerDao.getById(id)+ loadLegacyProvider(id)} else {- providerDao.getByUrlAndUser(normalizedServerUrl, normalizedUsername)+ findProviderByConfigurationIdentity(+ JellyfinConfig(normalizedServerUrl, normalizedUsername, "")+ )?.let { loadLegacyProvider(it.id) }}- val existingProvider = existingProviderEntity?.toDomain()+ val existingProvider = existingProviderEntityval authResult = when {normalizedPassword.isNotBlank() -> {onProgress?.invoke("Signing in to Jellyfin...")@@ -587,8 +805,7 @@ class ProviderRepositoryImpl @Inject constructor(is Result.Loading -> return Result.error("Unexpected loading state")}}- existingProvider != null -> try { credentialCrypto.decryptIfNeeded(existingProvider.password) }- catch (e: CredentialDecryptionException) { return Result.error(e.message ?: CredentialDecryptionException.MESSAGE, e) }+ existingProvider != null -> existingProvider.passwordelse -> return Result.error("Please enter Jellyfin password")}val onboardingTarget = if (existingProvider != null) {@@ -607,7 +824,7 @@ class ProviderRepositoryImpl @Inject constructor(val provider = Provider(name = providerName, type = ProviderType.JELLYFIN,serverUrl = normalizedServerUrl, username = normalizedUsername, password = authResult,isActive = false, status = ProviderStatus.PARTIAL)- val newId = providerDao.insert(provider.toSecureEntity())+ val newId = insertConfiguredProvider(provider)InitialOnboardingTarget(providerData = provider.copy(id = newId, password = ""),providerForSync = provider.copy(id = newId)@@ -624,8 +841,12 @@ class ProviderRepositoryImpl @Inject constructor(}}- override suspend fun loginJellyfinQuickConnect(- serverUrl: String, name: String, onCode: ((String) -> Unit)?, onProgress: ((String) -> Unit)?, id: Long?+ internal suspend fun loginJellyfinQuickConnect(+ serverUrl: String,+ name: String,+ onCode: ((String) -> Unit)? = null,+ onProgress: ((String) -> Unit)? = null,+ id: Long? = null): Result<Provider> {return try {val normalizedServerUrl = ProviderInputSanitizer.resolveUrlProtocol(@@ -636,7 +857,7 @@ class ProviderRepositoryImpl @Inject constructor(val providerName = normalizedName.ifBlank {normalizedServerUrl.substringAfter("//").substringBefore("/").ifBlank { "Jellyfin" }}- val existingProvider = if (id != null) providerDao.getById(id)?.toDomain() else null+ val existingProvider = id?.let { loadLegacyProvider(it) }onProgress?.invoke("Requesting Quick Connect code...")val quickConnect = when (val quickConnectResult = jellyfinProvider.authenticateQuickConnect(serverUrl = normalizedServerUrl, onCode = onCode, onProgress = onProgress@@ -678,7 +899,7 @@ class ProviderRepositoryImpl @Inject constructor(val provider = Provider(name = providerName, type = ProviderType.JELLYFIN,serverUrl = serverUrl, username = username, password = password,isActive = false, status = ProviderStatus.PARTIAL)- val newId = providerDao.insert(provider.toSecureEntity())+ val newId = insertConfiguredProvider(provider)InitialOnboardingTarget(providerData = provider.copy(id = newId, password = ""),providerForSync = provider.copy(id = newId)@@ -687,34 +908,34 @@ class ProviderRepositoryImpl @Inject constructor(}- override suspend fun loginStalker(+ internal suspend fun loginStalker(portalUrl: String,macAddress: String,name: String,- authMode: StalkerAuthMode,- username: String,- password: String,- httpUserAgent: String,- httpHeaders: String,- deviceProfile: String,- timezone: String,- locale: String,- serialNumber: String,- deviceId: String,- deviceId2: String,- signature: String,- stalkerAdvancedOptionsJson: String,- protocolPreference: StalkerProtocolPreference,- transportGrant: StalkerTransportGrant?,- saveWithoutVerification: Boolean,- repairConnection: Boolean,- requestedProfileId: String,- epgSyncMode: ProviderEpgSyncMode,- catalogMode: StalkerCatalogMode,- guideSourcePolicy: GuideSourcePolicy,- channelLogoSourcePolicy: ChannelLogoSourcePolicy,- onProgress: ((String) -> Unit)?,- id: Long?+ authMode: StalkerAuthMode = StalkerAuthMode.AUTO,+ username: String = "",+ password: String = "",+ httpUserAgent: String = "",+ httpHeaders: String = "",+ deviceProfile: String = "",+ timezone: String = "",+ locale: String = "",+ serialNumber: String = "",+ deviceId: String = "",+ deviceId2: String = "",+ signature: String = "",+ stalkerAdvancedOptionsJson: String = "",+ protocolPreference: StalkerProtocolPreference = StalkerProtocolPreference.AUTO,+ transportGrant: StalkerTransportGrant? = null,+ saveWithoutVerification: Boolean = false,+ repairConnection: Boolean = false,+ requestedProfileId: String = StalkerCompatibilityProfileIds.AUTO,+ epgSyncMode: ProviderEpgSyncMode = ProviderEpgSyncMode.BACKGROUND,+ catalogMode: StalkerCatalogMode = StalkerCatalogMode.ON_DEMAND,+ guideSourcePolicy: GuideSourcePolicy = GuideSourcePolicy.AUTO,+ channelLogoSourcePolicy: ChannelLogoSourcePolicy = ChannelLogoSourcePolicy.SUPPLIER_PREFERRED,+ onProgress: ((String) -> Unit)? = null,+ id: Long? = null): Result<Provider> {val normalizedPortalUrl = ProviderInputSanitizer.normalizeUrl(portalUrl)val normalizedMacAddress = ProviderInputSanitizer.normalizeMacAddress(macAddress)@@ -769,17 +990,29 @@ class ProviderRepositoryImpl @Inject constructor(val existingProvider = if (id != null) {// Edit path: check that the new normalized identity does not collide with a// different provider before we commit the update.- val collision = providerDao.getByUrlAndUser(resolvedPortalUrl, normalizedUsername, normalizedMacAddress)+ val collision = findProviderByConfigurationIdentity(+ StalkerConfig(+ portalUrl = resolvedPortalUrl,+ device = StalkerDeviceIdentity(normalizedMacAddress),+ username = normalizedUsername+ )+ )if (collision != null && collision.id != id) {return Result.error("A Stalker provider with this portal URL and identity already exists.")}- providerDao.getById(id)+ loadLegacyProvider(id)} else {- providerDao.getByUrlAndUser(resolvedPortalUrl, normalizedUsername, normalizedMacAddress)+ findProviderByConfigurationIdentity(+ StalkerConfig(+ portalUrl = resolvedPortalUrl,+ device = StalkerDeviceIdentity(normalizedMacAddress),+ username = normalizedUsername+ )+ )?.let { loadLegacyProvider(it.id) }}val effectivePassword = try {password.takeIf { it.isNotBlank() }- ?: existingProvider?.password?.let(credentialCrypto::decryptIfNeeded)+ ?: existingProvider?.password?: ""} catch (e: CredentialDecryptionException) {return Result.error(e.message ?: CredentialDecryptionException.MESSAGE, e)@@ -799,34 +1032,62 @@ class ProviderRepositoryImpl @Inject constructor(stalkerPortalStateStore.get(it.id)}- fun discoveryProvider(requireLiveReadiness: Boolean) = createStalkerProvider(- // Ordinary edits validate with the learned identity. Only a new provider or- // the explicit Repair connection action may rotate compatibility profiles.- providerId = if (existingProvider == null || repairConnection) 0L else existingProvider.id,- portalUrl = resolvedPortalUrl,- macAddress = normalizedMacAddress,- authMode = authMode,- username = normalizedUsername,- password = effectivePassword,- httpUserAgent = httpUserAgent,- httpHeaders = httpHeaders,- deviceProfile = normalizedDeviceProfile,- timezone = normalizedTimezone,- locale = normalizedLocale,- serialNumber = normalizedSerialNumber,- deviceId = normalizedDeviceId,- deviceId2 = normalizedDeviceId2,- signature = normalizedSignature,- stalkerAdvancedOptionsJson = normalizedAdvancedOptionsJson,- protocolPreference = protocolPreference,- transportGrant = effectiveTransportGrant,- requestedProfileId = requestedProfileId,- requireCatalogValidation = requireLiveReadiness,- catalogLayoutHint = existingProvider?.catalogLayout- ?: com.streamvault.domain.model.CatalogLayout.UNKNOWN,- catalogLayoutDetectionVersionHint = 0,- onProgress = onProgress- )+ val candidateGeneration = existingProvider+ ?.let { providerCapabilityResolver.snapshot(it.id)?.configurationGeneration }+ ?.plus(1L)+ ?: 1L+ fun discoveryProvider(requireLiveReadiness: Boolean): StalkerProvider {+ val providerId = if (existingProvider == null || repairConnection) 0L else existingProvider.id+ val snapshot = ProviderSnapshot(+ provider = StableProvider(+ id = providerId,+ name = normalizedName.ifBlank { "Stalker" },+ type = ProviderType.STALKER_PORTAL+ ),+ configuration = StalkerConfig(+ portalUrl = resolvedPortalUrl,+ device = StalkerDeviceIdentity(+ macAddress = normalizedMacAddress,+ deviceProfile = normalizedDeviceProfile,+ timezone = normalizedTimezone,+ locale = normalizedLocale,+ serialNumber = normalizedSerialNumber,+ deviceId = normalizedDeviceId,+ deviceId2 = normalizedDeviceId2,+ signature = normalizedSignature+ ),+ username = normalizedUsername,+ password = effectivePassword,+ httpUserAgent = httpUserAgent,+ httpHeaders = httpHeaders,+ advancedOptionsJson = normalizedAdvancedOptionsJson,+ authMode = authMode,+ requestedProfileId = requestedProfileId,+ protocolPreference = protocolPreference,+ transportGrant = effectiveTransportGrant,+ epgSyncMode = epgSyncMode,+ catalogMode = catalogMode,+ guideSourcePolicy = guideSourcePolicy,+ channelLogoSourcePolicy = channelLogoSourcePolicy+ ),+ configurationGeneration = candidateGeneration,+ accountRuntime = ProviderAccountRuntime(+ catalogLayout = existingProvider?.catalogLayout ?: CatalogLayout.UNKNOWN+ )+ )+ return when (val resolution = typedProviderClientFactory.stalker(+ snapshot,+ StalkerClientOptions(+ requireCatalogValidation = requireLiveReadiness,+ onProgress = onProgress+ )+ )) {+ is CapabilityResolution.Available -> resolution.capability+ is CapabilityResolution.ConfigurationError -> throw IllegalArgumentException(resolution.reason)+ is CapabilityResolution.Restricted -> throw IllegalArgumentException(resolution.reason)+ is CapabilityResolution.Unsupported -> throw IllegalArgumentException(resolution.reason)+ }+ }var authenticatedProvider = discoveryProvider(requireLiveReadiness = true)var authResult = authenticatedProvider.authenticate()@@ -839,6 +1100,10 @@ class ProviderRepositoryImpl @Inject constructor(}if (saveWithoutVerification && readinessWasInconclusive != null) {onProgress?.invoke("Authentication confirmed; saving with Live TV verification pending")+ // The failed readiness attempt is cached per portal/API identity. Clear that failure+ // before the deliberately weaker authentication retry, otherwise the retry returns+ // the cached inconclusive result without issuing the confirmation request.+ authenticatedProvider.invalidateAuthentication()authenticatedProvider = discoveryProvider(requireLiveReadiness = false)authResult = authenticatedProvider.authenticate()acceptedWithoutVerification = authResult is Result.Success@@ -860,8 +1125,7 @@ class ProviderRepositoryImpl @Inject constructor(StalkerDiscoveryStageEntity(discoveryId = discoveryId,providerId = existingProvider?.id,- configurationGeneration =- (existingProvider?.stalkerConfigurationGeneration ?: 0L) + 1L,+ configurationGeneration = candidateGeneration,sanitizedSummary = discoverySummary,createdAt = stagedAt)@@ -893,8 +1157,7 @@ class ProviderRepositoryImpl @Inject constructor(?: resolvedPortalUrl.toStalkerOrigin()?.toPersistenceValue().orEmpty(),stalkerTlsSpkiSha256 = effectiveTransportGrant?.spkiSha256.orEmpty(),stalkerTransportConsentAt = effectiveTransportGrant?.consentedAt ?: 0L,- stalkerConfigurationGeneration =- existingProvider.stalkerConfigurationGeneration + 1L,+ stalkerConfigurationGeneration = candidateGeneration,stalkerDiscoverySummary = discoverySummary,stalkerCapabilitiesJson = capabilitySummary,stalkerRequestedProfileId = requestedProfileId,@@ -910,13 +1173,6 @@ class ProviderRepositoryImpl @Inject constructor(lastSyncedAt = 0L,createdAt = existingProvider.createdAt)- validatedSnapshot?.let { (session, validatedProfile) ->- stalkerPortalStateStore.recordAuthentication(- providerId = updated.id,- session = session,- profile = validatedProfile- )- }stalkerDiscoveryStageDao?.delete(discoveryId)InitialOnboardingTarget(providerData = updated.copy(password = ""),@@ -962,12 +1218,13 @@ class ProviderRepositoryImpl @Inject constructor(status = ProviderStatus.PARTIAL)val newId = transactionRunner.inTransaction {- val insertedId = providerDao.insert(newData.toSecureEntity())+ val insertedId = insertConfiguredProvider(newData)validatedSnapshot?.let { (session, validatedProfile) ->stalkerPortalStateStore.recordAuthentication(providerId = insertedId,session = session,- profile = validatedProfile+ profile = validatedProfile,+ configurationGeneration = 1L)}stalkerDiscoveryStageDao?.delete(discoveryId)@@ -979,40 +1236,79 @@ class ProviderRepositoryImpl @Inject constructor()}- val onboardingResult = if (acceptedWithoutVerification) {- syncManager.scheduleProviderSyncResume(- onboardingTarget.providerData.id,- onboardingTarget.providerData.stalkerConfigurationGeneration- )- val message =- "Provider saved with Live TV verification pending. It needs a successful sync before activation."- Result.error(- message,- ProviderSavedWithSyncErrorException(- provider = onboardingTarget.providerData.copy(- status = ProviderStatus.PARTIAL,- isActive = false- ),- message = message+ val onboardingResult = try {+ if (acceptedWithoutVerification) {+ syncManager.scheduleProviderSyncResume(+ onboardingTarget.providerData.id,+ onboardingTarget.providerData.stalkerConfigurationGeneration+ )+ val message =+ "Provider saved with Live TV verification pending. It needs a successful sync before activation."+ Result.error(+ message,+ ProviderSavedWithSyncErrorException(+ provider = onboardingTarget.providerData.copy(+ status = ProviderStatus.PARTIAL,+ isActive = false+ ),+ message = message+ ))+ } else {+ handleInitialOnboardingSync(+ providerData = onboardingTarget.providerData,+ syncResult = syncInitialOnboarding(onboardingTarget, onProgress),+ syncFailurePrefix = "Provider login succeeded, but initial sync failed. The provider was saved and can be retried from Settings",+ pendingEdit = onboardingTarget.pendingEdit+ )+ }+ } catch (cancelled: CancellationException) {+ // Authentication state is provider-scoped. A cancelled edit must not leave+ // the old active configuration using the replacement session/recipe.+ restoreStalkerEditIfStillPending(+ existingProvider = existingProvider,+ pendingEdit = onboardingTarget.pendingEdit,+ previousPortalState = previousPortalState)- } else {- handleInitialOnboardingSync(- providerData = onboardingTarget.providerData,- syncResult = syncInitialOnboarding(onboardingTarget, onProgress),- syncFailurePrefix = "Provider login succeeded, but initial sync failed. The provider was saved and can be retried from Settings",- pendingEdit = onboardingTarget.pendingEdit+ throw cancelled+ }+ // Existing edits are staged until the first catalog transaction promotes the+ // candidate. Persisting authentication learning before that point would fail the+ // generation CAS (or, without it, attach the new observations to the old config).+ if (existingProvider != null &&+ !acceptedWithoutVerification &&+ validatedSnapshot != null &&+ onboardingTarget.pendingEdit?.let { pending ->+ providerConfigRevisionDao.getState(existingProvider.id, pending.revision) ==+ ProviderConfigRevisionState.COMMITTED+ } == true &&+ providerSnapshotDao.getConfig(existingProvider.id)?.configurationGeneration == candidateGeneration+ ) {+ val (session, validatedProfile) = validatedSnapshot+ stalkerPortalStateStore.recordAuthentication(+ providerId = existingProvider.id,+ session = session,+ profile = validatedProfile,+ configurationGeneration = candidateGeneration)}if (existingProvider != null && onboardingResult is Result.Error && !acceptedWithoutVerification) {- transactionRunner.inTransaction {- providerDao.update(existingProvider)- stalkerPortalStateStore.restore(existingProvider.id, previousPortalState)+ val restored = restoreStalkerEditIfStillPending(+ existingProvider = existingProvider,+ pendingEdit = onboardingTarget.pendingEdit,+ previousPortalState = previousPortalState+ )+ if (restored) {+ Result.error(+ "The new Stalker settings were not saved because initial readiness failed. The previous provider configuration is still active.",+ onboardingResult.exception?.cause ?: onboardingResult.exception+ )+ } else {+ // The first catalog transaction already promoted this edit. Keep the+ // candidate row aligned with the committed replacement catalog even if+ // a later optional phase reported an error.+ onboardingResult}- Result.error(- "The new Stalker settings were not saved because initial readiness failed. The previous provider configuration is still active.",- onboardingResult.exception?.cause ?: onboardingResult.exception- )} else {onboardingResult}@@ -1067,12 +1363,18 @@ class ProviderRepositoryImpl @Inject constructor(val now = System.currentTimeMillis()val revision = transactionRunner.inTransaction {val nextRevision = providerConfigRevisionDao.latestRevision(candidate.id) + 1L+ val configurationGeneration =+ (providerSnapshotDao.getConfig(candidate.id)?.configurationGeneration ?: 0L) + 1LproviderConfigRevisionDao.supersedeOlder(candidate.id, nextRevision, now)providerConfigRevisionDao.upsert(ProviderConfigRevisionEntity(providerId = candidate.id,revision = nextRevision,- configJson = gson.toJson(secureCandidate),+ configJson = ProviderConfigRevisionCodec(+ gson,+ providerConfigurationCodec,+ credentialCrypto+ ).encode(candidate, configurationGeneration),state = ProviderConfigRevisionState.PENDING,createdAt = now,updatedAt = now@@ -1108,7 +1410,10 @@ class ProviderRepositoryImpl @Inject constructor(} else {syncManager.syncWithProviderOverride(providerId = target.providerData.id,- force = false,+ // A staged edit must validate and publish the replacement catalog even when the+ // committed provider's cache is still fresh. Otherwise a successful edit can+ // finish without invoking the promotion callback and remain forever pending.+ force = true,onProgress = onProgress,trackInitialLiveOnboarding = trackInitialLiveOnboarding,providerOverride = pendingEdit.candidate,@@ -1117,16 +1422,118 @@ class ProviderRepositoryImpl @Inject constructor(}} catch (error: kotlinx.coroutines.CancellationException) {target.pendingEdit?.let { pendingEdit ->- providerConfigRevisionDao.releaseForRetry(- pendingEdit.candidate.id,- pendingEdit.revision,- System.currentTimeMillis()- )+ withContext(NonCancellable) {+ providerConfigRevisionDao.releaseForRetry(+ pendingEdit.candidate.id,+ pendingEdit.revision,+ System.currentTimeMillis()+ )+ }}throw error}}+ private suspend fun persistTypedSnapshot(+ providerId: Long,+ provider: Provider,+ currentGeneration: Long?+ ) {+ val configuration = provider.toTypedConfiguration()+ val currentConfiguration = providerSnapshotDao.getConfig(providerId)?.let { stored ->+ runCatching { providerConfigurationCodec.decode(stored.type, stored.encryptedConfigJson) }.getOrNull()+ }+ val generation = when {+ currentGeneration == null -> maxOf(1L, provider.stalkerConfigurationGeneration)+ currentConfiguration == configuration -> currentGeneration+ else -> currentGeneration + 1L+ }+ if (currentGeneration == null || currentConfiguration != configuration) {+ val committed = providerSnapshotDao.commitConfiguration(+ ProviderConfigEntity(+ providerId = providerId,+ type = provider.type,+ schemaVersion = configuration.schemaVersion,+ configurationGeneration = generation,+ identityKey = providerConfigurationCodec.identityKey(configuration),+ encryptedConfigJson = providerConfigurationCodec.encode(configuration),+ guideSourcePolicy = configuration.guidePolicy(),+ channelLogoSourcePolicy = configuration.logoPolicy(),+ updatedAt = System.currentTimeMillis()+ )+ )+ check(committed) { "Provider configuration generation was superseded" }+ }+ val runtime = provider.toAccountRuntime()+ providerSnapshotDao.upsertRuntime(+ ProviderAccountRuntimeEntity(+ providerId = providerId,+ maxConnections = runtime.maxConnections,+ expirationDate = runtime.expirationDate,+ apiVersion = runtime.apiVersion,+ allowedOutputFormatsJson = gson.toJson(runtime.allowedOutputFormats),+ catalogLayout = runtime.catalogLayout,+ catalogLayoutDetectionVersion = runtime.catalogLayoutDetectionVersion,+ observedAt = runtime.observedAt+ )+ )+ }++ private suspend fun insertConfiguredProvider(provider: Provider): Long =+ transactionRunner.inTransaction {+ val providerId = providerDao.insert(provider.toEntity())+ persistTypedSnapshot(providerId, provider, currentGeneration = null)+ providerId+ }++ private suspend fun findProviderByConfigurationIdentity(+ configuration: ProviderConfiguration+ ): ProviderEntity? = providerSnapshotDao+ .findProviderIdByIdentityKey(providerConfigurationCodec.identityKey(configuration))+ ?.let { providerDao.getById(it) }++ private suspend fun loadLegacyProvider(providerId: Long): Provider? =+ providerCapabilityResolver.snapshot(providerId)?.toLegacyProvider()++ private fun ProviderAccountRuntimeEntity.toDomainRuntime() = ProviderAccountRuntime(+ maxConnections = maxConnections,+ expirationDate = expirationDate,+ apiVersion = apiVersion,+ allowedOutputFormats = runCatching {+ gson.fromJson(allowedOutputFormatsJson, Array<String>::class.java).toList()+ }.getOrDefault(emptyList()),+ catalogLayout = catalogLayout,+ catalogLayoutDetectionVersion = catalogLayoutDetectionVersion,+ observedAt = observedAt+ )++ private suspend fun restoreStalkerEditIfStillPending(+ existingProvider: Provider?,+ pendingEdit: PendingProviderEdit?,+ previousPortalState: StalkerPortalStateEntity?+ ): Boolean {+ if (existingProvider == null || pendingEdit == null) return false+ return withContext(NonCancellable) {+ transactionRunner.inTransaction {+ // Read and restore in one Room transaction so a newer edit cannot be+ // overwritten by cleanup from an older cancelled/erroring edit.+ val state = providerConfigRevisionDao.getState(+ pendingEdit.candidate.id,+ pendingEdit.revision+ )+ val isCurrentUncommitted = state in setOf(+ ProviderConfigRevisionState.PENDING,+ ProviderConfigRevisionState.SYNCING,+ ProviderConfigRevisionState.FAILED+ ) && providerConfigRevisionDao.latestRevision(pendingEdit.candidate.id) == pendingEdit.revision+ if (!isCurrentUncommitted) return@inTransaction false+ providerDao.update(existingProvider.toEntity())+ stalkerPortalStateStore.restore(existingProvider.id, previousPortalState)+ true+ }+ }+ }+/*** Called while the catalog transaction is open. A stale revision is* rejected before it can replace the provider row, making a late sync completion harmless.@@ -1140,6 +1547,11 @@ class ProviderRepositoryImpl @Inject constructor(now) == 1) { "Provider edit ${pendingEdit.revision} was superseded before catalog commit." }+ persistTypedSnapshot(+ pendingEdit.candidate.id,+ pendingEdit.candidate,+ providerSnapshotDao.getConfig(pendingEdit.candidate.id)?.configurationGeneration+ )providerDao.update(pendingEdit.secureCandidate.copy(isActive = true,@@ -1290,7 +1702,7 @@ class ProviderRepositoryImpl @Inject constructor(): Result<Unit> {if (force && providerDao.getById(providerId)?.type == ProviderType.STALKER_PORTAL) {stalkerPortalStateStore.invalidateCapabilities(providerId)- providerDao.invalidateCatalogLayoutDetection(providerId)+ providerSnapshotDao.invalidateCatalogLayoutDetection(providerId)}var syncResult: Result<Unit>? = nullval disposition = providerWorkflowRunner.execute(@@ -1402,48 +1814,29 @@ class ProviderRepositoryImpl @Inject constructor(epgChannelId: String?,limit: Int): Result<List<Program>> {- val providerEntity = providerDao.getById(providerId)+ val providerEntity = loadLegacyProvider(providerId)?: return Result.error("Provider $providerId not found")- if (!allowsOnDemandGuide(providerEntity.toPublicDomain())) {+ if (!allowsOnDemandGuide(providerEntity)) {return Result.error("On-demand guide lookup is disabled for this provider.")}- return when (providerEntity.type) {- ProviderType.XTREAM_CODES -> when (val providerContextResult = createXtreamLiveProgramProviderContext(providerId)) {- is Result.Success -> {- val result = fetchXtreamProgramsForLiveStream(- providerId = providerId,- streamId = streamId,- epgChannelId = epgChannelId,- limit = limit,- xtreamProvider = providerContextResult.data- )- if (result is Result.Success && result.data.isNotEmpty()) {- cacheProgramsForChannel(providerId, result.data)- refreshCachedEpgMetadata(providerId)- }- result- }- is Result.Error -> Result.error(providerContextResult.message, providerContextResult.exception)- is Result.Loading -> Result.error("Unexpected loading state")- }- ProviderType.STALKER_PORTAL -> {- val stalkerProvider = createStalkerProviderFromEntity(providerEntity)- val channelKey = epgChannelId?.takeIf { it.isNotBlank() } ?: streamId.toString()- when (val result = stalkerProvider.getShortEpg(channelKey, limit)) {- is Result.Success -> {- if (result.data.isNotEmpty()) {- cacheProgramsForChannel(providerId, result.data)- refreshCachedEpgMetadata(providerId)- }- result- }- is Result.Error -> Result.error(result.message, result.exception)- is Result.Loading -> Result.error("Unexpected loading state")- }- }- ProviderType.M3U,- ProviderType.JELLYFIN -> Result.error("On-demand guide lookup is unavailable for this provider.")+ val guide = when (val resolution = resolveGuideCapability(providerId)) {+ is CapabilityResolution.Available -> resolution.capability+ is CapabilityResolution.ConfigurationError -> return Result.error(resolution.reason)+ is CapabilityResolution.Restricted -> return Result.error(resolution.reason)+ is CapabilityResolution.Unsupported -> return Result.error(resolution.reason)}+ val result = fetchProgramsForLiveStream(+ providerId = providerId,+ streamId = streamId,+ epgChannelId = epgChannelId,+ limit = limit,+ guide = guide+ )+ if (result is Result.Success && result.data.isNotEmpty()) {+ cacheProgramsForChannel(providerId, result.data)+ refreshCachedEpgMetadata(providerId)+ }+ return result}override suspend fun getProgramsForLiveStreams(@@ -1458,70 +1851,45 @@ class ProviderRepositoryImpl @Inject constructor(return emptyMap()}- val providerEntity = providerDao.getById(providerId)+ val providerEntity = loadLegacyProvider(providerId)?: return normalizedRequests.associateWith { Result.error("Provider $providerId not found") }- if (!allowsOnDemandGuide(providerEntity.toPublicDomain())) {+ if (!allowsOnDemandGuide(providerEntity)) {return normalizedRequests.associateWith {Result.error("On-demand guide lookup is disabled for this provider.")}}- return when (providerEntity.type) {- ProviderType.XTREAM_CODES -> when (val providerContextResult = createXtreamLiveProgramProviderContext(providerId)) {- is Result.Success -> coroutineScope {- val requestDispatcher = Dispatchers.IO.limitedParallelism(XTREAM_GUIDE_BATCH_CONCURRENCY)- normalizedRequests- .map { request ->- async(requestDispatcher) {- request to fetchXtreamProgramsForLiveStream(- providerId = providerId,- streamId = request.streamId,- epgChannelId = request.epgChannelId,- limit = limit,- xtreamProvider = providerContextResult.data- )- }- }- .awaitAll()- .also { results ->- val cachedPrograms = results- .mapNotNull { (_, result) -> (result as? Result.Success)?.data }- .flatten()- if (cachedPrograms.isNotEmpty()) {- cacheProgramsForChannels(providerId, cachedPrograms)- refreshCachedEpgMetadata(providerId)- }- }- .toMap()- }- is Result.Error -> normalizedRequests.associateWith {- Result.error(providerContextResult.message, providerContextResult.exception)- }- is Result.Loading -> normalizedRequests.associateWith {- Result.error("Unexpected loading state")- }- }- ProviderType.STALKER_PORTAL -> {- val stalkerProvider = createStalkerProviderFromEntity(providerEntity)- val results = normalizedRequests.associateWith { request ->- stalkerProvider.getShortEpg(- request.epgChannelId?.takeIf { it.isNotBlank() } ?: request.streamId.toString(),- limit- )+ val guide = when (val resolution = resolveGuideCapability(providerId)) {+ is CapabilityResolution.Available -> resolution.capability+ is CapabilityResolution.ConfigurationError -> return normalizedRequests.associateWith { Result.error(resolution.reason) }+ is CapabilityResolution.Restricted -> return normalizedRequests.associateWith { Result.error(resolution.reason) }+ is CapabilityResolution.Unsupported -> return normalizedRequests.associateWith { Result.error(resolution.reason) }+ }+ return coroutineScope {+ val requestDispatcher = Dispatchers.IO.limitedParallelism(XTREAM_GUIDE_BATCH_CONCURRENCY)+ normalizedRequests+ .map { request ->+ async(requestDispatcher) {+ request to fetchProgramsForLiveStream(+ providerId = providerId,+ streamId = request.streamId,+ epgChannelId = request.epgChannelId,+ limit = limit,+ guide = guide+ )+ }}- val cachedPrograms = results.values- .mapNotNull { (it as? Result.Success)?.data }- .flatten()- if (cachedPrograms.isNotEmpty()) {- cacheProgramsForChannels(providerId, cachedPrograms)- refreshCachedEpgMetadata(providerId)+ .awaitAll()+ .also { results ->+ val cachedPrograms = results+ .mapNotNull { (_, result) -> (result as? Result.Success)?.data }+ .flatten()+ if (cachedPrograms.isNotEmpty()) {+ cacheProgramsForChannels(providerId, cachedPrograms)+ refreshCachedEpgMetadata(providerId)+ }}- results- }- ProviderType.M3U,- ProviderType.JELLYFIN -> normalizedRequests.associateWith {- Result.error("On-demand guide lookup is unavailable for this provider.")- }+ .toMap()}}@@ -1530,34 +1898,26 @@ class ProviderRepositoryImpl @Inject constructor(}override suspend fun buildCatchUpUrls(providerId: Long, streamId: Long, start: Long, end: Long): List<String> {- val providerEntity = providerDao.getById(providerId) ?: return emptyList()- val provider = providerEntity.toPublicDomain()- val providerPassword = credentialCrypto.decryptIfNeeded(providerEntity.password)+ providerDao.getById(providerId) ?: return emptyList()val channel = channelDao.getById(streamId)val resolvedStreamId = channel?.streamId?.takeIf { it > 0 } ?: streamId- return when (provider.type) {- ProviderType.XTREAM_CODES -> createXtreamProvider(- providerId = providerId,- serverUrl = provider.serverUrl,- username = provider.username,- password = providerPassword,- allowedOutputFormats = provider.allowedOutputFormats,- httpUserAgent = provider.httpUserAgent,- httpHeaders = provider.httpHeaders- ).buildCatchUpUrls(resolvedStreamId, start, end)- ProviderType.M3U -> {- val source = channel?.catchUpSource ?: return emptyList()- buildM3uCatchUpUrls(source, start, end)- }- ProviderType.STALKER_PORTAL -> createStalkerProviderFromEntity(providerEntity).buildCatchUpUrls(+ val capabilitySet = when (val resolution = providerCapabilityResolver.resolve(providerId)) {+ is CapabilityResolution.Available -> resolution.capability+ else -> return emptyList()+ }+ val catchUp = when (val resolution = capabilitySet.catchUp()) {+ is CapabilityResolution.Available -> resolution.capability+ else -> return emptyList()+ }+ return catchUp.buildCatchUpUrls(+ CatchUpRequest(streamId = resolvedStreamId,start = start,end = end,sourceStreamUrl = channel?.streamUrl,- sourceCatchUpSource = channel?.catchUpSource+ sourceCatchUpTemplate = channel?.catchUpSource)- ProviderType.JELLYFIN -> emptyList()- }+ )}suspend fun createXtreamProvider(@@ -1568,22 +1928,25 @@ class ProviderRepositoryImpl @Inject constructor(allowedOutputFormats: List<String> = emptyList(),httpUserAgent: String = "",httpHeaders: String = ""- ): IptvProvider {- val enableBase64TextCompatibility = preferencesRepository.xtreamBase64TextCompatibility.first()- return XtreamProvider(- providerId = providerId,- api = xtreamApiService,- serverUrl = serverUrl,- username = username,- password = password,- allowedOutputFormats = allowedOutputFormats,- enableBase64TextCompatibility = enableBase64TextCompatibility,- requestProfile = buildGenericProviderRequestProfile(- ownerTag = "provider:$providerId/xtream",+ ): XtreamProvider {+ val snapshot = ProviderSnapshot(+ provider = StableProvider(providerId, "Xtream", ProviderType.XTREAM_CODES),+ configuration = XtreamConfig(+ serverUrl = serverUrl,+ username = username,+ password = password,httpUserAgent = httpUserAgent,httpHeaders = httpHeaders- )+ ),+ configurationGeneration = 1L,+ accountRuntime = ProviderAccountRuntime(allowedOutputFormats = allowedOutputFormats))+ return when (val resolution = typedProviderClientFactory.xtream(snapshot)) {+ is CapabilityResolution.Available -> resolution.capability+ is CapabilityResolution.ConfigurationError -> throw IllegalArgumentException(resolution.reason)+ is CapabilityResolution.Restricted -> throw IllegalArgumentException(resolution.reason)+ is CapabilityResolution.Unsupported -> throw IllegalArgumentException(resolution.reason)+ }}private fun createStalkerProvider(@@ -1615,123 +1978,148 @@ class ProviderRepositoryImpl @Inject constructor(transportGrant: StalkerTransportGrant? = null,requestedProfileId: String = StalkerCompatibilityProfileIds.AUTO,learnedProfileId: String = "",+ configurationGeneration: Long = 0L,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(- providerId = providerId,- api = stalkerApiService,- portalUrl = portalUrl,- macAddress = macAddress,- authMode = authMode,- username = username,- password = password,- httpUserAgent = httpUserAgent,- httpHeaders = httpHeaders,- portalFingerprintHint = portalFingerprintHint,- magPresetHint = magPresetHint,- bootstrapRecipeHint = bootstrapRecipeHint,- endpointPreferenceHint = endpointPreferenceHint,- cookieModeHint = cookieModeHint,- playbackBackendHint = playbackBackendHint,- portalProfileHint = portalProfileHint,- preferredPlaybackMode = preferredPlaybackMode,- deviceProfile = deviceProfile,- timezone = timezone,- locale = locale,- serialNumber = serialNumber,- deviceId = deviceId,- deviceId2 = deviceId2,- signature = signature,- stalkerAdvancedOptionsJson = stalkerAdvancedOptionsJson,- protocolPreference = protocolPreference,- transportGrant = transportGrant,- requestedProfileId = requestedProfileId,- learnedProfileId = learnedProfileId,- requireCatalogValidation = requireCatalogValidation,- catalogLayoutHint = catalogLayoutHint,- catalogLayoutDetectionVersionHint = catalogLayoutDetectionVersionHint,- identityResolver = stalkerRemoteIdentityResolver,- portalStateStore = stalkerPortalStateStore,- onProgress = onProgress- )- }-- private fun createStalkerProviderFromEntity(entity: ProviderEntity): StalkerProvider {- return createStalkerProvider(- providerId = entity.id,- portalUrl = entity.serverUrl,- macAddress = entity.stalkerMacAddress,- authMode = entity.stalkerAuthMode,- username = entity.username,- password = try {- credentialCrypto.decryptIfNeeded(entity.password)- } catch (_: Throwable) {- ""+ val generation = configurationGeneration.coerceAtLeast(1L)+ val learning = StalkerPortalLearning(+ configurationGeneration = generation,+ profileId = learnedProfileId.takeIf(String::isNotBlank)?.let {+ StalkerObservation(it, generation, StalkerObservationSource.DISCOVERY, 0L)},- httpUserAgent = entity.httpUserAgent,- httpHeaders = entity.httpHeaders,- portalFingerprintHint = entity.stalkerPortalFingerprint,- magPresetHint = entity.stalkerMagPreset,- bootstrapRecipeHint = entity.stalkerLastBootstrapRecipe,- endpointPreferenceHint = entity.stalkerEndpointPreference,- cookieModeHint = entity.stalkerCookieMode,- playbackBackendHint = entity.stalkerPlaybackBackendHint,- portalProfileHint = entity.stalkerPortalProfile,- preferredPlaybackMode = entity.stalkerLastPlaybackMode- ?.let { runCatching { StalkerPlaybackMode.valueOf(it) }.getOrNull() },- deviceProfile = entity.stalkerDeviceProfile,- timezone = entity.stalkerDeviceTimezone,- locale = entity.stalkerDeviceLocale,- serialNumber = entity.stalkerSerialNumber,- deviceId = entity.stalkerDeviceId,- deviceId2 = entity.stalkerDeviceId2,- signature = entity.stalkerSignature,- stalkerAdvancedOptionsJson = entity.stalkerAdvancedOptionsJson,- protocolPreference = entity.stalkerProtocolPreference,- transportGrant = entity.toStalkerTransportGrant(),- requestedProfileId = entity.stalkerRequestedProfileId,- learnedProfileId = entity.stalkerLearnedProfileId,- catalogLayoutHint = entity.catalogLayout,- catalogLayoutDetectionVersionHint = entity.catalogLayoutDetectionVersion+ portalProfile = StalkerObservation(portalProfileHint, generation, StalkerObservationSource.DISCOVERY, 0L),+ portalFingerprint = StalkerObservation(portalFingerprintHint, generation, StalkerObservationSource.DISCOVERY, 0L),+ magPreset = StalkerObservation(magPresetHint, generation, StalkerObservationSource.DISCOVERY, 0L),+ bootstrapRecipe = StalkerObservation(bootstrapRecipeHint, generation, StalkerObservationSource.DISCOVERY, 0L),+ endpointPreference = StalkerObservation(endpointPreferenceHint, generation, StalkerObservationSource.DISCOVERY, 0L),+ cookieMode = StalkerObservation(cookieModeHint, generation, StalkerObservationSource.DISCOVERY, 0L),+ playbackBackendHint = StalkerObservation(playbackBackendHint, generation, StalkerObservationSource.DISCOVERY, 0L),+ lastPlaybackMode = preferredPlaybackMode?.name?.let {+ StalkerObservation(it, generation, StalkerObservationSource.DISCOVERY, 0L)+ })+ val snapshot = ProviderSnapshot(+ provider = StableProvider(providerId, "Stalker", ProviderType.STALKER_PORTAL),+ configuration = StalkerConfig(+ portalUrl = portalUrl,+ device = StalkerDeviceIdentity(+ macAddress,+ deviceProfile,+ timezone,+ locale,+ serialNumber,+ deviceId,+ deviceId2,+ signature+ ),+ username = username,+ password = password,+ httpUserAgent = httpUserAgent,+ httpHeaders = httpHeaders,+ advancedOptionsJson = stalkerAdvancedOptionsJson,+ authMode = authMode,+ requestedProfileId = requestedProfileId,+ protocolPreference = protocolPreference,+ transportGrant = transportGrant+ ),+ configurationGeneration = generation,+ accountRuntime = ProviderAccountRuntime(+ catalogLayout = catalogLayoutHint,+ catalogLayoutDetectionVersion = catalogLayoutDetectionVersionHint+ ),+ stalkerLearning = learning+ )+ return when (val resolution = typedProviderClientFactory.stalker(+ snapshot,+ StalkerClientOptions(requireCatalogValidation, onProgress)+ )) {+ is CapabilityResolution.Available -> resolution.capability+ is CapabilityResolution.ConfigurationError -> throw IllegalArgumentException(resolution.reason)+ is CapabilityResolution.Restricted -> throw IllegalArgumentException(resolution.reason)+ is CapabilityResolution.Unsupported -> throw IllegalArgumentException(resolution.reason)+ }}private fun ProviderEntity.toPublicDomain(): Provider {return toDomain().copy(password = "")}- private suspend fun createXtreamLiveProgramProviderContext(providerId: Long): Result<XtreamProvider> {- if (providerId <= 0L) {- return Result.error("Live stream context is unavailable.")- }+ /** Public provider projections must never expose decrypted account credentials. */+ private fun Provider.redactedCredentials(): Provider = copy(password = "")- val providerEntity = providerDao.getById(providerId)- ?: return Result.error("Provider $providerId not found")- val provider = providerEntity.toPublicDomain()- if (provider.type != ProviderType.XTREAM_CODES) {- return Result.error("On-demand guide lookup is available only for Xtream providers.")- }+ /**+ * Settings edit a redacted public projection. Do not turn those non-secret edits into a+ * credential deletion; explicit setup/password changes still pass a nonblank value through.+ */+ private fun Provider.withPersistedCredential(+ currentConfiguration: ProviderConfiguration?+ ): Provider {+ if (password.isNotBlank()) return this+ val existingPassword = when (currentConfiguration) {+ is XtreamConfig -> currentConfiguration.password+ is StalkerConfig -> currentConfiguration.password+ is JellyfinConfig -> currentConfiguration.credential+ is M3uConfig, null -> ""+ }+ return if (existingPassword.isBlank()) this else copy(password = existingPassword)+ }- val providerPassword = try {- credentialCrypto.decryptIfNeeded(providerEntity.password)- } catch (e: CredentialDecryptionException) {- return Result.error(e.message ?: CredentialDecryptionException.MESSAGE, e)+ private suspend fun resolveGuideCapability(providerId: Long): CapabilityResolution<GuideSource> =+ when (val providerResolution = providerCapabilityResolver.resolve(providerId)) {+ is CapabilityResolution.Available -> providerResolution.capability.guide()+ is CapabilityResolution.ConfigurationError -> providerResolution+ is CapabilityResolution.Restricted -> providerResolution+ is CapabilityResolution.Unsupported -> providerResolution}- return Result.success(- createXtreamProvider(- providerId = providerId,- serverUrl = provider.serverUrl,- username = provider.username,- password = providerPassword,- allowedOutputFormats = provider.allowedOutputFormats,- httpUserAgent = provider.httpUserAgent,- httpHeaders = provider.httpHeaders- ) as XtreamProvider+ private suspend fun fetchProgramsForLiveStream(+ providerId: Long,+ streamId: Long,+ epgChannelId: String?,+ limit: Int,+ guide: GuideSource+ ): Result<List<Program>> {+ if (providerId <= 0L || streamId <= 0L) {+ return Result.error("Live stream context is unavailable.")+ }+ val request = GuideRequest(+ streamId = streamId,+ epgChannelId = epgChannelId,+ limit = limit.coerceAtLeast(1))+ val shortResult = guide.getShortEpg(request)+ val shortPrograms = (shortResult as? Result.Success)?.data+ ?.sortedBy(Program::startTime)+ .orEmpty()+ if (shortPrograms.isNotEmpty()) {+ return Result.success(+ normalizeXtreamPrograms(providerId, epgChannelId ?: streamId.toString(), shortPrograms)+ )+ }+ return when (val fullResult = guide.getEpg(request)) {+ is Result.Success -> Result.success(+ normalizeXtreamPrograms(+ providerId,+ epgChannelId ?: streamId.toString(),+ fullResult.data.sortedBy(Program::startTime)+ )+ )+ is Result.Error -> {+ val shortError = shortResult as? Result.Error+ Result.error(+ listOfNotNull(shortError?.message, fullResult.message)+ .filter(String::isNotBlank)+ .distinct()+ .joinToString(" / ")+ .ifBlank { "Failed to load on-demand guide" },+ fullResult.exception ?: shortError?.exception+ )+ }+ is Result.Loading -> Result.error("Unexpected loading state")+ }}private suspend fun fetchXtreamProgramsForLiveStream(@@ -1807,7 +2195,7 @@ class ProviderRepositoryImpl @Inject constructor(}private suspend fun maybeScheduleBackgroundEpgSync(providerId: Long) {- val provider = providerDao.getById(providerId) ?: return+ val provider = loadLegacyProvider(providerId) ?: returnif (provider.epgSyncMode != ProviderEpgSyncMode.BACKGROUND) {return}@@ -1869,7 +2257,7 @@ class ProviderRepositoryImpl @Inject constructor(}}-private fun ProviderEntity.toStalkerTransportGrant(): StalkerTransportGrant? {+private fun Provider.toStalkerTransportGrant(): StalkerTransportGrant? {if (stalkerTransportMode != StalkerTransportMode.USER_ACCEPTED_HTTP &&stalkerTransportMode != StalkerTransportMode.USER_ACCEPTED_UNVERIFIED_HTTPS &&stalkerTransportMode != StalkerTransportMode.VERIFIED_HTTPSdiff --git a/data/src/main/java/com/streamvault/data/repository/SeriesRepositoryImpl.kt b/data/src/main/java/com/streamvault/data/repository/SeriesRepositoryImpl.ktindex 93bdd7af..df318efd 100644--- a/data/src/main/java/com/streamvault/data/repository/SeriesRepositoryImpl.kt+++ b/data/src/main/java/com/streamvault/data/repository/SeriesRepositoryImpl.kt@@ -5,32 +5,23 @@ import android.util.Logimport com.streamvault.data.local.dao.*import com.streamvault.data.local.entity.*import com.streamvault.data.mapper.*-import com.streamvault.data.remote.jellyfin.JellyfinProvider-import com.streamvault.data.remote.http.toGenericRequestProfile-import com.streamvault.data.remote.stalker.StalkerApiServiceimport com.streamvault.data.remote.stalker.StalkerContentCapabilitiesCodecimport com.streamvault.data.remote.stalker.StalkerEpisodeSelectorDialect-import com.streamvault.data.remote.stalker.StalkerPlaybackModeimport com.streamvault.data.remote.stalker.StalkerProvider-import com.streamvault.data.remote.stalker.StalkerRemoteIdentityResolverimport com.streamvault.data.remote.stalker.StalkerRequestCoordinatorimport com.streamvault.data.remote.stalker.StalkerRequestDescriptorimport com.streamvault.data.remote.stalker.StalkerResponseMetrics-import com.streamvault.data.remote.stalker.StalkerPortalStateStoreimport com.streamvault.data.remote.stalker.StalkerTrafficCoordinatorimport com.streamvault.data.remote.stalker.StalkerSeriesDetailDialectimport com.streamvault.data.remote.stalker.StalkerUrlFactoryimport com.streamvault.data.remote.stalker.StalkerVodPlaybackDialect-import com.streamvault.data.remote.stalker.stalkerTransportGrantOrNull-import com.streamvault.data.remote.xtream.XtreamApiService-import com.streamvault.data.remote.xtream.XtreamProviderimport com.streamvault.data.remote.xtream.XtreamStreamUrlResolver-import com.streamvault.data.security.CredentialCryptoimport com.streamvault.data.sync.ContentCachePolicyimport com.streamvault.data.sync.SyncManagerimport com.streamvault.data.util.SeriesPresentationSettingsimport com.streamvault.data.util.buildPresentedSeriesimport com.streamvault.domain.model.*+import com.streamvault.domain.model.LegacyProvider as Providerimport com.streamvault.domain.model.Result.Successimport com.streamvault.domain.repository.PlaybackHistoryRepositoryimport com.streamvault.domain.repository.SeriesRepository@@ -56,6 +47,12 @@ import com.streamvault.data.util.rankSearchResultsimport java.util.concurrent.ConcurrentHashMapimport javax.inject.Injectimport com.streamvault.data.preferences.PreferencesRepository+import com.streamvault.data.provider.ProviderCapabilityResolver+import com.streamvault.data.provider.TypedProviderClientFactory+import com.streamvault.data.provider.toLegacyProvider+import com.streamvault.data.provider.ProviderCapabilityTimeoutException+import com.streamvault.domain.provider.CapabilityResolution+import com.streamvault.domain.provider.ProviderContentReferenceimport kotlinx.coroutines.sync.Muteximport kotlinx.coroutines.sync.withLockimport javax.inject.Singleton@@ -70,19 +67,15 @@ class SeriesRepositoryImpl @Inject constructor(private val playbackHistoryDao: PlaybackHistoryDao,private val playbackHistoryRepository: PlaybackHistoryRepository,private val providerDao: ProviderDao,- private val stalkerApiService: StalkerApiService,- private val xtreamApiService: XtreamApiService,- private val credentialCrypto: CredentialCrypto,private val preferencesRepository: PreferencesRepository,private val xtreamStreamUrlResolver: XtreamStreamUrlResolver,private val xtreamContentIndexDao: XtreamContentIndexDao,private val xtreamIndexJobDao: XtreamIndexJobDao,private val syncManager: SyncManager,private val seriesCategoryHydrationDao: SeriesCategoryHydrationDao,- private val jellyfinProvider: JellyfinProvider,- private val stalkerRemoteIdentityResolver: StalkerRemoteIdentityResolver,private val stalkerRequestCoordinator: StalkerRequestCoordinator,- private val stalkerPortalStateStore: StalkerPortalStateStore+ private val providerCapabilityResolver: ProviderCapabilityResolver,+ private val typedProviderClientFactory: TypedProviderClientFactory) : SeriesRepository {private companion object {const val TAG = "SeriesRepository"@@ -104,11 +97,6 @@ class SeriesRepositoryImpl @Inject constructor(val DETAIL_YEAR_REGEX = Regex("""(19|20)\d{2}""")}- private data class CachedXtreamProvider(- val signature: String,- val provider: XtreamProvider- )-private data class NameCursor(val name: String,val id: Long@@ -126,7 +114,6 @@ class SeriesRepositoryImpl @Inject constructor(val id: Long)- private val xtreamProviderCache = ConcurrentHashMap<Long, CachedXtreamProvider>()private val xtreamCategoryLoadLocks = ConcurrentHashMap<String, Mutex>()private val loadedXtreamCategories = ConcurrentHashMap.newKeySet<String>()private val backgroundRefreshes = ConcurrentHashMap.newKeySet<String>()@@ -238,9 +225,9 @@ class SeriesRepositoryImpl @Inject constructor(if (filteredCategories.isEmpty()) {flowOf(emptyMap())} else channelFlow {- val provider = providerDao.getById(providerId)+ val provider = loadCompatibilityProvider(providerId)val previewCategories = if (provider?.type == ProviderType.STALKER_PORTAL) {- val stalkerProvider = createStalkerProvider(providerId, provider)+ val stalkerProvider = createStalkerProvider(providerId)filteredCategories.filterNot { category ->stalkerProvider.isWildcardCategory(ContentType.SERIES, category.categoryId)}@@ -353,7 +340,7 @@ class SeriesRepositoryImpl @Inject constructor(query.categoryId?.takeIf { normalizedSearch.length < MIN_SEARCH_QUERY_LENGTH }?.let {- val provider = providerDao.getById(query.providerId)+ val provider = loadCompatibilityProvider(query.providerId)if (provider?.type == ProviderType.XTREAM_CODES) {ensureXtreamCategoryLoaded(providerId = query.providerId,@@ -388,7 +375,7 @@ class SeriesRepositoryImpl @Inject constructor(categoryId: Long,request: VodCategoryHydrationRequest): Result<Unit> {- val provider = providerDao.getById(providerId) ?: return Result.error("Provider not found")+ val provider = loadCompatibilityProvider(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 (@@ -478,7 +465,7 @@ class SeriesRepositoryImpl @Inject constructor(?: seriesDao.getBySeriesId(providerId, seriesId)?: return Result.error("Series not found")- val provider = providerDao.getById(providerId)+ val provider = loadCompatibilityProvider(providerId)?: return Result.error("Provider not found")if (seriesEntity.seriesId <= 0L) {@@ -502,57 +489,33 @@ class SeriesRepositoryImpl @Inject constructor(}val remoteResult = try {- when (provider.type) {- ProviderType.XTREAM_CODES -> withTimeoutOrNull(XTREAM_DETAIL_HYDRATION_TIMEOUT_MILLIS) {- getOrCreateXtreamProvider(providerId, provider).getSeriesInfo(seriesEntity.seriesId)- } ?: run {- xtreamContentIndexDao.markDetailHydrationError(- providerId = providerId,- contentType = ContentType.SERIES.name,- remoteId = seriesEntity.providerSeriesId?.takeIf { it.isNotBlank() } ?: seriesEntity.seriesId.toString(),- errorState = "DETAIL_FAILED_TIMEOUT"- )- return Result.success(attachSeriesPresentation(buildSeriesWithPersistedEpisodes(seriesEntity), knownPresentation))- }- ProviderType.STALKER_PORTAL -> createStalkerProvider(providerId, provider).getSeriesInfo(- providerSeriesId = seriesEntity.providerSeriesId?.takeIf { it.isNotBlank() }- ?: seriesEntity.seriesId.toString(),- catalogOrigin = seriesEntity.catalogOrigin,- episodePlaybackTemplateUrl = seriesEntity.episodePlaybackTemplateUrl,- learnedDialect = StalkerContentCapabilitiesCodec.decode(- provider.stalkerCapabilitiesJson,- provider.contentCapabilityGeneration()- ).seriesDetailDialect+ val capabilitySet = when (val resolution = providerCapabilityResolver.resolve(providerId)) {+ is CapabilityResolution.Available -> resolution.capability+ is CapabilityResolution.ConfigurationError,+ is CapabilityResolution.Restricted,+ is CapabilityResolution.Unsupported -> return Result.success(+ attachSeriesPresentation(buildSeriesWithPersistedEpisodes(seriesEntity), knownPresentation)+ )+ }+ val seriesSource = when (val resolution = capabilitySet.seriesCatalog()) {+ is CapabilityResolution.Available -> resolution.capability+ is CapabilityResolution.ConfigurationError,+ is CapabilityResolution.Restricted,+ is CapabilityResolution.Unsupported -> return Result.success(+ attachSeriesPresentation(buildSeriesWithPersistedEpisodes(seriesEntity), knownPresentation))- ProviderType.M3U -> return Result.success(attachSeriesPresentation(buildSeriesWithPersistedEpisodes(seriesEntity), knownPresentation))- ProviderType.JELLYFIN -> {- val remoteId = seriesEntity.providerSeriesId?.takeIf { it.isNotBlank() }- ?: return Result.success(attachSeriesPresentation(buildSeriesWithPersistedEpisodes(seriesEntity), knownPresentation))- val decryptedPassword = credentialCrypto.decryptIfNeeded(provider.password)- when (val episodesResult = jellyfinProvider.fetchEpisodes(- provider = com.streamvault.domain.model.Provider(- id = providerId, name = "Jellyfin", type = ProviderType.JELLYFIN,- serverUrl = provider.serverUrl, username = provider.username,- password = decryptedPassword- ),- seriesRemoteId = remoteId,- seriesLocalId = seriesEntity.id- )) {- is com.streamvault.domain.model.Result.Success -> {- if (episodesResult.data.isNotEmpty()) {- episodeDao.replaceAll(seriesEntity.id, providerId, episodesResult.data)- }- return Result.success(attachSeriesPresentation(buildSeriesWithPersistedEpisodes(seriesEntity), knownPresentation))- }- is com.streamvault.domain.model.Result.Error -> {- Log.w(TAG, "Failed to fetch Jellyfin episodes: ${episodesResult.message}")- return Result.success(attachSeriesPresentation(buildSeriesWithPersistedEpisodes(seriesEntity), knownPresentation))- }- is com.streamvault.domain.model.Result.Loading -> {}- }- return Result.success(attachSeriesPresentation(buildSeriesWithPersistedEpisodes(seriesEntity), knownPresentation))- }}+ seriesSource.hydrateSeries(+ reference = ProviderContentReference(+ providerId = providerId,+ localId = seriesEntity.id,+ streamId = seriesEntity.seriesId,+ remoteId = seriesEntity.providerSeriesId,+ seriesCatalogOrigin = seriesEntity.catalogOrigin,+ episodePlaybackTemplateUrl = seriesEntity.episodePlaybackTemplateUrl+ ),+ current = buildSeriesWithPersistedEpisodes(seriesEntity)+ )} catch (e: Exception) {if (provider.type == ProviderType.XTREAM_CODES) {xtreamContentIndexDao.markDetailHydrationError(@@ -608,48 +571,6 @@ class SeriesRepositoryImpl @Inject constructor(})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,@@ -761,7 +682,11 @@ class SeriesRepositoryImpl @Inject constructor(providerId = providerId,contentType = ContentType.SERIES.name,remoteId = seriesEntity.providerSeriesId?.takeIf { it.isNotBlank() } ?: seriesEntity.seriesId.toString(),- errorState = "DETAIL_FAILED_RETRYABLE"+ errorState = if (remoteResult.exception is ProviderCapabilityTimeoutException) {+ "DETAIL_FAILED_TIMEOUT"+ } else {+ "DETAIL_FAILED_RETRYABLE"+ })}val localSeries = attachSeriesPresentation(buildSeriesWithPersistedEpisodes(seriesEntity), knownPresentation)@@ -1314,7 +1239,7 @@ class SeriesRepositoryImpl @Inject constructor(}val hasMoreRemote = query.categoryId?.let { categoryId ->- val provider = providerDao.getById(query.providerId)+ val provider = loadCompatibilityProvider(query.providerId)if (provider?.type == ProviderType.STALKER_PORTAL) {seriesCategoryHydrationDao.get(query.providerId, categoryId)?.let { !it.isComplete } ?: false} else {@@ -1616,7 +1541,7 @@ class SeriesRepositoryImpl @Inject constructor(loadStalkerCategoryCompletely: Boolean = false) {val key = "$providerId:$categoryId"- val provider = providerDao.getById(providerId) ?: return+ val provider = loadCompatibilityProvider(providerId) ?: returnif (provider.type != ProviderType.XTREAM_CODES && provider.type != ProviderType.STALKER_PORTAL) returnval localCount = seriesDao.getCountByCategory(providerId, categoryId).first()@@ -1656,7 +1581,7 @@ class SeriesRepositoryImpl @Inject constructor(private fun triggerSeriesCategoryHydration(providerId: Long,categoryId: Long,- provider: ProviderEntity,+ provider: Provider,requiredCount: Int = SEARCH_RESULT_LIMIT,allowStalkerWildcard: Boolean = true) {@@ -1712,7 +1637,7 @@ class SeriesRepositoryImpl @Inject constructor(private suspend fun hydrateStalkerSeriesCategoryToCount(providerId: Long,categoryId: Long,- provider: ProviderEntity,+ provider: Provider,requiredCount: Int,localCount: Int? = null,hydration: SeriesCategoryHydrationEntity? = null,@@ -1725,7 +1650,7 @@ class SeriesRepositoryImpl @Inject constructor(lock.withLock {val persistedHydration = seriesCategoryHydrationDao.get(providerId, categoryId)if (requestedPage != null && (persistedHydration?.lastSuccessfulPage ?: 0) >= requestedPage) return- val stalkerProvider = createStalkerProvider(providerId, provider)+ val stalkerProvider = createStalkerProvider(providerId)if (!allowWildcard && stalkerProvider.isWildcardCategory(ContentType.SERIES, categoryId)) returnvar currentCount = localCount ?: seriesDao.getCountByCategory(providerId, categoryId).first()var currentHydration = persistedHydration ?: hydration@@ -1906,76 +1831,15 @@ class SeriesRepositoryImpl @Inject constructor(private fun seriesUpdatedScore(series: Series): Long =series.lastModified.takeIf { it > 0L } ?: 0L- private suspend fun getOrCreateXtreamProvider(providerId: Long, provider: ProviderEntity): XtreamProvider {- val enableBase64TextCompatibility = preferencesRepository.xtreamBase64TextCompatibility.first()- val signature = listOf(- provider.serverUrl,- provider.username,- provider.password,- provider.httpUserAgent,- provider.httpHeaders,- provider.allowedOutputFormatsJson,- enableBase64TextCompatibility.toString()- ).joinToString("\u0000")- return requireNotNull(- xtreamProviderCache.compute(providerId) { _, cached ->- if (cached != null && cached.signature == signature) {- cached- } else {- val decryptedPassword = credentialCrypto.decryptIfNeeded(provider.password)- CachedXtreamProvider(- signature = signature,- provider = XtreamProvider(- providerId = providerId,- api = xtreamApiService,- serverUrl = provider.serverUrl,- username = provider.username,- password = decryptedPassword,- allowedOutputFormats = provider.toDomain().allowedOutputFormats,- enableBase64TextCompatibility = enableBase64TextCompatibility,- requestProfile = provider.toGenericRequestProfile(ownerTag = "provider:$providerId/xtream")- )- )- }- }- ) { "Provider cache compute returned null for providerId=$providerId" }.provider- }-- private fun createStalkerProvider(providerId: Long, provider: ProviderEntity): StalkerProvider {- return StalkerProvider(- providerId = providerId,- api = stalkerApiService,- portalUrl = provider.serverUrl,- macAddress = provider.stalkerMacAddress,- authMode = provider.stalkerAuthMode,- username = provider.username,- password = credentialCrypto.decryptIfNeeded(provider.password),- httpUserAgent = provider.httpUserAgent,- httpHeaders = provider.httpHeaders,- portalFingerprintHint = provider.stalkerPortalFingerprint,- magPresetHint = provider.stalkerMagPreset,- bootstrapRecipeHint = provider.stalkerLastBootstrapRecipe,- endpointPreferenceHint = provider.stalkerEndpointPreference,- cookieModeHint = provider.stalkerCookieMode,- playbackBackendHint = provider.stalkerPlaybackBackendHint,- portalProfileHint = provider.stalkerPortalProfile,- preferredPlaybackMode = provider.stalkerLastPlaybackMode- ?.let { value -> runCatching { StalkerPlaybackMode.valueOf(value) }.getOrNull() },- deviceProfile = provider.stalkerDeviceProfile,- timezone = provider.stalkerDeviceTimezone,- locale = provider.stalkerDeviceLocale,- serialNumber = provider.stalkerSerialNumber,- deviceId = provider.stalkerDeviceId,- deviceId2 = provider.stalkerDeviceId2,- signature = provider.stalkerSignature,- stalkerAdvancedOptionsJson = provider.stalkerAdvancedOptionsJson,- protocolPreference = provider.stalkerProtocolPreference,- transportGrant = provider.stalkerTransportGrantOrNull(),- requestedProfileId = provider.stalkerRequestedProfileId,- learnedProfileId = provider.stalkerLearnedProfileId,- identityResolver = stalkerRemoteIdentityResolver,- portalStateStore = stalkerPortalStateStore- )+ private suspend fun createStalkerProvider(providerId: Long): StalkerProvider {+ val snapshot = providerCapabilityResolver.snapshot(providerId)+ ?: throw IllegalStateException("Provider $providerId has no typed configuration")+ return when (val resolution = typedProviderClientFactory.stalker(snapshot)) {+ is CapabilityResolution.Available -> resolution.capability+ is CapabilityResolution.ConfigurationError -> throw IllegalStateException(resolution.reason)+ is CapabilityResolution.Restricted -> throw IllegalStateException(resolution.reason)+ is CapabilityResolution.Unsupported -> throw IllegalStateException(resolution.reason)+ }}private fun SeriesEntity.hasFreshStalkerDetails(now: Long = System.currentTimeMillis()): Boolean {@@ -1985,7 +1849,7 @@ class SeriesRepositoryImpl @Inject constructor(return !ContentCachePolicy.shouldRefresh(detailHydratedAt, DETAIL_REFRESH_TTL_MILLIS, now)}- private fun ProviderEntity.contentCapabilityGeneration(): Int = listOf(+ private fun Provider.contentCapabilityGeneration(): Int = listOf(serverUrl,stalkerMacAddress,stalkerAuthMode.name,@@ -1995,4 +1859,7 @@ class SeriesRepositoryImpl @Inject constructor(catalogLayout.name,catalogLayoutDetectionVersion.toString()).joinToString("\u0000").hashCode()++ private suspend fun loadCompatibilityProvider(providerId: Long): Provider? =+ providerCapabilityResolver.snapshot(providerId)?.toLegacyProvider()}diff --git a/data/src/main/java/com/streamvault/data/sync/ProviderSyncAdapterRegistry.kt b/data/src/main/java/com/streamvault/data/sync/ProviderSyncAdapterRegistry.ktnew file mode 100644index 00000000..8663d2e3--- /dev/null+++ b/data/src/main/java/com/streamvault/data/sync/ProviderSyncAdapterRegistry.kt@@ -0,0 +1,75 @@+package com.streamvault.data.sync++import com.streamvault.data.provider.toLegacyProvider+import com.streamvault.domain.model.ProviderSnapshot+import com.streamvault.domain.model.ProviderType+import com.streamvault.domain.provider.CapabilityResolution++internal data class FullProviderSyncRequest(+ val snapshot: ProviderSnapshot,+ val force: Boolean,+ val onProgress: ((String) -> Unit)?,+ val trackInitialLiveOnboarding: Boolean,+ val deferProviderStateUntilCatalogCommit: Boolean,+ val afterCatalogApply: suspend () -> Unit+)++internal data class SectionProviderSyncRequest(+ val snapshot: ProviderSnapshot,+ val section: SyncRepairSection,+ val syncReason: XtreamLiveSyncReason,+ val onProgress: ((String) -> Unit)?+)++internal data class ProviderGuideSyncRequest(+ val snapshot: ProviderSnapshot,+ val force: Boolean,+ val now: Long,+ val onProgress: ((String) -> Unit)?+)++internal data class ProviderGuideSyncResult(+ val warnings: List<String>,+ val hasRetryableFailure: Boolean+)++internal fun ProviderSnapshot.toSyncCompatibilityProvider() =+ toLegacyProvider()++internal interface ProviderSyncAdapter {+ val providerType: ProviderType+ suspend fun syncFull(request: FullProviderSyncRequest): SyncOutcome+ suspend fun syncSection(request: SectionProviderSyncRequest): CapabilityResolution<SyncOutcome>+ suspend fun syncGuide(request: ProviderGuideSyncRequest): CapabilityResolution<ProviderGuideSyncResult>+}++internal class ProviderSyncAdapterRegistry(adapters: Collection<ProviderSyncAdapter>) {+ private val adaptersByType: Map<ProviderType, ProviderSyncAdapter>++ init {+ val duplicates = adapters.groupingBy { it.providerType }.eachCount().filterValues { it != 1 }.keys+ require(duplicates.isEmpty()) { "Duplicate provider sync adapters: $duplicates" }+ val missing = ProviderType.entries.toSet() - adapters.mapTo(mutableSetOf()) { it.providerType }+ require(missing.isEmpty()) { "Missing provider sync adapters: $missing" }+ adaptersByType = adapters.associateBy { it.providerType }+ }++ fun resolve(snapshot: ProviderSnapshot): CapabilityResolution<ProviderSyncAdapter> {+ if (snapshot.provider.type != snapshot.configuration.type) {+ return CapabilityResolution.ConfigurationError("Provider/configuration type mismatch")+ }+ return CapabilityResolution.Available(adaptersByType.getValue(snapshot.provider.type))+ }+}++internal class LambdaProviderSyncAdapter(+ override val providerType: ProviderType,+ private val full: suspend (FullProviderSyncRequest) -> SyncOutcome,+ private val section: suspend (SectionProviderSyncRequest) -> CapabilityResolution<SyncOutcome>,+ private val guide: suspend (ProviderGuideSyncRequest) -> CapabilityResolution<ProviderGuideSyncResult>+) : ProviderSyncAdapter {+ override suspend fun syncFull(request: FullProviderSyncRequest): SyncOutcome = full(request)+ override suspend fun syncSection(request: SectionProviderSyncRequest): CapabilityResolution<SyncOutcome> = section(request)+ override suspend fun syncGuide(request: ProviderGuideSyncRequest): CapabilityResolution<ProviderGuideSyncResult> =+ guide(request)+}diff --git a/data/src/main/java/com/streamvault/data/sync/ProviderSyncStateReaderImpl.kt b/data/src/main/java/com/streamvault/data/sync/ProviderSyncStateReaderImpl.ktindex a4e7bb84..3244d736 100644--- a/data/src/main/java/com/streamvault/data/sync/ProviderSyncStateReaderImpl.kt+++ b/data/src/main/java/com/streamvault/data/sync/ProviderSyncStateReaderImpl.kt@@ -40,6 +40,10 @@ class ProviderSyncStateReaderImpl @Inject constructor()}} == true- legacyIndexActive || workflowIndexActive+ // The durable workflow is authoritative once present. The legacy+ // Xtream rows remain a compatibility fallback for providers that+ // have not yet been migrated into the workflow table, but must not+ // resurrect a stale spinner after a workflow has completed.+ if (workflow != null) workflowIndexActive else legacyIndexActive}}diff --git a/data/src/main/java/com/streamvault/data/sync/ProviderSyncWorker.kt b/data/src/main/java/com/streamvault/data/sync/ProviderSyncWorker.ktindex 04bd4501..883c66bb 100644--- a/data/src/main/java/com/streamvault/data/sync/ProviderSyncWorker.kt+++ b/data/src/main/java/com/streamvault/data/sync/ProviderSyncWorker.kt@@ -25,11 +25,21 @@ import com.streamvault.data.local.dao.XtreamLiveOnboardingDaoimport com.streamvault.data.local.DatabaseTransactionRunnerimport com.streamvault.data.local.entity.ProviderConfigRevisionStateimport com.streamvault.data.local.entity.ProviderEntity+import com.streamvault.data.local.entity.ProviderConfigRevisionEntityimport com.streamvault.data.local.entity.ProviderWorkflowPhaseimport com.streamvault.data.local.entity.ProviderWorkflowReasonimport com.streamvault.data.local.entity.XtreamIndexJobEntityimport com.streamvault.data.mapper.toDomainimport com.streamvault.data.security.CredentialCrypto+import com.streamvault.data.provider.ProviderConfigurationCodec+import com.streamvault.data.provider.ProviderConfigRevisionCodec+import com.streamvault.data.provider.toAccountRuntime+import com.streamvault.data.provider.toTypedConfiguration+import com.streamvault.data.provider.guidePolicy+import com.streamvault.data.provider.logoPolicy+import com.streamvault.data.local.dao.ProviderSnapshotDao+import com.streamvault.data.local.entity.ProviderConfigEntity+import com.streamvault.data.local.entity.ProviderAccountRuntimeEntityimport com.streamvault.domain.model.ProviderStatusimport com.streamvault.domain.model.ContentTypeimport com.streamvault.domain.model.ProviderEpgSyncMode@@ -119,6 +129,14 @@ internal suspend fun shouldTrackInitialLiveOnboarding(): Boolean = provider.type == ProviderType.XTREAM_CODES &&onboardingDao.getIncompleteByProvider(provider.id) != null+internal fun isObsoleteProviderConfigRevision(+ revision: ProviderConfigRevisionEntity?,+ providerExists: Boolean+): Boolean = revision == null ||+ !providerExists ||+ revision.state == ProviderConfigRevisionState.COMMITTED ||+ revision.state == ProviderConfigRevisionState.SUPERSEDED+class ProviderSyncWorker(appContext: Context,workerParams: WorkerParameters@@ -134,6 +152,8 @@ class ProviderSyncWorker(fun syncMetadataRepository(): SyncMetadataRepositoryfun providerConfigRevisionDao(): ProviderConfigRevisionDaofun credentialCrypto(): CredentialCrypto+ fun providerConfigurationCodec(): ProviderConfigurationCodec+ fun providerSnapshotDao(): ProviderSnapshotDaofun gson(): Gsonfun xtreamIndexJobDao(): XtreamIndexJobDaofun xtreamLiveOnboardingDao(): XtreamLiveOnboardingDao@@ -284,6 +304,14 @@ class ProviderSyncWorker(if (providerId == INVALID_PROVIDER_ID) {return ProviderWorkflowDisposition.FAILED}+ // WorkManager may deliver an old revision after the provider was deleted or after a+ // newer edit superseded it. Do this check before creating a workflow row: the workflow+ // tables are foreign-keyed to providers, so a deleted provider must be a successful+ // no-op rather than a retrying database error.+ val revision = entryPoint.providerConfigRevisionDao().get(providerId, revisionNumber)+ if (isObsoleteProviderConfigRevision(revision, entryPoint.providerDao().getById(providerId) != null)) {+ return ProviderWorkflowDisposition.SUCCEEDED+ }return entryPoint.providerWorkflowRunner().execute(providerId = providerId,phase = ProviderWorkflowPhase.PREPARE,@@ -345,33 +373,66 @@ class ProviderSyncWorker(return RevisionRecoveryOutcome.SUCCESS}- val secureCandidate = try {- entryPoint.gson().fromJson(revision.configJson, ProviderEntity::class.java)- ?: throw IllegalStateException("Saved provider edit was empty.")+ val decodedRevision = try {+ ProviderConfigRevisionCodec(+ entryPoint.gson(),+ entryPoint.providerConfigurationCodec(),+ entryPoint.credentialCrypto()+ ).decode(revision.configJson)} catch (error: Exception) {revisionDao.markFailed(providerId, revisionNumber, "Saved provider edit is invalid.", now)return RevisionRecoveryOutcome.FAILURE}+ val secureCandidate = decodedRevision.secureEntityif (secureCandidate.id != providerId) {revisionDao.markFailed(providerId, revisionNumber, "Saved provider edit did not match its provider.", now)return RevisionRecoveryOutcome.FAILURE}- val candidate = try {- secureCandidate- .copy(password = entryPoint.credentialCrypto().decryptIfNeeded(secureCandidate.password))- .toDomain()- } catch (error: Exception) {- revisionDao.markFailed(providerId, revisionNumber, "Saved provider credentials could not be restored.", now)- return RevisionRecoveryOutcome.FAILURE+ val candidate = decodedRevision.candidate+ val currentConfigGeneration = entryPoint.providerSnapshotDao()+ .getConfig(providerId)?.configurationGeneration ?: 0L+ val commitGeneration = if (decodedRevision.wasLegacy) {+ currentConfigGeneration + 1L+ } else {+ decodedRevision.configurationGeneration}val result = entryPoint.syncManager().syncWithProviderOverride(providerId = providerId,- force = false,+ // Recovery must revalidate the staged configuration instead of accepting a fresh+ // cache belonging to the previously committed configuration.+ force = true,providerOverride = candidate,afterCatalogApply = {val committedAt = System.currentTimeMillis()+ val configuration = candidate.toTypedConfiguration()+ check(entryPoint.providerSnapshotDao().commitConfiguration(+ ProviderConfigEntity(+ providerId = providerId,+ type = configuration.type,+ schemaVersion = configuration.schemaVersion,+ configurationGeneration = commitGeneration,+ identityKey = entryPoint.providerConfigurationCodec().identityKey(configuration),+ encryptedConfigJson = entryPoint.providerConfigurationCodec().encode(configuration),+ guideSourcePolicy = configuration.guidePolicy(),+ channelLogoSourcePolicy = configuration.logoPolicy(),+ updatedAt = committedAt+ )+ )) { "Provider edit configuration was superseded before commit." }+ val runtime = candidate.toAccountRuntime()+ entryPoint.providerSnapshotDao().upsertRuntime(+ ProviderAccountRuntimeEntity(+ providerId = providerId,+ maxConnections = runtime.maxConnections,+ expirationDate = runtime.expirationDate,+ apiVersion = runtime.apiVersion,+ allowedOutputFormatsJson = entryPoint.gson().toJson(runtime.allowedOutputFormats),+ catalogLayout = runtime.catalogLayout,+ catalogLayoutDetectionVersion = runtime.catalogLayoutDetectionVersion,+ observedAt = runtime.observedAt+ )+ )check(revisionDao.markCommitted(providerId, revisionNumber, committedAt) == 1) {"Provider edit was superseded before recovery could commit it."}@@ -579,7 +640,7 @@ class ProviderSyncWorker(ContentCachePolicy.CATALOG_TTL_MILLIS,now)- val epgStale = provider.epgSyncMode != ProviderEpgSyncMode.SKIP &&+ val epgStale = providerEpgSyncMode(entryPoint, provider.id) != ProviderEpgSyncMode.SKIP &&ContentCachePolicy.shouldRefresh(metadata?.lastEpgSuccess ?: 0L,ContentCachePolicy.EPG_TTL_MILLIS,@@ -642,7 +703,7 @@ class ProviderSyncWorker(ContentCachePolicy.CATALOG_TTL_MILLIS,now)- val epgStale = provider.epgSyncMode != ProviderEpgSyncMode.SKIP &&+ val epgStale = providerEpgSyncMode(entryPoint, provider.id) != ProviderEpgSyncMode.SKIP &&ContentCachePolicy.shouldRefresh(metadata?.lastEpgSuccess ?: 0L,ContentCachePolicy.EPG_TTL_MILLIS,@@ -673,6 +734,23 @@ class ProviderSyncWorker(return com.streamvault.domain.model.Result.success(Unit)}+ private suspend fun providerEpgSyncMode(+ entryPoint: ProviderSyncWorkerEntryPoint,+ providerId: Long+ ): ProviderEpgSyncMode {+ val stored = entryPoint.providerSnapshotDao().getConfig(providerId)+ ?: return ProviderEpgSyncMode.SKIP+ return when (val configuration = entryPoint.providerConfigurationCodec().decode(+ stored.type,+ stored.encryptedConfigJson+ )) {+ is com.streamvault.domain.model.XtreamConfig -> configuration.epgSyncMode+ is com.streamvault.domain.model.M3uConfig -> configuration.epgSyncMode+ is com.streamvault.domain.model.StalkerConfig -> configuration.epgSyncMode+ is com.streamvault.domain.model.JellyfinConfig -> ProviderEpgSyncMode.SKIP+ }+ }+private suspend fun reconcileTargetedProviderStatus(entryPoint: ProviderSyncWorkerEntryPoint,provider: com.streamvault.data.local.entity.ProviderEntity,diff --git a/data/src/main/java/com/streamvault/data/sync/ProviderWorkflowRunner.kt b/data/src/main/java/com/streamvault/data/sync/ProviderWorkflowRunner.ktindex 9f4816e6..dbd04d61 100644--- a/data/src/main/java/com/streamvault/data/sync/ProviderWorkflowRunner.kt+++ b/data/src/main/java/com/streamvault/data/sync/ProviderWorkflowRunner.kt@@ -14,7 +14,6 @@ import java.util.UUIDimport javax.inject.Injectimport javax.inject.Singletonimport kotlinx.coroutines.CancellationException-import kotlinx.coroutines.NonCancellableimport kotlinx.coroutines.cancelAndJoinimport kotlinx.coroutines.coroutineScopeimport kotlinx.coroutines.delay@@ -101,15 +100,9 @@ class ProviderWorkflowRunner @Inject constructor(} catch (lost: ProviderWorkflowLeaseLostException) {ProviderWorkflowDisposition.SUPERSEDED} catch (cancelled: CancellationException) {- withContext(NonCancellable) {- workflowDao.fail(- lease = lease,- now = System.currentTimeMillis(),- errorCode = "CANCELLED",- errorMessage = "Worker cancelled before the phase completed.",- retryable = true- )- }+ // Cancellation is owner control flow, not a provider failure. Leave the durable+ // lease running so the normal stale-lease recovery path can reclaim it without+ // publishing a retry/error/status update after the worker has stopped.throw cancelled} catch (error: Exception) {publishOutcome(diff --git a/data/src/main/java/com/streamvault/data/sync/SyncManager.kt b/data/src/main/java/com/streamvault/data/sync/SyncManager.ktindex 2319a237..6e984aa1 100644--- a/data/src/main/java/com/streamvault/data/sync/SyncManager.kt+++ b/data/src/main/java/com/streamvault/data/sync/SyncManager.kt@@ -68,6 +68,9 @@ import com.streamvault.data.remote.xtream.XtreamApiServiceimport com.streamvault.data.remote.xtream.XtreamProviderimport com.streamvault.data.remote.xtream.XtreamUrlFactoryimport com.streamvault.data.security.CredentialCrypto+import com.streamvault.data.provider.toProviderSnapshot+import com.streamvault.data.provider.TypedProviderClientFactory+import com.streamvault.data.provider.XtreamClientOptionsimport com.streamvault.data.util.AdultContentClassifierimport com.streamvault.data.util.runSuspendCatchingimport com.streamvault.data.util.UrlSecurityPolicy@@ -77,7 +80,7 @@ import com.streamvault.domain.model.GuideSourcePolicyimport com.streamvault.domain.model.ContentTypeimport com.streamvault.domain.model.Movieimport com.streamvault.domain.model.ProviderEpgSyncMode-import com.streamvault.domain.model.Provider+import com.streamvault.domain.model.LegacyProvider as Providerimport com.streamvault.domain.model.ProviderTypeimport com.streamvault.domain.model.Resultimport com.streamvault.domain.model.Series@@ -91,11 +94,15 @@ import com.streamvault.domain.model.StalkerTransportOriginimport com.streamvault.domain.model.SyncMetadataimport com.streamvault.domain.model.SyncStateimport com.streamvault.domain.model.VodSyncMode+import com.streamvault.domain.model.XtreamConfig+import com.streamvault.data.provider.toLegacyProviderimport com.streamvault.domain.repository.EpgRepositoryimport com.streamvault.domain.repository.EpgSourceRepositoryimport com.streamvault.domain.repository.SyncMetadataRepository+import com.streamvault.domain.repository.ProviderSnapshotRepositoryimport com.streamvault.domain.sync.Sectionimport com.streamvault.domain.sync.SyncProgress+import com.streamvault.domain.provider.CapabilityResolutionimport dagger.hilt.android.qualifiers.ApplicationContextimport kotlinx.coroutines.asyncimport kotlinx.coroutines.Dispatchers@@ -246,7 +253,6 @@ class SyncManager @Inject constructor(private val xtreamIndexJobDao: XtreamIndexJobDao,private val stalkerIndexJobDao: StalkerIndexJobDao,private val xtreamLiveOnboardingDao: XtreamLiveOnboardingDao,- private val stalkerApiService: StalkerApiService,private val episodeDao: EpisodeDao,private val jellyfinProvider: JellyfinProvider,private val xtreamJson: Json,@@ -259,11 +265,12 @@ class SyncManager @Inject constructor(private val transactionRunner: DatabaseTransactionRunner,private val preferencesRepository: com.streamvault.data.preferences.PreferencesRepository,private val syncProgressBus: SyncProgressBus,- private val stalkerRemoteIdentityResolver: StalkerRemoteIdentityResolver,private val stalkerRequestCoordinator: StalkerRequestCoordinator,private val stalkerPortalStateStore: StalkerPortalStateStore,private val stalkerReadinessTracker: StalkerReadinessTracker,private val providerWorkflowCommitFence: ProviderWorkflowCommitFence,+ private val typedProviderClientFactory: TypedProviderClientFactory,+ private val providerSnapshotRepository: ProviderSnapshotRepository? = null,private val providerWorkflowDao: ProviderWorkflowDao? = null) {private val syncStateTracker = SyncStateTracker()@@ -296,6 +303,164 @@ class SyncManager @Inject constructor(seriesRequestTimeoutMillis = XTREAM_SERIES_REQUEST_TIMEOUT_MILLIS,recoveryAbortWarningSuffix = XTREAM_RECOVERY_ABORT_WARNING_SUFFIX)+ private val providerSyncRegistry: ProviderSyncAdapterRegistry by lazy {+ ProviderSyncAdapterRegistry(+ listOf(+ LambdaProviderSyncAdapter(+ providerType = ProviderType.XTREAM_CODES,+ full = { request ->+ val provider = request.snapshot.toSyncCompatibilityProvider()+ syncXtreamIndexFirst(+ provider = provider,+ force = request.force,+ onProgress = request.onProgress,+ trackInitialLiveOnboarding = request.trackInitialLiveOnboarding,+ syncReason = if (request.trackInitialLiveOnboarding) {+ XtreamLiveSyncReason.INITIAL_ONBOARDING+ } else {+ XtreamLiveSyncReason.FOREGROUND+ },+ afterCatalogApply = request.afterCatalogApply+ )+ },+ section = { request ->+ val provider = request.snapshot.toSyncCompatibilityProvider()+ CapabilityResolution.Available(when (request.section) {+ SyncRepairSection.LIVE -> syncXtreamLiveOnly(provider, request.syncReason, request.onProgress)+ SyncRepairSection.EPG -> {+ syncXtreamEpgOnly(provider, request.onProgress)+ SyncOutcome()+ }+ SyncRepairSection.MOVIES -> syncXtreamMoviesOnly(provider, request.onProgress)+ SyncRepairSection.SERIES -> syncXtreamSeriesOnly(provider, request.onProgress)+ })+ },+ guide = { request ->+ val provider = request.snapshot.toSyncCompatibilityProvider()+ CapabilityResolution.Available(+ syncXtreamProviderEpg(+ provider,+ syncMetadataRepository.getMetadata(provider.id) ?: SyncMetadata(provider.id),+ request.now,+ request.force,+ request.onProgress+ )+ )+ }+ ),+ LambdaProviderSyncAdapter(+ providerType = ProviderType.M3U,+ full = { request ->+ syncM3u(request.snapshot.toSyncCompatibilityProvider(), request.force, request.onProgress, request.afterCatalogApply)+ },+ section = { request ->+ val provider = request.snapshot.toSyncCompatibilityProvider()+ when (request.section) {+ SyncRepairSection.LIVE -> CapabilityResolution.Available(+ syncM3uLiveOnly(provider, request.onProgress)+ )+ SyncRepairSection.MOVIES -> CapabilityResolution.Available(+ syncM3uMoviesOnly(provider, request.onProgress)+ )+ SyncRepairSection.EPG -> {+ syncM3uEpgOnly(provider, request.onProgress)+ CapabilityResolution.Available(SyncOutcome())+ }+ SyncRepairSection.SERIES -> CapabilityResolution.Unsupported(+ "Series retry is unavailable for M3U providers"+ )+ }},+ guide = { request ->+ val provider = request.snapshot.toSyncCompatibilityProvider()+ CapabilityResolution.Available(+ syncM3uProviderEpg(+ provider,+ syncMetadataRepository.getMetadata(provider.id) ?: SyncMetadata(provider.id),+ request.now,+ request.force,+ request.onProgress+ )+ )+ }+ ),+ LambdaProviderSyncAdapter(+ providerType = ProviderType.STALKER_PORTAL,+ full = { request ->+ val provider = request.snapshot.toSyncCompatibilityProvider()+ syncStalker(+ provider = provider,+ force = request.force,+ onProgress = request.onProgress,+ afterCatalogApply = request.afterCatalogApply,+ deferProviderStateUntilCatalogCommit = request.deferProviderStateUntilCatalogCommit+ )+ },+ section = { request ->+ val provider = request.snapshot.toSyncCompatibilityProvider()+ CapabilityResolution.Available(when (request.section) {+ SyncRepairSection.LIVE -> syncStalkerLiveOnly(provider, request.onProgress)+ SyncRepairSection.EPG -> {+ syncStalkerEpgOnly(provider, request.onProgress)+ SyncOutcome()+ }+ SyncRepairSection.MOVIES -> syncStalkerMoviesOnly(provider, request.onProgress)+ SyncRepairSection.SERIES -> syncStalkerSeriesOnly(provider, request.onProgress)+ }) },+ guide = { request ->+ val provider = request.snapshot.toSyncCompatibilityProvider()+ CapabilityResolution.Available(+ syncStalkerProviderEpg(+ provider,+ syncMetadataRepository.getMetadata(provider.id) ?: SyncMetadata(provider.id),+ request.now,+ request.force,+ request.onProgress+ )+ )+ }+ ),+ LambdaProviderSyncAdapter(+ providerType = ProviderType.JELLYFIN,+ full = { request ->+ syncJellyfin(request.snapshot.toSyncCompatibilityProvider(), request.force, request.onProgress, request.afterCatalogApply)+ },+ section = { request ->+ val provider = request.snapshot.toSyncCompatibilityProvider()+ when (request.section) {+ SyncRepairSection.MOVIES -> {+ syncJellyfinMoviesOnly(provider, request.onProgress)+ CapabilityResolution.Available(SyncOutcome())+ }+ SyncRepairSection.SERIES -> {+ syncJellyfinSeriesOnly(provider, request.onProgress)+ CapabilityResolution.Available(SyncOutcome())+ }+ SyncRepairSection.LIVE -> CapabilityResolution.Unsupported(+ "Live TV retry is unavailable for Jellyfin providers"+ )+ SyncRepairSection.EPG -> CapabilityResolution.Unsupported(+ "Native guide retry is unavailable for Jellyfin providers"+ )+ }},+ guide = { request ->+ val provider = request.snapshot.toSyncCompatibilityProvider()+ CapabilityResolution.Available(+ syncJellyfinProviderEpg(+ provider,+ syncMetadataRepository.getMetadata(provider.id) ?: SyncMetadata(provider.id),+ request.now,+ request.force,+ request.onProgress+ )+ )+ }+ )+ )+ )+ }++ private suspend fun loadCompatibilityProvider(providerId: Long): Provider? =+ providerSnapshotRepository?.getSnapshot(providerId)?.toLegacyProvider()val syncState: StateFlow<SyncState> = syncStateTracker.aggregateStateval syncStatesByProvider: StateFlow<Map<Long, SyncState>> = syncStateTracker.statesByProviderprivate val providerSyncMutexes = ConcurrentHashMap<Long, Mutex>()@@ -317,7 +482,7 @@ class SyncManager @Inject constructor(}val lock = providerVodCategoryMutexes.computeIfAbsent("$providerId:$categoryId") { Mutex() }return lock.withLock {- val providerEntity = providerDao.getById(providerId)+ val providerEntity = loadCompatibilityProvider(providerId)?: return@withLock Result.error("Provider not found")if (providerEntity.type != ProviderType.STALKER_PORTAL) {return@withLock Result.success(Unit)@@ -331,7 +496,7 @@ class SyncManager @Inject constructor(return@withLock Result.success(Unit)}- val api = createStalkerSyncProvider(providerEntity.toDomain())+ val api = createStalkerSyncProvider(providerEntity)var hydration = currentvar nextPage = ((current?.lastSuccessfulPage ?: 0) + 1).coerceAtLeast(1)while (true) {@@ -449,7 +614,7 @@ class SyncManager @Inject constructor(}val lock = providerVodCategoryMutexes.computeIfAbsent("split:$providerId:$movieCategoryId") { Mutex() }return lock.withLock {- val providerEntity = providerDao.getById(providerId)+ val providerEntity = loadCompatibilityProvider(providerId)?: return@withLock Result.error("Provider not found")if (providerEntity.type != ProviderType.STALKER_PORTAL || providerEntity.catalogLayout != CatalogLayout.SPLIT) {return@withLock Result.success(Unit)@@ -463,7 +628,7 @@ class SyncManager @Inject constructor() {return@withLock Result.success(Unit)}- val api = createStalkerSyncProvider(providerEntity.toDomain())+ val api = createStalkerSyncProvider(providerEntity)val movieCategory = categoryDao.getByProviderAndTypeSync(providerId, ContentType.MOVIE.name).firstOrNull { it.categoryId == movieCategoryId }?: return@withLock Result.error("Movie category not found")@@ -632,11 +797,11 @@ class SyncManager @Inject constructor(seriesCategoryId: Long,request: com.streamvault.domain.model.VodCategoryHydrationRequest): Result<Unit> {- val providerEntity = providerDao.getById(providerId) ?: return Result.error("Provider not found")+ val providerEntity = loadCompatibilityProvider(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())+ val api = createStalkerSyncProvider(providerEntity)api.getSeriesCategories()val movieCategoryId = api.projectSeriesCategoryToVod(seriesCategoryId)?: return Result.error("Unable to resolve VOD category for derived Series")@@ -939,9 +1104,8 @@ class SyncManager @Inject constructor(force: Boolean,onProgress: ((String) -> Unit)?): com.streamvault.domain.model.Result<Unit> {- val provider = providerEntity- .copy(password = credentialCrypto.decryptIfNeeded(providerEntity.password))- .toDomain()+ val provider = loadCompatibilityProvider(providerEntity.id)+ ?: return Result.error("Provider ${providerEntity.id} has no typed configuration")val providerId = provider.idval startedAt = System.currentTimeMillis()@@ -955,13 +1119,26 @@ class SyncManager @Inject constructor(publishSyncState(providerId, SyncState.Syncing("Downloading EPG..."))return try {- val epgResult = syncProviderEpg(- provider = provider,- metadata = syncMetadataRepository.getMetadata(provider.id) ?: SyncMetadata(provider.id),- now = startedAt,- force = force,- onProgress = onProgress- )+ val snapshot = providerSnapshotRepository?.getSnapshot(providerId) ?: provider.toProviderSnapshot()+ val syncAdapter = when (val resolution = providerSyncRegistry.resolve(snapshot)) {+ is CapabilityResolution.Available -> resolution.capability+ is CapabilityResolution.ConfigurationError -> return Result.error(resolution.reason)+ is CapabilityResolution.Restricted -> return Result.error(resolution.reason)+ is CapabilityResolution.Unsupported -> return Result.error(resolution.reason)+ }+ val epgResult = when (val result = syncAdapter.syncGuide(+ ProviderGuideSyncRequest(+ snapshot = snapshot,+ force = force,+ now = startedAt,+ onProgress = onProgress+ )+ )) {+ is CapabilityResolution.Available -> result.capability+ is CapabilityResolution.ConfigurationError -> return Result.error(result.reason)+ is CapabilityResolution.Restricted -> return Result.error(result.reason)+ is CapabilityResolution.Unsupported -> return Result.error(result.reason)+ }val finishedAt = System.currentTimeMillis()val epgCount = programDao.countByProvider(providerId)updateXtreamEpgJobState(@@ -1081,9 +1258,8 @@ class SyncManager @Inject constructor(require(providerOverride == null || providerOverride.id == providerId) {"Provider override must match the requested provider ID."}- val provider = (providerOverride ?: providerEntity- .copy(password = credentialCrypto.decryptIfNeeded(providerEntity.password))- .toDomain())+ val provider = (providerOverride ?: loadCompatibilityProvider(providerId)+ ?: return@lock Result.error("Provider $providerId has no typed configuration")).let { resolvedProvider ->resolvedProvider.copy(xtreamFastSyncEnabled = movieFastSyncOverride ?: resolvedProvider.xtreamFastSyncEnabled,@@ -1094,25 +1270,33 @@ class SyncManager @Inject constructor(progressSession = beginProgressSession(providerId)publishSyncState(providerId, SyncState.Syncing("Starting..."))+ val snapshot = if (providerOverride != null) {+ provider.toProviderSnapshot()+ } else {+ providerSnapshotRepository?.getSnapshot(providerId) ?: provider.toProviderSnapshot()+ }+ val syncAdapter = when (val resolution = providerSyncRegistry.resolve(snapshot)) {+ is CapabilityResolution.Available -> resolution.capability+ is CapabilityResolution.ConfigurationError ->+ return@lock Result.error(resolution.reason)+ is CapabilityResolution.Restricted ->+ return@lock Result.error(resolution.reason)+ is CapabilityResolution.Unsupported ->+ return@lock Result.error(resolution.reason)+ }+try {val outcome = withContext(Dispatchers.IO) {- when (provider.type) {- ProviderType.XTREAM_CODES -> syncXtreamIndexFirst(- provider = provider,+ syncAdapter.syncFull(+ FullProviderSyncRequest(+ snapshot = snapshot,force = force,onProgress = onProgress,trackInitialLiveOnboarding = trackInitialLiveOnboarding,- syncReason = if (trackInitialLiveOnboarding) {- XtreamLiveSyncReason.INITIAL_ONBOARDING- } else {- XtreamLiveSyncReason.FOREGROUND- },+ deferProviderStateUntilCatalogCommit = providerOverride != null,afterCatalogApply = catalogCommitGate::apply)- ProviderType.M3U -> syncM3u(provider, force, onProgress, catalogCommitGate::apply)- ProviderType.STALKER_PORTAL -> syncStalker(provider, force, onProgress, catalogCommitGate::apply)- ProviderType.JELLYFIN -> syncJellyfin(provider, force, onProgress, catalogCommitGate::apply)- }+ )}transactionRunner.inTransaction {providerWorkflowCommitFence.assertCanCommit(providerId)@@ -1168,9 +1352,8 @@ class SyncManager @Inject constructor(return@lock com.streamvault.domain.model.Result.error("Index rebuild is only available for Xtream providers")}- val provider = providerEntity- .copy(password = credentialCrypto.decryptIfNeeded(providerEntity.password))- .toDomain()+ val provider = loadCompatibilityProvider(providerId)+ ?: return@lock Result.error("Provider $providerId has no typed configuration")publishSyncState(providerId, SyncState.Syncing("Preparing index rebuild..."))val now = System.currentTimeMillis()@@ -1275,27 +1458,46 @@ class SyncManager @Inject constructor(val providerEntity = providerDao.getById(providerId)?: return@lock com.streamvault.domain.model.Result.error("Provider $providerId not found")- val provider = providerEntity- .copy(password = credentialCrypto.decryptIfNeeded(providerEntity.password))- .toDomain()- .let { resolvedProvider ->- movieFastSyncOverride?.let { override ->- resolvedProvider.copy(xtreamFastSyncEnabled = override)- } ?: resolvedProvider- }+ val resolvedProvider = loadCompatibilityProvider(providerId)+ ?: return@lock Result.error("Provider $providerId has no typed configuration")+ val provider = movieFastSyncOverride?.let { override ->+ resolvedProvider.copy(xtreamFastSyncEnabled = override)+ } ?: resolvedProviderval progressSession = beginProgressSession(providerId)try {- val outcome = withContext(Dispatchers.IO) {- when (section) {- SyncRepairSection.LIVE -> syncLiveOnly(provider, syncReason, onProgress)- SyncRepairSection.EPG -> {- syncEpgOnly(provider, onProgress)- SyncOutcome()- }- SyncRepairSection.MOVIES -> syncMoviesOnly(provider, onProgress)- SyncRepairSection.SERIES -> syncSeriesOnly(provider, onProgress)- }+ val persistedSnapshot = providerSnapshotRepository?.getSnapshot(providerId) ?: provider.toProviderSnapshot()+ val persistedConfiguration = persistedSnapshot.configuration+ val snapshot = if (movieFastSyncOverride != null && persistedConfiguration is XtreamConfig) {+ persistedSnapshot.copy(+ configuration = persistedConfiguration.copy(+ fastSyncEnabled = movieFastSyncOverride+ )+ )+ } else {+ persistedSnapshot+ }+ val syncAdapter = when (val resolution = providerSyncRegistry.resolve(snapshot)) {+ is CapabilityResolution.Available -> resolution.capability+ is CapabilityResolution.ConfigurationError -> return@lock Result.error(resolution.reason)+ is CapabilityResolution.Restricted -> return@lock Result.error(resolution.reason)+ is CapabilityResolution.Unsupported -> return@lock Result.error(resolution.reason)+ }+ val sectionResult = withContext(Dispatchers.IO) {+ syncAdapter.syncSection(+ SectionProviderSyncRequest(+ snapshot = snapshot,+ section = section,+ syncReason = syncReason,+ onProgress = onProgress+ )+ )+ }+ val outcome = when (sectionResult) {+ is CapabilityResolution.Available -> sectionResult.capability+ is CapabilityResolution.Unsupported -> return@lock Result.error(sectionResult.reason)+ is CapabilityResolution.Restricted -> return@lock Result.error(sectionResult.reason)+ is CapabilityResolution.ConfigurationError -> return@lock Result.error(sectionResult.reason)}updateSyncStatusMetadata(providerId = providerId,@@ -1900,9 +2102,8 @@ class SyncManager @Inject constructor(return@lock com.streamvault.domain.model.Result.success(Unit)}- val provider = providerEntity- .copy(password = credentialCrypto.decryptIfNeeded(providerEntity.password))- .toDomain()+ val provider = loadCompatibilityProvider(providerId)+ ?: return@lock Result.error("Provider $providerId has no typed configuration")val useTextClassification = preferencesRepository.useXtreamTextClassification.first()val enableBase64TextCompatibility = preferencesRepository.xtreamBase64TextCompatibility.first()val api = createXtreamSyncProvider(provider, useTextClassification, enableBase64TextCompatibility)@@ -1975,7 +2176,8 @@ class SyncManager @Inject constructor(suspend fun reconcileStalkerIndexWorkAtStartup() {providerDao.getAllSync().filter { it.type == ProviderType.STALKER_PORTAL }- .forEach { provider ->+ .forEach { identity ->+ val provider = loadCompatibilityProvider(identity.id) ?: return@forEach// v62 and older reused Xtream rows. They are never valid Stalker owners now.xtreamIndexJobDao.deleteByProvider(provider.id)val hasPendingOneTime = listOf(ContentType.MOVIE, ContentType.SERIES).any { section ->@@ -2042,9 +2244,8 @@ class SyncManager @Inject constructor(return@lock com.streamvault.domain.model.Result.success(Unit)}- val provider = providerEntity- .copy(password = credentialCrypto.decryptIfNeeded(providerEntity.password))- .toDomain()+ val provider = loadCompatibilityProvider(providerId)+ ?: return@lock Result.error("Provider $providerId has no typed configuration")val api = createStalkerSyncProvider(provider)val decision = chooseNextStalkerCatalogSection(provider = provider,@@ -4402,10 +4603,6 @@ class SyncManager @Inject constructor(warnings += stats.warningsval playlistEpgUrl = stats.header.tvgUrlif (provider.epgUrl.isBlank() && !playlistEpgUrl.isNullOrBlank()) {- transactionRunner.inTransaction {- providerWorkflowCommitFence.assertCanCommit(provider.id)- providerDao.updateEpgUrl(provider.id, playlistEpgUrl)- }val existingSourcesByUrl = epgSourceRepository.getAllSources().first().associateBy { it.url }val assignedSourceIds = epgSourceRepository.getAssignmentsForProvider(provider.id).first()@@ -4461,7 +4658,7 @@ class SyncManager @Inject constructor(lastAttemptAt = now,lastError = null)- val epgResult = syncProviderEpg(+ val epgResult = syncM3uProviderEpg(provider = provider,metadata = metadata,now = now,@@ -4539,7 +4736,8 @@ class SyncManager @Inject constructor(provider: Provider,force: Boolean,onProgress: ((String) -> Unit)?,- afterCatalogApply: suspend () -> Unit = {}+ afterCatalogApply: suspend () -> Unit = {},+ deferProviderStateUntilCatalogCommit: Boolean = false): SyncOutcome {val warnings = mutableListOf<String>()stalkerReadinessTracker.start(provider.id)@@ -4556,18 +4754,12 @@ class SyncManager @Inject constructor(val catalogLayoutChanged =authenticatedProvider.catalogLayout != com.streamvault.domain.model.CatalogLayout.UNKNOWN &&authenticatedProvider.catalogLayout != provider.catalogLayout- if (+ val catalogLayoutDetectionChanged =catalogLayoutChanged ||- authenticatedProvider.catalogLayoutDetectionVersion != provider.catalogLayoutDetectionVersion- ) {- transactionRunner.inTransaction {- if (authenticatedProvider.catalogLayout != com.streamvault.domain.model.CatalogLayout.UNKNOWN) {- providerDao.updateCatalogLayout(- provider.id,- authenticatedProvider.catalogLayout,- authenticatedProvider.catalogLayoutDetectionVersion- )- }+ authenticatedProvider.catalogLayoutDetectionVersion != provider.catalogLayoutDetectionVersion+ var catalogCommitCallback = afterCatalogApply+ if (catalogLayoutDetectionChanged) {+ suspend fun clearIncompatibleVodCatalog() {if (catalogLayoutChanged) {categoryDao.deleteByProviderAndType(provider.id, ContentType.MOVIE.name)categoryDao.deleteByProviderAndType(provider.id, ContentType.SERIES.name)@@ -4578,6 +4770,29 @@ class SyncManager @Inject constructor(vodCatalogEntryDao.deleteByProvider(provider.id)}}++ if (deferProviderStateUntilCatalogCommit) {+ // A candidate edit must not rewrite the committed provider row or delete its+ // existing VOD catalog before the first replacement catalog transaction has+ // passed the revision commit gate. The callback executes inside that same Room+ // transaction, so a superseded/cancelled candidate rolls everything back.+ val originalCallback = catalogCommitCallback+ catalogCommitCallback = {+ originalCallback()+ clearIncompatibleVodCatalog()+ }+ } else {+ transactionRunner.inTransaction {+ if (authenticatedProvider.catalogLayout != com.streamvault.domain.model.CatalogLayout.UNKNOWN) {+ providerSnapshotRepository?.updateCatalogLayout(+ provider.id,+ authenticatedProvider.catalogLayout,+ authenticatedProvider.catalogLayoutDetectionVersion+ )+ }+ clearIncompatibleVodCatalog()+ }+ }}stalkerReadinessTracker.authenticated(provider.id)@@ -4597,7 +4812,7 @@ class SyncManager @Inject constructor(provider,hiddenLiveCategoryIds,onProgress,- afterCatalogApply+ catalogCommitCallback)metadata = metadata.copy(lastLiveSync = now,@@ -4790,7 +5005,7 @@ class SyncManager @Inject constructor(when (provider.epgSyncMode) {ProviderEpgSyncMode.UPFRONT -> {- val epgResult = syncProviderEpg(+ val epgResult = syncStalkerProviderEpg(provider = provider,metadata = metadata,now = now,@@ -4960,18 +5175,6 @@ class SyncManager @Inject constructor(error !is JellyfinResponseTooLargeException &&error !is JellyfinItemLimitException- /**- * Returned by [syncProviderEpg] so callers can distinguish between warning-only- * degradations and transient network/IO failures that WorkManager should retry.- */- private data class EpgSyncResult(- val warnings: List<String>,- /** True when at least one EPG sub-operation failed due to a network or IO error- * rather than a permanent configuration problem (bad URL, bad credentials, etc.).- * WorkManager workers should return [Result.retry()] when this is true. */- val hasRetryableFailure: Boolean- )-/*** Returns true for transient network/IO exceptions that are worth retrying via* WorkManager backoff — as opposed to permanent failures (bad URL, auth, parse error)@@ -4994,109 +5197,14 @@ class SyncManager @Inject constructor(metadata: SyncMetadata,now: Long,force: Boolean,- onProgress: ((String) -> Unit)?- ): EpgSyncResult {- var updatedMetadata = metadata+ onProgress: ((String) -> Unit)?,+ syncNativeGuide: suspend (MutableList<String>) -> Boolean+ ): ProviderGuideSyncResult {val warnings = mutableListOf<String>()- var hasRetryableFailure = false+ var hasRetryableFailure = syncNativeGuide(warnings)val hiddenLiveCategoryIds = preferencesRepository.getHiddenCategoryIds(provider.id, ContentType.LIVE).first()val guidePolicy = provider.guideSourcePolicy- when (provider.type) {- ProviderType.XTREAM_CODES -> {- if (shouldUseProviderGuide(guidePolicy) &&- (force || ContentCachePolicy.shouldRefresh(updatedMetadata.lastEpgSuccess, ContentCachePolicy.EPG_TTL_MILLIS, now))- ) {- try {- progress(provider.id, onProgress, "Downloading EPG...")- val base = provider.serverUrl.trimEnd('/')- val xmltvUrl = provider.epgUrl.ifBlank {- XtreamUrlFactory.buildXmltvUrl(base, provider.username, provider.password)- }- UrlSecurityPolicy.validateXtreamEpgUrl(xmltvUrl)?.let { message ->- throw IllegalStateException(message)- }- retryTransient {- requireResult(epgRepository.refreshEpg(provider.id, xmltvUrl), "Failed to refresh EPG")- }- val epgCount = programDao.countByProvider(provider.id)- updatedMetadata = updatedMetadata.copy(- lastEpgSync = now,- lastEpgSuccess = now,- epgCount = epgCount- )- syncMetadataRepository.updateMetadata(updatedMetadata)- if (epgCount == 0) {- warnings.add("EPG imported zero programs; live guide may require provider fallback.")- }- } catch (e: CancellationException) {- throw e- } catch (e: Exception) {- Log.e(TAG, "EPG sync failed (non-fatal): ${sanitizeThrowableMessage(e)}")- if (isRetryableEpgException(e)) hasRetryableFailure = true- warnings.add("EPG XMLTV sync failed.")- }- }- }-- ProviderType.M3U -> {- val currentEpgUrl = providerDao.getById(provider.id)?.epgUrl ?: provider.epgUrl- if (shouldUseProviderGuide(guidePolicy) &&- !currentEpgUrl.isNullOrBlank() &&- (force || ContentCachePolicy.shouldRefresh(updatedMetadata.lastEpgSuccess, ContentCachePolicy.EPG_TTL_MILLIS, now))- ) {- val epgValidationError = UrlSecurityPolicy.validateOptionalEpgUrl(currentEpgUrl)- if (epgValidationError != null) {- warnings.add(epgValidationError)- } else {- try {- progress(provider.id, onProgress, "Downloading EPG...")- retryTransient {- requireResult(epgRepository.refreshEpg(provider.id, currentEpgUrl), "Failed to refresh EPG")- }- updatedMetadata = updatedMetadata.copy(- lastEpgSync = now,- lastEpgSuccess = now,- epgCount = programDao.countByProvider(provider.id)- )- syncMetadataRepository.updateMetadata(updatedMetadata)- } catch (e: CancellationException) {- throw e- } catch (e: Exception) {- Log.e(TAG, "EPG sync failed (non-fatal): ${sanitizeThrowableMessage(e)}")- if (isRetryableEpgException(e)) hasRetryableFailure = true- warnings.add("EPG sync failed")- }- }- }- }-- ProviderType.STALKER_PORTAL -> {- if (shouldUseProviderGuide(guidePolicy) &&- (force || ContentCachePolicy.shouldRefresh(updatedMetadata.lastEpgSuccess, ContentCachePolicy.EPG_TTL_MILLIS, now))- ) {- val learnedEpgSupport = stalkerPortalStateStore.getValidated(provider.id)?.epgSupported- if (learnedEpgSupport == false && provider.epgUrl.isBlank()) {- StalkerTelemetry.strategySelected(provider.id, "EPG_SKIP", "EPG_KNOWN_UNSUPPORTED")- warnings += "Stalker portal guide is known to be unsupported; keeping cached guide data."- } else {- val stalkerEpgWarnings = syncStalkerPreferredEpg(- provider = provider,- now = now,- onProgress = onProgress- )- // A failed capability probe is retryable only until it is learned;- // subsequent syncs skip it for the validation TTL.- if (stalkerEpgWarnings.isNotEmpty()) hasRetryableFailure = true- warnings += stalkerEpgWarnings- }- updatedMetadata = syncMetadataRepository.getMetadata(provider.id) ?: updatedMetadata- }- }-- ProviderType.JELLYFIN -> Unit- }-if (shouldUseExternalGuide(guidePolicy)) {try {progress(provider.id, onProgress, "Refreshing external EPG sources...")@@ -5123,11 +5231,148 @@ class SyncManager @Inject constructor(epgSourceRepository.resolveForProvider(provider.id, hiddenLiveCategoryIds)}- return EpgSyncResult(warnings = warnings, hasRetryableFailure = hasRetryableFailure)+ return ProviderGuideSyncResult(warnings = warnings, hasRetryableFailure = hasRetryableFailure)}- private suspend fun syncEpgOnly(+ private suspend fun syncXtreamProviderEpg(provider: Provider,+ metadata: SyncMetadata,+ now: Long,+ force: Boolean,+ onProgress: ((String) -> Unit)?+ ): ProviderGuideSyncResult = syncProviderEpg(provider, metadata, now, force, onProgress) { warnings ->+ var retryable = false+ if (shouldUseProviderGuide(provider.guideSourcePolicy) &&+ (force || ContentCachePolicy.shouldRefresh(metadata.lastEpgSuccess, ContentCachePolicy.EPG_TTL_MILLIS, now))+ ) {+ try {+ progress(provider.id, onProgress, "Downloading EPG...")+ val base = provider.serverUrl.trimEnd('/')+ val xmltvUrl = provider.epgUrl.ifBlank {+ XtreamUrlFactory.buildXmltvUrl(base, provider.username, provider.password)+ }+ UrlSecurityPolicy.validateXtreamEpgUrl(xmltvUrl)?.let { throw IllegalStateException(it) }+ retryTransient {+ requireResult(epgRepository.refreshEpg(provider.id, xmltvUrl), "Failed to refresh EPG")+ }+ val epgCount = programDao.countByProvider(provider.id)+ syncMetadataRepository.updateMetadata(+ metadata.copy(lastEpgSync = now, lastEpgSuccess = now, epgCount = epgCount)+ )+ if (epgCount == 0) warnings += "EPG imported zero programs; live guide may require provider fallback."+ } catch (e: CancellationException) {+ throw e+ } catch (e: Exception) {+ Log.e(TAG, "EPG sync failed (non-fatal): ${sanitizeThrowableMessage(e)}")+ retryable = isRetryableEpgException(e)+ warnings += "EPG XMLTV sync failed."+ }+ }+ retryable+ }++ private suspend fun syncM3uProviderEpg(+ provider: Provider,+ metadata: SyncMetadata,+ now: Long,+ force: Boolean,+ onProgress: ((String) -> Unit)?+ ): ProviderGuideSyncResult = syncProviderEpg(provider, metadata, now, force, onProgress) { warnings ->+ var retryable = false+ val epgUrl = provider.epgUrl+ if (shouldUseProviderGuide(provider.guideSourcePolicy) && epgUrl.isNotBlank() &&+ (force || ContentCachePolicy.shouldRefresh(metadata.lastEpgSuccess, ContentCachePolicy.EPG_TTL_MILLIS, now))+ ) {+ val validationError = UrlSecurityPolicy.validateOptionalEpgUrl(epgUrl)+ if (validationError != null) {+ warnings += validationError+ } else {+ try {+ progress(provider.id, onProgress, "Downloading EPG...")+ retryTransient {+ requireResult(epgRepository.refreshEpg(provider.id, epgUrl), "Failed to refresh EPG")+ }+ syncMetadataRepository.updateMetadata(+ metadata.copy(+ lastEpgSync = now,+ lastEpgSuccess = now,+ epgCount = programDao.countByProvider(provider.id)+ )+ )+ } catch (e: CancellationException) {+ throw e+ } catch (e: Exception) {+ Log.e(TAG, "EPG sync failed (non-fatal): ${sanitizeThrowableMessage(e)}")+ retryable = isRetryableEpgException(e)+ warnings += "EPG sync failed"+ }+ }+ }+ retryable+ }++ private suspend fun syncStalkerProviderEpg(+ provider: Provider,+ metadata: SyncMetadata,+ now: Long,+ force: Boolean,+ onProgress: ((String) -> Unit)?+ ): ProviderGuideSyncResult = syncProviderEpg(provider, metadata, now, force, onProgress) { warnings ->+ var retryable = false+ if (shouldUseProviderGuide(provider.guideSourcePolicy) &&+ (force || ContentCachePolicy.shouldRefresh(metadata.lastEpgSuccess, ContentCachePolicy.EPG_TTL_MILLIS, now))+ ) {+ val learnedEpgSupport = stalkerPortalStateStore.getValidated(provider.id)?.epgSupported+ if (learnedEpgSupport == false && provider.epgUrl.isBlank()) {+ StalkerTelemetry.strategySelected(provider.id, "EPG_SKIP", "EPG_KNOWN_UNSUPPORTED")+ warnings += "Stalker portal guide is known to be unsupported; keeping cached guide data."+ } else {+ val stalkerWarnings = syncStalkerPreferredEpg(provider, now, onProgress)+ retryable = stalkerWarnings.isNotEmpty()+ warnings += stalkerWarnings+ }+ }+ retryable+ }++ private suspend fun syncJellyfinProviderEpg(+ provider: Provider,+ metadata: SyncMetadata,+ now: Long,+ force: Boolean,+ onProgress: ((String) -> Unit)?+ ): ProviderGuideSyncResult = syncProviderEpg(provider, metadata, now, force, onProgress) { false }++ private suspend fun syncXtreamEpgOnly(+ provider: Provider,+ onProgress: ((String) -> Unit)?+ ) = syncXmlTvEpgOnly(+ provider = provider,+ epgUrl = provider.epgUrl.ifBlank {+ XtreamUrlFactory.buildXmltvUrl(+ provider.serverUrl.trimEnd('/'),+ provider.username,+ provider.password+ )+ },+ validateUrl = UrlSecurityPolicy::validateXtreamEpgUrl,+ onProgress = onProgress+ )++ private suspend fun syncM3uEpgOnly(+ provider: Provider,+ onProgress: ((String) -> Unit)?+ ) = syncXmlTvEpgOnly(+ provider = provider,+ epgUrl = provider.epgUrl,+ validateUrl = UrlSecurityPolicy::validateOptionalEpgUrl,+ onProgress = onProgress+ )++ private suspend fun syncXmlTvEpgOnly(+ provider: Provider,+ epgUrl: String,+ validateUrl: (String) -> String?,onProgress: ((String) -> Unit)?) {progress(provider.id, onProgress, "Retrying EPG...")@@ -5138,42 +5383,6 @@ class SyncManager @Inject constructor(epgSourceRepository.resolveForProvider(provider.id, hiddenLiveCategoryIds)return}- if (provider.type == ProviderType.STALKER_PORTAL) {- if (shouldUseProviderGuide(guidePolicy)) {- syncStalkerPreferredEpg(- provider = provider,- now = System.currentTimeMillis(),- onProgress = onProgress- )- }- if (shouldUseExternalGuide(guidePolicy)) {- progress(provider.id, onProgress, "Refreshing external EPG sources...")- retryTransient {- requireResult(- epgSourceRepository.refreshAllForProvider(provider.id),- "External EPG source refresh failed"- )- }- progress(provider.id, onProgress, "Resolving EPG mappings...")- epgSourceRepository.resolveForProvider(provider.id, hiddenLiveCategoryIds)- }- if (!shouldUseExternalGuide(guidePolicy)) {- progress(provider.id, onProgress, "Resolving provider EPG mappings...")- epgSourceRepository.resolveForProvider(provider.id, hiddenLiveCategoryIds)- }- return- }- val epgUrl = when (provider.type) {- ProviderType.XTREAM_CODES -> {- val base = provider.serverUrl.trimEnd('/')- provider.epgUrl.ifBlank {- XtreamUrlFactory.buildXmltvUrl(base, provider.username, provider.password)- }- }- ProviderType.M3U -> providerDao.getById(provider.id)?.epgUrl ?: provider.epgUrl- ProviderType.STALKER_PORTAL -> providerDao.getById(provider.id)?.epgUrl ?: provider.epgUrl- ProviderType.JELLYFIN -> ""- }if (!shouldUseProviderGuide(guidePolicy)) {if (shouldUseExternalGuide(guidePolicy)) {progress(provider.id, onProgress, "Refreshing external EPG sources...")@@ -5191,13 +5400,7 @@ class SyncManager @Inject constructor(if (epgUrl.isBlank()) {throw IllegalStateException("No EPG URL configured for this provider")}- val validationError = when (provider.type) {- ProviderType.XTREAM_CODES -> UrlSecurityPolicy.validateXtreamEpgUrl(epgUrl)- ProviderType.M3U -> UrlSecurityPolicy.validateOptionalEpgUrl(epgUrl)- ProviderType.STALKER_PORTAL -> UrlSecurityPolicy.validateOptionalEpgUrl(epgUrl)- ProviderType.JELLYFIN -> null- }- validationError?.let { message ->+ validateUrl(epgUrl)?.let { message ->throw IllegalStateException(message)}retryTransient {@@ -5229,13 +5432,44 @@ class SyncManager @Inject constructor(}}+ private suspend fun syncStalkerEpgOnly(+ provider: Provider,+ onProgress: ((String) -> Unit)?+ ) {+ progress(provider.id, onProgress, "Retrying EPG...")+ val hiddenLiveCategoryIds = preferencesRepository.getHiddenCategoryIds(provider.id, ContentType.LIVE).first()+ val guidePolicy = provider.guideSourcePolicy+ if (guidePolicy == GuideSourcePolicy.DISABLED) {+ progress(provider.id, onProgress, "Guide data disabled for this provider.")+ epgSourceRepository.resolveForProvider(provider.id, hiddenLiveCategoryIds)+ return+ }+ if (shouldUseProviderGuide(guidePolicy)) {+ syncStalkerPreferredEpg(provider, System.currentTimeMillis(), onProgress)+ }+ if (shouldUseExternalGuide(guidePolicy)) {+ progress(provider.id, onProgress, "Refreshing external EPG sources...")+ retryTransient {+ requireResult(+ epgSourceRepository.refreshAllForProvider(provider.id),+ "External EPG source refresh failed"+ )+ }+ progress(provider.id, onProgress, "Resolving EPG mappings...")+ epgSourceRepository.resolveForProvider(provider.id, hiddenLiveCategoryIds)+ } else {+ progress(provider.id, onProgress, "Resolving provider EPG mappings...")+ epgSourceRepository.resolveForProvider(provider.id, hiddenLiveCategoryIds)+ }+ }+private suspend fun syncStalkerPreferredEpg(provider: Provider,now: Long,onProgress: ((String) -> Unit)?): List<String> {val warnings = mutableListOf<String>()- val currentEpgUrl = providerDao.getById(provider.id)?.epgUrl ?: provider.epgUrl+ val currentEpgUrl = provider.epgUrlvar shouldUseNativeGuide = currentEpgUrl.isBlank()if (currentEpgUrl.isNotBlank()) {@@ -5553,16 +5787,14 @@ class SyncManager @Inject constructor(}}- private suspend fun syncLiveOnly(+ private suspend fun syncXtreamLiveOnly(provider: Provider,syncReason: XtreamLiveSyncReason,onProgress: ((String) -> Unit)?): SyncOutcome {val now = System.currentTimeMillis()val sectionWarnings = mutableListOf<String>()- when (provider.type) {- ProviderType.XTREAM_CODES -> {- progress(provider.id, onProgress, "Retrying Live TV...")+ progress(provider.id, onProgress, "Retrying Live TV...")val useTextClassification = preferencesRepository.useXtreamTextClassification.first()val enableBase64TextCompatibility = preferencesRepository.xtreamBase64TextCompatibility.first()val hiddenLiveCategoryIds = preferencesRepository.getHiddenCategoryIds(provider.id, ContentType.LIVE).first()@@ -5661,9 +5893,15 @@ class SyncManager @Inject constructor()}}- }- ProviderType.M3U -> {- progress(provider.id, onProgress, "Retrying Live TV...")+ return if (sectionWarnings.isEmpty()) SyncOutcome() else SyncOutcome(partial = true, warnings = sectionWarnings)+ }++ private suspend fun syncM3uLiveOnly(+ provider: Provider,+ onProgress: ((String) -> Unit)?+ ): SyncOutcome {+ val now = System.currentTimeMillis()+ progress(provider.id, onProgress, "Retrying Live TV...")val stats = withContext(Dispatchers.IO) {m3uImporter.importPlaylist(provider, onProgress, includeLive = true, includeMovies = false)}@@ -5677,9 +5915,16 @@ class SyncManager @Inject constructor(liveCount = stats.liveCount)syncMetadataRepository.updateMetadata(metadata)- }- ProviderType.STALKER_PORTAL -> {- emitCatalogSyncProgress(provider.id, section = Section.LIVE)+ return SyncOutcome()+ }++ private suspend fun syncStalkerLiveOnly(+ provider: Provider,+ onProgress: ((String) -> Unit)?+ ): SyncOutcome {+ val now = System.currentTimeMillis()+ val sectionWarnings = mutableListOf<String>()+ emitCatalogSyncProgress(provider.id, section = Section.LIVE)progress(provider.id, onProgress, "Retrying Live TV...")val api = createStalkerSyncProvider(provider)val hiddenLiveCategoryIds = preferencesRepository.getHiddenCategoryIds(provider.id, ContentType.LIVE).first()@@ -5696,22 +5941,15 @@ class SyncManager @Inject constructor(itemsIndexed = liveCatalogResult.acceptedCount)sectionWarnings += liveCatalogResult.warnings- }-- ProviderType.JELLYFIN -> throw IllegalStateException("Live TV retry is unavailable for Jellyfin providers")- }return if (sectionWarnings.isEmpty()) SyncOutcome() else SyncOutcome(partial = true, warnings = sectionWarnings)}- private suspend fun syncMoviesOnly(+ private suspend fun syncXtreamMoviesOnly(provider: Provider,onProgress: ((String) -> Unit)?): SyncOutcome {val now = System.currentTimeMillis()- val sectionWarnings = mutableListOf<String>()- when (provider.type) {- ProviderType.XTREAM_CODES -> {- progress(provider.id, onProgress, "Queueing Movies index...")+ progress(provider.id, onProgress, "Queueing Movies index...")val useTextClassification = preferencesRepository.useXtreamTextClassification.first()val enableBase64TextCompatibility = preferencesRepository.xtreamBase64TextCompatibility.first()val api = createXtreamSyncProvider(provider, useTextClassification, enableBase64TextCompatibility)@@ -5746,9 +5984,15 @@ class SyncManager @Inject constructor()scheduleXtreamIndexSync(provider.id, ContentType.MOVIE)Log.i(TAG, "Queued Xtream movie index for provider ${provider.id}: $categoryCount categories.")- }- ProviderType.M3U -> {- progress(provider.id, onProgress, "Retrying Movies...")+ return SyncOutcome()+ }++ private suspend fun syncM3uMoviesOnly(+ provider: Provider,+ onProgress: ((String) -> Unit)?+ ): SyncOutcome {+ val now = System.currentTimeMillis()+ progress(provider.id, onProgress, "Retrying Movies...")val stats = withContext(Dispatchers.IO) {m3uImporter.importPlaylist(provider, onProgress, includeLive = false, includeMovies = true)}@@ -5766,9 +6010,15 @@ class SyncManager @Inject constructor(movieCatalogStale = false)syncMetadataRepository.updateMetadata(metadata)- }- ProviderType.STALKER_PORTAL -> {- progress(provider.id, onProgress, "Queueing Movies index...")+ return SyncOutcome()+ }++ private suspend fun syncStalkerMoviesOnly(+ provider: Provider,+ onProgress: ((String) -> Unit)?+ ): SyncOutcome {+ val now = System.currentTimeMillis()+ progress(provider.id, onProgress, "Queueing Movies index...")val api = createStalkerSyncProvider(provider)val categories = requireResult(api.getVodCategories(), "Failed to load movie categories")emitCatalogSyncProgress(provider.id,@@ -5807,21 +6057,14 @@ class SyncManager @Inject constructor()syncMetadataRepository.updateMetadata(metadata)scheduleStalkerIndexContinuation(provider, ContentType.MOVIE, force = true)- }-- ProviderType.JELLYFIN -> throw IllegalStateException("Movies retry is unavailable for Jellyfin providers")- }- return if (sectionWarnings.isEmpty()) SyncOutcome() else SyncOutcome(partial = true, warnings = sectionWarnings)+ return SyncOutcome()}- private suspend fun syncSeriesOnly(+ private suspend fun syncXtreamSeriesOnly(provider: Provider,onProgress: ((String) -> Unit)?): SyncOutcome {- val sectionWarnings = mutableListOf<String>()- when (provider.type) {- ProviderType.XTREAM_CODES -> {- val now = System.currentTimeMillis()+ val now = System.currentTimeMillis()progress(provider.id, onProgress, "Queueing Series index...")val useTextClassification = preferencesRepository.useXtreamTextClassification.first()val enableBase64TextCompatibility = preferencesRepository.xtreamBase64TextCompatibility.first()@@ -5855,9 +6098,14 @@ class SyncManager @Inject constructor()scheduleXtreamIndexSync(provider.id, ContentType.SERIES)Log.i(TAG, "Queued Xtream series index for provider ${provider.id}: $categoryCount categories.")- }- ProviderType.STALKER_PORTAL -> {- progress(provider.id, onProgress, "Queueing Series index...")+ return SyncOutcome()+ }++ private suspend fun syncStalkerSeriesOnly(+ provider: Provider,+ onProgress: ((String) -> Unit)?+ ): SyncOutcome {+ progress(provider.id, onProgress, "Queueing Series index...")val api = createStalkerSyncProvider(provider)val categories = requireResult(api.getSeriesCategories(), "Failed to load series categories")emitCatalogSyncProgress(provider.id,@@ -5890,17 +6138,117 @@ class SyncManager @Inject constructor(.copy(lastSeriesSync = now,seriesCount = seriesDao.getCount(provider.id).first()- )+ )syncMetadataRepository.updateMetadata(metadata)scheduleStalkerIndexContinuation(provider, ContentType.SERIES, force = true)- }- ProviderType.M3U -> {- throw IllegalStateException("Series retry is unavailable for this provider")- }+ return SyncOutcome()+ }- ProviderType.JELLYFIN -> throw IllegalStateException("Series retry is unavailable for Jellyfin providers")+ private suspend fun syncJellyfinMoviesOnly(+ provider: Provider,+ onProgress: ((String) -> Unit)?+ ) {+ progress(provider.id, onProgress, "Retrying Jellyfin movies...")+ val decrypted = provider+ val sessionId = syncCatalogStore.newSessionId()+ var startIndex = 0+ var expectedTotal: Int? = null+ try {+ do {+ when (val result = jellyfinProvider.fetchMoviesPage(decrypted, startIndex)) {+ is Result.Success -> {+ val page = result.data+ expectedTotal = expectedTotal ?: page.totalRecordCount+ if (page.totalRecordCount != expectedTotal) {+ throw JellyfinPaginationException("Jellyfin movie catalog changed during retry")+ }+ syncCatalogStore.stageMovieBatch(provider.id, sessionId, page.items)+ startIndex = page.nextStartIndex+ }+ is Result.Error -> throw result.exception ?: IllegalStateException(result.message)+ is Result.Loading -> throw JellyfinPaginationException("Jellyfin movie retry did not complete")+ }+ } while (startIndex < (expectedTotal ?: 0))+ syncCatalogStore.applyStagedMovieCatalog(+ providerId = provider.id,+ sessionId = sessionId,+ categories = listOf(CategoryEntity(+ providerId = provider.id,+ categoryId = 1L,+ name = "Movies",+ type = ContentType.MOVIE+ ))+ )+ val now = System.currentTimeMillis()+ val metadata = syncMetadataRepository.getMetadata(provider.id) ?: SyncMetadata(provider.id)+ syncMetadataRepository.updateMetadata(+ metadata.copy(+ lastMovieSync = now,+ lastMovieAttempt = now,+ lastMovieSuccess = now,+ movieCount = movieDao.getCount(provider.id).first(),+ movieCatalogStale = false+ )+ )+ } catch (cancelled: CancellationException) {+ withContext(NonCancellable) { syncCatalogStore.discardStagedImport(provider.id, sessionId) }+ throw cancelled+ } catch (error: Exception) {+ withContext(NonCancellable) { syncCatalogStore.discardStagedImport(provider.id, sessionId) }+ throw error+ }+ }++ private suspend fun syncJellyfinSeriesOnly(+ provider: Provider,+ onProgress: ((String) -> Unit)?+ ) {+ progress(provider.id, onProgress, "Retrying Jellyfin series...")+ val decrypted = provider+ val sessionId = syncCatalogStore.newSessionId()+ var startIndex = 0+ var expectedTotal: Int? = null+ try {+ do {+ when (val result = jellyfinProvider.fetchSeriesPage(decrypted, startIndex)) {+ is Result.Success -> {+ val page = result.data+ expectedTotal = expectedTotal ?: page.totalRecordCount+ if (page.totalRecordCount != expectedTotal) {+ throw JellyfinPaginationException("Jellyfin series catalog changed during retry")+ }+ syncCatalogStore.stageSeriesBatch(provider.id, sessionId, page.items)+ startIndex = page.nextStartIndex+ }+ is Result.Error -> throw result.exception ?: IllegalStateException(result.message)+ is Result.Loading -> throw JellyfinPaginationException("Jellyfin series retry did not complete")+ }+ } while (startIndex < (expectedTotal ?: 0))+ syncCatalogStore.applyStagedSeriesCatalog(+ providerId = provider.id,+ sessionId = sessionId,+ categories = listOf(CategoryEntity(+ providerId = provider.id,+ categoryId = 2L,+ name = "Series",+ type = ContentType.SERIES+ ))+ )+ val now = System.currentTimeMillis()+ val metadata = syncMetadataRepository.getMetadata(provider.id) ?: SyncMetadata(provider.id)+ syncMetadataRepository.updateMetadata(+ metadata.copy(+ lastSeriesSync = now,+ seriesCount = seriesDao.getCount(provider.id).first()+ )+ )+ } catch (cancelled: CancellationException) {+ withContext(NonCancellable) { syncCatalogStore.discardStagedImport(provider.id, sessionId) }+ throw cancelled+ } catch (error: Exception) {+ withContext(NonCancellable) { syncCatalogStore.discardStagedImport(provider.id, sessionId) }+ throw error}- return if (sectionWarnings.isEmpty()) SyncOutcome() else SyncOutcome(partial = true, warnings = sectionWarnings)}private suspend fun syncXtreamLiveCatalog(@@ -6340,61 +6688,29 @@ class SyncManager @Inject constructor(private const val PROGRESS_INTERVAL = 5_000}- private fun createXtreamSyncProvider(+ private suspend fun createXtreamSyncProvider(provider: Provider,useTextClassification: Boolean = true,enableBase64TextCompatibility: Boolean = false): XtreamProvider {- return XtreamProvider(- providerId = provider.id,- api = xtreamCatalogApiService,- serverUrl = provider.serverUrl,- username = provider.username,- password = provider.password,- allowedOutputFormats = provider.allowedOutputFormats,- useTextClassification = useTextClassification,- enableBase64TextCompatibility = enableBase64TextCompatibility,- requestProfile = provider.toGenericRequestProfile(ownerTag = "provider:${provider.id}/xtream")- )+ return when (val resolution = typedProviderClientFactory.xtream(+ provider.toProviderSnapshot(),+ XtreamClientOptions(useTextClassification, enableBase64TextCompatibility)+ )) {+ is CapabilityResolution.Available -> resolution.capability+ is CapabilityResolution.ConfigurationError -> throw IllegalArgumentException(resolution.reason)+ is CapabilityResolution.Restricted -> throw IllegalArgumentException(resolution.reason)+ is CapabilityResolution.Unsupported -> throw IllegalArgumentException(resolution.reason)+ }}private fun createStalkerSyncProvider(provider: Provider): StalkerProvider {- return StalkerProvider(- providerId = provider.id,- api = stalkerApiService,- portalUrl = provider.serverUrl,- macAddress = provider.stalkerMacAddress,- authMode = provider.stalkerAuthMode,- username = provider.username,- password = provider.password,- httpUserAgent = provider.httpUserAgent,- httpHeaders = provider.httpHeaders,- portalFingerprintHint = provider.stalkerPortalFingerprint,- magPresetHint = provider.stalkerMagPreset,- bootstrapRecipeHint = provider.stalkerLastBootstrapRecipe,- endpointPreferenceHint = provider.stalkerEndpointPreference,- cookieModeHint = provider.stalkerCookieMode,- playbackBackendHint = provider.stalkerPlaybackBackendHint,- portalProfileHint = provider.stalkerPortalProfile,- preferredPlaybackMode = provider.stalkerLastPlaybackMode- ?.let { value -> runCatching { StalkerPlaybackMode.valueOf(value) }.getOrNull() },- deviceProfile = provider.stalkerDeviceProfile,- timezone = provider.stalkerDeviceTimezone,- locale = provider.stalkerDeviceLocale,- serialNumber = provider.stalkerSerialNumber,- deviceId = provider.stalkerDeviceId,- deviceId2 = provider.stalkerDeviceId2,- signature = provider.stalkerSignature,- stalkerAdvancedOptionsJson = provider.stalkerAdvancedOptionsJson,- protocolPreference = provider.stalkerProtocolPreference,- transportGrant = provider.toStalkerTransportGrant(),- requestedProfileId = provider.stalkerRequestedProfileId,- learnedProfileId = provider.stalkerLearnedProfileId,- catalogLayoutHint = provider.catalogLayout,- catalogLayoutDetectionVersionHint = provider.catalogLayoutDetectionVersion,- identityResolver = stalkerRemoteIdentityResolver,- portalStateStore = stalkerPortalStateStore- )+ return when (val resolution = typedProviderClientFactory.stalker(provider.toProviderSnapshot())) {+ is CapabilityResolution.Available -> resolution.capability+ is CapabilityResolution.ConfigurationError -> throw IllegalArgumentException(resolution.reason)+ is CapabilityResolution.Restricted -> throw IllegalArgumentException(resolution.reason)+ is CapabilityResolution.Unsupported -> throw IllegalArgumentException(resolution.reason)+ }}/**diff --git a/data/src/main/java/com/streamvault/data/sync/SyncManagerM3uImporter.kt b/data/src/main/java/com/streamvault/data/sync/SyncManagerM3uImporter.ktindex f7c78f78..45a04d7b 100644--- a/data/src/main/java/com/streamvault/data/sync/SyncManagerM3uImporter.kt+++ b/data/src/main/java/com/streamvault/data/sync/SyncManagerM3uImporter.kt@@ -14,7 +14,7 @@ import com.streamvault.data.remote.http.withRequestProfileimport com.streamvault.data.util.AdultContentClassifierimport com.streamvault.data.util.UrlSecurityPolicyimport com.streamvault.domain.model.ContentType-import com.streamvault.domain.model.Provider+import com.streamvault.domain.model.LegacyProvider as Providerimport com.streamvault.domain.sync.Sectionimport com.streamvault.domain.sync.SyncProgressimport kotlinx.coroutines.NonCancellablediff --git a/data/src/main/java/com/streamvault/data/sync/SyncManagerXtreamFetcher.kt b/data/src/main/java/com/streamvault/data/sync/SyncManagerXtreamFetcher.ktindex 4cd2809d..32fac4fd 100644--- a/data/src/main/java/com/streamvault/data/sync/SyncManagerXtreamFetcher.kt+++ b/data/src/main/java/com/streamvault/data/sync/SyncManagerXtreamFetcher.kt@@ -12,7 +12,7 @@ import com.streamvault.data.remote.xtream.XtreamUrlFactoryimport com.streamvault.data.util.runSuspendCatchingimport com.streamvault.domain.model.Channelimport com.streamvault.domain.model.Movie-import com.streamvault.domain.model.Provider+import com.streamvault.domain.model.LegacyProvider as Providerimport com.streamvault.domain.model.Seriesimport kotlin.system.measureTimeMillisdiff --git a/data/src/main/java/com/streamvault/data/sync/SyncManagerXtreamLiveStrategy.kt b/data/src/main/java/com/streamvault/data/sync/SyncManagerXtreamLiveStrategy.ktindex 849a8c41..425eff4b 100644--- a/data/src/main/java/com/streamvault/data/sync/SyncManagerXtreamLiveStrategy.kt+++ b/data/src/main/java/com/streamvault/data/sync/SyncManagerXtreamLiveStrategy.kt@@ -11,7 +11,7 @@ import com.streamvault.data.remote.xtream.XtreamProviderimport com.streamvault.data.remote.xtream.XtreamUrlFactoryimport com.streamvault.domain.model.Channelimport com.streamvault.domain.model.ContentType-import com.streamvault.domain.model.Provider+import com.streamvault.domain.model.LegacyProvider as Providerimport com.streamvault.domain.model.SyncMetadataimport com.streamvault.domain.sync.Sectionimport com.streamvault.domain.sync.SyncProgressdiff --git a/data/src/main/java/com/streamvault/data/sync/SyncManagerXtreamSupport.kt b/data/src/main/java/com/streamvault/data/sync/SyncManagerXtreamSupport.ktindex fd811c62..c654f713 100644--- a/data/src/main/java/com/streamvault/data/sync/SyncManagerXtreamSupport.kt+++ b/data/src/main/java/com/streamvault/data/sync/SyncManagerXtreamSupport.kt@@ -7,7 +7,7 @@ import com.streamvault.data.remote.xtream.XtreamNetworkExceptionimport com.streamvault.data.remote.xtream.XtreamParsingExceptionimport com.streamvault.data.remote.xtream.XtreamRequestExceptionimport com.streamvault.data.remote.xtream.XtreamResponseTooLargeException-import com.streamvault.domain.model.Provider+import com.streamvault.domain.model.LegacyProvider as Providerimport kotlinx.coroutines.CancellationExceptionimport kotlinx.coroutines.TimeoutCancellationExceptionimport kotlinx.coroutines.asyncdiff --git a/data/src/test/java/com/streamvault/data/epg/EpgResolutionEngineTest.kt b/data/src/test/java/com/streamvault/data/epg/EpgResolutionEngineTest.ktindex fc57b729..50cd0ae5 100644--- a/data/src/test/java/com/streamvault/data/epg/EpgResolutionEngineTest.kt+++ b/data/src/test/java/com/streamvault/data/epg/EpgResolutionEngineTest.kt@@ -6,7 +6,7 @@ import com.streamvault.data.local.dao.ChannelEpgMappingDaoimport com.streamvault.data.local.dao.EpgChannelDaoimport com.streamvault.data.local.dao.EpgProgrammeDaoimport com.streamvault.data.local.dao.ProgramDao-import com.streamvault.data.local.dao.ProviderDao+import com.streamvault.data.local.dao.ProviderSnapshotDaoimport com.streamvault.data.local.dao.ProviderEpgSourceDaoimport com.streamvault.data.local.entity.ChannelEntityimport com.streamvault.data.local.entity.ChannelEpgMappingEntity@@ -14,7 +14,7 @@ import com.streamvault.data.local.entity.ChannelGuideLookupEntityimport com.streamvault.data.local.entity.EpgChannelEntityimport com.streamvault.data.local.entity.EpgProgrammeEntityimport com.streamvault.data.local.entity.ProgramBrowseEntity-import com.streamvault.data.local.entity.ProviderEntity+import com.streamvault.data.local.entity.ProviderConfigEntityimport com.streamvault.data.local.entity.ProviderEpgSourceEntityimport com.streamvault.domain.model.EpgMatchTypeimport com.streamvault.domain.model.EpgSourceType@@ -37,7 +37,7 @@ class EpgResolutionEngineTest {private val epgChannelDao: EpgChannelDao = mock()private val epgProgrammeDao: EpgProgrammeDao = mock()private val programDao: ProgramDao = mock()- private val providerDao: ProviderDao = mock()+ private val providerSnapshotDao: ProviderSnapshotDao = mock()private lateinit var engine: EpgResolutionEngine@@ -51,7 +51,7 @@ class EpgResolutionEngineTest {fun setup() {runTest {whenever(programDao.getChannelIdsWithPrograms(any(), any())).thenReturn(emptyList())- whenever(providerDao.getById(any())).thenReturn(makeProvider())+ whenever(providerSnapshotDao.getConfig(any())).thenReturn(makeProviderConfig())}engine = EpgResolutionEngine(channelDao = channelDao,@@ -60,7 +60,7 @@ class EpgResolutionEngineTest {epgChannelDao = epgChannelDao,epgProgrammeDao = epgProgrammeDao,programDao = programDao,- providerDao = providerDao+ providerSnapshotDao = providerSnapshotDao)}@@ -346,8 +346,8 @@ class EpgResolutionEngineTest {@Testfun `resolveForProvider_providerOnly_replaces_stale_external_mapping_with_provider_mapping`() = runTest {- whenever(providerDao.getById(PROVIDER_ID)).thenReturn(- makeProvider(guideSourcePolicy = GuideSourcePolicy.PROVIDER_ONLY)+ whenever(providerSnapshotDao.getConfig(PROVIDER_ID)).thenReturn(+ makeProviderConfig(GuideSourcePolicy.PROVIDER_ONLY))val channel = makeChannel(id = 1, name = "Local One", epgChannelId = "local.one")whenever(channelDao.getByProviderSync(PROVIDER_ID)).thenReturn(listOf(channel))@@ -457,8 +457,8 @@ class EpgResolutionEngineTest {@Testfun `getResolvedProgrammes_providerOnly_ignores_stale_external_mapping`() = runTest {val now = System.currentTimeMillis()- whenever(providerDao.getById(PROVIDER_ID)).thenReturn(- makeProvider(guideSourcePolicy = GuideSourcePolicy.PROVIDER_ONLY)+ whenever(providerSnapshotDao.getConfig(PROVIDER_ID)).thenReturn(+ makeProviderConfig(GuideSourcePolicy.PROVIDER_ONLY))whenever(channelEpgMappingDao.getForChannels(PROVIDER_ID, listOf(1L))).thenReturn(listOf(@@ -484,8 +484,8 @@ class EpgResolutionEngineTest {@Testfun `getResolvedProgrammes_disabled_ignores_all_mappings`() = runTest {val now = System.currentTimeMillis()- whenever(providerDao.getById(PROVIDER_ID)).thenReturn(- makeProvider(guideSourcePolicy = GuideSourcePolicy.DISABLED)+ whenever(providerSnapshotDao.getConfig(PROVIDER_ID)).thenReturn(+ makeProviderConfig(GuideSourcePolicy.DISABLED))val result = engine.getResolvedProgrammes(PROVIDER_ID, listOf(1L), now - 3600_000, now + 3600_000)@@ -518,13 +518,16 @@ class EpgResolutionEngineTest {epgChannelId = epgChannelId)- private fun makeProvider(+ private fun makeProviderConfig(guideSourcePolicy: GuideSourcePolicy = GuideSourcePolicy.AUTO- ) = ProviderEntity(- id = PROVIDER_ID,- name = "Provider",+ ) = ProviderConfigEntity(+ providerId = PROVIDER_ID,type = ProviderType.XTREAM_CODES,- serverUrl = "http://example.com",- guideSourcePolicy = guideSourcePolicy+ schemaVersion = 1,+ configurationGeneration = 1L,+ identityKey = "identity",+ encryptedConfigJson = "{}",+ guideSourcePolicy = guideSourcePolicy,+ updatedAt = 1L)}diff --git a/data/src/test/java/com/streamvault/data/local/ProviderConfigRevisionClockRecoveryTest.kt b/data/src/test/java/com/streamvault/data/local/ProviderConfigRevisionClockRecoveryTest.ktindex 8b0d215b..42bbcef7 100644--- a/data/src/test/java/com/streamvault/data/local/ProviderConfigRevisionClockRecoveryTest.kt+++ b/data/src/test/java/com/streamvault/data/local/ProviderConfigRevisionClockRecoveryTest.kt@@ -70,4 +70,47 @@ class ProviderConfigRevisionClockRecoveryTest {assertThat(candidates.map { it.providerId }).containsExactly(1L, 2L, 3L)assertThat(candidates.map { it.providerId }).doesNotContain(4L)}++ @Test+ fun `newer edit fences older revision promotion and provider deletion removes stale work`() = runTest {+ val providerDao = database.providerDao()+ val revisionDao = database.providerConfigRevisionDao()+ providerDao.insert(+ ProviderEntity(+ id = 11L,+ name = "Provider",+ type = ProviderType.M3U,+ serverUrl = "https://example.com"+ )+ )+ revisionDao.upsert(+ ProviderConfigRevisionEntity(+ providerId = 11L,+ revision = 1L,+ configJson = "old",+ state = ProviderConfigRevisionState.SYNCING,+ createdAt = 1L,+ updatedAt = 1L+ )+ )+ revisionDao.upsert(+ ProviderConfigRevisionEntity(+ providerId = 11L,+ revision = 2L,+ configJson = "new",+ state = ProviderConfigRevisionState.PENDING,+ createdAt = 2L,+ updatedAt = 2L+ )+ )++ assertThat(revisionDao.markCommitted(11L, 1L, 3L)).isEqualTo(0)+ assertThat(revisionDao.getState(11L, 1L)).isEqualTo(ProviderConfigRevisionState.SYNCING)+ assertThat(revisionDao.claimForSync(11L, 2L, 4L)).isEqualTo(1)+ assertThat(revisionDao.markCommitted(11L, 2L, 5L)).isEqualTo(1)++ providerDao.delete(11L)+ assertThat(revisionDao.get(11L, 1L)).isNull()+ assertThat(revisionDao.get(11L, 2L)).isNull()+ }}diff --git a/data/src/test/java/com/streamvault/data/local/ProviderSnapshotDaoTest.kt b/data/src/test/java/com/streamvault/data/local/ProviderSnapshotDaoTest.ktnew file mode 100644index 00000000..96ce5451--- /dev/null+++ b/data/src/test/java/com/streamvault/data/local/ProviderSnapshotDaoTest.kt@@ -0,0 +1,114 @@+package com.streamvault.data.local++import androidx.room.Room+import com.google.common.truth.Truth.assertThat+import com.streamvault.data.local.entity.ProviderConfigEntity+import com.streamvault.data.local.entity.ProviderEntity+import com.streamvault.data.local.entity.StalkerPortalStateEntity+import com.streamvault.domain.model.ProviderType+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.async+import kotlinx.coroutines.awaitAll+import kotlinx.coroutines.test.runTest+import kotlinx.coroutines.withContext+import org.junit.After+import org.junit.Before+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.RuntimeEnvironment++@RunWith(RobolectricTestRunner::class)+class ProviderSnapshotDaoTest {+ private lateinit var database: StreamVaultDatabase++ @Before+ fun setUp() {+ database = Room.inMemoryDatabaseBuilder(+ RuntimeEnvironment.getApplication(),+ StreamVaultDatabase::class.java+ ).allowMainThreadQueries().build()+ }++ @After+ fun tearDown() = database.close()++ @Test+ fun `configuration generation is monotonic and stale Stalker learning is rejected`() = runTest {+ database.providerDao().insert(+ ProviderEntity(+ id = 7,+ name = "Portal",+ type = ProviderType.STALKER_PORTAL,+ serverUrl = "https://portal.test",+ stalkerMacAddress = "00:11:22:33:44:55"+ )+ )+ val dao = database.providerSnapshotDao()+ assertThat(dao.commitConfiguration(config(generation = 1))).isTrue()+ assertThat(dao.commitConfiguration(config(generation = 1))).isFalse()+ assertThat(dao.commitConfiguration(config(generation = 2))).isTrue()++ assertThat(dao.compareAndSetStalkerLearning(+ StalkerPortalStateEntity(+ providerId = 7,+ workingEndpoint = "https://old.test/load.php",+ configurationGeneration = 1,+ observedAt = 10+ )+ )).isFalse()+ assertThat(dao.compareAndSetStalkerLearning(+ StalkerPortalStateEntity(+ providerId = 7,+ workingEndpoint = "https://new.test/load.php",+ configurationGeneration = 2,+ observedAt = 20+ )+ )).isTrue()+ assertThat(database.stalkerPortalStateDao().get(7)?.workingEndpoint)+ .isEqualTo("https://new.test/load.php")+ }++ @Test+ fun `concurrent learning from old generation cannot win after edit`() = runTest {+ database.providerDao().insert(+ ProviderEntity(+ id = 7,+ name = "Portal",+ type = ProviderType.STALKER_PORTAL,+ serverUrl = "https://portal.test",+ stalkerMacAddress = "00:11:22:33:44:55"+ )+ )+ val dao = database.providerSnapshotDao()+ dao.commitConfiguration(config(generation = 1))+ dao.commitConfiguration(config(generation = 2))++ val outcomes = withContext(Dispatchers.Default) {+ listOf(+ async {+ dao.compareAndSetStalkerLearning(+ StalkerPortalStateEntity(providerId = 7, workingEndpoint = "old", configurationGeneration = 1)+ )+ },+ async {+ dao.compareAndSetStalkerLearning(+ StalkerPortalStateEntity(providerId = 7, workingEndpoint = "new", configurationGeneration = 2)+ )+ }+ ).awaitAll()+ }+ assertThat(outcomes).containsExactly(false, true)+ assertThat(database.stalkerPortalStateDao().get(7)?.workingEndpoint).isEqualTo("new")+ }++ private fun config(generation: Long) = ProviderConfigEntity(+ providerId = 7,+ type = ProviderType.STALKER_PORTAL,+ schemaVersion = 1,+ configurationGeneration = generation,+ identityKey = "identity",+ encryptedConfigJson = "{}",+ updatedAt = generation+ )+}diff --git a/data/src/test/java/com/streamvault/data/local/entity/LegacyProviderEntityFixture.kt b/data/src/test/java/com/streamvault/data/local/entity/LegacyProviderEntityFixture.ktnew file mode 100644index 00000000..99a8e55f--- /dev/null+++ b/data/src/test/java/com/streamvault/data/local/entity/LegacyProviderEntityFixture.kt@@ -0,0 +1,79 @@+@file:Suppress("FunctionName", "LongParameterList", "UNUSED_PARAMETER")++package com.streamvault.data.local.entity++import com.streamvault.domain.model.*++/**+ * Source-compatible constructor for pre-schema-74 DAO fixtures.+ *+ * Configuration arguments are intentionally discarded: tests exercising configuration must seed+ * provider_configs and use ProviderSnapshotRepository. This helper only models the stable row.+ */+fun ProviderEntity(+ id: Long = 0,+ name: String,+ type: ProviderType,+ serverUrl: String,+ username: String = "",+ password: String = "",+ m3uUrl: String = "",+ epgUrl: String = "",+ httpUserAgent: String = "",+ httpHeaders: String = "",+ stalkerMacAddress: String = "",+ stalkerDeviceProfile: String = "",+ stalkerDeviceTimezone: String = "",+ stalkerDeviceLocale: String = "",+ stalkerSerialNumber: String = "",+ stalkerDeviceId: String = "",+ stalkerDeviceId2: String = "",+ stalkerSignature: String = "",+ stalkerAdvancedOptionsJson: String = "",+ stalkerAuthMode: StalkerAuthMode = StalkerAuthMode.AUTO,+ stalkerPortalProfile: StalkerPortalProfile = StalkerPortalProfile.MAG_BASIC,+ stalkerPortalFingerprint: StalkerPortalFingerprint = StalkerPortalFingerprint.BASIC_MAC,+ stalkerMagPreset: StalkerMagPreset = StalkerMagPreset.GENERIC_SAFE,+ stalkerProtocolPreference: StalkerProtocolPreference = StalkerProtocolPreference.AUTO,+ stalkerTransportMode: StalkerTransportMode = StalkerTransportMode.AUTO_STRICT,+ stalkerTransportOrigin: String = "",+ stalkerTlsSpkiSha256: String = "",+ stalkerTransportConsentAt: Long = 0L,+ stalkerConfigurationGeneration: Long = 0L,+ stalkerDiscoverySummary: String = "",+ stalkerCapabilitiesJson: String = "",+ stalkerRequestedProfileId: String = StalkerCompatibilityProfileIds.AUTO,+ stalkerLearnedProfileId: String = "",+ stalkerProfileRevision: Int = 0,+ stalkerProfileVerification: StalkerProfileVerification = StalkerProfileVerification.UNVERIFIED,+ stalkerProtocolFamily: StalkerProtocolFamily = StalkerProtocolFamily.CLASSIC_MAG,+ stalkerLastBootstrapRecipe: StalkerBootstrapRecipe = StalkerBootstrapRecipe.GENERIC_SAFE,+ stalkerEndpointPreference: StalkerEndpointPreference = StalkerEndpointPreference.AUTO,+ stalkerCookieMode: StalkerCookieMode = StalkerCookieMode.NONE,+ stalkerPlaybackBackendHint: StalkerPlaybackBackendHint = StalkerPlaybackBackendHint.AUTO,+ stalkerLastPlaybackMode: String? = null,+ stalkerCredentialsRequired: Boolean = false,+ stalkerMacRequired: Boolean = true,+ stalkerUsesTemporaryLinks: Boolean = false,+ stalkerModuleRestricted: Boolean = false,+ stalkerStrictFingerprintRequired: Boolean = false,+ stalkerRecipeFallbackUsed: Boolean = false,+ stalkerRecipeRediscoveryAttempts: Int = 0,+ isActive: Boolean = true,+ maxConnections: Int = 1,+ expirationDate: Long? = null,+ apiVersion: String? = null,+ allowedOutputFormatsJson: String = "[]",+ epgSyncMode: ProviderEpgSyncMode = ProviderEpgSyncMode.UPFRONT,+ stalkerCatalogMode: StalkerCatalogMode = StalkerCatalogMode.ON_DEMAND,+ guideSourcePolicy: GuideSourcePolicy = GuideSourcePolicy.AUTO,+ channelLogoSourcePolicy: ChannelLogoSourcePolicy = ChannelLogoSourcePolicy.SUPPLIER_PREFERRED,+ xtreamFastSyncEnabled: Boolean = false,+ xtreamLiveSyncMode: ProviderXtreamLiveSyncMode = ProviderXtreamLiveSyncMode.AUTO,+ m3uVodClassificationEnabled: Boolean = false,+ catalogLayout: CatalogLayout = CatalogLayout.SPLIT,+ catalogLayoutDetectionVersion: Int = 0,+ status: ProviderStatus = ProviderStatus.UNKNOWN,+ lastSyncedAt: Long = 0,+ createdAt: Long = System.currentTimeMillis()+): ProviderEntity = ProviderEntity(id, name, type, isActive, status, lastSyncedAt, createdAt)diff --git a/data/src/test/java/com/streamvault/data/manager/BackupManagerImplTest.kt b/data/src/test/java/com/streamvault/data/manager/BackupManagerImplTest.ktindex e5105f50..6a041fc6 100644--- a/data/src/test/java/com/streamvault/data/manager/BackupManagerImplTest.kt+++ b/data/src/test/java/com/streamvault/data/manager/BackupManagerImplTest.kt@@ -12,16 +12,21 @@ import com.streamvault.data.local.dao.FavoriteDaoimport com.streamvault.data.local.dao.MovieDaoimport com.streamvault.data.local.dao.PlaybackHistoryDaoimport com.streamvault.data.local.dao.ProviderDao+import com.streamvault.data.local.dao.ProviderSnapshotDaoimport com.streamvault.data.local.dao.BackupRestoreCheckpointDaoimport com.streamvault.data.local.dao.ChannelDaoimport com.streamvault.data.local.dao.RecordingScheduleDaoimport com.streamvault.data.local.dao.VirtualGroupDaoimport com.streamvault.data.local.entity.ProviderEntity+import com.streamvault.data.local.entity.ProviderConfigEntity+import com.streamvault.data.provider.ProviderConfigurationCodecimport com.streamvault.data.local.entity.EpgSourceEntityimport com.streamvault.data.local.entity.BackupRestoreCheckpointEntityimport com.streamvault.data.local.entity.ChannelEntityimport com.streamvault.data.local.entity.RecordingScheduleEntityimport com.streamvault.data.local.entity.VirtualGroupEntity+import com.streamvault.data.mapper.toEntity+import com.streamvault.data.provider.toProviderSnapshotimport com.streamvault.data.preferences.PreferencesRepositoryimport com.streamvault.data.security.CredentialCryptoimport com.streamvault.domain.manager.BackupData@@ -44,7 +49,7 @@ import com.streamvault.domain.model.DecoderModeimport com.streamvault.domain.model.Favoriteimport com.streamvault.domain.model.EpgSourceimport com.streamvault.domain.model.PlaybackHistory-import com.streamvault.domain.model.Provider+import com.streamvault.domain.model.LegacyProvider as Providerimport com.streamvault.domain.model.ProviderStatusimport com.streamvault.domain.model.ProviderTypeimport com.streamvault.domain.model.RecordingItem@@ -52,6 +57,8 @@ import com.streamvault.domain.model.RecordingRecurrenceimport com.streamvault.domain.model.RecordingStatusimport com.streamvault.domain.model.Resultimport com.streamvault.domain.model.StalkerTransportMode+import com.streamvault.domain.model.StalkerConfig+import com.streamvault.domain.repository.ProviderSnapshotRepositoryimport com.streamvault.domain.model.XmltvTimezonePolicyimport com.streamvault.domain.repository.CategoryRepositoryimport java.io.ByteArrayInputStream@@ -237,7 +244,7 @@ class BackupManagerImplTest {fun `inspectBackup rejects unsupported version before reading sections`() = runBlocking {val error = inspectAdmissionFailure("unsupported-version",- """{"version":11,"preferences":{"value":"${"x".repeat(8_193)}"}}"""+ """{"version":12,"preferences":{"value":"${"x".repeat(8_193)}"}}""")assertThat(error.reason).isEqualTo(BackupAdmissionReason.UNSUPPORTED_VERSION)@@ -282,7 +289,7 @@ class BackupManagerImplTest {@Testfun `recording conflict benchmark remains linear for duplicate heavy sections`() {- val provider = ProviderEntity(+ val provider = Provider(id = 7L,name = "Provider",type = ProviderType.M3U,@@ -396,9 +403,17 @@ class BackupManagerImplTest {ByteArrayInputStream(gson.toJson(backup).toByteArray()))whenever(providerDao.getAllSync()).thenReturn(emptyList())+ whenever(providerDao.insert(any())).thenReturn(9L)whenever(credentialCrypto.encryptIfNeeded(any())).thenAnswer { invocation ->invocation.arguments.first() as String}+ whenever(credentialCrypto.decryptIfNeeded(any())).thenAnswer { invocation ->+ invocation.arguments.first() as String+ }+ val providerSnapshotDao: ProviderSnapshotDao = mock()+ val configurationCodec = ProviderConfigurationCodec(gson, credentialCrypto)+ whenever(providerSnapshotDao.getConfig(any())).thenReturn(null)+ whenever(providerSnapshotDao.commitConfiguration(any())).thenReturn(true)val manager = BackupManagerImpl(context = context,preferencesRepository = mock(),@@ -416,7 +431,10 @@ class BackupManagerImplTest {transactionRunner = object : DatabaseTransactionRunner {override suspend fun <T> inTransaction(block: suspend () -> T): T = block()},- gson = gson+ gson = gson,+ providerSnapshotRepository = mock<ProviderSnapshotRepository>(),+ providerSnapshotDao = providerSnapshotDao,+ providerConfigurationCodec = configurationCodec)val result = manager.importConfig(@@ -432,15 +450,19 @@ class BackupManagerImplTest {)assertThat(result).isInstanceOf(Result.Success::class.java)+ assertThat((result as Result.Success).data.failedSections).isEmpty()+ assertThat((result as Result.Success).data.outcome).isEqualTo(BackupRestoreOutcome.COMPLETE)val inserted = org.mockito.kotlin.argumentCaptor<ProviderEntity>()verify(providerDao).insert(inserted.capture())- assertThat(inserted.firstValue.stalkerTransportMode)- .isEqualTo(StalkerTransportMode.AUTO_STRICT)- assertThat(inserted.firstValue.stalkerTransportOrigin).isEmpty()- assertThat(inserted.firstValue.stalkerTlsSpkiSha256).isEmpty()- assertThat(inserted.firstValue.stalkerTransportConsentAt).isEqualTo(0L)assertThat(inserted.firstValue.isActive).isFalse()assertThat(inserted.firstValue.status).isEqualTo(ProviderStatus.PARTIAL)+ val storedConfig = org.mockito.kotlin.argumentCaptor<ProviderConfigEntity>()+ verify(providerSnapshotDao).commitConfiguration(storedConfig.capture())+ val restoredConfig = configurationCodec.decode(+ storedConfig.firstValue.type,+ storedConfig.firstValue.encryptedConfigJson+ ) as StalkerConfig+ assertThat(restoredConfig.transportGrant).isNull()}@Test@@ -509,7 +531,8 @@ class BackupManagerImplTest {recordingManager = mock<RecordingManager>(),transactionRunner = transactionRunner,gson = gson,- channelDao = mock()+ channelDao = mock(),+ providerSnapshotRepository = snapshotRepositoryFor(backupProvider.copy(id = 7L)))val result = manager.importConfig(@@ -634,7 +657,8 @@ class BackupManagerImplTest {recordingManager = mock<RecordingManager>(),transactionRunner = transactionRunner,gson = gson,- channelDao = mock()+ channelDao = mock(),+ providerSnapshotRepository = snapshotRepositoryFor(backupProvider.copy(id = 7L)))val result = manager.importConfig(@@ -721,7 +745,8 @@ class BackupManagerImplTest {override suspend fun <T> inTransaction(block: suspend () -> T): T = block()},gson = gson,- channelDao = mock()+ channelDao = mock(),+ providerSnapshotRepository = snapshotRepositoryFor(backupProvider.copy(id = 7L)))val result = manager.importConfig(@@ -889,7 +914,7 @@ class BackupManagerImplTest {val categoryRepository: CategoryRepository = mock()val virtualGroupDao: VirtualGroupDao = mock()val channelDao: ChannelDao = mock()- val provider = ProviderEntity(+ val provider = Provider(id = 2L,name = "Source",type = ProviderType.XTREAM_CODES,@@ -958,7 +983,7 @@ class BackupManagerImplTest {val virtualGroupDao: VirtualGroupDao = mock()val channelDao: ChannelDao = mock()val providerReference = BackupProviderReference("https://example.com", "user")- val targetProvider = ProviderEntity(+ val targetProvider = Provider(id = 7L,name = "Target",type = ProviderType.XTREAM_CODES,@@ -991,7 +1016,7 @@ class BackupManagerImplTest {))whenever(context.contentResolver).thenReturn(contentResolver)- whenever(providerDao.getAllSync()).thenReturn(listOf(targetProvider))+ whenever(providerDao.getAllSync()).thenReturn(listOf(targetProvider.toEntity()))whenever(categoryRepository.getCategories(targetProvider.id)).thenReturn(flowOf(listOf(Category(id = 150L, roomId = 1_500L, name = "News", type = ContentType.LIVE))))@@ -1041,7 +1066,8 @@ class BackupManagerImplTest {providerDao = providerDao,categoryRepository = categoryRepository,virtualGroupDao = virtualGroupDao,- channelDao = channelDao+ channelDao = channelDao,+ storedProviders = listOf(targetProvider)).importConfig("content://portable-shifted", preferencesOnlyPlan())val imported = (result as Result.Success).data@@ -1065,7 +1091,7 @@ class BackupManagerImplTest {val virtualGroupDao: VirtualGroupDao = mock()val channelDao: ChannelDao = mock()val reference = BackupProviderReference("https://example.com", "user")- val targetProvider = ProviderEntity(+ val targetProvider = Provider(id = 7L,name = "Target",type = ProviderType.XTREAM_CODES,@@ -1073,7 +1099,7 @@ class BackupManagerImplTest {username = reference.username)whenever(context.contentResolver).thenReturn(contentResolver)- whenever(providerDao.getAllSync()).thenReturn(listOf(targetProvider))+ whenever(providerDao.getAllSync()).thenReturn(listOf(targetProvider.toEntity()))whenever(categoryRepository.getCategories(targetProvider.id)).thenReturn(flowOf(emptyList()))whenever(channelDao.getByProviderSync(targetProvider.id)).thenReturn(emptyList())whenever(virtualGroupDao.getByType(targetProvider.id, ContentType.LIVE.name)).thenReturn(@@ -1105,7 +1131,8 @@ class BackupManagerImplTest {providerDao = providerDao,categoryRepository = categoryRepository,virtualGroupDao = virtualGroupDao,- channelDao = channelDao+ channelDao = channelDao,+ storedProviders = listOf(targetProvider)).importConfig("content://portable-duplicate-group", preferencesOnlyPlan())val imported = (result as Result.Success).data@@ -1170,7 +1197,7 @@ class BackupManagerImplTest {serverUrl = "https://example.com",username = "user")- val targetProvider = ProviderEntity(+ val targetProvider = Provider(id = 7L,name = "Target",type = ProviderType.XTREAM_CODES,@@ -1181,7 +1208,7 @@ class BackupManagerImplTest {val uriString = "content://portable-conflict-${conflictStrategy.name}"var insertCalls = 0whenever(context.contentResolver).thenReturn(contentResolver)- whenever(providerDao.getAllSync()).thenReturn(listOf(targetProvider))+ whenever(providerDao.getAllSync()).thenReturn(listOf(targetProvider.toEntity()))doAnswer {insertCalls += 1targetProvider.id@@ -1209,7 +1236,8 @@ class BackupManagerImplTest {categoryRepository = categoryRepository,virtualGroupDao = virtualGroupDao,channelDao = channelDao,- credentialCrypto = credentialCrypto+ credentialCrypto = credentialCrypto,+ storedProviders = listOf(targetProvider)).importConfig(uriString,preferencesOnlyPlan().copy(@@ -1770,7 +1798,7 @@ class BackupManagerImplTest {@Testfun `importScheduledRecordingBackups reports skipped and failed outcomes`() {val recordingManager: RecordingManager = mock()- val provider = ProviderEntity(+ val provider = Provider(id = 7L,name = "Provider",type = ProviderType.M3U,@@ -1837,7 +1865,7 @@ class BackupManagerImplTest {@Testfun `importScheduledRecordingBackups reports replaced existing schedules`() {val recordingManager: RecordingManager = mock()- val provider = ProviderEntity(+ val provider = Provider(id = 7L,name = "Provider",type = ProviderType.M3U,@@ -1894,7 +1922,7 @@ class BackupManagerImplTest {@Testfun `importScheduledRecordingBackups keeps old schedule when replacement cancellation fails`() = runBlocking {val recordingManager: RecordingManager = mock()- val provider = ProviderEntity(+ val provider = Provider(id = 7L,name = "Provider",type = ProviderType.M3U,@@ -2001,7 +2029,7 @@ class BackupManagerImplTest {}}- private fun ProviderEntity.backupIdentityForTest(): Triple<String, String, String> =+ private fun Provider.backupIdentityForTest(): Triple<String, String, String> =Triple(serverUrl, username, stalkerMacAddress)private fun backupManagerForValidation(@@ -2014,6 +2042,7 @@ class BackupManagerImplTest {virtualGroupDao: VirtualGroupDao = mock(),credentialCrypto: CredentialCrypto = mock(),epgSourceDao: EpgSourceDao? = null,+ storedProviders: List<Provider> = emptyList(),): BackupManagerImpl = BackupManagerImpl(context = context,preferencesRepository = preferencesRepository,@@ -2031,6 +2060,23 @@ class BackupManagerImplTest {override suspend fun <T> inTransaction(block: suspend () -> T): T = block()},gson = Gson(),+ providerSnapshotRepository = object : ProviderSnapshotRepository {+ override suspend fun getSnapshot(providerId: Long) =+ storedProviders.firstOrNull { it.id == providerId }?.toProviderSnapshot()++ override suspend fun compareAndSetStalkerLearning(+ providerId: Long,+ learning: com.streamvault.domain.model.StalkerPortalLearning+ ): Boolean = false++ override suspend fun updateCatalogLayout(+ providerId: Long,+ layout: com.streamvault.domain.model.CatalogLayout,+ detectionVersion: Int+ ) = Unit+ },+ providerSnapshotDao = acceptingSnapshotDao(),+ providerConfigurationCodec = ProviderConfigurationCodec(Gson(), credentialCrypto),backupRestoreCheckpointDao = checkpointDao,channelDao = channelDao,epgSourceDao = epgSourceDao@@ -2044,4 +2090,29 @@ class BackupManagerImplTest {importMultiViewPresets = false,importRecordingSchedules = false)++ private fun snapshotRepositoryFor(vararg providers: Provider) = object : ProviderSnapshotRepository {+ override suspend fun getSnapshot(providerId: Long) =+ checkNotNull(providers.firstOrNull { it.id == providerId }) {+ "No typed provider fixture for id=$providerId; available=${providers.map { it.id }}"+ }.toProviderSnapshot()++ override suspend fun compareAndSetStalkerLearning(+ providerId: Long,+ learning: com.streamvault.domain.model.StalkerPortalLearning+ ): Boolean = false++ override suspend fun updateCatalogLayout(+ providerId: Long,+ layout: com.streamvault.domain.model.CatalogLayout,+ detectionVersion: Int+ ) = Unit+ }++ private fun acceptingSnapshotDao(): ProviderSnapshotDao = mock<ProviderSnapshotDao>().also { dao ->+ runBlocking {+ whenever(dao.getConfig(any())).thenReturn(null)+ whenever(dao.commitConfiguration(any())).thenReturn(true)+ }+ }}diff --git a/data/src/test/java/com/streamvault/data/mapper/EntityMappersTest.kt b/data/src/test/java/com/streamvault/data/mapper/EntityMappersTest.ktindex 136299b3..7708cbcc 100644--- a/data/src/test/java/com/streamvault/data/mapper/EntityMappersTest.kt+++ b/data/src/test/java/com/streamvault/data/mapper/EntityMappersTest.kt@@ -11,7 +11,7 @@ import com.streamvault.domain.model.ChannelQualityOptionimport com.streamvault.domain.model.ContentTypeimport com.streamvault.domain.model.Movieimport com.streamvault.domain.model.PlaybackWatchedStatus-import com.streamvault.domain.model.Provider+import com.streamvault.domain.model.LegacyProvider as Providerimport com.streamvault.domain.model.ProviderStatusimport com.streamvault.domain.model.ProviderTypeimport org.junit.Test@@ -27,8 +27,8 @@ class EntityMappersTest {// ── Provider ──────────────────────────────────────────────────@Test- fun `provider_roundTrip_preservesAllFields`() {- val original = Provider(+ fun `provider entity roundTrip preserves stable identity fields only`() {+ val legacy = Provider(id = 42L,name = "My Xtream Provider",type = ProviderType.XTREAM_CODES,@@ -47,24 +47,21 @@ class EntityMappersTest {createdAt = 1_600_000_000_000L)- val roundTripped = original.toEntity().toDomain()-- assertThat(roundTripped.id).isEqualTo(original.id)- assertThat(roundTripped.name).isEqualTo(original.name)- assertThat(roundTripped.type).isEqualTo(original.type)- assertThat(roundTripped.serverUrl).isEqualTo(original.serverUrl)- assertThat(roundTripped.username).isEqualTo(original.username)- assertThat(roundTripped.password).isEqualTo(original.password)- assertThat(roundTripped.m3uUrl).isEqualTo(original.m3uUrl)- assertThat(roundTripped.epgUrl).isEqualTo(original.epgUrl)- assertThat(roundTripped.isActive).isEqualTo(original.isActive)- assertThat(roundTripped.maxConnections).isEqualTo(original.maxConnections)- assertThat(roundTripped.expirationDate).isEqualTo(original.expirationDate)- assertThat(roundTripped.apiVersion).isEqualTo(original.apiVersion)- assertThat(roundTripped.allowedOutputFormats).containsExactlyElementsIn(original.allowedOutputFormats).inOrder()- assertThat(roundTripped.status).isEqualTo(original.status)- assertThat(roundTripped.lastSyncedAt).isEqualTo(original.lastSyncedAt)- assertThat(roundTripped.createdAt).isEqualTo(original.createdAt)+ val stableEntity = legacy.toEntity()+ val compatibilityView = stableEntity.toDomain()++ assertThat(compatibilityView.id).isEqualTo(legacy.id)+ assertThat(compatibilityView.name).isEqualTo(legacy.name)+ assertThat(compatibilityView.type).isEqualTo(legacy.type)+ assertThat(compatibilityView.isActive).isEqualTo(legacy.isActive)+ assertThat(compatibilityView.status).isEqualTo(legacy.status)+ assertThat(compatibilityView.lastSyncedAt).isEqualTo(legacy.lastSyncedAt)+ assertThat(compatibilityView.createdAt).isEqualTo(legacy.createdAt)+ assertThat(compatibilityView.serverUrl).isEmpty()+ assertThat(compatibilityView.username).isEmpty()+ assertThat(compatibilityView.password).isEmpty()+ assertThat(compatibilityView.maxConnections).isEqualTo(1)+ assertThat(compatibilityView.toEntity()).isEqualTo(stableEntity)}@Testdiff --git a/data/src/test/java/com/streamvault/data/provider/DefaultProviderCapabilityRegistryTest.kt b/data/src/test/java/com/streamvault/data/provider/DefaultProviderCapabilityRegistryTest.ktnew file mode 100644index 00000000..f64e9f19--- /dev/null+++ b/data/src/test/java/com/streamvault/data/provider/DefaultProviderCapabilityRegistryTest.kt@@ -0,0 +1,74 @@+package com.streamvault.data.provider++import com.streamvault.domain.model.Provider as StableProvider++import com.google.common.truth.Truth.assertThat+import com.streamvault.domain.model.*+import com.streamvault.domain.provider.*+import org.junit.Test++class DefaultProviderCapabilityRegistryTest {+ @Test(expected = IllegalArgumentException::class)+ fun `registry rejects missing provider types`() {+ DefaultProviderCapabilityRegistry(listOf(factory(ProviderType.M3U)))+ }++ @Test(expected = IllegalArgumentException::class)+ fun `registry rejects duplicate provider types`() {+ DefaultProviderCapabilityRegistry(+ ProviderType.entries.map(::factory) + factory(ProviderType.M3U)+ )+ }++ @Test+ fun `registry resolves exactly one factory for every provider type`() {+ val registry = DefaultProviderCapabilityRegistry(ProviderType.entries.map(::factory))+ ProviderType.entries.forEach { type ->+ val snapshot = snapshot(type)+ assertThat(registry.resolve(snapshot)).isInstanceOf(CapabilityResolution.Available::class.java)+ }+ }++ @Test+ fun `factory configuration failure is typed`() {+ val factories = ProviderType.entries.map { type ->+ if (type == ProviderType.M3U) object : ProviderCapabilityFactory {+ override val providerType = type+ override fun create(snapshot: ProviderSnapshot): ProviderCapabilitySet =+ throw IllegalArgumentException("bad config")+ } else factory(type)+ }+ assertThat(DefaultProviderCapabilityRegistry(factories).resolve(snapshot(ProviderType.M3U)))+ .isEqualTo(CapabilityResolution.ConfigurationError("bad config"))+ }++ private fun factory(type: ProviderType) = object : ProviderCapabilityFactory {+ override val providerType = type+ override fun create(snapshot: ProviderSnapshot): ProviderCapabilitySet = EmptySet(snapshot)+ }++ private fun snapshot(type: ProviderType): ProviderSnapshot {+ val config: ProviderConfiguration = when (type) {+ ProviderType.XTREAM_CODES -> XtreamConfig("https://x.test", "u", "p")+ ProviderType.M3U -> M3uConfig("https://m.test/list.m3u")+ ProviderType.STALKER_PORTAL -> StalkerConfig("https://s.test", StalkerDeviceIdentity("00:11:22:33:44:55"))+ ProviderType.JELLYFIN -> JellyfinConfig("https://j.test", "u", "t")+ }+ return ProviderSnapshot(+ provider = StableProvider(name = type.name, type = type),+ configuration = config,+ configurationGeneration = 1+ )+ }++ private class EmptySet(override val snapshot: ProviderSnapshot) : ProviderCapabilitySet {+ private fun unsupported() = CapabilityResolution.Unsupported("test")+ override fun authentication(): CapabilityResolution<ProviderAuthenticator> = unsupported()+ override fun liveCatalog(): CapabilityResolution<LiveCatalogSource> = unsupported()+ override fun vodCatalog(): CapabilityResolution<VodCatalogSource> = unsupported()+ override fun seriesCatalog(): CapabilityResolution<SeriesCatalogSource> = unsupported()+ override fun guide(): CapabilityResolution<GuideSource> = unsupported()+ override fun playback(): CapabilityResolution<PlaybackResolver> = unsupported()+ override fun catchUp(): CapabilityResolution<CatchUpSource> = unsupported()+ }+}diff --git a/data/src/test/java/com/streamvault/data/provider/ProductionProviderCapabilityFactoriesTest.kt b/data/src/test/java/com/streamvault/data/provider/ProductionProviderCapabilityFactoriesTest.ktnew file mode 100644index 00000000..6e04d585--- /dev/null+++ b/data/src/test/java/com/streamvault/data/provider/ProductionProviderCapabilityFactoriesTest.kt@@ -0,0 +1,174 @@+package com.streamvault.data.provider++import com.streamvault.domain.model.Provider as StableProvider++import com.google.common.truth.Truth.assertThat+import com.streamvault.data.local.dao.CategoryDao+import com.streamvault.data.local.dao.ChannelDao+import com.streamvault.data.local.dao.MovieDao+import com.streamvault.data.local.dao.ProgramDao+import com.streamvault.data.local.entity.CategoryEntity+import com.streamvault.data.remote.jellyfin.JellyfinProvider+import com.streamvault.data.remote.stalker.StalkerProvider+import com.streamvault.domain.model.CapabilityState+import com.streamvault.domain.model.ContentType+import com.streamvault.domain.model.JellyfinConfig+import com.streamvault.domain.model.M3uConfig+import com.streamvault.domain.model.LegacyProvider as Provider+import com.streamvault.domain.model.ProviderSnapshot+import com.streamvault.domain.model.ProviderType+import com.streamvault.domain.model.StalkerConfig+import com.streamvault.domain.model.StalkerDeviceIdentity+import com.streamvault.domain.model.StalkerObservation+import com.streamvault.domain.model.StalkerObservationSource+import com.streamvault.domain.model.StalkerPortalLearning+import com.streamvault.domain.model.XtreamConfig+import com.streamvault.domain.provider.CapabilityResolution+import com.streamvault.domain.provider.PlaybackResolver+import org.junit.Test+import kotlinx.coroutines.test.runTest+import org.mockito.kotlin.mock+import org.mockito.kotlin.whenever++class ProductionProviderCapabilityFactoriesTest {+ private val clients: TypedProviderClientFactory = mock()+ private val playbackCache: StalkerPlaybackCapabilityCache = mock()+ private val categoryDao: CategoryDao = mock()+ private val channelDao: ChannelDao = mock()+ private val movieDao: MovieDao = mock()+ private val programDao: ProgramDao = mock()++ @Test+ fun `production factories register every provider type exactly once`() {+ val stalker = snapshot(+ ProviderType.STALKER_PORTAL,+ StalkerConfig("https://portal.test", StalkerDeviceIdentity("00:11:22:33:44:55"))+ )+ whenever(clients.stalker(stalker)).thenReturn(CapabilityResolution.Available(mock<StalkerProvider>()))+ whenever(playbackCache.resolve(stalker)).thenReturn(CapabilityResolution.Available(mock<PlaybackResolver>()))+ val jellyfin = snapshot(+ ProviderType.JELLYFIN,+ JellyfinConfig("https://media.test", "alice", "token")+ )+ whenever(clients.jellyfin(jellyfin)).thenReturn(+ CapabilityResolution.Available(+ JellyfinClientContext(+ mock<JellyfinProvider>(),+ Provider(+ id = 4L,+ name = "Jellyfin",+ type = ProviderType.JELLYFIN,+ serverUrl = "https://media.test",+ username = "alice",+ password = "token"+ )+ )+ )+ )+ val registry = registry()++ assertThat(registry.resolve(snapshot(ProviderType.XTREAM_CODES, XtreamConfig("https://x.test", "u", "p"))))+ .isInstanceOf(CapabilityResolution.Available::class.java)+ assertThat(registry.resolve(snapshot(ProviderType.M3U, M3uConfig("https://m.test/list.m3u"))))+ .isInstanceOf(CapabilityResolution.Available::class.java)+ assertThat(registry.resolve(stalker)).isInstanceOf(CapabilityResolution.Available::class.java)+ assertThat(registry.resolve(jellyfin)).isInstanceOf(CapabilityResolution.Available::class.java)+ }++ @Test+ fun `m3u matrix exposes configured execution and typed native-guide absence`() {+ val set = availableSet(+ registry().resolve(snapshot(ProviderType.M3U, M3uConfig("https://m.test/list.m3u")))+ )++ assertThat(set.authentication()).isInstanceOf(CapabilityResolution.Unsupported::class.java)+ assertThat(set.liveCatalog()).isInstanceOf(CapabilityResolution.Available::class.java)+ assertThat(set.vodCatalog()).isInstanceOf(CapabilityResolution.Available::class.java)+ assertThat(set.seriesCatalog()).isInstanceOf(CapabilityResolution.Unsupported::class.java)+ assertThat(set.guide()).isInstanceOf(CapabilityResolution.Unsupported::class.java)+ assertThat(set.playback()).isInstanceOf(CapabilityResolution.Available::class.java)+ assertThat(set.catchUp()).isInstanceOf(CapabilityResolution.Available::class.java)+ }++ @Test+ fun `m3u configured XMLTV exposes guide capability`() {+ val set = availableSet(+ registry().resolve(+ snapshot(+ ProviderType.M3U,+ M3uConfig("https://m.test/list.m3u", epgUrl = "https://m.test/guide.xml")+ )+ )+ )++ assertThat(set.guide()).isInstanceOf(CapabilityResolution.Available::class.java)+ }++ @Test+ fun `m3u catalog capabilities expose the imported local catalog`() = runTest {+ whenever(categoryDao.getByProviderAndTypeSync(2L, ContentType.LIVE.name)).thenReturn(+ listOf(CategoryEntity(categoryId = 11L, name = "News", type = ContentType.LIVE, providerId = 2L))+ )+ whenever(categoryDao.getByProviderAndTypeSync(2L, ContentType.MOVIE.name)).thenReturn(+ listOf(CategoryEntity(categoryId = 12L, name = "Movies", type = ContentType.MOVIE, providerId = 2L))+ )+ val set = availableSet(+ registry().resolve(snapshot(ProviderType.M3U, M3uConfig("https://m.test/list.m3u")))+ )+ val live = (set.liveCatalog() as CapabilityResolution.Available).capability+ val vod = (set.vodCatalog() as CapabilityResolution.Available).capability++ assertThat((live.getLiveCategories() as com.streamvault.domain.model.Result.Success).data.single().name)+ .isEqualTo("News")+ assertThat((vod.getVodCategories() as com.streamvault.domain.model.Result.Success).data.single().name)+ .isEqualTo("Movies")+ }++ @Test+ fun `stalker learning dynamically restricts validated capabilities`() {+ val generation = 7L+ val observation = StalkerObservation(+ CapabilityState.RESTRICTED,+ generation,+ StalkerObservationSource.DISCOVERY,+ 100L+ )+ val stalker = snapshot(+ ProviderType.STALKER_PORTAL,+ StalkerConfig("https://portal.test", StalkerDeviceIdentity("00:11:22:33:44:55")),+ generation,+ StalkerPortalLearning(generation, capabilities = mapOf("series" to observation))+ )+ whenever(clients.stalker(stalker)).thenReturn(CapabilityResolution.Available(mock<StalkerProvider>()))+ whenever(playbackCache.resolve(stalker)).thenReturn(CapabilityResolution.Available(mock<PlaybackResolver>()))++ val set = availableSet(registry().resolve(stalker))++ assertThat(set.liveCatalog()).isInstanceOf(CapabilityResolution.Available::class.java)+ assertThat(set.seriesCatalog()).isInstanceOf(CapabilityResolution.Restricted::class.java)+ }++ private fun registry() = DefaultProviderCapabilityRegistry(+ listOf(+ XtreamCapabilityFactory(clients),+ StalkerCapabilityFactory(clients, playbackCache),+ M3uCapabilityFactory(categoryDao, channelDao, movieDao, programDao),+ JellyfinCapabilityFactory(clients)+ )+ )++ private fun availableSet(resolution: CapabilityResolution<com.streamvault.domain.provider.ProviderCapabilitySet>) =+ (resolution as CapabilityResolution.Available).capability++ private fun snapshot(+ type: ProviderType,+ configuration: com.streamvault.domain.model.ProviderConfiguration,+ generation: Long = 1L,+ learning: StalkerPortalLearning? = null+ ) = ProviderSnapshot(+ provider = StableProvider(id = type.ordinal.toLong() + 1L, name = type.name, type = type),+ configuration = configuration,+ configurationGeneration = generation,+ stalkerLearning = learning+ )+}diff --git a/data/src/test/java/com/streamvault/data/provider/ProviderConfigurationCodecTest.kt b/data/src/test/java/com/streamvault/data/provider/ProviderConfigurationCodecTest.ktnew file mode 100644index 00000000..039f55b6--- /dev/null+++ b/data/src/test/java/com/streamvault/data/provider/ProviderConfigurationCodecTest.kt@@ -0,0 +1,54 @@+package com.streamvault.data.provider++import com.google.common.truth.Truth.assertThat+import com.google.gson.Gson+import com.streamvault.data.security.CredentialCrypto+import com.streamvault.domain.model.*+import org.junit.Test++class ProviderConfigurationCodecTest {+ private val crypto = object : CredentialCrypto {+ override fun encryptIfNeeded(value: String) = if (value.isBlank() || value.startsWith("enc:test:")) value else "enc:test:$value"+ override fun decryptIfNeeded(value: String) = value.removePrefix("enc:test:")+ }+ private val codec = ProviderConfigurationCodec(Gson(), crypto)++ @Test+ fun `round trips every subtype without plaintext credentials`() {+ val configurations = listOf<ProviderConfiguration>(+ XtreamConfig("https://x.test", "alice", "secret"),+ M3uConfig("https://m.test/list.m3u", epgUrl = "https://m.test/epg.xml"),+ StalkerConfig(+ portalUrl = "https://s.test",+ device = StalkerDeviceIdentity("00:11:22:33:44:55", serialNumber = "serial"),+ username = "bob",+ password = "secret2"+ ),+ JellyfinConfig("https://j.test", "carol", "token")+ )++ configurations.forEach { configuration ->+ val encoded = codec.encode(configuration)+ if (configuration !is M3uConfig) assertThat(encoded).doesNotContain(when (configuration) {+ is XtreamConfig -> "\"password\":\"secret\""+ is StalkerConfig -> "\"password\":\"secret2\""+ is JellyfinConfig -> "\"credential\":\"token\""+ else -> error("unreachable")+ })+ assertThat(codec.decode(configuration.type, encoded)).isEqualTo(configuration)+ }+ }++ @Test+ fun `identity key is stable across secrets and cosmetic origin changes`() {+ val first = XtreamConfig("HTTPS://Example.COM", "alice", "one")+ val second = XtreamConfig("https://example.com:443/", "alice", "two")+ assertThat(codec.identityKey(first)).isEqualTo(codec.identityKey(second))+ assertThat(codec.identityKey(first)).hasLength(64)+ }++ @Test(expected = IllegalArgumentException::class)+ fun `decode rejects stored type mismatch`() {+ codec.decode(ProviderType.M3U, codec.encode(XtreamConfig("https://x.test", "u", "p")))+ }+}diff --git a/data/src/test/java/com/streamvault/data/provider/ProviderExecutionArchitectureTest.kt b/data/src/test/java/com/streamvault/data/provider/ProviderExecutionArchitectureTest.ktnew file mode 100644index 00000000..2f9b3362--- /dev/null+++ b/data/src/test/java/com/streamvault/data/provider/ProviderExecutionArchitectureTest.kt@@ -0,0 +1,88 @@+package com.streamvault.data.provider++import com.google.common.truth.Truth.assertThat+import java.nio.file.Files+import java.nio.file.Path+import java.nio.file.Paths+import kotlin.io.path.extension+import kotlin.io.path.invariantSeparatorsPathString+import kotlin.io.path.isDirectory+import kotlin.streams.toList+import org.junit.Test++class ProviderExecutionArchitectureTest {+ private val repositoryRoot: Path by lazy {+ generateSequence(Paths.get(System.getProperty("user.dir")).toAbsolutePath()) { it.parent }+ .first { Files.exists(it.resolve("settings.gradle.kts")) }+ }++ @Test+ fun `protocol clients are constructed only by the typed client factory`() {+ val allowed = setOf(+ "data/src/main/java/com/streamvault/data/provider/TypedProviderClientFactory.kt",+ "data/src/main/java/com/streamvault/data/remote/stalker/StalkerProvider.kt",+ "data/src/main/java/com/streamvault/data/remote/xtream/XtreamProvider.kt"+ )+ val constructorPattern = Regex("\\b(?:StalkerProvider|XtreamProvider)\\s*\\(")+ val violations = productionKotlinFiles()+ .filter { path ->+ constructorPattern.containsMatchIn(path.readText()) &&+ path.repoRelativePath() !in allowed+ }+ .map { it.repoRelativePath() }++ assertThat(violations).isEmpty()+ }++ @Test+ fun `runtime resolver boundaries do not branch on provider type`() {+ val boundaries = listOf(+ "data/src/main/java/com/streamvault/data/remote/xtream/XtreamStreamUrlResolver.kt",+ "data/src/main/java/com/streamvault/data/manager/RecordingManagerImpl.kt",+ "data/src/main/java/com/streamvault/data/epg/EpgResolutionEngine.kt"+ )+ val violations = boundaries.filter { relative ->+ repositoryRoot.resolve(relative).readText().contains("ProviderType.")+ }++ assertThat(violations).isEmpty()+ }++ @Test+ fun `sync execution does not redispatch on provider type after registry resolution`() {+ val source = repositoryRoot.resolve(+ "data/src/main/java/com/streamvault/data/sync/SyncManager.kt"+ ).readText()+ val providerTypeDispatch = Regex(+ """when\s*\(\s*(?:provider|providerEntity)\.type\s*\)"""+ )++ assertThat(providerTypeDispatch.containsMatchIn(source)).isFalse()+ assertThat(source).contains("providerSyncRegistry.resolve(snapshot)")+ assertThat(source).contains("syncAdapter.syncFull(")+ assertThat(source).contains("syncAdapter.syncSection(")+ assertThat(source).contains("syncAdapter.syncGuide(")+ }++ @Test+ fun `legacy provider interface cannot return`() {+ val violations = productionKotlinFiles()+ .filter { path -> path.readText().contains("IptvProvider") }+ .map { it.repoRelativePath() }++ assertThat(violations).isEmpty()+ }++ private fun productionKotlinFiles(): List<Path> =+ listOf("domain/src/main", "data/src/main", "app/src/main")+ .flatMap { relative ->+ Files.walk(repositoryRoot.resolve(relative)).use { paths ->+ paths.filter { path -> !path.isDirectory() && path.extension == "kt" }.toList()+ }+ }++ private fun Path.repoRelativePath(): String =+ repositoryRoot.relativize(this).invariantSeparatorsPathString++ private fun Path.readText(): String = String(Files.readAllBytes(this), Charsets.UTF_8)+}diff --git a/data/src/test/java/com/streamvault/data/remote/http/CancellableOkHttpTest.kt b/data/src/test/java/com/streamvault/data/remote/http/CancellableOkHttpTest.ktindex 9c7fcea3..ab347090 100644--- a/data/src/test/java/com/streamvault/data/remote/http/CancellableOkHttpTest.kt+++ b/data/src/test/java/com/streamvault/data/remote/http/CancellableOkHttpTest.kt@@ -22,6 +22,9 @@ import okio.BufferedSourceimport okio.Sourceimport okio.Timeoutimport okio.buffer+import okhttp3.mockwebserver.MockResponse+import okhttp3.mockwebserver.MockWebServer+import okhttp3.mockwebserver.SocketPolicyimport org.junit.Testclass CancellableOkHttpTest {@@ -98,8 +101,93 @@ class CancellableOkHttpTest {assertThat(bodyClosed.get()).isTrue()}+ @Test+ fun `MockWebServer never-header cancellation releases the dispatcher call`() = runBlocking {+ MockWebServer().use { server ->+ server.enqueue(MockResponse().setSocketPolicy(SocketPolicy.NO_RESPONSE))+ val client = OkHttpClient()+ val consumerEntered = AtomicBoolean(false)+ val job = launch(Dispatchers.IO) {+ client.newCall(request(server.url("/never-header"))).useCancellableResponse {+ consumerEntered.set(true)+ }+ }++ assertThat(server.takeRequest(5, TimeUnit.SECONDS)).isNotNull()+ job.cancelAndJoin()+ awaitIdle(client)++ assertThat(consumerEntered.get()).isFalse()+ }+ }++ @Test+ fun `MockWebServer never-first-byte cancellation releases the dispatcher call`() = runBlocking {+ MockWebServer().use { server ->+ server.enqueue(+ MockResponse()+ .setHeader("Content-Length", "1")+ .setSocketPolicy(SocketPolicy.KEEP_OPEN)+ )+ val client = OkHttpClient()+ val bodyReadStarted = CountDownLatch(1)+ val job = launch(Dispatchers.IO) {+ client.newCall(request(server.url("/never-first-byte"))).useCancellableResponse { response ->+ bodyReadStarted.countDown()+ response.body!!.source().read(Buffer(), 1)+ }+ }++ assertThat(server.takeRequest(5, TimeUnit.SECONDS)).isNotNull()+ assertThat(bodyReadStarted.await(5, TimeUnit.SECONDS)).isTrue()+ job.cancelAndJoin()+ awaitIdle(client)+ }+ }++ @Test+ fun `MockWebServer mid-body cancellation stops consumption and releases the call`() = runBlocking {+ MockWebServer().use { server ->+ server.enqueue(+ MockResponse()+ .setBody(Buffer().write(ByteArray(64 * 1024) { 'x'.code.toByte() }))+ .throttleBody(1024, 1, TimeUnit.SECONDS)+ )+ val client = OkHttpClient()+ val firstChunkRead = CountDownLatch(1)+ val persisted = AtomicBoolean(false)+ val job = launch(Dispatchers.IO) {+ client.newCall(request(server.url("/mid-body"))).useCancellableResponse { response ->+ val source = response.body!!.source()+ val sink = Buffer()+ source.read(sink, 64 * 1024)+ firstChunkRead.countDown()+ source.read(sink, 64 * 1024)+ persisted.set(true)+ }+ }++ assertThat(server.takeRequest(5, TimeUnit.SECONDS)).isNotNull()+ assertThat(firstChunkRead.await(5, TimeUnit.SECONDS)).isTrue()+ job.cancelAndJoin()+ awaitIdle(client)++ assertThat(persisted.get()).isFalse()+ }+ }+private fun request() = Request.Builder().url("https://example.test/stream").build()+ private fun request(url: okhttp3.HttpUrl) = Request.Builder().url(url).build()++ private suspend fun awaitIdle(client: OkHttpClient) {+ withTimeout(5_000) {+ while (client.dispatcher.runningCallsCount() != 0) {+ kotlinx.coroutines.delay(10)+ }+ }+ }+private fun blockingBody(chain: Interceptor.Chain,readStarted: CountDownLatch,diff --git a/data/src/test/java/com/streamvault/data/remote/http/RequestIdentityTest.kt b/data/src/test/java/com/streamvault/data/remote/http/RequestIdentityTest.ktindex 18fe998e..e1d09e1e 100644--- a/data/src/test/java/com/streamvault/data/remote/http/RequestIdentityTest.kt+++ b/data/src/test/java/com/streamvault/data/remote/http/RequestIdentityTest.kt@@ -1,7 +1,7 @@package com.streamvault.data.remote.httpimport com.google.common.truth.Truth.assertThat-import com.streamvault.domain.model.Provider+import com.streamvault.domain.model.LegacyProvider as Providerimport com.streamvault.domain.model.ProviderTypeimport okhttp3.Requestimport org.junit.Testdiff --git a/data/src/test/java/com/streamvault/data/remote/jellyfin/JellyfinImageAuthInterceptorTest.kt b/data/src/test/java/com/streamvault/data/remote/jellyfin/JellyfinImageAuthInterceptorTest.ktindex 3ad140a5..e751f3b7 100644--- a/data/src/test/java/com/streamvault/data/remote/jellyfin/JellyfinImageAuthInterceptorTest.kt+++ b/data/src/test/java/com/streamvault/data/remote/jellyfin/JellyfinImageAuthInterceptorTest.kt@@ -1,9 +1,14 @@package com.streamvault.data.remote.jellyfin+import com.google.gson.Gsonimport com.google.common.truth.Truth.assertThatimport com.streamvault.data.local.dao.ProviderDao+import com.streamvault.data.local.dao.ProviderSnapshotDao+import com.streamvault.data.local.entity.ProviderConfigEntityimport com.streamvault.data.local.entity.ProviderEntity+import com.streamvault.data.provider.ProviderConfigurationCodecimport com.streamvault.data.security.CredentialCrypto+import com.streamvault.domain.model.JellyfinConfigimport com.streamvault.domain.model.ProviderTypeimport java.util.concurrent.ConcurrentHashMapimport okhttp3.Interceptor@@ -19,16 +24,24 @@ import org.mockito.kotlin.wheneverclass JellyfinImageAuthInterceptorTest {private val providerDao: ProviderDao = mock()+ private val providerSnapshotDao: ProviderSnapshotDao = mock()private val credentialCrypto = object : CredentialCrypto {override fun encryptIfNeeded(value: String): String = valueoverride fun decryptIfNeeded(value: String): String = value}- private val interceptor = JellyfinImageAuthInterceptor(providerDao, credentialCrypto)+ private val configurationCodec = ProviderConfigurationCodec(Gson(), credentialCrypto)+ private val interceptor = JellyfinImageAuthInterceptor(+ providerDao,+ providerSnapshotDao,+ configurationCodec+ )@Testfun `two accounts on one server receive only their exact token`() {whenever(providerDao.getByIdSync(1L)).thenReturn(provider(1L, "account-a", "token-a"))whenever(providerDao.getByIdSync(2L)).thenReturn(provider(2L, "account-b", "token-b"))+ whenever(providerSnapshotDao.getConfigSync(1L)).thenReturn(config(1L, "account-a", "token-a"))+ whenever(providerSnapshotDao.getConfigSync(2L)).thenReturn(config(2L, "account-b", "token-b"))val captured = ConcurrentHashMap<Long, Request>()listOf(1L, 2L).parallelStream().forEach { providerId ->@@ -57,6 +70,9 @@ class JellyfinImageAuthInterceptorTest {.thenReturn(provider(7L, "account", "old-token")).thenReturn(provider(7L, "account", "new-token")).thenReturn(null)+ whenever(providerSnapshotDao.getConfigSync(7L))+ .thenReturn(config(7L, "account", "old-token"))+ .thenReturn(config(7L, "account", "new-token"))val url = "https://media.example/jellyfin/Items/item/Images/Primary?streamvault_provider_id=7"val beforeEdit = execute(url)@@ -74,6 +90,9 @@ class JellyfinImageAuthInterceptorTest {whenever(providerDao.getByIdSync(3L)).thenReturn(provider(3L, "account", "secret", serverUrl = "https://media.example/jellyfin"))+ whenever(providerSnapshotDao.getConfigSync(3L)).thenReturn(+ config(3L, "account", "secret", serverUrl = "https://media.example/jellyfin")+ )val captured = execute("https://media.example/other/Items/item/Images/Primary?streamvault_provider_id=3"@@ -126,9 +145,24 @@ class JellyfinImageAuthInterceptorTest {) = ProviderEntity(id = id,name = "Jellyfin $id",- type = ProviderType.JELLYFIN,- serverUrl = serverUrl,- username = username,- password = token+ type = ProviderType.JELLYFIN)++ private fun config(+ id: Long,+ username: String,+ token: String,+ serverUrl: String = "https://media.example/jellyfin"+ ): ProviderConfigEntity {+ val configuration = JellyfinConfig(serverUrl, username, token)+ return ProviderConfigEntity(+ providerId = id,+ type = ProviderType.JELLYFIN,+ schemaVersion = configuration.schemaVersion,+ configurationGeneration = 1L,+ identityKey = configurationCodec.identityKey(configuration),+ encryptedConfigJson = configurationCodec.encode(configuration),+ updatedAt = 1L+ )+ }}diff --git a/data/src/test/java/com/streamvault/data/remote/jellyfin/JellyfinProviderTest.kt b/data/src/test/java/com/streamvault/data/remote/jellyfin/JellyfinProviderTest.ktindex 69ae7a9d..6b0728d5 100644--- a/data/src/test/java/com/streamvault/data/remote/jellyfin/JellyfinProviderTest.kt+++ b/data/src/test/java/com/streamvault/data/remote/jellyfin/JellyfinProviderTest.kt@@ -2,7 +2,7 @@ package com.streamvault.data.remote.jellyfinimport com.google.common.truth.Truth.assertThatimport com.google.gson.Gson-import com.streamvault.domain.model.Provider+import com.streamvault.domain.model.LegacyProvider as Providerimport com.streamvault.domain.model.ProviderTypeimport com.streamvault.domain.model.Resultimport kotlinx.coroutines.test.runTestdiff --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 eaee7d66..a9523dfb 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@@ -1717,14 +1717,14 @@ class OkHttpStalkerApiServiceTest {deviceProfile = "MAG250",timezone = "UTC",locale = "en"- )+ ).copy(providerId = 101L)val profileB = buildStalkerDeviceProfile(portalUrl = "https://portal.example.com/c",macAddress = "00:1A:79:12:34:57",deviceProfile = "MAG250",timezone = "UTC",locale = "en"- )+ ).copy(providerId = 202L)val sessionA = (service.authenticate(profileA) as Result.Success).data.firstval sessionB = (service.authenticate(profileB) as Result.Success).data.first@@ -1735,6 +1735,12 @@ class OkHttpStalkerApiServiceTest {assertThat(playbackCookies.getValue("a")).doesNotContain("session-b")assertThat(playbackCookies.getValue("b")).contains("PHPSESSID=session-b")assertThat(playbackCookies.getValue("b")).doesNotContain("session-a")+ assertThat(sessionA.sessionScopeKey).contains("provider:101|epoch:")+ assertThat(sessionB.sessionScopeKey).contains("provider:202|epoch:")++ service.invalidateSessionScopes(101L)+ val sessionA2 = (service.authenticate(profileA) as Result.Success).data.first+ assertThat(sessionA2.sessionScopeKey).isNotEqualTo(sessionA.sessionScopeKey)}@Test@@ -1820,6 +1826,36 @@ class OkHttpStalkerApiServiceTest {assertThat(requestCount).isEqualTo(1)}+ @Test+ fun http_authentication_error_matrix_distinguishes_expired_session_and_forbidden_request() = runTest {+ suspend fun requestResult(code: Int, body: String): Result<List<StalkerCategoryRecord>> {+ val service = OkHttpStalkerApiService(+ okHttpClient = OkHttpClient.Builder()+ .addInterceptor { chain ->+ Response.Builder()+ .request(chain.request())+ .protocol(Protocol.HTTP_1_1)+ .code(code)+ .message("HTTP $code")+ .body(body.toResponseBody("application/json".toMediaType()))+ .build()+ }+ .build(),+ json = Json { ignoreUnknownKeys = true }+ )+ return service.getLiveCategories(stalkerSession(), stalkerProfile())+ }++ val unauthorized = requestResult(401, "{\"error\":\"expired\"}") as Result.Error+ val tokenRejected = requestResult(403, "{\"error\":\"not_valid_token\"}") as Result.Error+ val forbidden = requestResult(403, "{\"error\":\"forbidden\"}") as Result.Error++ assertThat(unauthorized.exception).isInstanceOf(StalkerApiError.SessionExpired::class.java)+ assertThat(tokenRejected.exception).isInstanceOf(StalkerApiError.SessionExpired::class.java)+ assertThat(forbidden.exception).isInstanceOf(StalkerApiError.BlockedOrConfiguration::class.java)+ assertThat(forbidden.exception).isNotInstanceOf(StalkerApiError.Authorization::class.java)+ }+@Testfun getVodStreams_truncates_huge_catalogs_at_page_limit_instead_of_failing() = runTest {var requestCount = 0@@ -2273,7 +2309,7 @@ class OkHttpStalkerApiServiceTest {portalUrl = "https://portal.example.com/c",macAddress = "00:1A:79:12:34:56",deviceProfile = "MAG250",- timezone = "UTC",+ timezone = "Europe/Amsterdam",locale = "en"),categoryId = "147",@@ -2284,7 +2320,8 @@ class OkHttpStalkerApiServiceTest {val success = result as Result.Successval item = success.data.items.single()val expectedAddedAt = LocalDateTime.of(2026, 5, 18, 13, 2, 23)- .toInstant(ZoneOffset.UTC)+ .atZone(ZoneId.of("Europe/Amsterdam"))+ .toInstant().toEpochMilli()assertThat(item.addedAt).isEqualTo(expectedAddedAt)}diff --git a/data/src/test/java/com/streamvault/data/remote/stalker/OkHttpStalkerCancellationTest.kt b/data/src/test/java/com/streamvault/data/remote/stalker/OkHttpStalkerCancellationTest.ktindex 580aed03..113d33f2 100644--- a/data/src/test/java/com/streamvault/data/remote/stalker/OkHttpStalkerCancellationTest.kt+++ b/data/src/test/java/com/streamvault/data/remote/stalker/OkHttpStalkerCancellationTest.kt@@ -3,22 +3,30 @@ package com.streamvault.data.remote.stalkerimport com.google.common.truth.Truth.assertThatimport com.streamvault.domain.model.Resultimport com.streamvault.domain.model.StalkerAuthMode+import com.streamvault.domain.model.StalkerPortalFingerprintimport com.streamvault.domain.model.DiscoveryBudgetimport java.io.IOExceptionimport java.util.concurrent.CopyOnWriteArrayListimport java.util.concurrent.CountDownLatchimport java.util.concurrent.TimeUnit+import java.util.concurrent.atomic.AtomicBooleanimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.cancelAndJoinimport kotlinx.coroutines.launchimport kotlinx.coroutines.runBlockingimport kotlinx.serialization.json.Jsonimport kotlin.system.measureTimeMillis+import okhttp3.ResponseBodyimport okhttp3.MediaType.Companion.toMediaTypeimport okhttp3.OkHttpClientimport okhttp3.Protocolimport okhttp3.Responseimport okhttp3.ResponseBody.Companion.toResponseBody+import okio.Buffer+import okio.BufferedSource+import okio.Source+import okio.Timeout+import okio.bufferimport org.junit.Testclass OkHttpStalkerCancellationTest {@@ -80,21 +88,221 @@ class OkHttpStalkerCancellationTest {}assertThat(result).isInstanceOf(Result.Error::class.java)- assertThat((result as Result.Error).message).contains("exceeded")+ val error = result as Result.Error+ assertThat(error.exception)+ .isInstanceOf(StalkerApiError.DiscoveryBudgetExceeded::class.java)+ assertThat(error.message).contains("budget")assertThat(cancelled.await(5, TimeUnit.SECONDS)).isTrue()assertThat(elapsedMillis).isLessThan(5_000L)}+ @Test+ fun `cancelling every discovery stage prevents later fallback requests`() = runBlocking {+ data class Scenario(+ val name: String,+ val targetAction: String,+ val profile: StalkerDeviceProfile+ )++ val scenarios = listOf(+ Scenario("profile", "get_profile", profile()),+ Scenario(+ "credentials",+ "do_auth",+ profile(+ authMode = StalkerAuthMode.MAC_PLUS_CREDENTIALS,+ username = "user",+ password = "password"+ )+ ),+ Scenario(+ "modules",+ "get_modules",+ profile(portalFingerprint = StalkerPortalFingerprint.MODULE_GATED)+ ),+ Scenario(+ "catalog",+ "get_ordered_list",+ profile(requireCatalogValidation = true)+ )+ )++ scenarios.forEach { scenario ->+ val actions = CopyOnWriteArrayList<String>()+ val started = CountDownLatch(1)+ val cancelled = CountDownLatch(1)+ val client = OkHttpClient.Builder().addInterceptor { chain ->+ val action = chain.request().url.queryParameter("action").orEmpty()+ actions += action+ if (action == scenario.targetAction) {+ started.countDown()+ while (!chain.call().isCanceled()) Thread.sleep(5)+ cancelled.countDown()+ throw IOException("cancelled")+ }+ Response.Builder()+ .request(chain.request())+ .protocol(Protocol.HTTP_1_1)+ .code(200)+ .message("OK")+ .body(discoveryResponse(action).toResponseBody("application/json".toMediaType()))+ .build()+ }.build()++ val job = launch(Dispatchers.IO) {+ OkHttpStalkerApiService(client, Json { ignoreUnknownKeys = true })+ .authenticate(scenario.profile)+ }++ assertThat(started.await(5, TimeUnit.SECONDS)).isTrue()+ job.cancelAndJoin()++ assertThat(cancelled.await(5, TimeUnit.SECONDS)).isTrue()+ assertThat(actions.last()).isEqualTo(scenario.targetAction)+ }+ }++ @Test+ fun `cancelling a streamed catalog closes the response body`() = runBlocking {+ val started = CountDownLatch(1)+ val cancelled = CountDownLatch(1)+ val bodyClosed = AtomicBoolean(false)+ val client = OkHttpClient.Builder().addInterceptor { chain ->+ Response.Builder()+ .request(chain.request())+ .protocol(Protocol.HTTP_1_1)+ .code(200)+ .message("OK")+ .body(blockingBody(chain, started, cancelled, bodyClosed))+ .build()+ }.build()+ val service = service(client)+ val profile = profile()+ val session = StalkerSession(+ loadUrl = "https://portal.example.com/server/load.php",+ portalReferer = "https://portal.example.com/c/",+ token = "token-123"+ )+ var emittedItems = 0++ val job = launch(Dispatchers.IO) {+ service.streamLiveStreams(session, profile) { emittedItems++ }+ }++ assertThat(started.await(5, TimeUnit.SECONDS)).isTrue()+ job.cancelAndJoin()++ assertThat(cancelled.await(5, TimeUnit.SECONDS)).isTrue()+ assertThat(bodyClosed.get()).isTrue()+ assertThat(emittedItems).isEqualTo(0)+ }++ @Test+ fun `cancelling after streamed headers does not learn response cookies`() = runBlocking {+ val started = CountDownLatch(1)+ val cancelled = CountDownLatch(1)+ val requestCookies = CopyOnWriteArrayList<String>()+ val client = OkHttpClient.Builder().addInterceptor { chain ->+ val action = chain.request().url.queryParameter("action").orEmpty()+ requestCookies += chain.request().header("Cookie").orEmpty()+ if (action == "get_all_channels") {+ Response.Builder()+ .request(chain.request())+ .protocol(Protocol.HTTP_1_1)+ .code(200)+ .message("OK")+ .header("Set-Cookie", "learned=cancelled; Max-Age=3600; Path=/")+ .body(blockingBody(chain, started, cancelled, AtomicBoolean(false)))+ .build()+ } else {+ Response.Builder()+ .request(chain.request())+ .protocol(Protocol.HTTP_1_1)+ .code(200)+ .message("OK")+ .body("""{"js":[]}""".toResponseBody("application/json".toMediaType()))+ .build()+ }+ }.build()+ val service = service(client)+ val profile = profile()+ val session = StalkerSession(+ loadUrl = "https://portal.example.com/server/load.php",+ portalReferer = "https://portal.example.com/c/",+ token = "token-123"+ )++ val job = launch(Dispatchers.IO) {+ service.streamLiveStreams(session, profile) { }+ }+ assertThat(started.await(5, TimeUnit.SECONDS)).isTrue()+ job.cancelAndJoin()+ assertThat(cancelled.await(5, TimeUnit.SECONDS)).isTrue()++ service.getLiveCategories(session, profile)++ assertThat(requestCookies).hasSize(2)+ assertThat(requestCookies.last()).doesNotContain("learned=cancelled")+ }+private fun service(client: OkHttpClient) =OkHttpStalkerApiService(client, Json { ignoreUnknownKeys = true })- private fun profile(budget: DiscoveryBudget = DiscoveryBudget()) = buildStalkerDeviceProfile(+ private fun profile(+ budget: DiscoveryBudget = DiscoveryBudget(),+ authMode: StalkerAuthMode = StalkerAuthMode.AUTO,+ portalFingerprint: StalkerPortalFingerprint = StalkerPortalFingerprint.BASIC_MAC,+ username: String = "",+ password: String = "",+ requireCatalogValidation: Boolean = false+ ) = buildStalkerDeviceProfile(portalUrl = "https://portal.example.com/c",macAddress = "00:1A:79:12:34:56",- authMode = StalkerAuthMode.AUTO,+ authMode = authMode,+ portalFingerprintHint = portalFingerprint,+ username = username,+ password = password,deviceProfile = "MAG250",timezone = "UTC",locale = "en",+ requireCatalogValidation = requireCatalogValidation,discoveryBudget = budget)++ private fun discoveryResponse(action: String): String = when (action) {+ "handshake" -> """{"js":{"token":"token-123","random":"random-123"}}"""+ "do_auth" -> """{"js":{"auth":1}}"""+ "get_profile", "get_main_info" ->+ """{"js":{"id":"42","name":"Test Portal","status":"1","auth_access":true}}"""+ "get_modules" -> """{"js":{"modules":{"itv":1,"vod":1}}}"""+ "get_localization" -> """{"js":{"lang":"en","timezone":"UTC"}}"""+ "get_events" -> """{"js":[]}"""+ "get_genres" -> """{"js":[{"id":"1","title":"News","name":"News"}]}"""+ "get_ordered_list" ->+ """{"js":{"data":[{"id":"1","name":"Channel","cmd":"http://stream.example/channel"}]}}"""+ else -> """{"js":{}}"""+ }++ private fun blockingBody(+ chain: okhttp3.Interceptor.Chain,+ started: CountDownLatch,+ cancelled: CountDownLatch,+ closed: AtomicBoolean+ ): ResponseBody = object : ResponseBody() {+ override fun contentType() = "application/json".toMediaType()+ override fun contentLength(): Long = -1L+ override fun source(): BufferedSource = object : Source {+ override fun read(sink: Buffer, byteCount: Long): Long {+ started.countDown()+ while (!chain.call().isCanceled()) Thread.sleep(5)+ cancelled.countDown()+ throw IOException("cancelled")+ }++ override fun timeout(): Timeout = Timeout.NONE+ override fun close() {+ closed.set(true)+ }+ }.buffer()+ }}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 6564c31b..9dae7a0d 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@@ -4,7 +4,14 @@ import com.google.common.truth.Truth.assertThatimport com.streamvault.data.local.dao.StalkerPortalStateDaoimport com.streamvault.data.local.entity.StalkerPortalStateEntityimport com.streamvault.domain.model.ContentType+import com.streamvault.domain.model.StalkerCookieMode+import com.streamvault.domain.model.StalkerEndpointPreference+import com.streamvault.domain.model.StalkerPlaybackBackendHintimport kotlinx.coroutines.test.runTest+import kotlinx.serialization.json.Json+import kotlinx.serialization.json.jsonObject+import kotlinx.serialization.json.jsonPrimitive+import kotlinx.serialization.json.longimport org.junit.Testclass StalkerPortalStateStoreTest {@@ -102,6 +109,41 @@ class StalkerPortalStateStoreTest {assertThat(state.workingEndpoint).isEqualTo("https://portal.invalid/portal.php")}+ @Test+ fun `authentication and playback observations share one generation-bound learning envelope`() = runTest {+ val dao = FakePortalStateDao()+ val store = StalkerPortalStateStore(dao)+ store.recordAuthentication(+ providerId = 8L,+ session = StalkerSession(+ loadUrl = "https://portal.test/load.php",+ portalReferer = "https://portal.test/c/",+ token = "token"+ ),+ profile = StalkerProviderProfile(compatibilityProfileId = "classic-mag"),+ now = 100L,+ configurationGeneration = 5L+ )+ store.recordPlayback(+ providerId = 8L,+ playbackMode = "DIRECT_URL",+ endpointPreference = StalkerEndpointPreference.SERVER_LOAD,+ cookieMode = StalkerCookieMode.BOTH,+ backendHint = StalkerPlaybackBackendHint.DIRECT,+ now = 200L,+ configurationGeneration = 5L+ )++ val learning = Json.parseToJsonElement(requireNotNull(store.get(8L)).learningJson).jsonObject+ assertThat(learning.getValue("configurationGeneration").jsonPrimitive.long).isEqualTo(5L)+ assertThat(learning.getValue("profileId").jsonObject.getValue("source").jsonPrimitive.content)+ .isEqualTo("AUTHENTICATION")+ assertThat(learning.getValue("lastPlaybackMode").jsonObject.getValue("source").jsonPrimitive.content)+ .isEqualTo("PLAYBACK")+ assertThat(learning.getValue("workingEndpoint").jsonObject.getValue("value").jsonPrimitive.content)+ .isEqualTo("https://portal.test/load.php")+ }+private class FakePortalStateDao : StalkerPortalStateDao {private val rows = mutableMapOf<Long, StalkerPortalStateEntity>()diff --git a/data/src/test/java/com/streamvault/data/remote/stalker/StalkerRemoteIdentityResolverTest.kt b/data/src/test/java/com/streamvault/data/remote/stalker/StalkerRemoteIdentityResolverTest.ktindex 8e0e25dc..4b020593 100644--- a/data/src/test/java/com/streamvault/data/remote/stalker/StalkerRemoteIdentityResolverTest.kt+++ b/data/src/test/java/com/streamvault/data/remote/stalker/StalkerRemoteIdentityResolverTest.kt@@ -9,6 +9,12 @@ import kotlinx.coroutines.test.runTestimport org.junit.Testclass StalkerRemoteIdentityResolverTest {+ @Test+ fun stableHashDoesNotCollapseKnownJavaHashCollision() {+ assertThat(stalkerStableHashId(7L, ContentType.MOVIE, "Aa"))+ .isNotEqualTo(stalkerStableHashId(7L, ContentType.MOVIE, "BB"))+ }+@Testfun collidingLegacyHashesRemainDistinctAndReversible() = runTest {val dao = FakeIdentityDao()diff --git a/data/src/test/java/com/streamvault/data/remote/stalker/StalkerSessionTest.kt b/data/src/test/java/com/streamvault/data/remote/stalker/StalkerSessionTest.ktnew file mode 100644index 00000000..61169ce8--- /dev/null+++ b/data/src/test/java/com/streamvault/data/remote/stalker/StalkerSessionTest.kt@@ -0,0 +1,33 @@+package com.streamvault.data.remote.stalker++import com.google.common.truth.Truth.assertThat+import org.junit.Test++class StalkerSessionTest {+ @Test+ fun session_expires_at_explicit_server_or_account_deadline() {+ val session = StalkerSession(+ loadUrl = "https://portal.example.com/server/load.php",+ portalReferer = "https://portal.example.com/c/",+ token = "token",+ authenticatedAtMillis = 1_000L,+ expiresAtMillis = 2_000L+ )++ assertThat(session.isExpired(1_999L)).isFalse()+ assertThat(session.isExpired(2_000L)).isTrue()+ }++ @Test+ fun session_without_server_deadline_has_bounded_maximum_age() {+ val session = StalkerSession(+ loadUrl = "https://portal.example.com/server/load.php",+ portalReferer = "https://portal.example.com/c/",+ token = "token",+ authenticatedAtMillis = 1_000L+ )++ assertThat(session.isExpired(1_000L + STALKER_SESSION_MAX_AGE_MILLIS - 1L)).isFalse()+ assertThat(session.isExpired(1_000L + STALKER_SESSION_MAX_AGE_MILLIS)).isTrue()+ }+}diff --git a/data/src/test/java/com/streamvault/data/remote/xtream/XtreamProviderTest.kt b/data/src/test/java/com/streamvault/data/remote/xtream/XtreamProviderTest.ktindex 951694d0..88a93207 100644--- a/data/src/test/java/com/streamvault/data/remote/xtream/XtreamProviderTest.kt+++ b/data/src/test/java/com/streamvault/data/remote/xtream/XtreamProviderTest.kt@@ -1,6 +1,7 @@package com.streamvault.data.remote.xtreamimport com.google.common.truth.Truth.assertThat+import com.google.common.truth.Truth.assertWithMessageimport com.streamvault.data.remote.http.HttpRequestProfileimport com.streamvault.data.remote.dto.XtreamAuthResponseimport com.streamvault.data.remote.dto.XtreamCategory@@ -18,7 +19,10 @@ import com.streamvault.data.remote.dto.XtreamUserInfoimport com.streamvault.data.remote.dto.XtreamVodInfoimport com.streamvault.data.remote.dto.XtreamVodInfoResponseimport com.streamvault.data.remote.dto.XtreamVodMovieData+import com.streamvault.domain.model.Result+import java.io.IOExceptionimport kotlinx.coroutines.CompletableDeferred+import kotlinx.coroutines.CancellationExceptionimport kotlinx.coroutines.ExperimentalCoroutinesApiimport kotlinx.coroutines.asyncimport kotlinx.coroutines.cancelAndJoin@@ -30,6 +34,130 @@ import org.junit.Test@OptIn(ExperimentalCoroutinesApi::class)class XtreamProviderTest {+ @Test+ fun `series compatibility fallback preserves cancellation and does not issue legacy request`() = runTest {+ val requestedEndpoints = mutableListOf<String>()+ val provider = XtreamProvider(+ providerId = 42,+ api = FakeXtreamApiService(+ seriesInfoLoader = { endpoint ->+ requestedEndpoints += endpoint.substringAfter("action=get_series_info")+ throw CancellationException("cancelled")+ }+ ),+ serverUrl = "https://example.com",+ username = "user",+ password = "pass"+ )+ var cancellation: CancellationException? = null++ try {+ provider.getSeriesInfo(91)+ } catch (error: CancellationException) {+ cancellation = error+ }++ assertThat(cancellation).isNotNull()+ assertThat(requestedEndpoints).hasSize(1)+ assertThat(requestedEndpoints.single()).contains("series_id=91")+ }++ @Test+ fun `streaming facade preserves cancellation from its batch consumer`() = runTest {+ val provider = XtreamProvider(+ providerId = 42,+ api = FakeXtreamApiService(+ vodStreams = listOf(vodStream("1"))+ ),+ serverUrl = "https://example.com",+ username = "user",+ password = "pass"+ )+ var cancellation: CancellationException? = null++ try {+ provider.streamVodSummaries(batchSize = 1) {+ throw CancellationException("cancelled while consuming batch")+ }+ } catch (error: CancellationException) {+ cancellation = error+ }++ assertThat(cancellation).isNotNull()+ }++ @Test+ fun `all public facade operations preserve cancellation`() = runTest {+ val operations = listOf(+ "authenticate" to CancellationTarget.AUTHENTICATE,+ "live categories" to CancellationTarget.LIVE_CATEGORIES,+ "live streams" to CancellationTarget.LIVE_STREAMS,+ "VOD categories" to CancellationTarget.VOD_CATEGORIES,+ "VOD streams" to CancellationTarget.VOD_STREAMS,+ "VOD stream summaries" to CancellationTarget.VOD_STREAM_SUMMARIES,+ "VOD details" to CancellationTarget.VOD_INFO,+ "series categories" to CancellationTarget.SERIES_CATEGORIES,+ "series list" to CancellationTarget.SERIES_LIST,+ "series summaries" to CancellationTarget.SERIES_SUMMARIES,+ "series details" to CancellationTarget.SERIES_INFO,+ "short EPG" to CancellationTarget.SHORT_EPG,+ "full EPG" to CancellationTarget.FULL_EPG+ )++ operations.forEach { (label, target) ->+ val provider = XtreamProvider(+ providerId = 42,+ api = CancellationXtreamApiService(target),+ serverUrl = "https://example.com",+ username = "user",+ password = "pass"+ )+ var cancellation: CancellationException? = null++ try {+ when (target) {+ CancellationTarget.AUTHENTICATE -> provider.authenticate()+ CancellationTarget.LIVE_CATEGORIES -> provider.getLiveCategories()+ CancellationTarget.LIVE_STREAMS -> provider.getLiveStreams()+ CancellationTarget.VOD_CATEGORIES -> provider.getVodCategories()+ CancellationTarget.VOD_STREAMS -> provider.getVodStreams()+ CancellationTarget.VOD_STREAM_SUMMARIES -> provider.streamVodSummaries { }+ CancellationTarget.VOD_INFO -> provider.getVodInfo(91)+ CancellationTarget.SERIES_CATEGORIES -> provider.getSeriesCategories()+ CancellationTarget.SERIES_LIST -> provider.getSeriesList()+ CancellationTarget.SERIES_SUMMARIES -> provider.streamSeriesSummaries { }+ CancellationTarget.SERIES_INFO -> provider.getSeriesInfo(91)+ CancellationTarget.SHORT_EPG -> provider.getShortEpg("91", 5)+ CancellationTarget.FULL_EPG -> provider.getEpg("91")+ }+ } catch (error: CancellationException) {+ cancellation = error+ }++ assertWithMessage("$label must preserve cancellation")+ .that(cancellation)+ .isNotNull()+ }+ }++ @Test+ fun `genuine Xtream network failures remain typed facade errors`() = runTest {+ val provider = XtreamProvider(+ providerId = 42,+ api = FakeXtreamApiService(+ authLoader = { throw IOException("connection reset") }+ ),+ serverUrl = "https://example.com",+ username = "user",+ password = "pass"+ )++ val result = provider.authenticate()++ assertThat(result).isInstanceOf(Result.Error::class.java)+ assertThat((result as Result.Error).exception).isInstanceOf(IOException::class.java)+ }+@Testfun `parseXtreamExpirationDate handles slash separated local date times`() {assertThat(parseXtreamExpirationDate("2026/03/20 14:30:00")).isEqualTo(1774017000000L)@@ -901,9 +1029,108 @@ class XtreamProviderTest {containerExtension = "mp4")+ private enum class CancellationTarget {+ AUTHENTICATE,+ LIVE_CATEGORIES,+ LIVE_STREAMS,+ VOD_CATEGORIES,+ VOD_STREAMS,+ VOD_STREAM_SUMMARIES,+ VOD_INFO,+ SERIES_CATEGORIES,+ SERIES_LIST,+ SERIES_SUMMARIES,+ SERIES_INFO,+ SHORT_EPG,+ FULL_EPG+ }++ private class CancellationXtreamApiService(+ private val target: CancellationTarget+ ) : XtreamApiService {+ private fun cancelIf(expected: CancellationTarget) {+ if (target == expected) throw CancellationException("${expected.name} cancelled")+ }++ override suspend fun authenticate(endpoint: String, requestProfile: HttpRequestProfile): XtreamAuthResponse {+ cancelIf(CancellationTarget.AUTHENTICATE)+ return XtreamAuthResponse(XtreamUserInfo(auth = 1), XtreamServerInfo())+ }++ override suspend fun getLiveCategories(endpoint: String, requestProfile: HttpRequestProfile): List<XtreamCategory> {+ cancelIf(CancellationTarget.LIVE_CATEGORIES)+ return emptyList()+ }++ override suspend fun getLiveStreams(endpoint: String, requestProfile: HttpRequestProfile): List<XtreamStream> {+ cancelIf(CancellationTarget.LIVE_STREAMS)+ return emptyList()+ }++ override suspend fun getVodCategories(endpoint: String, requestProfile: HttpRequestProfile): List<XtreamCategory> {+ cancelIf(CancellationTarget.VOD_CATEGORIES)+ return emptyList()+ }++ override suspend fun getVodStreams(endpoint: String, requestProfile: HttpRequestProfile): List<XtreamStream> {+ cancelIf(CancellationTarget.VOD_STREAMS)+ return emptyList()+ }++ override suspend fun streamVodStreams(+ endpoint: String,+ requestProfile: HttpRequestProfile,+ onItem: suspend (XtreamStream) -> Unit+ ): Int {+ cancelIf(CancellationTarget.VOD_STREAM_SUMMARIES)+ return super.streamVodStreams(endpoint, requestProfile, onItem)+ }++ override suspend fun getVodInfo(endpoint: String, requestProfile: HttpRequestProfile): XtreamVodInfoResponse {+ cancelIf(CancellationTarget.VOD_INFO)+ return XtreamVodInfoResponse()+ }++ override suspend fun getSeriesCategories(endpoint: String, requestProfile: HttpRequestProfile): List<XtreamCategory> {+ cancelIf(CancellationTarget.SERIES_CATEGORIES)+ return emptyList()+ }++ override suspend fun getSeriesList(endpoint: String, requestProfile: HttpRequestProfile): List<XtreamSeriesItem> {+ cancelIf(CancellationTarget.SERIES_LIST)+ return emptyList()+ }++ override suspend fun streamSeriesList(+ endpoint: String,+ requestProfile: HttpRequestProfile,+ onItem: suspend (XtreamSeriesItem) -> Unit+ ): Int {+ cancelIf(CancellationTarget.SERIES_SUMMARIES)+ return super.streamSeriesList(endpoint, requestProfile, onItem)+ }++ override suspend fun getSeriesInfo(endpoint: String, requestProfile: HttpRequestProfile): XtreamSeriesInfoResponse {+ cancelIf(CancellationTarget.SERIES_INFO)+ return XtreamSeriesInfoResponse()+ }++ override suspend fun getShortEpg(endpoint: String, requestProfile: HttpRequestProfile): XtreamEpgResponse {+ cancelIf(CancellationTarget.SHORT_EPG)+ return XtreamEpgResponse()+ }++ override suspend fun getFullEpg(endpoint: String, requestProfile: HttpRequestProfile): XtreamEpgResponse {+ cancelIf(CancellationTarget.FULL_EPG)+ return XtreamEpgResponse()+ }+ }+private class FakeXtreamApiService(private val authResponse: XtreamAuthResponse = XtreamAuthResponse(XtreamUserInfo(auth = 1), XtreamServerInfo()),+ private val authLoader: (suspend () -> XtreamAuthResponse)? = null,private val liveCategories: List<XtreamCategory> = emptyList(),+ private val liveCategoriesLoader: (suspend () -> List<XtreamCategory>)? = null,private val liveStreams: List<XtreamStream> = emptyList(),private val vodCategories: List<XtreamCategory> = emptyList(),private val vodCategoriesLoader: (suspend () -> List<XtreamCategory>)? = null,@@ -912,14 +1139,16 @@ class XtreamProviderTest {private val seriesCategories: List<XtreamCategory> = emptyList(),private val seriesList: List<XtreamSeriesItem> = emptyList(),private val seriesInfo: XtreamSeriesInfoResponse = XtreamSeriesInfoResponse(),+ private val seriesInfoLoader: (suspend (String) -> XtreamSeriesInfoResponse)? = null,private val shortEpg: XtreamEpgResponse = XtreamEpgResponse(),private val fullEpg: XtreamEpgResponse = XtreamEpgResponse()) : XtreamApiService {override suspend fun authenticate(endpoint: String, requestProfile: HttpRequestProfile): XtreamAuthResponse {- return authResponse+ return authLoader?.invoke() ?: authResponse}- override suspend fun getLiveCategories(endpoint: String, requestProfile: HttpRequestProfile): List<XtreamCategory> = liveCategories+ override suspend fun getLiveCategories(endpoint: String, requestProfile: HttpRequestProfile): List<XtreamCategory> =+ liveCategoriesLoader?.invoke() ?: liveCategoriesoverride suspend fun getLiveStreams(endpoint: String, requestProfile: HttpRequestProfile): List<XtreamStream> = liveStreams@@ -934,7 +1163,8 @@ class XtreamProviderTest {override suspend fun getSeriesList(endpoint: String, requestProfile: HttpRequestProfile): List<XtreamSeriesItem> = seriesList- override suspend fun getSeriesInfo(endpoint: String, requestProfile: HttpRequestProfile): XtreamSeriesInfoResponse = seriesInfo+ override suspend fun getSeriesInfo(endpoint: String, requestProfile: HttpRequestProfile): XtreamSeriesInfoResponse =+ seriesInfoLoader?.invoke(endpoint) ?: seriesInfooverride suspend fun getShortEpg(endpoint: String, requestProfile: HttpRequestProfile): XtreamEpgResponse = shortEpgdiff --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 bd218efc..c9e37e94 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@@ -4,7 +4,21 @@ import com.google.common.truth.Truth.assertThatimport com.streamvault.data.local.dao.ProviderDaoimport com.streamvault.data.local.entity.ProviderEntityimport com.streamvault.data.preferences.PreferencesRepository+import com.streamvault.data.mapper.toDomain+import com.streamvault.data.mapper.toEntity+import com.streamvault.data.provider.DefaultProviderCapabilityRegistry+import com.streamvault.data.provider.JellyfinCapabilityFactory+import com.streamvault.data.provider.M3uCapabilityFactory+import com.streamvault.data.provider.ProviderCapabilityResolver+import com.streamvault.data.provider.StalkerCapabilityFactory+import com.streamvault.data.provider.StalkerPlaybackCapabilityCache+import com.streamvault.data.provider.TypedProviderClientFactory+import com.streamvault.data.provider.XtreamCapabilityFactory+import com.streamvault.data.provider.toProviderSnapshot+import com.streamvault.data.remote.jellyfin.JellyfinProviderimport com.streamvault.data.remote.stalker.StalkerApiService+import com.streamvault.data.remote.stalker.StalkerPortalStateStore+import com.streamvault.data.remote.stalker.StalkerRemoteIdentityResolverimport com.streamvault.data.remote.stalker.StalkerCommandVariantimport com.streamvault.data.remote.stalker.StalkerCategoryRecordimport com.streamvault.data.remote.stalker.StalkerDeviceProfile@@ -26,6 +40,9 @@ import com.streamvault.data.security.CredentialCryptoimport com.streamvault.domain.model.LiveStreamFormatModeimport com.streamvault.domain.model.Resultimport com.streamvault.domain.model.ProviderType+import com.streamvault.domain.model.LegacyProvider as Provider+import com.streamvault.domain.model.StalkerPortalLearning+import com.streamvault.domain.repository.ProviderSnapshotRepositoryimport kotlinx.coroutines.flow.flowOfimport kotlinx.coroutines.runBlockingimport org.junit.Test@@ -55,7 +72,7 @@ class XtreamStreamUrlResolverTest {preferencesRepository = preferencesRepository(liveStreamFormatMode))- private fun xtreamProvider(): ProviderEntity = ProviderEntity(+ private fun xtreamProvider(): Provider = Provider(id = 9,name = "Xtream",type = ProviderType.XTREAM_CODES,@@ -180,7 +197,7 @@ class XtreamStreamUrlResolverTest {runBlocking {val resolver = XtreamStreamUrlResolver(providerDao = FakeProviderDao(- ProviderEntity(+ Provider(id = 9,name = "Xtream",type = ProviderType.XTREAM_CODES,@@ -213,7 +230,7 @@ class XtreamStreamUrlResolverTest {runBlocking {val resolver = XtreamStreamUrlResolver(providerDao = FakeProviderDao(- ProviderEntity(+ Provider(id = 9,name = "Xtream",type = ProviderType.XTREAM_CODES,@@ -250,7 +267,7 @@ class XtreamStreamUrlResolverTest {runBlocking {val resolver = XtreamStreamUrlResolver(providerDao = FakeProviderDao(- ProviderEntity(+ Provider(id = 9,name = "Xtream",type = ProviderType.XTREAM_CODES,@@ -283,7 +300,7 @@ class XtreamStreamUrlResolverTest {runBlocking {val resolver = XtreamStreamUrlResolver(providerDao = FakeProviderDao(- ProviderEntity(+ Provider(id = 9,name = "Xtream",type = ProviderType.XTREAM_CODES,@@ -315,7 +332,7 @@ class XtreamStreamUrlResolverTest {runBlocking {val resolver = XtreamStreamUrlResolver(providerDao = FakeProviderDao(- ProviderEntity(+ Provider(id = 21,name = "Playlist",type = ProviderType.M3U,@@ -376,7 +393,7 @@ class XtreamStreamUrlResolverTest {val fakeStalkerApiService = FakeStalkerApiService()val resolver = XtreamStreamUrlResolver(providerDao = FakeProviderDao(- ProviderEntity(+ Provider(id = 14,name = "Stalker",type = ProviderType.STALKER_PORTAL,@@ -427,7 +444,7 @@ class XtreamStreamUrlResolverTest {val fakeStalkerApiService = FakeStalkerApiService()val resolver = XtreamStreamUrlResolver(providerDao = FakeProviderDao(- ProviderEntity(+ Provider(id = 14,name = "Stalker",type = ProviderType.STALKER_PORTAL,@@ -466,7 +483,7 @@ class XtreamStreamUrlResolverTest {val fakeStalkerApiService = FakeStalkerApiService()val resolver = XtreamStreamUrlResolver(providerDao = FakeProviderDao(- ProviderEntity(+ Provider(id = 14,name = "Stalker",type = ProviderType.STALKER_PORTAL,@@ -509,7 +526,7 @@ class XtreamStreamUrlResolverTest {}val resolver = XtreamStreamUrlResolver(providerDao = FakeProviderDao(- ProviderEntity(+ Provider(id = 14,name = "Stalker",type = ProviderType.STALKER_PORTAL,@@ -553,7 +570,7 @@ class XtreamStreamUrlResolverTest {}val resolver = XtreamStreamUrlResolver(providerDao = FakeProviderDao(- ProviderEntity(+ Provider(id = 14,name = "Stalker",type = ProviderType.STALKER_PORTAL,@@ -592,7 +609,7 @@ class XtreamStreamUrlResolverTest {val fakeStalkerApiService = FakeStalkerApiService()val resolver = XtreamStreamUrlResolver(providerDao = FakeProviderDao(- ProviderEntity(+ Provider(id = 14,name = "Stalker",type = ProviderType.STALKER_PORTAL,@@ -647,7 +664,7 @@ class XtreamStreamUrlResolverTest {val fakeStalkerApiService = FakeStalkerApiService()val resolver = XtreamStreamUrlResolver(providerDao = FakeProviderDao(- ProviderEntity(+ Provider(id = 14,name = "Stalker",type = ProviderType.STALKER_PORTAL,@@ -683,12 +700,12 @@ class XtreamStreamUrlResolverTest {}private class FakeProviderDao(- private val provider: ProviderEntity?- ) : ProviderDao() {+ override val fixtureProvider: Provider?+ ) : ProviderDao(), ProviderFixtureSource {+ private val provider = fixtureProvider?.toEntity()override fun getAll() = flowOf(listOfNotNull(provider))override suspend fun getAllSync(): List<ProviderEntity> = listOfNotNull(provider)override fun getActive() = flowOf(provider)- override suspend fun getByUrlAndUser(serverUrl: String, username: String, stalkerMacAddress: String): ProviderEntity? = nulloverride suspend fun getById(id: Long): ProviderEntity? = provider?.takeIf { it.id == id }override fun getByIdSync(id: Long): ProviderEntity? = provider?.takeIf { it.id == id }override suspend fun getByIds(ids: List<Long>): List<ProviderEntity> =@@ -703,13 +720,6 @@ class XtreamStreamUrlResolverTest {override suspend fun deactivateAll() = Unitoverride suspend fun activate(id: Long) = Unitoverride suspend fun updateSyncTime(id: Long, timestamp: Long) = Unit- override 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 {@@ -848,3 +858,55 @@ class XtreamStreamUrlResolverTest {}}}++@Suppress("FunctionName")+private fun XtreamStreamUrlResolver(+ providerDao: ProviderDao,+ credentialCrypto: CredentialCrypto,+ stalkerApiService: StalkerApiService,+ preferencesRepository: PreferencesRepository+): XtreamStreamUrlResolver {+ val provider = requireNotNull((providerDao as? ProviderFixtureSource)?.fixtureProvider)+ val snapshots = object : ProviderSnapshotRepository {+ override suspend fun getSnapshot(providerId: Long) =+ provider.takeIf { it.id == providerId }?.toProviderSnapshot()++ override suspend fun compareAndSetStalkerLearning(+ providerId: Long,+ learning: StalkerPortalLearning+ ): Boolean = false++ override suspend fun updateCatalogLayout(+ providerId: Long,+ layout: com.streamvault.domain.model.CatalogLayout,+ detectionVersion: Int+ ) = Unit+ }+ val clients = TypedProviderClientFactory(+ xtreamApiService = mock(),+ stalkerApiService = stalkerApiService,+ jellyfinProvider = mock<JellyfinProvider>(),+ preferencesRepository = preferencesRepository,+ stalkerRemoteIdentityResolver = mock<StalkerRemoteIdentityResolver>(),+ stalkerPortalStateStore = mock<StalkerPortalStateStore>()+ )+ val stalkerPlaybackCache = StalkerPlaybackCapabilityCache(clients)+ val registry = DefaultProviderCapabilityRegistry(+ listOf(+ XtreamCapabilityFactory(clients),+ StalkerCapabilityFactory(clients, stalkerPlaybackCache),+ M3uCapabilityFactory(+ categoryDao = mock(),+ channelDao = mock(),+ movieDao = mock(),+ programDao = mock()+ ),+ JellyfinCapabilityFactory(clients)+ )+ )+ return XtreamStreamUrlResolver(ProviderCapabilityResolver(snapshots, registry))+}++private interface ProviderFixtureSource {+ val fixtureProvider: Provider?+}diff --git a/data/src/test/java/com/streamvault/data/repository/EpgRepositoryImplTest.kt b/data/src/test/java/com/streamvault/data/repository/EpgRepositoryImplTest.ktindex f7af912f..0215c0fb 100644--- a/data/src/test/java/com/streamvault/data/repository/EpgRepositoryImplTest.kt+++ b/data/src/test/java/com/streamvault/data/repository/EpgRepositoryImplTest.kt@@ -8,7 +8,12 @@ import com.streamvault.data.local.entity.ProviderEntityimport com.streamvault.data.local.entity.ProgramBrowseEntityimport com.streamvault.data.local.entity.ProgramEntityimport com.streamvault.data.parser.XmltvParser+import com.streamvault.data.provider.ProviderCapabilityResolverimport com.streamvault.domain.model.Program+import com.streamvault.domain.model.Provider+import com.streamvault.domain.model.ProviderSnapshot+import com.streamvault.domain.model.StalkerConfig+import com.streamvault.domain.model.StalkerDeviceIdentityimport com.streamvault.domain.model.ProviderTypeimport kotlinx.coroutines.CompletableDeferredimport kotlinx.coroutines.ExperimentalCoroutinesApi@@ -54,6 +59,7 @@ class EpgRepositoryImplTest {private val providerDao: ProviderDao = mock()private val xmltvParser: XmltvParser = mock()private val epgSourceRepository: EpgSourceRepository = mock()+ private val providerCapabilityResolver: ProviderCapabilityResolver = mock()private val preferencesRepository: PreferencesRepository = mock()private val transactionRunner = object : DatabaseTransactionRunner {override suspend fun <T> inTransaction(block: suspend () -> T): T = block()@@ -621,13 +627,21 @@ class EpgRepositoryImplTest {@Testfun `refreshEpg passes provider timezone to parser for no offset timestamps`() = runTest {- whenever(providerDao.getById(7L)).thenReturn(- ProviderEntity(- id = 7L,- name = "Provider",- type = ProviderType.M3U,- serverUrl = "https://provider.example.com",- stalkerDeviceTimezone = "America/New_York"+ whenever(providerCapabilityResolver.snapshot(7L)).thenReturn(+ ProviderSnapshot(+ provider = Provider(+ id = 7L,+ name = "Provider",+ type = ProviderType.STALKER_PORTAL+ ),+ configuration = StalkerConfig(+ portalUrl = "https://provider.example.com",+ device = StalkerDeviceIdentity(+ macAddress = "00:1A:79:00:00:07",+ timezone = "America/New_York"+ )+ ),+ configurationGeneration = 1L))whenever(xmltvParser.parseStreaming(any(), anyOrNull(), any())).thenAnswer { invocation ->@@ -654,7 +668,8 @@ class EpgRepositoryImplTest {okHttpClient = okHttpClientReturningXml(),transactionRunner = transactionRunner,epgSourceRepository = epgSourceRepository,- preferencesRepository = preferencesRepository+ preferencesRepository = preferencesRepository,+ providerCapabilityResolver = providerCapabilityResolver)val result = repository.refreshEpg(7L, "https://example.com/epg.xml")diff --git a/data/src/test/java/com/streamvault/data/repository/MovieRepositoryImplTest.kt b/data/src/test/java/com/streamvault/data/repository/MovieRepositoryImplTest.ktindex 573a006a..33063e8c 100644--- a/data/src/test/java/com/streamvault/data/repository/MovieRepositoryImplTest.kt+++ b/data/src/test/java/com/streamvault/data/repository/MovieRepositoryImplTest.kt@@ -18,13 +18,19 @@ import com.streamvault.data.local.entity.MovieEntityimport com.streamvault.data.local.entity.PlaybackHistoryLiteEntityimport com.streamvault.data.local.entity.ProviderEntityimport com.streamvault.data.local.entity.XtreamIndexJobEntity+import com.streamvault.data.mapper.toEntity+import com.streamvault.data.provider.ProviderCapabilityResolver+import com.streamvault.data.provider.TypedProviderClientFactory+import com.streamvault.data.provider.toProviderSnapshotimport com.streamvault.data.preferences.PreferencesRepositoryimport com.streamvault.data.remote.stalker.StalkerDeviceProfileimport com.streamvault.data.remote.stalker.StalkerProviderProfile+import com.streamvault.data.remote.stalker.StalkerProviderimport com.streamvault.data.remote.stalker.StalkerSessionimport com.streamvault.data.remote.stalker.StalkerCategoryRecordimport com.streamvault.data.remote.stalker.StalkerItemRecordimport com.streamvault.data.remote.stalker.StalkerPagedItems+import com.streamvault.data.remote.stalker.StalkerRemoteIdentityResolverimport com.streamvault.data.remote.dto.XtreamCategoryimport com.streamvault.data.remote.dto.XtreamStreamimport com.streamvault.data.remote.stalker.StalkerApiService@@ -41,6 +47,7 @@ import com.streamvault.domain.model.MovieDetailPresentationHintimport com.streamvault.domain.model.PlaybackHistoryimport com.streamvault.domain.model.ProviderStatusimport com.streamvault.domain.model.ProviderType+import com.streamvault.domain.model.LegacyProvider as Providerimport com.streamvault.domain.model.Resultimport com.streamvault.domain.model.SyncMetadataimport com.streamvault.domain.model.VodDuplicateConfidence@@ -53,6 +60,7 @@ import com.streamvault.domain.model.VodVariantObservationimport com.streamvault.domain.model.VodVariantPreferenceModeimport com.streamvault.domain.repository.PlaybackHistoryRepositoryimport com.streamvault.domain.repository.SyncMetadataRepository+import com.streamvault.domain.provider.CapabilityResolutionimport kotlinx.coroutines.CompletableDeferredimport kotlinx.coroutines.flow.firstimport kotlinx.coroutines.flow.flow@@ -88,6 +96,9 @@ class MovieRepositoryImplTest {private val xtreamContentIndexDao: XtreamContentIndexDao = mock()private val xtreamIndexJobDao: XtreamIndexJobDao = mock()private val syncManager: SyncManager = mock()+ private val providerCapabilityResolver: ProviderCapabilityResolver = mock()+ private val typedProviderClientFactory: TypedProviderClientFactory = mock()+ private val stalkerRemoteIdentityResolver: StalkerRemoteIdentityResolver = mock()private val credentialCrypto = object : CredentialCrypto {override fun encryptIfNeeded(value: String): String = valueoverride fun decryptIfNeeded(value: String): String = value@@ -201,8 +212,8 @@ class MovieRepositoryImplTest {whenever(movieDao.getCountByCategory(7L, 42L)).thenReturn(flowOf(0))whenever(movieDao.getByCategory(7L, 42L)).thenReturn(flowOf(emptyList()))whenever(movieCategoryHydrationDao.get(7L, 42L)).thenReturn(null)- whenever(providerDao.getById(7L)).thenReturn(- ProviderEntity(+ stubProvider(+ Provider(id = 7L,name = "Xtream",type = ProviderType.XTREAM_CODES,@@ -232,8 +243,8 @@ class MovieRepositoryImplTest {whenever(syncMetadataRepository.getMetadata(7L)).thenReturn(SyncMetadata(providerId = 7L, movieSyncMode = VodSyncMode.LAZY_BY_CATEGORY))- whenever(providerDao.getById(7L)).thenReturn(- ProviderEntity(+ stubProvider(+ Provider(id = 7L,name = "Xtream",type = ProviderType.XTREAM_CODES,@@ -263,8 +274,8 @@ class MovieRepositoryImplTest {whenever(xtreamIndexJobDao.get(7L, ContentType.MOVIE.name)).thenReturn(XtreamIndexJobEntity(providerId = 7L, section = ContentType.MOVIE.name, state = "RUNNING"))- whenever(providerDao.getById(7L)).thenReturn(- ProviderEntity(+ stubProvider(+ Provider(id = 7L,name = "Stalker",type = ProviderType.STALKER_PORTAL,@@ -307,8 +318,8 @@ class MovieRepositoryImplTest {detailHydratedAt = hydratedAt))- whenever(providerDao.getById(7L)).thenReturn(- ProviderEntity(+ stubProvider(+ Provider(id = 7L,name = "Xtream",type = ProviderType.XTREAM_CODES,@@ -353,8 +364,8 @@ class MovieRepositoryImplTest {)whenever(movieDao.getById(99L)).thenReturn(rawMovie)whenever(movieDao.getByProviderAndTmdbIdSync(7L, 777L)).thenReturn(listOf(rawMovie, alternateMovie))- whenever(providerDao.getById(7L)).thenReturn(- ProviderEntity(+ stubProvider(+ Provider(id = 7L,name = "Xtream",type = ProviderType.XTREAM_CODES,@@ -393,8 +404,8 @@ class MovieRepositoryImplTest {detailHydratedAt = hydratedAt)whenever(movieDao.getById(99L)).thenReturn(rawMovie)- whenever(providerDao.getById(7L)).thenReturn(- ProviderEntity(+ stubProvider(+ Provider(id = 7L,name = "Xtream",type = ProviderType.XTREAM_CODES,@@ -465,8 +476,8 @@ class MovieRepositoryImplTest {whenever(movieDao.getCountByCategory(7L, 42L)).thenReturn(flowOf(0))whenever(movieDao.getByCategory(7L, 42L)).thenReturn(flowOf(emptyList()))whenever(movieCategoryHydrationDao.get(7L, 42L)).thenReturn(null)- whenever(providerDao.getById(7L)).thenReturn(- ProviderEntity(+ stubProvider(+ Provider(id = 7L,name = "Stalker",type = ProviderType.STALKER_PORTAL,@@ -523,8 +534,8 @@ class MovieRepositoryImplTest {whenever(categoryDao.getByProviderAndType(7L, ContentType.MOVIE.name)).thenReturn(flowOf(listOf(com.streamvault.data.local.entity.CategoryEntity(providerId = 7L, categoryId = 42L, name = "Action", type = ContentType.MOVIE))))- whenever(providerDao.getById(7L)).thenReturn(- ProviderEntity(+ stubProvider(+ Provider(id = 7L,name = "Stalker",type = ProviderType.STALKER_PORTAL,@@ -586,7 +597,7 @@ class MovieRepositoryImplTest {)))- whenever(providerDao.getById(7L)).thenReturn(stalkerProviderEntity())+ stubProvider(stalkerProvider())whenever(stalkerApiService.authenticate(any())).thenReturn(stalkerSessionResult())whenever(stalkerApiService.getVodCategories(any(), any())).thenReturn(Result.success(listOf(StalkerCategoryRecord(id = "42", name = "Action")))@@ -634,7 +645,7 @@ class MovieRepositoryImplTest {)))- whenever(providerDao.getById(7L)).thenReturn(stalkerProviderEntity())+ stubProvider(stalkerProvider())whenever(stalkerApiService.authenticate(any())).thenReturn(stalkerSessionResult())whenever(stalkerApiService.getVodCategories(any(), any())).thenReturn(Result.success(listOf(StalkerCategoryRecord(id = "42", name = "Action")))@@ -655,7 +666,7 @@ class MovieRepositoryImplTest {whenever(movieDao.getCountByCategory(7L, 42L)).thenReturn(flowOf(0), flowOf(14), flowOf(28), flowOf(42))whenever(movieDao.getByCategoryPage(7L, 42L, 60, 0)).thenReturn(flowOf(emptyList()))whenever(movieCategoryHydrationDao.get(7L, 42L)).thenReturn(null)- whenever(providerDao.getById(7L)).thenReturn(stalkerProviderEntity())+ stubProvider(stalkerProvider())whenever(stalkerApiService.authenticate(any())).thenReturn(stalkerSessionResult())whenever(stalkerApiService.getVodCategories(any(), any())).thenReturn(Result.success(listOf(StalkerCategoryRecord(id = "42", name = "Action")))@@ -685,7 +696,7 @@ class MovieRepositoryImplTest {flowOf(42))whenever(movieCategoryHydrationDao.get(7L, 42L)).thenReturn(null)- whenever(providerDao.getById(7L)).thenReturn(stalkerProviderEntity())+ stubProvider(stalkerProvider())whenever(stalkerApiService.authenticate(any())).thenReturn(stalkerSessionResult())whenever(stalkerApiService.getVodCategories(any(), any())).thenReturn(Result.success(listOf(StalkerCategoryRecord(id = "42", name = "Action")))@@ -728,7 +739,7 @@ class MovieRepositoryImplTest {pageSize = 14))- whenever(providerDao.getById(7L)).thenReturn(stalkerProviderEntity())+ stubProvider(stalkerProvider())whenever(stalkerApiService.authenticate(any())).thenReturn(stalkerSessionResult())whenever(stalkerApiService.getVodCategories(any(), any())).thenReturn(Result.success(listOf(StalkerCategoryRecord(id = "42", name = "Action")))@@ -747,12 +758,15 @@ class MovieRepositoryImplTest {fun `stalker movie category hydration preserves requested category when portal omits item category fields`() = runTest {val actionCategoryId = ("7/${ContentType.MOVIE.name}/42".hashCode().toLong() and 0x7fff_ffffL).coerceAtLeast(1L)+ whenever(+ stalkerRemoteIdentityResolver.resolveCategories(eq(7L), eq(ContentType.MOVIE), any())+ ).thenReturn(mapOf("42" to actionCategoryId))whenever(preferencesRepository.parentalControlLevel).thenReturn(flowOf(0))whenever(movieDao.getCountByCategory(7L, actionCategoryId)).thenReturn(flowOf(0), flowOf(1))whenever(movieDao.getByCategory(7L, actionCategoryId)).thenReturn(flowOf(emptyList()))whenever(movieCategoryHydrationDao.get(7L, actionCategoryId)).thenReturn(null)- whenever(providerDao.getById(7L)).thenReturn(- ProviderEntity(+ stubProvider(+ Provider(id = 7L,name = "Stalker",type = ProviderType.STALKER_PORTAL,@@ -813,8 +827,8 @@ class MovieRepositoryImplTest {rating = 8.5f))- whenever(providerDao.getById(7L)).thenReturn(- ProviderEntity(+ stubProvider(+ Provider(id = 7L,name = "Stalker",type = ProviderType.STALKER_PORTAL,@@ -1148,9 +1162,6 @@ class MovieRepositoryImplTest {movieDao = movieDao,categoryDao = categoryDao,providerDao = providerDao,- stalkerApiService = stalkerApiService,- xtreamApiService = xtreamApiService,- credentialCrypto = credentialCrypto,preferencesRepository = preferencesRepository,favoriteDao = favoriteDao,playbackHistoryDao = playbackHistoryDao,@@ -1162,13 +1173,36 @@ class MovieRepositoryImplTest {xtreamIndexJobDao = xtreamIndexJobDao,syncManager = syncManager,transactionRunner = transactionRunner,- stalkerRemoteIdentityResolver = mock(),stalkerRequestCoordinator = com.streamvault.data.remote.stalker.StalkerRequestCoordinator(),- stalkerPortalStateStore = mock()+ providerCapabilityResolver = providerCapabilityResolver,+ typedProviderClientFactory = typedProviderClientFactory)}- private fun stalkerProviderEntity() = ProviderEntity(+ private suspend fun stubProvider(provider: Provider) {+ whenever(providerDao.getById(provider.id)).thenReturn(provider.toEntity())+ val snapshot = provider.toProviderSnapshot()+ whenever(providerCapabilityResolver.snapshot(provider.id)).thenReturn(snapshot)+ if (provider.type == ProviderType.STALKER_PORTAL) {+ whenever(typedProviderClientFactory.stalker(snapshot)).thenReturn(+ CapabilityResolution.Available(+ StalkerProvider(+ providerId = provider.id,+ api = stalkerApiService,+ portalUrl = provider.serverUrl,+ macAddress = provider.stalkerMacAddress,+ deviceProfile = provider.stalkerDeviceProfile,+ timezone = provider.stalkerDeviceTimezone,+ locale = provider.stalkerDeviceLocale,+ identityResolver = stalkerRemoteIdentityResolver,+ portalStateStore = mock()+ )+ )+ )+ }+ }++ private fun stalkerProvider() = Provider(id = 7L,name = "Stalker",type = ProviderType.STALKER_PORTAL,diff --git a/data/src/test/java/com/streamvault/data/repository/ProviderRepositoryImplTest.kt b/data/src/test/java/com/streamvault/data/repository/ProviderRepositoryImplTest.ktindex 5c610f58..c0b76935 100644--- a/data/src/test/java/com/streamvault/data/repository/ProviderRepositoryImplTest.kt+++ b/data/src/test/java/com/streamvault/data/repository/ProviderRepositoryImplTest.kt@@ -12,21 +12,24 @@ import com.streamvault.data.local.dao.ProgramDaoimport com.streamvault.data.local.dao.ProgramReminderDaoimport com.streamvault.data.local.dao.ProviderDaoimport com.streamvault.data.local.dao.ProviderConfigRevisionDao+import com.streamvault.data.local.dao.ProviderSnapshotDaoimport com.streamvault.data.local.dao.ProviderDeletionCleanupDaoimport com.streamvault.data.local.dao.RecordingRunDaoimport com.streamvault.data.local.dao.SeriesDaoimport com.streamvault.data.local.dao.SeriesCategoryHydrationDaoimport com.streamvault.data.local.dao.StalkerIndexJobDao-import com.streamvault.data.local.entity.ProviderEntity+import com.streamvault.data.local.entity.*import com.streamvault.data.local.entity.ProviderConfigRevisionStateimport com.streamvault.data.local.entity.CategoryEntityimport com.streamvault.data.local.entity.StalkerIndexJobEntity+import com.streamvault.data.local.entity.ProviderDeletionCleanupEntityimport com.streamvault.data.manager.recording.RecordingAlarmSchedulerimport com.streamvault.data.manager.reminder.ProgramReminderAlarmSchedulerimport com.streamvault.data.preferences.PreferencesRepositoryimport com.streamvault.data.remote.jellyfin.JellyfinProviderimport com.streamvault.data.remote.stalker.StalkerApiServiceimport com.streamvault.data.remote.stalker.StalkerApiError+import com.streamvault.data.remote.stalker.StalkerDeviceProfileimport com.streamvault.data.remote.stalker.StalkerProviderimport com.streamvault.data.remote.stalker.StalkerProviderProfileimport com.streamvault.data.remote.stalker.StalkerSession@@ -35,6 +38,13 @@ import com.streamvault.data.remote.dto.XtreamAuthResponseimport com.streamvault.data.remote.dto.XtreamServerInfoimport com.streamvault.data.remote.dto.XtreamUserInfoimport com.streamvault.data.security.CredentialCrypto+import com.streamvault.data.provider.ProviderConfigurationCodec+import com.streamvault.data.provider.ProviderCapabilityResolver+import com.streamvault.data.provider.TypedProviderClientFactory+import com.streamvault.data.remote.stalker.StalkerPortalStateStore+import com.streamvault.data.remote.stalker.StalkerRemoteIdentityResolver+import com.streamvault.data.provider.toProviderSnapshot+import com.streamvault.data.mapper.toEntityimport com.streamvault.data.sync.SyncManagerimport com.streamvault.data.sync.ProviderWorkflowDispositionimport com.streamvault.data.sync.ProviderWorkflowOutcome@@ -46,6 +56,7 @@ import com.streamvault.domain.model.Resultimport com.streamvault.domain.model.SyncStateimport com.streamvault.domain.model.ProviderStatusimport com.streamvault.domain.model.ProviderType+import com.streamvault.domain.model.LegacyProvider as Providerimport com.streamvault.domain.model.ContentTypeimport com.streamvault.domain.model.StalkerIndexStateimport com.streamvault.domain.model.StalkerAuthMode@@ -53,6 +64,8 @@ import com.streamvault.domain.model.StalkerTransportGrantimport com.streamvault.domain.model.StalkerTransportModeimport com.streamvault.domain.model.StalkerTransportOriginimport com.streamvault.domain.model.ProviderXtreamLiveSyncMode+import com.streamvault.domain.model.GuideSourcePolicy+import com.streamvault.domain.model.XtreamConfigimport com.streamvault.domain.model.SyncMetadataimport com.streamvault.domain.repository.SyncMetadataRepositoryimport kotlinx.coroutines.runBlocking@@ -73,6 +86,7 @@ import org.mockito.kotlin.wheneverclass ProviderRepositoryImplTest {private val providerDao: ProviderDao = mock()+ private val providerSnapshotDao: ProviderSnapshotDao = mock()private val categoryDao: CategoryDao = mock()private val channelDao: ChannelDao = mock()private val movieDao: MovieDao = mock()@@ -96,6 +110,17 @@ class ProviderRepositoryImplTest {private val providerDeletionCleanupEnqueuer: ProviderDeletionCleanupEnqueuer = mock()private val providerConfigRevisionDao: ProviderConfigRevisionDao = mock()private val providerWorkflowRunner: ProviderWorkflowRunner = mock()+ private val providerCapabilityResolver: ProviderCapabilityResolver = mock()+ private val stalkerRemoteIdentityResolver: StalkerRemoteIdentityResolver = mock()+ private val stalkerPortalStateStore: StalkerPortalStateStore = mock()+ private val typedProviderClientFactory = TypedProviderClientFactory(+ xtreamApiService = xtreamApiService,+ stalkerApiService = stalkerApiService,+ jellyfinProvider = jellyfinProvider,+ preferencesRepository = preferencesRepository,+ stalkerRemoteIdentityResolver = stalkerRemoteIdentityResolver,+ stalkerPortalStateStore = stalkerPortalStateStore+ )private val gson = Gson()private val appContext: Context = mock()private val transactionRunner = object : DatabaseTransactionRunner {@@ -106,6 +131,7 @@ class ProviderRepositoryImplTest {transactionRunner: DatabaseTransactionRunner = this.transactionRunner) = ProviderRepositoryImpl(providerDao = providerDao,+ providerSnapshotDao = providerSnapshotDao,categoryDao = categoryDao,channelDao = channelDao,movieDao = movieDao,@@ -114,8 +140,8 @@ class ProviderRepositoryImplTest {recordingRunDao = recordingRunDao,programReminderDao = programReminderDao,stalkerApiService = stalkerApiService,- xtreamApiService = xtreamApiService,credentialCrypto = credentialCrypto,+ providerConfigurationCodec = ProviderConfigurationCodec(gson, credentialCrypto),preferencesRepository = preferencesRepository,syncManager = syncManager,syncMetadataRepository = syncMetadataRepository,@@ -123,9 +149,8 @@ class ProviderRepositoryImplTest {recordingAlarmScheduler = recordingAlarmScheduler,programReminderAlarmScheduler = programReminderAlarmScheduler,jellyfinProvider = jellyfinProvider,- stalkerRemoteIdentityResolver = mock(),stalkerIndexJobDao = stalkerIndexJobDao,- stalkerPortalStateStore = mock(),+ stalkerPortalStateStore = stalkerPortalStateStore,movieCategoryHydrationDao = movieCategoryHydrationDao,seriesCategoryHydrationDao = seriesCategoryHydrationDao,providerDeletionCleanupDao = providerDeletionCleanupDao,@@ -134,6 +159,8 @@ class ProviderRepositoryImplTest {gson = gson,providerWorkflowRunner = providerWorkflowRunner,providerWorkflowCommitFence = ProviderWorkflowCommitFence(),+ providerCapabilityResolver = providerCapabilityResolver,+ typedProviderClientFactory = typedProviderClientFactory,appContext = appContext)@@ -141,7 +168,12 @@ class ProviderRepositoryImplTest {init {whenever(preferencesRepository.xtreamBase64TextCompatibility).thenReturn(flowOf(false))+ whenever(credentialCrypto.encryptIfNeeded(any())).thenAnswer { invocation ->+ invocation.getArgument<String>(0)+ }runBlocking {+ whenever(providerSnapshotDao.getConfig(any())).thenReturn(null)+ whenever(providerSnapshotDao.commitConfiguration(any())).thenReturn(true)whenever(providerConfigRevisionDao.latestRevision(any())).thenReturn(0L)whenever(providerConfigRevisionDao.claimForSync(any(), any(), any())).thenReturn(1)whenever(providerConfigRevisionDao.getState(any(), any()))@@ -173,6 +205,52 @@ class ProviderRepositoryImplTest {}}+ @Test+ fun `redacted settings update preserves the stored typed credential`() = runTest {+ whenever(credentialCrypto.decryptIfNeeded(any())).thenAnswer { invocation ->+ invocation.getArgument<String>(0)+ }+ val codec = ProviderConfigurationCodec(gson, credentialCrypto)+ val storedConfiguration = XtreamConfig(+ serverUrl = "https://example.com",+ username = "user",+ password = "secret"+ )+ val encodedConfiguration = codec.encode(storedConfiguration)+ whenever(providerSnapshotDao.getConfig(7L)).thenReturn(+ ProviderConfigEntity(+ providerId = 7L,+ type = ProviderType.XTREAM_CODES,+ schemaVersion = storedConfiguration.schemaVersion,+ configurationGeneration = 3L,+ identityKey = codec.identityKey(storedConfiguration),+ encryptedConfigJson = encodedConfiguration,+ updatedAt = 1L+ )+ )+ whenever(providerSnapshotDao.commitConfiguration(any())).thenReturn(true)++ val publicProjection = Provider(+ id = 7L,+ name = "Xtream",+ type = ProviderType.XTREAM_CODES,+ serverUrl = storedConfiguration.serverUrl,+ username = storedConfiguration.username,+ password = "",+ guideSourcePolicy = GuideSourcePolicy.EXTERNAL_ONLY+ )++ val result = repository.updateProvider(publicProjection)++ assertThat(result.isSuccess).isTrue()+ val committed = argumentCaptor<ProviderConfigEntity>()+ verify(providerSnapshotDao).commitConfiguration(committed.capture())+ val decoded = codec.decode(committed.firstValue.type, committed.firstValue.encryptedConfigJson)+ as XtreamConfig+ assertThat(decoded.password).isEqualTo("secret")+ assertThat(decoded.guideSourcePolicy).isEqualTo(GuideSourcePolicy.EXTERNAL_ONLY)+ }+@Testfun `buildStalkerSearchIndexOnce resets terminal crawl progress before queueing fresh jobs`() = runTest {whenever(providerDao.getById(7L)).thenReturn(@@ -215,31 +293,34 @@ class ProviderRepositoryImplTest {@Testfun `save without verification requires an inconclusive readiness result and stays inactive`() = runTest {StalkerProvider.clearSharedAuthCacheForTests()- whenever(providerDao.getByUrlAndUser(any(), any(), any())).thenReturn(null)whenever(providerDao.insert(any())).thenReturn(41L)whenever(credentialCrypto.encryptIfNeeded(any())).thenAnswer { invocation ->invocation.arguments.first() as String}- whenever(stalkerApiService.authenticate(any())).thenReturn(- Result.error(- "Authentication succeeded, but Live TV readiness could not be verified.",- StalkerApiError.ReadinessInconclusive(- evidenceCode = "LIVE_BUDGET_EXHAUSTED",- cause = java.io.IOException("temporary Live timeout")+ doAnswer { invocation ->+ val profile = invocation.getArgument<StalkerDeviceProfile>(0)+ if (profile.requireCatalogValidation) {+ Result.error(+ "Authentication succeeded, but Live TV readiness could not be verified.",+ StalkerApiError.ReadinessInconclusive(+ evidenceCode = "LIVE_BUDGET_EXHAUSTED",+ cause = java.io.IOException("temporary Live timeout")+ ))- ),- Result.success(- StalkerSession(- loadUrl = "https://portal.example.com/server/load.php",- portalReferer = "https://portal.example.com/c/",- token = "token"- ) to StalkerProviderProfile(- accountName = "MAG",- statusLabel = "1",- authAccess = true+ } else {+ Result.success(+ StalkerSession(+ loadUrl = "https://portal.example.com/server/load.php",+ portalReferer = "https://portal.example.com/c/",+ token = "token"+ ) to StalkerProviderProfile(+ accountName = "MAG",+ statusLabel = "1",+ authAccess = true+ ))- )- )+ }+ }.whenever(stalkerApiService).authenticate(any())val result = repository.loginStalker(portalUrl = "https://portal.example.com/c/",@@ -282,16 +363,23 @@ class ProviderRepositoryImplTest {val result = repository.deleteProvider(7L)assertThat(result.isSuccess).isTrue()- val inOrder = inOrder(recordingAlarmScheduler, programReminderAlarmScheduler, programDao, providerDao, syncManager)- inOrder.verify(programDao).deleteByProvider(7L)- inOrder.verify(providerDao).delete(7L)- inOrder.verify(recordingAlarmScheduler).cancel("run-1")- inOrder.verify(recordingAlarmScheduler).cancel("run-2")- inOrder.verify(programReminderAlarmScheduler).cancel(11L)- inOrder.verify(programReminderAlarmScheduler).cancel(12L)- inOrder.verify(syncManager).onProviderDeleted(7L)- verify(recordingRunDao).getIdsByProvider(7L)- verify(programReminderDao).getIdsByProvider(7L)+ val cleanup = argumentCaptor<List<ProviderDeletionCleanupEntity>>()+ verify(providerDeletionCleanupDao).insertAll(cleanup.capture())+ assertThat(cleanup.firstValue.map { it.action }).containsExactly(+ ProviderDeletionCleanupWorker.RECORDING_ALARM,+ ProviderDeletionCleanupWorker.RECORDING_ALARM,+ ProviderDeletionCleanupWorker.REMINDER_ALARM,+ ProviderDeletionCleanupWorker.REMINDER_ALARM,+ ProviderDeletionCleanupWorker.SYNC_RUNTIME+ ).inOrder()+ verify(programDao).deleteByProvider(7L)+ verify(providerDao).delete(7L)+ verify(providerDeletionCleanupEnqueuer, org.mockito.kotlin.atLeastOnce()).enqueue()+ verify(recordingAlarmScheduler, never()).cancel(any())+ verify(programReminderAlarmScheduler, never()).cancel(any())+ verify(syncManager, never()).onProviderDeleted(any())+ verify(recordingRunDao, org.mockito.kotlin.atLeastOnce()).getIdsByProvider(7L)+ verify(programReminderDao, org.mockito.kotlin.atLeastOnce()).getIdsByProvider(7L)}@Test@@ -320,9 +408,9 @@ class ProviderRepositoryImplTest {Unit}.whenever(providerDao).delete(7L)doAnswer {- events += "sync:cleanup"+ events += "cleanup:enqueue"Unit- }.whenever(syncManager).onProviderDeleted(7L)+ }.whenever(providerDeletionCleanupEnqueuer).enqueue()val result = trackedRepository.deleteProvider(7L)@@ -332,7 +420,7 @@ class ProviderRepositoryImplTest {"programs:delete","provider:delete","transaction:end",- "sync:cleanup"+ "cleanup:enqueue").inOrder()}@@ -340,22 +428,26 @@ class ProviderRepositoryImplTest {fun `deleteProvider keeps success after post commit cleanup failure`() = runTest {whenever(recordingRunDao.getIdsByProvider(7L)).thenReturn(listOf("run-1"))whenever(programReminderDao.getIdsByProvider(7L)).thenReturn(listOf(11L))- doAnswer { throw IllegalStateException("sync cleanup failed") }- .whenever(syncManager).onProviderDeleted(7L)+ var cleanupAttempted = false+ doAnswer {+ cleanupAttempted = true+ throw IllegalStateException("cleanup enqueue failed")+ }+ .whenever(providerDeletionCleanupEnqueuer).enqueue()val result = repository.deleteProvider(7L)assertThat(result.isSuccess).isTrue()verify(programDao).deleteByProvider(7L)verify(providerDao).delete(7L)- verify(recordingAlarmScheduler).cancel("run-1")- verify(programReminderAlarmScheduler).cancel(11L)- verify(syncManager).onProviderDeleted(7L)+ assertThat(cleanupAttempted).isTrue()+ verify(recordingAlarmScheduler, never()).cancel(any())+ verify(programReminderAlarmScheduler, never()).cancel(any())}@Testfun `validateM3u marks provider active only after successful onboarding`() = runTest {- val existingProvider = ProviderEntity(+ val existingProvider = Provider(id = 5L,name = "Playlist",type = ProviderType.M3U,@@ -364,8 +456,9 @@ class ProviderRepositoryImplTest {status = ProviderStatus.UNKNOWN)- whenever(providerDao.getByUrlAndUser("https://example.com/list.m3u", "", "")).thenReturn(existingProvider)- whenever(providerDao.getById(5L)).thenReturn(existingProvider)+ whenever(providerSnapshotDao.findProviderIdByIdentityKey(any())).thenReturn(existingProvider.id)+ whenever(providerDao.getById(existingProvider.id)).thenReturn(existingProvider.toEntity())+ whenever(providerCapabilityResolver.snapshot(existingProvider.id)).thenReturn(existingProvider.toProviderSnapshot())whenever(syncManager.sync(5L, false, null)).thenReturn(Result.success(Unit))whenever(syncManager.currentSyncState(5L)).thenReturn(SyncState.Success(123L))@@ -386,7 +479,6 @@ class ProviderRepositoryImplTest {@Testfun `validateM3u returns saved provider sync error exception when initial sync fails after save`() = runTest {- whenever(providerDao.getByUrlAndUser("https://example.com/list.m3u", "", "")).thenReturn(null)whenever(credentialCrypto.encryptIfNeeded("")).thenReturn("")whenever(providerDao.insert(any())).thenReturn(9L)whenever(providerDao.getById(9L)).thenReturn(@@ -424,7 +516,6 @@ class ProviderRepositoryImplTest {@Testfun `validateM3u persists new provider inactive until onboarding succeeds`() = runTest {- whenever(providerDao.getByUrlAndUser("https://example.com/list.m3u", "", "")).thenReturn(null)whenever(credentialCrypto.encryptIfNeeded("")).thenReturn("")whenever(providerDao.insert(any())).thenReturn(9L)whenever(providerDao.getById(9L)).thenReturn(@@ -495,7 +586,7 @@ class ProviderRepositoryImplTest {@Testfun `validateM3u edit path rejects update when new URL already belongs to a different provider`() = runTest {- val editTarget = ProviderEntity(+ val editTarget = Provider(id = 5L,name = "Playlist A",type = ProviderType.M3U,@@ -512,7 +603,8 @@ class ProviderRepositoryImplTest {status = ProviderStatus.ACTIVE)// Provider 9 already owns the URL we want to move provider 5 to.- whenever(providerDao.getByUrlAndUser("https://example.com/b.m3u", "", "")).thenReturn(collision)+ whenever(providerSnapshotDao.findProviderIdByIdentityKey(any())).thenReturn(collision.id)+ whenever(providerDao.getById(collision.id)).thenReturn(collision)val result = repository.validateM3u(url = "https://example.com/b.m3u",@@ -531,7 +623,7 @@ class ProviderRepositoryImplTest {@Testfun `validateM3u edit path allows update when URL belongs to the same provider being edited`() = runTest {- val editTarget = ProviderEntity(+ val editTarget = Provider(id = 5L,name = "Playlist A",type = ProviderType.M3U,@@ -540,8 +632,9 @@ class ProviderRepositoryImplTest {status = ProviderStatus.ACTIVE)// The collision query returns the same provider being edited — that is not a conflict.- whenever(providerDao.getByUrlAndUser("https://example.com/a.m3u", "", "")).thenReturn(editTarget)- whenever(providerDao.getById(5L)).thenReturn(editTarget)+ whenever(providerSnapshotDao.findProviderIdByIdentityKey(any())).thenReturn(editTarget.id)+ whenever(providerDao.getById(editTarget.id)).thenReturn(editTarget.toEntity())+ whenever(providerCapabilityResolver.snapshot(editTarget.id)).thenReturn(editTarget.toProviderSnapshot())whenever(syncManager.sync(5L, false, null)).thenReturn(Result.success(Unit))whenever(syncManager.currentSyncState(5L)).thenReturn(SyncState.Success(123L))@@ -647,7 +740,6 @@ class ProviderRepositoryImplTest {@Testfun `loginXtream does not fail onboarding when provider has no live but committed vod`() = runTest {- whenever(providerDao.getByUrlAndUser("https://example.com", "user")).thenReturn(null)whenever(credentialCrypto.encryptIfNeeded("pass")).thenReturn("pass")whenever(providerDao.insert(any())).thenReturn(9L)whenever(syncManager.sync(eq(9L), eq(false), anyOrNull(), anyOrNull(), anyOrNull(), eq(true)))@@ -694,7 +786,6 @@ class ProviderRepositoryImplTest {@Testfun `loginXtream does not fail onboarding when provider has no live but committed vod categories`() = runTest {- whenever(providerDao.getByUrlAndUser("https://example.com", "user")).thenReturn(null)whenever(credentialCrypto.encryptIfNeeded("pass")).thenReturn("pass")whenever(providerDao.insert(any())).thenReturn(9L)whenever(syncManager.sync(eq(9L), eq(false), anyOrNull(), anyOrNull(), anyOrNull(), eq(true)))diff --git a/data/src/test/java/com/streamvault/data/repository/SeriesRepositoryImplTest.kt b/data/src/test/java/com/streamvault/data/repository/SeriesRepositoryImplTest.ktindex ba1eafb2..5780a4f0 100644--- a/data/src/test/java/com/streamvault/data/repository/SeriesRepositoryImplTest.kt+++ b/data/src/test/java/com/streamvault/data/repository/SeriesRepositoryImplTest.kt@@ -18,7 +18,12 @@ import com.streamvault.data.local.entity.SeriesBrowseEntityimport com.streamvault.data.local.entity.SeriesCategoryHydrationEntityimport com.streamvault.data.local.entity.ProviderEntityimport com.streamvault.data.local.entity.XtreamIndexJobEntity+import com.streamvault.data.mapper.toEntity+import com.streamvault.data.provider.toProviderSnapshotimport com.streamvault.data.preferences.PreferencesRepository+import com.streamvault.data.provider.ProviderCapabilityResolver+import com.streamvault.data.provider.TypedProviderClientFactory+import com.streamvault.data.provider.ProviderCapabilityTimeoutExceptionimport com.streamvault.data.remote.jellyfin.JellyfinProviderimport com.streamvault.data.remote.dto.XtreamSeasonimport com.streamvault.data.remote.dto.XtreamSeriesInfoResponse@@ -27,6 +32,8 @@ import com.streamvault.data.remote.stalker.StalkerEpisodeRecordimport com.streamvault.data.remote.stalker.StalkerItemRecordimport com.streamvault.data.remote.stalker.StalkerPagedItemsimport com.streamvault.data.remote.stalker.StalkerProviderProfile+import com.streamvault.data.remote.stalker.StalkerProvider+import com.streamvault.data.remote.stalker.StalkerRemoteIdentityResolverimport com.streamvault.data.remote.stalker.StalkerSeasonRecordimport com.streamvault.data.remote.stalker.StalkerSeriesDetailsimport com.streamvault.data.remote.stalker.StalkerSession@@ -46,19 +53,28 @@ import com.streamvault.domain.model.LibrarySortByimport com.streamvault.domain.model.PlaybackHistoryimport com.streamvault.domain.model.ProviderStatusimport com.streamvault.domain.model.ProviderType+import com.streamvault.domain.model.LegacyProvider as Providerimport com.streamvault.domain.model.Resultimport com.streamvault.domain.model.SeriesDetailPresentationHint+import com.streamvault.domain.model.Episode+import com.streamvault.domain.model.Season+import com.streamvault.domain.model.Seriesimport com.streamvault.domain.model.VodDuplicateConfidenceimport com.streamvault.domain.model.VodDuplicateHandlingModeimport com.streamvault.domain.model.VodSeriesVariantimport com.streamvault.domain.model.VodVariantObservationimport com.streamvault.domain.model.VodVariantPreferenceModeimport com.streamvault.domain.repository.PlaybackHistoryRepository+import com.streamvault.domain.provider.CapabilityResolution+import com.streamvault.domain.provider.ProviderCapabilitySet+import com.streamvault.domain.provider.ProviderContentReference+import com.streamvault.domain.provider.SeriesCatalogSourceimport kotlinx.coroutines.flow.firstimport kotlinx.coroutines.flow.flowimport kotlinx.coroutines.flow.flowOfimport kotlinx.coroutines.delayimport kotlinx.coroutines.test.runTest+import kotlinx.coroutines.runBlockingimport org.junit.Testimport org.mockito.kotlin.anyimport org.mockito.kotlin.anyOrNull@@ -90,19 +106,36 @@ class SeriesRepositoryImplTest {private val xtreamContentIndexDao: XtreamContentIndexDao = mock()private val xtreamIndexJobDao: XtreamIndexJobDao = mock()private val syncManager: SyncManager = mock()+ private val providerCapabilityResolver: ProviderCapabilityResolver = mock()+ private val typedProviderClientFactory: TypedProviderClientFactory = mock()+ private val stalkerRemoteIdentityResolver: StalkerRemoteIdentityResolver = mock()+ private val providerCapabilitySet: ProviderCapabilitySet = mock()+ private val seriesCatalogSource: SeriesCatalogSource = mock()private val credentialCrypto = object : CredentialCrypto {override fun encryptIfNeeded(value: String): String = valueoverride fun decryptIfNeeded(value: String): String = value}+ init {+ whenever(providerCapabilitySet.seriesCatalog()).thenReturn(CapabilityResolution.Available(seriesCatalogSource))+ runBlocking {+ whenever(providerCapabilityResolver.resolve(any())).thenReturn(+ CapabilityResolution.Available(providerCapabilitySet)+ )+ whenever(seriesCatalogSource.hydrateSeries(any(), any())).doSuspendableAnswer { invocation ->+ Result.success(invocation.getArgument<Series>(1))+ }+ }+ }+@Testfun `getSeriesByCategory does not hydrate xtream category when local cache is empty`() = runTest {whenever(preferencesRepository.parentalControlLevel).thenReturn(flowOf(0))whenever(preferencesRepository.xtreamBase64TextCompatibility).thenReturn(flowOf(false))whenever(seriesDao.getCountByCategory(7L, 77L)).thenReturn(flowOf(0))whenever(seriesDao.getByCategory(7L, 77L)).thenReturn(flowOf(emptyList()))- whenever(providerDao.getById(7L)).thenReturn(- ProviderEntity(+ stubProvider(+ Provider(id = 7L,name = "Xtream",type = ProviderType.XTREAM_CODES,@@ -135,8 +168,8 @@ class SeriesRepositoryImplTest {whenever(xtreamIndexJobDao.get(7L, ContentType.SERIES.name)).thenReturn(XtreamIndexJobEntity(providerId = 7L, section = ContentType.SERIES.name, state = "RUNNING"))- whenever(providerDao.getById(7L)).thenReturn(- ProviderEntity(+ stubProvider(+ Provider(id = 7L,name = "Stalker",type = ProviderType.STALKER_PORTAL,@@ -177,8 +210,8 @@ class SeriesRepositoryImplTest {detailHydratedAt = hydratedAt)whenever(seriesDao.getById(99L)).thenReturn(seriesEntity)- whenever(providerDao.getById(7L)).thenReturn(- ProviderEntity(+ stubProvider(+ Provider(id = 7L,name = "Xtream",type = ProviderType.XTREAM_CODES,@@ -221,8 +254,8 @@ class SeriesRepositoryImplTest {)whenever(seriesDao.getById(99L)).thenReturn(rawSeries)whenever(seriesDao.getByProviderAndTmdbIdSync(7L, 777L)).thenReturn(listOf(rawSeries, alternateSeries))- whenever(providerDao.getById(7L)).thenReturn(- ProviderEntity(+ stubProvider(+ Provider(id = 7L,name = "Xtream",type = ProviderType.XTREAM_CODES,@@ -261,8 +294,8 @@ class SeriesRepositoryImplTest {detailHydratedAt = hydratedAt)whenever(seriesDao.getById(99L)).thenReturn(rawSeries)- whenever(providerDao.getById(7L)).thenReturn(- ProviderEntity(+ stubProvider(+ Provider(id = 7L,name = "Xtream",type = ProviderType.XTREAM_CODES,@@ -330,8 +363,8 @@ class SeriesRepositoryImplTest {whenever(preferencesRepository.parentalControlLevel).thenReturn(flowOf(0))whenever(seriesDao.getCountByCategory(7L, 77L)).thenReturn(flowOf(0))whenever(seriesDao.getByCategory(7L, 77L)).thenReturn(flowOf(emptyList()))- whenever(providerDao.getById(7L)).thenReturn(- ProviderEntity(+ stubProvider(+ Provider(id = 7L,name = "Stalker",type = ProviderType.STALKER_PORTAL,@@ -391,8 +424,8 @@ class SeriesRepositoryImplTest {whenever(categoryDao.getByProviderAndType(7L, ContentType.SERIES.name)).thenReturn(flowOf(listOf(com.streamvault.data.local.entity.CategoryEntity(providerId = 7L, categoryId = 77L, name = "Drama", type = ContentType.SERIES))))- whenever(providerDao.getById(7L)).thenReturn(- ProviderEntity(+ stubProvider(+ Provider(id = 7L,name = "Stalker",type = ProviderType.STALKER_PORTAL,@@ -440,7 +473,7 @@ class SeriesRepositoryImplTest {whenever(seriesDao.getCountByCategory(7L, 77L)).thenReturn(flowOf(0), flowOf(14), flowOf(28), flowOf(42))whenever(seriesDao.getByCategoryPage(7L, 77L, 60, 0)).thenReturn(flowOf(emptyList()))whenever(seriesCategoryHydrationDao.get(7L, 77L)).thenReturn(null)- whenever(providerDao.getById(7L)).thenReturn(stalkerProviderEntity())+ stubProvider(stalkerProvider())whenever(stalkerApiService.authenticate(any())).thenReturn(stalkerSessionResult())whenever(stalkerApiService.getSeriesCategories(any(), any())).thenReturn(Result.success(listOf(StalkerCategoryRecord(id = "77", name = "Drama")))@@ -477,7 +510,7 @@ class SeriesRepositoryImplTest {pageSize = 14))- whenever(providerDao.getById(7L)).thenReturn(stalkerProviderEntity())+ stubProvider(stalkerProvider())whenever(stalkerApiService.authenticate(any())).thenReturn(stalkerSessionResult())whenever(stalkerApiService.getSeriesCategories(any(), any())).thenReturn(Result.success(listOf(StalkerCategoryRecord(id = "77", name = "Drama")))@@ -608,8 +641,8 @@ class SeriesRepositoryImplTest {whenever(seriesDao.getCountByCategory(7L, 77L)).thenReturn(flowOf(0))whenever(seriesDao.getByCategory(7L, 77L)).thenReturn(flowOf(emptyList()))whenever(seriesCategoryHydrationDao.get(7L, 77L)).thenReturn(null)- whenever(providerDao.getById(7L)).thenReturn(- ProviderEntity(+ stubProvider(+ Provider(id = 7L,name = "Xtream",type = ProviderType.XTREAM_CODES,@@ -641,8 +674,8 @@ class SeriesRepositoryImplTest {)whenever(seriesDao.getById(301L)).thenReturn(null)whenever(seriesDao.getBySeriesId(7L, 301L)).thenReturn(seriesEntity)- whenever(providerDao.getById(7L)).thenReturn(- ProviderEntity(+ stubProvider(+ Provider(id = 7L,name = "Playlist",type = ProviderType.M3U,@@ -676,8 +709,8 @@ class SeriesRepositoryImplTest {)whenever(seriesDao.getById(301L)).thenReturn(null)whenever(seriesDao.getBySeriesId(7L, 301L)).thenReturn(seriesEntity)- whenever(providerDao.getById(7L)).thenReturn(- ProviderEntity(+ stubProvider(+ Provider(id = 7L,name = "Xtream",type = ProviderType.XTREAM_CODES,@@ -713,8 +746,8 @@ class SeriesRepositoryImplTest {)whenever(seriesDao.getById(301L)).thenReturn(null)whenever(seriesDao.getBySeriesId(7L, 301L)).thenReturn(seriesEntity)- whenever(providerDao.getById(7L)).thenReturn(- ProviderEntity(+ stubProvider(+ Provider(id = 7L,name = "Xtream",type = ProviderType.XTREAM_CODES,@@ -725,10 +758,12 @@ class SeriesRepositoryImplTest {))whenever(episodeDao.getBySeriesSync(15L)).thenReturn(emptyList())- whenever(xtreamApiService.getSeriesInfo(any(), any())).doSuspendableAnswer {- delay(30_000L)- XtreamSeriesInfoResponse()- }+ whenever(seriesCatalogSource.hydrateSeries(any(), any())).thenReturn(+ Result.error(+ "Xtream series detail hydration timed out",+ ProviderCapabilityTimeoutException("Xtream series detail hydration timed out")+ )+ )val result = createRepository().getSeriesDetails(7L, 301L)@@ -756,8 +791,8 @@ class SeriesRepositoryImplTest {)whenever(seriesDao.getById(15L)).thenReturn(seriesEntity)whenever(seriesDao.getById(15L)).thenReturn(seriesEntity)- whenever(providerDao.getById(7L)).thenReturn(- ProviderEntity(+ stubProvider(+ Provider(id = 7L,name = "Xtream",type = ProviderType.XTREAM_CODES,@@ -813,8 +848,8 @@ class SeriesRepositoryImplTest {providerId = 7L)whenever(seriesDao.getById(15L)).thenReturn(seriesEntity)- whenever(providerDao.getById(7L)).thenReturn(- ProviderEntity(+ stubProvider(+ Provider(id = 7L,name = "Stalker",type = ProviderType.STALKER_PORTAL,@@ -823,32 +858,29 @@ class SeriesRepositoryImplTest {status = ProviderStatus.ACTIVE))- whenever(stalkerApiService.authenticate(any())).thenReturn(- Result.success(- StalkerSession(- loadUrl = "http://example.com/stalker_portal/server/load.php",- portalReferer = "http://example.com/stalker_portal/c/",- token = "token"- ) to StalkerProviderProfile(accountName = "Stalker")- )- )- whenever(stalkerApiService.getSeriesDetails(any(), any(), eq("55000:55000"))).thenReturn(+ whenever(seriesCatalogSource.hydrateSeries(any(), any())).thenReturn(Result.success(- StalkerSeriesDetails(- series = StalkerItemRecord(id = "55000:55000", name = "", isSeries = true),+ Series(+ id = 15L,+ name = "",+ providerId = 7L,+ seriesId = 256103980L,+ providerSeriesId = "55000:55000",seasons = listOf(- StalkerSeasonRecord(+ Season(seasonNumber = 1,- name = "Season 1",episodes = listOf(- StalkerEpisodeRecord(- id = "55000:1:1",+ Episode(+ id = 1L,title = "Episode 1",episodeNumber = 1,seasonNumber = 1,- cmd = "cmd"+ streamUrl = "cmd",+ seriesId = 15L,+ providerId = 7L)- )+ ),+ episodeCount = 1)))@@ -863,7 +895,9 @@ class SeriesRepositoryImplTest {assertThat(result).isInstanceOf(com.streamvault.domain.model.Result.Success::class.java)val series = (result as com.streamvault.domain.model.Result.Success).dataassertThat(series.name).isEqualTo("Stored Series")- verify(stalkerApiService).getSeriesDetails(any(), any(), eq("55000:55000"))+ val referenceCaptor = argumentCaptor<ProviderContentReference>()+ verify(seriesCatalogSource).hydrateSeries(referenceCaptor.capture(), any())+ assertThat(referenceCaptor.firstValue.remoteId).isEqualTo("55000:55000")verifyNoInteractions(xtreamApiService)verify(xtreamContentIndexDao, never()).markDetailHydrated(any(), any(), any(), any(), anyOrNull(), any())}@@ -1072,23 +1106,42 @@ class SeriesRepositoryImplTest {playbackHistoryDao = playbackHistoryDao,playbackHistoryRepository = playbackHistoryRepository,providerDao = providerDao,- stalkerApiService = stalkerApiService,- xtreamApiService = xtreamApiService,- credentialCrypto = credentialCrypto,preferencesRepository = preferencesRepository,xtreamStreamUrlResolver = xtreamStreamUrlResolver,xtreamContentIndexDao = xtreamContentIndexDao,xtreamIndexJobDao = xtreamIndexJobDao,syncManager = syncManager,seriesCategoryHydrationDao = seriesCategoryHydrationDao,- jellyfinProvider = jellyfinProvider,- stalkerRemoteIdentityResolver = mock(),stalkerRequestCoordinator = com.streamvault.data.remote.stalker.StalkerRequestCoordinator(),- stalkerPortalStateStore = mock()+ providerCapabilityResolver = providerCapabilityResolver,+ typedProviderClientFactory = typedProviderClientFactory)}- private fun stalkerProviderEntity() = ProviderEntity(+ private suspend fun stubProvider(provider: Provider) {+ whenever(providerDao.getById(provider.id)).thenReturn(provider.toEntity())+ val snapshot = provider.toProviderSnapshot()+ whenever(providerCapabilityResolver.snapshot(provider.id)).thenReturn(snapshot)+ if (provider.type == ProviderType.STALKER_PORTAL) {+ whenever(typedProviderClientFactory.stalker(snapshot)).thenReturn(+ CapabilityResolution.Available(+ StalkerProvider(+ providerId = provider.id,+ api = stalkerApiService,+ portalUrl = provider.serverUrl,+ macAddress = provider.stalkerMacAddress,+ deviceProfile = provider.stalkerDeviceProfile,+ timezone = provider.stalkerDeviceTimezone,+ locale = provider.stalkerDeviceLocale,+ identityResolver = stalkerRemoteIdentityResolver,+ portalStateStore = mock()+ )+ )+ )+ }+ }++ private fun stalkerProvider() = Provider(id = 7L,name = "Stalker",type = ProviderType.STALKER_PORTAL,diff --git a/data/src/test/java/com/streamvault/data/sync/ProviderSyncStateReaderImplTest.kt b/data/src/test/java/com/streamvault/data/sync/ProviderSyncStateReaderImplTest.ktindex 4d71bdad..988cba10 100644--- a/data/src/test/java/com/streamvault/data/sync/ProviderSyncStateReaderImplTest.kt+++ b/data/src/test/java/com/streamvault/data/sync/ProviderSyncStateReaderImplTest.kt@@ -7,6 +7,7 @@ import com.streamvault.data.local.entity.ProviderWorkflowEntityimport com.streamvault.data.local.entity.ProviderWorkflowPhaseimport com.streamvault.data.local.entity.ProviderWorkflowReasonimport com.streamvault.data.local.entity.ProviderWorkflowState+import com.streamvault.data.local.entity.XtreamIndexJobEntityimport kotlinx.coroutines.flow.firstimport kotlinx.coroutines.flow.flowOfimport kotlinx.coroutines.test.runTest@@ -44,7 +45,17 @@ class ProviderSyncStateReaderImplTest {@Testfun `terminal durable workflow does not report background indexing`() = runTest {- whenever(xtreamIndexJobDao.observeForProvider(PROVIDER_ID)).thenReturn(flowOf(emptyList()))+ whenever(xtreamIndexJobDao.observeForProvider(PROVIDER_ID)).thenReturn(+ flowOf(+ listOf(+ XtreamIndexJobEntity(+ providerId = PROVIDER_ID,+ section = "MOVIE",+ state = "RUNNING"+ )+ )+ )+ )whenever(workflowDao.observeWorkflow(PROVIDER_ID)).thenReturn(flowOf(ProviderWorkflowEntity(@@ -64,6 +75,26 @@ class ProviderSyncStateReaderImplTest {assertThat(reader.observeBackgroundIndexingActive(PROVIDER_ID).first()).isFalse()}+ @Test+ fun `legacy indexing remains a fallback before durable workflow exists`() = runTest {+ whenever(xtreamIndexJobDao.observeForProvider(PROVIDER_ID)).thenReturn(+ flowOf(+ listOf(+ XtreamIndexJobEntity(+ providerId = PROVIDER_ID,+ section = "SERIES",+ state = "RUNNING"+ )+ )+ )+ )+ whenever(workflowDao.observeWorkflow(PROVIDER_ID)).thenReturn(flowOf(null))+ whenever(workflowDao.observeActivePhases(PROVIDER_ID)).thenReturn(flowOf(emptyList()))+ val reader = ProviderSyncStateReaderImpl(syncManager, xtreamIndexJobDao, workflowDao)++ assertThat(reader.observeBackgroundIndexingActive(PROVIDER_ID).first()).isTrue()+ }+private companion object {const val PROVIDER_ID = 7L}diff --git a/data/src/test/java/com/streamvault/data/sync/ProviderSyncWorkerTest.kt b/data/src/test/java/com/streamvault/data/sync/ProviderSyncWorkerTest.ktindex d0ca79af..9d6ea6a2 100644--- a/data/src/test/java/com/streamvault/data/sync/ProviderSyncWorkerTest.kt+++ b/data/src/test/java/com/streamvault/data/sync/ProviderSyncWorkerTest.kt@@ -6,6 +6,8 @@ import com.streamvault.data.local.dao.ChannelDaoimport com.streamvault.data.local.dao.ProviderDaoimport com.streamvault.data.local.dao.XtreamLiveOnboardingDaoimport com.streamvault.data.local.entity.CategoryEntity+import com.streamvault.data.local.entity.ProviderConfigRevisionEntity+import com.streamvault.data.local.entity.ProviderConfigRevisionStateimport com.streamvault.data.local.entity.ProviderEntityimport com.streamvault.data.local.entity.XtreamIndexJobEntityimport com.streamvault.data.local.entity.XtreamLiveOnboardingStateEntity@@ -41,6 +43,34 @@ class ProviderSyncWorkerTest {}}+ @Test+ fun `stale config work is a no-op after revision supersession or provider deletion`() {+ val base = ProviderConfigRevisionEntity(+ providerId = 7L,+ revision = 1L,+ configJson = "{}",+ state = ProviderConfigRevisionState.SYNCING,+ createdAt = 1L,+ updatedAt = 1L+ )++ assertThat(isObsoleteProviderConfigRevision(null, providerExists = false)).isTrue()+ assertThat(isObsoleteProviderConfigRevision(base, providerExists = false)).isTrue()+ assertThat(+ isObsoleteProviderConfigRevision(+ base.copy(state = ProviderConfigRevisionState.SUPERSEDED),+ providerExists = true+ )+ ).isTrue()+ assertThat(+ isObsoleteProviderConfigRevision(+ base.copy(state = ProviderConfigRevisionState.COMMITTED),+ providerExists = true+ )+ ).isTrue()+ assertThat(isObsoleteProviderConfigRevision(base, providerExists = true)).isFalse()+ }+@Testfun `future running index job timestamp is not fresh`() {assertThat(diff --git a/data/src/test/java/com/streamvault/data/sync/ProviderWorkflowCommitFenceTest.kt b/data/src/test/java/com/streamvault/data/sync/ProviderWorkflowCommitFenceTest.ktindex e9f29225..40f91e07 100644--- a/data/src/test/java/com/streamvault/data/sync/ProviderWorkflowCommitFenceTest.kt+++ b/data/src/test/java/com/streamvault/data/sync/ProviderWorkflowCommitFenceTest.kt@@ -11,6 +11,7 @@ import com.streamvault.data.local.entity.ProviderWorkflowReasonimport com.streamvault.domain.model.ProviderTypeimport kotlinx.coroutines.test.runTestimport kotlinx.coroutines.withContext+import kotlinx.coroutines.CancellationExceptionimport org.junit.Afterimport org.junit.Beforeimport org.junit.Test@@ -101,6 +102,41 @@ class ProviderWorkflowCommitFenceTest {.isEqualTo("Fresh")}+ @Test+ fun `failed candidate promotion rolls back replacement and retains committed catalog`() = runTest {+ insertProvider()+ database.channelDao().insertAll(listOf(channel(name = "Committed", streamUrl = "old")))+ val workflowDao = database.providerWorkflowDao()+ val ticket = workflowDao.request(+ PROVIDER_ID,+ ProviderWorkflowPhase.PREPARE,+ ProviderWorkflowReason.CONFIG_CHANGE,+ now = 100L,+ supersede = true,+ priority = 100,+ force = true+ )+ val lease = checkNotNull(+ workflowDao.claim(ticket, "candidate-owner", 101L, 1_000L, staleHeartbeatBefore = 0L)+ )++ val error = runCatching {+ withContext(ProviderWorkflowExecutionContext(lease)) {+ store().replaceLiveCatalog(+ providerId = PROVIDER_ID,+ categories = null,+ channels = listOf(channel(name = "Candidate", streamUrl = "new")),+ afterCatalogApply = { throw CancellationException("candidate cancelled") }+ )+ }+ }.exceptionOrNull()++ assertThat(error).isInstanceOf(CancellationException::class.java)+ val retained = database.channelDao().getByProviderSync(PROVIDER_ID).single()+ assertThat(retained.name).isEqualTo("Committed")+ assertThat(retained.streamUrl).isEqualTo("old")+ }+private fun store() = SyncCatalogStore(channelDao = database.channelDao(),movieDao = database.movieDao(),diff --git a/data/src/test/java/com/streamvault/data/sync/ProviderWorkflowRunnerTest.kt b/data/src/test/java/com/streamvault/data/sync/ProviderWorkflowRunnerTest.ktindex 50f14a29..9f2f8498 100644--- a/data/src/test/java/com/streamvault/data/sync/ProviderWorkflowRunnerTest.kt+++ b/data/src/test/java/com/streamvault/data/sync/ProviderWorkflowRunnerTest.kt@@ -2,6 +2,7 @@ package com.streamvault.data.syncimport androidx.room.Roomimport com.google.common.truth.Truth.assertThat+import com.google.common.truth.Truth.assertWithMessageimport com.streamvault.data.local.StreamVaultDatabaseimport com.streamvault.data.local.entity.ProviderEntityimport com.streamvault.data.local.entity.ProviderWorkflowPhase@@ -15,7 +16,10 @@ import com.streamvault.data.remote.jellyfin.JellyfinResponseTooLargeExceptionimport com.streamvault.domain.model.ProviderTypeimport java.io.IOExceptionimport kotlinx.coroutines.CompletableDeferred+import kotlinx.coroutines.CancellationExceptionimport kotlinx.coroutines.async+import kotlinx.coroutines.cancelAndJoin+import kotlinx.coroutines.launchimport kotlinx.coroutines.test.runTestimport org.junit.Afterimport org.junit.Before@@ -161,10 +165,96 @@ class ProviderWorkflowRunnerTest {assertThat(first.await()).isEqualTo(ProviderWorkflowDisposition.SUCCEEDED)}- private suspend fun insertProvider() {+ @Test+ fun `cancellation is rethrown without publishing workflow failure`() = runTest {+ insertProvider()+ val entered = CompletableDeferred<Unit>()+ var cancellation: CancellationException? = null+ val worker = launch {+ try {+ runner.execute(+ providerId = PROVIDER_ID,+ phase = ProviderWorkflowPhase.EPG,+ reason = ProviderWorkflowReason.PERIODIC+ ) {+ entered.complete(Unit)+ kotlinx.coroutines.awaitCancellation()+ }+ } catch (error: CancellationException) {+ cancellation = error+ throw error+ }+ }++ entered.await()+ worker.cancelAndJoin()++ assertThat(cancellation).isNotNull()+ val workflow = database.providerWorkflowDao().getWorkflow(PROVIDER_ID)!!+ assertThat(workflow.state).isEqualTo(ProviderWorkflowState.RUNNING)+ assertThat(workflow.lastErrorCode).isNull()+ assertThat(workflow.lastErrorMessage).isNull()+ assertThat(+ database.providerWorkflowDao()+ .getPhases(PROVIDER_ID, workflow.generation)+ .single()+ .state+ ).isEqualTo(ProviderWorkflowPhaseState.RUNNING)+ }++ @Test+ fun `provider worker cancellation matrix publishes no retry or error for any provider phase`() = runTest {+ val workerPhases = listOf(+ "background EPG" to ProviderWorkflowPhase.EPG,+ "provider catalog" to ProviderWorkflowPhase.PRIMARY_CATALOG,+ "Stalker index" to ProviderWorkflowPhase.CONTENT_INDEX,+ "Xtream index" to ProviderWorkflowPhase.MOVIE_INDEX+ )++ workerPhases.forEachIndexed { index, (owner, phase) ->+ val providerId = PROVIDER_ID + index + 1+ insertProvider(providerId)+ val entered = CompletableDeferred<Unit>()+ var cancellation: CancellationException? = null+ val worker = launch {+ try {+ runner.execute(+ providerId = providerId,+ phase = phase,+ reason = ProviderWorkflowReason.PERIODIC+ ) {+ entered.complete(Unit)+ kotlinx.coroutines.awaitCancellation()+ }+ } catch (error: CancellationException) {+ cancellation = error+ throw error+ }+ }++ entered.await()+ worker.cancelAndJoin()++ assertThat(cancellation).isNotNull()+ val workflow = database.providerWorkflowDao().getWorkflow(providerId)!!+ assertWithMessage("$owner cancellation must leave the lease running")+ .that(workflow.state)+ .isEqualTo(ProviderWorkflowState.RUNNING)+ assertThat(workflow.lastErrorCode).isNull()+ assertThat(workflow.lastErrorMessage).isNull()+ assertThat(+ database.providerWorkflowDao()+ .getPhases(providerId, workflow.generation)+ .single()+ .state+ ).isEqualTo(ProviderWorkflowPhaseState.RUNNING)+ }+ }++ private suspend fun insertProvider(providerId: Long = PROVIDER_ID) {database.providerDao().insert(ProviderEntity(- id = PROVIDER_ID,+ id = providerId,name = "Provider",type = ProviderType.M3U,serverUrl = "https://example.com"diff --git a/data/src/test/java/com/streamvault/data/sync/SyncManagerM3uImporterTest.kt b/data/src/test/java/com/streamvault/data/sync/SyncManagerM3uImporterTest.ktindex d10e5949..5483f3ed 100644--- a/data/src/test/java/com/streamvault/data/sync/SyncManagerM3uImporterTest.kt+++ b/data/src/test/java/com/streamvault/data/sync/SyncManagerM3uImporterTest.kt@@ -2,7 +2,7 @@ package com.streamvault.data.syncimport com.google.common.truth.Truth.assertThatimport com.streamvault.data.parser.M3uParser-import com.streamvault.domain.model.Provider+import com.streamvault.domain.model.LegacyProvider as Providerimport com.streamvault.domain.model.ProviderTypeimport kotlinx.coroutines.CancellationExceptionimport kotlinx.coroutines.test.runTestdiff --git a/data/src/test/java/com/streamvault/data/sync/SyncManagerTest.kt b/data/src/test/java/com/streamvault/data/sync/SyncManagerTest.ktindex 507e32f5..726bc635 100644--- a/data/src/test/java/com/streamvault/data/sync/SyncManagerTest.kt+++ b/data/src/test/java/com/streamvault/data/sync/SyncManagerTest.kt@@ -18,6 +18,7 @@ import com.streamvault.data.local.dao.ProviderDaoimport com.streamvault.data.local.dao.SeriesCategoryHydrationDaoimport com.streamvault.data.local.dao.SeriesDaoimport com.streamvault.data.local.dao.StalkerIndexJobDao+import com.streamvault.data.local.dao.StalkerRemoteIdentityDaoimport com.streamvault.data.local.dao.TmdbIdentityDaoimport com.streamvault.data.local.dao.VodCategoryHydrationDaoimport com.streamvault.data.local.dao.VodCatalogEntryDao@@ -30,9 +31,14 @@ import com.streamvault.data.local.entity.ChannelGuideSyncEntityimport com.streamvault.data.local.entity.MovieCategoryHydrationEntityimport com.streamvault.data.local.entity.MovieEntityimport com.streamvault.data.local.entity.ProviderEntity+import com.streamvault.data.mapper.toEntity+import com.streamvault.data.provider.toProviderSnapshot+import com.streamvault.data.provider.TypedProviderClientFactory+import com.streamvault.data.remote.xtream.OkHttpXtreamApiServiceimport com.streamvault.data.local.entity.SeriesCategoryHydrationEntityimport com.streamvault.data.local.entity.StalkerIndexJobEntityimport com.streamvault.data.local.entity.StalkerPortalStateEntity+import com.streamvault.data.local.entity.StalkerRemoteIdentityEntityimport com.streamvault.data.local.entity.XtreamIndexJobEntityimport com.streamvault.data.local.entity.XtreamLiveOnboardingStateEntityimport com.streamvault.data.parser.M3uParser@@ -42,6 +48,10 @@ import com.streamvault.domain.model.Resultimport com.streamvault.domain.model.ProviderEpgSyncModeimport com.streamvault.domain.model.ProviderXtreamLiveSyncModeimport com.streamvault.domain.model.ProviderType+import com.streamvault.domain.model.LegacyProvider as Provider+import com.streamvault.domain.model.CatalogLayout+import com.streamvault.domain.model.StalkerPortalLearning+import com.streamvault.domain.repository.ProviderSnapshotRepositoryimport com.streamvault.domain.model.StalkerIndexStateimport com.streamvault.domain.model.StalkerTransportModeimport com.streamvault.domain.model.SyncMetadata@@ -52,6 +62,8 @@ import com.streamvault.data.remote.stalker.StalkerItemRecordimport com.streamvault.data.remote.stalker.StalkerPagedItemsimport com.streamvault.data.remote.stalker.StalkerProgramRecordimport com.streamvault.data.remote.stalker.StalkerProviderProfile+import com.streamvault.data.remote.stalker.StalkerRemoteIdentityResolver+import com.streamvault.data.remote.stalker.stalkerStableHashIdimport com.streamvault.data.remote.stalker.StalkerSessionimport com.streamvault.data.remote.stalker.StalkerApiServiceimport com.streamvault.data.remote.stalker.StalkerAdvancedOptions@@ -95,7 +107,6 @@ import org.mockito.kotlin.mockimport org.mockito.kotlin.resetimport org.mockito.kotlin.verifyimport java.io.IOException-import java.util.Localeimport java.util.zip.GZIPOutputStream/**@@ -116,8 +127,9 @@ class SyncManagerTest {// ── In-memory fake ──────────────────────────────────────────────private class FakeProviderDao(- private val provider: ProviderEntity? = sampleProvider()+ provider: Provider? = sampleProvider()) : ProviderDao() {+ private val provider = provider?.toEntity()override suspend fun getById(id: Long): ProviderEntity? = provideroverride fun getByIdSync(id: Long): ProviderEntity? = provider?.takeIf { it.id == id }override suspend fun getByIds(ids: List<Long>): List<ProviderEntity> =@@ -136,22 +148,40 @@ class SyncManagerTest {override suspend fun deactivateAll() = Unitoverride suspend fun activate(id: Long) = Unitoverride suspend fun setActive(id: Long) = Unit- override suspend fun getByUrlAndUser(- serverUrl: String,- username: String,- stalkerMacAddress: String- ): ProviderEntity? = null- override 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 FakeStalkerRemoteIdentityDao : StalkerRemoteIdentityDao {+ private val rows = mutableListOf<StalkerRemoteIdentityEntity>()++ override suspend fun getByRawId(providerId: Long, contentType: String, rawId: String) =+ rows.firstOrNull { row ->+ row.providerId == providerId && row.contentType.name == contentType && row.rawId == rawId+ }++ override suspend fun getBySurrogateId(providerId: Long, contentType: String, surrogateId: Long) =+ rows.firstOrNull { row ->+ row.providerId == providerId && row.contentType.name == contentType && row.surrogateId == surrogateId+ }++ override suspend fun maxAllocatedSurrogate(providerId: Long, contentType: String, floor: Long): Long? =+ rows.asSequence()+ .filter { row ->+ row.providerId == providerId && row.contentType.name == contentType && row.surrogateId >= floor+ }+ .maxOfOrNull(StalkerRemoteIdentityEntity::surrogateId)++ override suspend fun insert(entity: StalkerRemoteIdentityEntity) {+ check(rows.none { row ->+ row.providerId == entity.providerId &&+ row.contentType == entity.contentType &&+ (row.rawId == entity.rawId || row.surrogateId == entity.surrogateId)+ })+ rows += entity+ }}companion object {- fun sampleProvider(type: ProviderType = ProviderType.XTREAM_CODES) = ProviderEntity(+ fun sampleProvider(type: ProviderType = ProviderType.XTREAM_CODES) = Provider(id = 1L, name = "Test", type = type,serverUrl = "https://test.example.com:8080",username = "demo", password = "demo",@@ -159,8 +189,7 @@ class SyncManagerTest {)fun stalkerSyntheticCategoryId(providerId: Long, type: ContentType, seed: String): Long {- val normalized = "$providerId/${type.name}/${seed.trim().lowercase(Locale.ROOT)}"- return (normalized.hashCode().toLong() and 0x7fff_ffffL).coerceAtLeast(1L)+ return stalkerStableHashId(providerId, type, seed)}}@@ -370,17 +399,28 @@ class SyncManagerTest {private fun buildManager(providerType: ProviderType = ProviderType.XTREAM_CODES,providerPresent: Boolean = true,- providerEntity: ProviderEntity? = null,+ providerEntity: Provider? = null,readinessTracker: StalkerReadinessTracker = StalkerReadinessTracker(),portalStateStore: com.streamvault.data.remote.stalker.StalkerPortalStateStore = mock()- ): SyncManager = SyncManager(+ ): SyncManager {+ val configuredProvider = if (providerPresent) providerEntity ?: sampleProvider(providerType) else null+ val stalkerRemoteIdentityResolver = StalkerRemoteIdentityResolver(+ dao = FakeStalkerRemoteIdentityDao(),+ transactionRunner = transactionRunner,+ categoryDao = categoryDao+ )+ val typedProviderClientFactory = TypedProviderClientFactory(+ xtreamApiService = OkHttpXtreamApiService(xtreamBackend.okHttpClient(), xtreamJson),+ stalkerApiService = stalkerApiService,+ jellyfinProvider = jellyfinProvider,+ preferencesRepository = preferencesRepo,+ stalkerRemoteIdentityResolver = stalkerRemoteIdentityResolver,+ stalkerPortalStateStore = portalStateStore+ )+ return SyncManager(applicationContext = applicationContext,providerDao = FakeProviderDao(- if (providerPresent) {- providerEntity ?: sampleProvider(providerType)- } else {- null- }+ configuredProvider),channelDao = channelDao,movieDao = movieDao,@@ -471,7 +511,6 @@ class SyncManagerTest {override suspend fun deleteByProvider(providerId: Long): Int = 0},xtreamLiveOnboardingDao = xtreamLiveOnboardingDao,- stalkerApiService = stalkerApiService,episodeDao = episodeDao,jellyfinProvider = jellyfinProvider,xtreamJson = xtreamJson,@@ -484,12 +523,24 @@ class SyncManagerTest {transactionRunner = transactionRunner,preferencesRepository = preferencesRepo,syncProgressBus = SyncProgressBus(),- stalkerRemoteIdentityResolver = mock(),stalkerRequestCoordinator = com.streamvault.data.remote.stalker.StalkerRequestCoordinator(),stalkerPortalStateStore = portalStateStore,stalkerReadinessTracker = readinessTracker,- providerWorkflowCommitFence = ProviderWorkflowCommitFence()+ providerWorkflowCommitFence = ProviderWorkflowCommitFence(),+ typedProviderClientFactory = typedProviderClientFactory,+ providerSnapshotRepository = object : ProviderSnapshotRepository {+ override suspend fun getSnapshot(providerId: Long) =+ configuredProvider?.takeIf { it.id == providerId }?.toProviderSnapshot()++ override suspend fun compareAndSetStalkerLearning(+ providerId: Long,+ learning: StalkerPortalLearning+ ): Boolean = configuredProvider?.id == providerId++ override suspend fun updateCatalogLayout(providerId: Long, layout: CatalogLayout, detectionVersion: Int) = Unit+ })+ }// ── Initial state ───────────────────────────────────────────────@@ -2759,7 +2810,7 @@ class SyncManagerTest {assertThat(result).isInstanceOf(Result.Success::class.java)verify(stalkerApiService).streamLiveStreams(any(), any(), any())verify(stalkerApiService).getLiveStreams(any(), any(), eq("10"))- verify(portalStateStore, org.mockito.kotlin.times(0)).recordBulkLive(eq(1L), eq(false), anyOrNull(), any())+ verify(portalStateStore, org.mockito.kotlin.times(0)).recordBulkLive(eq(1L), eq(false), anyOrNull(), any(), anyOrNull())}@Test@@ -2818,7 +2869,7 @@ class SyncManagerTest {val result = manager.sync(providerId = 1L, force = false)assertThat(result).isInstanceOf(Result.Success::class.java)- verify(portalStateStore).recordBulkLive(eq(1L), eq(false), anyOrNull(), any())+ verify(portalStateStore).recordBulkLive(eq(1L), eq(false), anyOrNull(), any(), anyOrNull())}@Test@@ -2877,7 +2928,7 @@ class SyncManagerTest {assertThat(result).isInstanceOf(Result.Success::class.java)verify(stalkerApiService).streamLiveStreams(any(), any(), any())verify(stalkerApiService, org.mockito.kotlin.times(0)).getLiveStreams(any(), any(), eq("10"))- verify(portalStateStore).recordBulkLive(eq(1L), eq(true), anyOrNull(), any())+ verify(portalStateStore).recordBulkLive(eq(1L), eq(true), anyOrNull(), any(), anyOrNull())}@Testdiff --git a/data/src/test/java/com/streamvault/data/sync/SyncManagerXtreamLiveStrategyTest.kt b/data/src/test/java/com/streamvault/data/sync/SyncManagerXtreamLiveStrategyTest.ktindex eb8655b1..7ea928c7 100644--- a/data/src/test/java/com/streamvault/data/sync/SyncManagerXtreamLiveStrategyTest.kt+++ b/data/src/test/java/com/streamvault/data/sync/SyncManagerXtreamLiveStrategyTest.kt@@ -22,7 +22,7 @@ import com.streamvault.data.remote.xtream.OkHttpXtreamApiServiceimport com.streamvault.data.remote.xtream.XtreamApiServiceimport com.streamvault.data.remote.xtream.XtreamProviderimport com.streamvault.domain.model.Channel-import com.streamvault.domain.model.Provider+import com.streamvault.domain.model.LegacyProvider as Providerimport com.streamvault.domain.model.ProviderTypeimport com.streamvault.domain.model.SyncMetadataimport java.util.concurrent.atomic.AtomicIntegerdiff --git a/data/src/test/java/com/streamvault/data/sync/SyncManagerXtreamSupportTest.kt b/data/src/test/java/com/streamvault/data/sync/SyncManagerXtreamSupportTest.ktindex 97b4acc9..fe37d2e2 100644--- a/data/src/test/java/com/streamvault/data/sync/SyncManagerXtreamSupportTest.kt+++ b/data/src/test/java/com/streamvault/data/sync/SyncManagerXtreamSupportTest.kt@@ -2,7 +2,7 @@ package com.streamvault.data.syncimport com.google.common.truth.Truth.assertThatimport com.streamvault.data.remote.dto.XtreamCategory-import com.streamvault.domain.model.Provider+import com.streamvault.domain.model.LegacyProvider as Providerimport com.streamvault.domain.model.ProviderTypeimport java.io.IOExceptionimport kotlinx.coroutines.delaydiff --git a/data/src/test/java/com/streamvault/data/sync/SyncWorkerPolicyTest.kt b/data/src/test/java/com/streamvault/data/sync/SyncWorkerPolicyTest.ktindex 5a98ab5a..cc059cbe 100644--- a/data/src/test/java/com/streamvault/data/sync/SyncWorkerPolicyTest.kt+++ b/data/src/test/java/com/streamvault/data/sync/SyncWorkerPolicyTest.kt@@ -4,6 +4,7 @@ import android.database.sqlite.SQLiteExceptionimport android.database.sqlite.SQLiteFullExceptionimport com.google.common.truth.Truth.assertThatimport com.streamvault.data.preferences.DatabaseMaintenanceSnapshot+import kotlinx.coroutines.CancellationExceptionimport kotlinx.coroutines.test.runTestimport org.mockito.kotlin.mockimport org.mockito.kotlin.whenever@@ -42,6 +43,24 @@ class SyncWorkerPolicyTest {assertThat(snapshots).isEmpty()}+ @Test+ fun `maintenance cancellation does not persist a failure or success snapshot`() = runTest {+ val snapshots = mutableListOf<DatabaseMaintenanceSnapshot>()+ var cancellation: CancellationException? = null++ try {+ completeMaintenanceRun(+ runMaintenance = { throw CancellationException("maintenance cancelled") },+ persistSnapshot = { snapshot -> snapshots += snapshot }+ )+ } catch (error: CancellationException) {+ cancellation = error+ }++ assertThat(cancellation).isNotNull()+ assertThat(snapshots).isEmpty()+ }+@Testfun `maintenance retries locked busy and full databases`() {assertThat(shouldRetryMaintenance(sqliteException("database is locked"))).isTrue()diff --git a/data/src/test/resources/stalker/fixtures/archive_recipe_fallback.json b/data/src/test/resources/stalker/fixtures/archive_recipe_fallback.jsonindex a3dd2be5..829feb78 100644--- a/data/src/test/resources/stalker/fixtures/archive_recipe_fallback.json+++ b/data/src/test/resources/stalker/fixtures/archive_recipe_fallback.json@@ -10,7 +10,7 @@"responses": [{ "action": "handshake", "body": "{\"js\":{\"token\":\"token-archive-fallback-a\"}}" },{ "action": "do_auth", "method": "POST", "body": "{\"js\":{\"status\":1}}" },- { "action": "get_profile", "body": "" },+ { "action": "get_profile", "code": 500, "body": "{}" },{ "action": "get_profile", "body": "{\"js\":{\"id\":\"504\",\"name\":\"Archive Fallback\",\"status\":\"1\",\"auth_access\":true}}" },{ "action": "get_main_info", "body": "{\"js\":{\"id\":\"504\",\"name\":\"Archive Fallback\",\"status\":\"1\",\"auth_access\":true}}" },{ "action": "get_localization", "body": "{\"js\":{\"lang\":\"en\",\"timezone\":\"UTC\"}}" },diff --git a/data/src/test/resources/stalker/fixtures/archive_strict_mag.json b/data/src/test/resources/stalker/fixtures/archive_strict_mag.jsonindex 2a29ba46..618e7aa1 100644--- a/data/src/test/resources/stalker/fixtures/archive_strict_mag.json+++ b/data/src/test/resources/stalker/fixtures/archive_strict_mag.json@@ -7,7 +7,7 @@},"responses": [{ "action": "handshake", "body": "{\"js\":{\"token\":\"token-archive-strict-a\"}}" },- { "action": "get_profile", "body": "" },+ { "action": "get_profile", "code": 500, "body": "{}" },{ "action": "get_profile", "body": "{\"js\":{\"id\":\"503\",\"name\":\"Archive Strict\",\"status\":\"1\",\"auth_access\":true}}" },{ "action": "get_main_info", "body": "{\"js\":{\"id\":\"503\",\"name\":\"Archive Strict\",\"status\":\"1\",\"auth_access\":true}}" },{ "action": "get_all_channels", "body": "{\"js\":{\"data\":[{\"id\":\"403\",\"name\":\"Archive Strict\",\"tv_genre_id\":\"12\",\"cmd\":\"ffmpeg http://localhost/ch/403_\",\"archive\":\"1\",\"allow_local_timeshift\":\"1\",\"nginx_secure_link\":\"1\"}]}}" },diff --git a/data/src/test/resources/stalker/fixtures/recipe_fallback.json b/data/src/test/resources/stalker/fixtures/recipe_fallback.jsonindex f401eeb2..a69208ad 100644--- a/data/src/test/resources/stalker/fixtures/recipe_fallback.json+++ b/data/src/test/resources/stalker/fixtures/recipe_fallback.json@@ -10,7 +10,7 @@"responses": [{ "action": "handshake", "body": "{\"js\":{\"token\":\"token-fallback-a\"}}" },{ "action": "do_auth", "method": "POST", "body": "{\"js\":{\"status\":1}}" },- { "action": "get_profile", "body": "" },+ { "action": "get_profile", "code": 500, "body": "{}" },{ "action": "get_profile", "body": "{\"js\":{\"id\":\"99\",\"name\":\"Recovered\",\"status\":\"1\",\"auth_access\":true}}" },{ "action": "get_main_info", "body": "{\"js\":{\"id\":\"99\",\"name\":\"Recovered\",\"status\":\"1\",\"auth_access\":true}}" },{ "action": "get_localization", "body": "{\"js\":{\"lang\":\"en\",\"timezone\":\"UTC\"}}" },diff --git a/data/src/test/resources/stalker/fixtures/strict_mag_legacy.json b/data/src/test/resources/stalker/fixtures/strict_mag_legacy.jsonindex 2f7dbc35..da4ea260 100644--- a/data/src/test/resources/stalker/fixtures/strict_mag_legacy.json+++ b/data/src/test/resources/stalker/fixtures/strict_mag_legacy.json@@ -7,7 +7,7 @@},"responses": [{ "action": "handshake", "body": "{\"js\":{\"token\":\"token-legacy-a\"}}" },- { "action": "get_profile", "body": "" },+ { "action": "get_profile", "code": 500, "body": "{}" },{ "action": "get_profile", "body": "{\"js\":{\"id\":\"88\",\"name\":\"Legacy\",\"status\":\"1\",\"auth_access\":true}}" },{ "action": "get_main_info", "body": "{\"js\":{\"id\":\"88\",\"name\":\"Legacy\",\"status\":\"1\",\"auth_access\":true}}" }],diff --git a/docs/IPTV_CODE_REVIEW.md b/docs/IPTV_CODE_REVIEW.mdindex e21d50d2..bc32362e 100644--- a/docs/IPTV_CODE_REVIEW.md+++ b/docs/IPTV_CODE_REVIEW.md@@ -51,7 +51,7 @@ Focused verification performed in this phase:| Module | Intended responsibility | Observed responsibility and dependencies ||---|---|---|-| `domain` | Platform-neutral models, repository/manager contracts, use cases | Pure Kotlin/JVM and depends only on coroutines/injection. It defines repositories, recording/backup contracts, provider setup use cases, and `IptvProvider`. However, its central `Provider` model contains extensive Stalker persistence/runtime-learning state (ARCH-002). |+| `domain` | Platform-neutral models, repository/manager contracts, use cases | Pure Kotlin/JVM and depends only on coroutines/injection. `Provider` is now stable identity/status; sealed `ProviderConfiguration`, `ProviderSnapshot`, generation-bound `StalkerPortalLearning`, and explicit capability contracts form the provider boundary. `LegacyProvider` remains only as a staged compatibility envelope for legacy UI/revision/backup callers (ARCH-001/ARCH-002 implementation, 2026-08-11). || `data` | Room, DataStore, networking, provider clients, parsers, sync, backup/recording implementations | Android library depending on `domain`. It owns the Room database and DAOs, Xtream/Stalker/Jellyfin clients, M3U/XMLTV parsing, synchronization workers, repositories, backup/Drive, downloads, recordings, reminders, and URL resolution. `SyncManager` centralizes much of the application's provider policy (ARCH-003). || `player` | Reusable playback engine and timeshift | Android library depending on `domain`. It wraps Media3/ExoPlayer, networking/data sources, decoder policy, media session, timeshift, and diagnostics. Provider URL resolution occurs outside this module in `data`/`app`, so the engine receives a resolved URL plus request metadata. || `app` | Android entry points, Compose UI/navigation, DI, TV integration, plugins, cast, updates | Depends on all other modules and is the composition root. Several ViewModels directly depend on `data` implementation types (`SyncManager`, `PreferencesRepository`, `XtreamStreamUrlResolver`, Stalker URL helpers), weakening the domain boundary (ARCH-005). |@@ -89,9 +89,9 @@ This is a hybrid state system: Room owns durable relational content and job meta### Declared boundary-`domain/provider/IptvProvider.kt` declares a uniform interface for authentication, live/VOD/series catalogs, EPG, stream URL building, and catch-up. Only `XtreamProvider` and `StalkerProvider` implement it.+The former monolithic `IptvProvider` contract has been removed. The domain now declares `ProviderAuthenticator`, `LiveCatalogSource`, `VodCatalogSource`, `SeriesCatalogSource`, `GuideSource`, `PlaybackResolver`, and `CatchUpSource`, resolved through one complete typed registry keyed by `ProviderType`.-### Actual boundaries+### Original boundaries (historical review baseline)| Provider/source | Setup and validation | Catalog/sync path | Playback resolution | EPG path ||---|---|---|---|---|@@ -102,7 +102,16 @@ This is a hybrid state system: Room owns durable relational content and job meta| Plugin-based | Android service discovery and Messenger protocol in `StreamVaultPluginManager` | Plugin catalogs are imported/mapped into an M3U provider record rather than represented as a provider capability | Playback delegates through the plugin manager or the mapped M3U path depending on manifest action | No first-class provider EPG contract identified || Recordings/local output | `RecordingManagerImpl`, Room recording entities, alarms, foreground service/capture engine | Local database/files/document URIs, reconciled on launch and periodically | Local `RecordingItem` enters player/navigation as content | EPG is used to schedule/name recordings; recordings do not supply EPG |-The table exposes the core provider problem: the documented shared abstraction is not the boundary used by the main synchronization or playback systems.+The registry is now the shared execution boundary for synchronization, detail hydration, guide lookup, playback, catch-up, recording-source resolution, and setup. Remaining coordinator decomposition and Stalker playback side-effect removal belong to ARCH-003/ARCH-004 in WP5.++### Current provider boundary (2026-08-11)++| Provider/source | Typed execution boundary | Capability notes |+|---|---|---|+| Xtream Codes | Typed setup and client factories; registry-selected sync, guide, detail, playback, and catch-up adapters | All seven capabilities available |+| Stalker Portal | `StalkerConfig` plus generation-bound `StalkerPortalLearning`; registry-selected adapters | All capabilities are potential and become typed restricted/unsupported from validated portal learning |+| M3U/M3U8 | `M3uConfig`; registry-selected live/VOD import and playback/catch-up adapters | Live, VOD, playback, and catch-up available; guide available only when XMLTV is configured; authentication/series unsupported |+| Jellyfin/local media | `JellyfinConfig`; registry-selected authentication, VOD/series sync/detail, and playback adapters | Authentication, VOD, series, and playback available; live, native guide, and catch-up unsupported |## Application and feature flows@@ -162,40 +171,42 @@ App update checking starts from `StreamVaultApp` and stores cached release metad| ID | Classification | Severity | Summary | Fix scope ||---|---|---:|---|---|-| ARCH-001 | Architectural concern | High | The advertised shared provider interface is only implemented by Xtream and Stalker and is bypassed by synchronization. | Architectural |-| ARCH-002 | Architectural concern | High | The domain `Provider` model is a provider-union record dominated by Stalker learned/runtime state. | Architectural |+| ARCH-001 | Implemented in code; API 25 migration evidence pending (2026-08-11) | High | Explicit provider capabilities and complete typed registries now drive synchronization and runtime provider execution. | Architectural |+| ARCH-002 | Implemented in code; API 25 migration evidence pending (2026-08-11) | High | Stable provider identity, typed encrypted configuration/runtime storage, and generation-bound Stalker learning replace the authoritative union row. | Architectural || ARCH-003 | Architectural concern | High | `SyncManager` is a 6,048-line policy, networking, persistence, recovery, and scheduling god object. | Architectural || ARCH-004 | Confirmed defect + architectural concern | Medium | The all-provider playback resolver contains contradictory dispatch and mixes URL resolution with Stalker session construction and persistence. | Local first; architectural follow-up || ARCH-005 | Architectural concern | High | `PlayerViewModel` is a 25+ dependency feature orchestrator that crosses domain/data/player boundaries. | Architectural || ARCH-006 | Highly likely defect | High | Plugin discovery performs multiple blocking IPC calls and maps plugin providers into M3U records. | Local + architectural || ARCH-007 | Architectural concern | Medium | Database schema and the full migration history are concentrated in one multi-thousand-line class. | Architectural |-| ARCH-008 | Implemented; device validation pending | Medium | Startup launches several overlapping background pipelines with independent work identities and state stores. | Architectural |+| ARCH-008 | Resolved in code; device validation pending | Medium | Startup launches several overlapping background pipelines with independent work identities and state stores. | Architectural |## Detailed Phase 1 findings### ARCH-001 — Shared provider abstraction is partial and not used by the main sync pipeline-- **Classification:** Architectural concern+- **Classification:** Implemented in code; API 25 migration evidence pending (2026-08-11)- **Severity:** High-- **Where:** `domain/.../provider/IptvProvider.kt`; `data/.../remote/xtream/XtreamProvider.kt`; `data/.../remote/stalker/StalkerProvider.kt`; `data/.../remote/jellyfin/JellyfinProvider.kt`; `data/.../sync/SyncManager.kt`, especially `sync`, `syncLiveOnly`, `syncMoviesOnly`, and `syncSeriesOnly`.+- **Where:** `domain/.../provider/ProviderCapabilities.kt`; `data/.../provider/DefaultProviderCapabilityRegistry.kt`; `data/.../provider/ProductionProviderCapabilityFactories.kt`; `data/.../sync/ProviderSyncAdapterRegistry.kt`; `data/.../sync/SyncManager.kt`.- **Current behavior:** `IptvProvider` claims to be the shared interface for all providers and includes authentication, every catalog type, EPG, playback, and catch-up. Only Xtream and Stalker implement it. M3U and Jellyfin bypass it. More importantly, `SyncManager` does not dispatch through this interface; it repeatedly switches on `ProviderType` and constructs/calls provider-specific helpers.- **Why this is wrong/fragile:** There are two competing provider architectures: a polymorphic domain contract and a central type switch. Adding or correcting a capability requires edits to multiple switches, repositories, URL resolution, setup, workers, and UI. The oversized interface also assumes every source supports authentication, live, VOD, series, EPG, and catch-up, which is false for M3U, Jellyfin, plugins, and recordings. This encourages dummy behavior and exceptions rather than explicit capabilities.- **Concrete failure scenario:** A new provider or a Jellyfin live-TV capability is added to one path (for example catalog sync) but omitted from one of `retrySection`, guide lookup, playback resolution, or background-worker dispatch. It compiles because `ProviderType` switches are distributed, then fails only in the omitted feature. Existing code already throws “retry unavailable” for Jellyfin in section-specific paths and handles Jellyfin separately in playback.- **Recommended correction:** Replace the monolithic interface with explicit capabilities (`ProviderAuthenticator`, `LiveCatalogSource`, `VodCatalogSource`, `SeriesCatalogSource`, `GuideSource`, `PlaybackResolver`, `CatchUpSource`) and a registry/factory keyed by provider type. Make `SyncManager` orchestrate capability results rather than provider types. M3U, Jellyfin, plugins, and local sources should implement only supported capabilities.- **Fix scope:** Architectural; can be introduced incrementally behind adapters.- **Required tests:** A provider capability contract test suite; registry completeness test for every `ProviderType`; unsupported-capability tests returning typed results rather than exceptions; end-to-end sync/playback tests using one fake per capability combination.+- **Implementation (2026-08-11):** Removed `IptvProvider`; introduced the seven explicit capability interfaces, typed `Available`/`Unsupported`/`Restricted`/`ConfigurationError` resolution, one validated factory per provider type, and the documented capability matrix. Full sync, section retry, and guide orchestration resolve through `ProviderSyncAdapterRegistry`; section implementations no longer re-dispatch on `ProviderType`. Detail hydration, on-demand guide, playback, catch-up, recording-source resolution, and setup resolve through the same capability boundary. Jellyfin movie/series retry is supported, configured M3U XMLTV exposes a cache-backed guide, and absent features return typed results. Architecture tests reject direct protocol-client construction outside `TypedProviderClientFactory`, reintroduction of `IptvProvider`, provider-type redispatch in `SyncManager`, and provider-type branching in the runtime playback/recording/guide boundaries. Stalker playback cache/learning side effects deliberately remain behind its adapter for ARCH-004/WP5.### ARCH-002 — Core domain model is polluted by Stalker transport, fingerprint, and learned state-- **Classification:** Architectural concern+- **Classification:** Implemented in code; API 25 migration evidence pending (2026-08-11)- **Severity:** High-- **Where:** `domain/.../model/Provider.kt:3-52` and corresponding provider entity/mappers/backup/setup code.+- **Where:** `domain/.../model/Provider.kt`; `domain/.../model/ProviderConfiguration.kt`; provider snapshot persistence/codecs; Room migrations 72→73→74; backup schema v11.- **Current behavior:** One `Provider` data class stores generic identity plus Stalker MAC, device profile, timezone/locale, serial/device IDs/signature, advanced JSON, auth mode, portal profile/fingerprint/MAG preset/bootstrap recipe, endpoint/cookie/playback preferences, learned playback mode, requirement flags, fallback use, and rediscovery attempts. Xtream and M3U flags are mixed into the same record.- **Why this is wrong/fragile:** Transport configuration, durable user configuration, portal-learning output, and cross-provider identity are conflated. Every layer and backup/migration must understand fields irrelevant to most providers. Defaults silently create plausible Stalker state, making “unset”, “learned”, and “user-selected” hard to distinguish. It also causes provider-specific policy to leak into UI and shared data paths.- **Concrete failure scenario:** A Stalker bootstrap attempt updates a learned recipe/fingerprint but a concurrent provider edit saves an older copied `Provider`, reverting learned state or overwriting user configuration. Alternatively, a new Stalker strategy requires more fields and forces domain model, Room schema, backup format, UI commands, and every mapper to change together.- **Recommended correction:** Keep `Provider` as stable identity/status. Store typed provider configurations (`XtreamConfig`, `M3uConfig`, `StalkerDeviceIdentity`, `StalkerPortalLearning`, `JellyfinConfig`) behind a sealed configuration model or dedicated tables. Separate user intent from observed/learned portal state with version/timestamp/source metadata.- **Fix scope:** Architectural and migration-sensitive.- **Required tests:** Mapping round trips for each provider subtype; migrations from the union record; concurrent edit-vs-learning update tests; backup compatibility tests; explicit unset/default/learned state tests.+- **Implementation (2026-08-11):** Canonical `Provider` now contains only stable identity/status and lifecycle timestamps. `ProviderSnapshot` combines that identity with sealed `XtreamConfig`, `M3uConfig`, `StalkerConfig`, or `JellyfinConfig`, account/runtime state, configuration generation, and optional generation-matched `StalkerPortalLearning`. Stalker user intent and observations are separate; observations carry generation, source, and timestamp, and compare-and-set persistence rejects stale writes. Room 72→73 creates authoritative encrypted `provider_configs`, runtime storage, and typed generation-bound learning and backfills every provider type; 73→74 rebuilds the stable `providers` table while preserving IDs/FKs and checking `PRAGMA foreign_key_check`. Pending revisions use a versioned typed envelope with legacy decoding. Backup v11 stores stable provider plus typed configuration and excludes sessions, learning, playback hints, TLS pins, and transport consent; versions 0–10 remain readable. `LegacyProvider` is retained only as an explicitly named compatibility envelope while presentation and old backup inputs complete their staged cutover; it is no longer the authoritative model or persistence row.### ARCH-003 — `SyncManager` is the application's provider-policy and persistence god object@@ -259,9 +270,9 @@ App update checking starts from `StreamVaultApp` and stores cached release metad### ARCH-008 — Background work is fragmented across independently scheduled pipelines-- **Classification:** Implemented; device integration validation pending+- **Classification:** Implementation complete; device integration validation pending- **Severity:** Medium-- **Implementation status (2026-07-30):** Implemented in code; device integration validation pending. The migration introduces one provider work identity, one in-process provider execution lane, a central startup-work registry, and a durable Room-backed workflow/phase coordinator with generation-fenced catalog and status commits. Configuration revisions explicitly supersede older work; ordinary sync, index, and EPG requests join the provider chain.+- **Implementation status (2026-08-09):** Complete in code; device integration validation pending. The implementation provides one provider work identity, one in-process provider execution lane, a central startup-work registry, and a durable Room-backed workflow/phase coordinator with generation-fenced catalog and status commits. Configuration revisions explicitly supersede older work; ordinary sync, index, and EPG requests join the provider chain. Stale revision input after provider deletion/supersession is rejected before a workflow row can be created.- **Where:** `StreamVaultApp.onCreate:74-97`; `ProviderSyncWorker`; `XtreamIndexWorker`; `StalkerIndexWorker`; `BackgroundEpgSyncWorker`; `RecordingReconcileWorker`; scheduling methods inside `SyncManager`.- **Current behavior:** Every process start enqueues maintenance, provider stale-check, Xtream index stale-check, and recording reconciliation, while periodic equivalents also exist. Provider sync can queue provider-specific index and EPG workers. Each class has separate unique names, `KEEP`/`REPLACE`/`APPEND_OR_REPLACE` policy, retry classification, delays, and persisted job metadata. In-process provider mutexes serialize some `SyncManager` calls but do not by themselves define a durable cross-worker state machine.- **Why this is wrong/fragile:** WorkManager uniqueness prevents duplicates only within an identical unique name. Different worker types can target the same provider and network/database concurrently. Status is distributed across WorkManager, Room job tables, provider status, sync metadata, and in-memory `SyncStateTracker`, so cancellation/process death may leave contradictory state.@@ -298,8 +309,8 @@ App update checking starts from `StreamVaultApp` and stores cached release metad- Workflow admission is priority-aware inside the Room transaction. Configuration changes (priority 100) cannot be displaced by manual refresh (50), and manual work cannot be displaced by periodic/startup work (0). Rejected lower-priority requests do not mutate the generation, reason, or phase ledger.- `ProviderWorkflowExecutionContext` carries the claimed generation/token through the sync coroutine. Every `SyncCatalogStore` apply path now checks that token inside the same Room transaction that applies staged categories/channels/movies/series. Supersession and catalog commit are therefore serialized: whichever transaction commits first determines whether the old apply is accepted or rejected.- `ProviderWorkflowCommitFenceTest` proves that a superseded generation cannot replace committed catalog rows and that the current owner can apply normally. Manual-refresh tests verify explicit join versus supersede arguments, and DAO tests cover configuration-over-manual priority inversion.-- `ProviderSyncStateReaderImpl` now combines durable active workflow phases with the legacy Xtream job table, so queued/running movie or series indexing remains observable after process recreation.-- Provider sync timestamps, sync metadata, discovered M3U EPG URLs, manual status reconciliation, and targeted-worker status reconciliation are now checked inside generation-owned transactions before publication. ARCH-008 remains open only for device-backed process-kill and manual-refresh-during-each-phase integration tests, plus final removal or demotion of redundant legacy status stores after UI compatibility is verified.+- `ProviderSyncStateReaderImpl` treats the durable workflow as authoritative whenever a workflow row exists; the legacy Xtream job table remains only as a migration fallback for providers without a workflow row. This prevents stale legacy rows from resurrecting a completed-work spinner after process recreation.+- Provider sync timestamps, sync metadata, discovered M3U EPG URLs, manual status reconciliation, and targeted-worker status reconciliation are now checked inside generation-owned transactions before publication. Stale or deleted configuration-revision input is rejected before workflow creation. ARCH-008 remains open only for device-backed process-kill and manual-refresh-during-each-phase integration tests.**Implementation evidence (2026-07-30, slice 5):**@@ -352,8 +363,8 @@ Phase 2 should review these files/modules first, in this order:| ID | Finding | Classification | Severity ||---|---|---|---|-| INFRA-001 | Cancellation is broadly converted into normal failure/retry results | Implemented; adverse-case verification pending (2026-07-27) | High |-| NET-001 | Suspend call paths use blocking, non-cancellable OkHttp `execute()` | Implemented; MockWebServer race matrix pending (2026-07-27) | High |+| INFRA-001 | Cancellation is broadly converted into normal failure/retry results | Resolved; five-worker adverse-case matrix and no-post-cancellation publication checks pass (2026-08-09) | High |+| NET-001 | Suspend call paths use blocking, non-cancellable OkHttp `execute()` | Resolved; MockWebServer never-header/first-byte/mid-body matrix passes (2026-08-09) | High || SYNC-001 | M3U staging has no effective response or catalog-size bound | Resolved (2026-07-26) | High || SYNC-002 | A global progress bus corrupts concurrent per-provider sync progress | Resolved (2026-08-01) | High || LIFE-001 | Every player engine permanently registers a timeshift component callback | Implemented; lifecycle stress verification pending (2026-07-27) | High |@@ -374,7 +385,7 @@ The urgent shared fixes are cancellation-safe HTTP, recording/timeshift lifecycl### INFRA-001 — Cancellation is broadly converted into normal failure/retry results-- **Classification:** Implemented; adverse-case verification pending (2026-07-27)+- **Classification:** Resolved (2026-08-09)- **Severity:** High- **Where:** `data/.../sync/{SyncWorker,BackgroundEpgSyncWorker,ProviderSyncWorker,StalkerIndexWorker,XtreamIndexWorker}.kt`; representative paths in `EpgSourceRepositoryImpl.kt:218-420`, `DownloadManagerImpl.kt:110-203`, `RecordingManagerImpl.kt:134-473`, and `SyncManager.kt:1423`. Static inventory found 289 `runCatching` sites and 234 broad `Exception`/`Throwable` catches.- **Current behavior:** All five coroutine workers end in `catch (Exception)` and translate the throwable to WorkManager failure/retry without first rethrowing `CancellationException`. Many suspending repository/manager operations use Kotlin `runCatching` or broad catches. EPG refresh can turn cancellation into persisted failure and continue cleanup/status work. `SyncManager.sync:712-714` correctly rethrows cancellation, but this is not consistent.@@ -383,11 +394,11 @@ The urgent shared fixes are cancellation-safe HTTP, recording/timeshift lifecycl- **Recommended correction:** Add a shared `runSuspendCatching`/`catchNonCancellation` helper that immediately rethrows cancellation; put an explicit cancellation catch before every broad worker/repository catch; prohibit raw `runCatching` around suspend calls with Detekt/review policy. Translate to domain `Result` only at an explicit owner boundary.- **Fix scope:** Cross-cutting but mechanical; start with workers, sync, recording, and EPG.- **Required tests:** Cancel every worker mid-call and assert no retry/failure or error metadata; cancel imports at parse/transaction boundaries; cancel download/recording/backup; prove child cancellation propagates while genuine `IOException` remains retryable.-- **Implementation (2026-07-27):** Shared `runSuspendCatching`/`rethrowIfCancellation` helpers now protect the WP1 recording, EPG, download, backup, and sync boundaries touched in this package. All five workers catch and rethrow cancellation before failure/retry classification. `Wp1CancellationPolicyTest` prevents the known worker, Stalker, Xtream, and plugin regressions. The finding remains unresolved until the five worker adverse tests and post-cancellation DAO/status assertions pass.+- **Resolution (2026-08-09):** Shared `runSuspendCatching`/`rethrowIfCancellation` helpers protect the WP1 recording, EPG, download, backup, and sync boundaries touched in this package. All five workers catch and rethrow cancellation before failure/retry classification. `Wp1CancellationPolicyTest`, the provider-worker phase matrix in `ProviderWorkflowRunnerTest`, and `SyncWorkerPolicyTest` cover cancellation and no post-cancellation failure/status/snapshot publication. Genuine I/O remains retryable through the existing workflow classifier.### NET-001 — Suspend call paths use blocking, non-cancellable OkHttp `execute()`-- **Classification:** Implemented; MockWebServer race matrix pending (2026-07-27)+- **Classification:** Resolved (2026-08-09)- **Severity:** High- **Where:** `SyncManagerM3uImporter.kt:236-267`; `EpgSourceRepositoryImpl.kt:256`; `EpgRepositoryImpl.kt:288`; `OkHttpStalkerApiService.kt:975,1082,1221`; `JellyfinProvider.kt:305-308`; `RecordingCaptureEngine.kt:80,238,248`; Google Drive/update/download/resolver paths. A correct reference bridge exists at `OkHttpXtreamApiService.executeCancellable:377-392`.- **Current behavior:** Suspending functions move to `Dispatchers.IO` and call synchronous `Call.execute()`. Coroutine cancellation does not call `Call.cancel()`; the thread remains blocked until data, timeout, or server closure. EPG reads are long and recording streams can remain open indefinitely.@@ -396,7 +407,7 @@ The urgent shared fixes are cancellation-safe HTTP, recording/timeshift lifecycl- **Recommended correction:** Standardize an OkHttp coroutine adapter using `suspendCancellableCoroutine`, `enqueue`, and `invokeOnCancellation { call.cancel() }`. Streaming operations need a cancellable handle that closes body and call. Apply operation-specific deadlines.- **Fix scope:** Shared adapter plus local migrations.- **Required tests:** MockWebServer never-headers, never-first-byte, and mid-body stalls; cancellation must promptly cancel the server call, close the body, avoid persistence, and release the dispatcher thread. Retain status/timeout/body-limit coverage.-- **Resolution (2026-07-27):** `Call.useCancellableResponse` now owns the response for the full consumer lifetime, not just until headers arrive. It asynchronously enqueues the call, cancels it before headers and during body reads, converts cancellation-triggered read failures back to coroutine cancellation, and closes the response/body on every exit. M3U, EPG, Jellyfin, recording capture/source probing, downloads, Drive backup, Stalker, and plugin APK download paths use the owned adapter. `CancellableOkHttpTest` proves pre-header cancellation, blocked-body cancellation with body closure, and closure when parsing throws, all under five-second bounds.+- **Resolution (2026-08-09):** `Call.useCancellableResponse` now owns the response for the full consumer lifetime, not just until headers arrive. It asynchronously enqueues the call, cancels it before headers and during body reads, converts cancellation-triggered read failures back to coroutine cancellation, and closes the response/body on every exit. M3U, EPG, Jellyfin, recording capture/source probing, downloads, Drive backup, Stalker, and plugin APK download paths use the owned adapter. `CancellableOkHttpTest` proves pre-header, never-first-byte, and mid-body MockWebServer cancellation, dispatcher release, blocked-body closure, and closure when parsing throws, all under five-second bounds.### SYNC-001 — M3U staging has no effective response or catalog-size bound@@ -617,13 +628,13 @@ Phase 3 should keep these shared defects separate from provider-specific behavio| ID | Finding | Classification | Severity ||---|---|---|---|-| STALKER-001 | All Stalker providers share and globally clear one cookie jar | Confirmed defect | High |-| STALKER-002 | Expired sessions reauthenticate only for one error phrase | Confirmed defect | High |-| STALKER-003 | Cancellation can continue through the Stalker recipe search | Implemented; stage-matrix verification pending (2026-07-27) | High |+| STALKER-001 | All Stalker providers share and globally clear one cookie jar | Implemented; provider-deletion/device matrix pending (2026-08-10) | High |+| STALKER-002 | Expired sessions reauthenticate only for one error phrase | Implemented; concurrent-refresh/retry-ceiling matrix pending (2026-08-10) | High |+| STALKER-003 | Cancellation can continue through the Stalker recipe search | Resolved; discovery-stage, stream-body, cookie, and fallback matrix passes (2026-08-09) | High || STALKER-004 | Catalog pagination silently declares page 200 complete | Confirmed defect | High |-| STALKER-005 | Portal-local dates are parsed as UTC | Confirmed defect | High |-| STALKER-006 | Non-numeric remote IDs collapse to a 31-bit Java hash | Confirmed defect | Medium |-| XTREAM-001 | Most Xtream provider operations swallow cancellation | Implemented; facade matrix verification pending (2026-07-27) | High |+| STALKER-005 | Portal-local dates are parsed as UTC | Implemented; full DST/archive matrix pending (2026-08-10) | High |+| STALKER-006 | Non-numeric remote IDs collapse to a 31-bit Java hash | Implemented; migration/stress matrix pending (2026-08-10) | Medium |+| XTREAM-001 | Most Xtream provider operations swallow cancellation | Resolved; complete public-facade and compatibility matrix passes (2026-08-09) | High || XTREAM-002 | A transient category failure is cached as an empty adult-category set | Resolved; recommended-standard cache policy verified (2026-08-01) | Medium || M3U-001 | Playlist decoding is fixed to UTF-8 and only the first header EPG URL is retained | Resolved; hardened and fully verified (2026-08-01) | Medium || M3U-002 | Query-bearing VOD file URLs are classified as live streams | Resolved; hardened and fully verified (2026-08-01) | Medium |@@ -639,7 +650,7 @@ Phase 3 should keep these shared defects separate from provider-specific behavio### STALKER-001 — All Stalker providers share and globally clear one cookie jar-- **Classification:** Confirmed defect+- **Classification:** Implemented; provider-deletion/device matrix pending (2026-08-10)- **Severity:** High- **Where:** `OkHttpStalkerApiService.kt:63-89,309-357,842-843,1455-1467,1504-1517,1581-1585,2728-2765`.- **Current behavior:** The Hilt-singleton API service owns one `InMemoryStalkerCookieJar`. Every direct/proxy client uses it, keyed only by registrable domain/host. Every authentication recipe calls `cookieJar.clear()`, and current playback cookies are read back by host. Provider ID, MAC, account, and auth epoch are absent from cookie ownership.@@ -648,10 +659,11 @@ Phase 3 should keep these shared defects separate from provider-specific behavio- **Recommended correction:** Scope cookie storage to a provider/auth-session key. Construct a session-owned client/jar or pass an explicit immutable cookie snapshot; never globally clear unrelated sessions. Remove expired session jars on invalidation/provider deletion.- **Fix scope:** Stalker API/session architecture.- **Required tests:** Two providers on different hosts and two MAC/accounts on the same host; concurrent authentication; B fallback clears only B; A playback renewal retains A cookies; provider deletion and token refresh cleanup.+- **Implementation (2026-08-10):** Session scope keys now include provider identity and a monotonically increasing authentication epoch. Recipe reconstruction preserves both fields, direct test profiles alias to the latest authenticated scope, and `invalidateSessionScopes(providerId)` removes that provider's cookie jars, HTTP clients, resolved endpoints, and aliases. Provider auth invalidation and successful provider deletion invoke the hook. Focused tests cover same-host isolation, scope ownership, and reauthentication after explicit invalidation.### STALKER-002 — Expired sessions reauthenticate only for one error phrase-- **Classification:** Confirmed defect+- **Classification:** Implemented; concurrent-refresh/retry-ceiling matrix pending (2026-08-10)- **Severity:** High- **Where:** `StalkerProvider.runWithAuthorizedSession:743-763`, `isAuthorizationFailure:1579-1584`; HTTP mapping in `OkHttpStalkerApiService.executeJsonRequest:974-1000`.- **Current behavior:** A provider retries authentication only when a domain message or exception contains the literal phrase `authorization failed`. The HTTP layer reports expired/rejected sessions as `Portal request failed with HTTP 401.` or `HTTP 403`; portals also use values such as `not_valid_token`, `access denied`, or empty/HTML login responses. These do not invalidate cached authentication.@@ -660,10 +672,11 @@ Phase 3 should keep these shared defects separate from provider-specific behavio- **Recommended correction:** Map HTTP/payload failures to typed `StalkerAuthenticationException`/`StalkerSessionExpiredException`; classify 401, applicable 403, known portal error codes, and login/invalid-token bodies centrally. Add session age/expiry and single-flight refresh. Do not infer auth from free-form UI text.- **Fix scope:** Stalker error/session contract.- **Required tests:** 401, token-specific 403, `not_valid_token`, `authorization failed`, HTML login redirect, genuine non-auth 403, concurrent refresh, and one retry ceiling.+- **Implementation (2026-08-10):** Cached sessions now carry authentication time and a bounded 30-minute maximum age, with earlier account expiry respected. HTTP 401 and token-specific 403 responses map to typed `SessionExpired`; generic 403 responses remain `BlockedOrConfiguration`. Existing mutex/single-retry behavior remains the refresh owner. Focused tests cover the 401/token-403/genuine-403 matrix and session deadlines.### STALKER-003 — Cancellation can continue through the Stalker recipe search-- **Classification:** Implemented; provider stage-matrix verification pending (2026-07-27)+- **Classification:** Resolved (2026-08-09)- **Severity:** High- **Where:** `OkHttpStalkerApiService.authenticate:71-383`, especially suspend calls inside `runCatching` at `96,133,157,173,200,219,236,260`; `runApiCall:1408-1415`; synchronous requests at `975,1082,1221`.- **Current behavior:** Authentication explores auth-mode, recipe, preset, and endpoint candidates. Suspend network calls are wrapped in standard `runCatching`, which captures `CancellationException` and often `continue`s to the next candidate. The API also uses blocking `execute()`, delaying cancellation. Public operations turn any `Exception` into a domain error.@@ -672,7 +685,7 @@ Phase 3 should keep these shared defects separate from provider-specific behavio- **Recommended correction:** Use the shared cancellable OkHttp adapter, explicitly rethrow cancellation at every fallback boundary, and place the complete discovery operation under an overall deadline/request budget. Fallback should continue only for typed compatibility failures.- **Fix scope:** Stalker authentication implementation, using Phase 2 shared primitives.- **Required tests:** Cancel during handshake, credential auth, profile, modules, and streamed page; assert no later recipe request, cookie clear, persisted learning, or error state. Test overall attempt/time budget separately.-- **Implementation (2026-07-27):** Stalker JSON and streaming requests use the owned cancellable response adapter, authentication attempts rethrow cancellation, and each authentication operation runs under an injectable 45-second/24-request budget. Recipe and credential fallback now continue only for `StalkerCompatibilityException`; authentication rejection, malformed accepted responses, cancellation, and budget exhaustion terminate discovery. `OkHttpStalkerCancellationTest` proves handshake cancellation prevents later recipe requests, request exhaustion prevents an additional outbound request, and the overall deadline cancels the active call. The finding remains unresolved pending cancellation coverage for credentials/profile/modules/streamed catalogs.+- **Resolution (2026-08-09):** Stalker JSON and streaming requests use the owned cancellable response adapter, authentication attempts rethrow cancellation, and each authentication operation runs under an injectable 45-second/24-request budget. Recipe and credential fallback now continue only for `StalkerCompatibilityException`; authentication rejection, malformed accepted responses, cancellation, and budget exhaustion terminate discovery. `OkHttpStalkerCancellationTest` covers handshake, credentials, profile, modules, streamed catalog cancellation, request exhaustion, overall deadline cancellation, body closure, no fallback request, no emitted catalog item, and no response-cookie learning after cancellation.### STALKER-004 — Catalog pagination silently declares page 200 complete@@ -688,7 +701,7 @@ Phase 3 should keep these shared defects separate from provider-specific behavio### STALKER-005 — Portal-local dates are parsed as UTC-- **Classification:** Confirmed defect+- **Classification:** Implemented; full DST/archive matrix pending (2026-08-10)- **Severity:** High- **Where:** `OkHttpStalkerApiService.toProgramRecord:1325-1349`, `toProgramRecords:2077-2099`, `parseExpirationDate/parseDateTime:2640-2663`; configured timezone in `buildStalkerDeviceProfile:2467-2547`.- **Current behavior:** Numeric epochs and offset-bearing timestamps are handled correctly, but date/time strings without an offset are converted using `ZoneOffset.UTC`. The parser does not receive `profile.timezone`, even though that timezone is sent to the portal in cookies/profile data. Account expiry strings use the same UTC assumption. Current Stalker tests overwhelmingly use `timezone = "UTC"`.@@ -697,10 +710,11 @@ Phase 3 should keep these shared defects separate from provider-specific behavio- **Recommended correction:** Parse local timestamps using the authenticated/configured portal `ZoneId`; keep offset/epoch precedence. Separate account-date and EPG parsers if their portal conventions differ, and record which interpretation was used for diagnostics.- **Fix scope:** Stalker DTO/parsing signatures and tests.- **Required tests:** UTC, positive/negative zones, DST summer/winter and transition ambiguity, explicit offset overriding profile zone, numeric epochs, expiry date-only semantics, and archive URL alignment.+- **Implementation (2026-08-10):** Catalog `added` timestamps on buffered, paged, validation, series-detail, and streamed item paths now receive the configured portal `ZoneId`; numeric epochs and explicit offsets retain precedence. Existing EPG and account-expiry parsing already use the same zone-aware parser. A non-UTC catalog regression test now verifies the wall-time conversion.### STALKER-006 — Non-numeric remote IDs collapse to a 31-bit Java hash-- **Classification:** Confirmed defect+- **Classification:** Implemented; migration/stress matrix pending (2026-08-10)- **Severity:** Medium- **Where:** `StalkerProvider.stableItemId/syntheticCategoryId:1495-1501`; use for channels, movies, series, episodes, programs, and categories around `696,1240,1284,1339,1374,1404,1465`.- **Current behavior:** Positive numeric IDs are preserved. Every non-numeric ID is mapped with Kotlin/Java `String.hashCode()`, masked to 31 positive bits. The provider/type prefix reduces cross-domain collisions but cannot prevent equal Java hashes; equal-length colliding suffixes such as `Aa`/`BB` remain collisions under the same prefix.@@ -709,12 +723,13 @@ Phase 3 should keep these shared defects separate from provider-specific behavio- **Recommended correction:** Persist canonical remote IDs as strings and use composite provider/type/remote-ID keys. Where a Long is unavoidable, use the existing 63-bit SHA-256-style stable hashing plus collision detection/resolution, never a bare 31-bit hash.- **Fix scope:** Provider identity/schema contract; migration implications belong to Phase 4.- **Required tests:** Known Java-hash collisions; 100k-1m generated remote IDs; stable across restart; collision detection; history/favorites/episodes preserve both records; migration from existing IDs.+- **Implementation (2026-08-10):** The persistent `StalkerRemoteIdentityResolver` and non-persistent fallback now derive candidates from 63-bit SHA-256 material, with collision allocation/resolution retained. Category, channel, movie, series, episode, and projected-category paths use the collision-safe resolver/fallback; known `Aa`/`BB` Java-hash collisions are explicitly covered.## Xtream Codes review### XTREAM-001 — Most Xtream provider operations swallow cancellation-- **Classification:** Implemented; facade matrix verification pending (2026-07-27)+- **Classification:** Resolved (2026-08-09)- **Severity:** High- **Where:** `XtreamProvider.kt:90-529`, including broad catches at `131,144,173,186,215,251,315,328,357,393,508,528`; compatibility `runCatching` at `1023,1037`. `getSeriesInfo:487-490` is the lone consistent cancellation-first example.- **Current behavior:** `OkHttpXtreamApiService` correctly cancels `Call` through `suspendCancellableCoroutine`, but the facade catches the resulting `CancellationException` as `Exception` and returns `Result.Error` for authentication, categories, catalogs, details, streaming indexes, and EPG. Series details explicitly rethrow, demonstrating the desired behavior.@@ -723,7 +738,7 @@ Phase 3 should keep these shared defects separate from provider-specific behavio- **Recommended correction:** Apply the cancellation-first pattern used by `getSeriesInfo` to every suspend method and compatibility fallback, ideally through the shared helper from Phase 2.- **Fix scope:** Local/mechanical across `XtreamProvider`.- **Required tests:** Cancellation for auth, each catalog stream, category prefetch, VOD/series detail, EPG, and primary-to-legacy compatibility; genuine parsing/network failures remain typed.-- **Implementation (2026-07-27):** Every public Xtream suspend operation now rethrows `CancellationException`, and series-info compatibility attempts use `runSuspendCatching`, so cancellation cannot reach the legacy request. Pure per-row mapping isolation remains unchanged. The existing provider/service tests pass, but the finding remains unresolved pending the complete facade cancellation matrix above.+- **Resolution (2026-08-09):** Every public Xtream suspend operation now rethrows `CancellationException`, and series-info compatibility attempts use `runSuspendCatching`, so cancellation cannot reach the legacy request. `XtreamProviderTest` covers authentication, category prefetch, every catalog/detail/EPG operation, both streaming facades, primary-to-legacy compatibility, and genuine network-error typing.### XTREAM-002 — A transient category failure is cached as an empty adult-category set@@ -914,7 +929,7 @@ Phase 4 should trace feature flows end to end in this order:| ID | Finding | Classification | Severity ||---|---|---|---|-| SETUP-001 | Editing an active provider deactivates it before replacement sync succeeds | Resolved (2026-07-29) | High |+| SETUP-001 | Editing an active provider deactivates it before replacement sync succeeds | Resolved (2026-08-10) | High || BACKUP-001 | Restore is non-atomic across Room, preferences, and recording alarms | Resolved (2026-07-29) | High || BACKUP-002 | Provider-scoped restored preferences retain obsolete database IDs | Resolved (2026-07-29) | High || DELETE-001 | Post-delete alarm/sync cleanup failures are never reconciled | Resolved (2026-07-29) | Medium |@@ -937,12 +952,12 @@ The main feature risks are cross-store transitions: provider edits expose partia- **Classification / severity:** Resolved (2026-07-29) — High- **Where:** `ProviderRepositoryImpl.kt:285-333` (Xtream), `381-420` (M3U), `467-485` (Jellyfin), `635-700` (Stalker), and `707-764` (shared completion).-- **Current behavior:** Existing-provider paths write `isActive = false`, `status = PARTIAL`, and reset sync metadata before initial sync. Only success reactivates; error persists inactive state and schedules resume. The old committed catalog does not preserve selection.+- **Current behavior:** Existing-provider paths stage the replacement configuration separately. The committed provider row and catalog remain authoritative while authentication and replacement catalog work run; activation/promotion is fenced by the provider workflow generation.- **Why / scenario:** Replacement authentication and catalog promotion are separate commits. A transient failure after editing the active account's name or HTTP profile disables Home/Live TV despite a previously usable catalog.- **Recommended correction:** Keep the last active provider/catalog until a pending configuration revision and sync epoch commit atomically. At minimum restore prior active state on failure and delay timestamp reset.- **Fix scope:** Shared provider state-transition architecture.- **Required tests:** Active/inactive edit for every provider; sync failure, cancellation, process death, success, old-catalog availability, and stale-epoch isolation.-- **Resolution:** Provider edits now create a candidate configuration revision and keep the last committed provider/catalog active until the replacement sync epoch promotes successfully. Failed or cancelled replacements retain the prior configuration and active catalog; stale candidate epochs cannot promote. Focused repository and worker coverage exercises successful promotion, failure, cancellation, and retry isolation.+- **Resolution (2026-08-10):** Provider edits now create an encrypted candidate configuration revision and keep the last committed provider/catalog active until a forced replacement sync reaches its first fenced catalog commit. Promotion, catalog publication, and Stalker layout side effects share the Room transaction; failed/cancelled replacements retain the prior configuration and active catalog, while stale/deleted WorkManager revisions become no-ops. Rollback cleanup is cancellation-safe and fenced to the still-current uncommitted revision, so an older edit cannot restore over a newer edit or over a candidate that already committed. Stalker authentication failure caches are cleared before the explicit save-with-verification-pending retry. Focused repository, revision-DAO, catalog-fence, and worker coverage exercises successful promotion, failure, cancellation, process-recovery fencing, and retry isolation.### BACKUP-001 — Restore is non-atomic across Room, preferences, and recording alarms@@ -1287,7 +1302,9 @@ WP0 and the initial WP7 harness can start immediately. WP1 establishes the cance- Providers: the existing Stalker and Xtream service suites remain green. `OkHttpStalkerCancellationTest` proves handshake cancellation issues no later recipe request and that request-budget exhaustion issues no request beyond the configured maximum.- Recording/player: `ActiveCaptureTest` proves repeated cancellation joins terminal cleanup; `TimeshiftOwnershipTest` proves writer cleanup precedes file deletion. The implementation registers lazy captures before start, serializes engine cleanup jobs, unregisters callbacks synchronously on terminal release, and closes timeshift calls before joining capture.- Plugins: `PluginPlaybackRoutingTest` proves explicit ownership/priority and one five-second discovery-plus-handler deadline; `StreamVaultPluginOwnerTest` retains package/service/manifest isolation. `PluginMessengerClient` unbinds in `finally` and no longer converts an ancestor timeout into a plugin-owned timeout.-- Status policy: none of the eight WP1 findings is marked resolved merely from implementation. NET-001 has focused adapter evidence, but remains implemented-but-unresolved until the complete MockWebServer race/stall matrix passes; the other findings likewise await their full worker, storage, lifecycle-stress, provider-stage, facade, and bound-service cancellation matrices.+- **Session completion (2026-08-10):** INFRA-001, NET-001, STALKER-003, and XTREAM-001 are resolved against their recommended cancellation matrices. `OkHttpStalkerCancellationTest` covers profile, credential, module, streamed-catalog, body, cookie, and fallback cancellation; `ProviderWorkflowRunnerTest` and `SyncWorkerPolicyTest` cover cancellation without durable failure/success publication; and `XtreamProviderTest` covers every public facade operation, compatibility fallback, streaming facade, and genuine network-error typing.+- The full `:data:testDebugUnitTest` suite now runs 924 tests with zero failures (2026-08-11), including the repaired Stalker replay fixtures.+- REC-001, LIFE-001, LIFE-002, and PLUGIN-003 retain their separate capture, lifecycle-stress, and bound-service cancellation matrices.### WP2 — Durable and truthful workflows@@ -1297,6 +1314,12 @@ WP0 and the initial WP7 harness can start immediately. WP1 establishes the cance- **Deliverables:** pending provider revisions and commit-time activation; checkpointed section-level backup import; stable-ID mapping from WP3; bounded streaming backup reader; deletion tombstones; alarm/reminder compensation; in-flight/success history markers; orphan-download reconciliation; typed retry/permanent outcomes; skew-safe timestamps; DataStore corruption policy; one startup-work registry.- **Exit criteria:** fault injection at every DB/DataStore/alarm/file boundary produces `complete`, `partial`, or `failed-before-commit` truthfully; retry is idempotent; previous active provider/schedule survives failed replacement; process-killed downloads become resumable/failed rather than stuck; update/reconciliation backoff distinguishes attempt from success; corrupt preferences reach a documented recovery state.+**Session completion (2026-08-10):**++- **SETUP-001 — Resolved:** encrypted candidate revisions, forced replacement validation, fenced first-catalog promotion, cancellation-safe rollback, stale/deleted revision no-ops, and Stalker candidate-state restoration are implemented and covered by focused tests.+- **ARCH-008 — Resolved in code; device validation pending:** one durable per-provider workflow/lease lane now fences generations and commits, manual/background work shares the provider chain, stale revision input is rejected before workflow creation, and durable workflow state is authoritative with legacy status only as a migration fallback. Instrumentation packaging passes; connected-device process-kill/manual-refresh execution remains outstanding.+- The remaining WP2 findings are unchanged and are not being marked complete by this session.+### WP3 — Provider, account, and content identity isolation- **Findings:** ARCH-001, ARCH-002, STALKER-001, STALKER-002, STALKER-005, STALKER-006, JELLYFIN-002, PLUGIN-001, PLUGIN-002, XMLTV-002.@@ -1311,6 +1334,14 @@ WP0 and the initial WP7 harness can start immediately. WP1 establishes the cance- Jellyfin: image authentication now performs an exact provider-ID lookup without a stale account cache and always removes internal routing metadata before network dispatch. Parallel same-server account, base-path, edit/delete, and pre-authenticated request tests pass.- Status policy: PLUGIN-001 and PLUGIN-002 were changed from “resolved” to implemented-but-open. Their complete ownership creation, restore, uninstall/replace/reinstall, active/combined-source, and adoption-policy matrices are still required for WP3 closure.+**ARCH-001/ARCH-002 staged closure evidence (2026-08-11):**++- Domain and execution boundary: stable `Provider`, sealed typed configurations, immutable `ProviderSnapshot`, generation-bound Stalker observations, seven explicit capability interfaces, complete/unique provider registries, typed capability absence/restriction, and deletion of `IptvProvider`.+- Runtime routing: setup, full/section/native-guide sync, movie/series hydration, on-demand guide, playback, catch-up, and recording source resolution route through registry adapters. `SyncManager` retains lock/progress/commit-fence ownership for WP5, but no longer switches on `ProviderType` for full, section, or guide dispatch. Jellyfin VOD/series retry and optional configured M3U guide behavior are covered.+- Persistence/compatibility: Room 72→73 adds encrypted typed configuration, account/runtime, and generation-bound learning storage; 73→74 rebuilds stable providers and validates all foreign keys. Typed pending revisions retain legacy recovery decoding. Backup v11 is config-only for Stalker transient state and v0–10 imports remain supported.+- Verification: domain 125/125, data 924/924, and app 279/279 JVM tests pass; Android-test sources compile. Focused Room 72→73 and 72→74 migration tests pass on the available API 36 emulator with all four provider types, encrypted credentials, pending revisions, Stalker learning, active state, dependent catalog rows, stable IDs, and zero FK violations.+- Remaining evidence: API 25 migration execution is unavailable in the installed Android SDK/emulator set. The broader historical migration instrumentation class is not yet a clean release gate because 16 older schema-fixture tests still fail independently of the passing 72→74 cases. ARCH-001 and ARCH-002 are therefore implemented in code, with this device/migration evidence explicitly pending rather than claimed complete.+### WP4 — Bounded ingestion and provider correctness- **Findings:** SYNC-001, STALKER-004, XTREAM-002, M3U-001, M3U-002, XMLTV-001, JELLYFIN-001.diff --git a/domain/src/main/java/com/streamvault/domain/manager/BackupManager.kt b/domain/src/main/java/com/streamvault/domain/manager/BackupManager.ktindex fce4b74e..fdaab616 100644--- a/domain/src/main/java/com/streamvault/domain/manager/BackupManager.kt+++ b/domain/src/main/java/com/streamvault/domain/manager/BackupManager.kt@@ -1,17 +1,25 @@package com.streamvault.domain.manager+import com.streamvault.domain.model.Provider as StableProvider+import com.streamvault.domain.model.PlaybackHistory-import com.streamvault.domain.model.Provider+import com.streamvault.domain.model.LegacyProvider as Providerimport com.streamvault.domain.model.ContentTypeimport com.streamvault.domain.model.RecordingRecurrenceimport kotlinx.coroutines.flow.Flowimport com.streamvault.domain.model.Result+import com.streamvault.domain.model.XtreamConfig+import com.streamvault.domain.model.M3uConfig+import com.streamvault.domain.model.StalkerConfig+import com.streamvault.domain.model.JellyfinConfigdata class BackupData(- val version: Int = 10,+ val version: Int = 11,val checksum: String? = null,val preferences: Map<String, String>? = null,val providers: List<Provider>? = null,+ /** v11 authoritative provider payload; v0-10 continue to use [providers]. */+ val providerSnapshots: List<ProviderBackupSnapshot>? = null,val favorites: List<com.streamvault.domain.model.Favorite>? = null,val virtualGroups: List<com.streamvault.domain.model.VirtualGroup>? = null,val playbackHistory: List<PlaybackHistory>? = null,@@ -22,6 +30,20 @@ data class BackupData(val epgSources: List<com.streamvault.domain.model.EpgSource>? = null)+data class ProviderBackupSnapshot(+ val provider: StableProvider,+ /** Runtime observations are portable and restore without becoming configuration state. */+ val accountRuntime: com.streamvault.domain.model.ProviderAccountRuntime? = null,+ val xtreamConfig: XtreamConfig? = null,+ val m3uConfig: M3uConfig? = null,+ val stalkerConfig: StalkerConfig? = null,+ val jellyfinConfig: JellyfinConfig? = null+) {+ fun configuration() = listOfNotNull(xtreamConfig, m3uConfig, stalkerConfig, jellyfinConfig)+ .singleOrNull()+ ?: throw IllegalArgumentException("Provider backup must contain exactly one typed configuration")+}+/*** Provider-scoped preference values expressed without local Room/DataStore identifiers.* Older backups omit this field and retain the legacy preference map for compatibility.diff --git a/domain/src/main/java/com/streamvault/domain/model/Provider.kt b/domain/src/main/java/com/streamvault/domain/model/Provider.ktindex 8b1800cb..8aff4dce 100644--- a/domain/src/main/java/com/streamvault/domain/model/Provider.kt+++ b/domain/src/main/java/com/streamvault/domain/model/Provider.kt@@ -1,6 +1,12 @@package com.streamvault.domain.model-data class Provider(+/**+ * Compatibility envelope for legacy callers, revisions, and backup formats.+ *+ * New persistence and provider execution must use [ProviderSnapshot] so configuration and+ * generation-bound observations cannot leak back into a flattened union model.+ */+data class LegacyProvider(val id: Long = 0,val name: String,val type: ProviderType,@@ -74,7 +80,7 @@ data class Provider(}override fun toString(): String =- "Provider(id=$id, name=$name, type=$type, status=$status, isActive=$isActive)"+ "LegacyProvider(id=$id, name=$name, type=$type, status=$status, isActive=$isActive)"}/** Provider-scoped presentation of the VOD catalog. */@@ -420,7 +426,7 @@ enum class ProviderStatus {}class ProviderSavedWithSyncErrorException(- val provider: Provider,+ val provider: LegacyProvider,message: String,cause: Throwable? = null) : Exception(message, cause)diff --git a/domain/src/main/java/com/streamvault/domain/model/ProviderConfiguration.kt b/domain/src/main/java/com/streamvault/domain/model/ProviderConfiguration.ktnew file mode 100644index 00000000..1ffd2ffe--- /dev/null+++ b/domain/src/main/java/com/streamvault/domain/model/ProviderConfiguration.kt@@ -0,0 +1,200 @@+package com.streamvault.domain.model++/**+ * User-owned provider configuration. Runtime/account observations deliberately do not belong+ * here: changing this value creates a new [ProviderSnapshot.configurationGeneration].+ */+sealed interface ProviderConfiguration {+ val type: ProviderType+ val schemaVersion: Int+}++data class XtreamConfig(+ val serverUrl: String,+ val username: String,+ val password: String,+ val httpUserAgent: String = "",+ val httpHeaders: String = "",+ val epgSyncMode: ProviderEpgSyncMode = ProviderEpgSyncMode.BACKGROUND,+ val guideSourcePolicy: GuideSourcePolicy = GuideSourcePolicy.AUTO,+ val channelLogoSourcePolicy: ChannelLogoSourcePolicy = ChannelLogoSourcePolicy.SUPPLIER_PREFERRED,+ val fastSyncEnabled: Boolean = true,+ val liveSyncMode: ProviderXtreamLiveSyncMode = ProviderXtreamLiveSyncMode.AUTO,+ override val schemaVersion: Int = CURRENT_SCHEMA_VERSION+) : ProviderConfiguration {+ override val type: ProviderType = ProviderType.XTREAM_CODES++ companion object { const val CURRENT_SCHEMA_VERSION = 1 }+}++data class M3uConfig(+ val playlistUrl: String,+ val epgUrl: String = "",+ val httpUserAgent: String = "",+ val httpHeaders: String = "",+ val epgSyncMode: ProviderEpgSyncMode = ProviderEpgSyncMode.BACKGROUND,+ val guideSourcePolicy: GuideSourcePolicy = GuideSourcePolicy.AUTO,+ val channelLogoSourcePolicy: ChannelLogoSourcePolicy = ChannelLogoSourcePolicy.SUPPLIER_PREFERRED,+ val vodClassificationEnabled: Boolean = false,+ override val schemaVersion: Int = CURRENT_SCHEMA_VERSION+) : ProviderConfiguration {+ override val type: ProviderType = ProviderType.M3U++ companion object { const val CURRENT_SCHEMA_VERSION = 1 }+}++/** Requested Stalker device identity; learned/effective values live in StalkerPortalLearning. */+data class StalkerDeviceIdentity(+ val macAddress: String,+ val deviceProfile: String = "",+ val timezone: String = "",+ val locale: String = "",+ val serialNumber: String = "",+ val deviceId: String = "",+ val deviceId2: String = "",+ val signature: String = ""+)++data class StalkerConfig(+ val portalUrl: String,+ val device: StalkerDeviceIdentity,+ val username: String = "",+ val password: String = "",+ val httpUserAgent: String = "",+ val httpHeaders: String = "",+ val advancedOptionsJson: String = "",+ val authMode: StalkerAuthMode = StalkerAuthMode.AUTO,+ val requestedProfileId: String = StalkerCompatibilityProfileIds.AUTO,+ val protocolPreference: StalkerProtocolPreference = StalkerProtocolPreference.AUTO,+ val transportGrant: StalkerTransportGrant? = null,+ val epgSyncMode: ProviderEpgSyncMode = ProviderEpgSyncMode.BACKGROUND,+ val catalogMode: StalkerCatalogMode = StalkerCatalogMode.ON_DEMAND,+ val guideSourcePolicy: GuideSourcePolicy = GuideSourcePolicy.AUTO,+ val channelLogoSourcePolicy: ChannelLogoSourcePolicy = ChannelLogoSourcePolicy.SUPPLIER_PREFERRED,+ override val schemaVersion: Int = CURRENT_SCHEMA_VERSION+) : ProviderConfiguration {+ override val type: ProviderType = ProviderType.STALKER_PORTAL++ companion object { const val CURRENT_SCHEMA_VERSION = 1 }+}++data class JellyfinConfig(+ val serverUrl: String,+ val username: String,+ /** Password before setup and access token after successful setup. */+ val credential: String,+ override val schemaVersion: Int = CURRENT_SCHEMA_VERSION+) : ProviderConfiguration {+ override val type: ProviderType = ProviderType.JELLYFIN++ companion object { const val CURRENT_SCHEMA_VERSION = 1 }+}++data class ProviderAccountRuntime(+ val maxConnections: Int = 1,+ val expirationDate: Long? = null,+ val apiVersion: String? = null,+ val allowedOutputFormats: List<String> = emptyList(),+ val catalogLayout: CatalogLayout = CatalogLayout.SPLIT,+ val catalogLayoutDetectionVersion: Int = 0,+ val observedAt: Long = 0L+) {+ init { require(maxConnections > 0) { "maxConnections must be positive" } }+}++enum class StalkerObservationSource {+ DISCOVERY,+ AUTHENTICATION,+ CATALOG,+ GUIDE,+ PLAYBACK+}++/** A learned value that is valid only for one immutable configuration generation. */+data class StalkerObservation<T>(+ val value: T,+ val configurationGeneration: Long,+ val source: StalkerObservationSource,+ val observedAt: Long+)++data class StalkerPortalLearning(+ val configurationGeneration: Long,+ val effectiveIdentity: StalkerObservation<StalkerDeviceIdentity>? = null,+ val profileId: StalkerObservation<String>? = null,+ val profileRevision: StalkerObservation<Int>? = null,+ val profileVerification: StalkerObservation<StalkerProfileVerification>? = null,+ val portalProfile: StalkerObservation<StalkerPortalProfile>? = null,+ val portalFingerprint: StalkerObservation<StalkerPortalFingerprint>? = null,+ val magPreset: StalkerObservation<StalkerMagPreset>? = null,+ val protocolFamily: StalkerObservation<StalkerProtocolFamily>? = null,+ val bootstrapRecipe: StalkerObservation<StalkerBootstrapRecipe>? = null,+ val endpointPreference: StalkerObservation<StalkerEndpointPreference>? = null,+ val workingEndpoint: StalkerObservation<String>? = null,+ val cookieMode: StalkerObservation<StalkerCookieMode>? = null,+ val playbackBackendHint: StalkerObservation<StalkerPlaybackBackendHint>? = null,+ val lastPlaybackMode: StalkerObservation<String>? = null,+ val capabilities: Map<String, StalkerObservation<CapabilityState>> = emptyMap(),+ val discoveryEvidence: List<StalkerObservation<DiscoveryObservation>> = emptyList()+) {+ init {+ val observations = buildList {+ add(effectiveIdentity)+ add(profileId)+ add(profileRevision)+ add(profileVerification)+ add(portalProfile)+ add(portalFingerprint)+ add(magPreset)+ add(protocolFamily)+ add(bootstrapRecipe)+ add(endpointPreference)+ add(workingEndpoint)+ add(cookieMode)+ add(playbackBackendHint)+ add(lastPlaybackMode)+ addAll(capabilities.values)+ addAll(discoveryEvidence)+ }.filterNotNull()+ require(observations.all { it.configurationGeneration == configurationGeneration }) {+ "Every Stalker observation must match the learning configuration generation"+ }+ }+}++/** Stable identity/status row; configuration and observations are deliberately absent. */+data class Provider(+ val id: Long = 0L,+ val name: String,+ val type: ProviderType,+ val isActive: Boolean = true,+ val status: ProviderStatus = ProviderStatus.UNKNOWN,+ val lastSyncedAt: Long = 0L,+ val createdAt: Long = System.currentTimeMillis()+) {+ init {+ require(name.isNotBlank()) { "Provider name must not be blank" }+ require(lastSyncedAt >= 0L) { "lastSyncedAt must be non-negative" }+ }+}++data class ProviderSnapshot(+ val provider: Provider,+ val configuration: ProviderConfiguration,+ val configurationGeneration: Long,+ val accountRuntime: ProviderAccountRuntime = ProviderAccountRuntime(),+ val stalkerLearning: StalkerPortalLearning? = null+) {+ init {+ require(provider.type == configuration.type) {+ "Provider type ${provider.type} does not match configuration type ${configuration.type}"+ }+ require(configurationGeneration >= 0L) { "configurationGeneration must be non-negative" }+ require(stalkerLearning == null || provider.type == ProviderType.STALKER_PORTAL) {+ "Stalker learning is valid only for Stalker providers"+ }+ require(stalkerLearning == null || stalkerLearning.configurationGeneration == configurationGeneration) {+ "Stalker learning is stale for this snapshot"+ }+ }+}diff --git a/domain/src/main/java/com/streamvault/domain/provider/IptvProvider.kt b/domain/src/main/java/com/streamvault/domain/provider/IptvProvider.ktdeleted file mode 100644index d217ab54..00000000--- a/domain/src/main/java/com/streamvault/domain/provider/IptvProvider.kt+++ /dev/null@@ -1,32 +0,0 @@-package com.streamvault.domain.provider--import com.streamvault.domain.model.*--/**- * Shared interface for all IPTV providers (Xtream Codes, M3U, etc.).- * Each provider type implements this to normalize data into domain models.- */-interface IptvProvider {- val providerId: Long-- suspend fun authenticate(): Result<Provider>-- suspend fun getLiveCategories(): Result<List<Category>>- suspend fun getLiveStreams(categoryId: Long? = null): Result<List<Channel>>-- suspend fun getVodCategories(): Result<List<Category>>- suspend fun getVodStreams(categoryId: Long? = null): Result<List<Movie>>- suspend fun getVodInfo(vodId: Long): Result<Movie>-- suspend fun getSeriesCategories(): Result<List<Category>>- suspend fun getSeriesList(categoryId: Long? = null): Result<List<Series>>- suspend fun getSeriesInfo(seriesId: Long): Result<Series>-- suspend fun getEpg(channelId: String): Result<List<Program>>- suspend fun getShortEpg(channelId: String, limit: Int = 4): Result<List<Program>>-- suspend fun buildStreamUrl(streamId: Long, containerExtension: String? = null): String- suspend fun buildCatchUpUrl(streamId: Long, start: Long, end: Long): String?- suspend fun buildCatchUpUrls(streamId: Long, start: Long, end: Long): List<String> =- listOfNotNull(buildCatchUpUrl(streamId, start, end))-}diff --git a/domain/src/main/java/com/streamvault/domain/provider/ProviderCapabilities.kt b/domain/src/main/java/com/streamvault/domain/provider/ProviderCapabilities.ktnew file mode 100644index 00000000..eb186a3c--- /dev/null+++ b/domain/src/main/java/com/streamvault/domain/provider/ProviderCapabilities.kt@@ -0,0 +1,192 @@+package com.streamvault.domain.provider++import com.streamvault.domain.model.Category+import com.streamvault.domain.model.Channel+import com.streamvault.domain.model.Movie+import com.streamvault.domain.model.Program+import com.streamvault.domain.model.LegacyProvider as Provider+import com.streamvault.domain.model.ProviderSnapshot+import com.streamvault.domain.model.ProviderType+import com.streamvault.domain.model.Result+import com.streamvault.domain.model.Series++data class ProviderContentReference(+ val providerId: Long,+ val localId: Long? = null,+ val streamId: Long? = null,+ val remoteId: String? = null,+ val seriesCatalogOrigin: com.streamvault.domain.model.SeriesCatalogOrigin? = null,+ val episodePlaybackTemplateUrl: String? = null+) {+ fun numericRemoteId(): Long? = remoteId?.toLongOrNull() ?: streamId+}++data class GuideRequest(+ val streamId: Long,+ val epgChannelId: String? = null,+ val limit: Int = 4+)++data class PlaybackRequest(+ val sourceUrl: String,+ val content: ProviderContentReference,+ val contentType: com.streamvault.domain.model.ContentType,+ val containerExtension: String? = null,+ val preferStableUrl: Boolean = false+)++data class ResolvedPlayback(+ val url: String,+ val expirationTime: Long? = null,+ val containerExtension: String? = null,+ val headers: Map<String, String> = emptyMap(),+ val userAgent: String? = null,+ val playbackTransportPolicy: com.streamvault.domain.model.PlaybackTransportPolicy? = null,+ val allowInvalidSsl: Boolean = false,+ val proxyHost: String = "",+ val proxyPort: Int? = null+)++data class CatchUpRequest(+ val streamId: Long,+ val start: Long,+ val end: Long,+ val sourceStreamUrl: String? = null,+ val sourceCatchUpTemplate: String? = null+)++enum class ProviderCapability {+ AUTHENTICATION,+ LIVE_CATALOG,+ VOD_CATALOG,+ SERIES_CATALOG,+ GUIDE,+ PLAYBACK,+ CATCH_UP+}++sealed interface CapabilityResolution<out T> {+ data class Available<T>(val capability: T) : CapabilityResolution<T>+ data class Unsupported(val reason: String) : CapabilityResolution<Nothing>+ data class Restricted(val reason: String) : CapabilityResolution<Nothing>+ data class ConfigurationError(val reason: String) : CapabilityResolution<Nothing>+}++interface ProviderAuthenticator {+ suspend fun authenticate(): Result<Provider>+}++interface LiveCatalogSource {+ suspend fun getLiveCategories(): Result<List<Category>>+ suspend fun getLiveStreams(categoryId: Long? = null): Result<List<Channel>>+}++interface VodCatalogSource {+ suspend fun getVodCategories(): Result<List<Category>>+ suspend fun getVodStreams(categoryId: Long? = null): Result<List<Movie>>+ suspend fun getVodInfo(vodId: Long): Result<Movie>+ suspend fun getVodInfo(reference: ProviderContentReference): Result<Movie> {+ val id = reference.numericRemoteId()+ ?: return Result.error("Provider does not expose a numeric VOD identifier")+ return getVodInfo(id)+ }+ suspend fun hydrateVod(reference: ProviderContentReference, current: Movie): Result<Movie> =+ getVodInfo(reference)+}++interface SeriesCatalogSource {+ suspend fun getSeriesCategories(): Result<List<Category>>+ suspend fun getSeriesList(categoryId: Long? = null): Result<List<Series>>+ suspend fun getSeriesInfo(seriesId: Long): Result<Series>+ suspend fun getSeriesInfo(reference: ProviderContentReference): Result<Series> {+ val id = reference.numericRemoteId()+ ?: return Result.error("Provider does not expose a numeric series identifier")+ return getSeriesInfo(id)+ }+ suspend fun hydrateSeries(reference: ProviderContentReference, current: Series): Result<Series> =+ getSeriesInfo(reference)+}++interface GuideSource {+ suspend fun getEpg(channelId: String): Result<List<Program>>+ suspend fun getShortEpg(channelId: String, limit: Int = 4): Result<List<Program>>+ suspend fun getEpg(request: GuideRequest): Result<List<Program>> =+ getEpg(request.epgChannelId?.takeIf(String::isNotBlank) ?: request.streamId.toString())+ suspend fun getShortEpg(request: GuideRequest): Result<List<Program>> =+ getShortEpg(request.epgChannelId?.takeIf(String::isNotBlank) ?: request.streamId.toString(), request.limit)+}++interface PlaybackResolver {+ suspend fun buildStreamUrl(streamId: Long, containerExtension: String? = null): String+ suspend fun resolve(request: PlaybackRequest): Result<ResolvedPlayback> {+ if (request.sourceUrl.isNotBlank()) {+ return Result.success(+ ResolvedPlayback(+ url = request.sourceUrl,+ containerExtension = request.containerExtension+ )+ )+ }+ val streamId = request.content.numericRemoteId()+ ?: return Result.error("Provider does not expose a numeric playback identifier")+ return runCatching { buildStreamUrl(streamId, request.containerExtension) }+ .fold(+ { Result.success(ResolvedPlayback(it, containerExtension = request.containerExtension)) },+ { Result.error(it.message ?: "Playback resolution failed", it) }+ )+ }+}++interface CatchUpSource {+ suspend fun buildCatchUpUrl(streamId: Long, start: Long, end: Long): String?+ suspend fun buildCatchUpUrls(streamId: Long, start: Long, end: Long): List<String> =+ listOfNotNull(buildCatchUpUrl(streamId, start, end))+ suspend fun buildCatchUpUrls(request: CatchUpRequest): List<String> =+ buildCatchUpUrls(request.streamId, request.start, request.end)+}++interface ProviderCapabilityFactory {+ val providerType: ProviderType+ fun create(snapshot: ProviderSnapshot): ProviderCapabilitySet+}++/** The typed execution surface for one immutable provider snapshot. */+interface ProviderCapabilitySet {+ val snapshot: ProviderSnapshot+ fun authentication(): CapabilityResolution<ProviderAuthenticator>+ fun liveCatalog(): CapabilityResolution<LiveCatalogSource>+ fun vodCatalog(): CapabilityResolution<VodCatalogSource>+ fun seriesCatalog(): CapabilityResolution<SeriesCatalogSource>+ fun guide(): CapabilityResolution<GuideSource>+ fun playback(): CapabilityResolution<PlaybackResolver>+ fun catchUp(): CapabilityResolution<CatchUpSource>+}++interface ProviderCapabilityRegistry {+ fun resolve(snapshot: ProviderSnapshot): CapabilityResolution<ProviderCapabilitySet>+}++/** Canonical potential-capability matrix. Runtime restrictions are applied by factories. */+object ProviderCapabilityMatrix {+ private val matrix = mapOf(+ ProviderType.XTREAM_CODES to ProviderCapability.entries.toSet(),+ ProviderType.STALKER_PORTAL to ProviderCapability.entries.toSet(),+ ProviderType.M3U to setOf(+ ProviderCapability.LIVE_CATALOG,+ ProviderCapability.VOD_CATALOG,+ ProviderCapability.GUIDE,+ ProviderCapability.PLAYBACK,+ ProviderCapability.CATCH_UP+ ),+ ProviderType.JELLYFIN to setOf(+ ProviderCapability.AUTHENTICATION,+ ProviderCapability.VOD_CATALOG,+ ProviderCapability.SERIES_CATALOG,+ ProviderCapability.PLAYBACK+ )+ )++ fun potentialCapabilities(type: ProviderType): Set<ProviderCapability> = matrix.getValue(type)+ fun supports(type: ProviderType, capability: ProviderCapability): Boolean =+ capability in potentialCapabilities(type)+}diff --git a/domain/src/main/java/com/streamvault/domain/repository/CombinedM3uRepository.kt b/domain/src/main/java/com/streamvault/domain/repository/CombinedM3uRepository.ktindex d262696e..fad853ac 100644--- a/domain/src/main/java/com/streamvault/domain/repository/CombinedM3uRepository.kt+++ b/domain/src/main/java/com/streamvault/domain/repository/CombinedM3uRepository.kt@@ -6,7 +6,7 @@ import com.streamvault.domain.model.Categoryimport com.streamvault.domain.model.Channelimport com.streamvault.domain.model.CombinedCategoryimport com.streamvault.domain.model.CombinedM3uProfile-import com.streamvault.domain.model.Provider+import com.streamvault.domain.model.LegacyProvider as Providerimport com.streamvault.domain.model.Resultimport kotlinx.coroutines.flow.Flowdiff --git a/domain/src/main/java/com/streamvault/domain/repository/ProviderRepository.kt b/domain/src/main/java/com/streamvault/domain/repository/ProviderRepository.ktindex b300f3b3..70d7a677 100644--- a/domain/src/main/java/com/streamvault/domain/repository/ProviderRepository.kt+++ b/domain/src/main/java/com/streamvault/domain/repository/ProviderRepository.kt@@ -4,7 +4,7 @@ import com.streamvault.domain.manager.ProviderCredentialsimport com.streamvault.domain.model.ChannelLogoSourcePolicyimport com.streamvault.domain.model.GuideSourcePolicyimport com.streamvault.domain.model.Program-import com.streamvault.domain.model.Provider+import com.streamvault.domain.model.LegacyProvider as Providerimport com.streamvault.domain.model.ProviderEpgSyncModeimport com.streamvault.domain.model.ProviderXtreamLiveSyncModeimport com.streamvault.domain.model.Result@@ -15,6 +15,22 @@ import com.streamvault.domain.model.StalkerProtocolPreferenceimport com.streamvault.domain.model.StalkerTransportGrantimport kotlinx.coroutines.flow.Flow+sealed interface ProviderSetupRequest {+ data class Configured(+ val name: String,+ val configuration: com.streamvault.domain.model.ProviderConfiguration,+ val existingProviderId: Long? = null,+ val saveWithoutVerification: Boolean = false,+ val repairConnection: Boolean = false+ ) : ProviderSetupRequest++ data class JellyfinQuickConnect(+ val serverUrl: String,+ val name: String,+ val existingProviderId: Long? = null+ ) : ProviderSetupRequest+}+data class LiveStreamProgramRequest(val streamId: Long,val epgChannelId: String? = null@@ -64,51 +80,10 @@ interface ProviderRepository {): Booleansuspend fun setActiveProvider(id: Long): Result<Unit>- suspend fun loginXtream(serverUrl: String, username: String, password: String, name: String, httpUserAgent: String = "", httpHeaders: String = "", xtreamFastSyncEnabled: Boolean, epgSyncMode: ProviderEpgSyncMode = ProviderEpgSyncMode.BACKGROUND, xtreamLiveSyncMode: ProviderXtreamLiveSyncMode = ProviderXtreamLiveSyncMode.AUTO, guideSourcePolicy: GuideSourcePolicy = GuideSourcePolicy.AUTO, channelLogoSourcePolicy: ChannelLogoSourcePolicy = ChannelLogoSourcePolicy.SUPPLIER_PREFERRED, onProgress: ((String) -> Unit)? = null, id: Long? = null): Result<Provider>- suspend fun validateM3u(url: String, name: String, httpUserAgent: String = "", httpHeaders: String = "", epgSyncMode: ProviderEpgSyncMode = ProviderEpgSyncMode.BACKGROUND, m3uVodClassificationEnabled: Boolean = false, guideSourcePolicy: GuideSourcePolicy = GuideSourcePolicy.AUTO, channelLogoSourcePolicy: ChannelLogoSourcePolicy = ChannelLogoSourcePolicy.SUPPLIER_PREFERRED, onProgress: ((String) -> Unit)? = null, id: Long? = null): Result<Provider>- suspend fun loginStalker(- portalUrl: String,- macAddress: String,- name: String,- authMode: StalkerAuthMode = StalkerAuthMode.AUTO,- username: String = "",- password: String = "",- httpUserAgent: String = "",- httpHeaders: String = "",- deviceProfile: String = "",- timezone: String = "",- locale: String = "",- serialNumber: String = "",- deviceId: String = "",- deviceId2: String = "",- signature: String = "",- stalkerAdvancedOptionsJson: String = "",- protocolPreference: StalkerProtocolPreference = StalkerProtocolPreference.AUTO,- transportGrant: StalkerTransportGrant? = null,- saveWithoutVerification: Boolean = false,- repairConnection: Boolean = false,- requestedProfileId: String = StalkerCompatibilityProfileIds.AUTO,- epgSyncMode: ProviderEpgSyncMode = ProviderEpgSyncMode.BACKGROUND,- catalogMode: StalkerCatalogMode = StalkerCatalogMode.ON_DEMAND,- guideSourcePolicy: GuideSourcePolicy = GuideSourcePolicy.AUTO,- channelLogoSourcePolicy: ChannelLogoSourcePolicy = ChannelLogoSourcePolicy.SUPPLIER_PREFERRED,- onProgress: ((String) -> Unit)? = null,- id: Long? = null- ): Result<Provider>- suspend fun loginJellyfin(- serverUrl: String,- username: String,- password: String,- name: String,- onProgress: ((String) -> Unit)? = null,- id: Long? = null- ): Result<Provider>- suspend fun loginJellyfinQuickConnect(- serverUrl: String,- name: String,- onCode: ((String) -> Unit)? = null,+ suspend fun setupProvider(+ request: ProviderSetupRequest,onProgress: ((String) -> Unit)? = null,- id: Long? = null+ onCode: ((String) -> Unit)? = null): Result<Provider>suspend fun refreshProviderData(providerId: Long,diff --git a/domain/src/main/java/com/streamvault/domain/repository/ProviderSnapshotRepository.kt b/domain/src/main/java/com/streamvault/domain/repository/ProviderSnapshotRepository.ktnew file mode 100644index 00000000..7f39e100--- /dev/null+++ b/domain/src/main/java/com/streamvault/domain/repository/ProviderSnapshotRepository.kt@@ -0,0 +1,17 @@+package com.streamvault.domain.repository++import com.streamvault.domain.model.ProviderSnapshot+import com.streamvault.domain.model.StalkerPortalLearning+import com.streamvault.domain.model.CatalogLayout++interface ProviderSnapshotRepository {+ suspend fun getSnapshot(providerId: Long): ProviderSnapshot?++ /** Returns false when the observation was produced by a stale configuration generation. */+ suspend fun compareAndSetStalkerLearning(+ providerId: Long,+ learning: StalkerPortalLearning+ ): Boolean++ suspend fun updateCatalogLayout(providerId: Long, layout: CatalogLayout, detectionVersion: Int)+}diff --git a/domain/src/main/java/com/streamvault/domain/usecase/SyncProvider.kt b/domain/src/main/java/com/streamvault/domain/usecase/SyncProvider.ktindex ea3514fd..415508d4 100644--- a/domain/src/main/java/com/streamvault/domain/usecase/SyncProvider.kt+++ b/domain/src/main/java/com/streamvault/domain/usecase/SyncProvider.kt@@ -1,7 +1,7 @@package com.streamvault.domain.usecaseimport com.streamvault.domain.manager.ProviderSyncStateReader-import com.streamvault.domain.model.Provider+import com.streamvault.domain.model.LegacyProvider as Providerimport com.streamvault.domain.model.ProviderEpgSyncModeimport com.streamvault.domain.model.ProviderStatusimport com.streamvault.domain.model.Resultdiff --git a/domain/src/main/java/com/streamvault/domain/usecase/ValidateAndAddProvider.kt b/domain/src/main/java/com/streamvault/domain/usecase/ValidateAndAddProvider.ktindex 27d36d37..93ca0f60 100644--- a/domain/src/main/java/com/streamvault/domain/usecase/ValidateAndAddProvider.kt+++ b/domain/src/main/java/com/streamvault/domain/usecase/ValidateAndAddProvider.kt@@ -3,7 +3,7 @@ package com.streamvault.domain.usecaseimport com.streamvault.domain.manager.ProviderSetupInputValidatorimport com.streamvault.domain.model.ChannelLogoSourcePolicyimport com.streamvault.domain.model.GuideSourcePolicy-import com.streamvault.domain.model.Provider+import com.streamvault.domain.model.LegacyProvider as Providerimport com.streamvault.domain.model.ProviderEpgSyncModeimport com.streamvault.domain.model.ProviderXtreamLiveSyncModeimport com.streamvault.domain.model.ProviderSavedWithSyncErrorException@@ -17,6 +17,12 @@ import com.streamvault.domain.model.StalkerTransportChallengeimport com.streamvault.domain.model.StalkerTransportGrantimport com.streamvault.domain.model.StalkerTransportConsentRequiredExceptionimport com.streamvault.domain.repository.ProviderRepository+import com.streamvault.domain.repository.ProviderSetupRequest+import com.streamvault.domain.model.XtreamConfig+import com.streamvault.domain.model.M3uConfig+import com.streamvault.domain.model.StalkerConfig+import com.streamvault.domain.model.StalkerDeviceIdentity+import com.streamvault.domain.model.JellyfinConfigimport java.net.URIimport java.net.URLDecoderimport java.nio.charset.StandardCharsets@@ -202,20 +208,24 @@ class ValidateAndAddProvider @Inject constructor(httpHeaders = command.httpHeaders)) {- is Result.Success -> providerRepository.loginXtream(- serverUrl = validated.data.serverUrl,- username = validated.data.username,- password = validated.data.password,- name = validated.data.name,- httpUserAgent = validated.data.httpUserAgent,- httpHeaders = validated.data.httpHeaders,- xtreamFastSyncEnabled = command.xtreamFastSyncEnabled,- epgSyncMode = command.epgSyncMode,- xtreamLiveSyncMode = command.xtreamLiveSyncMode,- guideSourcePolicy = command.guideSourcePolicy,- channelLogoSourcePolicy = command.channelLogoSourcePolicy,- onProgress = onProgress,- id = command.existingProviderId+ is Result.Success -> providerRepository.setupProvider(+ ProviderSetupRequest.Configured(+ name = validated.data.name,+ configuration = XtreamConfig(+ serverUrl = validated.data.serverUrl,+ username = validated.data.username,+ password = validated.data.password,+ httpUserAgent = validated.data.httpUserAgent,+ httpHeaders = validated.data.httpHeaders,+ fastSyncEnabled = command.xtreamFastSyncEnabled,+ epgSyncMode = command.epgSyncMode,+ liveSyncMode = command.xtreamLiveSyncMode,+ guideSourcePolicy = command.guideSourcePolicy,+ channelLogoSourcePolicy = command.channelLogoSourcePolicy+ ),+ existingProviderId = command.existingProviderId+ ),+ onProgress = onProgress).toUseCaseResult()is Result.Error -> ValidateAndAddProviderResult.ValidationError(validated.message)@@ -242,35 +252,43 @@ class ValidateAndAddProvider @Inject constructor(ValidateAndAddProviderResult.ValidationError(parsedXtream.message)is ParsedXtreamPlaylistUrlResult.Success -> {- providerRepository.loginXtream(- serverUrl = parsedXtream.serverUrl,- username = parsedXtream.username,- password = parsedXtream.password,- name = validatedInput.name,- httpUserAgent = validatedInput.httpUserAgent,- httpHeaders = validatedInput.httpHeaders,- xtreamFastSyncEnabled = false,- epgSyncMode = command.epgSyncMode,- xtreamLiveSyncMode = ProviderXtreamLiveSyncMode.AUTO,- guideSourcePolicy = command.guideSourcePolicy,- channelLogoSourcePolicy = command.channelLogoSourcePolicy,- onProgress = onProgress,- id = command.existingProviderId+ providerRepository.setupProvider(+ ProviderSetupRequest.Configured(+ name = validatedInput.name,+ configuration = XtreamConfig(+ serverUrl = parsedXtream.serverUrl,+ username = parsedXtream.username,+ password = parsedXtream.password,+ httpUserAgent = validatedInput.httpUserAgent,+ httpHeaders = validatedInput.httpHeaders,+ fastSyncEnabled = false,+ epgSyncMode = command.epgSyncMode,+ liveSyncMode = ProviderXtreamLiveSyncMode.AUTO,+ guideSourcePolicy = command.guideSourcePolicy,+ channelLogoSourcePolicy = command.channelLogoSourcePolicy+ ),+ existingProviderId = command.existingProviderId+ ),+ onProgress = onProgress).toUseCaseResult()}ParsedXtreamPlaylistUrlResult.NotXtreamPlaylist -> {- providerRepository.validateM3u(- url = validatedInput.url,- name = validatedInput.name,- httpUserAgent = validatedInput.httpUserAgent,- httpHeaders = validatedInput.httpHeaders,- epgSyncMode = command.epgSyncMode,- m3uVodClassificationEnabled = command.m3uVodClassificationEnabled,- guideSourcePolicy = command.guideSourcePolicy,- channelLogoSourcePolicy = command.channelLogoSourcePolicy,- onProgress = onProgress,- id = command.existingProviderId+ providerRepository.setupProvider(+ ProviderSetupRequest.Configured(+ name = validatedInput.name,+ configuration = M3uConfig(+ playlistUrl = validatedInput.url,+ httpUserAgent = validatedInput.httpUserAgent,+ httpHeaders = validatedInput.httpHeaders,+ epgSyncMode = command.epgSyncMode,+ vodClassificationEnabled = command.m3uVodClassificationEnabled,+ guideSourcePolicy = command.guideSourcePolicy,+ channelLogoSourcePolicy = command.channelLogoSourcePolicy+ ),+ existingProviderId = command.existingProviderId+ ),+ onProgress = onProgress).toUseCaseResult()}}@@ -306,34 +324,40 @@ class ValidateAndAddProvider @Inject constructor(stalkerAdvancedOptionsJson = command.stalkerAdvancedOptionsJson)) {- is Result.Success -> providerRepository.loginStalker(- portalUrl = validated.data.portalUrl,- macAddress = validated.data.macAddress,- name = validated.data.name,- authMode = validated.data.authMode,- username = validated.data.username,- password = validated.data.password,- httpUserAgent = validated.data.httpUserAgent,- httpHeaders = validated.data.httpHeaders,- deviceProfile = validated.data.deviceProfile,- timezone = validated.data.timezone,- locale = validated.data.locale,- serialNumber = validated.data.serialNumber,- deviceId = validated.data.deviceId,- deviceId2 = validated.data.deviceId2,- signature = validated.data.signature,- stalkerAdvancedOptionsJson = validated.data.stalkerAdvancedOptionsJson,- protocolPreference = command.protocolPreference,- transportGrant = command.transportGrant,- saveWithoutVerification = command.saveWithoutVerification,- repairConnection = command.repairConnection,- requestedProfileId = command.requestedProfileId,- epgSyncMode = command.epgSyncMode,- catalogMode = command.catalogMode,- guideSourcePolicy = command.guideSourcePolicy,- channelLogoSourcePolicy = command.channelLogoSourcePolicy,- onProgress = onProgress,- id = command.existingProviderId+ is Result.Success -> providerRepository.setupProvider(+ ProviderSetupRequest.Configured(+ name = validated.data.name,+ configuration = StalkerConfig(+ portalUrl = validated.data.portalUrl,+ device = StalkerDeviceIdentity(+ macAddress = validated.data.macAddress,+ deviceProfile = validated.data.deviceProfile,+ timezone = validated.data.timezone,+ locale = validated.data.locale,+ serialNumber = validated.data.serialNumber,+ deviceId = validated.data.deviceId,+ deviceId2 = validated.data.deviceId2,+ signature = validated.data.signature+ ),+ authMode = validated.data.authMode,+ username = validated.data.username,+ password = validated.data.password,+ httpUserAgent = validated.data.httpUserAgent,+ httpHeaders = validated.data.httpHeaders,+ advancedOptionsJson = validated.data.stalkerAdvancedOptionsJson,+ protocolPreference = command.protocolPreference,+ transportGrant = command.transportGrant,+ requestedProfileId = command.requestedProfileId,+ epgSyncMode = command.epgSyncMode,+ catalogMode = command.catalogMode,+ guideSourcePolicy = command.guideSourcePolicy,+ channelLogoSourcePolicy = command.channelLogoSourcePolicy+ ),+ existingProviderId = command.existingProviderId,+ saveWithoutVerification = command.saveWithoutVerification,+ repairConnection = command.repairConnection+ ),+ onProgress = onProgress).toUseCaseResult()is Result.Error -> ValidateAndAddProviderResult.ValidationError(validated.message)@@ -354,13 +378,17 @@ class ValidateAndAddProvider @Inject constructor(name = command.name)) {- is Result.Success -> providerRepository.loginJellyfin(- serverUrl = validated.data.serverUrl,- username = validated.data.username,- password = validated.data.password,- name = validated.data.name,- onProgress = onProgress,- id = command.existingProviderId+ is Result.Success -> providerRepository.setupProvider(+ ProviderSetupRequest.Configured(+ name = validated.data.name,+ configuration = JellyfinConfig(+ serverUrl = validated.data.serverUrl,+ username = validated.data.username,+ credential = validated.data.password+ ),+ existingProviderId = command.existingProviderId+ ),+ onProgress = onProgress).toUseCaseResult()is Result.Error -> ValidateAndAddProviderResult.ValidationError(validated.message)@@ -379,12 +407,14 @@ class ValidateAndAddProvider @Inject constructor(name = command.name)) {- is Result.Success -> providerRepository.loginJellyfinQuickConnect(- serverUrl = validated.data.serverUrl,- name = validated.data.name,- onCode = onCode,+ is Result.Success -> providerRepository.setupProvider(+ ProviderSetupRequest.JellyfinQuickConnect(+ serverUrl = validated.data.serverUrl,+ name = validated.data.name,+ existingProviderId = command.existingProviderId+ ),onProgress = onProgress,- id = command.existingProviderId+ onCode = onCode).toUseCaseResult()is Result.Error -> ValidateAndAddProviderResult.ValidationError(validated.message)diff --git a/domain/src/test/java/com/streamvault/domain/model/ProviderSnapshotTest.kt b/domain/src/test/java/com/streamvault/domain/model/ProviderSnapshotTest.ktnew file mode 100644index 00000000..a5b62a4b--- /dev/null+++ b/domain/src/test/java/com/streamvault/domain/model/ProviderSnapshotTest.kt@@ -0,0 +1,39 @@+package com.streamvault.domain.model++import com.streamvault.domain.model.Provider as StableProvider++import com.google.common.truth.Truth.assertThat+import org.junit.Test++class ProviderSnapshotTest {+ @Test(expected = IllegalArgumentException::class)+ fun `snapshot rejects mismatched configuration`() {+ ProviderSnapshot(+ provider = StableProvider(name = "p", type = ProviderType.M3U),+ configuration = JellyfinConfig("https://media.test", "u", "token"),+ configurationGeneration = 1+ )+ }++ @Test(expected = IllegalArgumentException::class)+ fun `learning rejects stale observations`() {+ StalkerPortalLearning(+ configurationGeneration = 2,+ profileId = StalkerObservation(+ value = "profile",+ configurationGeneration = 1,+ source = StalkerObservationSource.DISCOVERY,+ observedAt = 10+ )+ )+ }++ @Test+ fun `typed configuration exposes its fixed provider type`() {+ assertThat(XtreamConfig("https://x.test", "u", "p").type).isEqualTo(ProviderType.XTREAM_CODES)+ assertThat(M3uConfig("https://m.test/list.m3u").type).isEqualTo(ProviderType.M3U)+ assertThat(StalkerConfig("https://s.test", StalkerDeviceIdentity("00:11:22:33:44:55")).type)+ .isEqualTo(ProviderType.STALKER_PORTAL)+ assertThat(JellyfinConfig("https://j.test", "u", "t").type).isEqualTo(ProviderType.JELLYFIN)+ }+}diff --git a/domain/src/test/java/com/streamvault/domain/provider/ProviderCapabilityMatrixTest.kt b/domain/src/test/java/com/streamvault/domain/provider/ProviderCapabilityMatrixTest.ktnew file mode 100644index 00000000..55c3878c--- /dev/null+++ b/domain/src/test/java/com/streamvault/domain/provider/ProviderCapabilityMatrixTest.kt@@ -0,0 +1,28 @@+package com.streamvault.domain.provider++import com.google.common.truth.Truth.assertThat+import com.streamvault.domain.model.ProviderType+import org.junit.Test++class ProviderCapabilityMatrixTest {+ @Test+ fun `capability matrix is exact for every provider type`() {+ assertThat(ProviderCapabilityMatrix.potentialCapabilities(ProviderType.XTREAM_CODES))+ .containsExactlyElementsIn(ProviderCapability.entries)+ assertThat(ProviderCapabilityMatrix.potentialCapabilities(ProviderType.STALKER_PORTAL))+ .containsExactlyElementsIn(ProviderCapability.entries)+ assertThat(ProviderCapabilityMatrix.potentialCapabilities(ProviderType.M3U)).containsExactly(+ ProviderCapability.LIVE_CATALOG,+ ProviderCapability.VOD_CATALOG,+ ProviderCapability.GUIDE,+ ProviderCapability.PLAYBACK,+ ProviderCapability.CATCH_UP+ )+ assertThat(ProviderCapabilityMatrix.potentialCapabilities(ProviderType.JELLYFIN)).containsExactly(+ ProviderCapability.AUTHENTICATION,+ ProviderCapability.VOD_CATALOG,+ ProviderCapability.SERIES_CATALOG,+ ProviderCapability.PLAYBACK+ )+ }+}diff --git a/domain/src/test/java/com/streamvault/domain/usecase/SyncProviderTest.kt b/domain/src/test/java/com/streamvault/domain/usecase/SyncProviderTest.ktindex 8c809965..12554c4b 100644--- a/domain/src/test/java/com/streamvault/domain/usecase/SyncProviderTest.kt+++ b/domain/src/test/java/com/streamvault/domain/usecase/SyncProviderTest.kt@@ -6,7 +6,7 @@ import com.streamvault.domain.manager.ProviderSyncStateReaderimport com.streamvault.domain.model.ChannelLogoSourcePolicyimport com.streamvault.domain.model.GuideSourcePolicyimport com.streamvault.domain.model.Program-import com.streamvault.domain.model.Provider+import com.streamvault.domain.model.LegacyProvider as Providerimport com.streamvault.domain.model.ProviderEpgSyncModeimport com.streamvault.domain.model.ProviderStatusimport com.streamvault.domain.model.ProviderType@@ -19,6 +19,7 @@ import com.streamvault.domain.model.StalkerTransportGrantimport com.streamvault.domain.model.SyncStateimport com.streamvault.domain.repository.ProviderDeleteProgressimport com.streamvault.domain.repository.ProviderRepository+import com.streamvault.domain.repository.ProviderSetupRequestimport kotlinx.coroutines.flow.Flowimport kotlinx.coroutines.flow.flowOfimport kotlinx.coroutines.test.runTest@@ -123,7 +124,13 @@ private class FakeSyncProviderRepository(override suspend fun setActiveProvider(id: Long): Result<Unit> = error("Not used in test")- override suspend fun loginXtream(+ override suspend fun setupProvider(+ request: ProviderSetupRequest,+ onProgress: ((String) -> Unit)?,+ onCode: ((String) -> Unit)?+ ): Result<Provider> = error("Not used in test")++ suspend fun loginXtream(serverUrl: String,username: String,password: String,@@ -139,7 +146,7 @@ private class FakeSyncProviderRepository(id: Long?): Result<Provider> = error("Not used in test")- override suspend fun validateM3u(+ suspend fun validateM3u(url: String,name: String,httpUserAgent: String,@@ -152,7 +159,7 @@ private class FakeSyncProviderRepository(id: Long?): Result<Provider> = error("Not used in test")- override suspend fun loginStalker(+ suspend fun loginStalker(portalUrl: String,macAddress: String,name: String,@@ -182,7 +189,7 @@ private class FakeSyncProviderRepository(id: Long?): Result<Provider> = error("Not used in test")- override suspend fun loginJellyfin(+ suspend fun loginJellyfin(serverUrl: String,username: String,password: String,@@ -191,7 +198,7 @@ private class FakeSyncProviderRepository(id: Long?): Result<Provider> = error("Not used in test")- override suspend fun loginJellyfinQuickConnect(+ suspend fun loginJellyfinQuickConnect(serverUrl: String,name: String,onCode: ((String) -> Unit)?,diff --git a/domain/src/test/java/com/streamvault/domain/usecase/ValidateAndAddProviderTest.kt b/domain/src/test/java/com/streamvault/domain/usecase/ValidateAndAddProviderTest.ktindex 4d0cb632..56d190da 100644--- a/domain/src/test/java/com/streamvault/domain/usecase/ValidateAndAddProviderTest.kt+++ b/domain/src/test/java/com/streamvault/domain/usecase/ValidateAndAddProviderTest.kt@@ -11,8 +11,10 @@ import com.streamvault.domain.manager.ValidatedStalkerProviderInputimport com.streamvault.domain.manager.ValidatedXtreamProviderInputimport com.streamvault.domain.model.ChannelLogoSourcePolicyimport com.streamvault.domain.model.GuideSourcePolicy+import com.streamvault.domain.model.JellyfinConfig+import com.streamvault.domain.model.M3uConfigimport com.streamvault.domain.model.ProviderEpgSyncMode-import com.streamvault.domain.model.Provider+import com.streamvault.domain.model.LegacyProvider as Providerimport com.streamvault.domain.model.ProviderSavedWithSyncErrorExceptionimport com.streamvault.domain.model.ProviderStatusimport com.streamvault.domain.model.ProviderType@@ -29,8 +31,11 @@ import com.streamvault.domain.model.StalkerTransportConsentRequiredExceptionimport com.streamvault.domain.model.StalkerTransportGrantimport com.streamvault.domain.model.StalkerTransportModeimport com.streamvault.domain.model.StalkerTransportOrigin+import com.streamvault.domain.model.StalkerConfig+import com.streamvault.domain.model.XtreamConfigimport com.streamvault.domain.repository.ProviderDeleteProgressimport com.streamvault.domain.repository.ProviderRepository+import com.streamvault.domain.repository.ProviderSetupRequestimport kotlinx.coroutines.flow.Flowimport kotlinx.coroutines.flow.flowOfimport kotlinx.coroutines.test.runTest@@ -767,7 +772,45 @@ private class FakeProviderRepository : ProviderRepository {override suspend fun setActiveProvider(id: Long): Result<Unit> = error("Not used in test")- override suspend fun loginXtream(+ override suspend fun setupProvider(+ request: ProviderSetupRequest,+ onProgress: ((String) -> Unit)?,+ onCode: ((String) -> Unit)?+ ): Result<Provider> = when (request) {+ is ProviderSetupRequest.Configured -> when (val config = request.configuration) {+ is XtreamConfig -> loginXtream(+ config.serverUrl, config.username, config.password, request.name,+ config.httpUserAgent, config.httpHeaders, config.fastSyncEnabled,+ config.epgSyncMode, config.liveSyncMode, config.guideSourcePolicy,+ config.channelLogoSourcePolicy, onProgress, request.existingProviderId+ )+ is M3uConfig -> validateM3u(+ config.playlistUrl, request.name, config.httpUserAgent, config.httpHeaders,+ config.epgSyncMode, config.vodClassificationEnabled, config.guideSourcePolicy,+ config.channelLogoSourcePolicy, onProgress, request.existingProviderId+ )+ is StalkerConfig -> loginStalker(+ config.portalUrl, config.device.macAddress, request.name, config.authMode,+ config.username, config.password, config.httpUserAgent, config.httpHeaders,+ config.device.deviceProfile, config.device.timezone, config.device.locale,+ config.device.serialNumber, config.device.deviceId, config.device.deviceId2,+ config.device.signature, config.advancedOptionsJson, config.protocolPreference,+ config.transportGrant, request.saveWithoutVerification, request.repairConnection,+ config.requestedProfileId, config.epgSyncMode, config.catalogMode,+ config.guideSourcePolicy, config.channelLogoSourcePolicy, onProgress,+ request.existingProviderId+ )+ is JellyfinConfig -> loginJellyfin(+ config.serverUrl, config.username, config.credential, request.name,+ onProgress, request.existingProviderId+ )+ }+ is ProviderSetupRequest.JellyfinQuickConnect -> loginJellyfinQuickConnect(+ request.serverUrl, request.name, onCode, onProgress, request.existingProviderId+ )+ }++ suspend fun loginXtream(serverUrl: String,username: String,password: String,@@ -786,7 +829,7 @@ private class FakeProviderRepository : ProviderRepository {return xtreamResult ?: Result.success(provider(id = id ?: 1L, name = name, type = ProviderType.XTREAM_CODES))}- override suspend fun validateM3u(+ suspend fun validateM3u(url: String,name: String,httpUserAgent: String,@@ -802,7 +845,7 @@ private class FakeProviderRepository : ProviderRepository {return m3uResult ?: Result.success(provider(id = id ?: 2L, name = name, type = ProviderType.M3U, m3uUrl = url))}- override suspend fun loginStalker(+ suspend fun loginStalker(portalUrl: String,macAddress: String,name: String,@@ -876,7 +919,7 @@ private class FakeProviderRepository : ProviderRepository {)}- override suspend fun loginJellyfin(+ suspend fun loginJellyfin(serverUrl: String,username: String,password: String,@@ -893,7 +936,7 @@ private class FakeProviderRepository : ProviderRepository {)}- override suspend fun loginJellyfinQuickConnect(+ suspend fun loginJellyfinQuickConnect(serverUrl: String,name: String,onCode: ((String) -> Unit)?,