StreamVault is a TV-first free IPTV player for Android TV built with Kotlin, Jetpack Compose, Room, Hilt, and Media3.
Kotlin iptv-player
feat: Implement migration support and playback observation enhancements
David Nashash855e073e32be
diff --git a/app/src/androidTest/java/com/streamvault/app/ui/PlayerSmokeTest.kt b/app/src/androidTest/java/com/streamvault/app/ui/PlayerSmokeTest.ktindex 91f2cebd..a30c5b6b 100644--- a/app/src/androidTest/java/com/streamvault/app/ui/PlayerSmokeTest.kt+++ b/app/src/androidTest/java/com/streamvault/app/ui/PlayerSmokeTest.kt@@ -68,6 +68,7 @@ class PlayerSmokeTest {contentType = "MOVIE",isPlaying = false,currentProgram = null,+ currentChannel = null,currentChannelName = null,displayChannelNumber = TestFixtures.displayChannelNumber,currentPosition = TestFixtures.currentPositionMs,@@ -116,6 +117,7 @@ class PlayerSmokeTest {contentType = "LIVE",isPlaying = true,currentProgram = null,+ currentChannel = null,currentChannelName = TestFixtures.liveTitle,displayChannelNumber = TestFixtures.displayChannelNumber,currentPosition = 0L,diff --git a/app/src/androidTest/java/com/streamvault/app/ui/PremiumRouteGoldenTest.kt b/app/src/androidTest/java/com/streamvault/app/ui/PremiumRouteGoldenTest.ktindex be2eefb6..439445ab 100644--- a/app/src/androidTest/java/com/streamvault/app/ui/PremiumRouteGoldenTest.kt+++ b/app/src/androidTest/java/com/streamvault/app/ui/PremiumRouteGoldenTest.kt@@ -273,7 +273,10 @@ class PremiumRouteGoldenTest {) {Column(modifier = Modifier.weight(1f)) {AppScreenScaffold(- currentRoute = Routes.FAVORITES,+ // Saved Library is no longer a top-level navigation destination.+ // Keep this visual fixture unselected instead of highlighting an+ // unrelated production route.+ currentRoute = "saved_library_golden_fixture",onNavigate = {},title = "Saved",subtitle = "Manage favorite channels, movies, and series from one premium hub."diff --git a/app/src/androidTest/java/com/streamvault/app/ui/screens/player/overlay/PlayerOverlayGoldenTest.kt b/app/src/androidTest/java/com/streamvault/app/ui/screens/player/overlay/PlayerOverlayGoldenTest.ktindex d29ebe62..d81b322f 100644--- a/app/src/androidTest/java/com/streamvault/app/ui/screens/player/overlay/PlayerOverlayGoldenTest.kt+++ b/app/src/androidTest/java/com/streamvault/app/ui/screens/player/overlay/PlayerOverlayGoldenTest.kt@@ -38,6 +38,7 @@ class PlayerOverlayGoldenTest {contentType = "MOVIE",isPlaying = true,currentProgram = null,+ currentChannel = null,currentChannelName = null,displayChannelNumber = TestFixtures.displayChannelNumber,currentPosition = TestFixtures.currentPositionMs,diff --git a/app/src/main/java/com/streamvault/app/di/RepositoryModule.kt b/app/src/main/java/com/streamvault/app/di/RepositoryModule.ktindex 6fa5d316..ff566fd5 100644--- a/app/src/main/java/com/streamvault/app/di/RepositoryModule.kt+++ b/app/src/main/java/com/streamvault/app/di/RepositoryModule.kt@@ -18,6 +18,8 @@ import com.streamvault.data.provider.JellyfinCapabilityFactoryimport com.streamvault.data.provider.M3uCapabilityFactoryimport com.streamvault.data.provider.StalkerCapabilityFactoryimport com.streamvault.data.provider.XtreamCapabilityFactory+import com.streamvault.data.remote.xtream.PlaybackObservationCoordinator+import com.streamvault.data.remote.xtream.PlaybackObservationSinkimport com.streamvault.data.validation.ProviderSetupInputValidatorImplimport com.streamvault.domain.manager.ParentalPinVerifierimport com.streamvault.domain.manager.ProviderSetupInputValidator@@ -26,6 +28,8 @@ import com.streamvault.data.repository.*import com.streamvault.domain.manager.ParentalControlSessionStoreimport com.streamvault.domain.repository.*import com.streamvault.domain.provider.ProviderCapabilityRegistry+import com.streamvault.domain.provider.ProviderSourceRegistry+import com.streamvault.app.plugins.StreamVaultPluginManagerimport dagger.Bindsimport dagger.Moduleimport dagger.Provides@@ -133,6 +137,12 @@ abstract class RepositoryModule {@Binds @Singletonabstract fun bindCredentialCrypto(impl: AndroidKeystoreCredentialCrypto): CredentialCrypto+ @Binds @Singleton+ abstract fun bindProviderSourceRegistry(impl: StreamVaultPluginManager): ProviderSourceRegistry++ @Binds @Singleton+ abstract fun bindPlaybackObservationSink(impl: PlaybackObservationCoordinator): PlaybackObservationSink+companion object {@Provides@Singletondiff --git a/app/src/main/java/com/streamvault/app/plugins/PluginModels.kt b/app/src/main/java/com/streamvault/app/plugins/PluginModels.ktindex 913138c0..06677cd9 100644--- a/app/src/main/java/com/streamvault/app/plugins/PluginModels.kt+++ b/app/src/main/java/com/streamvault/app/plugins/PluginModels.kt@@ -47,12 +47,21 @@ data class InstalledStreamVaultPlugin(val manifest: StreamVaultPluginManifest,val enabled: Boolean,val statusLabel: String = "",- val lastMessage: String = ""+ val lastMessage: String = "",+ val discoveryState: PluginDiscoveryState = PluginDiscoveryState.READY) {val displayName: Stringget() = manifest.name.ifBlank { appLabel.ifBlank { packageName } }}+enum class PluginDiscoveryState { LOADING, READY, PARTIAL, TIMED_OUT, ERROR }++data class PluginDiscoveryStatus(+ val state: PluginDiscoveryState,+ val message: String = ""+)++data class StreamVaultPluginOwner(val packageName: String,val serviceClassName: String,diff --git a/app/src/main/java/com/streamvault/app/plugins/PluginWorkCoordinator.kt b/app/src/main/java/com/streamvault/app/plugins/PluginWorkCoordinator.ktnew file mode 100644index 00000000..d99ad6a8--- /dev/null+++ b/app/src/main/java/com/streamvault/app/plugins/PluginWorkCoordinator.kt@@ -0,0 +1,52 @@+package com.streamvault.app.plugins++import javax.inject.Inject+import javax.inject.Singleton+import kotlinx.coroutines.CancellationException+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.Job+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.asStateFlow+import kotlinx.coroutines.launch++/** Application-lifetime owner for non-durable plugin reconciliation and catalog refresh work. */+@Singleton+class PluginWorkCoordinator @Inject constructor() {+ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)+ private val lock = Any()+ private var catalogRefreshJob: Job? = null+ private val _catalogRefreshRunning = MutableStateFlow(false)+ val catalogRefreshRunning: StateFlow<Boolean> = _catalogRefreshRunning.asStateFlow()++ fun launchReconciliation(block: suspend () -> Unit): Job = scope.launch { runSafely(block) }++ fun replaceCatalogRefresh(block: suspend () -> Unit) {+ synchronized(lock) {+ catalogRefreshJob?.cancel()+ catalogRefreshJob = scope.launch {+ _catalogRefreshRunning.value = true+ try {+ runSafely(block)+ } finally {+ _catalogRefreshRunning.value = false+ synchronized(lock) {+ if (catalogRefreshJob === coroutineContext[Job]) catalogRefreshJob = null+ }+ }+ }+ }+ }++ private suspend fun runSafely(block: suspend () -> Unit) {+ try {+ block()+ } catch (cancelled: CancellationException) {+ throw cancelled+ } catch (_: Exception) {+ // Startup/package lifecycle reconciliation is the retry boundary.+ }+ }+}diff --git a/app/src/main/java/com/streamvault/app/plugins/StreamVaultPluginManager.kt b/app/src/main/java/com/streamvault/app/plugins/StreamVaultPluginManager.ktindex 334ccafe..4ddcefa0 100644--- a/app/src/main/java/com/streamvault/app/plugins/StreamVaultPluginManager.kt+++ b/app/src/main/java/com/streamvault/app/plugins/StreamVaultPluginManager.kt@@ -26,6 +26,11 @@ import com.streamvault.domain.model.DrmSchemeimport com.streamvault.domain.model.M3uConfigimport com.streamvault.domain.model.LegacyProvider as Providerimport com.streamvault.domain.model.ProviderEpgSyncMode+import com.streamvault.domain.model.ProviderType+import com.streamvault.domain.provider.PluginProviderSource+import com.streamvault.domain.provider.PluginSourceIdentity+import com.streamvault.domain.provider.ProviderSource+import com.streamvault.domain.provider.ProviderSourceRegistryimport com.streamvault.domain.model.Resultimport com.streamvault.domain.model.StreamInfoimport com.streamvault.domain.model.StreamType@@ -39,18 +44,20 @@ import javax.inject.Injectimport javax.inject.Singletonimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.CancellationException-import kotlinx.coroutines.CoroutineScope-import kotlinx.coroutines.CoroutineStart-import kotlinx.coroutines.SupervisorJobimport kotlinx.coroutines.asyncimport kotlinx.coroutines.awaitAllimport kotlinx.coroutines.coroutineScope-import kotlinx.coroutines.currentCoroutineContext-import kotlinx.coroutines.Jobimport kotlinx.coroutines.flow.first+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.asStateFlow+import kotlinx.coroutines.flow.updateimport kotlinx.coroutines.launch+import kotlinx.coroutines.supervisorScopeimport kotlinx.coroutines.withContextimport kotlinx.coroutines.withTimeoutOrNull+import kotlinx.coroutines.sync.Mutex+import kotlinx.coroutines.sync.withLockimport kotlinx.serialization.json.Jsonimport kotlinx.serialization.json.JsonObjectimport okhttp3.OkHttpClient@@ -65,14 +72,17 @@ class StreamVaultPluginManager @Inject constructor(private val pluginProviderOwnershipDao: PluginProviderOwnershipDao,private val combinedM3uRepository: CombinedM3uRepository,private val tvInputChannelSyncManager: TvInputChannelSyncManager,+ private val pluginWorkCoordinator: PluginWorkCoordinator,private val okHttpClient: OkHttpClient,private val json: Json-) {+) : ProviderSourceRegistry {private val prefs = context.getSharedPreferences("streamvault_plugins", Context.MODE_PRIVATE)private val discoveryLock = Any()- private val backgroundScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)- private val refreshLock = Any()- private var refreshJob: Job? = null+ private val pluginMutationMutex = Mutex()+ private val _discoveryStates =+ MutableStateFlow<Map<StreamVaultPluginComponent, PluginDiscoveryStatus>>(emptyMap())+ val discoveryStates: StateFlow<Map<StreamVaultPluginComponent, PluginDiscoveryStatus>> =+ _discoveryStates.asStateFlow()@Volatileprivate var cachedDiscovery: List<InstalledStreamVaultPlugin>? = null@@ -86,7 +96,7 @@ class StreamVaultPluginManager @Inject constructor(// Package broadcasts are the authoritative lifecycle signal. Reconcile immediately// instead of waiting for the next process start, especially after external uninstall.val pendingResult = goAsync()- backgroundScope.launch {+ pluginWorkCoordinator.launchReconciliation {try {reconcilePluginProviders()} catch (cancelled: CancellationException) {@@ -118,16 +128,68 @@ class StreamVaultPluginManager @Inject constructor(suspend fun discoverPlugins(): List<InstalledStreamVaultPlugin> = withContext(Dispatchers.IO) {cachedDiscovery?.takeIf { System.currentTimeMillis() < discoveryExpiresAtMillis }?.let { return@withContext it }val resolveInfos = queryPluginServices()- val plugins = (withTimeoutOrNull(DISCOVERY_TOTAL_TIMEOUT_MILLIS) {- coroutineScope {- resolveInfos- .map { resolveInfo -> async { resolvePlugin(resolveInfo) } }- .awaitAll()- .filterNotNull()+ _discoveryStates.value = resolveInfos.mapNotNull(::componentOf)+ .associateWith { PluginDiscoveryStatus(PluginDiscoveryState.LOADING) }+ val plugins = supervisorScope {+ // Each service has its own bound, so one dead service cannot erase results from+ // services that already completed. Since all requests run concurrently, this is also+ // a bounded global discovery window independent of the number of installed plugins.+ val jobs = resolveInfos.map { resolveInfo ->+ async {+ val component = componentOf(resolveInfo)+ val attempt = withTimeoutOrNull(DISCOVERY_PLUGIN_TIMEOUT_MILLIS) {+ runPluginCatching { resolvePlugin(resolveInfo) }+ }+ when {+ attempt == null -> {+ component?.let { key ->+ _discoveryStates.update {+ it + (key to PluginDiscoveryStatus(+ PluginDiscoveryState.TIMED_OUT,+ "Plugin discovery timed out"+ ))+ }+ }+ metadataOnlyPlugin(+ resolveInfo,+ "Plugin discovery timed out",+ PluginDiscoveryState.TIMED_OUT+ )+ }+ attempt.isFailure -> {+ val error = attempt.exceptionOrNull()+ component?.let { key ->+ _discoveryStates.update {+ it + (key to PluginDiscoveryStatus(+ PluginDiscoveryState.ERROR,+ error?.message.orEmpty()+ ))+ }+ }+ metadataOnlyPlugin(+ resolveInfo,+ error?.message.orEmpty().ifBlank { "Plugin discovery failed" },+ PluginDiscoveryState.ERROR+ )+ }+ else -> attempt.getOrNull().also { plugin ->+ if (component != null && plugin != null) {+ _discoveryStates.update {+ it + (component to PluginDiscoveryStatus(+ plugin.discoveryState,+ plugin.lastMessage+ ))+ }+ }+ }+ }+ }}- } ?: resolveInfos.mapNotNull { resolveInfo ->- metadataOnlyPlugin(resolveInfo, "Plugin discovery timed out")- })+ // The per-service timeout is also the global bound because all services are queried+ // concurrently. Most importantly, awaitAll preserves completed services when one+ // peer times out instead of replacing the whole result set.+ jobs.awaitAll().filterNotNull()+ }.sortedBy { it.displayName.lowercase() }migrateLegacyEnabledStates(plugins)plugins.map { plugin -> plugin.copy(enabled = isEnabled(plugin)) }.also { discovered ->@@ -145,14 +207,59 @@ class StreamVaultPluginManager @Inject constructor(* malformed update, or manifest-ID rename is not proof that its provider is orphaned.*/suspend fun reconcilePluginProviders() = withContext(Dispatchers.IO) {- val installedComponents = queryPluginServices().mapNotNull { resolveInfo ->- val serviceInfo = resolveInfo.serviceInfo ?: return@mapNotNull null- val packageName = serviceInfo.packageName ?: return@mapNotNull null- val serviceName = serviceInfo.name ?: return@mapNotNull null- StreamVaultPluginComponent(packageName, serviceName)- }.toSet()- orphanedPluginOwnerships(pluginProviderOwnershipDao.getAll(), installedComponents)- .forEach { ownership -> removeOwnedProvider(ownership) }+ pluginMutationMutex.withLock {+ val installedComponents = queryPluginServices().mapNotNull { resolveInfo ->+ componentOf(resolveInfo)+ }.toSet()+ orphanedPluginOwnerships(pluginProviderOwnershipDao.getAll(), installedComponents)+ .forEach { ownership ->+ if (removeOwnedProvider(ownership) == null) {+ clearPendingMutation(+ StreamVaultPluginOwner(+ ownership.packageName,+ ownership.serviceClassName,+ ownership.manifestId+ )+ )+ }+ }+ clearPendingMutationsForMissingComponents(installedComponents)++ // A mutation checkpoint is written before contacting a plugin. Replaying it here+ // closes process-death windows between remote enable/disable, provider import, and+ // ownership persistence. An enabled source with missing ownership is also repaired.+ discoverPlugins().forEach { plugin ->+ val pending = pendingMutation(plugin.owner)+ val desiredEnabled = pending ?: isEnabled(plugin)+ if (pending != null) {+ val response = runPluginCatching {+ sendEnabledCommand(plugin, desiredEnabled)+ }.getOrNull() ?: return@forEach+ if (!response.getBoolean(StreamVaultPluginContract.KEY_SUCCESS, true)) {+ clearPendingMutation(plugin.owner)+ return@forEach+ }+ prefs.edit().putBoolean(enabledKey(plugin.owner), desiredEnabled).apply()+ }+ if (!plugin.manifest.hasCapability(StreamVaultPluginContract.CAPABILITY_PROVIDER_M3U)) {+ if (pending != null) clearPendingMutation(plugin.owner)+ return@forEach+ }+ if (desiredEnabled) {+ if (pending != null || trackedOwnership(plugin) == null) {+ if (syncPluginProvider(plugin, onProgress = {}) == null) {+ prefs.edit().putBoolean(enabledKey(plugin.owner), true).apply()+ clearPendingMutation(plugin.owner)+ }+ }+ } else if (pending != null) {+ if (removePluginProvider(plugin) == null) {+ prefs.edit().putBoolean(enabledKey(plugin.owner), false).apply()+ clearPendingMutation(plugin.owner)+ }+ }+ }+ }}suspend fun setPluginEnabled(@@ -160,23 +267,19 @@ class StreamVaultPluginManager @Inject constructor(enabled: Boolean,onProgress: (String) -> Unit = {}): PluginActionResult = withContext(Dispatchers.IO) {- val command = Bundle().apply {- putBoolean(StreamVaultPluginContract.KEY_ENABLED, enabled)+ pluginMutationMutex.withLock mutation@{+ if (!recordPendingMutation(plugin.owner, enabled)) {+ return@mutation PluginActionResult(false, "Could not persist plugin operation checkpoint")}val response = runPluginCatching {- messengerClient.send(- packageName = plugin.packageName,- serviceClassName = plugin.serviceClassName,- what = StreamVaultPluginContract.MSG_SET_ENABLED,- data = command,- timeoutMillis = 120_000L- )+ sendEnabledCommand(plugin, enabled)}.getOrElse { error ->- return@withContext PluginActionResult(false, error.message ?: "Plugin did not respond")+ return@mutation PluginActionResult(false, error.message ?: "Plugin did not respond")}if (!response.getBoolean(StreamVaultPluginContract.KEY_SUCCESS, true)) {- return@withContext PluginActionResult(+ clearPendingMutation(plugin.owner)+ return@mutation PluginActionResult(success = false,message = response.getString(StreamVaultPluginContract.KEY_MESSAGE).orEmpty().ifBlank { "Plugin rejected the request" }@@ -185,16 +288,19 @@ class StreamVaultPluginManager @Inject constructor(prefs.edit().putBoolean(enabledKey(plugin.owner), enabled).apply()if (enabled && plugin.manifest.hasCapability(StreamVaultPluginContract.CAPABILITY_PROVIDER_M3U)) {- syncPluginProvider(plugin, onProgress)?.let { return@withContext it }+ syncPluginProvider(plugin, onProgress)?.let { return@mutation it }} else if (!enabled) {- removePluginProvider(plugin)?.let { return@withContext it }+ removePluginProvider(plugin)?.let { return@mutation it }}+ clearPendingMutation(plugin.owner)+ invalidateDiscovery()PluginActionResult(success = true,message = response.getString(StreamVaultPluginContract.KEY_MESSAGE).orEmpty().ifBlank { if (enabled) "Plugin activated" else "Plugin deactivated" })+ }}suspend fun installApkFromUri(uri: Uri): Result<Unit> = withContext(Dispatchers.IO) {@@ -632,6 +738,19 @@ class StreamVaultPluginManager @Inject constructor(return null}+ private suspend fun sendEnabledCommand(+ plugin: InstalledStreamVaultPlugin,+ enabled: Boolean+ ): Bundle = messengerClient.send(+ packageName = plugin.packageName,+ serviceClassName = plugin.serviceClassName,+ what = StreamVaultPluginContract.MSG_SET_ENABLED,+ data = Bundle().apply {+ putBoolean(StreamVaultPluginContract.KEY_ENABLED, enabled)+ },+ timeoutMillis = 120_000L+ )+private suspend fun removePluginProvider(plugin: InstalledStreamVaultPlugin): PluginActionResult? {val ownership = trackedOwnership(plugin) ?: return nullreturn removeOwnedProvider(ownership)@@ -676,29 +795,31 @@ class StreamVaultPluginManager @Inject constructor(}private fun refreshTvInputCatalogInBackground() {- synchronized(refreshLock) {- refreshJob?.cancel()- val newJob = backgroundScope.launch(start = CoroutineStart.LAZY) {- try {- tvInputChannelSyncManager.refreshTvInputCatalog()- } catch (cancelled: CancellationException) {- throw cancelled- } catch (_: Exception) {- // Best-effort catalog refresh; the next provider/plugin change retries it.- } finally {- val completedJob = currentCoroutineContext()[Job]- synchronized(refreshLock) {- if (refreshJob === completedJob) {- refreshJob = null- }- }- }- }- refreshJob = newJob- newJob.start()+ pluginWorkCoordinator.replaceCatalogRefresh(tvInputChannelSyncManager::refreshTvInputCatalog)+ }++ override suspend fun sources(): List<ProviderSource> = withContext(Dispatchers.IO) {+ val pluginsByComponent = discoverPlugins().associateBy { it.owner.component }+ pluginProviderOwnershipDao.getAll().mapNotNull { ownership ->+ val component = StreamVaultPluginComponent(ownership.packageName, ownership.serviceClassName)+ val plugin = pluginsByComponent[component] ?: return@mapNotNull null+ PluginProviderSource(+ identity = PluginSourceIdentity(+ packageName = plugin.packageName,+ serviceClassName = plugin.serviceClassName,+ manifestId = plugin.manifest.id+ ),+ providerId = ownership.providerId,+ enabled = plugin.enabled,+ capabilities = plugin.manifest.capabilities.toSet(),+ backingProviderType = ProviderType.M3U+ )}}+ suspend fun pluginProviderSources(): List<PluginProviderSource> =+ sources().filterIsInstance<PluginProviderSource>()+private suspend fun resolvePlugin(resolveInfo: ResolveInfo): InstalledStreamVaultPlugin? = coroutineScope {val serviceInfo = resolveInfo.serviceInfo ?: return@coroutineScope nullval packageName = serviceInfo.packageName ?: return@coroutineScope null@@ -731,13 +852,19 @@ class StreamVaultPluginManager @Inject constructor(manifest = manifest,enabled = false,statusLabel = status?.getString(StreamVaultPluginContract.KEY_STATUS_LABEL).orEmpty(),- lastMessage = status?.getString(StreamVaultPluginContract.KEY_MESSAGE).orEmpty()+ lastMessage = status?.getString(StreamVaultPluginContract.KEY_MESSAGE).orEmpty(),+ discoveryState = if (status == null || manifestResult.await() == null) {+ PluginDiscoveryState.PARTIAL+ } else {+ PluginDiscoveryState.READY+ })}private fun metadataOnlyPlugin(resolveInfo: ResolveInfo,- errorMessage: String+ errorMessage: String,+ discoveryState: PluginDiscoveryState = PluginDiscoveryState.TIMED_OUT): InstalledStreamVaultPlugin? {val serviceInfo = resolveInfo.serviceInfo ?: return nullval packageName = serviceInfo.packageName ?: return null@@ -755,7 +882,8 @@ class StreamVaultPluginManager @Inject constructor(appLabel = appLabel,manifest = manifest,enabled = false,- lastMessage = errorMessage+ lastMessage = errorMessage,+ discoveryState = discoveryState)}@@ -816,6 +944,13 @@ class StreamVaultPluginManager @Inject constructor(}}+ private fun componentOf(resolveInfo: ResolveInfo): StreamVaultPluginComponent? {+ val serviceInfo = resolveInfo.serviceInfo ?: return null+ val packageName = serviceInfo.packageName ?: return null+ val serviceName = serviceInfo.name ?: return null+ return StreamVaultPluginComponent(packageName, serviceName)+ }+private fun launchPackageInstaller(apkFile: File): Result<Unit> {if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && !context.packageManager.canRequestPackageInstalls()) {val settingsIntent = Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES).apply {@@ -922,14 +1057,47 @@ class StreamVaultPluginManager @Inject constructor(private fun enabledKey(owner: StreamVaultPluginOwner): String ="enabled.${owner.packageName}.${owner.serviceClassName}.${owner.manifestId}"+ private fun pendingMutationKey(owner: StreamVaultPluginOwner): String =+ "pending.${owner.packageName}|${owner.serviceClassName}|${owner.manifestId}"++ private fun recordPendingMutation(owner: StreamVaultPluginOwner, enabled: Boolean): Boolean =+ prefs.edit().putBoolean(pendingMutationKey(owner), enabled).commit()++ private fun pendingMutation(owner: StreamVaultPluginOwner): Boolean? =+ pendingMutationKey(owner).let { key ->+ if (prefs.contains(key)) prefs.getBoolean(key, false) else null+ }++ private fun clearPendingMutation(owner: StreamVaultPluginOwner) {+ prefs.edit().remove(pendingMutationKey(owner)).apply()+ }++ private fun clearPendingMutationsForMissingComponents(+ installedComponents: Set<StreamVaultPluginComponent>+ ) {+ val editor = prefs.edit()+ prefs.all.keys.asSequence()+ .filter { it.startsWith(PENDING_MUTATION_PREFIX) }+ .forEach { key ->+ val identity = key.removePrefix(PENDING_MUTATION_PREFIX).split('|', limit = 3)+ if (identity.size < 2 ||+ StreamVaultPluginComponent(identity[0], identity[1]) !in installedComponents+ ) {+ editor.remove(key)+ }+ }+ editor.apply()+ }+private fun legacyEnabledKey(pluginId: String): String = "enabled.$pluginId"private companion object {const val DISCOVERY_CACHE_TTL_MILLIS = 30_000Lconst val DISCOVERY_REQUEST_TIMEOUT_MILLIS = 1_500L- const val DISCOVERY_TOTAL_TIMEOUT_MILLIS = 5_000L+ const val DISCOVERY_PLUGIN_TIMEOUT_MILLIS = 2_500Lconst val PLAYBACK_HANDLER_TIMEOUT_MILLIS = 5_000Lconst val PLAYBACK_TOTAL_TIMEOUT_MILLIS = 5_000L+ const val PENDING_MUTATION_PREFIX = "pending."}}diff --git a/app/src/main/java/com/streamvault/app/tvinput/StreamVaultTvInputService.kt b/app/src/main/java/com/streamvault/app/tvinput/StreamVaultTvInputService.ktindex b33f3cb2..49440629 100644--- a/app/src/main/java/com/streamvault/app/tvinput/StreamVaultTvInputService.kt+++ b/app/src/main/java/com/streamvault/app/tvinput/StreamVaultTvInputService.kt@@ -22,6 +22,7 @@ import androidx.media3.exoplayer.source.MediaSourceimport androidx.media3.exoplayer.source.ProgressiveMediaSourceimport com.streamvault.domain.model.Channelimport com.streamvault.domain.model.StreamInfo+import com.streamvault.domain.util.BoundedExpiringCacheimport com.streamvault.domain.model.StreamTypeimport com.streamvault.domain.repository.ChannelRepositoryimport com.streamvault.player.playback.applyUnsafeTlsBypass@@ -35,7 +36,6 @@ import kotlinx.coroutines.launchimport kotlinx.coroutines.withContextimport java.net.InetSocketAddressimport java.net.Proxy-import java.util.concurrent.ConcurrentHashMapimport okhttp3.OkHttpClientimport javax.inject.Inject@@ -48,7 +48,13 @@ class StreamVaultTvInputService : TvInputService() {@Injectlateinit var okHttpClient: OkHttpClient- private val playbackClients = ConcurrentHashMap<PlaybackClientKey, OkHttpClient>()+ // TV input sessions can observe many proxy/transport combinations over the service+ // lifetime. Keep only a small, expiring set of derived clients; eviction drops the cache+ // reference and never closes a client that may still be serving an active tune.+ private val playbackClients = BoundedExpiringCache<PlaybackClientKey, OkHttpClient>(+ maxEntries = 8,+ ttlMillis = 15L * 60L * 1_000L+ )override fun onCreateSession(inputId: String): Session = StreamVaultSession(this)@@ -197,7 +203,7 @@ class StreamVaultTvInputService : TvInputService() {proxyHost = streamInfo.proxyHost.trim(),proxyPort = streamInfo.proxyPort)- return playbackClients.computeIfAbsent(key) {+ return playbackClients.getOrPut(key) {newBuilder().apply {val transportPolicy = streamInfo.playbackTransportPolicydiff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerContentResolutionSupport.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerContentResolutionSupport.ktindex a0a08f11..41ff8bdc 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerContentResolutionSupport.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerContentResolutionSupport.kt@@ -161,7 +161,7 @@ internal suspend fun resolvePlayerPlaybackStreamInfo(}try {- xtreamStreamUrlResolver.resolveWithMetadata(+ xtreamStreamUrlResolver.resolveAndCommitMetadata(url = logicalUrl,fallbackProviderId = providerId.takeIf { it > 0 },fallbackStreamId = fallbackStreamId,diff --git a/app/src/main/java/com/streamvault/app/ui/screens/plugins/PluginsScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/plugins/PluginsScreen.ktindex 3ab8c076..73ec95ec 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/plugins/PluginsScreen.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/plugins/PluginsScreen.kt@@ -56,6 +56,7 @@ import com.streamvault.app.plugins.InstalledStreamVaultPluginimport com.streamvault.app.plugins.PluginConfigurationActionimport com.streamvault.app.plugins.PluginConfigurationFieldimport com.streamvault.app.plugins.PluginConfigurationSection+import com.streamvault.app.plugins.ownerimport com.streamvault.app.ui.components.dialogs.PremiumDialogimport com.streamvault.app.ui.components.dialogs.PremiumDialogFooterButtonimport com.streamvault.app.ui.components.shell.AppNavigationChrome@@ -149,6 +150,14 @@ fun PluginsScreen()}+ if (uiState.providerSources.isNotEmpty()) {+ Text(+ text = "${uiState.providerSources.size} plugin provider source(s) available",+ style = MaterialTheme.typography.bodySmall,+ color = AppColors.TextSecondary+ )+ }+LazyColumn(modifier = Modifier.fillMaxSize(),verticalArrangement = Arrangement.spacedBy(10.dp)@@ -162,10 +171,10 @@ fun PluginsScreen()}}- items(uiState.plugins, key = { it.manifest.id }) { plugin ->+ items(uiState.plugins, key = { it.owner }) { plugin ->PluginCard(plugin = plugin,- busy = uiState.activePluginId == plugin.manifest.id,+ busy = uiState.activePluginOwner == plugin.owner,onEnabledChange = { enabled -> viewModel.setPluginEnabled(plugin, enabled) },onOpenConfiguration = { viewModel.openPluginConfiguration(plugin) })diff --git a/app/src/main/java/com/streamvault/app/ui/screens/plugins/PluginsViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/plugins/PluginsViewModel.ktindex 00939013..25d935f0 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/plugins/PluginsViewModel.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/plugins/PluginsViewModel.kt@@ -8,7 +8,11 @@ import com.streamvault.app.plugins.PluginConfigurationActionimport com.streamvault.app.plugins.PluginConfigurationFieldimport com.streamvault.app.plugins.PluginConfigurationSchemaimport com.streamvault.app.plugins.StreamVaultPluginManager+import com.streamvault.app.plugins.StreamVaultPluginOwner+import com.streamvault.app.plugins.ownerimport com.streamvault.domain.model.Result+import com.streamvault.domain.provider.ProviderSource+import com.streamvault.domain.provider.ProviderSourceRegistryimport dagger.hilt.android.lifecycle.HiltViewModelimport javax.inject.Injectimport kotlinx.coroutines.flow.MutableStateFlow@@ -28,11 +32,12 @@ import kotlinx.serialization.json.putdata class PluginsUiState(val plugins: List<InstalledStreamVaultPlugin> = emptyList(),+ val providerSources: List<ProviderSource> = emptyList(),val installUrl: String = "",val isLoading: Boolean = false,val isInstalling: Boolean = false,val isConfigurationLoading: Boolean = false,- val activePluginId: String? = null,+ val activePluginOwner: StreamVaultPluginOwner? = null,val configuration: ActivePluginConfiguration? = null,val syncProgress: String? = null,val userMessage: String? = null@@ -53,7 +58,8 @@ data class ActivePluginConfiguration(@HiltViewModelclass PluginsViewModel @Inject constructor(- private val pluginManager: StreamVaultPluginManager+ private val pluginManager: StreamVaultPluginManager,+ private val providerSourceRegistry: ProviderSourceRegistry) : ViewModel() {private val _uiState = MutableStateFlow(PluginsUiState(isLoading = true))val uiState: StateFlow<PluginsUiState> = _uiState.asStateFlow()@@ -70,17 +76,19 @@ class PluginsViewModel @Inject constructor(viewModelScope.launch {_uiState.update { it.copy(isLoading = true, syncProgress = null) }val result = runCatching { pluginManager.discoverPlugins() }- _uiState.update {- it.copy(+ val sources = runCatching { providerSourceRegistry.sources() }+ _uiState.update { state ->+ state.copy(plugins = result.getOrDefault(emptyList()),+ providerSources = sources.getOrElse { state.providerSources },isLoading = false,- configuration = it.configuration?.let { configuration ->+ configuration = state.configuration?.let { configuration ->val refreshedPlugin = result.getOrDefault(emptyList())- .firstOrNull { plugin -> plugin.manifest.id == configuration.plugin.manifest.id }+ .firstOrNull { plugin -> plugin.owner == configuration.plugin.owner }?: configuration.pluginconfiguration.copy(plugin = refreshedPlugin)},- userMessage = result.exceptionOrNull()?.message+ userMessage = result.exceptionOrNull()?.message ?: sources.exceptionOrNull()?.message)}}@@ -123,7 +131,7 @@ class PluginsViewModel @Inject constructor(viewModelScope.launch {_uiState.update {it.copy(- activePluginId = plugin.manifest.id,+ activePluginOwner = plugin.owner,syncProgress = if (enabled) "Activating ${plugin.displayName}..." else "Deactivating ${plugin.displayName}...",userMessage = null)@@ -132,10 +140,13 @@ class PluginsViewModel @Inject constructor(_uiState.update { it.copy(syncProgress = progress) }}val refreshed = runCatching { pluginManager.discoverPlugins() }.getOrDefault(_uiState.value.plugins)+ val refreshedSources = runCatching { providerSourceRegistry.sources() }+ .getOrDefault(_uiState.value.providerSources)_uiState.update {it.copy(plugins = refreshed,- activePluginId = null,+ providerSources = refreshedSources,+ activePluginOwner = null,syncProgress = null,userMessage = result.message)@@ -154,7 +165,7 @@ class PluginsViewModel @Inject constructor(_uiState.update {it.copy(isConfigurationLoading = true,- activePluginId = plugin.manifest.id,+ activePluginOwner = plugin.owner,userMessage = null)}@@ -163,7 +174,7 @@ class PluginsViewModel @Inject constructor(_uiState.update {it.copy(isConfigurationLoading = false,- activePluginId = null,+ activePluginOwner = null,userMessage = result.message)}@@ -174,7 +185,7 @@ class PluginsViewModel @Inject constructor(_uiState.update {it.copy(isConfigurationLoading = false,- activePluginId = null,+ activePluginOwner = null,configuration = ActivePluginConfiguration(plugin = snapshot.plugin,schema = snapshot.schema,diff --git a/data/src/androidTest/java/com/streamvault/data/local/StreamVaultDatabaseMigrationTest.kt b/data/src/androidTest/java/com/streamvault/data/local/StreamVaultDatabaseMigrationTest.ktindex 27d68aae..b0dd4794 100644--- a/data/src/androidTest/java/com/streamvault/data/local/StreamVaultDatabaseMigrationTest.kt+++ b/data/src/androidTest/java/com/streamvault/data/local/StreamVaultDatabaseMigrationTest.kt@@ -25,6 +25,31 @@ class StreamVaultDatabaseMigrationTest {FrameworkSQLiteOpenHelperFactory())+ @Test+ fun everyExportedHistoricalSchemaMigratesToCurrent() {+ // Version 2 was never exported; validate every historical artifact that can ship.+ val exportedHistoricalVersions =+ (StreamVaultDatabaseMigrationRegistry.CURRENT_VERSION - 1 downTo 3).toList() + 1++ exportedHistoricalVersions.forEach { startVersion ->+ val databaseName = "streamvault-every-schema-$startVersion"+ migrationTestHelper.createDatabase(databaseName, startVersion).close()+ val pathToCurrent = StreamVaultDatabaseMigrationRegistry.all+ .filter { migration -> migration.startVersion >= startVersion }++ try {+ migrationTestHelper.runMigrationsAndValidate(+ databaseName,+ StreamVaultDatabaseMigrationRegistry.CURRENT_VERSION,+ true,+ *pathToCurrent.toTypedArray()+ ).close()+ } catch (error: Throwable) {+ throw AssertionError("Migration failed from exported schema v$startVersion", error)+ }+ }+ }+@Testfun migrate9To10_createsBackfillsAndMaintainsFtsTables() {migrationTestHelper.createDatabase(testDbName, 9).apply {@@ -145,10 +170,11 @@ class StreamVaultDatabaseMigrationTest {"""INSERT INTO providers (id, name, type, server_url, username, password, m3u_url, epg_url,+ stalker_mac_address, stalker_device_profile, stalker_device_timezone, stalker_device_locale,is_active, max_connections, allowed_output_formats_json, epg_sync_mode,xtream_fast_sync_enabled, m3u_vod_classification_enabled, status,last_synced_at, created_at- ) VALUES (1, 'Public Master Provider', 'XTREAM_CODES', 'https://provider.example.com', 'demo', 'secret', '', '', 1, 1, '[]', 'UPFRONT', 1, 0, 'ACTIVE', 0, 0)+ ) VALUES (1, 'Public Master Provider', 'XTREAM_CODES', 'https://provider.example.com', 'demo', 'secret', '', '', '', '', '', '', 1, 1, '[]', 'UPFRONT', 1, 0, 'ACTIVE', 0, 0)""".trimIndent())close()@@ -186,12 +212,13 @@ class StreamVaultDatabaseMigrationTest {"""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,is_active, max_connections, expiration_date, api_version, allowed_output_formats_json,epg_sync_mode, xtream_fast_sync_enabled, m3u_vod_classification_enabled, status,last_synced_at, created_at) VALUES (- 1, 'Provider', 'XTREAM_CODES', 'https://provider.example.com', 'demo', 'secret', '', '',+ 1, 'Provider', 'XTREAM_CODES', 'https://provider.example.com', 'demo', 'secret', '', '', '', '','', '', '', '', 1, 1, NULL, NULL, '[]','UPFRONT', 1, 0, 'ACTIVE', 0, 0)@@ -481,7 +508,7 @@ class StreamVaultDatabaseMigrationTest {}@Test- fun migrate32To33_backfillsMovieWatchCountAndAddsGlobalFavoritesIndex() {+ fun migrate32To33_backfillsMovieWatchCount() {migrationTestHelper.createDatabase("streamvault-32-33-test", 32).apply {execSQL("""@@ -527,14 +554,6 @@ class StreamVaultDatabaseMigrationTest {)assertEquals(6, countRows(migratedDb, "SELECT watch_count FROM movies WHERE id = 10"))- assertEquals(- 1,- countRows(- migratedDb,- "SELECT COUNT(*) FROM sqlite_master WHERE type = 'index' AND name = 'index_favorites_global_provider_id_content_type_content_id' AND sql LIKE '%WHERE group_id IS NULL%'"- )- )-migratedDb.close()}@@ -603,10 +622,11 @@ class StreamVaultDatabaseMigrationTest {"""INSERT INTO providers (id, name, type, server_url, username, password, m3u_url, epg_url,+ stalker_mac_address, stalker_device_profile, stalker_device_timezone, stalker_device_locale,is_active, max_connections, allowed_output_formats_json, epg_sync_mode,xtream_fast_sync_enabled, m3u_vod_classification_enabled, status,last_synced_at, created_at- ) VALUES (1, 'Provider', 'M3U', 'https://provider.example.com', '', '', '', '', 1, 1, '[]', 'UPFRONT', 0, 0, 'ACTIVE', 0, 0)+ ) VALUES (1, 'Provider', 'M3U', 'https://provider.example.com', '', '', '', '', '', '', '', '', 1, 1, '[]', 'UPFRONT', 0, 0, 'ACTIVE', 0, 0)""".trimIndent())execSQL(@@ -653,10 +673,11 @@ class StreamVaultDatabaseMigrationTest {"""INSERT INTO providers (id, name, type, server_url, username, password, m3u_url, epg_url,+ stalker_mac_address, stalker_device_profile, stalker_device_timezone, stalker_device_locale,is_active, max_connections, allowed_output_formats_json, epg_sync_mode,xtream_fast_sync_enabled, m3u_vod_classification_enabled, status,last_synced_at, created_at- ) VALUES (1, 'Provider', 'STALKER_PORTAL', 'https://provider.example.com', '', '', '', '', 1, 1, '[]', 'UPFRONT', 0, 0, 'ACTIVE', 0, 0)+ ) VALUES (1, 'Provider', 'STALKER_PORTAL', 'https://provider.example.com', '', '', '', '', '00:1A:79:00:00:01', 'MAG250', 'UTC', 'en', 1, 1, '[]', 'UPFRONT', 0, 0, 'ACTIVE', 0, 0)""".trimIndent())execSQL(@@ -1559,7 +1580,7 @@ class StreamVaultDatabaseMigrationTest {assertEquals(1, countRows(migratedDb, "SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = '$table'"))}assertEquals(1, countRows(migratedDb, "SELECT COUNT(*) FROM pragma_table_info('recording_runs') WHERE name = 'exact_alarm_armed'"))- assertEquals(1, countRows(migratedDb, "SELECT COUNT(*) FROM pragma_table_info('providers') WHERE name = 'xmltv_timezone_policy'"))+ assertEquals(1, countRows(migratedDb, "SELECT COUNT(*) FROM pragma_table_info('epg_sources') WHERE name = 'timezone_policy'"))migratedDb.close()}@@ -1668,7 +1689,7 @@ class StreamVaultDatabaseMigrationTest {'UNKNOWN',0,0)""".trimIndent(),- arrayOf(id, name, type, "seed://$id", "seed-$id", "seed-mac-$id")+ arrayOf<Any?>(id, name, type, "seed://$id", "seed-$id", "seed-mac-$id"))}@@ -1685,7 +1706,7 @@ class StreamVaultDatabaseMigrationTest {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)+ arrayOf<Any?>(id, streamId, name, providerId))}diff --git a/data/src/main/java/com/streamvault/data/local/FeatureMigrationsV49To75.kt b/data/src/main/java/com/streamvault/data/local/FeatureMigrationsV49To75.ktnew file mode 100644index 00000000..4ad01f1b--- /dev/null+++ b/data/src/main/java/com/streamvault/data/local/FeatureMigrationsV49To75.kt@@ -0,0 +1,1329 @@+@file:Suppress("PARAMETER_NAME_CHANGED_ON_OVERRIDE", "TYPE_INTERSECTION_AS_REIFIED")++package com.streamvault.data.local++import androidx.room.migration.Migration+import androidx.sqlite.db.SupportSQLiteDatabase+import org.json.JSONObject+import java.net.URI+import java.security.MessageDigest++/** Provider runtime, workflow, backup, plugin ownership, and typed-configuration migrations (v49 through v75). Executable bodies live here, outside the Room schema declaration. */+internal object FeatureMigrationsV49To75 {+ val MIGRATION_49_50 = object : Migration(49, 50) {+ override fun migrate(database: SupportSQLiteDatabase) {+ database.execSQL(+ """+ CREATE TABLE IF NOT EXISTS xtream_live_onboarding_state (+ provider_id INTEGER NOT NULL,+ provider_type TEXT NOT NULL DEFAULT 'XTREAM_CODES',+ content_type TEXT NOT NULL DEFAULT 'LIVE',+ phase TEXT NOT NULL DEFAULT 'STARTING',+ staged_session_id INTEGER,+ import_strategy TEXT,+ next_category_index INTEGER NOT NULL DEFAULT 0,+ accepted_row_count INTEGER NOT NULL DEFAULT 0,+ staged_flush_count INTEGER NOT NULL DEFAULT 0,+ last_error TEXT,+ created_at INTEGER NOT NULL DEFAULT 0,+ updated_at INTEGER NOT NULL DEFAULT 0,+ completed_at INTEGER,+ PRIMARY KEY(provider_id),+ FOREIGN KEY(provider_id) REFERENCES providers(id) ON UPDATE NO ACTION ON DELETE CASCADE+ )+ """.trimIndent()+ )+ database.execSQL("CREATE INDEX IF NOT EXISTS index_xtream_live_onboarding_state_provider_id ON xtream_live_onboarding_state(provider_id)")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_xtream_live_onboarding_state_phase ON xtream_live_onboarding_state(phase)")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_xtream_live_onboarding_state_updated_at ON xtream_live_onboarding_state(updated_at)")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_xtream_live_onboarding_state_staged_session_id ON xtream_live_onboarding_state(staged_session_id)")++ validateForeignKeys(database, "xtream_live_onboarding_state")+ }+ }++ val MIGRATION_50_51 = object : Migration(50, 51) {+ override fun migrate(database: SupportSQLiteDatabase) {+ database.execSQL("ALTER TABLE xtream_live_onboarding_state ADD COLUMN sync_profile_tier TEXT")+ database.execSQL("ALTER TABLE xtream_live_onboarding_state ADD COLUMN sync_profile_batch_size INTEGER NOT NULL DEFAULT 0")+ database.execSQL("ALTER TABLE xtream_live_onboarding_state ADD COLUMN sync_profile_strategy TEXT")+ database.execSQL("ALTER TABLE xtream_live_onboarding_state ADD COLUMN sync_profile_low_memory INTEGER NOT NULL DEFAULT 0")+ database.execSQL("ALTER TABLE xtream_live_onboarding_state ADD COLUMN sync_profile_memory_class_mb INTEGER NOT NULL DEFAULT 0")+ database.execSQL("ALTER TABLE xtream_live_onboarding_state ADD COLUMN sync_profile_available_mem_mb INTEGER NOT NULL DEFAULT 0")+ validateForeignKeys(database, "xtream_live_onboarding_state")+ }+ }++ val MIGRATION_51_52 = object : Migration(51, 52) {+ override fun migrate(database: SupportSQLiteDatabase) {+ database.execSQL("ALTER TABLE providers ADD COLUMN xtream_live_sync_mode TEXT NOT NULL DEFAULT 'AUTO'")+ validateForeignKeys(database, "providers")+ }+ }++ val MIGRATION_52_53 = object : Migration(52, 53) {+ override fun migrate(database: SupportSQLiteDatabase) {+ addStalkerHardeningColumns(database, "movie_category_hydration")+ addStalkerHardeningColumns(database, "series_category_hydration")+ validateForeignKeys(database, "movie_category_hydration")+ validateForeignKeys(database, "series_category_hydration")+ }+ }++ val MIGRATION_53_54 = object : Migration(53, 54) {+ override fun migrate(database: SupportSQLiteDatabase) {+ database.execSQL("ALTER TABLE providers ADD COLUMN stalker_serial_number TEXT NOT NULL DEFAULT ''")+ database.execSQL("ALTER TABLE providers ADD COLUMN stalker_device_id TEXT NOT NULL DEFAULT ''")+ database.execSQL("ALTER TABLE providers ADD COLUMN stalker_device_id2 TEXT NOT NULL DEFAULT ''")+ database.execSQL("ALTER TABLE providers ADD COLUMN stalker_signature TEXT NOT NULL DEFAULT ''")+ database.execSQL("ALTER TABLE providers ADD COLUMN stalker_auth_mode TEXT NOT NULL DEFAULT 'AUTO'")+ database.execSQL("ALTER TABLE providers ADD COLUMN stalker_portal_profile TEXT NOT NULL DEFAULT 'MAG_BASIC'")+ database.execSQL("ALTER TABLE providers ADD COLUMN stalker_last_playback_mode TEXT")+ database.execSQL("ALTER TABLE providers ADD COLUMN stalker_credentials_required INTEGER NOT NULL DEFAULT 0")+ database.execSQL("ALTER TABLE providers ADD COLUMN stalker_mac_required INTEGER NOT NULL DEFAULT 1")+ database.execSQL("ALTER TABLE providers ADD COLUMN stalker_uses_temp_links INTEGER NOT NULL DEFAULT 0")+ database.execSQL("ALTER TABLE providers ADD COLUMN stalker_module_restricted INTEGER NOT NULL DEFAULT 0")+ validateForeignKeys(database, "providers")+ }+ }++ val MIGRATION_54_55 = object : Migration(54, 55) {+ override fun migrate(database: SupportSQLiteDatabase) {+ // Schema 55 is identical to 54; the complete identity/auth shape shipped in 54.+ }+ }++ private fun addStalkerHardeningColumns(database: SupportSQLiteDatabase, tableName: String) {+ database.execSQL("ALTER TABLE $tableName ADD COLUMN last_attempted_page INTEGER NOT NULL DEFAULT 0")+ database.execSQL("ALTER TABLE $tableName ADD COLUMN last_successful_page INTEGER NOT NULL DEFAULT 0")+ database.execSQL("ALTER TABLE $tableName ADD COLUMN retry_after_ms INTEGER NOT NULL DEFAULT 0")+ database.execSQL("ALTER TABLE $tableName ADD COLUMN failure_count INTEGER NOT NULL DEFAULT 0")+ database.execSQL("ALTER TABLE $tableName ADD COLUMN retry_budget_remaining INTEGER NOT NULL DEFAULT 3")+ database.execSQL("ALTER TABLE $tableName ADD COLUMN last_page_fingerprint TEXT")+ }++ private fun addColumnIfMissing(+ database: SupportSQLiteDatabase,+ tableName: String,+ columnName: String,+ columnDefinition: String+ ) {+ if (tableHasColumn(database, tableName, columnName)) {+ return+ }+ 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<Any?>(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<Any?>(+ 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<Any?>(+ generation,+ legacyStalkerLearning(cursor, generation, updatedAt).toString(),+ updatedAt,+ providerId+ )+ )+ }+ }+ }+ }++ val MIGRATION_55_56 = object : Migration(55, 56) {+ override fun migrate(database: SupportSQLiteDatabase) {+ database.execSQL(+ "ALTER TABLE providers ADD COLUMN stalker_portal_fingerprint TEXT NOT NULL DEFAULT 'BASIC_MAC'"+ )+ database.execSQL(+ "ALTER TABLE providers ADD COLUMN stalker_mag_preset TEXT NOT NULL DEFAULT 'GENERIC_SAFE'"+ )+ database.execSQL(+ "ALTER TABLE providers ADD COLUMN stalker_last_bootstrap_recipe TEXT NOT NULL DEFAULT 'GENERIC_SAFE'"+ )+ database.execSQL(+ "ALTER TABLE providers ADD COLUMN stalker_strict_fingerprint_required INTEGER NOT NULL DEFAULT 0"+ )+ database.execSQL(+ "ALTER TABLE providers ADD COLUMN stalker_recipe_fallback_used INTEGER NOT NULL DEFAULT 0"+ )+ database.execSQL(+ "ALTER TABLE providers ADD COLUMN stalker_recipe_rediscovery_attempts INTEGER NOT NULL DEFAULT 0"+ )+ validateForeignKeys(database, "providers")+ }+ }++ val MIGRATION_56_57 = object : Migration(56, 57) {+ override fun migrate(database: SupportSQLiteDatabase) {+ database.execSQL(+ "ALTER TABLE providers ADD COLUMN stalker_endpoint_preference TEXT NOT NULL DEFAULT 'AUTO'"+ )+ database.execSQL(+ "ALTER TABLE providers ADD COLUMN stalker_cookie_mode TEXT NOT NULL DEFAULT 'NONE'"+ )+ database.execSQL(+ "ALTER TABLE providers ADD COLUMN stalker_playback_backend_hint TEXT NOT NULL DEFAULT 'AUTO'"+ )+ validateForeignKeys(database, "providers")+ }+ }++ /**+ * Migration 57 → 58: add downloads table for tracking in-app download operations.+ */++ val MIGRATION_57_58 = object : Migration(57, 58) {+ override fun migrate(database: SupportSQLiteDatabase) {+ database.execSQL(+ """+ CREATE TABLE IF NOT EXISTS downloads (+ id TEXT NOT NULL PRIMARY KEY,+ 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 DEFAULT 'PENDING',+ bytes_written INTEGER NOT NULL DEFAULT 0,+ total_bytes INTEGER,+ created_at INTEGER NOT NULL,+ completed_at INTEGER,+ failure_reason TEXT,+ series_id INTEGER,+ season_number INTEGER,+ episode_number INTEGER+ )+ """.trimIndent()+ )+ database.execSQL("CREATE INDEX IF NOT EXISTS index_downloads_status ON downloads(status)")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_downloads_provider_id ON downloads(provider_id)")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_downloads_content_type_content_id ON downloads(content_type, content_id)")+ }+ }++ val MIGRATION_58_59 = object : Migration(58, 59) {+ override fun migrate(database: SupportSQLiteDatabase) {+ database.execSQL("ALTER TABLE downloads ADD COLUMN supports_resume INTEGER NOT NULL DEFAULT 0")+ database.execSQL("ALTER TABLE downloads ADD COLUMN retry_count INTEGER NOT NULL DEFAULT 0")+ }+ }++ val MIGRATION_59_60 = object : Migration(59, 60) {+ override fun migrate(database: SupportSQLiteDatabase) {+ addColumnIfMissing(database, "downloads", "source_stream_url", "TEXT")++ addColumnIfMissing(database, "downloads", "source_stream_id", "INTEGER")+ addColumnIfMissing(database, "downloads", "container_extension", "TEXT")+ }+ }++ val MIGRATION_60_61 = object : Migration(60, 61) {+ override fun migrate(database: SupportSQLiteDatabase) {+ addColumnIfMissing(+ database,+ tableName = "providers",+ columnName = "stalker_advanced_options_json",+ columnDefinition = "TEXT NOT NULL DEFAULT ''"+ )+ validateForeignKeys(database, "providers")+ }+ }++ val MIGRATION_61_62 = object : Migration(61, 62) {+ override fun migrate(database: SupportSQLiteDatabase) {+ addColumnIfMissing(+ database,+ tableName = "providers",+ columnName = "guide_source_policy",+ columnDefinition = "TEXT NOT NULL DEFAULT 'AUTO'"+ )+ addColumnIfMissing(+ database,+ tableName = "providers",+ columnName = "channel_logo_source_policy",+ columnDefinition = "TEXT NOT NULL DEFAULT 'SUPPLIER_PREFERRED'"+ )+ validateForeignKeys(database, "providers")+ }+ }++ val MIGRATION_62_63 = object : Migration(62, 63) {+ override fun migrate(database: SupportSQLiteDatabase) {+ addColumnIfMissing(+ database,+ tableName = "providers",+ columnName = "stalker_catalog_mode",+ columnDefinition = "TEXT NOT NULL DEFAULT 'ON_DEMAND'"+ )+ database.execSQL(+ """+ CREATE TABLE IF NOT EXISTS stalker_index_jobs (+ provider_id INTEGER NOT NULL,+ section TEXT NOT NULL,+ state TEXT NOT NULL DEFAULT 'DISABLED',+ total_categories INTEGER NOT NULL DEFAULT 0,+ completed_categories INTEGER NOT NULL DEFAULT 0,+ next_category_index INTEGER NOT NULL DEFAULT 0,+ failed_categories INTEGER NOT NULL DEFAULT 0,+ indexed_rows INTEGER NOT NULL DEFAULT 0,+ skipped_malformed_rows INTEGER NOT NULL DEFAULT 0,+ deleted_pruned_rows INTEGER NOT NULL DEFAULT 0,+ last_error TEXT,+ last_attempt_at INTEGER NOT NULL DEFAULT 0,+ last_success_at INTEGER NOT NULL DEFAULT 0,+ updated_at INTEGER NOT NULL DEFAULT 0,+ PRIMARY KEY(provider_id, section),+ FOREIGN KEY(provider_id) REFERENCES providers(id) ON UPDATE NO ACTION ON DELETE CASCADE+ )+ """.trimIndent()+ )+ database.execSQL("CREATE INDEX IF NOT EXISTS index_stalker_index_jobs_provider_id ON stalker_index_jobs(provider_id)")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_stalker_index_jobs_state ON stalker_index_jobs(state)")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_stalker_index_jobs_updated_at ON stalker_index_jobs(updated_at)")+ database.execSQL(+ """+ INSERT OR REPLACE INTO stalker_index_jobs (+ provider_id, section, state, total_categories, completed_categories,+ next_category_index, failed_categories, indexed_rows, skipped_malformed_rows,+ deleted_pruned_rows, last_error,+ last_attempt_at, last_success_at, updated_at+ )+ SELECT j.provider_id, j.section, 'DISABLED', j.total_categories, j.completed_categories,+ j.next_category_index, j.failed_categories, j.indexed_rows, j.skipped_malformed_rows,+ j.deleted_pruned_rows, j.last_error,+ j.last_attempt_at, j.last_success_at, j.updated_at+ FROM xtream_index_jobs j+ INNER JOIN providers p ON p.id = j.provider_id+ WHERE p.type = 'STALKER_PORTAL' AND j.section IN ('MOVIE', 'SERIES')+ """.trimIndent()+ )+ database.execSQL(+ "DELETE FROM xtream_index_jobs WHERE provider_id IN (SELECT id FROM providers WHERE type = 'STALKER_PORTAL')"+ )+ database.execSQL(+ """+ CREATE TABLE IF NOT EXISTS stalker_portal_state (+ provider_id INTEGER NOT NULL,+ working_endpoint TEXT,+ bootstrap_recipe TEXT,+ bulk_live_supported INTEGER,+ bulk_live_category_fidelity INTEGER,+ movie_wildcard_supported INTEGER,+ series_wildcard_supported INTEGER,+ epg_supported INTEGER,+ safe_metadata_concurrency INTEGER NOT NULL,+ stress_cooldown_until INTEGER NOT NULL,+ endpoint_health_json TEXT NOT NULL,+ endpoint_failed_until INTEGER NOT NULL,+ validated_at INTEGER NOT NULL,+ schema_version INTEGER NOT NULL,+ PRIMARY KEY(provider_id),+ FOREIGN KEY(provider_id) REFERENCES providers(id) ON UPDATE NO ACTION ON DELETE CASCADE+ )+ """.trimIndent()+ )+ database.execSQL("CREATE UNIQUE INDEX IF NOT EXISTS index_stalker_portal_state_provider_id ON stalker_portal_state(provider_id)")+ database.execSQL(+ """+ CREATE TABLE IF NOT EXISTS stalker_remote_identities (+ 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+ )+ """.trimIndent()+ )+ database.execSQL("CREATE INDEX IF NOT EXISTS index_stalker_remote_identities_provider_id ON stalker_remote_identities(provider_id)")+ database.execSQL("CREATE UNIQUE INDEX IF NOT EXISTS index_stalker_remote_identities_provider_id_content_type_surrogate_id ON stalker_remote_identities(provider_id, content_type, surrogate_id)")+ validateForeignKeys(database, "providers", "stalker_index_jobs", "stalker_portal_state", "stalker_remote_identities")+ }+ }++ val MIGRATION_63_64 = object : Migration(63, 64) {+ override fun migrate(database: SupportSQLiteDatabase) {+ addColumnIfMissing(database, "providers", "stalker_protocol_preference", "TEXT NOT NULL DEFAULT 'AUTO'")+ addColumnIfMissing(database, "providers", "stalker_requested_profile_id", "TEXT NOT NULL DEFAULT 'auto'")+ addColumnIfMissing(database, "providers", "stalker_learned_profile_id", "TEXT NOT NULL DEFAULT ''")+ addColumnIfMissing(database, "providers", "stalker_profile_revision", "INTEGER NOT NULL DEFAULT 0")+ addColumnIfMissing(database, "providers", "stalker_profile_verification", "TEXT NOT NULL DEFAULT 'UNVERIFIED'")+ addColumnIfMissing(database, "providers", "stalker_protocol_family", "TEXT NOT NULL DEFAULT 'CLASSIC_MAG'")+ database.execSQL(++ """+ UPDATE providers SET stalker_requested_profile_id = CASE stalker_mag_preset+ WHEN 'MAG250_LEGACY' THEN 'classic.mag250.legacy'+ WHEN 'MAG254_STRICT' THEN 'classic.mag254.strict'+ WHEN 'MINISTRA_MODERN' THEN 'classic.mag322.modern'+ ELSE 'classic.mag250.generic'+ END,+ stalker_learned_profile_id = CASE stalker_mag_preset+ WHEN 'MAG250_LEGACY' THEN 'classic.mag250.legacy'+ WHEN 'MAG254_STRICT' THEN 'classic.mag254.strict'+ WHEN 'MINISTRA_MODERN' THEN 'classic.mag322.modern'+ ELSE 'classic.mag250.generic'+ END,+ stalker_profile_revision = 1,+ stalker_profile_verification = 'VERIFIED'+ WHERE type = 'STALKER_PORTAL'+ """.trimIndent()+ )+ validateForeignKeys(database, "providers")+ }+ }++ val MIGRATION_64_65 = object : Migration(64, 65) {+ override fun migrate(database: SupportSQLiteDatabase) {+ addColumnIfMissing(+ database,+ "providers",+ "stalker_transport_mode",+ "TEXT NOT NULL DEFAULT 'AUTO_STRICT'"+ )+ addColumnIfMissing(+ database,+ "providers",+ "stalker_transport_origin",+ "TEXT NOT NULL DEFAULT ''"+ )+ addColumnIfMissing(+ database,+ "providers",+ "stalker_tls_spki_sha256",+ "TEXT NOT NULL DEFAULT ''"+ )+ addColumnIfMissing(+ database,+ "providers",+ "stalker_transport_consent_at",+ "INTEGER NOT NULL DEFAULT 0"+ )+ addColumnIfMissing(+ database,+ "providers",+ "stalker_configuration_generation",+ "INTEGER NOT NULL DEFAULT 0"+ )+ addColumnIfMissing(+ database,+ "providers",+ "stalker_discovery_summary",+ "TEXT NOT NULL DEFAULT ''"+ )+ addColumnIfMissing(+ database,+ "providers",+ "stalker_capabilities_json",+ "TEXT NOT NULL DEFAULT ''"+ )+ database.execSQL(+ """+ CREATE TABLE IF NOT EXISTS stalker_discovery_staging (+ discovery_id TEXT NOT NULL PRIMARY KEY,+ 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+ )+ """.trimIndent()+ )+ database.execSQL(+ "CREATE INDEX IF NOT EXISTS index_stalker_discovery_staging_provider_id ON stalker_discovery_staging(provider_id)"+ )+ database.execSQL(+ "CREATE INDEX IF NOT EXISTS index_stalker_discovery_staging_created_at ON stalker_discovery_staging(created_at)"+ )+ // Existing installs used a global trust-all client. They deliberately migrate to+ // strict verification and must consent in the foreground if their portal needs+ // HTTP or invalid TLS.+ database.execSQL(+ """+ UPDATE providers+ SET stalker_transport_mode = 'AUTO_STRICT',+ stalker_transport_origin = '',+ stalker_tls_spki_sha256 = '',+ stalker_transport_consent_at = 0+ WHERE type = 'STALKER_PORTAL'+ """.trimIndent()+ )+ database.execSQL(+ """+ UPDATE providers+ SET status = 'PARTIAL',+ is_active = 0+ WHERE type = 'STALKER_PORTAL'+ AND lower(server_url) LIKE 'http://%'+ """.trimIndent()+ )+ listOf(+ imageUrlMigrationSql("movies", "poster_url"),+ imageUrlMigrationSql("movies", "backdrop_url"),+ imageUrlMigrationSql("series", "poster_url"),+ imageUrlMigrationSql("series", "backdrop_url"),+ imageUrlMigrationSql("episodes", "cover_url")+ ).forEach(database::execSQL)+ validateForeignKeys(database, "providers")+ }+ }++ val MIGRATION_65_66 = object : Migration(65, 66) {+ override fun migrate(database: SupportSQLiteDatabase) {+ addColumnIfMissing(+ database,+ "providers",+ "catalog_layout",+ "TEXT NOT NULL DEFAULT 'SPLIT'"+ )+ addColumnIfMissing(+ database,+ "providers",+ "catalog_layout_detection_version",+ "INTEGER NOT NULL DEFAULT 0"+ )+ addColumnIfMissing(+ database,+ "categories",+ "provider_order",+ "INTEGER NOT NULL DEFAULT 0"+ )+ addColumnIfMissing(+ database,++ "category_import_stage",+ "provider_order",+ "INTEGER NOT NULL DEFAULT 0"+ )+ addColumnIfMissing(+ database,+ "series",+ "catalog_origin",+ "TEXT NOT NULL DEFAULT 'NATIVE'"+ )+ addColumnIfMissing(+ database,+ "series",+ "episode_playback_template_url",+ "TEXT"+ )+ database.execSQL(+ """+ CREATE TABLE IF NOT EXISTS vod_category_hydration (+ provider_id INTEGER NOT NULL,+ category_id INTEGER NOT NULL,+ last_loaded_page INTEGER NOT NULL DEFAULT 0,+ last_attempted_page INTEGER NOT NULL DEFAULT 0,+ last_successful_page INTEGER NOT NULL DEFAULT 0,+ total_pages INTEGER NOT NULL DEFAULT 0,+ page_size INTEGER NOT NULL DEFAULT 0,+ item_count INTEGER NOT NULL DEFAULT 0,+ is_complete INTEGER NOT NULL DEFAULT 0,+ has_movies INTEGER NOT NULL DEFAULT 0,+ has_series INTEGER NOT NULL DEFAULT 0,+ last_hydrated_at INTEGER NOT NULL DEFAULT 0,+ last_status TEXT NOT NULL DEFAULT 'IDLE',+ last_error TEXT,+ retry_after_ms INTEGER NOT NULL DEFAULT 0,+ failure_count INTEGER NOT NULL DEFAULT 0,+ retry_budget_remaining INTEGER NOT NULL DEFAULT 3,+ last_page_fingerprint TEXT,+ PRIMARY KEY(provider_id, category_id),+ FOREIGN KEY(provider_id) REFERENCES providers(id) ON UPDATE NO ACTION ON DELETE CASCADE+ )+ """.trimIndent()+ )+ database.execSQL(+ "CREATE INDEX IF NOT EXISTS index_vod_category_hydration_provider_id ON vod_category_hydration(provider_id)"+ )+ database.execSQL(+ """+ CREATE TABLE IF NOT EXISTS vod_catalog_entries (+ provider_id INTEGER NOT NULL,+ category_id INTEGER NOT NULL,+ raw_item_id TEXT NOT NULL,+ item_type TEXT NOT NULL,+ target_id INTEGER NOT NULL,+ raw_page INTEGER NOT NULL,+ raw_index INTEGER NOT NULL,+ PRIMARY KEY(provider_id, category_id, raw_item_id),+ FOREIGN KEY(provider_id) REFERENCES providers(id) ON UPDATE NO ACTION ON DELETE CASCADE+ )+ """.trimIndent()+ )+ database.execSQL("CREATE INDEX IF NOT EXISTS index_vod_catalog_entries_provider_id ON vod_catalog_entries(provider_id)")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_vod_catalog_entries_provider_id_category_id_raw_page_raw_index ON vod_catalog_entries(provider_id, category_id, raw_page, raw_index)")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_vod_catalog_entries_provider_id_item_type_target_id ON vod_catalog_entries(provider_id, item_type, target_id)")+ validateForeignKeys(database, "providers", "vod_category_hydration", "vod_catalog_entries")+ }+ }++ /** Migration 66 -> 67: retain candidate provider edits until they are atomically promoted. */++ val MIGRATION_66_67 = object : Migration(66, 67) {+ override fun migrate(database: SupportSQLiteDatabase) {+ database.execSQL("""CREATE TABLE IF NOT EXISTS plugin_provider_ownership (+ 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+ )""")+ database.execSQL("CREATE UNIQUE INDEX IF NOT EXISTS index_plugin_provider_ownership_provider_id ON plugin_provider_ownership(provider_id)")+ database.execSQL("""CREATE TABLE IF NOT EXISTS provider_deletion_cleanup (+ id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,+ provider_id INTEGER NOT NULL,+ action TEXT NOT NULL,+ target_id TEXT NOT NULL DEFAULT '',+ created_at INTEGER NOT NULL,+ attempt_count INTEGER NOT NULL DEFAULT 0,+ last_error TEXT+ )""")+ database.execSQL("CREATE UNIQUE INDEX IF NOT EXISTS index_provider_deletion_cleanup_provider_id_action_target_id ON provider_deletion_cleanup(provider_id, action, target_id)")+ addColumnIfMissing(database, "recording_runs", "exact_alarm_armed", "INTEGER NOT NULL DEFAULT 1")+ addColumnIfMissing(database, "program_reminders", "exact_alarm_armed", "INTEGER NOT NULL DEFAULT 1")+ database.execSQL(+ """+ CREATE TABLE IF NOT EXISTS provider_config_revisions (+ provider_id INTEGER NOT NULL,+ revision INTEGER NOT NULL,+ config_json TEXT NOT NULL,+ state TEXT NOT NULL,+ attempt_count INTEGER NOT NULL DEFAULT 0,+ 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 DELETE CASCADE+ )+ """.trimIndent()+ )+ database.execSQL("CREATE INDEX IF NOT EXISTS index_provider_config_revisions_provider_id_state ON provider_config_revisions(provider_id, state)")+ validateForeignKeys(database, "provider_config_revisions")+ }+ }++ /** Migration 67 -> 68: retain cross-store backup restore progress for safe retry. */++ val MIGRATION_67_68 = object : Migration(67, 68) {+ override fun migrate(database: SupportSQLiteDatabase) {+ database.execSQL(+ """+ CREATE TABLE IF NOT EXISTS backup_restore_checkpoints (+ restore_key TEXT NOT NULL,+ room_complete INTEGER NOT NULL DEFAULT 0,+ preferences_complete INTEGER NOT NULL DEFAULT 0,+ presets_complete INTEGER NOT NULL DEFAULT 0,+ schedules_complete INTEGER NOT NULL DEFAULT 0,+ 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)+ )+ """.trimIndent()+ )+ }+ }++ /** Migration 68 -> 69: make active download ownership durable and reclaimable. */++ val MIGRATION_68_69 = object : Migration(68, 69) {+ override fun migrate(database: SupportSQLiteDatabase) {+ addColumnIfMissing(database, "downloads", "owner_id", "TEXT")+ addColumnIfMissing(database, "downloads", "owner_epoch", "INTEGER NOT NULL DEFAULT 0")+ addColumnIfMissing(database, "downloads", "heartbeat_at", "INTEGER")+ }+ }++ /** Migration 69 -> 70: make reminder delivery outcomes durable and recoverable. */++ val MIGRATION_69_70 = object : Migration(69, 70) {+ override fun migrate(database: SupportSQLiteDatabase) {+ addColumnIfMissing(database, "program_reminders", "delivery_state", "TEXT NOT NULL DEFAULT 'PENDING'")+ addColumnIfMissing(database, "program_reminders", "delivery_attempt_token", "TEXT")+ addColumnIfMissing(database, "program_reminders", "delivery_attempted_at", "INTEGER")+ addColumnIfMissing(database, "program_reminders", "delivery_attempt_count", "INTEGER NOT NULL DEFAULT 0")+ addColumnIfMissing(database, "program_reminders", "delivery_failure_reason", "TEXT")+ database.execSQL(+ """+ UPDATE program_reminders+ SET delivery_state = CASE+ WHEN notified_at IS NOT NULL THEN 'DELIVERED'+ WHEN is_dismissed = 1 THEN 'DISMISSED'+ ELSE 'PENDING'++ END+ """.trimIndent()+ )+ }+ }++ /** Migration 70 -> 71: persist the provider workflow generation, lease, and phase ledger. */++ val MIGRATION_70_71 = object : Migration(70, 71) {+ override fun migrate(database: SupportSQLiteDatabase) {+ database.execSQL(+ """+ CREATE TABLE IF NOT EXISTS provider_workflows (+ 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+ )+ """.trimIndent()+ )+ database.execSQL("CREATE INDEX IF NOT EXISTS index_provider_workflows_state ON provider_workflows(state)")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_provider_workflows_updated_at ON provider_workflows(updated_at)")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_provider_workflows_lease_expires_at ON provider_workflows(lease_expires_at)")+ database.execSQL(+ """+ CREATE TABLE IF NOT EXISTS provider_workflow_phases (+ 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+ )+ """.trimIndent()+ )+ database.execSQL("CREATE INDEX IF NOT EXISTS index_provider_workflow_phases_provider_id ON provider_workflow_phases(provider_id)")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_provider_workflow_phases_state ON provider_workflow_phases(state)")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_provider_workflow_phases_updated_at ON provider_workflow_phases(updated_at)")+ validateForeignKeys(database, "provider_workflows", "provider_workflow_phases")+ }+ }++ /** Migration 71 -> 72: make offset-free XMLTV timestamp handling explicit per source. */++ val MIGRATION_71_72 = object : Migration(71, 72) {+ override fun migrate(database: SupportSQLiteDatabase) {+ addColumnIfMissing(database, "epg_sources", "timezone_policy", "TEXT NOT NULL DEFAULT 'REQUIRE_OFFSET'")+ addColumnIfMissing(database, "epg_sources", "timezone_id", "TEXT")+ addColumnIfMissing(database, "categories", "provider_order", "INTEGER NOT NULL DEFAULT 0")+ addColumnIfMissing(database, "category_import_stage", "provider_order", "INTEGER NOT NULL DEFAULT 0")+ addColumnIfMissing(database, "series", "catalog_origin", "TEXT NOT NULL DEFAULT 'NATIVE'")+ addColumnIfMissing(database, "series", "episode_playback_template_url", "TEXT")+ // The entity was absent from exported schemas v67-v71 and returns in v72.+ // IF NOT EXISTS also preserves state for older paths where v62 created it.+ database.execSQL(+ """+ CREATE TABLE IF NOT EXISTS stalker_portal_state (+ provider_id INTEGER NOT NULL,+ working_endpoint TEXT,+ bootstrap_recipe TEXT,+ bulk_live_supported INTEGER,+ bulk_live_category_fidelity INTEGER,+ movie_wildcard_supported INTEGER,+ series_wildcard_supported INTEGER,+ epg_supported INTEGER,+ safe_metadata_concurrency INTEGER NOT NULL,+ stress_cooldown_until INTEGER NOT NULL,+ endpoint_health_json TEXT NOT NULL,+ endpoint_failed_until INTEGER NOT NULL,+ validated_at INTEGER NOT NULL,+ schema_version INTEGER NOT NULL,+ PRIMARY KEY(provider_id),+ FOREIGN KEY(provider_id) REFERENCES providers(id) ON UPDATE NO ACTION ON DELETE CASCADE+ )+ """.trimIndent()+ )+ database.execSQL(+ "CREATE UNIQUE INDEX IF NOT EXISTS index_stalker_portal_state_provider_id ON stalker_portal_state(provider_id)"+ )+ database.execSQL(+ """+ CREATE TABLE IF NOT EXISTS stalker_discovery_staging (+ 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)+ )+ """.trimIndent()+ )+ database.execSQL("CREATE INDEX IF NOT EXISTS index_stalker_discovery_staging_provider_id ON stalker_discovery_staging(provider_id)")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_stalker_discovery_staging_created_at ON stalker_discovery_staging(created_at)")+ database.execSQL(+ """+ CREATE TABLE IF NOT EXISTS stalker_index_jobs (+ 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+ )+ """.trimIndent()+ )+ database.execSQL("CREATE INDEX IF NOT EXISTS index_stalker_index_jobs_provider_id ON stalker_index_jobs(provider_id)")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_stalker_index_jobs_state ON stalker_index_jobs(state)")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_stalker_index_jobs_updated_at ON stalker_index_jobs(updated_at)")+ database.execSQL(+ """+ CREATE TABLE IF NOT EXISTS stalker_remote_identities (+ 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+ )+ """.trimIndent()+ )+ database.execSQL("CREATE INDEX IF NOT EXISTS index_stalker_remote_identities_provider_id ON stalker_remote_identities(provider_id)")+ database.execSQL("CREATE UNIQUE INDEX IF NOT EXISTS index_stalker_remote_identities_provider_id_content_type_surrogate_id ON stalker_remote_identities(provider_id, content_type, surrogate_id)")+ database.execSQL(+ """+ CREATE TABLE IF NOT EXISTS vod_catalog_entries (+ provider_id INTEGER NOT NULL,+ category_id INTEGER NOT NULL,+ raw_item_id TEXT NOT NULL,+ item_type TEXT NOT NULL,+ target_id INTEGER NOT NULL,+ raw_page INTEGER NOT NULL,+ raw_index INTEGER NOT NULL,+ PRIMARY KEY(provider_id, category_id, raw_item_id),+ FOREIGN KEY(provider_id) REFERENCES providers(id) ON UPDATE NO ACTION ON DELETE CASCADE+ )+ """.trimIndent()+ )+ database.execSQL("CREATE INDEX IF NOT EXISTS index_vod_catalog_entries_provider_id ON vod_catalog_entries(provider_id)")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_vod_catalog_entries_provider_id_category_id_raw_page_raw_index ON vod_catalog_entries(provider_id, category_id, raw_page, raw_index)")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_vod_catalog_entries_provider_id_item_type_target_id ON vod_catalog_entries(provider_id, item_type, target_id)")+ database.execSQL(+ """+ CREATE TABLE IF NOT EXISTS vod_category_hydration (+ provider_id INTEGER NOT NULL,+ category_id INTEGER NOT NULL,+ last_loaded_page INTEGER NOT NULL,+ 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+ )+ """.trimIndent()+ )+ database.execSQL("CREATE INDEX IF NOT EXISTS index_vod_category_hydration_provider_id ON vod_category_hydration(provider_id)")+ }+ }++ /** 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)+ }+ }++ /** Migration 74 -> 75: retain Stalker server pagination totals for resumable catalogs. */++ val MIGRATION_74_75 = object : Migration(74, 75) {+ override fun migrate(database: SupportSQLiteDatabase) {+ listOf(+ "movie_category_hydration",+ "series_category_hydration",+ "vod_category_hydration"+ ).forEach { tableName ->+ addColumnIfMissing(database, tableName, "advertised_total_items", "INTEGER")+ addColumnIfMissing(database, tableName, "advertised_total_pages", "INTEGER")+ }++ // Older paths added these fields with ALTER TABLE defaults. Rebuild at the+ // convergence boundary so every historical path matches Room's v75 schema.+ database.execSQL(+ """+ CREATE TABLE sync_metadata_new (+ 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+ )+ """.trimIndent()+ )+ database.execSQL(+ """+ INSERT INTO sync_metadata_new (+ provider_id, last_live_sync, last_live_success, last_movie_sync,+ last_series_sync, last_series_success, last_epg_sync, last_epg_success,+ last_movie_attempt, last_movie_success, last_movie_partial, live_count,+ movie_count, series_count, epg_count, last_sync_status, movie_sync_mode,+ movie_warnings_count, movie_catalog_stale, live_avoid_full_until,+ movie_avoid_full_until, series_avoid_full_until,+ live_sequential_failures_remembered, live_healthy_sync_streak,+ movie_parallel_failures_remembered, movie_healthy_sync_streak,+ series_sequential_failures_remembered, series_healthy_sync_streak+ )+ SELECT+ provider_id, last_live_sync, last_live_success, last_movie_sync,+ last_series_sync, last_series_success, last_epg_sync, last_epg_success,+ last_movie_attempt, last_movie_success, last_movie_partial, live_count,+ movie_count, series_count, epg_count, last_sync_status, movie_sync_mode,+ movie_warnings_count, movie_catalog_stale, live_avoid_full_until,+ movie_avoid_full_until, series_avoid_full_until,+ live_sequential_failures_remembered, live_healthy_sync_streak,+ movie_parallel_failures_remembered, movie_healthy_sync_streak,+ series_sequential_failures_remembered, series_healthy_sync_streak+ FROM sync_metadata+ """.trimIndent()+ )+ database.execSQL("DROP TABLE sync_metadata")+ database.execSQL("ALTER TABLE sync_metadata_new RENAME TO sync_metadata")+ }+ }++ 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 = CASE+ WHEN instr($column, 'streamvault_provider_id=') > 0 THEN $column+ ELSE $column || CASE WHEN instr($column, '?') = 0 THEN '?streamvault_provider_id=' ELSE '&streamvault_provider_id=' END || provider_id+ END+ WHERE $column IS NOT NULL+ AND provider_id IN (SELECT id FROM providers WHERE type = 'JELLYFIN')+ """.trimIndent()++ val all: List<Migration> = listOf(+ MIGRATION_49_50,+ MIGRATION_50_51,+ MIGRATION_51_52,+ MIGRATION_52_53,+ MIGRATION_53_54,+ MIGRATION_54_55,+ MIGRATION_55_56,+ MIGRATION_56_57,+ MIGRATION_57_58,+ MIGRATION_58_59,+ MIGRATION_59_60,+ MIGRATION_60_61,+ MIGRATION_61_62,+ MIGRATION_62_63,+ MIGRATION_63_64,+ MIGRATION_64_65,+ MIGRATION_65_66,+ MIGRATION_66_67,+ MIGRATION_67_68,+ MIGRATION_68_69,+ MIGRATION_69_70,+ MIGRATION_70_71,+ MIGRATION_71_72,+ MIGRATION_72_73,+ MIGRATION_73_74,+ MIGRATION_74_75+ )+}diff --git a/data/src/main/java/com/streamvault/data/local/LegacyMigrationsV1To24.kt b/data/src/main/java/com/streamvault/data/local/LegacyMigrationsV1To24.ktnew file mode 100644index 00000000..8a7572f1--- /dev/null+++ b/data/src/main/java/com/streamvault/data/local/LegacyMigrationsV1To24.kt@@ -0,0 +1,1176 @@+@file:Suppress("PARAMETER_NAME_CHANGED_ON_OVERRIDE", "TYPE_INTERSECTION_AS_REIFIED")++package com.streamvault.data.local++import androidx.room.migration.Migration+import androidx.sqlite.db.SupportSQLiteDatabase+import org.json.JSONObject+import java.net.URI+import java.security.MessageDigest++/** Historical foundation migrations (v1 through v24). Executable bodies live here, outside the Room schema declaration. */+internal object LegacyMigrationsV1To24 {+ val MIGRATION_1_2 = object : Migration(1, 2) {+ override fun migrate(database: SupportSQLiteDatabase) {+ // Schema was identical between v1 and v2; nothing to alter.+ }+ }++ /**+ * Migration 2 → 3: added parental-control protection columns.+ */++ val MIGRATION_2_3 = object : Migration(2, 3) {+ override fun migrate(database: SupportSQLiteDatabase) {+ database.execSQL("ALTER TABLE categories ADD COLUMN is_adult INTEGER NOT NULL DEFAULT 0")+ database.execSQL("ALTER TABLE categories ADD COLUMN is_user_protected INTEGER NOT NULL DEFAULT 0")+ database.execSQL("ALTER TABLE channels ADD COLUMN is_adult INTEGER NOT NULL DEFAULT 0")+ database.execSQL("ALTER TABLE channels ADD COLUMN is_user_protected INTEGER NOT NULL DEFAULT 0")+ database.execSQL("ALTER TABLE movies ADD COLUMN is_adult INTEGER NOT NULL DEFAULT 0")+ database.execSQL("ALTER TABLE movies ADD COLUMN is_user_protected INTEGER NOT NULL DEFAULT 0")+ database.execSQL("ALTER TABLE series ADD COLUMN is_adult INTEGER NOT NULL DEFAULT 0")+ database.execSQL("ALTER TABLE series ADD COLUMN is_user_protected INTEGER NOT NULL DEFAULT 0")+ database.execSQL("ALTER TABLE episodes ADD COLUMN is_adult INTEGER NOT NULL DEFAULT 0")+ database.execSQL("ALTER TABLE episodes ADD COLUMN is_user_protected INTEGER NOT NULL DEFAULT 0")+ }+ }++ val MIGRATION_3_4 = object : Migration(3, 4) {+ override fun migrate(database: SupportSQLiteDatabase) {+ database.execSQL("ALTER TABLE channels ADD COLUMN catchUpSource TEXT")+ // 1. Create playback_history table+ database.execSQL("""+ CREATE TABLE IF NOT EXISTS playback_history (+ 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 DEFAULT '',+ poster_url TEXT,+ stream_url TEXT NOT NULL DEFAULT '',+ resume_position_ms INTEGER NOT NULL DEFAULT 0,+ total_duration_ms INTEGER NOT NULL DEFAULT 0,+ last_watched_at INTEGER NOT NULL DEFAULT 0,+ watch_count INTEGER NOT NULL DEFAULT 1,+ series_id INTEGER,+ season_number INTEGER,+ episode_number INTEGER+ )+ """)+ database.execSQL("CREATE UNIQUE INDEX IF NOT EXISTS idx_history_unique ON playback_history(content_id, content_type, provider_id)")+ database.execSQL("CREATE INDEX IF NOT EXISTS idx_history_last_watched ON playback_history(last_watched_at DESC)")+ database.execSQL("CREATE INDEX IF NOT EXISTS idx_history_provider ON playback_history(provider_id)")++ // 2. Create sync_metadata table+ database.execSQL("""+ CREATE TABLE IF NOT EXISTS sync_metadata (+ provider_id INTEGER PRIMARY KEY NOT NULL,+ last_live_sync INTEGER NOT NULL DEFAULT 0,+ last_movie_sync INTEGER NOT NULL DEFAULT 0,+ last_series_sync INTEGER NOT NULL DEFAULT 0,+ last_epg_sync INTEGER NOT NULL DEFAULT 0,+ live_count INTEGER NOT NULL DEFAULT 0,+ movie_count INTEGER NOT NULL DEFAULT 0,+ series_count INTEGER NOT NULL DEFAULT 0,+ epg_count INTEGER NOT NULL DEFAULT 0,+ last_sync_status TEXT NOT NULL DEFAULT 'NONE'+ )+ """)++ // 3. Migrate existing watch progress to history+ database.execSQL("""+ INSERT OR IGNORE INTO playback_history (content_id, content_type, provider_id, title, resume_position_ms, last_watched_at)+ SELECT id, 'MOVIE', provider_id, name, watch_progress, last_watched_at+ FROM movies WHERE watch_progress > 0+ """)+ database.execSQL("""+ INSERT OR IGNORE INTO playback_history (content_id, content_type, provider_id, title, resume_position_ms, last_watched_at, series_id, season_number, episode_number)+ SELECT id, 'SERIES_EPISODE', provider_id, title, watch_progress, last_watched_at, series_id, season_number, episode_number+ FROM episodes WHERE watch_progress > 0+ """)+ }+ }++ val MIGRATION_4_5 = object : Migration(4, 5) {+ override fun migrate(database: SupportSQLiteDatabase) {+ // Note: Room auto-generates index names as 'index_tableName_columnNames'+ // Channels+ database.execSQL("DROP INDEX IF EXISTS index_channels_category_id")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_channels_provider_id_category_id ON channels(provider_id, category_id)")++ // Movies+ database.execSQL("DROP INDEX IF EXISTS index_movies_category_id")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_movies_provider_id_category_id ON movies(provider_id, category_id)")++ // Series+ database.execSQL("DROP INDEX IF EXISTS index_series_category_id")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_series_provider_id_category_id ON series(provider_id, category_id)")++ // Favorites+ database.execSQL("DROP INDEX IF EXISTS index_favorites_group_id")+ database.execSQL("DROP INDEX IF EXISTS index_favorites_position")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_favorites_content_type_group_id ON favorites(content_type, group_id)")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_favorites_group_id_position ON favorites(group_id, position)")+ }+ }++ val MIGRATION_5_6 = object : Migration(5, 6) {+ override fun migrate(database: SupportSQLiteDatabase) {+ database.execSQL("ALTER TABLE virtual_groups ADD COLUMN content_type TEXT NOT NULL DEFAULT 'LIVE'")+ }+ }++ val MIGRATION_6_7 = object : Migration(6, 7) {+ override fun migrate(database: SupportSQLiteDatabase) {+ database.execSQL("ALTER TABLE channels ADD COLUMN logical_group_id TEXT NOT NULL DEFAULT ''")+ database.execSQL("ALTER TABLE channels ADD COLUMN error_count INTEGER NOT NULL DEFAULT 0")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_channels_logical_group_id ON channels(logical_group_id)")+ }+ }++ val MIGRATION_7_8 = object : Migration(7, 8) {+ override fun migrate(database: SupportSQLiteDatabase) {+ database.execSQL("ALTER TABLE programs ADD COLUMN provider_id INTEGER NOT NULL DEFAULT 0")+ database.execSQL("DROP INDEX IF EXISTS index_programs_channel_id")+ database.execSQL("DROP INDEX IF EXISTS index_programs_channel_id_start_time")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_programs_provider_id ON programs(provider_id)")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_programs_provider_id_channel_id ON programs(provider_id, channel_id)")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_programs_provider_id_channel_id_start_time ON programs(provider_id, channel_id, start_time)")+ database.execSQL(+ "CREATE UNIQUE INDEX IF NOT EXISTS index_programs_provider_id_channel_id_start_time_end_time " ++ "ON programs(provider_id, channel_id, start_time, end_time)"+ )+ }+ }++ val MIGRATION_8_9 = object : Migration(8, 9) {+ override fun migrate(database: SupportSQLiteDatabase) {+ // Rebuild media tables to normalize legacy local IDs and keep only provider-scoped remote IDs as remote keys.+ // This preserves user-facing references by remapping favorites/history through temporary ID maps.++ // Channels+ database.execSQL(+ """+ CREATE TABLE IF NOT EXISTS channels_new (+ 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+ )+ """.trimIndent()+ )+ database.execSQL(+ """+ INSERT INTO channels_new (+ stream_id, name, logo_url, group_title, category_id, category_name, stream_url,+ epg_channel_id, number, catch_up_supported, catch_up_days, catchUpSource,+ provider_id, is_adult, is_user_protected, logical_group_id, error_count+ )+ SELECT+ stream_id, name, logo_url, group_title, category_id, category_name, stream_url,+ epg_channel_id, number, catch_up_supported, catch_up_days, catchUpSource,+ provider_id, is_adult, is_user_protected, logical_group_id, error_count+ FROM channels+ """.trimIndent()+ )+ database.execSQL("CREATE TEMP TABLE channel_id_map(old_id INTEGER PRIMARY KEY NOT NULL, new_id INTEGER NOT NULL)")+ database.execSQL(+ """+ INSERT INTO channel_id_map(old_id, new_id)+ SELECT old.id, MIN(new.id)+ FROM channels old+ JOIN channels_new new+ ON new.provider_id = old.provider_id+ AND new.stream_id = old.stream_id+ GROUP BY old.id+ """.trimIndent()+ )+ database.execSQL(+ """+ UPDATE favorites+ SET content_id = (SELECT new_id FROM channel_id_map WHERE old_id = content_id)+ WHERE content_type = 'LIVE'+ AND content_id IN (SELECT old_id FROM channel_id_map)+ """.trimIndent()+ )+ database.execSQL(+ """+ UPDATE playback_history+ SET content_id = (SELECT new_id FROM channel_id_map WHERE old_id = content_id)+ WHERE content_type = 'LIVE'+ AND content_id IN (SELECT old_id FROM channel_id_map)+ """.trimIndent()+ )+ database.execSQL("DROP TABLE channels")+ database.execSQL("ALTER TABLE channels_new RENAME TO channels")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_channels_provider_id ON channels(provider_id)")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_channels_provider_id_category_id ON channels(provider_id, category_id)")+ database.execSQL("CREATE UNIQUE INDEX IF NOT EXISTS index_channels_provider_id_stream_id ON channels(provider_id, stream_id)")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_channels_logical_group_id ON channels(logical_group_id)")+ database.execSQL("DROP TABLE channel_id_map")++ // Movies+ database.execSQL(+ """+ CREATE TABLE IF NOT EXISTS movies_new (+ id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,+ stream_id INTEGER NOT NULL,+ name TEXT NOT NULL,+ poster_url TEXT,+ backdrop_url TEXT,+ category_id INTEGER,+ category_name TEXT,+ stream_url TEXT NOT NULL,+ container_extension TEXT,+ plot TEXT,+ "cast" TEXT,+ director TEXT,+ genre TEXT,+ release_date TEXT,+ duration TEXT,+ duration_seconds INTEGER NOT NULL,+ rating REAL NOT NULL,+ year TEXT,+ tmdb_id INTEGER,+ youtube_trailer TEXT,+ provider_id INTEGER NOT NULL,+ watch_progress INTEGER NOT NULL,+ last_watched_at INTEGER NOT NULL,+ is_adult INTEGER NOT NULL,+ is_user_protected INTEGER NOT NULL+ )+ """.trimIndent()+ )+ database.execSQL(+ """+ INSERT INTO movies_new (+ stream_id, name, poster_url, backdrop_url, category_id, category_name, stream_url,+ container_extension, plot, "cast", director, genre, release_date, duration, duration_seconds,+ rating, year, tmdb_id, youtube_trailer, provider_id, watch_progress, last_watched_at,+ is_adult, is_user_protected+ )+ SELECT+ stream_id, name, poster_url, backdrop_url, category_id, category_name, stream_url,+ container_extension, plot, "cast", director, genre, release_date, duration, duration_seconds,+ rating, year, tmdb_id, youtube_trailer, provider_id, watch_progress, last_watched_at,+ is_adult, is_user_protected+ FROM movies+ """.trimIndent()+ )+ database.execSQL("CREATE TEMP TABLE movie_id_map(old_id INTEGER PRIMARY KEY NOT NULL, new_id INTEGER NOT NULL)")+ database.execSQL(+ """+ INSERT INTO movie_id_map(old_id, new_id)+ SELECT old.id, MIN(new.id)+ FROM movies old+ JOIN movies_new new+ ON new.provider_id = old.provider_id+ AND new.stream_id = old.stream_id+ GROUP BY old.id+ """.trimIndent()+ )+ database.execSQL(+ """+ UPDATE favorites+ SET content_id = (SELECT new_id FROM movie_id_map WHERE old_id = content_id)+ WHERE content_type = 'MOVIE'+ AND content_id IN (SELECT old_id FROM movie_id_map)+ """.trimIndent()+ )+ database.execSQL(+ """+ UPDATE playback_history+ SET content_id = (SELECT new_id FROM movie_id_map WHERE old_id = content_id)+ WHERE content_type = 'MOVIE'+ AND content_id IN (SELECT old_id FROM movie_id_map)+ """.trimIndent()+ )+ database.execSQL("DROP TABLE movies")+ database.execSQL("ALTER TABLE movies_new RENAME TO movies")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_movies_provider_id ON movies(provider_id)")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_movies_provider_id_category_id ON movies(provider_id, category_id)")+ database.execSQL("CREATE UNIQUE INDEX IF NOT EXISTS index_movies_provider_id_stream_id ON movies(provider_id, stream_id)")+ database.execSQL("DROP TABLE movie_id_map")++ // Series+ database.execSQL(+ """+ CREATE TABLE IF NOT EXISTS series_new (+ id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,+ series_id INTEGER NOT NULL,+ name TEXT NOT NULL,+ poster_url TEXT,++ backdrop_url TEXT,+ category_id INTEGER,+ category_name TEXT,+ plot TEXT,+ "cast" TEXT,+ director TEXT,+ genre TEXT,+ release_date TEXT,+ rating REAL NOT NULL,+ tmdb_id INTEGER,+ youtube_trailer TEXT,+ episode_run_time TEXT,+ last_modified INTEGER NOT NULL,+ provider_id INTEGER NOT NULL,+ is_adult INTEGER NOT NULL,+ is_user_protected INTEGER NOT NULL+ )+ """.trimIndent()+ )+ database.execSQL(+ """+ INSERT INTO series_new (+ series_id, name, poster_url, backdrop_url, category_id, category_name, plot, "cast",+ director, genre, release_date, rating, tmdb_id, youtube_trailer, episode_run_time,+ last_modified, provider_id, is_adult, is_user_protected+ )+ SELECT+ series_id, name, poster_url, backdrop_url, category_id, category_name, plot, "cast",+ director, genre, release_date, rating, tmdb_id, youtube_trailer, episode_run_time,+ last_modified, provider_id, is_adult, is_user_protected+ FROM series+ """.trimIndent()+ )+ database.execSQL("CREATE TEMP TABLE series_id_map(old_id INTEGER PRIMARY KEY NOT NULL, new_id INTEGER NOT NULL)")+ database.execSQL(+ """+ INSERT INTO series_id_map(old_id, new_id)+ SELECT old.id, MIN(new.id)+ FROM series old+ JOIN series_new new+ ON new.provider_id = old.provider_id+ AND new.series_id = old.series_id+ GROUP BY old.id+ """.trimIndent()+ )+ database.execSQL(+ """+ UPDATE favorites+ SET content_id = (SELECT new_id FROM series_id_map WHERE old_id = content_id)+ WHERE content_type = 'SERIES'+ AND content_id IN (SELECT old_id FROM series_id_map)+ """.trimIndent()+ )+ database.execSQL(+ """+ UPDATE playback_history+ SET content_id = (SELECT new_id FROM series_id_map WHERE old_id = content_id)+ WHERE content_type = 'SERIES'+ AND content_id IN (SELECT old_id FROM series_id_map)+ """.trimIndent()+ )+ database.execSQL(+ """+ UPDATE playback_history+ SET series_id = (SELECT new_id FROM series_id_map WHERE old_id = series_id)+ WHERE series_id IS NOT NULL+ AND series_id IN (SELECT old_id FROM series_id_map)+ """.trimIndent()+ )+ database.execSQL(+ """+ UPDATE episodes+ SET series_id = (SELECT new_id FROM series_id_map WHERE old_id = series_id)+ WHERE series_id IN (SELECT old_id FROM series_id_map)+ """.trimIndent()+ )+ database.execSQL("DROP TABLE series")+ database.execSQL("ALTER TABLE series_new RENAME TO series")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_series_provider_id ON series(provider_id)")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_series_provider_id_category_id ON series(provider_id, category_id)")+ database.execSQL("CREATE UNIQUE INDEX IF NOT EXISTS index_series_provider_id_series_id ON series(provider_id, series_id)")+ database.execSQL("DROP TABLE series_id_map")++ // Episodes+ database.execSQL(+ """+ CREATE TABLE IF NOT EXISTS episodes_new (+ 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+ )+ """.trimIndent()+ )+ database.execSQL(+ """+ INSERT INTO episodes_new (+ episode_id, title, episode_number, season_number, stream_url, container_extension, cover_url,+ plot, duration, duration_seconds, rating, release_date, series_id, provider_id, watch_progress,+ last_watched_at, is_adult, is_user_protected+ )+ SELECT+ episode_id, title, episode_number, season_number, stream_url, container_extension, cover_url,+ plot, duration, duration_seconds, rating, release_date, series_id, provider_id, watch_progress,+ last_watched_at, is_adult, is_user_protected+ FROM episodes+ """.trimIndent()+ )+ database.execSQL("CREATE TEMP TABLE episode_id_map(old_id INTEGER PRIMARY KEY NOT NULL, new_id INTEGER NOT NULL)")+ database.execSQL(+ """+ INSERT INTO episode_id_map(old_id, new_id)+ SELECT old.id, new.id+ FROM episodes old+ JOIN episodes_new new+ ON new.provider_id = old.provider_id+ AND new.episode_id = old.episode_id+ """.trimIndent()+ )+ database.execSQL(+ """+ UPDATE playback_history+ SET content_id = (SELECT new_id FROM episode_id_map WHERE old_id = content_id)+ WHERE content_type = 'SERIES_EPISODE'+ AND content_id IN (SELECT old_id FROM episode_id_map)+ """.trimIndent()+ )+ database.execSQL("DROP TABLE episodes")+ database.execSQL("ALTER TABLE episodes_new RENAME TO episodes")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_episodes_series_id ON episodes(series_id)")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_episodes_provider_id ON episodes(provider_id)")+ database.execSQL("CREATE UNIQUE INDEX IF NOT EXISTS index_episodes_provider_id_episode_id ON episodes(provider_id, episode_id)")+ database.execSQL("DROP TABLE episode_id_map")+ validateForeignKeys(database, "episodes")+ }++ }++ val MIGRATION_9_10 = object : Migration(9, 10) {+ override fun migrate(database: SupportSQLiteDatabase) {+ database.execSQL("CREATE VIRTUAL TABLE IF NOT EXISTS channels_fts USING fts4(name, content=`channels`)")+ database.execSQL("CREATE VIRTUAL TABLE IF NOT EXISTS movies_fts USING fts4(name, content=`movies`)")+ database.execSQL("CREATE VIRTUAL TABLE IF NOT EXISTS series_fts USING fts4(name, content=`series`)")++ database.execSQL("INSERT INTO channels_fts(rowid, name) SELECT id, name FROM channels")+ database.execSQL("INSERT INTO movies_fts(rowid, name) SELECT id, name FROM movies")+ database.execSQL("INSERT INTO series_fts(rowid, name) SELECT id, name FROM series")++ database.execSQL(+ """+ CREATE TRIGGER IF NOT EXISTS channels_ai+ AFTER INSERT ON channels BEGIN+ INSERT INTO channels_fts(rowid, name) VALUES (new.id, new.name);+ END+ """.trimIndent()+ )+ database.execSQL(+ """+ CREATE TRIGGER IF NOT EXISTS channels_ad+ BEFORE DELETE ON channels BEGIN+ DELETE FROM channels_fts WHERE rowid = old.id;+ END+ """.trimIndent()+ )+ database.execSQL(+ """+ CREATE TRIGGER IF NOT EXISTS channels_au+ AFTER UPDATE OF name ON channels BEGIN+ UPDATE channels_fts SET name = new.name WHERE rowid = old.id;+ END+ """.trimIndent()+ )++ database.execSQL(+ """+ CREATE TRIGGER IF NOT EXISTS movies_ai+ AFTER INSERT ON movies BEGIN+ INSERT INTO movies_fts(rowid, name) VALUES (new.id, new.name);+ END+ """.trimIndent()+ )+ database.execSQL(+ """+ CREATE TRIGGER IF NOT EXISTS movies_ad+ BEFORE DELETE ON movies BEGIN+ DELETE FROM movies_fts WHERE rowid = old.id;+ END+ """.trimIndent()+ )+ database.execSQL(+ """+ CREATE TRIGGER IF NOT EXISTS movies_au+ AFTER UPDATE OF name ON movies BEGIN+ UPDATE movies_fts SET name = new.name WHERE rowid = old.id;+ END+ """.trimIndent()+ )++ database.execSQL(+ """+ CREATE TRIGGER IF NOT EXISTS series_ai+ AFTER INSERT ON series BEGIN+ INSERT INTO series_fts(rowid, name) VALUES (new.id, new.name);+ END+ """.trimIndent()+ )+ database.execSQL(+ """+ CREATE TRIGGER IF NOT EXISTS series_ad+ BEFORE DELETE ON series BEGIN+ DELETE FROM series_fts WHERE rowid = old.id;+ END+ """.trimIndent()+ )+ database.execSQL(+ """+ CREATE TRIGGER IF NOT EXISTS series_au+ AFTER UPDATE OF name ON series BEGIN+ UPDATE series_fts SET name = new.name WHERE rowid = old.id;+ END+ """.trimIndent()+ )+ }+ }++ /**+ * Migration 10 → 11: Add foreign key constraints to child tables.+ * Tables referencing providers get ON DELETE CASCADE.+ * Favorites referencing virtual_groups get ON DELETE SET NULL.+ * Programs table excluded (uses negative staging provider IDs).+ */++ val MIGRATION_10_11 = object : Migration(10, 11) {+ override fun migrate(database: SupportSQLiteDatabase) {+ // Clean up orphaned records before adding FK constraints+ database.execSQL("DELETE FROM channels WHERE provider_id NOT IN (SELECT id FROM providers)")+ database.execSQL("DELETE FROM movies WHERE provider_id NOT IN (SELECT id FROM providers)")+ database.execSQL("DELETE FROM series WHERE provider_id NOT IN (SELECT id FROM providers)")+ database.execSQL("DELETE FROM episodes WHERE provider_id NOT IN (SELECT id FROM providers)")+ database.execSQL("DELETE FROM categories WHERE provider_id NOT IN (SELECT id FROM providers)")+ database.execSQL("DELETE FROM playback_history WHERE provider_id NOT IN (SELECT id FROM providers)")+ database.execSQL("DELETE FROM sync_metadata WHERE provider_id NOT IN (SELECT id FROM providers)")+ database.execSQL("UPDATE favorites SET group_id = NULL WHERE group_id IS NOT NULL AND group_id NOT IN (SELECT id FROM virtual_groups)")++ // ── Drop FTS triggers and tables (channels, movies, series) ──+ database.execSQL("DROP TRIGGER IF EXISTS channels_ai")+ database.execSQL("DROP TRIGGER IF EXISTS channels_ad")+ database.execSQL("DROP TRIGGER IF EXISTS channels_au")+ database.execSQL("DROP TRIGGER IF EXISTS movies_ai")+ database.execSQL("DROP TRIGGER IF EXISTS movies_ad")+ database.execSQL("DROP TRIGGER IF EXISTS movies_au")+ database.execSQL("DROP TRIGGER IF EXISTS series_ai")+ database.execSQL("DROP TRIGGER IF EXISTS series_ad")+ database.execSQL("DROP TRIGGER IF EXISTS series_au")+ database.execSQL("DROP TABLE IF EXISTS channels_fts")+ database.execSQL("DROP TABLE IF EXISTS movies_fts")+ database.execSQL("DROP TABLE IF EXISTS series_fts")++ // ── Channels ──+ database.execSQL("""+ CREATE TABLE channels_new (+ id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,+ stream_id INTEGER NOT NULL DEFAULT 0,+ name TEXT NOT NULL,+ logo_url TEXT,+ group_title TEXT,+ category_id INTEGER,+ category_name TEXT,+ stream_url TEXT NOT NULL DEFAULT '',+ epg_channel_id TEXT,+ number INTEGER NOT NULL DEFAULT 0,+ catch_up_supported INTEGER NOT NULL DEFAULT 0,+ catch_up_days INTEGER NOT NULL DEFAULT 0,+ catchUpSource TEXT,+ provider_id INTEGER NOT NULL DEFAULT 0,+ is_adult INTEGER NOT NULL DEFAULT 0,+ is_user_protected INTEGER NOT NULL DEFAULT 0,+ logical_group_id TEXT NOT NULL DEFAULT '',+ error_count INTEGER NOT NULL DEFAULT 0,+ FOREIGN KEY(provider_id) REFERENCES providers(id) ON DELETE CASCADE+ )+ """.trimIndent())+ database.execSQL("INSERT INTO channels_new SELECT * FROM channels")+ database.execSQL("DROP TABLE channels")+ database.execSQL("ALTER TABLE channels_new RENAME TO channels")+ database.execSQL("CREATE INDEX index_channels_provider_id ON channels(provider_id)")+ database.execSQL("CREATE INDEX index_channels_provider_id_category_id ON channels(provider_id, category_id)")++ database.execSQL("CREATE UNIQUE INDEX index_channels_provider_id_stream_id ON channels(provider_id, stream_id)")+ database.execSQL("CREATE INDEX index_channels_logical_group_id ON channels(logical_group_id)")++ // ── Movies ──+ database.execSQL("""+ CREATE TABLE movies_new (+ id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,+ stream_id INTEGER NOT NULL DEFAULT 0,+ name TEXT NOT NULL,+ poster_url TEXT,+ backdrop_url TEXT,+ category_id INTEGER,+ category_name TEXT,+ stream_url TEXT NOT NULL DEFAULT '',+ container_extension TEXT,+ plot TEXT,+ "cast" TEXT,+ director TEXT,+ genre TEXT,+ release_date TEXT,+ duration TEXT,+ duration_seconds INTEGER NOT NULL DEFAULT 0,+ rating REAL NOT NULL DEFAULT 0,+ year TEXT,+ tmdb_id INTEGER,+ youtube_trailer TEXT,+ provider_id INTEGER NOT NULL DEFAULT 0,+ watch_progress INTEGER NOT NULL DEFAULT 0,+ last_watched_at INTEGER NOT NULL DEFAULT 0,+ is_adult INTEGER NOT NULL DEFAULT 0,+ is_user_protected INTEGER NOT NULL DEFAULT 0,+ FOREIGN KEY(provider_id) REFERENCES providers(id) ON DELETE CASCADE+ )+ """.trimIndent())+ database.execSQL("INSERT INTO movies_new SELECT * FROM movies")+ database.execSQL("DROP TABLE movies")+ database.execSQL("ALTER TABLE movies_new RENAME TO movies")+ database.execSQL("CREATE INDEX index_movies_provider_id ON movies(provider_id)")+ database.execSQL("CREATE INDEX index_movies_provider_id_category_id ON movies(provider_id, category_id)")+ database.execSQL("CREATE UNIQUE INDEX index_movies_provider_id_stream_id ON movies(provider_id, stream_id)")++ // ── Series ──+ database.execSQL("""+ CREATE TABLE series_new (+ id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,+ series_id INTEGER NOT NULL DEFAULT 0,+ 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 DEFAULT 0,+ tmdb_id INTEGER,+ youtube_trailer TEXT,+ episode_run_time TEXT,+ last_modified INTEGER NOT NULL DEFAULT 0,+ provider_id INTEGER NOT NULL DEFAULT 0,+ is_adult INTEGER NOT NULL DEFAULT 0,+ is_user_protected INTEGER NOT NULL DEFAULT 0,+ FOREIGN KEY(provider_id) REFERENCES providers(id) ON DELETE CASCADE+ )+ """.trimIndent())+ database.execSQL("INSERT INTO series_new SELECT * FROM series")+ database.execSQL("DROP TABLE series")+ database.execSQL("ALTER TABLE series_new RENAME TO series")+ database.execSQL("CREATE INDEX index_series_provider_id ON series(provider_id)")+ database.execSQL("CREATE INDEX index_series_provider_id_category_id ON series(provider_id, category_id)")+ database.execSQL("CREATE UNIQUE INDEX index_series_provider_id_series_id ON series(provider_id, series_id)")++ // ── Recreate FTS tables and triggers ──+ database.execSQL("CREATE VIRTUAL TABLE IF NOT EXISTS channels_fts USING fts4(name, content=`channels`)")+ database.execSQL("CREATE VIRTUAL TABLE IF NOT EXISTS movies_fts USING fts4(name, content=`movies`)")+ database.execSQL("CREATE VIRTUAL TABLE IF NOT EXISTS series_fts USING fts4(name, content=`series`)")+ database.execSQL("INSERT INTO channels_fts(rowid, name) SELECT id, name FROM channels")+ database.execSQL("INSERT INTO movies_fts(rowid, name) SELECT id, name FROM movies")+ database.execSQL("INSERT INTO series_fts(rowid, name) SELECT id, name FROM series")+ database.execSQL("CREATE TRIGGER IF NOT EXISTS channels_ai AFTER INSERT ON channels BEGIN INSERT INTO channels_fts(rowid, name) VALUES (new.id, new.name); END")+ database.execSQL("CREATE TRIGGER IF NOT EXISTS channels_ad BEFORE DELETE ON channels BEGIN DELETE FROM channels_fts WHERE rowid = old.id; END")+ database.execSQL("CREATE TRIGGER IF NOT EXISTS channels_au AFTER UPDATE OF name ON channels BEGIN UPDATE channels_fts SET name = new.name WHERE rowid = old.id; END")+ database.execSQL("CREATE TRIGGER IF NOT EXISTS movies_ai AFTER INSERT ON movies BEGIN INSERT INTO movies_fts(rowid, name) VALUES (new.id, new.name); END")+ database.execSQL("CREATE TRIGGER IF NOT EXISTS movies_ad BEFORE DELETE ON movies BEGIN DELETE FROM movies_fts WHERE rowid = old.id; END")+ database.execSQL("CREATE TRIGGER IF NOT EXISTS movies_au AFTER UPDATE OF name ON movies BEGIN UPDATE movies_fts SET name = new.name WHERE rowid = old.id; END")+ database.execSQL("CREATE TRIGGER IF NOT EXISTS series_ai AFTER INSERT ON series BEGIN INSERT INTO series_fts(rowid, name) VALUES (new.id, new.name); END")+ database.execSQL("CREATE TRIGGER IF NOT EXISTS series_ad BEFORE DELETE ON series BEGIN DELETE FROM series_fts WHERE rowid = old.id; END")+ database.execSQL("CREATE TRIGGER IF NOT EXISTS series_au AFTER UPDATE OF name ON series BEGIN UPDATE series_fts SET name = new.name WHERE rowid = old.id; END")++ // ── Episodes ──+ database.execSQL("""+ CREATE TABLE episodes_new (+ id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,+ episode_id INTEGER NOT NULL DEFAULT 0,+ title TEXT NOT NULL,+ episode_number INTEGER NOT NULL,+ season_number INTEGER NOT NULL,+ stream_url TEXT NOT NULL DEFAULT '',+ container_extension TEXT,+ cover_url TEXT,+ plot TEXT,+ duration TEXT,+ duration_seconds INTEGER NOT NULL DEFAULT 0,+ rating REAL NOT NULL DEFAULT 0,+ release_date TEXT,+ series_id INTEGER NOT NULL DEFAULT 0,+ provider_id INTEGER NOT NULL DEFAULT 0,+ watch_progress INTEGER NOT NULL DEFAULT 0,+ last_watched_at INTEGER NOT NULL DEFAULT 0,+ is_adult INTEGER NOT NULL DEFAULT 0,+ is_user_protected INTEGER NOT NULL DEFAULT 0,+ FOREIGN KEY(provider_id) REFERENCES providers(id) ON DELETE CASCADE+ )+ """.trimIndent())+ database.execSQL("INSERT INTO episodes_new SELECT * FROM episodes")+ database.execSQL("DROP TABLE episodes")+ database.execSQL("ALTER TABLE episodes_new RENAME TO episodes")+ database.execSQL("CREATE INDEX index_episodes_series_id ON episodes(series_id)")+ database.execSQL("CREATE INDEX index_episodes_provider_id ON episodes(provider_id)")+ database.execSQL("CREATE UNIQUE INDEX index_episodes_provider_id_episode_id ON episodes(provider_id, episode_id)")++ // ── Categories ──+ database.execSQL("""+ CREATE TABLE categories_new (+ id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,+ category_id INTEGER NOT NULL DEFAULT 0,+ name TEXT NOT NULL,+ parent_id INTEGER,+ type TEXT NOT NULL DEFAULT 'LIVE',+ provider_id INTEGER NOT NULL DEFAULT 0,+ is_adult INTEGER NOT NULL DEFAULT 0,+ is_user_protected INTEGER NOT NULL DEFAULT 0,+ FOREIGN KEY(provider_id) REFERENCES providers(id) ON DELETE CASCADE+ )+ """.trimIndent())+ database.execSQL("""+ INSERT INTO categories_new (+ id, category_id, name, parent_id, type, provider_id,+ is_adult, is_user_protected+ )+ SELECT+ id, category_id, name, parent_id, type, provider_id,+ is_adult, is_user_protected+ FROM categories+ """.trimIndent())+ database.execSQL("DROP TABLE categories")+ database.execSQL("ALTER TABLE categories_new RENAME TO categories")+ database.execSQL("CREATE INDEX index_categories_provider_id ON categories(provider_id)")+ database.execSQL("CREATE UNIQUE INDEX index_categories_provider_id_category_id_type ON categories(provider_id, category_id, type)")++ // ── Playback History ──+ database.execSQL("""+ CREATE TABLE playback_history_new (+ 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 DEFAULT '',+ poster_url TEXT,+ stream_url TEXT NOT NULL DEFAULT '',+ resume_position_ms INTEGER NOT NULL DEFAULT 0,+ total_duration_ms INTEGER NOT NULL DEFAULT 0,+ last_watched_at INTEGER NOT NULL DEFAULT 0,+ watch_count INTEGER NOT NULL DEFAULT 1,+ series_id INTEGER,+ season_number INTEGER,+ episode_number INTEGER,+ FOREIGN KEY(provider_id) REFERENCES providers(id) ON DELETE CASCADE+ )+ """.trimIndent())+ database.execSQL("INSERT INTO playback_history_new SELECT * FROM playback_history")+ database.execSQL("DROP TABLE playback_history")+ database.execSQL("ALTER TABLE playback_history_new RENAME TO playback_history")+ database.execSQL("CREATE UNIQUE INDEX index_playback_history_content_id_content_type_provider_id ON playback_history(content_id, content_type, provider_id)")+ database.execSQL("CREATE INDEX index_playback_history_last_watched_at ON playback_history(last_watched_at)")+ database.execSQL("CREATE INDEX index_playback_history_provider_id ON playback_history(provider_id)")++ // ── Sync Metadata ──+ database.execSQL("""+ CREATE TABLE sync_metadata_new (+ provider_id INTEGER NOT NULL PRIMARY KEY,+ last_live_sync INTEGER NOT NULL DEFAULT 0,+ last_movie_sync INTEGER NOT NULL DEFAULT 0,+ last_series_sync INTEGER NOT NULL DEFAULT 0,+ last_epg_sync INTEGER NOT NULL DEFAULT 0,+ live_count INTEGER NOT NULL DEFAULT 0,+ movie_count INTEGER NOT NULL DEFAULT 0,+ series_count INTEGER NOT NULL DEFAULT 0,+ epg_count INTEGER NOT NULL DEFAULT 0,+ last_sync_status TEXT NOT NULL DEFAULT 'NONE',+ FOREIGN KEY(provider_id) REFERENCES providers(id) ON DELETE CASCADE+ )+ """.trimIndent())+ database.execSQL("INSERT INTO sync_metadata_new SELECT * FROM sync_metadata")+ database.execSQL("DROP TABLE sync_metadata")+ database.execSQL("ALTER TABLE sync_metadata_new RENAME TO sync_metadata")++ // ── Favorites ──+ database.execSQL("""+ CREATE TABLE favorites_new (+ id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,+ content_id INTEGER NOT NULL,+ content_type TEXT NOT NULL,+ position INTEGER NOT NULL DEFAULT 0,+ group_id INTEGER,+ added_at INTEGER NOT NULL,+ FOREIGN KEY(group_id) REFERENCES virtual_groups(id) ON DELETE SET NULL+ )+ """.trimIndent())+ database.execSQL("INSERT INTO favorites_new SELECT * FROM favorites")+ database.execSQL("DROP TABLE favorites")+ database.execSQL("ALTER TABLE favorites_new RENAME TO favorites")+ database.execSQL("CREATE UNIQUE INDEX index_favorites_content_id_content_type_group_id ON favorites(content_id, content_type, group_id)")+ database.execSQL("CREATE INDEX index_favorites_content_type_group_id ON favorites(content_type, group_id)")+ database.execSQL("CREATE INDEX index_favorites_group_id_position ON favorites(group_id, position)")+ validateForeignKeys(database, "favorites")+ }+ }+ /**+ * Migration 11 → 12: adds series_id FK to episodes.+ * Episodes whose series_id has no matching row in the series table are silently+ * removed — they are unreachable orphans and would violate the new constraint.+ */++ val MIGRATION_11_12 = object : Migration(11, 12) {+ override fun migrate(database: SupportSQLiteDatabase) {+ // Create new episodes table with both FK constraints+ database.execSQL("""+ CREATE TABLE episodes_new (+ id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,+ episode_id INTEGER NOT NULL DEFAULT 0,+ title TEXT NOT NULL,+ episode_number INTEGER NOT NULL,+ season_number INTEGER NOT NULL,+ stream_url TEXT NOT NULL DEFAULT '',+ container_extension TEXT,+ cover_url TEXT,+ plot TEXT,+ duration TEXT,+ duration_seconds INTEGER NOT NULL DEFAULT 0,+ rating REAL NOT NULL DEFAULT 0,+ release_date TEXT,+ series_id INTEGER NOT NULL DEFAULT 0,+ provider_id INTEGER NOT NULL DEFAULT 0,+ watch_progress INTEGER NOT NULL DEFAULT 0,+ last_watched_at INTEGER NOT NULL DEFAULT 0,+ is_adult INTEGER NOT NULL DEFAULT 0,+ is_user_protected INTEGER NOT NULL DEFAULT 0,+ FOREIGN KEY(provider_id) REFERENCES providers(id) ON DELETE CASCADE,+ FOREIGN KEY(series_id) REFERENCES series(id) ON DELETE CASCADE+ )+ """.trimIndent())+ // Migrate only episodes with a valid series parent; orphans are discarded+ database.execSQL("""+ INSERT INTO episodes_new+ SELECT * FROM episodes+ WHERE series_id IN (SELECT id FROM series)+ """.trimIndent())+ database.execSQL("DROP TABLE episodes")+ database.execSQL("ALTER TABLE episodes_new RENAME TO episodes")+ database.execSQL("CREATE INDEX index_episodes_series_id ON episodes(series_id)")+ database.execSQL("CREATE INDEX index_episodes_provider_id ON episodes(provider_id)")+ database.execSQL("CREATE UNIQUE INDEX index_episodes_provider_id_episode_id ON episodes(provider_id, episode_id)")+ }+ }++ /**+ * Migration 12 → 13: move high-cardinality per-channel UI state into Room.+ * Existing DataStore aspect-ratio entries are read lazily as a legacy fallback and+ * get replaced in Room on the next write for each channel.+ */++ val MIGRATION_12_13 = object : Migration(12, 13) {+ override fun migrate(database: SupportSQLiteDatabase) {+ database.execSQL(+ """+ CREATE TABLE IF NOT EXISTS channel_preferences (+ id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,+ channel_id INTEGER NOT NULL,+ aspect_ratio TEXT,+ updated_at INTEGER NOT NULL DEFAULT 0,+ FOREIGN KEY(channel_id) REFERENCES channels(id) ON DELETE CASCADE+ )+ """.trimIndent()+ )+ database.execSQL(+ "CREATE UNIQUE INDEX IF NOT EXISTS index_channel_preferences_channel_id ON channel_preferences(channel_id)"+ )+ }+ }++ /**+ * Migration 13 → 14: add targeted secondary indexes for broad EPG windows,+ * provider/type category filtering, and virtual group content type lookups.+ */++ val MIGRATION_13_14 = object : Migration(13, 14) {+ override fun migrate(database: SupportSQLiteDatabase) {+ database.execSQL(+ "CREATE INDEX IF NOT EXISTS index_programs_provider_id_start_time_end_time ON programs(provider_id, start_time, end_time)"+ )+ database.execSQL(+ "CREATE INDEX IF NOT EXISTS index_categories_provider_id_type ON categories(provider_id, type)"+ )+ database.execSQL(+ "CREATE INDEX IF NOT EXISTS index_virtual_groups_content_type ON virtual_groups(content_type)"+ )+ }+ }++ val MIGRATION_14_15 = object : Migration(14, 15) {+ override fun migrate(database: SupportSQLiteDatabase) {+ database.execSQL("ALTER TABLE providers ADD COLUMN api_version TEXT")+ database.execSQL("ALTER TABLE channels ADD COLUMN quality_options_json TEXT")+ database.execSQL("ALTER TABLE programs ADD COLUMN rating TEXT")+ database.execSQL("ALTER TABLE programs ADD COLUMN image_url TEXT")+ database.execSQL("ALTER TABLE programs ADD COLUMN genre TEXT")+ database.execSQL("ALTER TABLE programs ADD COLUMN category TEXT")+ database.execSQL("ALTER TABLE playback_history ADD COLUMN watched_status TEXT NOT NULL DEFAULT 'IN_PROGRESS'")+ }+ }++ val MIGRATION_15_16 = object : Migration(15, 16) {+ override fun migrate(database: SupportSQLiteDatabase) {+ database.execSQL(+ "CREATE INDEX IF NOT EXISTS index_channels_provider_id_category_id_logical_group_id " ++ "ON channels(provider_id, category_id, logical_group_id)"+ )+ }+ }++ val MIGRATION_16_17 = object : Migration(16, 17) {+ override fun migrate(database: SupportSQLiteDatabase) {+ database.execSQL(+ "ALTER TABLE providers ADD COLUMN allowed_output_formats_json TEXT NOT NULL DEFAULT '[]'"+ )+ }+ }++ val MIGRATION_17_18 = object : Migration(17, 18) {+ override fun migrate(database: SupportSQLiteDatabase) {+ database.execSQL("ALTER TABLE sync_metadata ADD COLUMN last_movie_attempt INTEGER NOT NULL DEFAULT 0")+ database.execSQL("ALTER TABLE sync_metadata ADD COLUMN last_movie_success INTEGER NOT NULL DEFAULT 0")+ database.execSQL("ALTER TABLE sync_metadata ADD COLUMN last_movie_partial INTEGER NOT NULL DEFAULT 0")+ database.execSQL("ALTER TABLE sync_metadata ADD COLUMN movie_sync_mode TEXT NOT NULL DEFAULT 'UNKNOWN'")+ database.execSQL("ALTER TABLE sync_metadata ADD COLUMN movie_warnings_count INTEGER NOT NULL DEFAULT 0")+ database.execSQL("ALTER TABLE sync_metadata ADD COLUMN movie_catalog_stale INTEGER NOT NULL DEFAULT 0")+ database.execSQL("ALTER TABLE sync_metadata ADD COLUMN movie_parallel_failures_remembered INTEGER NOT NULL DEFAULT 0")+ }+ }++ val MIGRATION_18_19 = object : Migration(18, 19) {+ override fun migrate(database: SupportSQLiteDatabase) {+ database.execSQL("ALTER TABLE sync_metadata ADD COLUMN movie_healthy_sync_streak INTEGER NOT NULL DEFAULT 0")+ }+ }++ val MIGRATION_19_20 = object : Migration(19, 20) {+ override fun migrate(database: SupportSQLiteDatabase) {+ database.execSQL("ALTER TABLE channels ADD COLUMN sync_fingerprint TEXT NOT NULL DEFAULT ''")+ database.execSQL("ALTER TABLE movies ADD COLUMN sync_fingerprint TEXT NOT NULL DEFAULT ''")+ database.execSQL("ALTER TABLE series ADD COLUMN sync_fingerprint TEXT NOT NULL DEFAULT ''")+ database.execSQL("ALTER TABLE categories ADD COLUMN sync_fingerprint TEXT NOT NULL DEFAULT ''")++ database.execSQL(+ """+ CREATE TABLE IF NOT EXISTS channel_import_stage (+ 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,+ sync_fingerprint TEXT NOT NULL,+ PRIMARY KEY(session_id, provider_id, stream_id),+ FOREIGN KEY(provider_id) REFERENCES providers(id) ON DELETE CASCADE+ )+ """.trimIndent()+ )+ database.execSQL("CREATE INDEX IF NOT EXISTS index_channel_import_stage_provider_id ON channel_import_stage(provider_id)")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_channel_import_stage_session_id_provider_id ON channel_import_stage(session_id, provider_id)")++ database.execSQL(+ """+ CREATE TABLE IF NOT EXISTS movie_import_stage (+ 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,+ PRIMARY KEY(session_id, provider_id, stream_id),+ FOREIGN KEY(provider_id) REFERENCES providers(id) ON DELETE CASCADE+ )+ """.trimIndent()+ )+ database.execSQL("CREATE INDEX IF NOT EXISTS index_movie_import_stage_provider_id ON movie_import_stage(provider_id)")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_movie_import_stage_session_id_provider_id ON movie_import_stage(session_id, provider_id)")++ database.execSQL(+ """+ CREATE TABLE IF NOT EXISTS series_import_stage (+ session_id INTEGER NOT NULL,+ provider_id INTEGER NOT NULL,+ series_id INTEGER NOT NULL,+ name TEXT NOT NULL,+ poster_url TEXT,+ backdrop_url TEXT,+ category_id INTEGER,+ category_name TEXT,+ plot TEXT,+ "cast" TEXT,+ director TEXT,+ genre TEXT,+ release_date TEXT,+ rating REAL NOT NULL,+ tmdb_id INTEGER,+ youtube_trailer TEXT,+ episode_run_time TEXT,+ last_modified INTEGER NOT NULL,+ is_adult INTEGER NOT NULL,+ sync_fingerprint TEXT NOT NULL,+ PRIMARY KEY(session_id, provider_id, series_id),+ FOREIGN KEY(provider_id) REFERENCES providers(id) ON DELETE CASCADE+ )+ """.trimIndent()+ )+ database.execSQL("CREATE INDEX IF NOT EXISTS index_series_import_stage_provider_id ON series_import_stage(provider_id)")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_series_import_stage_session_id_provider_id ON series_import_stage(session_id, provider_id)")++ database.execSQL(+ """+ CREATE TABLE IF NOT EXISTS category_import_stage (+ session_id INTEGER NOT NULL,++ provider_id INTEGER NOT NULL,+ category_id INTEGER NOT NULL,+ name TEXT NOT NULL,+ parent_id INTEGER,+ type TEXT NOT NULL,+ is_adult INTEGER NOT NULL,+ sync_fingerprint TEXT NOT NULL,+ PRIMARY KEY(session_id, provider_id, category_id, type),+ FOREIGN KEY(provider_id) REFERENCES providers(id) ON DELETE CASCADE+ )+ """.trimIndent()+ )+ database.execSQL("CREATE INDEX IF NOT EXISTS index_category_import_stage_provider_id ON category_import_stage(provider_id)")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_category_import_stage_session_id_provider_id ON category_import_stage(session_id, provider_id)")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_category_import_stage_provider_id_type ON category_import_stage(provider_id, type)")+ }+ }++ val MIGRATION_20_21 = object : Migration(20, 21) {+ override fun migrate(database: SupportSQLiteDatabase) {+ database.execSQL("ALTER TABLE sync_metadata ADD COLUMN live_avoid_full_until INTEGER NOT NULL DEFAULT 0")+ database.execSQL("ALTER TABLE sync_metadata ADD COLUMN movie_avoid_full_until INTEGER NOT NULL DEFAULT 0")+ database.execSQL("ALTER TABLE sync_metadata ADD COLUMN series_avoid_full_until INTEGER NOT NULL DEFAULT 0")+ database.execSQL("ALTER TABLE sync_metadata ADD COLUMN live_sequential_failures_remembered INTEGER NOT NULL DEFAULT 0")+ database.execSQL("ALTER TABLE sync_metadata ADD COLUMN live_healthy_sync_streak INTEGER NOT NULL DEFAULT 0")+ database.execSQL("ALTER TABLE sync_metadata ADD COLUMN series_sequential_failures_remembered INTEGER NOT NULL DEFAULT 0")+ database.execSQL("ALTER TABLE sync_metadata ADD COLUMN series_healthy_sync_streak INTEGER NOT NULL DEFAULT 0")+ }+ }++ val MIGRATION_21_22 = object : Migration(21, 22) {+ override fun migrate(database: SupportSQLiteDatabase) {+ database.execSQL("ALTER TABLE channel_import_stage ADD COLUMN logical_group_id TEXT NOT NULL DEFAULT ''")+ }+ }++ val MIGRATION_22_23 = object : Migration(22, 23) {+ override fun migrate(database: SupportSQLiteDatabase) {+ database.execSQL("ALTER TABLE channel_import_stage ADD COLUMN error_count INTEGER NOT NULL DEFAULT 0")+ }+ }++ val MIGRATION_23_24 = object : Migration(23, 24) {+ override fun migrate(database: SupportSQLiteDatabase) {+ database.execSQL("ALTER TABLE providers ADD COLUMN xtream_fast_sync_enabled INTEGER NOT NULL DEFAULT 0")+ database.execSQL(+ """+ CREATE TABLE IF NOT EXISTS movie_category_hydration (+ provider_id INTEGER NOT NULL,+ category_id INTEGER NOT NULL,+ last_hydrated_at INTEGER NOT NULL DEFAULT 0,+ item_count INTEGER NOT NULL DEFAULT 0,+ last_status TEXT NOT NULL DEFAULT 'IDLE',+ last_error TEXT,+ PRIMARY KEY(provider_id, category_id),+ FOREIGN KEY(provider_id) REFERENCES providers(id) ON DELETE CASCADE+ )+ """.trimIndent()+ )+ database.execSQL(+ "CREATE INDEX IF NOT EXISTS index_movie_category_hydration_provider_id ON movie_category_hydration(provider_id)"+ )+ }+ }++ val all: List<Migration> = listOf(+ MIGRATION_1_2,+ MIGRATION_2_3,+ MIGRATION_3_4,+ MIGRATION_4_5,+ MIGRATION_5_6,+ MIGRATION_6_7,+ MIGRATION_7_8,+ MIGRATION_8_9,+ MIGRATION_9_10,+ MIGRATION_10_11,+ MIGRATION_11_12,+ MIGRATION_12_13,+ MIGRATION_13_14,+ MIGRATION_14_15,+ MIGRATION_15_16,+ MIGRATION_16_17,+ MIGRATION_17_18,+ MIGRATION_18_19,+ MIGRATION_19_20,+ MIGRATION_20_21,+ MIGRATION_21_22,+ MIGRATION_22_23,+ MIGRATION_23_24+ )+}diff --git a/data/src/main/java/com/streamvault/data/local/LegacyMigrationsV24To49.kt b/data/src/main/java/com/streamvault/data/local/LegacyMigrationsV24To49.ktnew file mode 100644index 00000000..f61dff52--- /dev/null+++ b/data/src/main/java/com/streamvault/data/local/LegacyMigrationsV24To49.kt@@ -0,0 +1,1351 @@+@file:Suppress("PARAMETER_NAME_CHANGED_ON_OVERRIDE", "TYPE_INTERSECTION_AS_REIFIED")++package com.streamvault.data.local++import androidx.room.migration.Migration+import androidx.sqlite.db.SupportSQLiteDatabase+import org.json.JSONObject+import java.net.URI+import java.security.MessageDigest++/** Catalog, guide, recording, and playback-history migrations (v24 through v49). Executable bodies live here, outside the Room schema declaration. */+internal object LegacyMigrationsV24To49 {+ val MIGRATION_24_25 = object : Migration(24, 25) {+ override fun migrate(database: SupportSQLiteDatabase) {+ // ── epg_sources ──+ database.execSQL("""+ CREATE TABLE IF NOT EXISTS epg_sources (+ id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,+ name TEXT NOT NULL,+ url TEXT NOT NULL,+ enabled INTEGER NOT NULL DEFAULT 1,+ last_refresh_at INTEGER NOT NULL DEFAULT 0,+ last_success_at INTEGER NOT NULL DEFAULT 0,+ last_error TEXT,+ priority INTEGER NOT NULL DEFAULT 0,+ created_at INTEGER NOT NULL DEFAULT 0,+ updated_at INTEGER NOT NULL DEFAULT 0+ )+ """.trimIndent())+ database.execSQL("CREATE UNIQUE INDEX IF NOT EXISTS index_epg_sources_url ON epg_sources(url)")++ // ── provider_epg_sources ──+ database.execSQL("""+ CREATE TABLE IF NOT EXISTS provider_epg_sources (+ id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,+ provider_id INTEGER NOT NULL,+ epg_source_id INTEGER NOT NULL,+ priority INTEGER NOT NULL DEFAULT 0,+ enabled INTEGER NOT NULL DEFAULT 1,+ FOREIGN KEY(provider_id) REFERENCES providers(id) ON DELETE CASCADE,+ FOREIGN KEY(epg_source_id) REFERENCES epg_sources(id) ON DELETE CASCADE+ )+ """.trimIndent())+ database.execSQL("CREATE UNIQUE INDEX IF NOT EXISTS index_provider_epg_sources_provider_id_epg_source_id ON provider_epg_sources(provider_id, epg_source_id)")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_provider_epg_sources_epg_source_id ON provider_epg_sources(epg_source_id)")++ // ── epg_channels ──+ database.execSQL("""+ CREATE TABLE IF NOT EXISTS epg_channels (+ 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 DEFAULT '',+ icon_url TEXT,+ FOREIGN KEY(epg_source_id) REFERENCES epg_sources(id) ON DELETE CASCADE+ )+ """.trimIndent())+ database.execSQL("CREATE UNIQUE INDEX IF NOT EXISTS index_epg_channels_epg_source_id_xmltv_channel_id ON epg_channels(epg_source_id, xmltv_channel_id)")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_epg_channels_epg_source_id ON epg_channels(epg_source_id)")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_epg_channels_normalized_name ON epg_channels(normalized_name)")++ // ── epg_programmes ──+ database.execSQL("""+ CREATE TABLE IF NOT EXISTS epg_programmes (+ id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,+ epg_source_id INTEGER NOT NULL,+ xmltv_channel_id TEXT NOT NULL,+ start_time INTEGER NOT NULL DEFAULT 0,+ end_time INTEGER NOT NULL DEFAULT 0,+ title TEXT NOT NULL,+ subtitle TEXT,+ description TEXT NOT NULL DEFAULT '',++ category TEXT,+ lang TEXT NOT NULL DEFAULT '',+ rating TEXT,+ image_url TEXT,+ episode_info TEXT,+ FOREIGN KEY(epg_source_id) REFERENCES epg_sources(id) ON DELETE CASCADE+ )+ """.trimIndent())+ database.execSQL("CREATE INDEX IF NOT EXISTS index_epg_programmes_epg_source_id_xmltv_channel_id_start_time ON epg_programmes(epg_source_id, xmltv_channel_id, start_time)")+ database.execSQL("CREATE UNIQUE INDEX IF NOT EXISTS index_epg_programmes_epg_source_id_xmltv_channel_id_start_time_end_time ON epg_programmes(epg_source_id, xmltv_channel_id, start_time, end_time)")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_epg_programmes_epg_source_id ON epg_programmes(epg_source_id)")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_epg_programmes_start_time ON epg_programmes(start_time)")++ // ── channel_epg_mappings ──+ database.execSQL("""+ CREATE TABLE IF NOT EXISTS channel_epg_mappings (+ id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,+ provider_channel_id INTEGER NOT NULL,+ provider_id INTEGER NOT NULL,+ source_type TEXT NOT NULL DEFAULT 'NONE',+ epg_source_id INTEGER,+ xmltv_channel_id TEXT,+ match_type TEXT,+ confidence REAL NOT NULL DEFAULT 0,+ is_manual_override INTEGER NOT NULL DEFAULT 0,+ updated_at INTEGER NOT NULL DEFAULT 0,+ FOREIGN KEY(provider_id) REFERENCES providers(id) ON DELETE CASCADE+ )+ """.trimIndent())+ database.execSQL("CREATE UNIQUE INDEX IF NOT EXISTS index_channel_epg_mappings_provider_id_provider_channel_id ON channel_epg_mappings(provider_id, provider_channel_id)")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_channel_epg_mappings_provider_id ON channel_epg_mappings(provider_id)")+ }+ }++ val MIGRATION_25_26 = object : Migration(25, 26) {+ override fun migrate(database: SupportSQLiteDatabase) {+ database.execSQL("""+ CREATE TABLE IF NOT EXISTS series_category_hydration (+ provider_id INTEGER NOT NULL,+ category_id INTEGER NOT NULL,+ last_hydrated_at INTEGER NOT NULL DEFAULT 0,+ item_count INTEGER NOT NULL DEFAULT 0,+ last_status TEXT NOT NULL DEFAULT 'IDLE',+ last_error TEXT,+ PRIMARY KEY(provider_id, category_id),+ FOREIGN KEY(provider_id) REFERENCES providers(id) ON DELETE CASCADE+ )+ """.trimIndent())+ database.execSQL("CREATE INDEX IF NOT EXISTS index_series_category_hydration_provider_id ON series_category_hydration(provider_id)")+ }+ }++ val MIGRATION_26_27 = object : Migration(26, 27) {+ override fun migrate(database: SupportSQLiteDatabase) {+ database.execSQL("ALTER TABLE providers ADD COLUMN epg_sync_mode TEXT NOT NULL DEFAULT 'UPFRONT'")+ }+ }++ val MIGRATION_27_28 = object : Migration(27, 28) {+ override fun migrate(database: SupportSQLiteDatabase) {+ database.execSQL("ALTER TABLE providers ADD COLUMN m3u_vod_classification_enabled INTEGER NOT NULL DEFAULT 1")+ }+ }++ val MIGRATION_28_29 = object : Migration(28, 29) {+ override fun migrate(database: SupportSQLiteDatabase) {+ database.execSQL(+ """+ CREATE TABLE IF NOT EXISTS recording_schedules (+ 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 DEFAULT 1,+ is_manual INTEGER NOT NULL DEFAULT 0,+ priority INTEGER NOT NULL DEFAULT 0,+ created_at INTEGER NOT NULL,+ updated_at INTEGER NOT NULL,+ FOREIGN KEY(provider_id) REFERENCES providers(id) ON DELETE CASCADE+ )+ """.trimIndent()+ )+ database.execSQL("CREATE INDEX IF NOT EXISTS index_recording_schedules_provider_id ON recording_schedules(provider_id)")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_recording_schedules_enabled_requested_start_ms ON recording_schedules(enabled, requested_start_ms)")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_recording_schedules_recurring_rule_id ON recording_schedules(recurring_rule_id)")++ database.execSQL(+ """+ CREATE TABLE IF NOT EXISTS recording_runs (+ id TEXT PRIMARY KEY 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 DEFAULT '{}',+ user_agent TEXT,+ expiration_time INTEGER,+ provider_label TEXT,+ output_uri TEXT,+ output_display_path TEXT,+ bytes_written INTEGER NOT NULL DEFAULT 0,+ average_throughput_bps INTEGER NOT NULL DEFAULT 0,+ retry_count INTEGER NOT NULL DEFAULT 0,+ last_progress_at_ms INTEGER,++ failure_category TEXT NOT NULL DEFAULT 'NONE',+ failure_reason TEXT,+ terminal_at_ms INTEGER,+ started_at_ms INTEGER,+ ended_at_ms INTEGER,+ schedule_enabled INTEGER NOT NULL DEFAULT 1,+ priority INTEGER NOT NULL DEFAULT 0,+ alarm_start_at_ms INTEGER,+ alarm_stop_at_ms INTEGER,+ created_at INTEGER NOT NULL,+ updated_at INTEGER NOT NULL,+ FOREIGN KEY(schedule_id) REFERENCES recording_schedules(id) ON DELETE CASCADE,+ FOREIGN KEY(provider_id) REFERENCES providers(id) ON DELETE CASCADE+ )+ """.trimIndent()+ )+ database.execSQL("CREATE INDEX IF NOT EXISTS index_recording_runs_schedule_id ON recording_runs(schedule_id)")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_recording_runs_provider_id ON recording_runs(provider_id)")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_recording_runs_status_scheduled_start_ms ON recording_runs(status, scheduled_start_ms)")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_recording_runs_alarm_start_at_ms ON recording_runs(alarm_start_at_ms)")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_recording_runs_alarm_stop_at_ms ON recording_runs(alarm_stop_at_ms)")++ database.execSQL(+ """+ CREATE TABLE IF NOT EXISTS recording_storage (+ id INTEGER PRIMARY KEY NOT NULL,+ tree_uri TEXT,+ display_name TEXT,+ output_directory TEXT,+ available_bytes INTEGER,+ is_writable INTEGER NOT NULL DEFAULT 0,+ file_name_pattern TEXT NOT NULL DEFAULT 'ChannelName_yyyy-MM-dd_HH-mm_ProgramTitle.ts',+ retention_days INTEGER,+ max_simultaneous_recordings INTEGER NOT NULL DEFAULT 2,+ updated_at INTEGER NOT NULL+ )+ """.trimIndent()+ )+ val now = System.currentTimeMillis()+ database.execSQL(+ """+ INSERT OR IGNORE INTO recording_storage (+ id, tree_uri, display_name, output_directory, available_bytes, is_writable, file_name_pattern,+ retention_days, max_simultaneous_recordings, updated_at+ ) VALUES (+ 1, NULL, NULL, NULL, NULL, 0, 'ChannelName_yyyy-MM-dd_HH-mm_ProgramTitle.ts', NULL, 2, $now+ )+ """.trimIndent()+ )+ validateForeignKeys(database, "recording_schedules", "recording_runs")+ }+ }++ val MIGRATION_29_30 = object : Migration(29, 30) {+ override fun migrate(database: SupportSQLiteDatabase) {+ database.execSQL(+ """+ CREATE TABLE IF NOT EXISTS combined_m3u_profiles (+ id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,+ name TEXT NOT NULL,+ enabled INTEGER NOT NULL DEFAULT 1,+ created_at INTEGER NOT NULL,+ updated_at INTEGER NOT NULL+ )+ """.trimIndent()+ )+ database.execSQL(+ """+ CREATE TABLE IF NOT EXISTS combined_m3u_profile_members (+ 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 DEFAULT 1,+ FOREIGN KEY(profile_id) REFERENCES combined_m3u_profiles(id) ON DELETE CASCADE,+ FOREIGN KEY(provider_id) REFERENCES providers(id) ON DELETE CASCADE+ )+ """.trimIndent()+ )+ database.execSQL(+ "CREATE INDEX IF NOT EXISTS index_combined_m3u_profile_members_profile_id ON combined_m3u_profile_members(profile_id)"+ )+ database.execSQL(+ "CREATE INDEX IF NOT EXISTS index_combined_m3u_profile_members_provider_id ON combined_m3u_profile_members(provider_id)"+ )+ database.execSQL(+ "CREATE UNIQUE INDEX IF NOT EXISTS index_combined_m3u_profile_members_profile_id_provider_id ON combined_m3u_profile_members(profile_id, provider_id)"+ )+ }+ }++ val MIGRATION_30_31 = object : Migration(30, 31) {+ override fun migrate(database: SupportSQLiteDatabase) {+ database.execSQL("ALTER TABLE movies ADD COLUMN added_at INTEGER NOT NULL DEFAULT 0")+ }+ }++ val MIGRATION_31_32 = object : Migration(31, 32) {+ override fun migrate(database: SupportSQLiteDatabase) {+ database.execSQL("ALTER TABLE movie_import_stage ADD COLUMN added_at INTEGER NOT NULL DEFAULT 0")+ fun firstLong(query: String): Long? = database.query(query).use { cursor ->+ if (cursor.moveToFirst() && !cursor.isNull(0)) cursor.getLong(0) else null+ }++ // FK enforcement was never enabled at runtime (setForeignKeyConstraintsEnabled was+ // never called), so ON DELETE CASCADE never fired when a provider was deleted.+ // Purge orphaned content rows now so the provider_id inference below can only+ // ever produce valid FK values. Favorites pointing to purged content will resolve+ // to NULL and be silently dropped via the `continue` below.+ database.execSQL("DELETE FROM channels WHERE provider_id NOT IN (SELECT id FROM providers)")+ database.execSQL("DELETE FROM movies WHERE provider_id NOT IN (SELECT id FROM providers)")+ database.execSQL("DELETE FROM series WHERE provider_id NOT IN (SELECT id FROM providers)")++ val defaultProviderId = firstLong(+ "SELECT id FROM providers WHERE is_active = 1 ORDER BY id LIMIT 1"+ ) ?: firstLong(+ "SELECT id FROM providers ORDER BY id LIMIT 1"+ )++ database.execSQL(+ """+ CREATE TABLE IF NOT EXISTS virtual_groups_new (+ 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 DELETE CASCADE+ )+ """.trimIndent()+ )++ val providersByLegacyGroup = mutableMapOf<Long, MutableSet<Long>>()+ database.query(+ """+ SELECT f.group_id,+ CASE f.content_type+ WHEN 'LIVE' THEN (SELECT provider_id FROM channels WHERE id = f.content_id)+ WHEN 'MOVIE' THEN (SELECT provider_id FROM movies WHERE id = f.content_id)+ WHEN 'SERIES' THEN (SELECT provider_id FROM series WHERE id = f.content_id)+ ELSE NULL+ END AS provider_id+ FROM favorites f+ WHERE f.group_id IS NOT NULL+ """.trimIndent()+ ).use { cursor ->+ while (cursor.moveToNext()) {+ if (cursor.isNull(0) || cursor.isNull(1)) continue+ val groupId = cursor.getLong(0)++ val providerId = cursor.getLong(1)+ providersByLegacyGroup.getOrPut(groupId) { linkedSetOf() }.add(providerId)+ }+ }++ val groupProviderToNewId = mutableMapOf<Pair<Long, Long>, Long>()+ var nextGroupId = (firstLong("SELECT MAX(id) FROM virtual_groups") ?: 0L) + 1L++ database.query(+ "SELECT id, name, icon_emoji, position, created_at, content_type FROM virtual_groups ORDER BY id"+ ).use { cursor ->+ while (cursor.moveToNext()) {+ val legacyGroupId = cursor.getLong(0)+ val name = cursor.getString(1)+ val iconEmoji = if (cursor.isNull(2)) null else cursor.getString(2)+ val position = cursor.getInt(3)+ val createdAt = cursor.getLong(4)+ val contentType = cursor.getString(5)+ val providerIds = providersByLegacyGroup[legacyGroupId]+ ?.toList()+ ?.sorted()+ ?: defaultProviderId?.let(::listOf)+ ?: emptyList()++ providerIds.forEachIndexed { index, providerId ->+ val newGroupId = if (index == 0) legacyGroupId else nextGroupId+++ groupProviderToNewId[legacyGroupId to providerId] = newGroupId+ database.execSQL(+ """+ INSERT INTO virtual_groups_new(+ id, provider_id, name, icon_emoji, position, created_at, content_type+ ) VALUES (?, ?, ?, ?, ?, ?, ?)+ """.trimIndent(),+ arrayOf<Any?>(newGroupId, providerId, name, iconEmoji, position, createdAt, contentType)+ )+ }+ }+ }++ database.execSQL("ALTER TABLE virtual_groups RENAME TO virtual_groups_legacy")+ database.execSQL("ALTER TABLE virtual_groups_new RENAME TO virtual_groups")+ database.execSQL("DROP INDEX IF EXISTS index_virtual_groups_position")+ database.execSQL("DROP INDEX IF EXISTS index_virtual_groups_content_type")+ database.execSQL(+ "CREATE INDEX IF NOT EXISTS index_virtual_groups_provider_id_content_type ON virtual_groups(provider_id, content_type)"+ )+ database.execSQL(+ "CREATE INDEX IF NOT EXISTS index_virtual_groups_position ON virtual_groups(position)"+ )+ database.execSQL(+ "CREATE INDEX IF NOT EXISTS index_virtual_groups_content_type ON virtual_groups(content_type)"+ )++ database.execSQL(+ """+ CREATE TABLE IF NOT EXISTS favorites_new (+ id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,+ provider_id INTEGER NOT NULL,+ content_id INTEGER NOT NULL,+ content_type TEXT NOT NULL,+ position INTEGER NOT NULL,+ group_id INTEGER,+ added_at INTEGER NOT NULL,+ FOREIGN KEY(provider_id) REFERENCES providers(id) ON DELETE CASCADE,+ FOREIGN KEY(group_id) REFERENCES virtual_groups(id) ON DELETE SET NULL+ )+ """.trimIndent()+ )++ database.query(+ """+ SELECT f.id, f.content_id, f.content_type, f.position, f.group_id, f.added_at,+ CASE f.content_type+ WHEN 'LIVE' THEN (SELECT provider_id FROM channels WHERE id = f.content_id)+ WHEN 'MOVIE' THEN (SELECT provider_id FROM movies WHERE id = f.content_id)+ WHEN 'SERIES' THEN (SELECT provider_id FROM series WHERE id = f.content_id)+ ELSE NULL+ END AS provider_id+ FROM favorites f+ ORDER BY f.id ASC+ """.trimIndent()+ ).use { cursor ->+ while (cursor.moveToNext()) {+ val favoriteId = cursor.getLong(0)+ val contentId = cursor.getLong(1)+ val contentType = cursor.getString(2)+ val position = cursor.getInt(3)+ val legacyGroupId = if (cursor.isNull(4)) null else cursor.getLong(4)+ val addedAt = cursor.getLong(5)+ val providerId = when {+ !cursor.isNull(6) -> cursor.getLong(6)+ legacyGroupId != null -> groupProviderToNewId.keys+ .firstOrNull { it.first == legacyGroupId }+ ?.second+ else -> null+ } ?: continue++ val newGroupId = legacyGroupId?.let { groupId ->+ groupProviderToNewId[groupId to providerId]+ ?: groupProviderToNewId.entries.firstOrNull { it.key.first == groupId }?.value+ }++ database.execSQL(+ """+ INSERT OR REPLACE INTO favorites_new(+ id, provider_id, content_id, content_type, position, group_id, added_at+ ) VALUES (?, ?, ?, ?, ?, ?, ?)+ """.trimIndent(),+ arrayOf<Any?>(favoriteId, providerId, contentId, contentType, position, newGroupId, addedAt)+ )+ }+ }++ database.execSQL("ALTER TABLE favorites RENAME TO favorites_legacy")+ database.execSQL("ALTER TABLE favorites_new RENAME TO favorites")+ database.execSQL("DROP INDEX IF EXISTS index_favorites_group_id_position")+ database.execSQL(+ "CREATE UNIQUE INDEX IF NOT EXISTS index_favorites_provider_id_content_id_content_type_group_id ON favorites(provider_id, content_id, content_type, group_id)"+ )+ database.execSQL(+ "CREATE INDEX IF NOT EXISTS index_favorites_provider_id_content_type_group_id ON favorites(provider_id, content_type, group_id)"+ )+ database.execSQL(+ "CREATE INDEX IF NOT EXISTS index_favorites_group_id_position ON favorites(group_id, position)"+ )++ database.execSQL("DROP TABLE favorites_legacy")+ database.execSQL("DROP TABLE virtual_groups_legacy")+ validateForeignKeys(database, "virtual_groups", "favorites")+ }+ }++ val MIGRATION_32_33 = object : Migration(32, 33) {+ override fun migrate(database: SupportSQLiteDatabase) {+ database.execSQL("ALTER TABLE movies ADD COLUMN watch_count INTEGER NOT NULL DEFAULT 0")+ database.execSQL(+ """+ UPDATE movies+ SET watch_count = COALESCE((+ SELECT playback_history.watch_count+ FROM playback_history+ WHERE playback_history.content_id = movies.id+ AND playback_history.content_type = 'MOVIE'+ AND playback_history.provider_id = movies.provider_id+ ), 0)+ """.trimIndent()+ )+ }+ }++ val MIGRATION_33_34 = object : Migration(33, 34) {+ override fun migrate(database: SupportSQLiteDatabase) {+ database.execSQL("ALTER TABLE sync_metadata ADD COLUMN last_live_success INTEGER NOT NULL DEFAULT 0")+ database.execSQL("ALTER TABLE sync_metadata ADD COLUMN last_series_success INTEGER NOT NULL DEFAULT 0")+ database.execSQL("ALTER TABLE sync_metadata ADD COLUMN last_epg_success INTEGER NOT NULL DEFAULT 0")+ database.execSQL("UPDATE sync_metadata SET last_live_success = last_live_sync")+ database.execSQL("UPDATE sync_metadata SET last_series_success = last_series_sync")+ database.execSQL("UPDATE sync_metadata SET last_epg_success = last_epg_sync")+ database.execSQL(+ "CREATE INDEX IF NOT EXISTS index_programs_provider_id_end_time_channel_id ON programs(provider_id, end_time, channel_id)"+ )+ // No FK-bearing rows added; only column additions and indexes.+ }+ }++ val MIGRATION_34_35 = object : Migration(34, 35) {+ override fun migrate(database: SupportSQLiteDatabase) {+ database.execSQL(+ """+ CREATE TABLE IF NOT EXISTS search_history (+ id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,+ query TEXT NOT NULL,+ content_scope TEXT NOT NULL,+ provider_id INTEGER NOT NULL DEFAULT 0,+ used_at INTEGER NOT NULL,+ use_count INTEGER NOT NULL DEFAULT 1+ )+ """.trimIndent()+ )+ database.execSQL(+ "CREATE INDEX IF NOT EXISTS index_search_history_content_scope_provider_id_used_at ON search_history(content_scope, provider_id, used_at)"+ )+ database.execSQL(+ "CREATE INDEX IF NOT EXISTS index_search_history_used_at ON search_history(used_at)"+ )+ database.execSQL(+ "CREATE INDEX IF NOT EXISTS index_search_history_provider_id ON search_history(provider_id)"+ )+ database.execSQL(+ "CREATE UNIQUE INDEX IF NOT EXISTS index_search_history_query_content_scope_provider_id ON search_history(query, content_scope, provider_id)"+ )+ // search_history has no FK columns; no FK check needed.+ }+ }++ val MIGRATION_35_36 = object : Migration(35, 36) {+ override fun migrate(database: SupportSQLiteDatabase) {+ database.execSQL("ALTER TABLE channel_epg_mappings ADD COLUMN matched_at INTEGER NOT NULL DEFAULT 0")+ database.execSQL("ALTER TABLE channel_epg_mappings ADD COLUMN failed_attempts INTEGER NOT NULL DEFAULT 0")+ database.execSQL("ALTER TABLE channel_epg_mappings ADD COLUMN source TEXT")++ database.execSQL(+ """+ CREATE TABLE IF NOT EXISTS program_reminders (+ 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 DEFAULT 5,+ is_dismissed INTEGER NOT NULL DEFAULT 0,+ notified_at INTEGER,+ created_at INTEGER NOT NULL,+ FOREIGN KEY(provider_id) REFERENCES providers(id) ON DELETE CASCADE+ )+ """.trimIndent()+ )+ database.execSQL(+ "CREATE INDEX IF NOT EXISTS index_program_reminders_provider_id_remind_at ON program_reminders(provider_id, remind_at)"+ )+ database.execSQL(+ "CREATE INDEX IF NOT EXISTS index_program_reminders_is_dismissed_notified_at_remind_at ON program_reminders(is_dismissed, notified_at, remind_at)"+ )+ database.execSQL(+ "CREATE INDEX IF NOT EXISTS index_program_reminders_provider_id_channel_id_program_start_time ON program_reminders(provider_id, channel_id, program_start_time)"+ )+ database.execSQL(+ "CREATE UNIQUE INDEX IF NOT EXISTS index_program_reminders_provider_id_channel_id_program_title_program_start_time ON program_reminders(provider_id, channel_id, program_title, program_start_time)"+ )+ validateForeignKeys(database, "program_reminders")+ }+ }++ val MIGRATION_36_37 = object : Migration(36, 37) {+ override fun migrate(database: SupportSQLiteDatabase) {+ database.execSQL(+ """+ CREATE TABLE IF NOT EXISTS tmdb_identity (+ 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 DELETE CASCADE+ )+ """.trimIndent()+ )+ database.execSQL("CREATE INDEX IF NOT EXISTS index_tmdb_identity_content_type ON tmdb_identity(content_type)")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_tmdb_identity_canonical_provider_id ON tmdb_identity(canonical_provider_id)")+ database.execSQL(+ """+ INSERT OR REPLACE INTO tmdb_identity (tmdb_id, content_type, canonical_provider_id, first_seen_at)+ SELECT tmdb_id, 'MOVIE', MIN(provider_id), 0+ FROM movies+ WHERE tmdb_id IS NOT NULL+ GROUP BY tmdb_id+ """.trimIndent()+ )+ database.execSQL(+ """+ INSERT OR REPLACE INTO tmdb_identity (tmdb_id, content_type, canonical_provider_id, first_seen_at)+ SELECT tmdb_id, 'SERIES', MIN(provider_id), 0+ FROM series+ WHERE tmdb_id IS NOT NULL+ GROUP BY tmdb_id+ """.trimIndent()+ )+ validateForeignKeys(database, "tmdb_identity")+ }+ }++ val MIGRATION_37_38 = object : Migration(37, 38) {+ override fun migrate(database: SupportSQLiteDatabase) {+ database.execSQL("ALTER TABLE epg_sources ADD COLUMN etag TEXT DEFAULT NULL")+ database.execSQL("ALTER TABLE epg_sources ADD COLUMN last_modified_header TEXT DEFAULT NULL")+ }+ }++ val MIGRATION_38_39 = object : Migration(38, 39) {+ override fun migrate(database: SupportSQLiteDatabase) {+ database.execSQL("ALTER TABLE providers ADD COLUMN stalker_mac_address TEXT NOT NULL DEFAULT ''")+ database.execSQL("ALTER TABLE providers ADD COLUMN stalker_device_profile TEXT NOT NULL DEFAULT ''")+ database.execSQL("ALTER TABLE providers ADD COLUMN stalker_device_timezone TEXT NOT NULL DEFAULT ''")+ database.execSQL("ALTER TABLE providers ADD COLUMN stalker_device_locale TEXT NOT NULL DEFAULT ''")+ database.execSQL("DROP INDEX IF EXISTS index_providers_server_url_username")+ database.execSQL("DROP INDEX IF EXISTS index_providers_server_url_username_stalker_mac_address")+ database.execSQL(+ """+ CREATE UNIQUE INDEX IF NOT EXISTS index_providers_server_url_username_stalker_mac_address+ ON providers(server_url, username, stalker_mac_address)+ """.trimIndent()+ )+ }+ }++ /**+ * Migration 39 → 40: Drop per-row FTS triggers.+ * The triggers (channels_ai/ad/au, movies_ai/ad/au, series_ai/ad/au) fired for every+ * individual row INSERT/DELETE/UPDATE and serialised 52k+ writes through the FTS index+ * one row at a time, causing minute-long first-sync freezes on large providers.+ * FTS is now rebuilt in bulk via INSERT INTO table_fts(table_fts) VALUES('rebuild')+ * once per sync, after each catalog transaction commits.+ */++ val MIGRATION_39_40 = object : Migration(39, 40) {+ override fun migrate(database: SupportSQLiteDatabase) {+ database.execSQL("DROP TRIGGER IF EXISTS channels_ai")+ database.execSQL("DROP TRIGGER IF EXISTS channels_ad")+ database.execSQL("DROP TRIGGER IF EXISTS channels_au")+ database.execSQL("DROP TRIGGER IF EXISTS movies_ai")+ database.execSQL("DROP TRIGGER IF EXISTS movies_ad")+ database.execSQL("DROP TRIGGER IF EXISTS movies_au")+ database.execSQL("DROP TRIGGER IF EXISTS series_ai")+ database.execSQL("DROP TRIGGER IF EXISTS series_ad")+ database.execSQL("DROP TRIGGER IF EXISTS series_au")+ }+ }++ /**+ * Migration 40 → 41: add per-channel A/V sync override.+ * Null means the channel follows the global player default.+ */++ val MIGRATION_40_41 = object : Migration(40, 41) {+ override fun migrate(database: SupportSQLiteDatabase) {+ database.execSQL("ALTER TABLE channel_preferences ADD COLUMN audio_video_offset_ms INTEGER DEFAULT NULL")+ }+ }++ /**+ * Migration 41 -> 42: remember playback decoder/surface combinations that fail+ * silently on a device so Auto mode can avoid repeating them.+ */++ val MIGRATION_41_42 = object : Migration(41, 42) {+ override fun migrate(database: SupportSQLiteDatabase) {+ database.execSQL(+ """+ CREATE TABLE IF NOT EXISTS playback_compatibility_records (+ 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 DEFAULT '',+ last_failed_at INTEGER NOT NULL DEFAULT 0,+ last_succeeded_at INTEGER NOT NULL DEFAULT 0,+ failure_count INTEGER NOT NULL DEFAULT 0,++ success_count INTEGER NOT NULL DEFAULT 0+ )+ """.trimIndent()+ )+ database.execSQL(+ """+ CREATE UNIQUE INDEX IF NOT EXISTS index_playback_compatibility_records_device_fingerprint_stream_type_video_mime_type_resolution_bucket_decoder_name_surface_type+ ON playback_compatibility_records(device_fingerprint, stream_type, video_mime_type, resolution_bucket, decoder_name, surface_type)+ """.trimIndent()+ )+ database.execSQL(+ """+ CREATE INDEX IF NOT EXISTS index_playback_compatibility_records_device_fingerprint_stream_type_video_mime_type_resolution_bucket+ ON playback_compatibility_records(device_fingerprint, stream_type, video_mime_type, resolution_bucket)+ """.trimIndent()+ )+ database.execSQL("CREATE INDEX IF NOT EXISTS index_playback_compatibility_records_last_failed_at ON playback_compatibility_records(last_failed_at)")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_playback_compatibility_records_last_succeeded_at ON playback_compatibility_records(last_succeeded_at)")+ }+ }++ /**+ * Migration 42 -> 43: preserve provider-native series identifiers so Stalker+ * series details can round-trip composite portal IDs.+ */++ val MIGRATION_42_43 = object : Migration(42, 43) {+ override fun migrate(database: SupportSQLiteDatabase) {+ database.execSQL("ALTER TABLE series ADD COLUMN provider_series_id TEXT")+ database.execSQL(+ "UPDATE series SET provider_series_id = CAST(series_id AS TEXT) WHERE provider_series_id IS NULL"+ )+ }+ }++ /**+ * Migration 43 -> 44: add page-aware VOD/series category hydration metadata+ * for on-demand Stalker paging while preserving existing complete caches.+ */++ val MIGRATION_43_44 = object : Migration(43, 44) {+ override fun migrate(database: SupportSQLiteDatabase) {+ addPagedHydrationColumns(database, "movie_category_hydration")+ addPagedHydrationColumns(database, "series_category_hydration")+ }++ private fun addPagedHydrationColumns(database: SupportSQLiteDatabase, tableName: String) {+ database.execSQL("ALTER TABLE $tableName ADD COLUMN last_loaded_page INTEGER NOT NULL DEFAULT 0")+ database.execSQL("ALTER TABLE $tableName ADD COLUMN total_pages INTEGER NOT NULL DEFAULT 0")+ database.execSQL("ALTER TABLE $tableName ADD COLUMN is_complete INTEGER NOT NULL DEFAULT 0")+ database.execSQL("ALTER TABLE $tableName ADD COLUMN page_size INTEGER NOT NULL DEFAULT 0")+ database.execSQL(+ """+ UPDATE $tableName+ SET last_loaded_page = CASE+ WHEN last_status = 'SUCCESS' THEN 1+ ELSE 0+ END,+ total_pages = CASE+ WHEN last_status = 'SUCCESS' THEN 1+ ELSE 0+ END,+ is_complete = CASE+ WHEN last_status = 'SUCCESS' THEN 1+ ELSE 0+ END,+ page_size = CASE+ WHEN last_status = 'SUCCESS' THEN item_count+ ELSE 0+ END+ """.trimIndent()+ )+ }+ }++ /**+ * Migration 44 -> 45: make favorite uniqueness null-safe by materializing a non-null+ * group scope key and deduping any pre-existing global favorite collisions.+ */++ val MIGRATION_44_45 = object : Migration(44, 45) {+ override fun migrate(database: SupportSQLiteDatabase) {+ database.execSQL("ALTER TABLE favorites ADD COLUMN group_key INTEGER NOT NULL DEFAULT 0")+ database.execSQL("UPDATE favorites SET group_key = COALESCE(group_id, 0)")+ database.execSQL(+ """+ UPDATE favorites+ SET position = (+ SELECT MIN(dupe.position)+ FROM favorites AS dupe+ WHERE dupe.group_id IS NULL+ AND dupe.provider_id = favorites.provider_id+ AND dupe.content_id = favorites.content_id+ AND dupe.content_type = favorites.content_type+ ),+ added_at = (+ SELECT MIN(dupe.added_at)+ FROM favorites AS dupe+ WHERE dupe.group_id IS NULL+ AND dupe.provider_id = favorites.provider_id+ AND dupe.content_id = favorites.content_id+ AND dupe.content_type = favorites.content_type+ )+ WHERE favorites.group_id IS NULL+ AND favorites.id IN (+ SELECT MIN(id)+ FROM favorites+ WHERE group_id IS NULL+ GROUP BY provider_id, content_id, content_type+ HAVING COUNT(*) > 1+ )+ """.trimIndent()+ )+ database.execSQL(+ """+ DELETE FROM favorites+ WHERE group_id IS NULL+ AND id NOT IN (+ SELECT MIN(id)+ FROM favorites+ WHERE group_id IS NULL+ GROUP BY provider_id, content_id, content_type+ )+ """.trimIndent()+ )++ database.execSQL("DROP INDEX IF EXISTS index_favorites_provider_id_content_id_content_type_group_id")+ database.execSQL("DROP TABLE IF EXISTS favorites_new")+ database.execSQL(+ """+ CREATE TABLE IF NOT EXISTS favorites_new (+ 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 DELETE CASCADE,+ FOREIGN KEY(group_id) REFERENCES virtual_groups(id) ON DELETE SET NULL+ )+ """.trimIndent()+ )+ database.execSQL(+ """+ INSERT INTO favorites_new(+ id,+ provider_id,+ content_id,+ content_type,+ position,+ group_id,++ group_key,+ added_at+ )+ SELECT+ id,+ provider_id,+ content_id,+ content_type,+ position,+ group_id,+ group_key,+ added_at+ FROM favorites+ """.trimIndent()+ )+ database.execSQL("DROP TABLE favorites")+ database.execSQL("ALTER TABLE favorites_new RENAME TO favorites")+ database.execSQL(+ "CREATE UNIQUE INDEX IF NOT EXISTS index_favorites_provider_id_content_id_content_type_group_key ON favorites(provider_id, content_id, content_type, group_key)"+ )+ database.execSQL(+ "CREATE INDEX IF NOT EXISTS index_favorites_provider_id_content_type_group_id ON favorites(provider_id, content_type, group_id)"+ )+ database.execSQL(+ "CREATE INDEX IF NOT EXISTS index_favorites_group_id_position ON favorites(group_id, position)"+ )+ validateForeignKeys(database, "favorites")+ }+ }++ /**+ * Migration 45 -> 46: preserve provider-native series IDs through staging by storing both+ * the raw provider ID and a non-null remote key used for staged apply matching.+ */++ val MIGRATION_45_46 = object : Migration(45, 46) {+ override fun migrate(database: SupportSQLiteDatabase) {+ database.execSQL(+ """+ CREATE TABLE IF NOT EXISTS series_import_stage_new (+ 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 DELETE CASCADE+ )+ """.trimIndent()+ )+ database.execSQL(+ """+ INSERT INTO series_import_stage_new (+ session_id,+ provider_id,+ series_id,+ provider_series_id,+ provider_series_key,+ name,+ poster_url,+ backdrop_url,+ category_id,+ category_name,+ plot,+ "cast",+ director,+ genre,+ release_date,+ rating,+ tmdb_id,+ youtube_trailer,+ episode_run_time,+ last_modified,+ is_adult,+ sync_fingerprint+ )+ SELECT+ session_id,+ provider_id,+ series_id,+ NULL,+ CAST(series_id AS TEXT),+ name,+ poster_url,+ backdrop_url,+ category_id,+ category_name,+ plot,+ "cast",+ director,+ genre,+ release_date,+ rating,+ tmdb_id,+ youtube_trailer,+ episode_run_time,+ last_modified,+ is_adult,+ sync_fingerprint+ FROM series_import_stage+ """.trimIndent()+ )+ database.execSQL("DROP TABLE series_import_stage")+ database.execSQL("ALTER TABLE series_import_stage_new RENAME TO series_import_stage")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_series_import_stage_provider_id ON series_import_stage(provider_id)")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_series_import_stage_session_id_provider_id ON series_import_stage(session_id, provider_id)")+ validateForeignKeys(database, "series_import_stage")+ }+ }++ /**+ * Migration 46 -> 47: add provider-leading browse indexes so large-provider cursor pages,+ * category/rating sorts, and correlated playback-history filters avoid wide scans.+ */++ val MIGRATION_46_47 = object : Migration(46, 47) {+ override fun migrate(database: SupportSQLiteDatabase) {+ database.execSQL("CREATE INDEX IF NOT EXISTS index_movies_provider_id_name_id ON movies(provider_id, name, id)")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_movies_provider_id_category_id_name_id ON movies(provider_id, category_id, name, id)")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_movies_provider_id_rating_name_id ON movies(provider_id, rating, name, id)")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_movies_provider_id_added_at_release_date_name_id ON movies(provider_id, added_at, release_date, name, id)")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_series_provider_id_name_id ON series(provider_id, name, id)")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_series_provider_id_category_id_name_id ON series(provider_id, category_id, name, id)")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_series_provider_id_rating_name_id ON series(provider_id, rating, name, id)")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_series_provider_id_last_modified_name_id ON series(provider_id, last_modified, name, id)")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_playback_history_provider_id_content_type_content_id ON playback_history(provider_id, content_type, content_id)")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_playback_history_provider_id_content_type_last_watched_at ON playback_history(provider_id, content_type, last_watched_at)")+ }+ }++ /**+ * Migration 47 -> 48: create the Xtream summary index and section job state tables.+ * Existing Xtream live/movie/series rows are backfilled without deleting or remapping+ * the playable/detail tables that favorites and history already reference.+ */++ val MIGRATION_47_48 = object : Migration(47, 48) {+ override fun migrate(database: SupportSQLiteDatabase) {+ database.execSQL("ALTER TABLE providers ADD COLUMN http_user_agent TEXT NOT NULL DEFAULT ''")+ database.execSQL("ALTER TABLE providers ADD COLUMN http_headers TEXT NOT NULL DEFAULT ''")+ database.execSQL("ALTER TABLE movies ADD COLUMN cache_state TEXT NOT NULL DEFAULT 'DETAIL_HYDRATED'")+ database.execSQL("ALTER TABLE movies ADD COLUMN detail_hydrated_at INTEGER NOT NULL DEFAULT 0")+ database.execSQL("ALTER TABLE movies ADD COLUMN remote_stale_at INTEGER NOT NULL DEFAULT 0")+ database.execSQL("ALTER TABLE series ADD COLUMN cache_state TEXT NOT NULL DEFAULT 'DETAIL_HYDRATED'")+ database.execSQL("ALTER TABLE series ADD COLUMN detail_hydrated_at INTEGER NOT NULL DEFAULT 0")+ database.execSQL("ALTER TABLE series ADD COLUMN remote_stale_at INTEGER NOT NULL DEFAULT 0")++ database.execSQL(+ """+ UPDATE movies+ SET cache_state = 'SUMMARY_ONLY'+ WHERE COALESCE(plot, '') = ''+ AND COALESCE("cast", '') = ''+ AND COALESCE(director, '') = ''+ AND COALESCE(genre, '') = ''+ AND COALESCE(duration, '') = ''+ AND duration_seconds = 0+ AND tmdb_id IS NULL+ """.trimIndent()+ )+ database.execSQL(+ """+ UPDATE series+ SET cache_state = 'SUMMARY_ONLY'+ WHERE COALESCE(plot, '') = ''+ AND COALESCE("cast", '') = ''+ AND COALESCE(director, '') = ''+ AND COALESCE(genre, '') = ''+ AND COALESCE(episode_run_time, '') = ''+ AND tmdb_id IS NULL+ """.trimIndent()+ )+ database.execSQL(+ """+ UPDATE movies+ SET detail_hydrated_at = COALESCE(+ (SELECT providers.last_synced_at FROM providers WHERE providers.id = movies.provider_id),+ 0+ )+ WHERE cache_state = 'DETAIL_HYDRATED'+ """.trimIndent()+ )+ database.execSQL(+ """+ UPDATE series+ SET detail_hydrated_at = COALESCE(+ (SELECT providers.last_synced_at FROM providers WHERE providers.id = series.provider_id),+ 0+ )+ WHERE cache_state = 'DETAIL_HYDRATED'+ """.trimIndent()+ )++ database.execSQL(+ """+ CREATE TABLE IF NOT EXISTS xtream_content_index (+ 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 DELETE CASCADE+ )+ """.trimIndent()+ )+ database.execSQL("CREATE INDEX IF NOT EXISTS index_xtream_content_index_provider_id_content_type ON xtream_content_index(provider_id, content_type)")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_xtream_content_index_provider_id_content_type_category_id ON xtream_content_index(provider_id, content_type, category_id)")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_xtream_content_index_provider_id_content_type_name ON xtream_content_index(provider_id, content_type, name)")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_xtream_content_index_provider_id_content_type_local_content_id ON xtream_content_index(provider_id, content_type, local_content_id)")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_xtream_content_index_provider_id_indexed_at ON xtream_content_index(provider_id, indexed_at)")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_xtream_content_index_stale_state ON xtream_content_index(stale_state)")++ database.execSQL(+ """+ CREATE TABLE IF NOT EXISTS xtream_index_jobs (+ 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 DELETE CASCADE+ )+ """.trimIndent()+ )+ database.execSQL("CREATE INDEX IF NOT EXISTS index_xtream_index_jobs_provider_id ON xtream_index_jobs(provider_id)")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_xtream_index_jobs_section ON xtream_index_jobs(section)")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_xtream_index_jobs_state ON xtream_index_jobs(state)")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_xtream_index_jobs_updated_at ON xtream_index_jobs(updated_at)")++ database.execSQL(+ """+ INSERT OR REPLACE INTO xtream_content_index (+ provider_id, content_type, remote_id, local_content_id, name, category_id,+ category_name, image_url, container_extension, rating, added_at, remote_updated_at,+ is_adult, indexed_at, detail_hydrated_at, stale_state, error_state, sync_fingerprint+ )+ SELECT+ c.provider_id,+ 'LIVE',+ CAST(c.stream_id AS TEXT),+ c.id,+ c.name,+ c.category_id,+ c.category_name,+ c.logo_url,+ NULL,+ 0,+ 0,+ 0,+ c.is_adult,+ COALESCE(p.last_synced_at, 0),+ COALESCE(p.last_synced_at, 0),+ 'ACTIVE',+ NULL,+ c.sync_fingerprint+ FROM channels c+ JOIN providers p ON p.id = c.provider_id+ WHERE p.type = 'XTREAM_CODES'+ """.trimIndent()+ )+ database.execSQL(+ """++ INSERT OR REPLACE INTO xtream_content_index (+ provider_id, content_type, remote_id, local_content_id, name, category_id,+ category_name, image_url, container_extension, rating, added_at, remote_updated_at,+ is_adult, indexed_at, detail_hydrated_at, stale_state, error_state, sync_fingerprint+ )+ SELECT+ m.provider_id,+ 'MOVIE',+ CAST(m.stream_id AS TEXT),+ m.id,+ m.name,+ m.category_id,+ m.category_name,+ m.poster_url,+ m.container_extension,+ m.rating,+ m.added_at,+ 0,+ m.is_adult,+ COALESCE(p.last_synced_at, 0),+ CASE WHEN m.cache_state = 'DETAIL_HYDRATED' THEN COALESCE(p.last_synced_at, 0) ELSE 0 END,+ 'ACTIVE',+ NULL,+ m.sync_fingerprint+ FROM movies m+ JOIN providers p ON p.id = m.provider_id+ WHERE p.type = 'XTREAM_CODES'+ """.trimIndent()+ )+ database.execSQL(+ """+ INSERT OR REPLACE INTO xtream_content_index (+ provider_id, content_type, remote_id, local_content_id, name, category_id,+ category_name, image_url, container_extension, rating, added_at, remote_updated_at,+ is_adult, indexed_at, detail_hydrated_at, stale_state, error_state, sync_fingerprint+ )+ SELECT+ s.provider_id,+ 'SERIES',+ COALESCE(s.provider_series_id, CAST(s.series_id AS TEXT)),+ s.id,+ s.name,+ s.category_id,+ s.category_name,+ s.poster_url,+ NULL,+ s.rating,+ 0,+ s.last_modified,+ s.is_adult,+ COALESCE(p.last_synced_at, 0),+ CASE WHEN s.cache_state = 'DETAIL_HYDRATED' THEN COALESCE(p.last_synced_at, 0) ELSE 0 END,+ 'ACTIVE',+ NULL,+ s.sync_fingerprint+ FROM series s+ JOIN providers p ON p.id = s.provider_id+ WHERE p.type = 'XTREAM_CODES'+ """.trimIndent()+ )++ database.execSQL(+ """+ INSERT OR REPLACE INTO xtream_index_jobs (+ provider_id, section, state, total_categories, completed_categories, next_category_index, failed_categories,+ indexed_rows, skipped_malformed_rows, deleted_pruned_rows, priority_category_id, priority_requested_at, last_error,+ last_attempt_at, last_success_at, updated_at+ )+ SELECT+ p.id,+ section.name,+ CASE+ WHEN section.name = 'LIVE' AND (+ COALESCE(NULLIF(sm.last_live_success, 0), NULLIF(sm.last_live_sync, 0), 0) > 0+ OR (SELECT COUNT(*) FROM channels c WHERE c.provider_id = p.id) > 0+ ) THEN 'SUCCESS'+ WHEN section.name = 'MOVIE' AND (+ COALESCE(NULLIF(sm.last_movie_success, 0), NULLIF(sm.last_movie_sync, 0), 0) > 0+ OR (SELECT COUNT(*) FROM movies m WHERE m.provider_id = p.id) > 0+ ) THEN 'SUCCESS'+ WHEN section.name = 'SERIES' AND (+ COALESCE(NULLIF(sm.last_series_success, 0), NULLIF(sm.last_series_sync, 0), 0) > 0+ OR (SELECT COUNT(*) FROM series s WHERE s.provider_id = p.id) > 0+ ) THEN 'SUCCESS'+ WHEN section.name = 'EPG' AND COALESCE(NULLIF(sm.last_epg_success, 0), NULLIF(sm.last_epg_sync, 0), 0) > 0 THEN 'SUCCESS'+ ELSE 'IDLE'+ END,+ CASE section.name+ WHEN 'LIVE' THEN (SELECT COUNT(*) FROM categories cat WHERE cat.provider_id = p.id AND cat.type = 'LIVE')+ WHEN 'MOVIE' THEN (SELECT COUNT(*) FROM categories cat WHERE cat.provider_id = p.id AND cat.type = 'MOVIE')+ WHEN 'SERIES' THEN (SELECT COUNT(*) FROM categories cat WHERE cat.provider_id = p.id AND cat.type = 'SERIES')+ ELSE 0+ END,+ CASE+ WHEN section.name = 'LIVE' AND (SELECT COUNT(*) FROM channels c WHERE c.provider_id = p.id) > 0+ THEN (SELECT COUNT(*) FROM categories cat WHERE cat.provider_id = p.id AND cat.type = 'LIVE')+ WHEN section.name = 'MOVIE' AND (SELECT COUNT(*) FROM movies m WHERE m.provider_id = p.id) > 0+ THEN (SELECT COUNT(*) FROM categories cat WHERE cat.provider_id = p.id AND cat.type = 'MOVIE')+ WHEN section.name = 'SERIES' AND (SELECT COUNT(*) FROM series s WHERE s.provider_id = p.id) > 0+ THEN (SELECT COUNT(*) FROM categories cat WHERE cat.provider_id = p.id AND cat.type = 'SERIES')+ ELSE 0+ END,+ CASE+ WHEN section.name = 'LIVE' AND (SELECT COUNT(*) FROM channels c WHERE c.provider_id = p.id) > 0+ THEN (SELECT COUNT(*) FROM categories cat WHERE cat.provider_id = p.id AND cat.type = 'LIVE')+ WHEN section.name = 'MOVIE' AND (SELECT COUNT(*) FROM movies m WHERE m.provider_id = p.id) > 0+ THEN (SELECT COUNT(*) FROM categories cat WHERE cat.provider_id = p.id AND cat.type = 'MOVIE')+ WHEN section.name = 'SERIES' AND (SELECT COUNT(*) FROM series s WHERE s.provider_id = p.id) > 0+ THEN (SELECT COUNT(*) FROM categories cat WHERE cat.provider_id = p.id AND cat.type = 'SERIES')+ ELSE 0+ END,+ 0,+ CASE section.name+ WHEN 'LIVE' THEN (SELECT COUNT(*) FROM channels c WHERE c.provider_id = p.id)+ WHEN 'MOVIE' THEN (SELECT COUNT(*) FROM movies m WHERE m.provider_id = p.id)+ WHEN 'SERIES' THEN (SELECT COUNT(*) FROM series s WHERE s.provider_id = p.id)+ WHEN 'EPG' THEN COALESCE(sm.epg_count, 0)+ ELSE 0+ END,+ 0,+ 0,+ NULL,+ 0,+ NULL,+ CASE section.name+ WHEN 'LIVE' THEN COALESCE(sm.last_live_sync, 0)+ WHEN 'MOVIE' THEN COALESCE(NULLIF(sm.last_movie_attempt, 0), sm.last_movie_sync, 0)+ WHEN 'SERIES' THEN COALESCE(sm.last_series_sync, 0)+ WHEN 'EPG' THEN COALESCE(sm.last_epg_sync, 0)+ ELSE 0+ END,+ CASE section.name+ WHEN 'LIVE' THEN COALESCE(NULLIF(sm.last_live_success, 0), sm.last_live_sync, 0)+ WHEN 'MOVIE' THEN COALESCE(NULLIF(sm.last_movie_success, 0), sm.last_movie_sync, 0)+ WHEN 'SERIES' THEN COALESCE(NULLIF(sm.last_series_success, 0), sm.last_series_sync, 0)+ WHEN 'EPG' THEN COALESCE(NULLIF(sm.last_epg_success, 0), sm.last_epg_sync, 0)+ ELSE 0+ END,+ COALESCE(p.last_synced_at, 0)+ FROM providers p+ CROSS JOIN (+ SELECT 'LIVE' AS name+ UNION ALL SELECT 'MOVIE'+ UNION ALL SELECT 'SERIES'+ UNION ALL SELECT 'EPG'+ ) section+ LEFT JOIN sync_metadata sm ON sm.provider_id = p.id+ WHERE p.type = 'XTREAM_CODES'+ """.trimIndent()+ )+++ validateForeignKeys(database, "xtream_content_index", "xtream_index_jobs")+ }+ }++ val MIGRATION_48_49 = object : Migration(48, 49) {+ override fun migrate(database: SupportSQLiteDatabase) {+ // Schema 49 is identical to 48. HTTP profile columns shipped in schema 48.+ }+ }++ val all: List<Migration> = listOf(+ MIGRATION_24_25,+ MIGRATION_25_26,+ MIGRATION_26_27,+ MIGRATION_27_28,+ MIGRATION_28_29,+ MIGRATION_29_30,+ MIGRATION_30_31,+ MIGRATION_31_32,+ MIGRATION_32_33,+ MIGRATION_33_34,+ MIGRATION_34_35,+ MIGRATION_35_36,+ MIGRATION_36_37,+ MIGRATION_37_38,+ MIGRATION_38_39,+ MIGRATION_39_40,+ MIGRATION_40_41,+ MIGRATION_41_42,+ MIGRATION_42_43,+ MIGRATION_43_44,+ MIGRATION_44_45,+ MIGRATION_45_46,+ MIGRATION_46_47,+ MIGRATION_47_48,+ MIGRATION_48_49+ )+}diff --git a/data/src/main/java/com/streamvault/data/local/MigrationSupport.kt b/data/src/main/java/com/streamvault/data/local/MigrationSupport.ktnew file mode 100644index 00000000..93fc5c53--- /dev/null+++ b/data/src/main/java/com/streamvault/data/local/MigrationSupport.kt@@ -0,0 +1,126 @@+package com.streamvault.data.local++import androidx.sqlite.db.SupportSQLiteDatabase+import org.json.JSONObject+import java.net.URI++/** Shared, reviewable assertions and deterministic backfill helpers for versioned migrations. */+/**+ * Checks FK integrity for the specified tables only.+ * Always pass the tables the migration actually wrote to — never call with no arguments,+ * as that would check the entire database and can crash on pre-existing violations in+ * unrelated tables that the migration didn't touch.+ */+internal fun validateForeignKeys(database: SupportSQLiteDatabase, vararg tableNames: String) {+ for (table in tableNames) {+ database.query("PRAGMA foreign_key_check($table)").use { cursor ->+ if (cursor.moveToFirst()) {+ val tbl = 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 migration: table=$tbl rowId=$rowId parent=$parent"+ )+ }+ }+ }+}++/**+ * Migration 1 → 2: no-op stub.+ * v1 databases had the same table structure as v2; this migration prevents Room+ * from crashing with an "unsatisfied migration" exception on very early installs.+ */++++internal 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())+ }+}++internal 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)+}++internal 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() }++internal fun tableHasColumn(+ database: SupportSQLiteDatabase,+ tableName: String,+ columnName: String+): Boolean {+ database.query("PRAGMA table_info($tableName)").use { cursor ->+ val nameIndex = cursor.getColumnIndex("name")+ while (cursor.moveToNext()) {+ if (nameIndex >= 0 && cursor.getString(nameIndex) == columnName) {+ return true+ }+ }+ }+ return false+}diff --git a/data/src/main/java/com/streamvault/data/local/StreamVaultDatabase.kt b/data/src/main/java/com/streamvault/data/local/StreamVaultDatabase.ktindex e274d241..8b1d83ca 100644--- a/data/src/main/java/com/streamvault/data/local/StreamVaultDatabase.kt+++ b/data/src/main/java/com/streamvault/data/local/StreamVaultDatabase.kt@@ -1,3 +1,4 @@+package com.streamvault.data.localimport androidx.room.Database@@ -122,3614 +123,79 @@ abstract class StreamVaultDatabase : RoomDatabase() {abstract fun providerWorkflowDao(): ProviderWorkflowDaocompanion object {- /**- * Checks FK integrity for the specified tables only.- * Always pass the tables the migration actually wrote to — never call with no arguments,- * as that would check the entire database and can crash on pre-existing violations in- * unrelated tables that the migration didn't touch.- */- private fun validateForeignKeys(database: SupportSQLiteDatabase, vararg tableNames: String) {- for (table in tableNames) {- database.query("PRAGMA foreign_key_check($table)").use { cursor ->- if (cursor.moveToFirst()) {- val tbl = 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 migration: table=$tbl rowId=$rowId parent=$parent"- )- }- }- }- }-- /**- * Migration 1 → 2: no-op stub.- * v1 databases had the same table structure as v2; this migration prevents Room- * from crashing with an "unsatisfied migration" exception on very early installs.- */- val MIGRATION_1_2 = object : Migration(1, 2) {- override fun migrate(database: SupportSQLiteDatabase) {- // Schema was identical between v1 and v2; nothing to alter.- }- }-- /**- * Migration 2 → 3: added parental-control protection columns.- */- val MIGRATION_2_3 = object : Migration(2, 3) {- override fun migrate(database: SupportSQLiteDatabase) {- database.execSQL("ALTER TABLE categories ADD COLUMN is_user_protected INTEGER NOT NULL DEFAULT 0")- database.execSQL("ALTER TABLE channels ADD COLUMN is_user_protected INTEGER NOT NULL DEFAULT 0")- database.execSQL("ALTER TABLE movies ADD COLUMN is_adult INTEGER NOT NULL DEFAULT 0")- database.execSQL("ALTER TABLE movies ADD COLUMN is_user_protected INTEGER NOT NULL DEFAULT 0")- database.execSQL("ALTER TABLE series ADD COLUMN is_adult INTEGER NOT NULL DEFAULT 0")- database.execSQL("ALTER TABLE series ADD COLUMN is_user_protected INTEGER NOT NULL DEFAULT 0")- database.execSQL("ALTER TABLE episodes ADD COLUMN is_adult INTEGER NOT NULL DEFAULT 0")- database.execSQL("ALTER TABLE episodes ADD COLUMN is_user_protected INTEGER NOT NULL DEFAULT 0")- }- }-- val MIGRATION_3_4 = object : Migration(3, 4) {- override fun migrate(database: SupportSQLiteDatabase) {- // 1. Create playback_history table- database.execSQL("""- CREATE TABLE IF NOT EXISTS playback_history (- 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 DEFAULT '',- poster_url TEXT,- stream_url TEXT NOT NULL DEFAULT '',- resume_position_ms INTEGER NOT NULL DEFAULT 0,- total_duration_ms INTEGER NOT NULL DEFAULT 0,- last_watched_at INTEGER NOT NULL DEFAULT 0,- watch_count INTEGER NOT NULL DEFAULT 1,- series_id INTEGER,- season_number INTEGER,- episode_number INTEGER- )- """)- database.execSQL("CREATE UNIQUE INDEX IF NOT EXISTS idx_history_unique ON playback_history(content_id, content_type, provider_id)")- database.execSQL("CREATE INDEX IF NOT EXISTS idx_history_last_watched ON playback_history(last_watched_at DESC)")- database.execSQL("CREATE INDEX IF NOT EXISTS idx_history_provider ON playback_history(provider_id)")-- // 2. Create sync_metadata table- database.execSQL("""- CREATE TABLE IF NOT EXISTS sync_metadata (- provider_id INTEGER PRIMARY KEY NOT NULL,- last_live_sync INTEGER NOT NULL DEFAULT 0,- last_movie_sync INTEGER NOT NULL DEFAULT 0,- last_series_sync INTEGER NOT NULL DEFAULT 0,- last_epg_sync INTEGER NOT NULL DEFAULT 0,- live_count INTEGER NOT NULL DEFAULT 0,- movie_count INTEGER NOT NULL DEFAULT 0,- series_count INTEGER NOT NULL DEFAULT 0,- epg_count INTEGER NOT NULL DEFAULT 0,- last_sync_status TEXT NOT NULL DEFAULT 'NONE'- )- """)-- // 3. Migrate existing watch progress to history- database.execSQL("""- INSERT OR IGNORE INTO playback_history (content_id, content_type, provider_id, title, resume_position_ms, last_watched_at)- SELECT id, 'MOVIE', provider_id, name, watch_progress, last_watched_at- FROM movies WHERE watch_progress > 0- """)- database.execSQL("""- INSERT OR IGNORE INTO playback_history (content_id, content_type, provider_id, title, resume_position_ms, last_watched_at, series_id, season_number, episode_number)- SELECT id, 'SERIES_EPISODE', provider_id, title, watch_progress, last_watched_at, series_id, season_number, episode_number- FROM episodes WHERE watch_progress > 0- """)- }- }-- val MIGRATION_4_5 = object : Migration(4, 5) {- override fun migrate(database: SupportSQLiteDatabase) {- // Note: Room auto-generates index names as 'index_tableName_columnNames'- // Channels- database.execSQL("DROP INDEX IF EXISTS index_channels_category_id")- database.execSQL("CREATE INDEX IF NOT EXISTS index_channels_provider_id_category_id ON channels(provider_id, category_id)")-- // Movies- database.execSQL("DROP INDEX IF EXISTS index_movies_category_id")- database.execSQL("CREATE INDEX IF NOT EXISTS index_movies_provider_id_category_id ON movies(provider_id, category_id)")-- // Series- database.execSQL("DROP INDEX IF EXISTS index_series_category_id")- database.execSQL("CREATE INDEX IF NOT EXISTS index_series_provider_id_category_id ON series(provider_id, category_id)")-- // Favorites- database.execSQL("DROP INDEX IF EXISTS index_favorites_group_id")- database.execSQL("DROP INDEX IF EXISTS index_favorites_position")- database.execSQL("CREATE INDEX IF NOT EXISTS index_favorites_content_type_group_id ON favorites(content_type, group_id)")- database.execSQL("CREATE INDEX IF NOT EXISTS index_favorites_group_id_position ON favorites(group_id, position)")- }- }-- val MIGRATION_5_6 = object : Migration(5, 6) {- override fun migrate(database: SupportSQLiteDatabase) {- database.execSQL("ALTER TABLE virtual_groups ADD COLUMN content_type TEXT NOT NULL DEFAULT 'LIVE'")- }- }-- val MIGRATION_6_7 = object : Migration(6, 7) {- override fun migrate(database: SupportSQLiteDatabase) {- database.execSQL("ALTER TABLE channels ADD COLUMN logical_group_id TEXT NOT NULL DEFAULT ''")- database.execSQL("ALTER TABLE channels ADD COLUMN error_count INTEGER NOT NULL DEFAULT 0")- database.execSQL("CREATE INDEX IF NOT EXISTS index_channels_logical_group_id ON channels(logical_group_id)")- }- }-- val MIGRATION_7_8 = object : Migration(7, 8) {- override fun migrate(database: SupportSQLiteDatabase) {- database.execSQL("ALTER TABLE programs ADD COLUMN provider_id INTEGER NOT NULL DEFAULT 0")- database.execSQL("DROP INDEX IF EXISTS index_programs_channel_id")- database.execSQL("DROP INDEX IF EXISTS index_programs_channel_id_start_time")- database.execSQL("CREATE INDEX IF NOT EXISTS index_programs_provider_id ON programs(provider_id)")- database.execSQL("CREATE INDEX IF NOT EXISTS index_programs_provider_id_channel_id ON programs(provider_id, channel_id)")- database.execSQL("CREATE INDEX IF NOT EXISTS index_programs_provider_id_channel_id_start_time ON programs(provider_id, channel_id, start_time)")- database.execSQL(- "CREATE UNIQUE INDEX IF NOT EXISTS index_programs_provider_id_channel_id_start_time_end_time " +- "ON programs(provider_id, channel_id, start_time, end_time)"- )- }- }-- val MIGRATION_8_9 = object : Migration(8, 9) {- override fun migrate(database: SupportSQLiteDatabase) {- // Rebuild media tables to normalize legacy local IDs and keep only provider-scoped remote IDs as remote keys.- // This preserves user-facing references by remapping favorites/history through temporary ID maps.-- // Channels- database.execSQL(- """- CREATE TABLE IF NOT EXISTS channels_new (- 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- )- """.trimIndent()- )- database.execSQL(- """- INSERT INTO channels_new (- stream_id, name, logo_url, group_title, category_id, category_name, stream_url,- epg_channel_id, number, catch_up_supported, catch_up_days, catchUpSource,- provider_id, is_adult, is_user_protected, logical_group_id, error_count- )- SELECT- stream_id, name, logo_url, group_title, category_id, category_name, stream_url,- epg_channel_id, number, catch_up_supported, catch_up_days, catchUpSource,- provider_id, is_adult, is_user_protected, logical_group_id, error_count- FROM channels- """.trimIndent()- )- database.execSQL("CREATE TEMP TABLE channel_id_map(old_id INTEGER PRIMARY KEY NOT NULL, new_id INTEGER NOT NULL)")- database.execSQL(- """- INSERT INTO channel_id_map(old_id, new_id)- SELECT old.id, MIN(new.id)- FROM channels old- JOIN channels_new new- ON new.provider_id = old.provider_id- AND new.stream_id = old.stream_id- GROUP BY old.id- """.trimIndent()- )- database.execSQL(- """- UPDATE favorites- SET content_id = (SELECT new_id FROM channel_id_map WHERE old_id = content_id)- WHERE content_type = 'LIVE'- AND content_id IN (SELECT old_id FROM channel_id_map)- """.trimIndent()- )- database.execSQL(- """- UPDATE playback_history- SET content_id = (SELECT new_id FROM channel_id_map WHERE old_id = content_id)- WHERE content_type = 'LIVE'- AND content_id IN (SELECT old_id FROM channel_id_map)- """.trimIndent()- )- database.execSQL("DROP TABLE channels")- database.execSQL("ALTER TABLE channels_new RENAME TO channels")- database.execSQL("CREATE INDEX IF NOT EXISTS index_channels_provider_id ON channels(provider_id)")- database.execSQL("CREATE INDEX IF NOT EXISTS index_channels_provider_id_category_id ON channels(provider_id, category_id)")- database.execSQL("CREATE UNIQUE INDEX IF NOT EXISTS index_channels_provider_id_stream_id ON channels(provider_id, stream_id)")- database.execSQL("CREATE INDEX IF NOT EXISTS index_channels_logical_group_id ON channels(logical_group_id)")- database.execSQL("DROP TABLE channel_id_map")-- // Movies- database.execSQL(- """- CREATE TABLE IF NOT EXISTS movies_new (- id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,- stream_id INTEGER NOT NULL,- name TEXT NOT NULL,- poster_url TEXT,- backdrop_url TEXT,- category_id INTEGER,- category_name TEXT,- stream_url TEXT NOT NULL,- container_extension TEXT,- plot TEXT,- "cast" TEXT,- director TEXT,- genre TEXT,- release_date TEXT,- duration TEXT,- duration_seconds INTEGER NOT NULL,- rating REAL NOT NULL,- year TEXT,- tmdb_id INTEGER,- youtube_trailer TEXT,- provider_id INTEGER NOT NULL,- watch_progress INTEGER NOT NULL,- last_watched_at INTEGER NOT NULL,- is_adult INTEGER NOT NULL,- is_user_protected INTEGER NOT NULL- )- """.trimIndent()- )- database.execSQL(- """- INSERT INTO movies_new (- stream_id, name, poster_url, backdrop_url, category_id, category_name, stream_url,- container_extension, plot, "cast", director, genre, release_date, duration, duration_seconds,- rating, year, tmdb_id, youtube_trailer, provider_id, watch_progress, last_watched_at,- is_adult, is_user_protected- )- SELECT- stream_id, name, poster_url, backdrop_url, category_id, category_name, stream_url,- container_extension, plot, "cast", director, genre, release_date, duration, duration_seconds,- rating, year, tmdb_id, youtube_trailer, provider_id, watch_progress, last_watched_at,- is_adult, is_user_protected- FROM movies- """.trimIndent()- )- database.execSQL("CREATE TEMP TABLE movie_id_map(old_id INTEGER PRIMARY KEY NOT NULL, new_id INTEGER NOT NULL)")- database.execSQL(- """- INSERT INTO movie_id_map(old_id, new_id)- SELECT old.id, MIN(new.id)- FROM movies old- JOIN movies_new new- ON new.provider_id = old.provider_id- AND new.stream_id = old.stream_id- GROUP BY old.id- """.trimIndent()- )- database.execSQL(- """- UPDATE favorites- SET content_id = (SELECT new_id FROM movie_id_map WHERE old_id = content_id)- WHERE content_type = 'MOVIE'- AND content_id IN (SELECT old_id FROM movie_id_map)- """.trimIndent()- )- database.execSQL(- """- UPDATE playback_history- SET content_id = (SELECT new_id FROM movie_id_map WHERE old_id = content_id)- WHERE content_type = 'MOVIE'- AND content_id IN (SELECT old_id FROM movie_id_map)- """.trimIndent()- )- database.execSQL("DROP TABLE movies")- database.execSQL("ALTER TABLE movies_new RENAME TO movies")- database.execSQL("CREATE INDEX IF NOT EXISTS index_movies_provider_id ON movies(provider_id)")- database.execSQL("CREATE INDEX IF NOT EXISTS index_movies_provider_id_category_id ON movies(provider_id, category_id)")- database.execSQL("CREATE UNIQUE INDEX IF NOT EXISTS index_movies_provider_id_stream_id ON movies(provider_id, stream_id)")- database.execSQL("DROP TABLE movie_id_map")-- // Series- database.execSQL(- """- CREATE TABLE IF NOT EXISTS series_new (- id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,- series_id INTEGER NOT NULL,- name TEXT NOT NULL,- poster_url TEXT,- backdrop_url TEXT,- category_id INTEGER,- category_name TEXT,- plot TEXT,- "cast" TEXT,- director TEXT,- genre TEXT,- release_date TEXT,- rating REAL NOT NULL,- tmdb_id INTEGER,- youtube_trailer TEXT,- episode_run_time TEXT,- last_modified INTEGER NOT NULL,- provider_id INTEGER NOT NULL,- is_adult INTEGER NOT NULL,- is_user_protected INTEGER NOT NULL- )- """.trimIndent()- )- database.execSQL(- """- INSERT INTO series_new (- series_id, name, poster_url, backdrop_url, category_id, category_name, plot, "cast",- director, genre, release_date, rating, tmdb_id, youtube_trailer, episode_run_time,- last_modified, provider_id, is_adult, is_user_protected- )- SELECT- series_id, name, poster_url, backdrop_url, category_id, category_name, plot, "cast",- director, genre, release_date, rating, tmdb_id, youtube_trailer, episode_run_time,- last_modified, provider_id, is_adult, is_user_protected- FROM series- """.trimIndent()- )- database.execSQL("CREATE TEMP TABLE series_id_map(old_id INTEGER PRIMARY KEY NOT NULL, new_id INTEGER NOT NULL)")- database.execSQL(- """- INSERT INTO series_id_map(old_id, new_id)- SELECT old.id, MIN(new.id)- FROM series old- JOIN series_new new- ON new.provider_id = old.provider_id- AND new.series_id = old.series_id- GROUP BY old.id- """.trimIndent()- )- database.execSQL(- """- UPDATE favorites- SET content_id = (SELECT new_id FROM series_id_map WHERE old_id = content_id)- WHERE content_type = 'SERIES'- AND content_id IN (SELECT old_id FROM series_id_map)- """.trimIndent()- )- database.execSQL(- """- UPDATE playback_history- SET content_id = (SELECT new_id FROM series_id_map WHERE old_id = content_id)- WHERE content_type = 'SERIES'- AND content_id IN (SELECT old_id FROM series_id_map)- """.trimIndent()- )- database.execSQL(- """- UPDATE playback_history- SET series_id = (SELECT new_id FROM series_id_map WHERE old_id = series_id)- WHERE series_id IS NOT NULL- AND series_id IN (SELECT old_id FROM series_id_map)- """.trimIndent()- )- database.execSQL(- """- UPDATE episodes- SET series_id = (SELECT new_id FROM series_id_map WHERE old_id = series_id)- WHERE series_id IN (SELECT old_id FROM series_id_map)- """.trimIndent()- )- database.execSQL("DROP TABLE series")- database.execSQL("ALTER TABLE series_new RENAME TO series")- database.execSQL("CREATE INDEX IF NOT EXISTS index_series_provider_id ON series(provider_id)")- database.execSQL("CREATE INDEX IF NOT EXISTS index_series_provider_id_category_id ON series(provider_id, category_id)")- database.execSQL("CREATE UNIQUE INDEX IF NOT EXISTS index_series_provider_id_series_id ON series(provider_id, series_id)")- database.execSQL("DROP TABLE series_id_map")-- // Episodes- database.execSQL(- """- CREATE TABLE IF NOT EXISTS episodes_new (- 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- )- """.trimIndent()- )- database.execSQL(- """- INSERT INTO episodes_new (- episode_id, title, episode_number, season_number, stream_url, container_extension, cover_url,- plot, duration, duration_seconds, rating, release_date, series_id, provider_id, watch_progress,- last_watched_at, is_adult, is_user_protected- )- SELECT- episode_id, title, episode_number, season_number, stream_url, container_extension, cover_url,- plot, duration, duration_seconds, rating, release_date, series_id, provider_id, watch_progress,- last_watched_at, is_adult, is_user_protected- FROM episodes- """.trimIndent()- )- database.execSQL("CREATE TEMP TABLE episode_id_map(old_id INTEGER PRIMARY KEY NOT NULL, new_id INTEGER NOT NULL)")- database.execSQL(- """- INSERT INTO episode_id_map(old_id, new_id)- SELECT old.id, new.id- FROM episodes old- JOIN episodes_new new- ON new.provider_id = old.provider_id- AND new.episode_id = old.episode_id- """.trimIndent()- )- database.execSQL(- """- UPDATE playback_history- SET content_id = (SELECT new_id FROM episode_id_map WHERE old_id = content_id)- WHERE content_type = 'SERIES_EPISODE'- AND content_id IN (SELECT old_id FROM episode_id_map)- """.trimIndent()- )- database.execSQL("DROP TABLE episodes")- database.execSQL("ALTER TABLE episodes_new RENAME TO episodes")- database.execSQL("CREATE INDEX IF NOT EXISTS index_episodes_series_id ON episodes(series_id)")- database.execSQL("CREATE INDEX IF NOT EXISTS index_episodes_provider_id ON episodes(provider_id)")- database.execSQL("CREATE UNIQUE INDEX IF NOT EXISTS index_episodes_provider_id_episode_id ON episodes(provider_id, episode_id)")- database.execSQL("DROP TABLE episode_id_map")- validateForeignKeys(database, "episodes")- }- }-- val MIGRATION_9_10 = object : Migration(9, 10) {- override fun migrate(database: SupportSQLiteDatabase) {- database.execSQL("CREATE VIRTUAL TABLE IF NOT EXISTS channels_fts USING fts4(name, content='channels')")- database.execSQL("CREATE VIRTUAL TABLE IF NOT EXISTS movies_fts USING fts4(name, content='movies')")- database.execSQL("CREATE VIRTUAL TABLE IF NOT EXISTS series_fts USING fts4(name, content='series')")-- database.execSQL("INSERT INTO channels_fts(rowid, name) SELECT id, name FROM channels")- database.execSQL("INSERT INTO movies_fts(rowid, name) SELECT id, name FROM movies")- database.execSQL("INSERT INTO series_fts(rowid, name) SELECT id, name FROM series")-- database.execSQL(- """- CREATE TRIGGER IF NOT EXISTS channels_ai- AFTER INSERT ON channels BEGIN- INSERT INTO channels_fts(rowid, name) VALUES (new.id, new.name);- END- """.trimIndent()- )- database.execSQL(- """- CREATE TRIGGER IF NOT EXISTS channels_ad- AFTER DELETE ON channels BEGIN- DELETE FROM channels_fts WHERE rowid = old.id;- END- """.trimIndent()- )- database.execSQL(- """- CREATE TRIGGER IF NOT EXISTS channels_au- AFTER UPDATE OF name ON channels BEGIN- UPDATE channels_fts SET name = new.name WHERE rowid = old.id;- END- """.trimIndent()- )-- database.execSQL(- """- CREATE TRIGGER IF NOT EXISTS movies_ai- AFTER INSERT ON movies BEGIN- INSERT INTO movies_fts(rowid, name) VALUES (new.id, new.name);- END- """.trimIndent()- )- database.execSQL(- """- CREATE TRIGGER IF NOT EXISTS movies_ad- AFTER DELETE ON movies BEGIN- DELETE FROM movies_fts WHERE rowid = old.id;- END- """.trimIndent()- )- database.execSQL(- """- CREATE TRIGGER IF NOT EXISTS movies_au- AFTER UPDATE OF name ON movies BEGIN- UPDATE movies_fts SET name = new.name WHERE rowid = old.id;- END- """.trimIndent()- )-- database.execSQL(- """- CREATE TRIGGER IF NOT EXISTS series_ai- AFTER INSERT ON series BEGIN- INSERT INTO series_fts(rowid, name) VALUES (new.id, new.name);- END- """.trimIndent()- )- database.execSQL(- """- CREATE TRIGGER IF NOT EXISTS series_ad- AFTER DELETE ON series BEGIN- DELETE FROM series_fts WHERE rowid = old.id;- END- """.trimIndent()- )- database.execSQL(- """- CREATE TRIGGER IF NOT EXISTS series_au- AFTER UPDATE OF name ON series BEGIN- UPDATE series_fts SET name = new.name WHERE rowid = old.id;- END- """.trimIndent()- )- }- }-- /**- * Migration 10 → 11: Add foreign key constraints to child tables.- * Tables referencing providers get ON DELETE CASCADE.- * Favorites referencing virtual_groups get ON DELETE SET NULL.- * Programs table excluded (uses negative staging provider IDs).- */- val MIGRATION_10_11 = object : Migration(10, 11) {- override fun migrate(database: SupportSQLiteDatabase) {- // Clean up orphaned records before adding FK constraints- database.execSQL("DELETE FROM channels WHERE provider_id NOT IN (SELECT id FROM providers)")- database.execSQL("DELETE FROM movies WHERE provider_id NOT IN (SELECT id FROM providers)")- database.execSQL("DELETE FROM series WHERE provider_id NOT IN (SELECT id FROM providers)")- database.execSQL("DELETE FROM episodes WHERE provider_id NOT IN (SELECT id FROM providers)")- database.execSQL("DELETE FROM categories WHERE provider_id NOT IN (SELECT id FROM providers)")- database.execSQL("DELETE FROM playback_history WHERE provider_id NOT IN (SELECT id FROM providers)")- database.execSQL("DELETE FROM sync_metadata WHERE provider_id NOT IN (SELECT id FROM providers)")- database.execSQL("UPDATE favorites SET group_id = NULL WHERE group_id IS NOT NULL AND group_id NOT IN (SELECT id FROM virtual_groups)")-- // ── Drop FTS triggers and tables (channels, movies, series) ──- database.execSQL("DROP TRIGGER IF EXISTS channels_ai")- database.execSQL("DROP TRIGGER IF EXISTS channels_ad")- database.execSQL("DROP TRIGGER IF EXISTS channels_au")- database.execSQL("DROP TRIGGER IF EXISTS movies_ai")- database.execSQL("DROP TRIGGER IF EXISTS movies_ad")- database.execSQL("DROP TRIGGER IF EXISTS movies_au")- database.execSQL("DROP TRIGGER IF EXISTS series_ai")- database.execSQL("DROP TRIGGER IF EXISTS series_ad")- database.execSQL("DROP TRIGGER IF EXISTS series_au")- database.execSQL("DROP TABLE IF EXISTS channels_fts")- database.execSQL("DROP TABLE IF EXISTS movies_fts")- database.execSQL("DROP TABLE IF EXISTS series_fts")-- // ── Channels ──- database.execSQL("""- CREATE TABLE channels_new (- id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,- stream_id INTEGER NOT NULL DEFAULT 0,- name TEXT NOT NULL,- logo_url TEXT,- group_title TEXT,- category_id INTEGER,- category_name TEXT,- stream_url TEXT NOT NULL DEFAULT '',- epg_channel_id TEXT,- number INTEGER NOT NULL DEFAULT 0,- catch_up_supported INTEGER NOT NULL DEFAULT 0,- catch_up_days INTEGER NOT NULL DEFAULT 0,- catchUpSource TEXT,- provider_id INTEGER NOT NULL DEFAULT 0,- is_adult INTEGER NOT NULL DEFAULT 0,- is_user_protected INTEGER NOT NULL DEFAULT 0,- logical_group_id TEXT NOT NULL DEFAULT '',- error_count INTEGER NOT NULL DEFAULT 0,- FOREIGN KEY(provider_id) REFERENCES providers(id) ON DELETE CASCADE- )- """.trimIndent())- database.execSQL("INSERT INTO channels_new SELECT * FROM channels")- database.execSQL("DROP TABLE channels")- database.execSQL("ALTER TABLE channels_new RENAME TO channels")- database.execSQL("CREATE INDEX index_channels_provider_id ON channels(provider_id)")- database.execSQL("CREATE INDEX index_channels_provider_id_category_id ON channels(provider_id, category_id)")- database.execSQL("CREATE UNIQUE INDEX index_channels_provider_id_stream_id ON channels(provider_id, stream_id)")- database.execSQL("CREATE INDEX index_channels_logical_group_id ON channels(logical_group_id)")-- // ── Movies ──- database.execSQL("""- CREATE TABLE movies_new (- id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,- stream_id INTEGER NOT NULL DEFAULT 0,- name TEXT NOT NULL,- poster_url TEXT,- backdrop_url TEXT,- category_id INTEGER,- category_name TEXT,- stream_url TEXT NOT NULL DEFAULT '',- container_extension TEXT,- plot TEXT,- "cast" TEXT,- director TEXT,- genre TEXT,- release_date TEXT,- duration TEXT,- duration_seconds INTEGER NOT NULL DEFAULT 0,- rating REAL NOT NULL DEFAULT 0,- year TEXT,- tmdb_id INTEGER,- youtube_trailer TEXT,- provider_id INTEGER NOT NULL DEFAULT 0,- watch_progress INTEGER NOT NULL DEFAULT 0,- last_watched_at INTEGER NOT NULL DEFAULT 0,- is_adult INTEGER NOT NULL DEFAULT 0,- is_user_protected INTEGER NOT NULL DEFAULT 0,- FOREIGN KEY(provider_id) REFERENCES providers(id) ON DELETE CASCADE- )- """.trimIndent())- database.execSQL("INSERT INTO movies_new SELECT * FROM movies")- database.execSQL("DROP TABLE movies")- database.execSQL("ALTER TABLE movies_new RENAME TO movies")- database.execSQL("CREATE INDEX index_movies_provider_id ON movies(provider_id)")- database.execSQL("CREATE INDEX index_movies_provider_id_category_id ON movies(provider_id, category_id)")- database.execSQL("CREATE UNIQUE INDEX index_movies_provider_id_stream_id ON movies(provider_id, stream_id)")-- // ── Series ──- database.execSQL("""- CREATE TABLE series_new (- id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,- series_id INTEGER NOT NULL DEFAULT 0,- 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 DEFAULT 0,- tmdb_id INTEGER,- youtube_trailer TEXT,- episode_run_time TEXT,- last_modified INTEGER NOT NULL DEFAULT 0,- provider_id INTEGER NOT NULL DEFAULT 0,- is_adult INTEGER NOT NULL DEFAULT 0,- is_user_protected INTEGER NOT NULL DEFAULT 0,- FOREIGN KEY(provider_id) REFERENCES providers(id) ON DELETE CASCADE- )- """.trimIndent())- database.execSQL("INSERT INTO series_new SELECT * FROM series")- database.execSQL("DROP TABLE series")- database.execSQL("ALTER TABLE series_new RENAME TO series")- database.execSQL("CREATE INDEX index_series_provider_id ON series(provider_id)")- database.execSQL("CREATE INDEX index_series_provider_id_category_id ON series(provider_id, category_id)")- database.execSQL("CREATE UNIQUE INDEX index_series_provider_id_series_id ON series(provider_id, series_id)")-- // ── Recreate FTS tables and triggers ──- database.execSQL("CREATE VIRTUAL TABLE IF NOT EXISTS channels_fts USING fts4(name, content='channels')")- database.execSQL("CREATE VIRTUAL TABLE IF NOT EXISTS movies_fts USING fts4(name, content='movies')")- database.execSQL("CREATE VIRTUAL TABLE IF NOT EXISTS series_fts USING fts4(name, content='series')")- database.execSQL("INSERT INTO channels_fts(rowid, name) SELECT id, name FROM channels")- database.execSQL("INSERT INTO movies_fts(rowid, name) SELECT id, name FROM movies")- database.execSQL("INSERT INTO series_fts(rowid, name) SELECT id, name FROM series")- database.execSQL("CREATE TRIGGER IF NOT EXISTS channels_ai AFTER INSERT ON channels BEGIN INSERT INTO channels_fts(rowid, name) VALUES (new.id, new.name); END")- database.execSQL("CREATE TRIGGER IF NOT EXISTS channels_ad AFTER DELETE ON channels BEGIN DELETE FROM channels_fts WHERE rowid = old.id; END")- database.execSQL("CREATE TRIGGER IF NOT EXISTS channels_au AFTER UPDATE OF name ON channels BEGIN UPDATE channels_fts SET name = new.name WHERE rowid = old.id; END")- database.execSQL("CREATE TRIGGER IF NOT EXISTS movies_ai AFTER INSERT ON movies BEGIN INSERT INTO movies_fts(rowid, name) VALUES (new.id, new.name); END")- database.execSQL("CREATE TRIGGER IF NOT EXISTS movies_ad AFTER DELETE ON movies BEGIN DELETE FROM movies_fts WHERE rowid = old.id; END")- database.execSQL("CREATE TRIGGER IF NOT EXISTS movies_au AFTER UPDATE OF name ON movies BEGIN UPDATE movies_fts SET name = new.name WHERE rowid = old.id; END")- database.execSQL("CREATE TRIGGER IF NOT EXISTS series_ai AFTER INSERT ON series BEGIN INSERT INTO series_fts(rowid, name) VALUES (new.id, new.name); END")- database.execSQL("CREATE TRIGGER IF NOT EXISTS series_ad AFTER DELETE ON series BEGIN DELETE FROM series_fts WHERE rowid = old.id; END")- database.execSQL("CREATE TRIGGER IF NOT EXISTS series_au AFTER UPDATE OF name ON series BEGIN UPDATE series_fts SET name = new.name WHERE rowid = old.id; END")-- // ── Episodes ──- database.execSQL("""- CREATE TABLE episodes_new (- id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,- episode_id INTEGER NOT NULL DEFAULT 0,- title TEXT NOT NULL,- episode_number INTEGER NOT NULL,- season_number INTEGER NOT NULL,- stream_url TEXT NOT NULL DEFAULT '',- container_extension TEXT,- cover_url TEXT,- plot TEXT,- duration TEXT,- duration_seconds INTEGER NOT NULL DEFAULT 0,- rating REAL NOT NULL DEFAULT 0,- release_date TEXT,- series_id INTEGER NOT NULL DEFAULT 0,- provider_id INTEGER NOT NULL DEFAULT 0,- watch_progress INTEGER NOT NULL DEFAULT 0,- last_watched_at INTEGER NOT NULL DEFAULT 0,- is_adult INTEGER NOT NULL DEFAULT 0,- is_user_protected INTEGER NOT NULL DEFAULT 0,- FOREIGN KEY(provider_id) REFERENCES providers(id) ON DELETE CASCADE- )- """.trimIndent())- database.execSQL("INSERT INTO episodes_new SELECT * FROM episodes")- database.execSQL("DROP TABLE episodes")- database.execSQL("ALTER TABLE episodes_new RENAME TO episodes")- database.execSQL("CREATE INDEX index_episodes_series_id ON episodes(series_id)")- database.execSQL("CREATE INDEX index_episodes_provider_id ON episodes(provider_id)")- database.execSQL("CREATE UNIQUE INDEX index_episodes_provider_id_episode_id ON episodes(provider_id, episode_id)")-- // ── Categories ──- database.execSQL("""- CREATE TABLE categories_new (- id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,- category_id INTEGER NOT NULL DEFAULT 0,- name TEXT NOT NULL,- parent_id INTEGER,- type TEXT NOT NULL DEFAULT 'LIVE',- provider_id INTEGER NOT NULL DEFAULT 0,- is_adult INTEGER NOT NULL DEFAULT 0,- is_user_protected INTEGER NOT NULL DEFAULT 0,- FOREIGN KEY(provider_id) REFERENCES providers(id) ON DELETE CASCADE- )- """.trimIndent())- database.execSQL("INSERT INTO categories_new SELECT * FROM categories")- database.execSQL("DROP TABLE categories")- database.execSQL("ALTER TABLE categories_new RENAME TO categories")- database.execSQL("CREATE INDEX index_categories_provider_id ON categories(provider_id)")- database.execSQL("CREATE UNIQUE INDEX index_categories_provider_id_category_id_type ON categories(provider_id, category_id, type)")-- // ── Playback History ──- database.execSQL("""- CREATE TABLE playback_history_new (- 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 DEFAULT '',- poster_url TEXT,- stream_url TEXT NOT NULL DEFAULT '',- resume_position_ms INTEGER NOT NULL DEFAULT 0,- total_duration_ms INTEGER NOT NULL DEFAULT 0,- last_watched_at INTEGER NOT NULL DEFAULT 0,- watch_count INTEGER NOT NULL DEFAULT 1,- series_id INTEGER,- season_number INTEGER,- episode_number INTEGER,- FOREIGN KEY(provider_id) REFERENCES providers(id) ON DELETE CASCADE- )- """.trimIndent())- database.execSQL("INSERT INTO playback_history_new SELECT * FROM playback_history")- database.execSQL("DROP TABLE playback_history")- database.execSQL("ALTER TABLE playback_history_new RENAME TO playback_history")- database.execSQL("CREATE UNIQUE INDEX index_playback_history_content_id_content_type_provider_id ON playback_history(content_id, content_type, provider_id)")- database.execSQL("CREATE INDEX index_playback_history_last_watched_at ON playback_history(last_watched_at)")- database.execSQL("CREATE INDEX index_playback_history_provider_id ON playback_history(provider_id)")-- // ── Sync Metadata ──- database.execSQL("""- CREATE TABLE sync_metadata_new (- provider_id INTEGER NOT NULL PRIMARY KEY,- last_live_sync INTEGER NOT NULL DEFAULT 0,- last_movie_sync INTEGER NOT NULL DEFAULT 0,- last_series_sync INTEGER NOT NULL DEFAULT 0,- last_epg_sync INTEGER NOT NULL DEFAULT 0,- live_count INTEGER NOT NULL DEFAULT 0,- movie_count INTEGER NOT NULL DEFAULT 0,- series_count INTEGER NOT NULL DEFAULT 0,- epg_count INTEGER NOT NULL DEFAULT 0,- last_sync_status TEXT NOT NULL DEFAULT 'NONE',- FOREIGN KEY(provider_id) REFERENCES providers(id) ON DELETE CASCADE- )- """.trimIndent())- database.execSQL("INSERT INTO sync_metadata_new SELECT * FROM sync_metadata")- database.execSQL("DROP TABLE sync_metadata")- database.execSQL("ALTER TABLE sync_metadata_new RENAME TO sync_metadata")-- // ── Favorites ──- database.execSQL("""- CREATE TABLE favorites_new (- id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,- content_id INTEGER NOT NULL,- content_type TEXT NOT NULL,- position INTEGER NOT NULL DEFAULT 0,- group_id INTEGER,- added_at INTEGER NOT NULL,- FOREIGN KEY(group_id) REFERENCES virtual_groups(id) ON DELETE SET NULL- )- """.trimIndent())- database.execSQL("INSERT INTO favorites_new SELECT * FROM favorites")- database.execSQL("DROP TABLE favorites")- database.execSQL("ALTER TABLE favorites_new RENAME TO favorites")- database.execSQL("CREATE UNIQUE INDEX index_favorites_content_id_content_type_group_id ON favorites(content_id, content_type, group_id)")- database.execSQL("CREATE INDEX index_favorites_content_type_group_id ON favorites(content_type, group_id)")- database.execSQL("CREATE INDEX index_favorites_group_id_position ON favorites(group_id, position)")- validateForeignKeys(database, "favorites")- }- }- /**- * Migration 11 → 12: adds series_id FK to episodes.- * Episodes whose series_id has no matching row in the series table are silently- * removed — they are unreachable orphans and would violate the new constraint.- */- val MIGRATION_11_12 = object : Migration(11, 12) {- override fun migrate(database: SupportSQLiteDatabase) {- // Create new episodes table with both FK constraints- database.execSQL("""- CREATE TABLE episodes_new (- id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,- episode_id INTEGER NOT NULL DEFAULT 0,- title TEXT NOT NULL,- episode_number INTEGER NOT NULL,- season_number INTEGER NOT NULL,- stream_url TEXT NOT NULL DEFAULT '',- container_extension TEXT,- cover_url TEXT,- plot TEXT,- duration TEXT,- duration_seconds INTEGER NOT NULL DEFAULT 0,- rating REAL NOT NULL DEFAULT 0,- release_date TEXT,- series_id INTEGER NOT NULL DEFAULT 0,- provider_id INTEGER NOT NULL DEFAULT 0,- watch_progress INTEGER NOT NULL DEFAULT 0,- last_watched_at INTEGER NOT NULL DEFAULT 0,- is_adult INTEGER NOT NULL DEFAULT 0,- is_user_protected INTEGER NOT NULL DEFAULT 0,- FOREIGN KEY(provider_id) REFERENCES providers(id) ON DELETE CASCADE,- FOREIGN KEY(series_id) REFERENCES series(id) ON DELETE CASCADE- )- """.trimIndent())- // Migrate only episodes with a valid series parent; orphans are discarded- database.execSQL("""- INSERT INTO episodes_new- SELECT * FROM episodes- WHERE series_id IN (SELECT id FROM series)- """.trimIndent())- database.execSQL("DROP TABLE episodes")- database.execSQL("ALTER TABLE episodes_new RENAME TO episodes")- database.execSQL("CREATE INDEX index_episodes_series_id ON episodes(series_id)")- database.execSQL("CREATE INDEX index_episodes_provider_id ON episodes(provider_id)")- database.execSQL("CREATE UNIQUE INDEX index_episodes_provider_id_episode_id ON episodes(provider_id, episode_id)")- }- }-- /**- * Migration 12 → 13: move high-cardinality per-channel UI state into Room.- * Existing DataStore aspect-ratio entries are read lazily as a legacy fallback and- * get replaced in Room on the next write for each channel.- */- val MIGRATION_12_13 = object : Migration(12, 13) {- override fun migrate(database: SupportSQLiteDatabase) {- database.execSQL(- """- CREATE TABLE IF NOT EXISTS channel_preferences (- id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,- channel_id INTEGER NOT NULL,- aspect_ratio TEXT,- updated_at INTEGER NOT NULL DEFAULT 0,- FOREIGN KEY(channel_id) REFERENCES channels(id) ON DELETE CASCADE- )- """.trimIndent()- )- database.execSQL(- "CREATE UNIQUE INDEX IF NOT EXISTS index_channel_preferences_channel_id ON channel_preferences(channel_id)"- )- }- }-- /**- * Migration 13 → 14: add targeted secondary indexes for broad EPG windows,- * provider/type category filtering, and virtual group content type lookups.- */- val MIGRATION_13_14 = object : Migration(13, 14) {- override fun migrate(database: SupportSQLiteDatabase) {- database.execSQL(- "CREATE INDEX IF NOT EXISTS index_programs_provider_id_start_time_end_time ON programs(provider_id, start_time, end_time)"- )- database.execSQL(- "CREATE INDEX IF NOT EXISTS index_categories_provider_id_type ON categories(provider_id, type)"- )- database.execSQL(- "CREATE INDEX IF NOT EXISTS index_virtual_groups_content_type ON virtual_groups(content_type)"- )- }- }-- val MIGRATION_14_15 = object : Migration(14, 15) {- override fun migrate(database: SupportSQLiteDatabase) {- database.execSQL("ALTER TABLE providers ADD COLUMN api_version TEXT")- database.execSQL("ALTER TABLE channels ADD COLUMN quality_options_json TEXT")- database.execSQL("ALTER TABLE programs ADD COLUMN rating TEXT")- database.execSQL("ALTER TABLE programs ADD COLUMN image_url TEXT")- database.execSQL("ALTER TABLE programs ADD COLUMN genre TEXT")- database.execSQL("ALTER TABLE programs ADD COLUMN category TEXT")- database.execSQL("ALTER TABLE playback_history ADD COLUMN watched_status TEXT NOT NULL DEFAULT 'IN_PROGRESS'")- }- }-- val MIGRATION_15_16 = object : Migration(15, 16) {- override fun migrate(database: SupportSQLiteDatabase) {- database.execSQL(- "CREATE INDEX IF NOT EXISTS index_channels_provider_id_category_id_logical_group_id " +- "ON channels(provider_id, category_id, logical_group_id)"- )- }- }-- val MIGRATION_16_17 = object : Migration(16, 17) {- override fun migrate(database: SupportSQLiteDatabase) {- database.execSQL(- "ALTER TABLE providers ADD COLUMN allowed_output_formats_json TEXT NOT NULL DEFAULT '[]'"- )- }- }-- val MIGRATION_17_18 = object : Migration(17, 18) {- override fun migrate(database: SupportSQLiteDatabase) {- database.execSQL("ALTER TABLE sync_metadata ADD COLUMN last_movie_attempt INTEGER NOT NULL DEFAULT 0")- database.execSQL("ALTER TABLE sync_metadata ADD COLUMN last_movie_success INTEGER NOT NULL DEFAULT 0")- database.execSQL("ALTER TABLE sync_metadata ADD COLUMN last_movie_partial INTEGER NOT NULL DEFAULT 0")- database.execSQL("ALTER TABLE sync_metadata ADD COLUMN movie_sync_mode TEXT NOT NULL DEFAULT 'UNKNOWN'")- database.execSQL("ALTER TABLE sync_metadata ADD COLUMN movie_warnings_count INTEGER NOT NULL DEFAULT 0")- database.execSQL("ALTER TABLE sync_metadata ADD COLUMN movie_catalog_stale INTEGER NOT NULL DEFAULT 0")- database.execSQL("ALTER TABLE sync_metadata ADD COLUMN movie_parallel_failures_remembered INTEGER NOT NULL DEFAULT 0")- }- }-- val MIGRATION_18_19 = object : Migration(18, 19) {- override fun migrate(database: SupportSQLiteDatabase) {- database.execSQL("ALTER TABLE sync_metadata ADD COLUMN movie_healthy_sync_streak INTEGER NOT NULL DEFAULT 0")- }- }-- val MIGRATION_19_20 = object : Migration(19, 20) {- override fun migrate(database: SupportSQLiteDatabase) {- database.execSQL("ALTER TABLE channels ADD COLUMN sync_fingerprint TEXT NOT NULL DEFAULT ''")- database.execSQL("ALTER TABLE movies ADD COLUMN sync_fingerprint TEXT NOT NULL DEFAULT ''")- database.execSQL("ALTER TABLE series ADD COLUMN sync_fingerprint TEXT NOT NULL DEFAULT ''")- database.execSQL("ALTER TABLE categories ADD COLUMN sync_fingerprint TEXT NOT NULL DEFAULT ''")-- database.execSQL(- """- CREATE TABLE IF NOT EXISTS channel_import_stage (- 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,- sync_fingerprint TEXT NOT NULL,- PRIMARY KEY(session_id, provider_id, stream_id),- FOREIGN KEY(provider_id) REFERENCES providers(id) ON DELETE CASCADE- )- """.trimIndent()- )- database.execSQL("CREATE INDEX IF NOT EXISTS index_channel_import_stage_provider_id ON channel_import_stage(provider_id)")- database.execSQL("CREATE INDEX IF NOT EXISTS index_channel_import_stage_session_id_provider_id ON channel_import_stage(session_id, provider_id)")-- database.execSQL(- """- CREATE TABLE IF NOT EXISTS movie_import_stage (- 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,- PRIMARY KEY(session_id, provider_id, stream_id),- FOREIGN KEY(provider_id) REFERENCES providers(id) ON DELETE CASCADE- )- """.trimIndent()- )- database.execSQL("CREATE INDEX IF NOT EXISTS index_movie_import_stage_provider_id ON movie_import_stage(provider_id)")- database.execSQL("CREATE INDEX IF NOT EXISTS index_movie_import_stage_session_id_provider_id ON movie_import_stage(session_id, provider_id)")-- database.execSQL(- """- CREATE TABLE IF NOT EXISTS series_import_stage (- session_id INTEGER NOT NULL,- provider_id INTEGER NOT NULL,- series_id INTEGER NOT NULL,- name TEXT NOT NULL,- poster_url TEXT,- backdrop_url TEXT,- category_id INTEGER,- category_name TEXT,- plot TEXT,- "cast" TEXT,- director TEXT,- genre TEXT,- release_date TEXT,- rating REAL NOT NULL,- tmdb_id INTEGER,- youtube_trailer TEXT,- episode_run_time TEXT,- last_modified INTEGER NOT NULL,- is_adult INTEGER NOT NULL,- sync_fingerprint TEXT NOT NULL,- PRIMARY KEY(session_id, provider_id, series_id),- FOREIGN KEY(provider_id) REFERENCES providers(id) ON DELETE CASCADE- )- """.trimIndent()- )- database.execSQL("CREATE INDEX IF NOT EXISTS index_series_import_stage_provider_id ON series_import_stage(provider_id)")- database.execSQL("CREATE INDEX IF NOT EXISTS index_series_import_stage_session_id_provider_id ON series_import_stage(session_id, provider_id)")-- database.execSQL(- """- CREATE TABLE IF NOT EXISTS category_import_stage (- session_id INTEGER NOT NULL,- provider_id INTEGER NOT NULL,- category_id INTEGER NOT NULL,- name TEXT NOT NULL,- parent_id INTEGER,- type TEXT NOT NULL,- is_adult INTEGER NOT NULL,- sync_fingerprint TEXT NOT NULL,- PRIMARY KEY(session_id, provider_id, category_id, type),- FOREIGN KEY(provider_id) REFERENCES providers(id) ON DELETE CASCADE- )- """.trimIndent()- )- database.execSQL("CREATE INDEX IF NOT EXISTS index_category_import_stage_provider_id ON category_import_stage(provider_id)")- database.execSQL("CREATE INDEX IF NOT EXISTS index_category_import_stage_session_id_provider_id ON category_import_stage(session_id, provider_id)")- database.execSQL("CREATE INDEX IF NOT EXISTS index_category_import_stage_provider_id_type ON category_import_stage(provider_id, type)")- }- }-- val MIGRATION_20_21 = object : Migration(20, 21) {- override fun migrate(database: SupportSQLiteDatabase) {- database.execSQL("ALTER TABLE sync_metadata ADD COLUMN live_avoid_full_until INTEGER NOT NULL DEFAULT 0")- database.execSQL("ALTER TABLE sync_metadata ADD COLUMN movie_avoid_full_until INTEGER NOT NULL DEFAULT 0")- database.execSQL("ALTER TABLE sync_metadata ADD COLUMN series_avoid_full_until INTEGER NOT NULL DEFAULT 0")- database.execSQL("ALTER TABLE sync_metadata ADD COLUMN live_sequential_failures_remembered INTEGER NOT NULL DEFAULT 0")- database.execSQL("ALTER TABLE sync_metadata ADD COLUMN live_healthy_sync_streak INTEGER NOT NULL DEFAULT 0")- database.execSQL("ALTER TABLE sync_metadata ADD COLUMN series_sequential_failures_remembered INTEGER NOT NULL DEFAULT 0")- database.execSQL("ALTER TABLE sync_metadata ADD COLUMN series_healthy_sync_streak INTEGER NOT NULL DEFAULT 0")- }- }-- val MIGRATION_21_22 = object : Migration(21, 22) {- override fun migrate(database: SupportSQLiteDatabase) {- database.execSQL("ALTER TABLE channel_import_stage ADD COLUMN logical_group_id TEXT NOT NULL DEFAULT ''")- }- }-- val MIGRATION_22_23 = object : Migration(22, 23) {- override fun migrate(database: SupportSQLiteDatabase) {- database.execSQL("ALTER TABLE channel_import_stage ADD COLUMN error_count INTEGER NOT NULL DEFAULT 0")- }- }-- val MIGRATION_23_24 = object : Migration(23, 24) {- override fun migrate(database: SupportSQLiteDatabase) {- database.execSQL("ALTER TABLE providers ADD COLUMN xtream_fast_sync_enabled INTEGER NOT NULL DEFAULT 0")- database.execSQL(- """- CREATE TABLE IF NOT EXISTS movie_category_hydration (- provider_id INTEGER NOT NULL,- category_id INTEGER NOT NULL,- last_hydrated_at INTEGER NOT NULL DEFAULT 0,- item_count INTEGER NOT NULL DEFAULT 0,- last_status TEXT NOT NULL DEFAULT 'IDLE',- last_error TEXT,- PRIMARY KEY(provider_id, category_id),- FOREIGN KEY(provider_id) REFERENCES providers(id) ON DELETE CASCADE- )- """.trimIndent()- )- database.execSQL(- "CREATE INDEX IF NOT EXISTS index_movie_category_hydration_provider_id ON movie_category_hydration(provider_id)"- )- }- }-- val MIGRATION_25_26 = object : Migration(25, 26) {- override fun migrate(database: SupportSQLiteDatabase) {- database.execSQL("""- CREATE TABLE IF NOT EXISTS series_category_hydration (- provider_id INTEGER NOT NULL,- category_id INTEGER NOT NULL,- last_hydrated_at INTEGER NOT NULL DEFAULT 0,- item_count INTEGER NOT NULL DEFAULT 0,- last_status TEXT NOT NULL DEFAULT 'IDLE',- last_error TEXT,- PRIMARY KEY(provider_id, category_id),- FOREIGN KEY(provider_id) REFERENCES providers(id) ON DELETE CASCADE- )- """.trimIndent())- database.execSQL("CREATE INDEX IF NOT EXISTS index_series_category_hydration_provider_id ON series_category_hydration(provider_id)")- }- }-- val MIGRATION_26_27 = object : Migration(26, 27) {- override fun migrate(database: SupportSQLiteDatabase) {- database.execSQL("ALTER TABLE providers ADD COLUMN epg_sync_mode TEXT NOT NULL DEFAULT 'UPFRONT'")- }- }-- val MIGRATION_27_28 = object : Migration(27, 28) {- override fun migrate(database: SupportSQLiteDatabase) {- database.execSQL("ALTER TABLE providers ADD COLUMN m3u_vod_classification_enabled INTEGER NOT NULL DEFAULT 1")- }- }-- val MIGRATION_28_29 = object : Migration(28, 29) {- override fun migrate(database: SupportSQLiteDatabase) {- database.execSQL(- """- CREATE TABLE IF NOT EXISTS recording_schedules (- 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 DEFAULT 1,- is_manual INTEGER NOT NULL DEFAULT 0,- priority INTEGER NOT NULL DEFAULT 0,- created_at INTEGER NOT NULL,- updated_at INTEGER NOT NULL,- FOREIGN KEY(provider_id) REFERENCES providers(id) ON DELETE CASCADE- )- """.trimIndent()- )- database.execSQL("CREATE INDEX IF NOT EXISTS index_recording_schedules_provider_id ON recording_schedules(provider_id)")- database.execSQL("CREATE INDEX IF NOT EXISTS index_recording_schedules_enabled_requested_start_ms ON recording_schedules(enabled, requested_start_ms)")- database.execSQL("CREATE INDEX IF NOT EXISTS index_recording_schedules_recurring_rule_id ON recording_schedules(recurring_rule_id)")-- database.execSQL(- """- CREATE TABLE IF NOT EXISTS recording_runs (- id TEXT PRIMARY KEY 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 DEFAULT '{}',- user_agent TEXT,- expiration_time INTEGER,- provider_label TEXT,- output_uri TEXT,- output_display_path TEXT,- bytes_written INTEGER NOT NULL DEFAULT 0,- average_throughput_bps INTEGER NOT NULL DEFAULT 0,- retry_count INTEGER NOT NULL DEFAULT 0,- last_progress_at_ms INTEGER,- failure_category TEXT NOT NULL DEFAULT 'NONE',- failure_reason TEXT,- terminal_at_ms INTEGER,- started_at_ms INTEGER,- ended_at_ms INTEGER,- schedule_enabled INTEGER NOT NULL DEFAULT 1,- priority INTEGER NOT NULL DEFAULT 0,- alarm_start_at_ms INTEGER,- alarm_stop_at_ms INTEGER,- created_at INTEGER NOT NULL,- updated_at INTEGER NOT NULL,- FOREIGN KEY(schedule_id) REFERENCES recording_schedules(id) ON DELETE CASCADE,- FOREIGN KEY(provider_id) REFERENCES providers(id) ON DELETE CASCADE- )- """.trimIndent()- )- database.execSQL("CREATE INDEX IF NOT EXISTS index_recording_runs_schedule_id ON recording_runs(schedule_id)")- database.execSQL("CREATE INDEX IF NOT EXISTS index_recording_runs_provider_id ON recording_runs(provider_id)")- database.execSQL("CREATE INDEX IF NOT EXISTS index_recording_runs_status_scheduled_start_ms ON recording_runs(status, scheduled_start_ms)")- database.execSQL("CREATE INDEX IF NOT EXISTS index_recording_runs_alarm_start_at_ms ON recording_runs(alarm_start_at_ms)")- database.execSQL("CREATE INDEX IF NOT EXISTS index_recording_runs_alarm_stop_at_ms ON recording_runs(alarm_stop_at_ms)")-- database.execSQL(- """- CREATE TABLE IF NOT EXISTS recording_storage (- id INTEGER PRIMARY KEY NOT NULL,- tree_uri TEXT,- display_name TEXT,- output_directory TEXT,- available_bytes INTEGER,- is_writable INTEGER NOT NULL DEFAULT 0,- file_name_pattern TEXT NOT NULL DEFAULT 'ChannelName_yyyy-MM-dd_HH-mm_ProgramTitle.ts',- retention_days INTEGER,- max_simultaneous_recordings INTEGER NOT NULL DEFAULT 2,- updated_at INTEGER NOT NULL- )- """.trimIndent()- )- val now = System.currentTimeMillis()- database.execSQL(- """- INSERT OR IGNORE INTO recording_storage (- id, tree_uri, display_name, output_directory, available_bytes, is_writable, file_name_pattern,- retention_days, max_simultaneous_recordings, updated_at- ) VALUES (- 1, NULL, NULL, NULL, NULL, 0, 'ChannelName_yyyy-MM-dd_HH-mm_ProgramTitle.ts', NULL, 2, $now- )- """.trimIndent()- )- validateForeignKeys(database, "recording_schedules", "recording_runs")- }- }-- val MIGRATION_29_30 = object : Migration(29, 30) {- override fun migrate(database: SupportSQLiteDatabase) {- database.execSQL(- """- CREATE TABLE IF NOT EXISTS combined_m3u_profiles (- id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,- name TEXT NOT NULL,- enabled INTEGER NOT NULL DEFAULT 1,- created_at INTEGER NOT NULL,- updated_at INTEGER NOT NULL- )- """.trimIndent()- )- database.execSQL(- """- CREATE TABLE IF NOT EXISTS combined_m3u_profile_members (- 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 DEFAULT 1,- FOREIGN KEY(profile_id) REFERENCES combined_m3u_profiles(id) ON DELETE CASCADE,- FOREIGN KEY(provider_id) REFERENCES providers(id) ON DELETE CASCADE- )- """.trimIndent()- )- database.execSQL(- "CREATE INDEX IF NOT EXISTS index_combined_m3u_profile_members_profile_id ON combined_m3u_profile_members(profile_id)"- )- database.execSQL(- "CREATE INDEX IF NOT EXISTS index_combined_m3u_profile_members_provider_id ON combined_m3u_profile_members(provider_id)"- )- database.execSQL(- "CREATE UNIQUE INDEX IF NOT EXISTS index_combined_m3u_profile_members_profile_id_provider_id ON combined_m3u_profile_members(profile_id, provider_id)"- )- }- }-- val MIGRATION_30_31 = object : Migration(30, 31) {- override fun migrate(database: SupportSQLiteDatabase) {- database.execSQL("ALTER TABLE movies ADD COLUMN added_at INTEGER NOT NULL DEFAULT 0")- }- }-- val MIGRATION_31_32 = object : Migration(31, 32) {- override fun migrate(database: SupportSQLiteDatabase) {- fun firstLong(query: String): Long? = database.query(query).use { cursor ->- if (cursor.moveToFirst() && !cursor.isNull(0)) cursor.getLong(0) else null- }-- // FK enforcement was never enabled at runtime (setForeignKeyConstraintsEnabled was- // never called), so ON DELETE CASCADE never fired when a provider was deleted.- // Purge orphaned content rows now so the provider_id inference below can only- // ever produce valid FK values. Favorites pointing to purged content will resolve- // to NULL and be silently dropped via the `continue` below.- database.execSQL("DELETE FROM channels WHERE provider_id NOT IN (SELECT id FROM providers)")- database.execSQL("DELETE FROM movies WHERE provider_id NOT IN (SELECT id FROM providers)")- database.execSQL("DELETE FROM series WHERE provider_id NOT IN (SELECT id FROM providers)")-- val defaultProviderId = firstLong(- "SELECT id FROM providers WHERE is_active = 1 ORDER BY id LIMIT 1"- ) ?: firstLong(- "SELECT id FROM providers ORDER BY id LIMIT 1"- )-- database.execSQL(- """- CREATE TABLE IF NOT EXISTS virtual_groups_new (- 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 DELETE CASCADE- )- """.trimIndent()- )-- val providersByLegacyGroup = mutableMapOf<Long, MutableSet<Long>>()- database.query(- """- SELECT f.group_id,- CASE f.content_type- WHEN 'LIVE' THEN (SELECT provider_id FROM channels WHERE id = f.content_id)- WHEN 'MOVIE' THEN (SELECT provider_id FROM movies WHERE id = f.content_id)- WHEN 'SERIES' THEN (SELECT provider_id FROM series WHERE id = f.content_id)- ELSE NULL- END AS provider_id- FROM favorites f- WHERE f.group_id IS NOT NULL- """.trimIndent()- ).use { cursor ->- while (cursor.moveToNext()) {- if (cursor.isNull(0) || cursor.isNull(1)) continue- val groupId = cursor.getLong(0)- val providerId = cursor.getLong(1)- providersByLegacyGroup.getOrPut(groupId) { linkedSetOf() }.add(providerId)- }- }-- val groupProviderToNewId = mutableMapOf<Pair<Long, Long>, Long>()- var nextGroupId = (firstLong("SELECT MAX(id) FROM virtual_groups") ?: 0L) + 1L-- database.query(- "SELECT id, name, icon_emoji, position, created_at, content_type FROM virtual_groups ORDER BY id"- ).use { cursor ->- while (cursor.moveToNext()) {- val legacyGroupId = cursor.getLong(0)- val name = cursor.getString(1)- val iconEmoji = if (cursor.isNull(2)) null else cursor.getString(2)- val position = cursor.getInt(3)- val createdAt = cursor.getLong(4)- val contentType = cursor.getString(5)- val providerIds = providersByLegacyGroup[legacyGroupId]- ?.toList()- ?.sorted()- ?: defaultProviderId?.let(::listOf)- ?: emptyList()-- providerIds.forEachIndexed { index, providerId ->- val newGroupId = if (index == 0) legacyGroupId else nextGroupId++- groupProviderToNewId[legacyGroupId to providerId] = newGroupId- database.execSQL(- """- INSERT INTO virtual_groups_new(- id, provider_id, name, icon_emoji, position, created_at, content_type- ) VALUES (?, ?, ?, ?, ?, ?, ?)- """.trimIndent(),- arrayOf(newGroupId, providerId, name, iconEmoji, position, createdAt, contentType)- )- }- }- }-- database.execSQL("ALTER TABLE virtual_groups RENAME TO virtual_groups_legacy")- database.execSQL("ALTER TABLE virtual_groups_new RENAME TO virtual_groups")- database.execSQL(- "CREATE INDEX IF NOT EXISTS index_virtual_groups_provider_id_content_type ON virtual_groups(provider_id, content_type)"- )- database.execSQL(- "CREATE INDEX IF NOT EXISTS index_virtual_groups_position ON virtual_groups(position)"- )- database.execSQL(- "CREATE INDEX IF NOT EXISTS index_virtual_groups_content_type ON virtual_groups(content_type)"- )-- database.execSQL(- """- CREATE TABLE IF NOT EXISTS favorites_new (- id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,- provider_id INTEGER NOT NULL,- content_id INTEGER NOT NULL,- content_type TEXT NOT NULL,- position INTEGER NOT NULL,- group_id INTEGER,- added_at INTEGER NOT NULL,- FOREIGN KEY(provider_id) REFERENCES providers(id) ON DELETE CASCADE,- FOREIGN KEY(group_id) REFERENCES virtual_groups(id) ON DELETE SET NULL- )- """.trimIndent()- )-- database.query(- """- SELECT f.id, f.content_id, f.content_type, f.position, f.group_id, f.added_at,- CASE f.content_type- WHEN 'LIVE' THEN (SELECT provider_id FROM channels WHERE id = f.content_id)- WHEN 'MOVIE' THEN (SELECT provider_id FROM movies WHERE id = f.content_id)- WHEN 'SERIES' THEN (SELECT provider_id FROM series WHERE id = f.content_id)- ELSE NULL- END AS provider_id- FROM favorites f- ORDER BY f.id ASC- """.trimIndent()- ).use { cursor ->- while (cursor.moveToNext()) {- val favoriteId = cursor.getLong(0)- val contentId = cursor.getLong(1)- val contentType = cursor.getString(2)- val position = cursor.getInt(3)- val legacyGroupId = if (cursor.isNull(4)) null else cursor.getLong(4)- val addedAt = cursor.getLong(5)- val providerId = when {- !cursor.isNull(6) -> cursor.getLong(6)- legacyGroupId != null -> groupProviderToNewId.keys- .firstOrNull { it.first == legacyGroupId }- ?.second- else -> null- } ?: continue-- val newGroupId = legacyGroupId?.let { groupId ->- groupProviderToNewId[groupId to providerId]- ?: groupProviderToNewId.entries.firstOrNull { it.key.first == groupId }?.value- }-- database.execSQL(- """- INSERT OR REPLACE INTO favorites_new(- id, provider_id, content_id, content_type, position, group_id, added_at- ) VALUES (?, ?, ?, ?, ?, ?, ?)- """.trimIndent(),- arrayOf(favoriteId, providerId, contentId, contentType, position, newGroupId, addedAt)- )- }- }-- database.execSQL("ALTER TABLE favorites RENAME TO favorites_legacy")- database.execSQL("ALTER TABLE favorites_new RENAME TO favorites")- database.execSQL(- "CREATE UNIQUE INDEX IF NOT EXISTS index_favorites_provider_id_content_id_content_type_group_id ON favorites(provider_id, content_id, content_type, group_id)"- )- database.execSQL(- "CREATE INDEX IF NOT EXISTS index_favorites_provider_id_content_type_group_id ON favorites(provider_id, content_type, group_id)"- )- database.execSQL(- "CREATE INDEX IF NOT EXISTS index_favorites_group_id_position ON favorites(group_id, position)"- )-- database.execSQL("DROP TABLE favorites_legacy")- database.execSQL("DROP TABLE virtual_groups_legacy")- validateForeignKeys(database, "virtual_groups", "favorites")- }- }-- val MIGRATION_32_33 = object : Migration(32, 33) {- override fun migrate(database: SupportSQLiteDatabase) {- database.execSQL("ALTER TABLE movies ADD COLUMN watch_count INTEGER NOT NULL DEFAULT 0")- database.execSQL(- """- UPDATE movies- SET watch_count = COALESCE((- SELECT playback_history.watch_count- FROM playback_history- WHERE playback_history.content_id = movies.id- AND playback_history.content_type = 'MOVIE'- AND playback_history.provider_id = movies.provider_id- ), 0)- """.trimIndent()- )- database.execSQL(- """- CREATE INDEX IF NOT EXISTS index_favorites_global_provider_id_content_type_content_id- ON favorites(provider_id, content_type, content_id)- WHERE group_id IS NULL- """.trimIndent()- )- }- }-- val MIGRATION_33_34 = object : Migration(33, 34) {- override fun migrate(database: SupportSQLiteDatabase) {- database.execSQL("ALTER TABLE sync_metadata ADD COLUMN last_live_success INTEGER NOT NULL DEFAULT 0")- database.execSQL("ALTER TABLE sync_metadata ADD COLUMN last_series_success INTEGER NOT NULL DEFAULT 0")- database.execSQL("ALTER TABLE sync_metadata ADD COLUMN last_epg_success INTEGER NOT NULL DEFAULT 0")- database.execSQL("UPDATE sync_metadata SET last_live_success = last_live_sync")- database.execSQL("UPDATE sync_metadata SET last_series_success = last_series_sync")- database.execSQL("UPDATE sync_metadata SET last_epg_success = last_epg_sync")- database.execSQL(- "CREATE INDEX IF NOT EXISTS index_programs_provider_id_end_time_channel_id ON programs(provider_id, end_time, channel_id)"- )- // No FK-bearing rows added; only column additions and indexes.- }- }-- val MIGRATION_34_35 = object : Migration(34, 35) {- override fun migrate(database: SupportSQLiteDatabase) {- database.execSQL(- """- CREATE TABLE IF NOT EXISTS search_history (- id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,- query TEXT NOT NULL,- content_scope TEXT NOT NULL,- provider_id INTEGER NOT NULL DEFAULT 0,- used_at INTEGER NOT NULL,- use_count INTEGER NOT NULL DEFAULT 1- )- """.trimIndent()- )- database.execSQL(- "CREATE INDEX IF NOT EXISTS index_search_history_content_scope_provider_id_used_at ON search_history(content_scope, provider_id, used_at)"- )- database.execSQL(- "CREATE INDEX IF NOT EXISTS index_search_history_used_at ON search_history(used_at)"- )- database.execSQL(- "CREATE INDEX IF NOT EXISTS index_search_history_provider_id ON search_history(provider_id)"- )- database.execSQL(- "CREATE UNIQUE INDEX IF NOT EXISTS index_search_history_query_content_scope_provider_id ON search_history(query, content_scope, provider_id)"- )- // search_history has no FK columns; no FK check needed.- }- }-- val MIGRATION_35_36 = object : Migration(35, 36) {- override fun migrate(database: SupportSQLiteDatabase) {- database.execSQL("ALTER TABLE channel_epg_mappings ADD COLUMN matched_at INTEGER NOT NULL DEFAULT 0")- database.execSQL("ALTER TABLE channel_epg_mappings ADD COLUMN failed_attempts INTEGER NOT NULL DEFAULT 0")- database.execSQL("ALTER TABLE channel_epg_mappings ADD COLUMN source TEXT")-- database.execSQL(- """- CREATE TABLE IF NOT EXISTS program_reminders (- 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 DEFAULT 5,- is_dismissed INTEGER NOT NULL DEFAULT 0,- notified_at INTEGER,- created_at INTEGER NOT NULL,- FOREIGN KEY(provider_id) REFERENCES providers(id) ON DELETE CASCADE- )- """.trimIndent()- )- database.execSQL(- "CREATE INDEX IF NOT EXISTS index_program_reminders_provider_id_remind_at ON program_reminders(provider_id, remind_at)"- )- database.execSQL(- "CREATE INDEX IF NOT EXISTS index_program_reminders_is_dismissed_notified_at_remind_at ON program_reminders(is_dismissed, notified_at, remind_at)"- )- database.execSQL(- "CREATE INDEX IF NOT EXISTS index_program_reminders_provider_id_channel_id_program_start_time ON program_reminders(provider_id, channel_id, program_start_time)"- )- database.execSQL(- "CREATE UNIQUE INDEX IF NOT EXISTS index_program_reminders_provider_id_channel_id_program_title_program_start_time ON program_reminders(provider_id, channel_id, program_title, program_start_time)"- )- validateForeignKeys(database, "program_reminders")- }- }-- val MIGRATION_24_25 = object : Migration(24, 25) {- override fun migrate(database: SupportSQLiteDatabase) {- // ── epg_sources ──- database.execSQL("""- CREATE TABLE IF NOT EXISTS epg_sources (- id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,- name TEXT NOT NULL,- url TEXT NOT NULL,- enabled INTEGER NOT NULL DEFAULT 1,- last_refresh_at INTEGER NOT NULL DEFAULT 0,- last_success_at INTEGER NOT NULL DEFAULT 0,- last_error TEXT,- priority INTEGER NOT NULL DEFAULT 0,- created_at INTEGER NOT NULL DEFAULT 0,- updated_at INTEGER NOT NULL DEFAULT 0- )- """.trimIndent())- database.execSQL("CREATE UNIQUE INDEX IF NOT EXISTS index_epg_sources_url ON epg_sources(url)")-- // ── provider_epg_sources ──- database.execSQL("""- CREATE TABLE IF NOT EXISTS provider_epg_sources (- id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,- provider_id INTEGER NOT NULL,- epg_source_id INTEGER NOT NULL,- priority INTEGER NOT NULL DEFAULT 0,- enabled INTEGER NOT NULL DEFAULT 1,- FOREIGN KEY(provider_id) REFERENCES providers(id) ON DELETE CASCADE,- FOREIGN KEY(epg_source_id) REFERENCES epg_sources(id) ON DELETE CASCADE- )- """.trimIndent())- database.execSQL("CREATE UNIQUE INDEX IF NOT EXISTS index_provider_epg_sources_provider_id_epg_source_id ON provider_epg_sources(provider_id, epg_source_id)")- database.execSQL("CREATE INDEX IF NOT EXISTS index_provider_epg_sources_epg_source_id ON provider_epg_sources(epg_source_id)")-- // ── epg_channels ──- database.execSQL("""- CREATE TABLE IF NOT EXISTS epg_channels (- 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 DEFAULT '',- icon_url TEXT,- FOREIGN KEY(epg_source_id) REFERENCES epg_sources(id) ON DELETE CASCADE- )- """.trimIndent())- database.execSQL("CREATE UNIQUE INDEX IF NOT EXISTS index_epg_channels_epg_source_id_xmltv_channel_id ON epg_channels(epg_source_id, xmltv_channel_id)")- database.execSQL("CREATE INDEX IF NOT EXISTS index_epg_channels_epg_source_id ON epg_channels(epg_source_id)")- database.execSQL("CREATE INDEX IF NOT EXISTS index_epg_channels_normalized_name ON epg_channels(normalized_name)")-- // ── epg_programmes ──- database.execSQL("""- CREATE TABLE IF NOT EXISTS epg_programmes (- id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,- epg_source_id INTEGER NOT NULL,- xmltv_channel_id TEXT NOT NULL,- start_time INTEGER NOT NULL DEFAULT 0,- end_time INTEGER NOT NULL DEFAULT 0,- title TEXT NOT NULL,- subtitle TEXT,- description TEXT NOT NULL DEFAULT '',- category TEXT,- lang TEXT NOT NULL DEFAULT '',- rating TEXT,- image_url TEXT,- episode_info TEXT,- FOREIGN KEY(epg_source_id) REFERENCES epg_sources(id) ON DELETE CASCADE- )- """.trimIndent())- database.execSQL("CREATE INDEX IF NOT EXISTS index_epg_programmes_epg_source_id_xmltv_channel_id_start_time ON epg_programmes(epg_source_id, xmltv_channel_id, start_time)")- database.execSQL("CREATE UNIQUE INDEX IF NOT EXISTS index_epg_programmes_epg_source_id_xmltv_channel_id_start_time_end_time ON epg_programmes(epg_source_id, xmltv_channel_id, start_time, end_time)")- database.execSQL("CREATE INDEX IF NOT EXISTS index_epg_programmes_epg_source_id ON epg_programmes(epg_source_id)")- database.execSQL("CREATE INDEX IF NOT EXISTS index_epg_programmes_start_time ON epg_programmes(start_time)")-- // ── channel_epg_mappings ──- database.execSQL("""- CREATE TABLE IF NOT EXISTS channel_epg_mappings (- id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,- provider_channel_id INTEGER NOT NULL,- provider_id INTEGER NOT NULL,- source_type TEXT NOT NULL DEFAULT 'NONE',- epg_source_id INTEGER,- xmltv_channel_id TEXT,- match_type TEXT,- confidence REAL NOT NULL DEFAULT 0,- is_manual_override INTEGER NOT NULL DEFAULT 0,- updated_at INTEGER NOT NULL DEFAULT 0,- FOREIGN KEY(provider_id) REFERENCES providers(id) ON DELETE CASCADE- )- """.trimIndent())- database.execSQL("CREATE UNIQUE INDEX IF NOT EXISTS index_channel_epg_mappings_provider_id_provider_channel_id ON channel_epg_mappings(provider_id, provider_channel_id)")- database.execSQL("CREATE INDEX IF NOT EXISTS index_channel_epg_mappings_provider_id ON channel_epg_mappings(provider_id)")- }- }-- val MIGRATION_36_37 = object : Migration(36, 37) {- override fun migrate(database: SupportSQLiteDatabase) {- database.execSQL(- """- CREATE TABLE IF NOT EXISTS tmdb_identity (- 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 DELETE CASCADE- )- """.trimIndent()- )- database.execSQL("CREATE INDEX IF NOT EXISTS index_tmdb_identity_content_type ON tmdb_identity(content_type)")- database.execSQL("CREATE INDEX IF NOT EXISTS index_tmdb_identity_canonical_provider_id ON tmdb_identity(canonical_provider_id)")- database.execSQL(- """- INSERT OR REPLACE INTO tmdb_identity (tmdb_id, content_type, canonical_provider_id, first_seen_at)- SELECT tmdb_id, 'MOVIE', MIN(provider_id), 0- FROM movies- WHERE tmdb_id IS NOT NULL- GROUP BY tmdb_id- """.trimIndent()- )- database.execSQL(- """- INSERT OR REPLACE INTO tmdb_identity (tmdb_id, content_type, canonical_provider_id, first_seen_at)- SELECT tmdb_id, 'SERIES', MIN(provider_id), 0- FROM series- WHERE tmdb_id IS NOT NULL- GROUP BY tmdb_id- """.trimIndent()- )- validateForeignKeys(database, "tmdb_identity")- }- }-- val MIGRATION_37_38 = object : Migration(37, 38) {- override fun migrate(database: SupportSQLiteDatabase) {- database.execSQL("ALTER TABLE epg_sources ADD COLUMN etag TEXT DEFAULT NULL")- database.execSQL("ALTER TABLE epg_sources ADD COLUMN last_modified_header TEXT DEFAULT NULL")- }- }-- val MIGRATION_38_39 = object : Migration(38, 39) {- override fun migrate(database: SupportSQLiteDatabase) {- database.execSQL("ALTER TABLE providers ADD COLUMN stalker_mac_address TEXT NOT NULL DEFAULT ''")- database.execSQL("ALTER TABLE providers ADD COLUMN stalker_device_profile TEXT NOT NULL DEFAULT ''")- database.execSQL("ALTER TABLE providers ADD COLUMN stalker_device_timezone TEXT NOT NULL DEFAULT ''")- database.execSQL("ALTER TABLE providers ADD COLUMN stalker_device_locale TEXT NOT NULL DEFAULT ''")- database.execSQL("DROP INDEX IF EXISTS index_providers_server_url_username")- database.execSQL("DROP INDEX IF EXISTS index_providers_server_url_username_stalker_mac_address")- database.execSQL(- """- CREATE UNIQUE INDEX IF NOT EXISTS index_providers_server_url_username_stalker_mac_address- ON providers(server_url, username, stalker_mac_address)- """.trimIndent()- )- }- }-- /**- * Migration 39 → 40: Drop per-row FTS triggers.- * The triggers (channels_ai/ad/au, movies_ai/ad/au, series_ai/ad/au) fired for every- * individual row INSERT/DELETE/UPDATE and serialised 52k+ writes through the FTS index- * one row at a time, causing minute-long first-sync freezes on large providers.- * FTS is now rebuilt in bulk via INSERT INTO table_fts(table_fts) VALUES('rebuild')- * once per sync, after each catalog transaction commits.- */- val MIGRATION_39_40 = object : Migration(39, 40) {- override fun migrate(database: SupportSQLiteDatabase) {- database.execSQL("DROP TRIGGER IF EXISTS channels_ai")- database.execSQL("DROP TRIGGER IF EXISTS channels_ad")- database.execSQL("DROP TRIGGER IF EXISTS channels_au")- database.execSQL("DROP TRIGGER IF EXISTS movies_ai")- database.execSQL("DROP TRIGGER IF EXISTS movies_ad")- database.execSQL("DROP TRIGGER IF EXISTS movies_au")- database.execSQL("DROP TRIGGER IF EXISTS series_ai")- database.execSQL("DROP TRIGGER IF EXISTS series_ad")- database.execSQL("DROP TRIGGER IF EXISTS series_au")- }- }-- /**- * Migration 40 → 41: add per-channel A/V sync override.- * Null means the channel follows the global player default.- */- val MIGRATION_40_41 = object : Migration(40, 41) {- override fun migrate(database: SupportSQLiteDatabase) {- database.execSQL("ALTER TABLE channel_preferences ADD COLUMN audio_video_offset_ms INTEGER DEFAULT NULL")- }- }-- /**- * Migration 41 -> 42: remember playback decoder/surface combinations that fail- * silently on a device so Auto mode can avoid repeating them.- */- val MIGRATION_41_42 = object : Migration(41, 42) {- override fun migrate(database: SupportSQLiteDatabase) {- database.execSQL(- """- CREATE TABLE IF NOT EXISTS playback_compatibility_records (- 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 DEFAULT '',- last_failed_at INTEGER NOT NULL DEFAULT 0,- last_succeeded_at INTEGER NOT NULL DEFAULT 0,- failure_count INTEGER NOT NULL DEFAULT 0,- success_count INTEGER NOT NULL DEFAULT 0- )- """.trimIndent()- )- database.execSQL(- """- CREATE UNIQUE INDEX IF NOT EXISTS index_playback_compatibility_records_device_fingerprint_stream_type_video_mime_type_resolution_bucket_decoder_name_surface_type- ON playback_compatibility_records(device_fingerprint, stream_type, video_mime_type, resolution_bucket, decoder_name, surface_type)- """.trimIndent()- )- database.execSQL(- """- CREATE INDEX IF NOT EXISTS index_playback_compatibility_records_device_fingerprint_stream_type_video_mime_type_resolution_bucket- ON playback_compatibility_records(device_fingerprint, stream_type, video_mime_type, resolution_bucket)- """.trimIndent()- )- database.execSQL("CREATE INDEX IF NOT EXISTS index_playback_compatibility_records_last_failed_at ON playback_compatibility_records(last_failed_at)")- database.execSQL("CREATE INDEX IF NOT EXISTS index_playback_compatibility_records_last_succeeded_at ON playback_compatibility_records(last_succeeded_at)")- }- }-- /**- * Migration 42 -> 43: preserve provider-native series identifiers so Stalker- * series details can round-trip composite portal IDs.- */- val MIGRATION_42_43 = object : Migration(42, 43) {- override fun migrate(database: SupportSQLiteDatabase) {- database.execSQL("ALTER TABLE series ADD COLUMN provider_series_id TEXT")- database.execSQL(- "UPDATE series SET provider_series_id = CAST(series_id AS TEXT) WHERE provider_series_id IS NULL"- )- }- }-- /**- * Migration 43 -> 44: add page-aware VOD/series category hydration metadata- * for on-demand Stalker paging while preserving existing complete caches.- */- val MIGRATION_43_44 = object : Migration(43, 44) {- override fun migrate(database: SupportSQLiteDatabase) {- addPagedHydrationColumns(database, "movie_category_hydration")- addPagedHydrationColumns(database, "series_category_hydration")- }-- private fun addPagedHydrationColumns(database: SupportSQLiteDatabase, tableName: String) {- database.execSQL("ALTER TABLE $tableName ADD COLUMN last_loaded_page INTEGER NOT NULL DEFAULT 0")- database.execSQL("ALTER TABLE $tableName ADD COLUMN total_pages INTEGER NOT NULL DEFAULT 0")- database.execSQL("ALTER TABLE $tableName ADD COLUMN is_complete INTEGER NOT NULL DEFAULT 0")- database.execSQL("ALTER TABLE $tableName ADD COLUMN page_size INTEGER NOT NULL DEFAULT 0")- database.execSQL(- """- UPDATE $tableName- SET last_loaded_page = CASE- WHEN last_status = 'SUCCESS' THEN 1- ELSE 0- END,- total_pages = CASE- WHEN last_status = 'SUCCESS' THEN 1- ELSE 0- END,- is_complete = CASE- WHEN last_status = 'SUCCESS' THEN 1- ELSE 0- END,- page_size = CASE- WHEN last_status = 'SUCCESS' THEN item_count- ELSE 0- END- """.trimIndent()- )- }- }-- /**- * Migration 44 -> 45: make favorite uniqueness null-safe by materializing a non-null- * group scope key and deduping any pre-existing global favorite collisions.- */- val MIGRATION_44_45 = object : Migration(44, 45) {- override fun migrate(database: SupportSQLiteDatabase) {- database.execSQL("ALTER TABLE favorites ADD COLUMN group_key INTEGER NOT NULL DEFAULT 0")- database.execSQL("UPDATE favorites SET group_key = COALESCE(group_id, 0)")- database.execSQL(- """- UPDATE favorites- SET position = (- SELECT MIN(dupe.position)- FROM favorites AS dupe- WHERE dupe.group_id IS NULL- AND dupe.provider_id = favorites.provider_id- AND dupe.content_id = favorites.content_id- AND dupe.content_type = favorites.content_type- ),- added_at = (- SELECT MIN(dupe.added_at)- FROM favorites AS dupe- WHERE dupe.group_id IS NULL- AND dupe.provider_id = favorites.provider_id- AND dupe.content_id = favorites.content_id- AND dupe.content_type = favorites.content_type- )- WHERE favorites.group_id IS NULL- AND favorites.id IN (- SELECT MIN(id)- FROM favorites- WHERE group_id IS NULL- GROUP BY provider_id, content_id, content_type- HAVING COUNT(*) > 1- )- """.trimIndent()- )- database.execSQL(- """- DELETE FROM favorites- WHERE group_id IS NULL- AND id NOT IN (- SELECT MIN(id)- FROM favorites- WHERE group_id IS NULL- GROUP BY provider_id, content_id, content_type- )- """.trimIndent()- )-- database.execSQL("DROP INDEX IF EXISTS index_favorites_provider_id_content_id_content_type_group_id")- database.execSQL("DROP TABLE IF EXISTS favorites_new")- database.execSQL(- """- CREATE TABLE IF NOT EXISTS favorites_new (- 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 DELETE CASCADE,- FOREIGN KEY(group_id) REFERENCES virtual_groups(id) ON DELETE SET NULL- )- """.trimIndent()- )- database.execSQL(- """- INSERT INTO favorites_new(- id,- provider_id,- content_id,- content_type,- position,- group_id,- group_key,- added_at- )- SELECT- id,- provider_id,- content_id,- content_type,- position,- group_id,- group_key,- added_at- FROM favorites- """.trimIndent()- )- database.execSQL("DROP TABLE favorites")- database.execSQL("ALTER TABLE favorites_new RENAME TO favorites")- database.execSQL(- "CREATE UNIQUE INDEX IF NOT EXISTS index_favorites_provider_id_content_id_content_type_group_key ON favorites(provider_id, content_id, content_type, group_key)"- )- database.execSQL(- "CREATE INDEX IF NOT EXISTS index_favorites_provider_id_content_type_group_id ON favorites(provider_id, content_type, group_id)"- )- database.execSQL(- "CREATE INDEX IF NOT EXISTS index_favorites_group_id_position ON favorites(group_id, position)"- )- validateForeignKeys(database, "favorites")- }- }-- /**- * Migration 45 -> 46: preserve provider-native series IDs through staging by storing both- * the raw provider ID and a non-null remote key used for staged apply matching.- */- val MIGRATION_45_46 = object : Migration(45, 46) {- override fun migrate(database: SupportSQLiteDatabase) {- database.execSQL(- """- CREATE TABLE IF NOT EXISTS series_import_stage_new (- 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 DELETE CASCADE- )- """.trimIndent()- )- database.execSQL(- """- INSERT INTO series_import_stage_new (- session_id,- provider_id,- series_id,- provider_series_id,- provider_series_key,- name,- poster_url,- backdrop_url,- category_id,- category_name,- plot,- "cast",- director,- genre,- release_date,- rating,- tmdb_id,- youtube_trailer,- episode_run_time,- last_modified,- is_adult,- sync_fingerprint- )- SELECT- session_id,- provider_id,- series_id,- NULL,- CAST(series_id AS TEXT),- name,- poster_url,- backdrop_url,- category_id,- category_name,- plot,- "cast",- director,- genre,- release_date,- rating,- tmdb_id,- youtube_trailer,- episode_run_time,- last_modified,- is_adult,- sync_fingerprint- FROM series_import_stage- """.trimIndent()- )- database.execSQL("DROP TABLE series_import_stage")- database.execSQL("ALTER TABLE series_import_stage_new RENAME TO series_import_stage")- database.execSQL("CREATE INDEX IF NOT EXISTS index_series_import_stage_provider_id ON series_import_stage(provider_id)")- database.execSQL("CREATE INDEX IF NOT EXISTS index_series_import_stage_session_id_provider_id ON series_import_stage(session_id, provider_id)")- validateForeignKeys(database, "series_import_stage")- }- }-- /**- * Migration 46 -> 47: add provider-leading browse indexes so large-provider cursor pages,- * category/rating sorts, and correlated playback-history filters avoid wide scans.- */- val MIGRATION_46_47 = object : Migration(46, 47) {- override fun migrate(database: SupportSQLiteDatabase) {- database.execSQL("CREATE INDEX IF NOT EXISTS index_movies_provider_id_name_id ON movies(provider_id, name, id)")- database.execSQL("CREATE INDEX IF NOT EXISTS index_movies_provider_id_category_id_name_id ON movies(provider_id, category_id, name, id)")- database.execSQL("CREATE INDEX IF NOT EXISTS index_movies_provider_id_rating_name_id ON movies(provider_id, rating, name, id)")- database.execSQL("CREATE INDEX IF NOT EXISTS index_movies_provider_id_added_at_release_date_name_id ON movies(provider_id, added_at, release_date, name, id)")- database.execSQL("CREATE INDEX IF NOT EXISTS index_series_provider_id_name_id ON series(provider_id, name, id)")- database.execSQL("CREATE INDEX IF NOT EXISTS index_series_provider_id_category_id_name_id ON series(provider_id, category_id, name, id)")- database.execSQL("CREATE INDEX IF NOT EXISTS index_series_provider_id_rating_name_id ON series(provider_id, rating, name, id)")- database.execSQL("CREATE INDEX IF NOT EXISTS index_series_provider_id_last_modified_name_id ON series(provider_id, last_modified, name, id)")- database.execSQL("CREATE INDEX IF NOT EXISTS index_playback_history_provider_id_content_type_content_id ON playback_history(provider_id, content_type, content_id)")- database.execSQL("CREATE INDEX IF NOT EXISTS index_playback_history_provider_id_content_type_last_watched_at ON playback_history(provider_id, content_type, last_watched_at)")- }- }-- /**- * Migration 47 -> 48: create the Xtream summary index and section job state tables.- * Existing Xtream live/movie/series rows are backfilled without deleting or remapping- * the playable/detail tables that favorites and history already reference.- */- val MIGRATION_47_48 = object : Migration(47, 48) {- override fun migrate(database: SupportSQLiteDatabase) {- database.execSQL("ALTER TABLE movies ADD COLUMN cache_state TEXT NOT NULL DEFAULT 'DETAIL_HYDRATED'")- database.execSQL("ALTER TABLE movies ADD COLUMN detail_hydrated_at INTEGER NOT NULL DEFAULT 0")- database.execSQL("ALTER TABLE movies ADD COLUMN remote_stale_at INTEGER NOT NULL DEFAULT 0")- database.execSQL("ALTER TABLE series ADD COLUMN cache_state TEXT NOT NULL DEFAULT 'DETAIL_HYDRATED'")- database.execSQL("ALTER TABLE series ADD COLUMN detail_hydrated_at INTEGER NOT NULL DEFAULT 0")- database.execSQL("ALTER TABLE series ADD COLUMN remote_stale_at INTEGER NOT NULL DEFAULT 0")-- database.execSQL(- """- UPDATE movies- SET cache_state = 'SUMMARY_ONLY'- WHERE COALESCE(plot, '') = ''- AND COALESCE("cast", '') = ''- AND COALESCE(director, '') = ''- AND COALESCE(genre, '') = ''- AND COALESCE(duration, '') = ''- AND duration_seconds = 0- AND tmdb_id IS NULL- """.trimIndent()- )- database.execSQL(- """- UPDATE series- SET cache_state = 'SUMMARY_ONLY'- WHERE COALESCE(plot, '') = ''- AND COALESCE("cast", '') = ''- AND COALESCE(director, '') = ''- AND COALESCE(genre, '') = ''- AND COALESCE(episode_run_time, '') = ''- AND tmdb_id IS NULL- """.trimIndent()- )- database.execSQL(- """- UPDATE movies- SET detail_hydrated_at = COALESCE(- (SELECT providers.last_synced_at FROM providers WHERE providers.id = movies.provider_id),- 0- )- WHERE cache_state = 'DETAIL_HYDRATED'- """.trimIndent()- )- database.execSQL(- """- UPDATE series- SET detail_hydrated_at = COALESCE(- (SELECT providers.last_synced_at FROM providers WHERE providers.id = series.provider_id),- 0- )- WHERE cache_state = 'DETAIL_HYDRATED'- """.trimIndent()- )-- database.execSQL(- """- CREATE TABLE IF NOT EXISTS xtream_content_index (- 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 DELETE CASCADE- )- """.trimIndent()- )- database.execSQL("CREATE INDEX IF NOT EXISTS index_xtream_content_index_provider_id_content_type ON xtream_content_index(provider_id, content_type)")- database.execSQL("CREATE INDEX IF NOT EXISTS index_xtream_content_index_provider_id_content_type_category_id ON xtream_content_index(provider_id, content_type, category_id)")- database.execSQL("CREATE INDEX IF NOT EXISTS index_xtream_content_index_provider_id_content_type_name ON xtream_content_index(provider_id, content_type, name)")- database.execSQL("CREATE INDEX IF NOT EXISTS index_xtream_content_index_provider_id_content_type_local_content_id ON xtream_content_index(provider_id, content_type, local_content_id)")- database.execSQL("CREATE INDEX IF NOT EXISTS index_xtream_content_index_provider_id_indexed_at ON xtream_content_index(provider_id, indexed_at)")- database.execSQL("CREATE INDEX IF NOT EXISTS index_xtream_content_index_stale_state ON xtream_content_index(stale_state)")-- database.execSQL(- """- CREATE TABLE IF NOT EXISTS xtream_index_jobs (- 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 DELETE CASCADE- )- """.trimIndent()- )- database.execSQL("CREATE INDEX IF NOT EXISTS index_xtream_index_jobs_provider_id ON xtream_index_jobs(provider_id)")- database.execSQL("CREATE INDEX IF NOT EXISTS index_xtream_index_jobs_section ON xtream_index_jobs(section)")- database.execSQL("CREATE INDEX IF NOT EXISTS index_xtream_index_jobs_state ON xtream_index_jobs(state)")- database.execSQL("CREATE INDEX IF NOT EXISTS index_xtream_index_jobs_updated_at ON xtream_index_jobs(updated_at)")-- database.execSQL(- """- INSERT OR REPLACE INTO xtream_content_index (- provider_id, content_type, remote_id, local_content_id, name, category_id,- category_name, image_url, container_extension, rating, added_at, remote_updated_at,- is_adult, indexed_at, detail_hydrated_at, stale_state, error_state, sync_fingerprint- )- SELECT- c.provider_id,- 'LIVE',- CAST(c.stream_id AS TEXT),- c.id,- c.name,- c.category_id,- c.category_name,- c.logo_url,- NULL,- 0,- 0,- 0,- c.is_adult,- COALESCE(p.last_synced_at, 0),- COALESCE(p.last_synced_at, 0),- 'ACTIVE',- NULL,- c.sync_fingerprint- FROM channels c- JOIN providers p ON p.id = c.provider_id- WHERE p.type = 'XTREAM_CODES'- """.trimIndent()- )- database.execSQL(- """- INSERT OR REPLACE INTO xtream_content_index (- provider_id, content_type, remote_id, local_content_id, name, category_id,- category_name, image_url, container_extension, rating, added_at, remote_updated_at,- is_adult, indexed_at, detail_hydrated_at, stale_state, error_state, sync_fingerprint- )- SELECT- m.provider_id,- 'MOVIE',- CAST(m.stream_id AS TEXT),- m.id,- m.name,- m.category_id,- m.category_name,- m.poster_url,- m.container_extension,- m.rating,- m.added_at,- 0,- m.is_adult,- COALESCE(p.last_synced_at, 0),- CASE WHEN m.cache_state = 'DETAIL_HYDRATED' THEN COALESCE(p.last_synced_at, 0) ELSE 0 END,- 'ACTIVE',- NULL,- m.sync_fingerprint- FROM movies m- JOIN providers p ON p.id = m.provider_id- WHERE p.type = 'XTREAM_CODES'- """.trimIndent()- )- database.execSQL(- """- INSERT OR REPLACE INTO xtream_content_index (- provider_id, content_type, remote_id, local_content_id, name, category_id,- category_name, image_url, container_extension, rating, added_at, remote_updated_at,- is_adult, indexed_at, detail_hydrated_at, stale_state, error_state, sync_fingerprint- )- SELECT- s.provider_id,- 'SERIES',- COALESCE(s.provider_series_id, CAST(s.series_id AS TEXT)),- s.id,- s.name,- s.category_id,- s.category_name,- s.poster_url,- NULL,- s.rating,- 0,- s.last_modified,- s.is_adult,- COALESCE(p.last_synced_at, 0),- CASE WHEN s.cache_state = 'DETAIL_HYDRATED' THEN COALESCE(p.last_synced_at, 0) ELSE 0 END,- 'ACTIVE',- NULL,- s.sync_fingerprint- FROM series s- JOIN providers p ON p.id = s.provider_id- WHERE p.type = 'XTREAM_CODES'- """.trimIndent()- )-- database.execSQL(- """- INSERT OR REPLACE INTO xtream_index_jobs (- provider_id, section, state, total_categories, completed_categories, next_category_index, failed_categories,- indexed_rows, skipped_malformed_rows, deleted_pruned_rows, priority_category_id, priority_requested_at, last_error,- last_attempt_at, last_success_at, updated_at- )- SELECT- p.id,- section.name,- CASE- WHEN section.name = 'LIVE' AND (- COALESCE(NULLIF(sm.last_live_success, 0), NULLIF(sm.last_live_sync, 0), 0) > 0- OR (SELECT COUNT(*) FROM channels c WHERE c.provider_id = p.id) > 0- ) THEN 'SUCCESS'- WHEN section.name = 'MOVIE' AND (- COALESCE(NULLIF(sm.last_movie_success, 0), NULLIF(sm.last_movie_sync, 0), 0) > 0- OR (SELECT COUNT(*) FROM movies m WHERE m.provider_id = p.id) > 0- ) THEN 'SUCCESS'- WHEN section.name = 'SERIES' AND (- COALESCE(NULLIF(sm.last_series_success, 0), NULLIF(sm.last_series_sync, 0), 0) > 0- OR (SELECT COUNT(*) FROM series s WHERE s.provider_id = p.id) > 0- ) THEN 'SUCCESS'- WHEN section.name = 'EPG' AND COALESCE(NULLIF(sm.last_epg_success, 0), NULLIF(sm.last_epg_sync, 0), 0) > 0 THEN 'SUCCESS'- ELSE 'IDLE'- END,- CASE section.name- WHEN 'LIVE' THEN (SELECT COUNT(*) FROM categories cat WHERE cat.provider_id = p.id AND cat.type = 'LIVE')- WHEN 'MOVIE' THEN (SELECT COUNT(*) FROM categories cat WHERE cat.provider_id = p.id AND cat.type = 'MOVIE')- WHEN 'SERIES' THEN (SELECT COUNT(*) FROM categories cat WHERE cat.provider_id = p.id AND cat.type = 'SERIES')- ELSE 0- END,- CASE- WHEN section.name = 'LIVE' AND (SELECT COUNT(*) FROM channels c WHERE c.provider_id = p.id) > 0- THEN (SELECT COUNT(*) FROM categories cat WHERE cat.provider_id = p.id AND cat.type = 'LIVE')- WHEN section.name = 'MOVIE' AND (SELECT COUNT(*) FROM movies m WHERE m.provider_id = p.id) > 0- THEN (SELECT COUNT(*) FROM categories cat WHERE cat.provider_id = p.id AND cat.type = 'MOVIE')- WHEN section.name = 'SERIES' AND (SELECT COUNT(*) FROM series s WHERE s.provider_id = p.id) > 0- THEN (SELECT COUNT(*) FROM categories cat WHERE cat.provider_id = p.id AND cat.type = 'SERIES')- ELSE 0- END,- CASE- WHEN section.name = 'LIVE' AND (SELECT COUNT(*) FROM channels c WHERE c.provider_id = p.id) > 0- THEN (SELECT COUNT(*) FROM categories cat WHERE cat.provider_id = p.id AND cat.type = 'LIVE')- WHEN section.name = 'MOVIE' AND (SELECT COUNT(*) FROM movies m WHERE m.provider_id = p.id) > 0- THEN (SELECT COUNT(*) FROM categories cat WHERE cat.provider_id = p.id AND cat.type = 'MOVIE')- WHEN section.name = 'SERIES' AND (SELECT COUNT(*) FROM series s WHERE s.provider_id = p.id) > 0- THEN (SELECT COUNT(*) FROM categories cat WHERE cat.provider_id = p.id AND cat.type = 'SERIES')- ELSE 0- END,- 0,- CASE section.name- WHEN 'LIVE' THEN (SELECT COUNT(*) FROM channels c WHERE c.provider_id = p.id)- WHEN 'MOVIE' THEN (SELECT COUNT(*) FROM movies m WHERE m.provider_id = p.id)- WHEN 'SERIES' THEN (SELECT COUNT(*) FROM series s WHERE s.provider_id = p.id)- WHEN 'EPG' THEN COALESCE(sm.epg_count, 0)- ELSE 0- END,- 0,- 0,- NULL,- 0,- NULL,- CASE section.name- WHEN 'LIVE' THEN COALESCE(sm.last_live_sync, 0)- WHEN 'MOVIE' THEN COALESCE(NULLIF(sm.last_movie_attempt, 0), sm.last_movie_sync, 0)- WHEN 'SERIES' THEN COALESCE(sm.last_series_sync, 0)- WHEN 'EPG' THEN COALESCE(sm.last_epg_sync, 0)- ELSE 0- END,- CASE section.name- WHEN 'LIVE' THEN COALESCE(NULLIF(sm.last_live_success, 0), sm.last_live_sync, 0)- WHEN 'MOVIE' THEN COALESCE(NULLIF(sm.last_movie_success, 0), sm.last_movie_sync, 0)- WHEN 'SERIES' THEN COALESCE(NULLIF(sm.last_series_success, 0), sm.last_series_sync, 0)- WHEN 'EPG' THEN COALESCE(NULLIF(sm.last_epg_success, 0), sm.last_epg_sync, 0)- ELSE 0- END,- COALESCE(p.last_synced_at, 0)- FROM providers p- CROSS JOIN (- SELECT 'LIVE' AS name- UNION ALL SELECT 'MOVIE'- UNION ALL SELECT 'SERIES'- UNION ALL SELECT 'EPG'- ) section- LEFT JOIN sync_metadata sm ON sm.provider_id = p.id- WHERE p.type = 'XTREAM_CODES'- """.trimIndent()- )-- validateForeignKeys(database, "xtream_content_index", "xtream_index_jobs")- }- }-- val MIGRATION_48_49 = object : Migration(48, 49) {- override fun migrate(database: SupportSQLiteDatabase) {- database.execSQL("ALTER TABLE providers ADD COLUMN http_user_agent TEXT NOT NULL DEFAULT ''")- database.execSQL("ALTER TABLE providers ADD COLUMN http_headers TEXT NOT NULL DEFAULT ''")- }- }-- val MIGRATION_49_50 = object : Migration(49, 50) {- override fun migrate(database: SupportSQLiteDatabase) {- database.execSQL(- """- CREATE TABLE IF NOT EXISTS xtream_live_onboarding_state (- provider_id INTEGER NOT NULL,- provider_type TEXT NOT NULL DEFAULT 'XTREAM_CODES',- content_type TEXT NOT NULL DEFAULT 'LIVE',- phase TEXT NOT NULL DEFAULT 'STARTING',- staged_session_id INTEGER,- import_strategy TEXT,- next_category_index INTEGER NOT NULL DEFAULT 0,- accepted_row_count INTEGER NOT NULL DEFAULT 0,- staged_flush_count INTEGER NOT NULL DEFAULT 0,- last_error TEXT,- created_at INTEGER NOT NULL DEFAULT 0,- updated_at INTEGER NOT NULL DEFAULT 0,- completed_at INTEGER,- PRIMARY KEY(provider_id),- FOREIGN KEY(provider_id) REFERENCES providers(id) ON UPDATE NO ACTION ON DELETE CASCADE- )- """.trimIndent()- )- database.execSQL("CREATE INDEX IF NOT EXISTS index_xtream_live_onboarding_state_provider_id ON xtream_live_onboarding_state(provider_id)")- database.execSQL("CREATE INDEX IF NOT EXISTS index_xtream_live_onboarding_state_phase ON xtream_live_onboarding_state(phase)")- database.execSQL("CREATE INDEX IF NOT EXISTS index_xtream_live_onboarding_state_updated_at ON xtream_live_onboarding_state(updated_at)")- database.execSQL("CREATE INDEX IF NOT EXISTS index_xtream_live_onboarding_state_staged_session_id ON xtream_live_onboarding_state(staged_session_id)")-- validateForeignKeys(database, "xtream_live_onboarding_state")- }- }-- val MIGRATION_50_51 = object : Migration(50, 51) {- override fun migrate(database: SupportSQLiteDatabase) {- database.execSQL("ALTER TABLE xtream_live_onboarding_state ADD COLUMN sync_profile_tier TEXT")- database.execSQL("ALTER TABLE xtream_live_onboarding_state ADD COLUMN sync_profile_batch_size INTEGER NOT NULL DEFAULT 0")- database.execSQL("ALTER TABLE xtream_live_onboarding_state ADD COLUMN sync_profile_strategy TEXT")- database.execSQL("ALTER TABLE xtream_live_onboarding_state ADD COLUMN sync_profile_low_memory INTEGER NOT NULL DEFAULT 0")- database.execSQL("ALTER TABLE xtream_live_onboarding_state ADD COLUMN sync_profile_memory_class_mb INTEGER NOT NULL DEFAULT 0")- database.execSQL("ALTER TABLE xtream_live_onboarding_state ADD COLUMN sync_profile_available_mem_mb INTEGER NOT NULL DEFAULT 0")- validateForeignKeys(database, "xtream_live_onboarding_state")- }- }-- val MIGRATION_51_52 = object : Migration(51, 52) {- override fun migrate(database: SupportSQLiteDatabase) {- database.execSQL("ALTER TABLE providers ADD COLUMN xtream_live_sync_mode TEXT NOT NULL DEFAULT 'AUTO'")- validateForeignKeys(database, "providers")- }- }-- val MIGRATION_55_56 = object : Migration(55, 56) {- override fun migrate(database: SupportSQLiteDatabase) {- database.execSQL(- "ALTER TABLE providers ADD COLUMN stalker_portal_fingerprint TEXT NOT NULL DEFAULT 'BASIC_MAC'"- )- database.execSQL(- "ALTER TABLE providers ADD COLUMN stalker_mag_preset TEXT NOT NULL DEFAULT 'GENERIC_SAFE'"- )- database.execSQL(- "ALTER TABLE providers ADD COLUMN stalker_last_bootstrap_recipe TEXT NOT NULL DEFAULT 'GENERIC_SAFE'"- )- database.execSQL(- "ALTER TABLE providers ADD COLUMN stalker_strict_fingerprint_required INTEGER NOT NULL DEFAULT 0"- )- database.execSQL(- "ALTER TABLE providers ADD COLUMN stalker_recipe_fallback_used INTEGER NOT NULL DEFAULT 0"- )- database.execSQL(- "ALTER TABLE providers ADD COLUMN stalker_recipe_rediscovery_attempts INTEGER NOT NULL DEFAULT 0"- )- validateForeignKeys(database, "providers")- }- }-- val MIGRATION_56_57 = object : Migration(56, 57) {- override fun migrate(database: SupportSQLiteDatabase) {- database.execSQL(- "ALTER TABLE providers ADD COLUMN stalker_endpoint_preference TEXT NOT NULL DEFAULT 'AUTO'"- )- database.execSQL(- "ALTER TABLE providers ADD COLUMN stalker_cookie_mode TEXT NOT NULL DEFAULT 'NONE'"- )- database.execSQL(- "ALTER TABLE providers ADD COLUMN stalker_playback_backend_hint TEXT NOT NULL DEFAULT 'AUTO'"- )- validateForeignKeys(database, "providers")- }- }-- /**- * Migration 57 → 58: add downloads table for tracking in-app download operations.- */- val MIGRATION_57_58 = object : Migration(57, 58) {- override fun migrate(database: SupportSQLiteDatabase) {- database.execSQL(- """- CREATE TABLE IF NOT EXISTS downloads (- id TEXT NOT NULL PRIMARY KEY,- 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 DEFAULT 'PENDING',- bytes_written INTEGER NOT NULL DEFAULT 0,- total_bytes INTEGER,- created_at INTEGER NOT NULL,- completed_at INTEGER,- failure_reason TEXT,- series_id INTEGER,- season_number INTEGER,- episode_number INTEGER- )- """.trimIndent()- )- database.execSQL("CREATE INDEX IF NOT EXISTS index_downloads_status ON downloads(status)")- database.execSQL("CREATE INDEX IF NOT EXISTS index_downloads_provider_id ON downloads(provider_id)")- database.execSQL("CREATE INDEX IF NOT EXISTS index_downloads_content_type_content_id ON downloads(content_type, content_id)")- }- }-- val MIGRATION_58_59 = object : Migration(58, 59) {- override fun migrate(database: SupportSQLiteDatabase) {- database.execSQL("ALTER TABLE downloads ADD COLUMN supports_resume INTEGER NOT NULL DEFAULT 0")- database.execSQL("ALTER TABLE downloads ADD COLUMN retry_count INTEGER NOT NULL DEFAULT 0")- }- }-- val MIGRATION_59_60 = object : Migration(59, 60) {- override fun migrate(database: SupportSQLiteDatabase) {- addColumnIfMissing(database, "downloads", "source_stream_url", "TEXT")- addColumnIfMissing(database, "downloads", "source_stream_id", "INTEGER")- addColumnIfMissing(database, "downloads", "container_extension", "TEXT")- }- }-- val MIGRATION_60_61 = object : Migration(60, 61) {- override fun migrate(database: SupportSQLiteDatabase) {- addColumnIfMissing(- database,- tableName = "providers",- columnName = "stalker_advanced_options_json",- columnDefinition = "TEXT NOT NULL DEFAULT ''"- )- validateForeignKeys(database, "providers")- }- }-- val MIGRATION_61_62 = object : Migration(61, 62) {- override fun migrate(database: SupportSQLiteDatabase) {- addColumnIfMissing(- database,- tableName = "providers",- columnName = "guide_source_policy",- columnDefinition = "TEXT NOT NULL DEFAULT 'AUTO'"- )- addColumnIfMissing(- database,- tableName = "providers",- columnName = "channel_logo_source_policy",- columnDefinition = "TEXT NOT NULL DEFAULT 'SUPPLIER_PREFERRED'"- )- validateForeignKeys(database, "providers")- }- }-- val MIGRATION_62_63 = object : Migration(62, 63) {- override fun migrate(database: SupportSQLiteDatabase) {- addColumnIfMissing(- database,- tableName = "providers",- columnName = "stalker_catalog_mode",- columnDefinition = "TEXT NOT NULL DEFAULT 'ON_DEMAND'"- )- database.execSQL(- """- CREATE TABLE IF NOT EXISTS stalker_index_jobs (- provider_id INTEGER NOT NULL,- section TEXT NOT NULL,- state TEXT NOT NULL DEFAULT 'DISABLED',- total_categories INTEGER NOT NULL DEFAULT 0,- completed_categories INTEGER NOT NULL DEFAULT 0,- next_category_index INTEGER NOT NULL DEFAULT 0,- failed_categories INTEGER NOT NULL DEFAULT 0,- indexed_rows INTEGER NOT NULL DEFAULT 0,- skipped_malformed_rows INTEGER NOT NULL DEFAULT 0,- deleted_pruned_rows INTEGER NOT NULL DEFAULT 0,- last_error TEXT,- last_attempt_at INTEGER NOT NULL DEFAULT 0,- last_success_at INTEGER NOT NULL DEFAULT 0,- updated_at INTEGER NOT NULL DEFAULT 0,- PRIMARY KEY(provider_id, section),- FOREIGN KEY(provider_id) REFERENCES providers(id) ON UPDATE NO ACTION ON DELETE CASCADE- )- """.trimIndent()- )- database.execSQL("CREATE INDEX IF NOT EXISTS index_stalker_index_jobs_provider_id ON stalker_index_jobs(provider_id)")- database.execSQL("CREATE INDEX IF NOT EXISTS index_stalker_index_jobs_state ON stalker_index_jobs(state)")- database.execSQL("CREATE INDEX IF NOT EXISTS index_stalker_index_jobs_updated_at ON stalker_index_jobs(updated_at)")- database.execSQL(- """- INSERT OR REPLACE INTO stalker_index_jobs (- provider_id, section, state, total_categories, completed_categories,- next_category_index, failed_categories, indexed_rows, skipped_malformed_rows,- deleted_pruned_rows, last_error,- last_attempt_at, last_success_at, updated_at- )- SELECT j.provider_id, j.section, 'DISABLED', j.total_categories, j.completed_categories,- j.next_category_index, j.failed_categories, j.indexed_rows, j.skipped_malformed_rows,- j.deleted_pruned_rows, j.last_error,- j.last_attempt_at, j.last_success_at, j.updated_at- FROM xtream_index_jobs j- INNER JOIN providers p ON p.id = j.provider_id- WHERE p.type = 'STALKER_PORTAL' AND j.section IN ('MOVIE', 'SERIES')- """.trimIndent()- )- database.execSQL(- "DELETE FROM xtream_index_jobs WHERE provider_id IN (SELECT id FROM providers WHERE type = 'STALKER_PORTAL')"- )- database.execSQL(- """- CREATE TABLE IF NOT EXISTS stalker_portal_state (- 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 DEFAULT 2,- stress_cooldown_until INTEGER NOT NULL DEFAULT 0,- endpoint_health_json TEXT NOT NULL DEFAULT '{}',- endpoint_failed_until INTEGER NOT NULL DEFAULT 0,- validated_at INTEGER NOT NULL DEFAULT 0,- schema_version INTEGER NOT NULL DEFAULT 1,- 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_stalker_portal_state_provider_id ON stalker_portal_state(provider_id)")- database.execSQL(- """- CREATE TABLE IF NOT EXISTS stalker_remote_identities (- 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- )- """.trimIndent()- )- database.execSQL("CREATE INDEX IF NOT EXISTS index_stalker_remote_identities_provider_id ON stalker_remote_identities(provider_id)")- database.execSQL("CREATE UNIQUE INDEX IF NOT EXISTS index_stalker_remote_identities_provider_id_content_type_surrogate_id ON stalker_remote_identities(provider_id, content_type, surrogate_id)")- database.execSQL("""CREATE TABLE IF NOT EXISTS provider_deletion_cleanup (- id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,- provider_id INTEGER NOT NULL,- action TEXT NOT NULL,- target_id TEXT NOT NULL DEFAULT '',- created_at INTEGER NOT NULL,- attempt_count INTEGER NOT NULL DEFAULT 0,- last_error TEXT- )""")- database.execSQL("CREATE UNIQUE INDEX IF NOT EXISTS index_provider_deletion_cleanup_provider_id_action_target_id ON provider_deletion_cleanup(provider_id, action, target_id)")- validateForeignKeys(database, "providers", "stalker_index_jobs", "stalker_portal_state", "stalker_remote_identities")- }- }-- val MIGRATION_63_64 = object : Migration(63, 64) {- override fun migrate(database: SupportSQLiteDatabase) {- addColumnIfMissing(database, "providers", "stalker_protocol_preference", "TEXT NOT NULL DEFAULT 'AUTO'")- addColumnIfMissing(database, "providers", "stalker_requested_profile_id", "TEXT NOT NULL DEFAULT 'auto'")- addColumnIfMissing(database, "providers", "stalker_learned_profile_id", "TEXT NOT NULL DEFAULT ''")- addColumnIfMissing(database, "providers", "stalker_profile_revision", "INTEGER NOT NULL DEFAULT 0")- addColumnIfMissing(database, "providers", "stalker_profile_verification", "TEXT NOT NULL DEFAULT 'UNVERIFIED'")- addColumnIfMissing(database, "providers", "stalker_protocol_family", "TEXT NOT NULL DEFAULT 'CLASSIC_MAG'")- database.execSQL(- """- UPDATE providers SET stalker_requested_profile_id = CASE stalker_mag_preset- WHEN 'MAG250_LEGACY' THEN 'classic.mag250.legacy'- WHEN 'MAG254_STRICT' THEN 'classic.mag254.strict'- WHEN 'MINISTRA_MODERN' THEN 'classic.mag322.modern'- ELSE 'classic.mag250.generic'- END,- stalker_learned_profile_id = CASE stalker_mag_preset- WHEN 'MAG250_LEGACY' THEN 'classic.mag250.legacy'- WHEN 'MAG254_STRICT' THEN 'classic.mag254.strict'- WHEN 'MINISTRA_MODERN' THEN 'classic.mag322.modern'- ELSE 'classic.mag250.generic'- END,- stalker_profile_revision = 1,- stalker_profile_verification = 'VERIFIED'- WHERE type = 'STALKER_PORTAL'- """.trimIndent()- )- database.execSQL("""CREATE TABLE IF NOT EXISTS plugin_provider_ownership (- 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- )""")- database.execSQL("CREATE UNIQUE INDEX IF NOT EXISTS index_plugin_provider_ownership_provider_id ON plugin_provider_ownership(provider_id)")- validateForeignKeys(database, "providers")- }- }-- val MIGRATION_64_65 = object : Migration(64, 65) {- override fun migrate(database: SupportSQLiteDatabase) {- addColumnIfMissing(- database,- "providers",- "stalker_transport_mode",- "TEXT NOT NULL DEFAULT 'AUTO_STRICT'"- )- addColumnIfMissing(- database,- "providers",- "stalker_transport_origin",- "TEXT NOT NULL DEFAULT ''"- )- addColumnIfMissing(- database,- "providers",- "stalker_tls_spki_sha256",- "TEXT NOT NULL DEFAULT ''"- )- addColumnIfMissing(- database,- "providers",- "stalker_transport_consent_at",- "INTEGER NOT NULL DEFAULT 0"- )- addColumnIfMissing(- database,- "providers",- "stalker_configuration_generation",- "INTEGER NOT NULL DEFAULT 0"- )- addColumnIfMissing(- database,- "providers",- "stalker_discovery_summary",- "TEXT NOT NULL DEFAULT ''"- )- addColumnIfMissing(- database,- "providers",- "stalker_capabilities_json",- "TEXT NOT NULL DEFAULT ''"- )- database.execSQL(- """- CREATE TABLE IF NOT EXISTS stalker_discovery_staging (- discovery_id TEXT NOT NULL PRIMARY KEY,- 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- )- """.trimIndent()- )- database.execSQL(- "CREATE INDEX IF NOT EXISTS index_stalker_discovery_staging_provider_id ON stalker_discovery_staging(provider_id)"- )- database.execSQL(- "CREATE INDEX IF NOT EXISTS index_stalker_discovery_staging_created_at ON stalker_discovery_staging(created_at)"- )- // Existing installs used a global trust-all client. They deliberately migrate to- // strict verification and must consent in the foreground if their portal needs- // HTTP or invalid TLS.- database.execSQL(- """- UPDATE providers- SET stalker_transport_mode = 'AUTO_STRICT',- stalker_transport_origin = '',- stalker_tls_spki_sha256 = '',- stalker_transport_consent_at = 0- WHERE type = 'STALKER_PORTAL'- """.trimIndent()- )- database.execSQL(- """- UPDATE providers- SET status = 'PARTIAL',- is_active = 0- WHERE type = 'STALKER_PORTAL'- AND lower(server_url) LIKE 'http://%'- """.trimIndent()- )- listOf(- imageUrlMigrationSql("movies", "poster_url"),- imageUrlMigrationSql("movies", "backdrop_url"),- imageUrlMigrationSql("series", "poster_url"),- imageUrlMigrationSql("series", "backdrop_url"),- imageUrlMigrationSql("episodes", "cover_url")- ).forEach(database::execSQL)- validateForeignKeys(database, "providers")- }- }-- val MIGRATION_65_66 = object : Migration(65, 66) {- override fun migrate(database: SupportSQLiteDatabase) {- addColumnIfMissing(- database,- "providers",- "catalog_layout",- "TEXT NOT NULL DEFAULT 'SPLIT'"- )- addColumnIfMissing(- database,- "providers",- "catalog_layout_detection_version",- "INTEGER NOT NULL DEFAULT 0"- )- addColumnIfMissing(- database,- "categories",- "provider_order",- "INTEGER NOT NULL DEFAULT 0"- )- addColumnIfMissing(- database,- "category_import_stage",- "provider_order",- "INTEGER NOT NULL DEFAULT 0"- )- addColumnIfMissing(- database,- "series",- "catalog_origin",- "TEXT NOT NULL DEFAULT 'NATIVE'"- )- addColumnIfMissing(- database,- "series",- "episode_playback_template_url",- "TEXT"- )- database.execSQL(- """- CREATE TABLE IF NOT EXISTS vod_category_hydration (- provider_id INTEGER NOT NULL,- category_id INTEGER NOT NULL,- last_loaded_page INTEGER NOT NULL DEFAULT 0,- last_attempted_page INTEGER NOT NULL DEFAULT 0,- last_successful_page INTEGER NOT NULL DEFAULT 0,- total_pages INTEGER NOT NULL DEFAULT 0,- page_size INTEGER NOT NULL DEFAULT 0,- item_count INTEGER NOT NULL DEFAULT 0,- is_complete INTEGER NOT NULL DEFAULT 0,- has_movies INTEGER NOT NULL DEFAULT 0,- has_series INTEGER NOT NULL DEFAULT 0,- last_hydrated_at INTEGER NOT NULL DEFAULT 0,- last_status TEXT NOT NULL DEFAULT 'IDLE',- last_error TEXT,- retry_after_ms INTEGER NOT NULL DEFAULT 0,- failure_count INTEGER NOT NULL DEFAULT 0,- retry_budget_remaining INTEGER NOT NULL DEFAULT 3,- last_page_fingerprint TEXT,- PRIMARY KEY(provider_id, category_id),- FOREIGN KEY(provider_id) REFERENCES providers(id) ON UPDATE NO ACTION ON DELETE CASCADE- )- """.trimIndent()- )- database.execSQL(- "CREATE INDEX IF NOT EXISTS index_vod_category_hydration_provider_id ON vod_category_hydration(provider_id)"- )- database.execSQL(- """- CREATE TABLE IF NOT EXISTS vod_catalog_entries (- provider_id INTEGER NOT NULL,- category_id INTEGER NOT NULL,- raw_item_id TEXT NOT NULL,- item_type TEXT NOT NULL,- target_id INTEGER NOT NULL,- raw_page INTEGER NOT NULL,- raw_index INTEGER NOT NULL,- PRIMARY KEY(provider_id, category_id, raw_item_id),- FOREIGN KEY(provider_id) REFERENCES providers(id) ON UPDATE NO ACTION ON DELETE CASCADE- )- """.trimIndent()- )- database.execSQL("CREATE INDEX IF NOT EXISTS index_vod_catalog_entries_provider_id ON vod_catalog_entries(provider_id)")- database.execSQL("CREATE INDEX IF NOT EXISTS index_vod_catalog_entries_provider_id_category_id_raw_page_raw_index ON vod_catalog_entries(provider_id, category_id, raw_page, raw_index)")- database.execSQL("CREATE INDEX IF NOT EXISTS index_vod_catalog_entries_provider_id_item_type_target_id ON vod_catalog_entries(provider_id, item_type, target_id)")- addColumnIfMissing(- database,- tableName = "recording_runs",- columnName = "exact_alarm_armed",- columnDefinition = "INTEGER NOT NULL DEFAULT 1"- )- addColumnIfMissing(- database,- tableName = "program_reminders",- columnName = "exact_alarm_armed",- columnDefinition = "INTEGER NOT NULL DEFAULT 1"- )- validateForeignKeys(database, "providers", "vod_category_hydration", "vod_catalog_entries")- }- }-- /** Migration 66 -> 67: retain candidate provider edits until they are atomically promoted. */- val MIGRATION_66_67 = object : Migration(66, 67) {- override fun migrate(database: SupportSQLiteDatabase) {- database.execSQL(- """- CREATE TABLE IF NOT EXISTS provider_config_revisions (- provider_id INTEGER NOT NULL,- revision INTEGER NOT NULL,- config_json TEXT NOT NULL,- state TEXT NOT NULL,- attempt_count INTEGER NOT NULL DEFAULT 0,- 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 DELETE CASCADE- )- """.trimIndent()- )- database.execSQL("CREATE INDEX IF NOT EXISTS index_provider_config_revisions_provider_id_state ON provider_config_revisions(provider_id, state)")- validateForeignKeys(database, "provider_config_revisions")- }- }-- /** Migration 67 -> 68: retain cross-store backup restore progress for safe retry. */- val MIGRATION_67_68 = object : Migration(67, 68) {- override fun migrate(database: SupportSQLiteDatabase) {- database.execSQL(- """- CREATE TABLE IF NOT EXISTS backup_restore_checkpoints (- restore_key TEXT NOT NULL,- room_complete INTEGER NOT NULL DEFAULT 0,- preferences_complete INTEGER NOT NULL DEFAULT 0,- presets_complete INTEGER NOT NULL DEFAULT 0,- schedules_complete INTEGER NOT NULL DEFAULT 0,- 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)- )- """.trimIndent()- )- }- }-- /** Migration 68 -> 69: make active download ownership durable and reclaimable. */- val MIGRATION_68_69 = object : Migration(68, 69) {- override fun migrate(database: SupportSQLiteDatabase) {- addColumnIfMissing(database, "downloads", "owner_id", "TEXT")- addColumnIfMissing(database, "downloads", "owner_epoch", "INTEGER NOT NULL DEFAULT 0")- addColumnIfMissing(database, "downloads", "heartbeat_at", "INTEGER")- }- }-- /** Migration 69 -> 70: make reminder delivery outcomes durable and recoverable. */- val MIGRATION_69_70 = object : Migration(69, 70) {- override fun migrate(database: SupportSQLiteDatabase) {- addColumnIfMissing(database, "program_reminders", "delivery_state", "TEXT NOT NULL DEFAULT 'PENDING'")- addColumnIfMissing(database, "program_reminders", "delivery_attempt_token", "TEXT")- addColumnIfMissing(database, "program_reminders", "delivery_attempted_at", "INTEGER")- addColumnIfMissing(database, "program_reminders", "delivery_attempt_count", "INTEGER NOT NULL DEFAULT 0")- addColumnIfMissing(database, "program_reminders", "delivery_failure_reason", "TEXT")- database.execSQL(- """- UPDATE program_reminders- SET delivery_state = CASE- WHEN notified_at IS NOT NULL THEN 'DELIVERED'- WHEN is_dismissed = 1 THEN 'DISMISSED'- ELSE 'PENDING'- END- """.trimIndent()- )- }- }-- /** Migration 70 -> 71: persist the provider workflow generation, lease, and phase ledger. */- val MIGRATION_70_71 = object : Migration(70, 71) {- override fun migrate(database: SupportSQLiteDatabase) {- database.execSQL(- """- CREATE TABLE IF NOT EXISTS provider_workflows (- 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- )- """.trimIndent()- )- database.execSQL("CREATE INDEX IF NOT EXISTS index_provider_workflows_state ON provider_workflows(state)")- database.execSQL("CREATE INDEX IF NOT EXISTS index_provider_workflows_updated_at ON provider_workflows(updated_at)")- database.execSQL("CREATE INDEX IF NOT EXISTS index_provider_workflows_lease_expires_at ON provider_workflows(lease_expires_at)")- database.execSQL(- """- CREATE TABLE IF NOT EXISTS provider_workflow_phases (- 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- )- """.trimIndent()- )- database.execSQL("CREATE INDEX IF NOT EXISTS index_provider_workflow_phases_provider_id ON provider_workflow_phases(provider_id)")- database.execSQL("CREATE INDEX IF NOT EXISTS index_provider_workflow_phases_state ON provider_workflow_phases(state)")- database.execSQL("CREATE INDEX IF NOT EXISTS index_provider_workflow_phases_updated_at ON provider_workflow_phases(updated_at)")- validateForeignKeys(database, "provider_workflows", "provider_workflow_phases")- }- }-- /** Migration 71 -> 72: make offset-free XMLTV timestamp handling explicit per source. */- val MIGRATION_71_72 = object : Migration(71, 72) {- override fun migrate(database: SupportSQLiteDatabase) {- addColumnIfMissing(database, "epg_sources", "timezone_policy", "TEXT NOT NULL DEFAULT 'REQUIRE_OFFSET'")- addColumnIfMissing(database, "epg_sources", "timezone_id", "TEXT")- }- }-- /** 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)- }- }-- /** Migration 74 -> 75: retain Stalker server pagination totals for resumable catalogs. */- val MIGRATION_74_75 = object : Migration(74, 75) {- override fun migrate(database: SupportSQLiteDatabase) {- listOf(- "movie_category_hydration",- "series_category_hydration",- "vod_category_hydration"- ).forEach { tableName ->- addColumnIfMissing(database, tableName, "advertised_total_items", "INTEGER")- addColumnIfMissing(database, tableName, "advertised_total_pages", "INTEGER")- }- }- }-- 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 = CASE- WHEN instr($column, 'streamvault_provider_id=') > 0 THEN $column- ELSE $column || CASE WHEN instr($column, '?') = 0 THEN '?streamvault_provider_id=' ELSE '&streamvault_provider_id=' END || provider_id- END- WHERE $column IS NOT NULL- AND provider_id IN (SELECT id FROM providers WHERE type = 'JELLYFIN')- """.trimIndent()-- val MIGRATION_52_53 = object : Migration(52, 53) {- override fun migrate(database: SupportSQLiteDatabase) {- addStalkerHardeningColumns(database, "movie_category_hydration")- addStalkerHardeningColumns(database, "series_category_hydration")- validateForeignKeys(database, "movie_category_hydration")- validateForeignKeys(database, "series_category_hydration")- }- }-- val MIGRATION_53_54 = object : Migration(53, 54) {- override fun migrate(database: SupportSQLiteDatabase) {- database.execSQL("ALTER TABLE providers ADD COLUMN stalker_serial_number TEXT NOT NULL DEFAULT ''")- database.execSQL("ALTER TABLE providers ADD COLUMN stalker_device_id TEXT NOT NULL DEFAULT ''")- database.execSQL("ALTER TABLE providers ADD COLUMN stalker_device_id2 TEXT NOT NULL DEFAULT ''")- database.execSQL("ALTER TABLE providers ADD COLUMN stalker_signature TEXT NOT NULL DEFAULT ''")- validateForeignKeys(database, "providers")- }- }-- val MIGRATION_54_55 = object : Migration(54, 55) {- override fun migrate(database: SupportSQLiteDatabase) {- database.execSQL("ALTER TABLE providers ADD COLUMN stalker_auth_mode TEXT NOT NULL DEFAULT 'AUTO'")- database.execSQL("ALTER TABLE providers ADD COLUMN stalker_portal_profile TEXT NOT NULL DEFAULT 'MAG_BASIC'")- database.execSQL("ALTER TABLE providers ADD COLUMN stalker_last_playback_mode TEXT")- database.execSQL("ALTER TABLE providers ADD COLUMN stalker_credentials_required INTEGER NOT NULL DEFAULT 0")- database.execSQL("ALTER TABLE providers ADD COLUMN stalker_mac_required INTEGER NOT NULL DEFAULT 1")- database.execSQL("ALTER TABLE providers ADD COLUMN stalker_uses_temp_links INTEGER NOT NULL DEFAULT 0")- database.execSQL("ALTER TABLE providers ADD COLUMN stalker_module_restricted INTEGER NOT NULL DEFAULT 0")- validateForeignKeys(database, "providers")- }- }-- private fun addStalkerHardeningColumns(database: SupportSQLiteDatabase, tableName: String) {- database.execSQL("ALTER TABLE $tableName ADD COLUMN last_attempted_page INTEGER NOT NULL DEFAULT 0")- database.execSQL("ALTER TABLE $tableName ADD COLUMN last_successful_page INTEGER NOT NULL DEFAULT 0")- database.execSQL("ALTER TABLE $tableName ADD COLUMN retry_after_ms INTEGER NOT NULL DEFAULT 0")- database.execSQL("ALTER TABLE $tableName ADD COLUMN failure_count INTEGER NOT NULL DEFAULT 0")- database.execSQL("ALTER TABLE $tableName ADD COLUMN retry_budget_remaining INTEGER NOT NULL DEFAULT 3")- database.execSQL("ALTER TABLE $tableName ADD COLUMN last_page_fingerprint TEXT")- }-- private fun addColumnIfMissing(- database: SupportSQLiteDatabase,- tableName: String,- columnName: String,- columnDefinition: String- ) {- if (tableHasColumn(database, tableName, columnName)) {- return- }- 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,- columnName: String- ): Boolean {- database.query("PRAGMA table_info($tableName)").use { cursor ->- val nameIndex = cursor.getColumnIndex("name")- while (cursor.moveToNext()) {- if (nameIndex >= 0 && cursor.getString(nameIndex) == columnName) {- return true- }- }- }- return false- }+ val MIGRATION_1_2 = LegacyMigrationsV1To24.MIGRATION_1_2+ val MIGRATION_2_3 = LegacyMigrationsV1To24.MIGRATION_2_3+ val MIGRATION_3_4 = LegacyMigrationsV1To24.MIGRATION_3_4+ val MIGRATION_4_5 = LegacyMigrationsV1To24.MIGRATION_4_5+ val MIGRATION_5_6 = LegacyMigrationsV1To24.MIGRATION_5_6+ val MIGRATION_6_7 = LegacyMigrationsV1To24.MIGRATION_6_7+ val MIGRATION_7_8 = LegacyMigrationsV1To24.MIGRATION_7_8+ val MIGRATION_8_9 = LegacyMigrationsV1To24.MIGRATION_8_9+ val MIGRATION_9_10 = LegacyMigrationsV1To24.MIGRATION_9_10+ val MIGRATION_10_11 = LegacyMigrationsV1To24.MIGRATION_10_11+ val MIGRATION_11_12 = LegacyMigrationsV1To24.MIGRATION_11_12+ val MIGRATION_12_13 = LegacyMigrationsV1To24.MIGRATION_12_13+ val MIGRATION_13_14 = LegacyMigrationsV1To24.MIGRATION_13_14+ val MIGRATION_14_15 = LegacyMigrationsV1To24.MIGRATION_14_15+ val MIGRATION_15_16 = LegacyMigrationsV1To24.MIGRATION_15_16+ val MIGRATION_16_17 = LegacyMigrationsV1To24.MIGRATION_16_17+ val MIGRATION_17_18 = LegacyMigrationsV1To24.MIGRATION_17_18+ val MIGRATION_18_19 = LegacyMigrationsV1To24.MIGRATION_18_19+ val MIGRATION_19_20 = LegacyMigrationsV1To24.MIGRATION_19_20+ val MIGRATION_20_21 = LegacyMigrationsV1To24.MIGRATION_20_21+ val MIGRATION_21_22 = LegacyMigrationsV1To24.MIGRATION_21_22+ val MIGRATION_22_23 = LegacyMigrationsV1To24.MIGRATION_22_23+ val MIGRATION_23_24 = LegacyMigrationsV1To24.MIGRATION_23_24+ val MIGRATION_24_25 = LegacyMigrationsV24To49.MIGRATION_24_25+ val MIGRATION_25_26 = LegacyMigrationsV24To49.MIGRATION_25_26+ val MIGRATION_26_27 = LegacyMigrationsV24To49.MIGRATION_26_27+ val MIGRATION_27_28 = LegacyMigrationsV24To49.MIGRATION_27_28+ val MIGRATION_28_29 = LegacyMigrationsV24To49.MIGRATION_28_29+ val MIGRATION_29_30 = LegacyMigrationsV24To49.MIGRATION_29_30+ val MIGRATION_30_31 = LegacyMigrationsV24To49.MIGRATION_30_31+ val MIGRATION_31_32 = LegacyMigrationsV24To49.MIGRATION_31_32+ val MIGRATION_32_33 = LegacyMigrationsV24To49.MIGRATION_32_33+ val MIGRATION_33_34 = LegacyMigrationsV24To49.MIGRATION_33_34+ val MIGRATION_34_35 = LegacyMigrationsV24To49.MIGRATION_34_35+ val MIGRATION_35_36 = LegacyMigrationsV24To49.MIGRATION_35_36+ val MIGRATION_36_37 = LegacyMigrationsV24To49.MIGRATION_36_37+ val MIGRATION_37_38 = LegacyMigrationsV24To49.MIGRATION_37_38+ val MIGRATION_38_39 = LegacyMigrationsV24To49.MIGRATION_38_39+ val MIGRATION_39_40 = LegacyMigrationsV24To49.MIGRATION_39_40+ val MIGRATION_40_41 = LegacyMigrationsV24To49.MIGRATION_40_41+ val MIGRATION_41_42 = LegacyMigrationsV24To49.MIGRATION_41_42+ val MIGRATION_42_43 = LegacyMigrationsV24To49.MIGRATION_42_43+ val MIGRATION_43_44 = LegacyMigrationsV24To49.MIGRATION_43_44+ val MIGRATION_44_45 = LegacyMigrationsV24To49.MIGRATION_44_45+ val MIGRATION_45_46 = LegacyMigrationsV24To49.MIGRATION_45_46+ val MIGRATION_46_47 = LegacyMigrationsV24To49.MIGRATION_46_47+ val MIGRATION_47_48 = LegacyMigrationsV24To49.MIGRATION_47_48+ val MIGRATION_48_49 = LegacyMigrationsV24To49.MIGRATION_48_49+ val MIGRATION_49_50 = FeatureMigrationsV49To75.MIGRATION_49_50+ val MIGRATION_50_51 = FeatureMigrationsV49To75.MIGRATION_50_51+ val MIGRATION_51_52 = FeatureMigrationsV49To75.MIGRATION_51_52+ val MIGRATION_52_53 = FeatureMigrationsV49To75.MIGRATION_52_53+ val MIGRATION_53_54 = FeatureMigrationsV49To75.MIGRATION_53_54+ val MIGRATION_54_55 = FeatureMigrationsV49To75.MIGRATION_54_55+ val MIGRATION_55_56 = FeatureMigrationsV49To75.MIGRATION_55_56+ val MIGRATION_56_57 = FeatureMigrationsV49To75.MIGRATION_56_57+ val MIGRATION_57_58 = FeatureMigrationsV49To75.MIGRATION_57_58+ val MIGRATION_58_59 = FeatureMigrationsV49To75.MIGRATION_58_59+ val MIGRATION_59_60 = FeatureMigrationsV49To75.MIGRATION_59_60+ val MIGRATION_60_61 = FeatureMigrationsV49To75.MIGRATION_60_61+ val MIGRATION_61_62 = FeatureMigrationsV49To75.MIGRATION_61_62+ val MIGRATION_62_63 = FeatureMigrationsV49To75.MIGRATION_62_63+ val MIGRATION_63_64 = FeatureMigrationsV49To75.MIGRATION_63_64+ val MIGRATION_64_65 = FeatureMigrationsV49To75.MIGRATION_64_65+ val MIGRATION_65_66 = FeatureMigrationsV49To75.MIGRATION_65_66+ val MIGRATION_66_67 = FeatureMigrationsV49To75.MIGRATION_66_67+ val MIGRATION_67_68 = FeatureMigrationsV49To75.MIGRATION_67_68+ val MIGRATION_68_69 = FeatureMigrationsV49To75.MIGRATION_68_69+ val MIGRATION_69_70 = FeatureMigrationsV49To75.MIGRATION_69_70+ val MIGRATION_70_71 = FeatureMigrationsV49To75.MIGRATION_70_71+ val MIGRATION_71_72 = FeatureMigrationsV49To75.MIGRATION_71_72+ val MIGRATION_72_73 = FeatureMigrationsV49To75.MIGRATION_72_73+ val MIGRATION_73_74 = FeatureMigrationsV49To75.MIGRATION_73_74+ val MIGRATION_74_75 = FeatureMigrationsV49To75.MIGRATION_74_75}}diff --git a/data/src/main/java/com/streamvault/data/local/StreamVaultDatabaseMigrationRegistry.kt b/data/src/main/java/com/streamvault/data/local/StreamVaultDatabaseMigrationRegistry.ktindex e3b18f48..b1da6e5d 100644--- a/data/src/main/java/com/streamvault/data/local/StreamVaultDatabaseMigrationRegistry.kt+++ b/data/src/main/java/com/streamvault/data/local/StreamVaultDatabaseMigrationRegistry.kt@@ -3,98 +3,15 @@ package com.streamvault.data.localimport androidx.room.migration.Migration/**- * The single migration topology for the production database.- *- * Bodies remain close to the schema compatibility code in [StreamVaultDatabase], while this- * registry is version-grouped and is the only list consumed by the database builder. The- * contiguous-chain check fails at startup/build time if a migration is forgotten.+ * The single migration topology consumed by production. Definitions are grouped into auditable+ * version-era files; this registry verifies that no adjacent release hop is missing or duplicated.*/object StreamVaultDatabaseMigrationRegistry {const val CURRENT_VERSION = STREAM_VAULT_DATABASE_VERSION- val v1To24: List<Migration> = listOf(- StreamVaultDatabase.MIGRATION_1_2,- StreamVaultDatabase.MIGRATION_2_3,- StreamVaultDatabase.MIGRATION_3_4,- StreamVaultDatabase.MIGRATION_4_5,- StreamVaultDatabase.MIGRATION_5_6,- StreamVaultDatabase.MIGRATION_6_7,- StreamVaultDatabase.MIGRATION_7_8,- StreamVaultDatabase.MIGRATION_8_9,- StreamVaultDatabase.MIGRATION_9_10,- StreamVaultDatabase.MIGRATION_10_11,- StreamVaultDatabase.MIGRATION_11_12,- StreamVaultDatabase.MIGRATION_12_13,- StreamVaultDatabase.MIGRATION_13_14,- StreamVaultDatabase.MIGRATION_14_15,- StreamVaultDatabase.MIGRATION_15_16,- StreamVaultDatabase.MIGRATION_16_17,- StreamVaultDatabase.MIGRATION_17_18,- StreamVaultDatabase.MIGRATION_18_19,- StreamVaultDatabase.MIGRATION_19_20,- StreamVaultDatabase.MIGRATION_20_21,- StreamVaultDatabase.MIGRATION_21_22,- StreamVaultDatabase.MIGRATION_22_23,- StreamVaultDatabase.MIGRATION_23_24- )-- val v24To49: List<Migration> = listOf(- StreamVaultDatabase.MIGRATION_24_25,- StreamVaultDatabase.MIGRATION_25_26,- StreamVaultDatabase.MIGRATION_26_27,- StreamVaultDatabase.MIGRATION_27_28,- StreamVaultDatabase.MIGRATION_28_29,- StreamVaultDatabase.MIGRATION_29_30,- StreamVaultDatabase.MIGRATION_30_31,- StreamVaultDatabase.MIGRATION_31_32,- StreamVaultDatabase.MIGRATION_32_33,- StreamVaultDatabase.MIGRATION_33_34,- StreamVaultDatabase.MIGRATION_34_35,- StreamVaultDatabase.MIGRATION_35_36,- StreamVaultDatabase.MIGRATION_36_37,- StreamVaultDatabase.MIGRATION_37_38,- StreamVaultDatabase.MIGRATION_38_39,- StreamVaultDatabase.MIGRATION_39_40,- StreamVaultDatabase.MIGRATION_40_41,- StreamVaultDatabase.MIGRATION_41_42,- StreamVaultDatabase.MIGRATION_42_43,- StreamVaultDatabase.MIGRATION_43_44,- StreamVaultDatabase.MIGRATION_44_45,- StreamVaultDatabase.MIGRATION_45_46,- StreamVaultDatabase.MIGRATION_46_47,- StreamVaultDatabase.MIGRATION_47_48,- StreamVaultDatabase.MIGRATION_48_49- )-- val v49To75: List<Migration> = listOf(- StreamVaultDatabase.MIGRATION_49_50,- StreamVaultDatabase.MIGRATION_50_51,- StreamVaultDatabase.MIGRATION_51_52,- StreamVaultDatabase.MIGRATION_52_53,- StreamVaultDatabase.MIGRATION_53_54,- StreamVaultDatabase.MIGRATION_54_55,- StreamVaultDatabase.MIGRATION_55_56,- StreamVaultDatabase.MIGRATION_56_57,- StreamVaultDatabase.MIGRATION_57_58,- StreamVaultDatabase.MIGRATION_58_59,- StreamVaultDatabase.MIGRATION_59_60,- StreamVaultDatabase.MIGRATION_60_61,- StreamVaultDatabase.MIGRATION_61_62,- StreamVaultDatabase.MIGRATION_62_63,- StreamVaultDatabase.MIGRATION_63_64,- StreamVaultDatabase.MIGRATION_64_65,- StreamVaultDatabase.MIGRATION_65_66,- StreamVaultDatabase.MIGRATION_66_67,- StreamVaultDatabase.MIGRATION_67_68,- StreamVaultDatabase.MIGRATION_68_69,- StreamVaultDatabase.MIGRATION_69_70,- StreamVaultDatabase.MIGRATION_70_71,- StreamVaultDatabase.MIGRATION_71_72,- StreamVaultDatabase.MIGRATION_72_73,- StreamVaultDatabase.MIGRATION_73_74,- StreamVaultDatabase.MIGRATION_74_75- )-+ val v1To24: List<Migration> = LegacyMigrationsV1To24.all+ val v24To49: List<Migration> = LegacyMigrationsV24To49.all+ val v49To75: List<Migration> = FeatureMigrationsV49To75.allval all: List<Migration> = (v1To24 + v24To49 + v49To75).also(::validate)private fun validate(migrations: List<Migration>) {@@ -108,5 +25,10 @@ object StreamVaultDatabaseMigrationRegistry {require(migrations.all { it.endVersion == it.startVersion + 1 }) {"Room migration registry must contain adjacent migrations only"}+ require(migrations.zipWithNext().all { (current, next) ->+ current.endVersion == next.startVersion+ }) {+ "Room migration registry is not ordered as one contiguous chain"+ }}}diff --git a/data/src/main/java/com/streamvault/data/manager/DownloadManagerImpl.kt b/data/src/main/java/com/streamvault/data/manager/DownloadManagerImpl.ktindex 59e7d45c..facca728 100644--- a/data/src/main/java/com/streamvault/data/manager/DownloadManagerImpl.kt+++ b/data/src/main/java/com/streamvault/data/manager/DownloadManagerImpl.kt@@ -622,7 +622,7 @@ class DownloadManagerImpl @Inject constructor(private suspend fun resolveFreshDownloadStream(entity: DownloadEntity): ResolvedStreamUrl? {val logicalUrl = entity.sourceStreamUrl?.takeIf { it.isNotBlank() } ?: entity.streamUrlreturn runSuspendCatching {- xtreamStreamUrlResolver.resolveWithMetadata(+ xtreamStreamUrlResolver.resolveAndCommitMetadata(url = logicalUrl,fallbackProviderId = entity.providerId,fallbackStreamId = entity.sourceStreamId ?: entity.contentId,diff --git a/data/src/main/java/com/streamvault/data/manager/recording/RecordingSourceResolver.kt b/data/src/main/java/com/streamvault/data/manager/recording/RecordingSourceResolver.ktindex c40418c3..152f4e72 100644--- a/data/src/main/java/com/streamvault/data/manager/recording/RecordingSourceResolver.kt+++ b/data/src/main/java/com/streamvault/data/manager/recording/RecordingSourceResolver.kt@@ -37,7 +37,7 @@ class RecordingSourceResolver @Inject constructor(channelId: Long,logicalUrl: String): ResolvedRecordingSource {- val resolved = xtreamStreamUrlResolver.resolveWithMetadata(+ val resolved = xtreamStreamUrlResolver.resolveAndCommitMetadata(url = logicalUrl,fallbackProviderId = providerId,fallbackStreamId = channelId,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 1ba03a87..aa4582f7 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@@ -7,6 +7,7 @@ import com.streamvault.domain.model.Categoryimport com.streamvault.domain.model.CatalogLayoutimport com.streamvault.domain.model.Channelimport com.streamvault.domain.model.ContentType+import com.streamvault.domain.util.KeyedMutexRegistryimport com.streamvault.domain.model.Episodeimport com.streamvault.domain.model.Movieimport com.streamvault.domain.model.PlaybackTransportMode@@ -45,8 +46,6 @@ import java.security.MessageDigestimport java.util.Base64import java.util.Localeimport java.util.concurrent.ConcurrentHashMap-import kotlinx.coroutines.sync.Mutex-import kotlinx.coroutines.sync.withLockdata class StalkerPlaybackInfo(val url: String,@@ -140,14 +139,13 @@ internal companion object {const val CATALOG_LAYOUT_DETECTION_VERSION = 1private val sharedAuthCache = ConcurrentHashMap<String, CachedAuth>()private val sharedAuthFailureCache = ConcurrentHashMap<String, CachedAuthFailure>()- private val sharedAuthMutexes = ConcurrentHashMap<String, Mutex>()+ private val sharedAuthMutexes = KeyedMutexRegistry<String>()private val resolvedStreamUrlCache = ConcurrentHashMap<String, CachedResolvedUrl>()private val missingVodClassificationLogged = ConcurrentHashMap.newKeySet<Long>()fun clearSharedAuthCacheForTests() {sharedAuthCache.clear()sharedAuthFailureCache.clear()- sharedAuthMutexes.clear()}fun clearResolvedStreamUrlCacheForTests() {@@ -160,7 +158,6 @@ internal companion object {val authPrefix = "provider:$providerId|"sharedAuthCache.keys.filter { it.startsWith(authPrefix) }.forEach(sharedAuthCache::remove)sharedAuthFailureCache.keys.filter { it.startsWith(authPrefix) }.forEach(sharedAuthFailureCache::remove)- sharedAuthMutexes.keys.filter { it.startsWith(authPrefix) }.forEach(sharedAuthMutexes::remove)resolvedStreamUrlCache.keys.filter { it.startsWith("$providerId|") }.forEach(resolvedStreamUrlCache::remove)@@ -213,7 +210,6 @@ internal companion object {// Authentication lock identity must remain stable for the provider lifetime. Evicting a// configuration-scoped lock while an older provider instance still holds it permits a second// mutex to be created and defeats same-provider authentication serialization.- private val authMutex = sharedAuthMutexes.computeIfAbsent(authMutexKey()) { Mutex() }private var sessionCache: StalkerSession? = nullprivate var accountProfileCache: StalkerProviderProfile? = nullprivate var authFailureCache: CachedAuthFailure? = null@@ -221,7 +217,7 @@ internal companion object {private val remoteIdentityCache = ConcurrentHashMap<Pair<ContentType, String>, Long>()suspend fun invalidateAuthentication() {- authMutex.withLock {+ sharedAuthMutexes.withLock(authMutexKey()) {sessionCache = nullaccountProfileCache = nullauthFailureCache = null@@ -1122,14 +1118,6 @@ is Result.Success -> {)) {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,@@ -1139,7 +1127,17 @@ is Result.Success -> {playbackTransportPolicy = info.transportPolicy,allowInvalidSsl = info.allowInvalidSsl,proxyHost = info.proxyHost,- proxyPort = info.proxyPort+ proxyPort = info.proxyPort,+ observations = listOf(+ com.streamvault.domain.provider.StalkerPlaybackObservation(+ providerId = providerId,+ configurationGeneration = configurationGeneration,+ playbackMode = info.playbackMode.name,+ endpointPreference = info.endpointPreference,+ cookieMode = info.cookieMode,+ backendHint = info.backendHint+ )+ )))}@@ -1391,7 +1389,7 @@ is Result.Success -> {}private suspend fun ensureAuthenticated(): Result<Pair<StalkerSession, StalkerProviderProfile>> =- authMutex.withLock {+ sharedAuthMutexes.withLock(authMutexKey()) {val cachedSession = sessionCacheval cachedProfile = accountProfileCacheif (cachedSession != null && cachedProfile != null &&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 575a621a..e4efd70b 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@@ -6,12 +6,10 @@ import com.streamvault.data.local.dao.StalkerRemoteIdentityDaoimport com.streamvault.data.local.dao.CategoryDaoimport com.streamvault.data.local.entity.StalkerRemoteIdentityEntityimport com.streamvault.domain.model.ContentType+import com.streamvault.domain.util.KeyedMutexRegistryimport java.util.Locale-import java.util.concurrent.ConcurrentHashMapimport javax.inject.Injectimport javax.inject.Singleton-import kotlinx.coroutines.sync.Mutex-import kotlinx.coroutines.sync.withLock/** Collision-safe, persistent translation between portal IDs and local Long IDs. */@Singleton@@ -33,7 +31,7 @@ class StalkerRemoteIdentityResolver private constructor(transactionRunner: DatabaseTransactionRunner) : this(dao, transactionRunner, null, Unit)- private val locks = ConcurrentHashMap<String, Mutex>()+ private val locks = KeyedMutexRegistry<String>()suspend fun resolveAll(providerId: Long,@@ -43,7 +41,7 @@ class StalkerRemoteIdentityResolver private constructor(val normalizedIds = rawIds.map(String::trim).filter(String::isNotEmpty).distinct().sorted()if (normalizedIds.isEmpty()) return emptyMap()val key = "$providerId/${contentType.name}"- return locks.computeIfAbsent(key) { Mutex() }.withLock {+ return locks.withLock(key) {transactionRunner.inTransaction {normalizedIds.associateWith { rawId -> resolveLocked(providerId, contentType, rawId) }}@@ -72,7 +70,7 @@ class StalkerRemoteIdentityResolver private constructor(rawId to existingByName[name.lowercase(Locale.ROOT)]?.categoryId}val key = "$providerId/${contentType.name}"- return locks.computeIfAbsent(key) { Mutex() }.withLock {+ return locks.withLock(key) {transactionRunner.inTransaction {normalized.associate { (rawId, _) ->rawId to resolveLocked(providerId, contentType, rawId, preferred[rawId])diff --git a/data/src/main/java/com/streamvault/data/remote/xtream/PlaybackObservationCoordinator.kt b/data/src/main/java/com/streamvault/data/remote/xtream/PlaybackObservationCoordinator.ktnew file mode 100644index 00000000..b582a878--- /dev/null+++ b/data/src/main/java/com/streamvault/data/remote/xtream/PlaybackObservationCoordinator.kt@@ -0,0 +1,33 @@+package com.streamvault.data.remote.xtream++import com.streamvault.data.remote.stalker.StalkerPortalStateStore+import com.streamvault.domain.provider.PlaybackObservation+import com.streamvault.domain.provider.StalkerPlaybackObservation+import javax.inject.Inject+import javax.inject.Singleton++/** Commit boundary used by playback resolution; implementations may persist or audit observations. */+fun interface PlaybackObservationSink {+ suspend fun persist(observations: List<PlaybackObservation>)+}++/** Persists resolver observations behind generation-aware compare-and-set storage. */+@Singleton+class PlaybackObservationCoordinator @Inject constructor(+ private val stalkerStateStore: StalkerPortalStateStore+) : PlaybackObservationSink {+ override suspend fun persist(observations: List<PlaybackObservation>) {+ observations.forEach { observation ->+ when (observation) {+ is StalkerPlaybackObservation -> stalkerStateStore.recordPlayback(+ providerId = observation.providerId,+ playbackMode = observation.playbackMode,+ endpointPreference = observation.endpointPreference,+ cookieMode = observation.cookieMode,+ backendHint = observation.backendHint,+ configurationGeneration = observation.configurationGeneration+ )+ }+ }+ }+}diff --git a/data/src/main/java/com/streamvault/data/remote/xtream/PlaybackResolutionCoordinator.kt b/data/src/main/java/com/streamvault/data/remote/xtream/PlaybackResolverRegistry.ktsimilarity index 96%rename from data/src/main/java/com/streamvault/data/remote/xtream/PlaybackResolutionCoordinator.ktrename to data/src/main/java/com/streamvault/data/remote/xtream/PlaybackResolverRegistry.ktindex 6cfd63f6..9c51d465 100644--- a/data/src/main/java/com/streamvault/data/remote/xtream/PlaybackResolutionCoordinator.kt+++ b/data/src/main/java/com/streamvault/data/remote/xtream/PlaybackResolverRegistry.kt@@ -10,7 +10,7 @@ import com.streamvault.domain.provider.PlaybackRequestimport com.streamvault.domain.provider.ProviderContentReference/** Resolves a typed provider playback capability without constructing provider sessions itself. */-internal class PlaybackResolutionCoordinator(+class PlaybackResolverRegistry(private val providerCapabilities: ProviderCapabilityResolver) {suspend fun resolve(@@ -53,7 +53,8 @@ internal class PlaybackResolutionCoordinator(playbackTransportPolicy = resolved.playbackTransportPolicy,allowInvalidSsl = resolved.allowInvalidSsl,proxyHost = resolved.proxyHost,- proxyPort = resolved.proxyPort+ proxyPort = resolved.proxyPort,+ observations = resolved.observations)}is Result.Error -> {diff --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 7b24e009..faea8c73 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@@ -17,15 +17,17 @@ data class ResolvedStreamUrl(val playbackTransportPolicy: PlaybackTransportPolicy? = null,val allowInvalidSsl: Boolean = false,val proxyHost: String = "",- val proxyPort: Int? = null+ val proxyPort: Int? = null,+ val observations: List<com.streamvault.domain.provider.PlaybackObservation> = emptyList())/** Provider-neutral playback entry point. Provider selection is owned by the capability registry. */@Singleton-class XtreamStreamUrlResolver @Inject constructor(- providerCapabilities: com.streamvault.data.provider.ProviderCapabilityResolver+class ProviderPlaybackResolver @Inject constructor(+ providerCapabilities: com.streamvault.data.provider.ProviderCapabilityResolver,+ private val observationCoordinator: PlaybackObservationSink? = null) {- private val playbackCoordinator = PlaybackResolutionCoordinator(providerCapabilities)+ private val playbackCoordinator = PlaybackResolverRegistry(providerCapabilities)fun isInternalStreamUrl(url: String?): Boolean =XtreamUrlFactory.isInternalStreamUrl(url) || StalkerUrlFactory.isInternalStreamUrl(url)@@ -96,8 +98,34 @@ class XtreamStreamUrlResolver @Inject constructor(isStalkerSource = stalkerToken != null)}++ /** Explicit resolve-and-commit boundary for callers that want learned playback observations. */+ suspend fun resolveAndCommitMetadata(+ url: String,+ fallbackProviderId: Long? = null,+ fallbackStreamId: Long? = null,+ fallbackContentType: ContentType? = null,+ fallbackContainerExtension: String? = null,+ preferStableUrl: Boolean = false+ ): ResolvedStreamUrl? = resolveWithMetadata(+ url,+ fallbackProviderId,+ fallbackStreamId,+ fallbackContentType,+ fallbackContainerExtension,+ preferStableUrl+ ).also { resolved ->+ resolved?.let {+ checkNotNull(observationCoordinator) {+ "Playback observation coordinator is required for resolveAndCommitMetadata"+ }.persist(it.observations)+ }+ }}+/** Compatibility alias for callers migrating to the provider-neutral resolver name. */+typealias XtreamStreamUrlResolver = ProviderPlaybackResolver+private fun XtreamStreamKind.toContentType(): ContentType = when (this) {XtreamStreamKind.LIVE -> ContentType.LIVEXtreamStreamKind.MOVIE -> ContentType.MOVIEdiff --git a/data/src/main/java/com/streamvault/data/repository/ChannelRepositoryImpl.kt b/data/src/main/java/com/streamvault/data/repository/ChannelRepositoryImpl.ktindex bb6020fc..f988f801 100644--- a/data/src/main/java/com/streamvault/data/repository/ChannelRepositoryImpl.kt+++ b/data/src/main/java/com/streamvault/data/repository/ChannelRepositoryImpl.kt@@ -244,7 +244,7 @@ class ChannelRepositoryImpl @Inject constructor(}override suspend fun getStreamInfo(channel: Channel, preferStableUrl: Boolean): Result<StreamInfo> = try {- xtreamStreamUrlResolver.resolveWithMetadata(+ xtreamStreamUrlResolver.resolveAndCommitMetadata(url = channel.streamUrl,fallbackProviderId = channel.providerId,fallbackStreamId = channel.streamId.takeIf { it > 0L }diff --git a/data/src/main/java/com/streamvault/data/repository/EpgRepositoryImpl.kt b/data/src/main/java/com/streamvault/data/repository/EpgRepositoryImpl.ktindex 914cd5be..9ae23eb4 100644--- a/data/src/main/java/com/streamvault/data/repository/EpgRepositoryImpl.kt+++ b/data/src/main/java/com/streamvault/data/repository/EpgRepositoryImpl.kt@@ -38,8 +38,6 @@ import kotlinx.coroutines.flow.flowimport kotlinx.coroutines.flow.flowOfimport kotlinx.coroutines.flow.mapimport kotlinx.coroutines.flow.shareIn-import kotlinx.coroutines.sync.Mutex-import kotlinx.coroutines.sync.withLockimport kotlinx.coroutines.withContextimport kotlinx.coroutines.yieldimport okhttp3.OkHttpClient@@ -49,7 +47,7 @@ import java.io.InputStreamimport java.io.IOExceptionimport java.util.concurrent.TimeUnitimport com.streamvault.data.remote.NetworkTimeoutConfig-import java.util.concurrent.ConcurrentHashMap+import com.streamvault.domain.util.KeyedMutexRegistryimport javax.inject.Injectimport javax.inject.Singleton@@ -77,7 +75,7 @@ class EpgRepositoryImpl @Inject constructor(private fun List<Program>.shiftAll(offsetMs: Long): List<Program> =if (offsetMs == 0L) this else map { it.shifted(offsetMs) }- private val providerRefreshMutexes = ConcurrentHashMap<Long, Mutex>()+ private val providerRefreshMutexes = KeyedMutexRegistry<Long>()private val epgHttpClient: OkHttpClient by lazy {okHttpClient.newBuilder()@@ -267,7 +265,7 @@ class EpgRepositoryImpl @Inject constructor(override suspend fun refreshEpg(providerId: Long, epgUrl: String): Result<Unit> =withContext(Dispatchers.IO) {- providerRefreshMutex(providerId).withLock {+ providerRefreshMutexes.withLock(providerId) {val stagingProviderId = -providerIdval providerTimezoneId = (providerCapabilityResolver?.snapshot(providerId)?.configuration as? StalkerConfig)?.device@@ -365,7 +363,7 @@ class EpgRepositoryImpl @Inject constructor(}override fun onProviderDeleted(providerId: Long) {- providerRefreshMutexes.remove(providerId)+ // Entries are reference-counted and removed after the final refresh exits.}override suspend fun getResolvedProgramsForChannels(@@ -430,6 +428,4 @@ class EpgRepositoryImpl @Inject constructor(return channelIds.associateWith { id -> grouped[id]?.firstOrNull() }}- private fun providerRefreshMutex(providerId: Long): Mutex =- providerRefreshMutexes.computeIfAbsent(providerId) { Mutex() }}diff --git a/data/src/main/java/com/streamvault/data/repository/EpgSourceRepositoryImpl.kt b/data/src/main/java/com/streamvault/data/repository/EpgSourceRepositoryImpl.ktindex 3acf6b3e..72b90522 100644--- a/data/src/main/java/com/streamvault/data/repository/EpgSourceRepositoryImpl.kt+++ b/data/src/main/java/com/streamvault/data/repository/EpgSourceRepositoryImpl.kt@@ -47,8 +47,7 @@ import kotlinx.coroutines.CancellationExceptionimport kotlinx.coroutines.flow.Flowimport kotlinx.coroutines.flow.firstimport kotlinx.coroutines.flow.map-import kotlinx.coroutines.sync.Mutex-import kotlinx.coroutines.sync.withLock+import com.streamvault.domain.util.KeyedMutexRegistryimport kotlinx.coroutines.withContextimport okhttp3.OkHttpClientimport okhttp3.Request@@ -57,7 +56,6 @@ import java.io.InputStreamimport java.util.concurrent.TimeUnitimport com.streamvault.data.remote.NetworkTimeoutConfigimport dagger.hilt.android.qualifiers.ApplicationContext-import java.util.concurrent.ConcurrentHashMapimport javax.inject.Injectimport javax.inject.Singleton@@ -133,7 +131,7 @@ class EpgSourceRepositoryImpl @Inject constructor(private const val MIN_REFRESH_INTERVAL_MS = 5L * 60L * 1000L // 5 minutes}- private val sourceRefreshMutexes = ConcurrentHashMap<Long, Mutex>()+ private val sourceRefreshMutexes = KeyedMutexRegistry<Long>()// Dedicated client for EPG downloads: longer read timeout for large/slow feeds,// and no automatic Accept-Encoding: gzip (we handle gzip manually via maybeDecompressGzip).@@ -213,6 +211,7 @@ class EpgSourceRepositoryImpl @Inject constructor(epgProgrammeDao.deleteBySource(id)epgChannelDao.deleteBySource(id)epgSourceDao.delete(id)+ sourceRefreshMutexes.forget(id)resolveAffectedProviders(affectedProviderIds)}@@ -285,8 +284,7 @@ class EpgSourceRepositoryImpl @Inject constructor(sourceId: Long,resolveAffectedProviders: Boolean): Result<Unit> = withContext(Dispatchers.IO) {- val mutex = sourceRefreshMutexes.computeIfAbsent(sourceId) { Mutex() }- mutex.withLock {+ sourceRefreshMutexes.withLock(sourceId) {val source = epgSourceDao.getById(sourceId)?: return@withLock Result.error("Source not found")diff --git a/data/src/main/java/com/streamvault/data/repository/MovieRepositoryImpl.kt b/data/src/main/java/com/streamvault/data/repository/MovieRepositoryImpl.ktindex 79264f3e..e114ffdf 100644--- a/data/src/main/java/com/streamvault/data/repository/MovieRepositoryImpl.kt+++ b/data/src/main/java/com/streamvault/data/repository/MovieRepositoryImpl.kt@@ -76,9 +76,8 @@ import kotlinx.coroutines.flow.flowOfimport kotlinx.coroutines.flow.flowOnimport kotlinx.coroutines.flow.mapimport kotlinx.coroutines.launch-import java.util.concurrent.ConcurrentHashMap-import kotlinx.coroutines.sync.Mutex-import kotlinx.coroutines.sync.withLock+import com.streamvault.domain.util.KeyedMutexRegistry+import com.streamvault.domain.util.BoundedKeySetimport javax.inject.Injectimport javax.inject.Singleton@@ -104,6 +103,7 @@ class MovieRepositoryImpl @Inject constructor(private val typedProviderClientFactory: TypedProviderClientFactory) : MovieRepository {private companion object {+ const val MAX_BACKGROUND_CATEGORY_REFRESHES = 256const val TAG = "MovieRepository"const val SEARCH_RESULT_LIMIT = 200const val SEARCH_OVERSAMPLE_LIMIT = 500@@ -140,9 +140,8 @@ class MovieRepositoryImpl @Inject constructor(val id: Long)- private val xtreamCategoryLoadLocks = ConcurrentHashMap<String, Mutex>()- private val freshXtreamCategories = ConcurrentHashMap.newKeySet<String>()- private val backgroundRefreshes = ConcurrentHashMap.newKeySet<String>()+ private val xtreamCategoryLoadLocks = KeyedMutexRegistry<String>()+ private val backgroundRefreshes = BoundedKeySet<String>(MAX_BACKGROUND_CATEGORY_REFRESHES)private val repositoryScope = CoroutineScope(SupervisorJob() + Dispatchers.IO.limitedParallelism(XTREAM_CATEGORY_HYDRATION_CONCURRENCY))@@ -651,7 +650,7 @@ class MovieRepositoryImpl @Inject constructor(}override suspend fun getStreamInfo(movie: Movie): Result<StreamInfo> = try {- xtreamStreamUrlResolver.resolveWithMetadata(+ xtreamStreamUrlResolver.resolveAndCommitMetadata(url = movie.streamUrl,fallbackProviderId = movie.providerId,fallbackStreamId = movie.streamId,@@ -1590,7 +1589,6 @@ class MovieRepositoryImpl @Inject constructor(val hydration = movieCategoryHydrationDao.get(providerId, categoryId)if (provider.type == ProviderType.XTREAM_CODES) {if (localCount > 0) {- freshXtreamCategories.add(key)} else {syncManager.prioritizeXtreamIndexCategory(providerId, ContentType.MOVIE, categoryId)}@@ -1641,8 +1639,8 @@ class MovieRepositoryImpl @Inject constructor(allowStalkerWildcard: Boolean = true) {val key = "$providerId:$categoryId"- if (!backgroundRefreshes.add(key)) returnrepositoryScope.launch {+ if (!backgroundRefreshes.awaitAdd(key)) return@launchtry {val provider = loadCompatibilityProvider(providerId) ?: return@launchif (provider.type != ProviderType.XTREAM_CODES && provider.type != ProviderType.STALKER_PORTAL) {@@ -1712,18 +1710,17 @@ class MovieRepositoryImpl @Inject constructor(requestedPage: Int? = null) {val key = "$providerId:$categoryId"- val lock = xtreamCategoryLoadLocks.getOrPut(key) { Mutex() }- lock.withLock {+ xtreamCategoryLoadLocks.withLock(key) {val persistedHydration = movieCategoryHydrationDao.get(providerId, categoryId)- if (requestedPage != null && (persistedHydration?.lastSuccessfulPage ?: 0) >= requestedPage) return+ if (requestedPage != null && (persistedHydration?.lastSuccessfulPage ?: 0) >= requestedPage) return@withLockval stalkerProvider = createStalkerProvider(providerId)- if (!allowWildcard && stalkerProvider.isWildcardCategory(ContentType.MOVIE, categoryId)) return+ if (!allowWildcard && stalkerProvider.isWildcardCategory(ContentType.MOVIE, categoryId)) return@withLockvar currentCount = localCount ?: movieDao.getCountByCategory(providerId, categoryId).first()var currentHydration = persistedHydration ?: hydrationif ((currentHydration?.isComplete == true && currentCount > 0) ||(!loadCompletely && currentCount >= requiredCount)- ) return- if (currentCount == 0 && currentHydration?.isEmptyRetryCoolingDown() == true) return+ ) return@withLock+ if (currentCount == 0 && currentHydration?.isEmptyRetryCoolingDown() == true) return@withLockval isPreviewLoad = requiredCount <= STALKER_PREVIEW_REQUIRED_COUNT_THRESHOLDval isInitialCategoryFill = !isPreviewLoad && currentCount < STALKER_INITIAL_CATEGORY_FILL_COUNTdiff --git a/data/src/main/java/com/streamvault/data/repository/SeriesRepositoryImpl.kt b/data/src/main/java/com/streamvault/data/repository/SeriesRepositoryImpl.ktindex 532ec50c..a151d936 100644--- a/data/src/main/java/com/streamvault/data/repository/SeriesRepositoryImpl.kt+++ b/data/src/main/java/com/streamvault/data/repository/SeriesRepositoryImpl.kt@@ -44,7 +44,6 @@ import kotlinx.coroutines.launchimport kotlinx.coroutines.withTimeoutOrNullimport com.streamvault.data.util.toFtsPrefixQueryimport com.streamvault.data.util.rankSearchResults-import java.util.concurrent.ConcurrentHashMapimport javax.inject.Injectimport com.streamvault.data.preferences.PreferencesRepositoryimport com.streamvault.data.provider.ProviderCapabilityResolver@@ -53,8 +52,8 @@ import com.streamvault.data.provider.toLegacyProviderimport com.streamvault.data.provider.ProviderCapabilityTimeoutExceptionimport com.streamvault.domain.provider.CapabilityResolutionimport com.streamvault.domain.provider.ProviderContentReference-import kotlinx.coroutines.sync.Mutex-import kotlinx.coroutines.sync.withLock+import com.streamvault.domain.util.KeyedMutexRegistry+import com.streamvault.domain.util.BoundedKeySetimport javax.inject.Singleton@Singleton@@ -78,6 +77,7 @@ class SeriesRepositoryImpl @Inject constructor(private val typedProviderClientFactory: TypedProviderClientFactory) : SeriesRepository {private companion object {+ const val MAX_BACKGROUND_CATEGORY_REFRESHES = 256const val TAG = "SeriesRepository"const val SEARCH_RESULT_LIMIT = 200const val SEARCH_OVERSAMPLE_LIMIT = 500@@ -115,9 +115,8 @@ class SeriesRepositoryImpl @Inject constructor(val id: Long)- private val xtreamCategoryLoadLocks = ConcurrentHashMap<String, Mutex>()- private val loadedXtreamCategories = ConcurrentHashMap.newKeySet<String>()- private val backgroundRefreshes = ConcurrentHashMap.newKeySet<String>()+ private val xtreamCategoryLoadLocks = KeyedMutexRegistry<String>()+ private val backgroundRefreshes = BoundedKeySet<String>(MAX_BACKGROUND_CATEGORY_REFRESHES)private val repositoryScope = CoroutineScope(SupervisorJob() + Dispatchers.IO.limitedParallelism(XTREAM_CATEGORY_HYDRATION_CONCURRENCY))@@ -701,7 +700,7 @@ class SeriesRepositoryImpl @Inject constructor(}override suspend fun getEpisodeStreamInfo(episode: Episode): Result<StreamInfo> = try {- xtreamStreamUrlResolver.resolveWithMetadata(+ xtreamStreamUrlResolver.resolveAndCommitMetadata(url = episode.streamUrl,fallbackProviderId = episode.providerId,fallbackStreamId = episode.episodeId.takeIf { it > 0 } ?: episode.id,@@ -1552,7 +1551,6 @@ class SeriesRepositoryImpl @Inject constructor(val hydration = seriesCategoryHydrationDao.get(providerId, categoryId)if (provider.type == ProviderType.XTREAM_CODES) {if (localCount > 0) {- loadedXtreamCategories.add(key)} else {syncManager.prioritizeXtreamIndexCategory(providerId, ContentType.SERIES, categoryId)}@@ -1590,8 +1588,8 @@ class SeriesRepositoryImpl @Inject constructor(allowStalkerWildcard: Boolean = true) {val key = "$providerId:$categoryId"- if (!backgroundRefreshes.add(key)) returnrepositoryScope.launch {+ if (!backgroundRefreshes.awaitAdd(key)) return@launchtry {if (provider.type == ProviderType.XTREAM_CODES) {return@launch@@ -1649,18 +1647,17 @@ class SeriesRepositoryImpl @Inject constructor(requestedPage: Int? = null) {val key = "$providerId:$categoryId"- val lock = xtreamCategoryLoadLocks.getOrPut(key) { Mutex() }- lock.withLock {+ xtreamCategoryLoadLocks.withLock(key) {val persistedHydration = seriesCategoryHydrationDao.get(providerId, categoryId)- if (requestedPage != null && (persistedHydration?.lastSuccessfulPage ?: 0) >= requestedPage) return+ if (requestedPage != null && (persistedHydration?.lastSuccessfulPage ?: 0) >= requestedPage) return@withLockval stalkerProvider = createStalkerProvider(providerId)- if (!allowWildcard && stalkerProvider.isWildcardCategory(ContentType.SERIES, categoryId)) return+ if (!allowWildcard && stalkerProvider.isWildcardCategory(ContentType.SERIES, categoryId)) return@withLockvar currentCount = localCount ?: seriesDao.getCountByCategory(providerId, categoryId).first()var currentHydration = persistedHydration ?: hydrationif ((currentHydration?.isComplete == true && currentCount > 0) ||(!loadCompletely && currentCount >= requiredCount)- ) return- if (currentCount == 0 && currentHydration?.isEmptyRetryCoolingDown() == true) return+ ) return@withLock+ if (currentCount == 0 && currentHydration?.isEmptyRetryCoolingDown() == true) return@withLockval isPreviewLoad = requiredCount <= STALKER_PREVIEW_REQUIRED_COUNT_THRESHOLDval isInitialCategoryFill = !isPreviewLoad && currentCount < STALKER_INITIAL_CATEGORY_FILL_COUNTdiff --git a/data/src/main/java/com/streamvault/data/sync/ProviderSyncLockRegistry.kt b/data/src/main/java/com/streamvault/data/sync/ProviderSyncLockRegistry.ktindex e160d4b6..3df9352b 100644--- a/data/src/main/java/com/streamvault/data/sync/ProviderSyncLockRegistry.kt+++ b/data/src/main/java/com/streamvault/data/sync/ProviderSyncLockRegistry.kt@@ -1,10 +1,9 @@package com.streamvault.data.syncimport com.streamvault.domain.model.ContentType-import java.util.concurrent.ConcurrentHashMap+import com.streamvault.domain.util.KeyedMutexRegistryimport javax.inject.Injectimport javax.inject.Singleton-import kotlinx.coroutines.sync.Mutex/*** Owns the narrower locks used by interactive hydration and incremental index work.@@ -15,50 +14,35 @@ import kotlinx.coroutines.sync.Mutex*/@Singletonclass ProviderSyncLockRegistry @Inject constructor() {- private val vodCategoryLocks = ConcurrentHashMap<String, Mutex>()- private val stalkerSummaryLocks = ConcurrentHashMap<Long, Mutex>()- private val stalkerIndexSectionLocks = ConcurrentHashMap<String, Mutex>()+ private val vodCategoryLocks = KeyedMutexRegistry<String>()+ private val stalkerSummaryLocks = KeyedMutexRegistry<Long>()+ private val stalkerIndexSectionLocks = KeyedMutexRegistry<String>()suspend fun <T> withVodCategoryLock(providerId: Long,categoryId: Long,splitCatalog: Boolean,block: suspend () -> T- ): T = withMutexLock(- lockFor(vodCategoryLocks, vodCategoryKey(providerId, categoryId, splitCatalog)),- block- )+ ): T = vodCategoryLocks.withLock(vodCategoryKey(providerId, categoryId, splitCatalog), block)suspend fun <T> withStalkerSummaryLock(providerId: Long,block: suspend () -> T- ): T = withMutexLock(lockFor(stalkerSummaryLocks, providerId), block)+ ): T = stalkerSummaryLocks.withLock(providerId, block)suspend fun <T> withStalkerIndexSectionLock(providerId: Long,section: ContentType,block: suspend () -> T- ): T = withMutexLock(lockFor(stalkerIndexSectionLocks, "$providerId:${section.name}"), block)+ ): T = stalkerIndexSectionLocks.withLock("$providerId:${section.name}", block)/** Removes idle keys after durable provider deletion. */- fun forgetProvider(providerId: Long) {- stalkerSummaryLocks.remove(providerId)- vodCategoryLocks.keys.removeIf { it.startsWith("$providerId:") || it.startsWith("split:$providerId:") }- stalkerIndexSectionLocks.keys.removeIf { it.startsWith("$providerId:") }+ suspend fun forgetProvider(providerId: Long) {+ stalkerSummaryLocks.forget(providerId)+ // Category/section entries release themselves when their last active/waiting user exits.}private fun vodCategoryKey(providerId: Long, categoryId: Long, splitCatalog: Boolean): String =if (splitCatalog) "split:$providerId:$categoryId" else "$providerId:$categoryId"- private fun <K> lockFor(locks: ConcurrentHashMap<K, Mutex>, key: K): Mutex =- locks.computeIfAbsent(key) { Mutex() }-- private suspend fun <T> withMutexLock(mutex: Mutex, block: suspend () -> T): T {- mutex.lock()- return try {- block()- } finally {- mutex.unlock()- }- }}diff --git a/data/src/main/java/com/streamvault/data/sync/ProviderWorkLockRegistry.kt b/data/src/main/java/com/streamvault/data/sync/ProviderWorkLockRegistry.ktindex 74d7a8c3..8bd80b47 100644--- a/data/src/main/java/com/streamvault/data/sync/ProviderWorkLockRegistry.kt+++ b/data/src/main/java/com/streamvault/data/sync/ProviderWorkLockRegistry.kt@@ -1,6 +1,6 @@package com.streamvault.data.sync-import java.util.concurrent.ConcurrentHashMap+import com.streamvault.domain.util.KeyedMutexRegistryimport java.util.concurrent.atomic.AtomicIntegerimport kotlinx.coroutines.sync.Muteximport kotlinx.coroutines.sync.withLock@@ -14,19 +14,18 @@ import javax.inject.Singleton@Singletonclass ProviderWorkLockRegistry @Inject constructor() {private val admissionMutex = Mutex()- private val providerMutexes = ConcurrentHashMap<Long, Mutex>()+ private val providerMutexes = KeyedMutexRegistry<Long>()private val admittedCount = AtomicInteger(0)fun isAnyWorkActiveOrWaiting(): Boolean = admittedCount.get() > 0suspend fun <T> withProviderLock(providerId: Long, block: suspend () -> T): T {require(providerId > 0L) { "Provider work requires a positive provider ID." }- val providerMutex = admissionMutex.withLock {+ admissionMutex.withLock {admittedCount.incrementAndGet()- providerMutexes.computeIfAbsent(providerId) { Mutex() }}return try {- providerMutex.withLock { block() }+ providerMutexes.withLock(providerId, block)} finally {admissionMutex.withLock {admittedCount.decrementAndGet()@@ -46,7 +45,7 @@ class ProviderWorkLockRegistry @Inject constructor() {/** Removes idle provider state after durable provider deletion. */suspend fun forgetProvider(providerId: Long) {admissionMutex.withLock {- providerMutexes.remove(providerId)+ providerMutexes.forget(providerId)}}}diff --git a/data/src/test/java/com/streamvault/data/local/StreamVaultDatabaseMigrationRegistryTest.kt b/data/src/test/java/com/streamvault/data/local/StreamVaultDatabaseMigrationRegistryTest.ktindex 71f11b73..b047136b 100644--- a/data/src/test/java/com/streamvault/data/local/StreamVaultDatabaseMigrationRegistryTest.kt+++ b/data/src/test/java/com/streamvault/data/local/StreamVaultDatabaseMigrationRegistryTest.kt@@ -11,8 +11,10 @@ class StreamVaultDatabaseMigrationRegistryTest {assertThat(migrations).hasSize(StreamVaultDatabaseMigrationRegistry.CURRENT_VERSION - 1)assertThat(migrations.map { it.startVersion }).containsExactlyElementsIn(1 until STREAM_VAULT_DATABASE_VERSION)+ .inOrder()assertThat(migrations.map { it.endVersion }).containsExactlyElementsIn(2..STREAM_VAULT_DATABASE_VERSION)+ .inOrder()}@Testdiff --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 c9e37e94..5ede45db 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@@ -35,6 +35,7 @@ import com.streamvault.data.remote.stalker.StalkerSeriesDetailsimport com.streamvault.data.remote.stalker.StalkerSessionimport com.streamvault.data.remote.stalker.StalkerStreamKindimport com.streamvault.data.remote.stalker.StalkerUrlFactory+import com.streamvault.data.remote.xtream.PlaybackObservationSinkimport com.streamvault.domain.model.ContentTypeimport com.streamvault.data.security.CredentialCryptoimport com.streamvault.domain.model.LiveStreamFormatMode@@ -42,6 +43,8 @@ import com.streamvault.domain.model.Resultimport com.streamvault.domain.model.ProviderTypeimport com.streamvault.domain.model.LegacyProvider as Providerimport com.streamvault.domain.model.StalkerPortalLearning+import com.streamvault.domain.provider.PlaybackObservation+import com.streamvault.domain.provider.StalkerPlaybackObservationimport com.streamvault.domain.repository.ProviderSnapshotRepositoryimport kotlinx.coroutines.flow.flowOfimport kotlinx.coroutines.runBlocking@@ -699,6 +702,56 @@ class XtreamStreamUrlResolverTest {}}+ @Test+ fun resolveAndCommitMetadata_commits_learned_playback_observations() {+ runBlocking {+ val sink = RecordingPlaybackObservationSink()+ val resolver = XtreamStreamUrlResolver(+ providerDao = FakeProviderDao(+ Provider(+ id = 14,+ name = "Stalker",+ type = ProviderType.STALKER_PORTAL,+ serverUrl = "https://portal.example.com",+ stalkerMacAddress = "00:1A:79:12:34:56",+ stalkerDeviceProfile = "MAG250",+ stalkerDeviceTimezone = "UTC",+ stalkerDeviceLocale = "en"+ )+ ),+ credentialCrypto = credentialCrypto,+ stalkerApiService = FakeStalkerApiService(),+ preferencesRepository = preferencesRepository(),+ observationSink = sink+ )+ val internalUrl = StalkerUrlFactory.buildInternalStreamUrl(+ providerId = 14,+ kind = StalkerStreamKind.LIVE,+ itemId = 77,+ cmd = "http://edge.example.com/live/77.m3u8",+ containerExtension = "m3u8"+ )++ resolver.resolveAndCommitMetadata(internalUrl)++ assertThat(sink.observations).hasSize(1)+ assertThat(sink.observations.single()).isInstanceOf(StalkerPlaybackObservation::class.java)+ }+ }++ @Test+ fun resolveAndCommitMetadata_requires_an_observation_sink() {+ runBlocking {+ val resolver = xtreamResolver()++ val error = org.junit.Assert.assertThrows(IllegalStateException::class.java) {+ runBlocking { resolver.resolveAndCommitMetadata("https://edge.example.com/live.m3u8") }+ }++ assertThat(error).hasMessageThat().contains("observation coordinator")+ }+ }+private class FakeProviderDao(override val fixtureProvider: Provider?) : ProviderDao(), ProviderFixtureSource {@@ -864,7 +917,8 @@ private fun XtreamStreamUrlResolver(providerDao: ProviderDao,credentialCrypto: CredentialCrypto,stalkerApiService: StalkerApiService,- preferencesRepository: PreferencesRepository+ preferencesRepository: PreferencesRepository,+ observationSink: PlaybackObservationSink? = null): XtreamStreamUrlResolver {val provider = requireNotNull((providerDao as? ProviderFixtureSource)?.fixtureProvider)val snapshots = object : ProviderSnapshotRepository {@@ -904,7 +958,15 @@ private fun XtreamStreamUrlResolver(JellyfinCapabilityFactory(clients)))- return XtreamStreamUrlResolver(ProviderCapabilityResolver(snapshots, registry))+ return XtreamStreamUrlResolver(ProviderCapabilityResolver(snapshots, registry), observationSink)+}++private class RecordingPlaybackObservationSink : PlaybackObservationSink {+ val observations = mutableListOf<PlaybackObservation>()++ override suspend fun persist(observations: List<PlaybackObservation>) {+ this.observations += observations+ }}private interface ProviderFixtureSource {diff --git a/docs/DATABASE_MIGRATION_INVARIANTS.md b/docs/DATABASE_MIGRATION_INVARIANTS.mdnew file mode 100644index 00000000..832de10e--- /dev/null+++ b/docs/DATABASE_MIGRATION_INVARIANTS.md@@ -0,0 +1,20 @@+# Database migration invariants++Every schema change must satisfy this checklist before the database version is advanced:++- Add exactly one adjacent migration to the appropriate version-group file and keep the registry contiguous.+- Export and commit the new Room schema JSON; its version must equal `STREAM_VAULT_DATABASE_VERSION`.+- Preserve provider identity, encrypted typed configuration, configuration generation, and active-source references.+- Preserve foreign keys and indexes for catalog, EPG assignment, recording, history, backup/workflow, and plugin ownership tables.+- Backfills must be deterministic, idempotent within the transaction, and explicit about defaults and nullability.+- Add `MigrationTestHelper` coverage for the new adjacent hop and at least one populated supported multi-hop origin.+- Run every committed historical schema artifact through the exact production registry to the current version; document intentionally absent exports.+- Verify `PRAGMA foreign_key_check` for every table written by the migration.+- Downgrades remain unsupported and must fail explicitly; destructive fallback is prohibited.++## Current verification++- Current schema: v75.+- Exported historical origins: v1 and v3-v74; v2 has no committed Room schema export.+- `StreamVaultDatabaseMigrationTest` validates all exported origins to v75 plus populated direct/multi-hop preservation fixtures.+- Device result (2026-08-13): 37/37 passed on `Television_1080p(AVD) - 16`.diff --git a/docs/IPTV_CODE_REVIEW.md b/docs/IPTV_CODE_REVIEW.mdindex d09a2c5a..95bd6290 100644--- a/docs/IPTV_CODE_REVIEW.md+++ b/docs/IPTV_CODE_REVIEW.md@@ -161,11 +161,11 @@ UI uses `ScheduleRecording`/`RecordingManager`. `RecordingManagerImpl` persists### Plugins-`StreamVaultPluginManager` discovers Android services implementing the plugin action, reads a manifest over Messenger or service metadata, enables/disables plugins in its own preferences, invokes plugin operations, imports plugin-provided catalog data into an M3U provider mapping, and refreshes TV input/catalog state. Discovery currently performs synchronous `runBlocking(Dispatchers.IO)` Messenger calls (ARCH-006).+`StreamVaultPluginManager` discovers Android services implementing the plugin action, reads manifests over bounded concurrent Messenger calls or service metadata, and publishes first-class plugin source identities. Lifecycle-owned work serializes enable/disable/import/remove operations and repairs interrupted or uninstalled plugin ownership (ARCH-006).### App upgrades and database migrations-App update checking starts from `StreamVaultApp` and stores cached release metadata in `PreferencesRepository`; install UI/service logic lives under `app/update`. Room database upgrades are handled by the large explicit migration chain in `StreamVaultDatabase`, with schema JSON emitted by the Room Gradle plugin. Migration correctness is deferred to Phase 4, but its concentration is recorded in ARCH-007.+App update checking starts from `StreamVaultApp` and stores cached release metadata in `PreferencesRepository`; install UI/service logic lives under `app/update`. Room schema/DAO declaration remains in `StreamVaultDatabase`, while executable migrations are grouped into three version-era files behind one validated contiguous registry. Committed schema JSON and every exported-origin-to-current device test form the upgrade gate (ARCH-007).## Phase 1 findings summary@@ -174,10 +174,10 @@ App update checking starts from `StreamVaultApp` and stores cached release metad| 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 | Implemented in code; device validation pending (2026-08-12) | High | Provider plans, activation receipts, durable continuation scheduling, state publication, index execution, and workflow admission are separated; the remaining `SyncManager` compatibility façade is approximately 2,451 lines. | 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-004 | Implemented and verified (2026-08-13) | Medium | Provider-neutral playback resolution is split from generation-fenced observation persistence. | Architectural || 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-006 | Implemented and verified (2026-08-13) | High | Plugin discovery is bounded/cancellable and plugins have stable first-class source identity with lifecycle repair. | Local + architectural |+| ARCH-007 | Implemented and device-verified (2026-08-13) | Medium | Migrations are version-grouped behind a complete registry and every exported historical schema reaches v75. | 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@@ -193,7 +193,7 @@ App update checking starts from `StreamVaultApp` and stores cached release metad- **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.+- **Implementation (2026-08-11; ARCH-004 follow-up 2026-08-13):** 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 observations are now returned from resolution and persisted separately through generation fencing.### ARCH-002 — Core domain model is polluted by Stalker transport, fingerprint, and learned state@@ -241,7 +241,7 @@ App update checking starts from `StreamVaultApp` and stores cached release metad### ARCH-004 — Playback resolver has contradictory provider dispatch and hidden side effects-- **Classification:** Confirmed defect and architectural concern+- **Classification:** Implemented and verified (2026-08-13)- **Severity:** Medium- **Where:** `data/.../remote/xtream/XtreamStreamUrlResolver.kt:45-227`, especially `resolveWithMetadata`; Stalker provider cache and learning helpers in the same class.- **Current behavior:** A class named `XtreamStreamUrlResolver` resolves Xtream, Stalker, M3U, and Jellyfin. In its exhaustive provider `when`, `ProviderType.M3U` is handled at lines 217-224 and then listed again with Jellyfin at lines 225-226. Kotlin accepts this, and the forced data-module compile passed, but the second M3U label contradicts the preceding pass-through behavior. The resolver also decrypts provider state, constructs/caches a full `StalkerProvider`, authenticates/resolves a link, and persists learned Stalker playback behavior.@@ -250,6 +250,7 @@ App update checking starts from `StreamVaultApp` and stores cached release metad- **Recommended correction:** Immediately remove the duplicate M3U label and add exhaustive provider-routing tests. Rename/split this into a provider-neutral `PlaybackResolverRegistry` with independent Xtream, Stalker, M3U, and Jellyfin resolvers. Return explicit `PlaybackResolution` plus optional observations; persist observations in a separate coordinator with compare/version semantics rather than inside resolution.- **Fix scope:** Duplicate-label fix is local; side-effect/cache correction is architectural.- **Required tests:** One routing test per provider for internal and direct URLs; blank/missing provider cases; Stalker cache invalidation after every configuration field changes; concurrent resolve/edit; temporary-link expiry/renewal; observation persistence conflict tests.+- **Implementation (2026-08-13):** Replaced provider-type dispatch in the former Xtream-named resolver with the provider-neutral `ProviderPlaybackResolver`/`PlaybackResolverRegistry` boundary backed by independently registered playback capabilities. Resolution now returns `PlaybackResolution` observations without persisting them; `PlaybackObservationCoordinator` owns explicit generation-fenced persistence, and production callers opt into `resolveAndCommitMetadata`. The old class name remains only as a compatibility type alias. Routing, Stalker configuration replacement, temporary-link behavior, and stale-generation compare-and-set coverage are present in the resolver/provider snapshot suites.### ARCH-005 — `PlayerViewModel` crosses every layer and is a feature-level god object@@ -265,7 +266,7 @@ App update checking starts from `StreamVaultApp` and stores cached release metad### ARCH-006 — Plugin discovery blocks callers and plugins are not first-class providers-- **Classification:** Highly likely defect+- **Classification:** Implemented and verified (2026-08-13)- **Severity:** High- **Where:** `app/.../plugins/StreamVaultPluginManager.kt`, especially `resolvePlugin`, `readManifestFromService`, `refreshTvInputCatalogInBackground`, and provider mapping/import methods.- **Current behavior:** Discovery resolves each service and uses `runBlocking(Dispatchers.IO)` for status and manifest Messenger calls with 2.5s and 3s timeouts. These calls are sequential per plugin and are invoked from non-suspending discovery helpers. Background TV refresh creates an unowned `CoroutineScope(Dispatchers.IO)`. Plugin catalog identity is persisted as a mapping to an M3U provider, so plugin lifecycle and provider lifecycle are coupled indirectly by names/IDs and preferences.@@ -274,10 +275,11 @@ App update checking starts from `StreamVaultApp` and stores cached release metad- **Recommended correction:** Make discovery/status loading suspending and concurrent with a bounded global timeout, expose per-plugin loading/error state, and run it in a lifecycle-owned scope. Model plugins as a provider/source capability with stable package/service/manifest identity and explicit uninstall/disable cleanup. Replace the ad-hoc scope with injected application work coordination or WorkManager if durable.- **Fix scope:** Local for blocking calls/scope; architectural for provider modeling.- **Required tests:** Main-thread discovery test; multiple slow/dead plugin services; timeout/cancellation; uninstall during import; duplicate manifest IDs; mapping cleanup and TV catalog consistency; process death during catalog import.+- **Implementation (2026-08-13):** Discovery is suspending, concurrent per service, bounded by request and global timeouts, cancellation-safe, and exposes per-component loading/partial/timeout/error state. Application-owned `PluginWorkCoordinator` replaces ad-hoc scopes. Plugins implement the domain `ProviderSourceRegistry` as first-class `PluginProviderSource` values with package/service/manifest identity, capabilities, enabled state, and an explicitly labeled backing storage representation. Enable/disable mutations are serialized and checkpointed before IPC; startup and package broadcasts replay interrupted import/removal work, repair missing ownership, and remove providers only when their exact Android service component is absent.### ARCH-007 — Database definition and migration history are too concentrated to audit safely-- **Classification:** Architectural concern+- **Classification:** Implemented and device-verified (2026-08-13)- **Severity:** Medium- **Where:** `data/.../local/StreamVaultDatabase.kt` and generated `data/schemas`.- **Current behavior:** One multi-thousand-line Room database class declares a large entity set and a long sequence of handwritten migrations. The forced compile emitted dozens of migration override warnings and two warnings about inferred intersection types in migration code, in addition to schema-related warning noise.@@ -286,6 +288,7 @@ App update checking starts from `StreamVaultApp` and stores cached release metad- **Recommended correction:** Split migrations into versioned files grouped by feature, introduce reusable migration assertions/backfill helpers, and maintain an explicit schema-invariant checklist. Treat warnings as errors after cleaning the current baseline. Keep Room schema exports under version control and test every supported historical start version.- **Fix scope:** Architectural organization; individual warning fixes are local.- **Required tests:** Room MigrationTestHelper coverage from every shipped schema to current; multi-hop and direct-chain equivalence; data-preservation fixtures for every provider, EPG assignment, recording, history, and plugin mapping; downgrade/restore incompatibility messaging.+- **Implementation (2026-08-13):** `StreamVaultDatabase` now contains the Room schema/DAO surface and compatibility aliases only. All 74 adjacent migrations are physically grouped into `LegacyMigrationsV1To24`, `LegacyMigrationsV24To49`, and `FeatureMigrationsV49To75`, with shared SQL/backfill validation in `MigrationSupport` and one ordered production registry. `DATABASE_MIGRATION_INVARIANTS.md` records the review checklist; registry validation fails on any missing, duplicate, non-adjacent, or reordered version. Historical ownership defects were repaired for parental-control fields, FTS definitions/triggers, provider HTTP/Stalker fields, plugin/alarm cleanup, hydration/state-table reintroduction, and final `sync_metadata` convergence. The Android `MigrationTestHelper` class now validates every exported origin (v1 and v3-v74; no v2 export exists) against v75 using the exact production registry, alongside populated provider/favorite/EPG/recording/history fixtures. All 37 tests passed on `Television_1080p(AVD) - 16` on 2026-08-13.### ARCH-008 — Background work is fragmented across independently scheduled pipelines@@ -394,7 +397,7 @@ Phase 2 should review these files/modules first, in this order:| WORK-001 | Local database maintenance is incorrectly gated on connectivity | Resolved (2026-08-01) | Medium || WORK-002 | Recording reconciliation retries every error without classification/cap | Resolved (2026-07-29) | Medium || UPDATE-001 | Failed automatic update checks suppress another attempt for 24 hours | Resolved (2026-07-29) | Medium |-| MEMORY-001 | Process-lifetime maps grow with provider/category/host/media identities | Architectural concern | Medium |+| MEMORY-001 | Process-lifetime maps grow with provider/category/host/media identities | Implemented and verified (2026-08-13) | Medium || PERSIST-001 | The central preferences DataStore has no explicit corruption recovery | Implemented; boundary verification pending (2026-07-30) | Medium || TEST-001 | The player suite asserts the opposite MPEG-TS extractor policy from production | Resolved (2026-07-26) | Medium |@@ -564,7 +567,7 @@ The urgent shared fixes are cancellation-safe HTTP, recording/timeshift lifecycl### MEMORY-001 — Process-lifetime maps grow with provider/category/host/media identities-- **Classification:** Architectural concern+- **Classification:** Implemented and verified (2026-08-13)- **Severity:** Medium- **Where:** `PlayerDataSourceFactoryProvider.clientsByKey:42-78`; `PlayerAddressHealthStore`; `Media3PlayerEngine.promotedLiveHlsBufferReasonsByMediaId:225,1764`; `AudioCompatibilityMemoryStore`; movie/series category caches and locks; `EpgSourceRepositoryImpl.sourceRefreshMutexes:81,218`; URL resolver Stalker-provider registry.- **Current behavior:** Singleton/long-lived maps, sets, and per-media preference keys have no maximum, comprehensive TTL sweep, or deletion hook. Keys are data/network driven; player client keys include address/proxy variations. `SyncManager.onProviderDeleted` does not invalidate these other registries.@@ -573,6 +576,7 @@ The urgent shared fixes are cancellation-safe HTTP, recording/timeshift lifecycl- **Recommended correction:** Set ownership/bounds for every registry: provider-delete invalidation, LRU/TTL with proactive sweep, removal of unused mutexes, and a small fixed set of client profiles. Version/cap persisted compatibility memory.- **Fix scope:** Shared cache policy plus local hooks.- **Required tests:** 100,000 unique keys remain within fixed bounds; delete/re-add; TTL without same-key lookup; concurrent eviction/use; active calls survive client policy.+- **Implementation (2026-08-13):** Added shared bounded/expiring cache, bounded-key-set, and idle self-releasing keyed-mutex policies. Applied fixed limits/TTL or lifecycle removal to player clients, address health, promoted-HLS reasons, versioned audio compatibility memory, movie/series/EPG locks and in-flight sets, sync/work locks, Stalker resolver/auth/URL/identity caches, and provider deletion hooks. Stress tests exercise 100,000 unique keys, TTL sweeping without same-key access, delete/re-add, eviction during active use, and lock replacement safety; evicting a client reference does not cancel an already active OkHttp call.### PERSIST-001 — The central preferences DataStore has no explicit corruption recovery@@ -1046,7 +1050,7 @@ The main feature risks are cross-store transitions: provider edits expose partia- **Fix scope:** Migration test infrastructure/CI; no production migration omission was found.- **Required tests:** 61/60/57/oldest-supported→62, every provider type, defaults/FKs/indexes, registry parity, and downgrade if supported.- **Resolution:** Added an Android Room migration test for the 61→62 production migration and verifies both newly added provider policy columns.-- **2026-07-27 implementation:** A populated v60 provider fixture now migrates through the current v66 schema and verifies retained provider data plus v62 policy defaults; v65→66 has its own schema fixture. Coverage for every supported upgrade origin and production-registry parity remains required. **Status: Needs improvement.**+- **2026-08-13 completion:** The production registry is contiguous through v75 and the Android migration suite now opens every committed historical schema artifact (v1 and v3-v74; v2 was never exported), runs its exact production path to v75, and validates the final Room schema. Populated targeted fixtures cover provider variants, favorites/groups, EPG assignment, recording/reminder state, history, plugin ownership, provider snapshots, and foreign-key preservation. All 37 migration tests passed on `Television_1080p(AVD) - 16`. **Status: Resolved.**## Phase 4 verification and evidence@@ -1359,7 +1363,7 @@ WP0 and the initial WP7 harness can start immediately. WP1 establishes the cance- 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.+- Remaining evidence: API 25 migration execution is unavailable in the installed Android SDK/emulator set. On the available API 36 TV emulator, the repaired historical suite is now a clean release gate: all 37 migration tests pass, including every committed historical origin to v75. ARCH-001 and ARCH-002 therefore retain only the explicit API 25 device-evidence caveat.### WP4 — Bounded ingestion and provider correctnessdiff --git a/domain/src/main/java/com/streamvault/domain/provider/ProviderCapabilities.kt b/domain/src/main/java/com/streamvault/domain/provider/ProviderCapabilities.ktindex eb186a3c..92d94642 100644--- a/domain/src/main/java/com/streamvault/domain/provider/ProviderCapabilities.kt+++ b/domain/src/main/java/com/streamvault/domain/provider/ProviderCapabilities.kt@@ -44,9 +44,25 @@ data class ResolvedPlayback(val playbackTransportPolicy: com.streamvault.domain.model.PlaybackTransportPolicy? = null,val allowInvalidSsl: Boolean = false,val proxyHost: String = "",- val proxyPort: Int? = null+ val proxyPort: Int? = null,+ val observations: List<PlaybackObservation> = emptyList())+/** State learned while resolving, returned as data so the resolver itself remains side-effect free. */+sealed interface PlaybackObservation {+ val providerId: Long+ val configurationGeneration: Long+}++data class StalkerPlaybackObservation(+ override val providerId: Long,+ override val configurationGeneration: Long,+ val playbackMode: String,+ val endpointPreference: com.streamvault.domain.model.StalkerEndpointPreference,+ val cookieMode: com.streamvault.domain.model.StalkerCookieMode,+ val backendHint: com.streamvault.domain.model.StalkerPlaybackBackendHint+) : PlaybackObservation+data class CatchUpRequest(val streamId: Long,val start: Long,diff --git a/domain/src/main/java/com/streamvault/domain/provider/ProviderSources.kt b/domain/src/main/java/com/streamvault/domain/provider/ProviderSources.ktnew file mode 100644index 00000000..8bd71fbe--- /dev/null+++ b/domain/src/main/java/com/streamvault/domain/provider/ProviderSources.kt@@ -0,0 +1,39 @@+package com.streamvault.domain.provider++import com.streamvault.domain.model.ProviderType++/** Stable identity of an external source, independent of labels, URLs, and imported provider IDs. */+data class PluginSourceIdentity(+ val packageName: String,+ val serviceClassName: String,+ val manifestId: String+)++sealed interface ProviderSource {+ val providerId: Long+ val enabled: Boolean+ val capabilities: Set<String>+}++data class NativeProviderSource(+ override val providerId: Long,+ override val enabled: Boolean,+ override val capabilities: Set<String>,+ val providerType: ProviderType+) : ProviderSource++/**+ * First-class plugin source. [backingProviderType] describes storage/import representation only;+ * lifecycle and capability ownership remain attached to [identity].+ */+data class PluginProviderSource(+ override val providerId: Long,+ override val enabled: Boolean,+ override val capabilities: Set<String>,+ val identity: PluginSourceIdentity,+ val backingProviderType: ProviderType+) : ProviderSource++interface ProviderSourceRegistry {+ suspend fun sources(): List<ProviderSource>+}diff --git a/domain/src/main/java/com/streamvault/domain/util/BoundedExpiringCache.kt b/domain/src/main/java/com/streamvault/domain/util/BoundedExpiringCache.ktindex 6ef7b17d..4b88fdd3 100644--- a/domain/src/main/java/com/streamvault/domain/util/BoundedExpiringCache.kt+++ b/domain/src/main/java/com/streamvault/domain/util/BoundedExpiringCache.kt@@ -54,6 +54,24 @@ class BoundedExpiringCache<K, V>(@Synchronizedfun remove(key: K): V? = entries.remove(key)?.value+ @Synchronized+ fun removeIf(predicate: (K, V) -> Boolean): Int {+ var removed = 0+ val iterator = entries.entries.iterator()+ while (iterator.hasNext()) {+ val (key, entry) = iterator.next()+ if (predicate(key, entry.value)) {+ iterator.remove()+ removed+++ }+ }+ return removed+ }++ /** Proactively expires stale entries without requiring a lookup of the same key. */+ @Synchronized+ fun sweep() = sweepAll()+@Synchronizedfun clear() {entries.clear()diff --git a/domain/src/main/java/com/streamvault/domain/util/BoundedKeySet.kt b/domain/src/main/java/com/streamvault/domain/util/BoundedKeySet.ktnew file mode 100644index 00000000..b1bc55c3--- /dev/null+++ b/domain/src/main/java/com/streamvault/domain/util/BoundedKeySet.kt@@ -0,0 +1,33 @@+package com.streamvault.domain.util++import kotlinx.coroutines.delay++/** Atomic admission set for in-flight work; rejects new unique keys at a fixed capacity. */+class BoundedKeySet<K>(private val maxEntries: Int) {+ private val entries = LinkedHashSet<K>()++ init { require(maxEntries > 0) }++ @Synchronized+ fun tryAdd(key: K): Boolean {+ if (key in entries || entries.size >= maxEntries) return false+ entries.add(key)+ return true+ }++ /**+ * Waits for an admission slot instead of silently dropping work when the bound is full.+ * A duplicate key is still coalesced and returns false immediately.+ */+ suspend fun awaitAdd(key: K, retryDelayMs: Long = 50L): Boolean {+ while (true) {+ if (tryAdd(key)) return true+ if (contains(key)) return false+ delay(retryDelayMs)+ }+ }++ @Synchronized fun remove(key: K): Boolean = entries.remove(key)+ @Synchronized fun size(): Int = entries.size+ @Synchronized fun contains(key: K): Boolean = key in entries+}diff --git a/domain/src/main/java/com/streamvault/domain/util/KeyedMutexRegistry.kt b/domain/src/main/java/com/streamvault/domain/util/KeyedMutexRegistry.ktnew file mode 100644index 00000000..ccc28aa0--- /dev/null+++ b/domain/src/main/java/com/streamvault/domain/util/KeyedMutexRegistry.kt@@ -0,0 +1,39 @@+package com.streamvault.domain.util++import kotlinx.coroutines.sync.Mutex+import kotlinx.coroutines.sync.withLock++/**+ * Per-key serialization without retaining every key for the process lifetime.+ *+ * Reference counting happens under [registryMutex], so an entry cannot be removed while another+ * caller is acquiring or using it. The final caller removes the idle mutex in `finally`.+ */+class KeyedMutexRegistry<K> {+ private data class Entry(val mutex: Mutex = Mutex(), var users: Int = 0)++ private val registryMutex = Mutex()+ private val entries = mutableMapOf<K, Entry>()++ suspend fun <T> withLock(key: K, block: suspend () -> T): T {+ val entry = registryMutex.withLock {+ entries.getOrPut(key) { Entry() }.also { it.users++ }+ }+ return try {+ entry.mutex.withLock { block() }+ } finally {+ registryMutex.withLock {+ entry.users--+ if (entry.users == 0 && !entry.mutex.isLocked) entries.remove(key, entry)+ }+ }+ }++ suspend fun forget(key: K) {+ registryMutex.withLock {+ entries[key]?.takeIf { it.users == 0 && !it.mutex.isLocked }?.let { entries.remove(key, it) }+ }+ }++ internal suspend fun sizeForTests(): Int = registryMutex.withLock { entries.size }+}diff --git a/domain/src/test/java/com/streamvault/domain/util/BoundedExpiringCacheTest.kt b/domain/src/test/java/com/streamvault/domain/util/BoundedExpiringCacheTest.ktnew file mode 100644index 00000000..ba1c9d1f--- /dev/null+++ b/domain/src/test/java/com/streamvault/domain/util/BoundedExpiringCacheTest.kt@@ -0,0 +1,42 @@+package com.streamvault.domain.util++import com.google.common.truth.Truth.assertThat+import org.junit.Test++class BoundedExpiringCacheTest {+ @Test+ fun oneHundredThousandUniqueKeysRemainWithinFixedBound() {+ val cache = BoundedExpiringCache<Int, Int>(maxEntries = 128, ttlMillis = Long.MAX_VALUE)++ repeat(100_000) { cache.put(it, it) }++ assertThat(cache.size()).isEqualTo(128)+ assertThat(cache.get(99_999)).isEqualTo(99_999)+ }++ @Test+ fun proactiveSweepExpiresEntriesWithoutSameKeyLookup() {+ var now = 0L+ val cache = BoundedExpiringCache<Int, Int>(8, 100L) { now }+ cache.put(1, 1)++ now = 101L+ cache.sweep()++ assertThat(cache.size()).isEqualTo(0)+ }++ @Test+ fun evictedResourceRemainsUsableByActiveOwner() {+ data class Resource(val id: Int, var active: Boolean = true)+ val cache = BoundedExpiringCache<Int, Resource>(1, Long.MAX_VALUE)+ val activeCallResource = Resource(1)+ cache.put(1, activeCallResource)++ cache.put(2, Resource(2))++ assertThat(cache.get(1)).isNull()+ assertThat(activeCallResource.active).isTrue()+ assertThat(activeCallResource.id).isEqualTo(1)+ }+}diff --git a/domain/src/test/java/com/streamvault/domain/util/BoundedKeySetTest.kt b/domain/src/test/java/com/streamvault/domain/util/BoundedKeySetTest.ktnew file mode 100644index 00000000..d550d41c--- /dev/null+++ b/domain/src/test/java/com/streamvault/domain/util/BoundedKeySetTest.kt@@ -0,0 +1,31 @@+package com.streamvault.domain.util++import com.google.common.truth.Truth.assertThat+import kotlinx.coroutines.async+import kotlinx.coroutines.test.runTest+import org.junit.Test++class BoundedKeySetTest {+ @Test+ fun oneHundredThousandAdmissionsStayBounded() {+ val set = BoundedKeySet<Int>(256)+ repeat(100_000) { set.tryAdd(it) }+ assertThat(set.size()).isEqualTo(256)+ }++ @Test+ fun awaitAddWaitsForCapacityAndDoesNotDropWork() = runTest {+ val set = BoundedKeySet<Int>(1)+ assertThat(set.tryAdd(1)).isTrue()+ val waiting = async { set.awaitAdd(2, retryDelayMs = 1L) }++ testScheduler.runCurrent()+ assertThat(waiting.isCompleted).isFalse()++ set.remove(1)+ testScheduler.advanceUntilIdle()++ assertThat(waiting.await()).isTrue()+ assertThat(set.contains(2)).isTrue()+ }+}diff --git a/domain/src/test/java/com/streamvault/domain/util/KeyedMutexRegistryTest.kt b/domain/src/test/java/com/streamvault/domain/util/KeyedMutexRegistryTest.ktnew file mode 100644index 00000000..f0a0ae2f--- /dev/null+++ b/domain/src/test/java/com/streamvault/domain/util/KeyedMutexRegistryTest.kt@@ -0,0 +1,51 @@+package com.streamvault.domain.util++import com.google.common.truth.Truth.assertThat+import org.junit.Test+import kotlinx.coroutines.async+import kotlinx.coroutines.awaitAll+import kotlinx.coroutines.test.runTest+import kotlinx.coroutines.CompletableDeferred++class KeyedMutexRegistryTest {+ @Test+ fun completedUniqueKeysAreNotRetained() = runTest {+ val registry = KeyedMutexRegistry<Int>()++ (0 until 100_000).chunked(1_000).forEach { keys ->+ keys.map { key -> async { registry.withLock(key) { key } } }.awaitAll()+ }++ assertThat(registry.sizeForTests()).isEqualTo(0)+ }++ @Test+ fun forgetDuringUseDoesNotBreakSerializationAndReAddIsClean() = runTest {+ val registry = KeyedMutexRegistry<Long>()+ val entered = CompletableDeferred<Unit>()+ val release = CompletableDeferred<Unit>()+ val order = mutableListOf<String>()+ val first = async {+ registry.withLock(7L) {+ order += "first-enter"+ entered.complete(Unit)+ release.await()+ order += "first-exit"+ }+ }+ entered.await()+ registry.forget(7L)+ val second = async {+ registry.withLock(7L) { order += "second" }+ }+ release.complete(Unit)+ first.await()+ second.await()++ registry.forget(7L)+ registry.withLock(7L) { order += "re-added" }++ assertThat(order).containsExactly("first-enter", "first-exit", "second", "re-added").inOrder()+ assertThat(registry.sizeForTests()).isEqualTo(0)+ }+}diff --git a/player/src/main/java/com/streamvault/player/AudioCompatibilityMemoryStore.kt b/player/src/main/java/com/streamvault/player/AudioCompatibilityMemoryStore.ktindex b774e471..7a2361d2 100644--- a/player/src/main/java/com/streamvault/player/AudioCompatibilityMemoryStore.kt+++ b/player/src/main/java/com/streamvault/player/AudioCompatibilityMemoryStore.kt@@ -26,17 +26,20 @@ class AudioCompatibilityMemoryStore @Inject constructor(fun lookup(mediaId: String, streamType: String): LearnedAudioCompatibility? {val encoded = preferences.getString(key(mediaId, streamType), null) ?: return nullval parts = encoded.split(FIELD_SEPARATOR)- if (parts.size < 4) return null+ if (parts.size < 5 || parts[0] != FORMAT_VERSION) {+ preferences.edit().remove(key(mediaId, streamType)).apply()+ return null+ }return LearnedAudioCompatibility(mediaId = mediaId,streamType = streamType,- audioMimeTypes = parts[0]+ audioMimeTypes = parts[2].split(LIST_SEPARATOR).map(String::trim).filter(String::isNotEmpty),- decision = parts[1],- detail = parts[2].takeIf(String::isNotBlank),- updatedAtMs = parts[3].toLongOrNull() ?: 0L+ decision = parts[3],+ detail = parts[4].takeIf(String::isNotBlank),+ updatedAtMs = parts[1].toLongOrNull() ?: 0L)}@@ -50,17 +53,20 @@ class AudioCompatibilityMemoryStore @Inject constructor(.map(String::trim).filter(String::isNotEmpty).distinct()+ val now = System.currentTimeMillis()preferences.edit().putString(key(mediaId, streamType),listOf(+ FORMAT_VERSION,+ now.toString(),normalizedMimeTypes.joinToString(LIST_SEPARATOR.toString()),DECISION_SOFTWARE_FFMPEG,- detail.orEmpty().replace(FIELD_SEPARATOR.toString(), " "),- System.currentTimeMillis().toString()+ detail.orEmpty().replace(FIELD_SEPARATOR.toString(), " ")).joinToString(FIELD_SEPARATOR.toString())).apply()+ trimToBound()}fun clear() {@@ -71,8 +77,24 @@ class AudioCompatibilityMemoryStore @Inject constructor(return "${Build.FINGERPRINT}|${Build.MODEL}|$streamType|$mediaId"}+ private fun trimToBound() {+ val excess = preferences.all.size - MAX_ENTRIES+ if (excess <= 0) return+ val oldestKeys = preferences.all.entries+ .sortedBy { (_, value) ->+ (value as? String)?.split(FIELD_SEPARATOR)?.getOrNull(1)?.toLongOrNull() ?: Long.MIN_VALUE+ }+ .take(excess)+ .map(Map.Entry<String, *>::key)+ preferences.edit().also { editor -> oldestKeys.forEach(editor::remove) }.apply()+ }++ internal fun sizeForTests(): Int = preferences.all.size+companion object {private const val PREFS_NAME = "audio_compatibility_memory"+ private const val FORMAT_VERSION = "v2"+ private const val MAX_ENTRIES = 512private const val FIELD_SEPARATOR = '|'private const val LIST_SEPARATOR = ','const val DECISION_SOFTWARE_FFMPEG = "software-ffmpeg"diff --git a/player/src/main/java/com/streamvault/player/Media3PlayerEngine.kt b/player/src/main/java/com/streamvault/player/Media3PlayerEngine.ktindex 3fd6b6e5..4938e4f6 100644--- a/player/src/main/java/com/streamvault/player/Media3PlayerEngine.kt+++ b/player/src/main/java/com/streamvault/player/Media3PlayerEngine.kt@@ -222,7 +222,11 @@ class Media3PlayerEngine @Inject constructor(private var currentBufferIsLive: Boolean? = nullprivate var currentBufferPolicyLabel: String? = nullprivate var currentBufferPolicy: PlaybackBufferPolicy? = null- private val promotedLiveHlsBufferReasonsByMediaId = mutableMapOf<String, String>()+ private val promotedLiveHlsBufferReasonsByMediaId =+ com.streamvault.domain.util.BoundedExpiringCache<String, String>(+ maxEntries = 512,+ ttlMillis = 24L * 60L * 60L * 1_000L+ )private var audioCodecUnsupportedReported = falseprivate var lastSupportErrorMessage: String? = nullprivate val isLowMemoryPlaybackDevice: Boolean = run {@@ -1051,7 +1055,7 @@ class Media3PlayerEngine @Inject constructor(bufferMode = requestedPlaybackBufferMode,streamInfo = streamInfo,observedVideoFormat = _videoFormat.value,- qualityReasonOverride = promotedLiveHlsBufferReasonsByMediaId[mediaId]+ qualityReasonOverride = promotedLiveHlsBufferReasonsByMediaId.get(mediaId))val needsRecreate = activeAudioDecoderMode != preferredAudioDecoderMode ||activeVideoDecoderMode != preferredVideoDecoderMode ||@@ -1774,7 +1778,7 @@ class Media3PlayerEngine @Inject constructor(bufferMode = requestedPlaybackBufferMode,resolvedStreamType = currentResolvedStreamType,isLive = isCurrentStreamLive(),- mediaAlreadyPromoted = mediaId in promotedLiveHlsBufferReasonsByMediaId,+ mediaAlreadyPromoted = promotedLiveHlsBufferReasonsByMediaId.get(mediaId) != null,currentPolicyLabel = currentBufferPolicyLabel,streamInfo = streamInfo,observedVideoFormat = observedFormat,@@ -1782,7 +1786,7 @@ class Media3PlayerEngine @Inject constructor(lowMemoryDevice = isLowMemoryPlaybackDevice) ?: return false- promotedLiveHlsBufferReasonsByMediaId[mediaId] = decision.qualityReason+ promotedLiveHlsBufferReasonsByMediaId.put(mediaId, decision.qualityReason)val wasPlaying = exoPlayer?.playWhenReady ?: trueLog.i(TAG,