StreamVault is a TV-first free IPTV player for Android TV built with Kotlin, Jetpack Compose, Room, Hilt, and Media3.
Kotlin iptv-player
Implement durable portable backup restore
David Nashash58b8c134a534
diff --git a/app/src/main/java/com/streamvault/app/StreamVaultApp.kt b/app/src/main/java/com/streamvault/app/StreamVaultApp.ktindex 8fd8333a..7bd2ec30 100644--- a/app/src/main/java/com/streamvault/app/StreamVaultApp.kt+++ b/app/src/main/java/com/streamvault/app/StreamVaultApp.kt@@ -28,6 +28,7 @@ import androidx.work.NetworkTypeimport androidx.work.PeriodicWorkRequestBuilderimport androidx.work.WorkManagerimport com.streamvault.data.manager.recording.RecordingReconcileWorker+import com.streamvault.data.manager.PendingBackupRestoreCoordinatorimport com.streamvault.data.sync.ProviderSyncWorkerimport com.streamvault.data.sync.XtreamIndexWorkerimport com.streamvault.data.sync.ProviderSyncLifecycle@@ -61,6 +62,9 @@ class StreamVaultApp : Application(), SingletonImageLoader.Factory {@Injectlateinit var startupWorkRegistry: StartupWorkRegistry+ @Inject+ lateinit var pendingBackupRestoreCoordinator: PendingBackupRestoreCoordinator+private val imageOkHttpClient: OkHttpClient by lazy {okHttpClient.newBuilder().addInterceptor(jellyfinImageAuthInterceptor)@@ -88,6 +92,9 @@ class StreamVaultApp : Application(), SingletonImageLoader.Factory {applicationScope.launch {providerSyncLifecycle.reconcileStalkerIndexWorkAtStartup()}+ applicationScope.launch {+ pendingBackupRestoreCoordinator.applyAllAvailable()+ }startupWorkRegistry.register()}diff --git a/app/src/main/java/com/streamvault/app/di/DatabaseModule.kt b/app/src/main/java/com/streamvault/app/di/DatabaseModule.ktindex ec6c4129..1c509b7d 100644--- a/app/src/main/java/com/streamvault/app/di/DatabaseModule.kt+++ b/app/src/main/java/com/streamvault/app/di/DatabaseModule.kt@@ -94,6 +94,7 @@ object DatabaseModule {@Provides fun provideProviderDeletionCleanupDao(db: StreamVaultDatabase): ProviderDeletionCleanupDao = db.providerDeletionCleanupDao()@Provides fun provideProviderConfigRevisionDao(db: StreamVaultDatabase): ProviderConfigRevisionDao = db.providerConfigRevisionDao()@Provides fun provideBackupRestoreCheckpointDao(db: StreamVaultDatabase): BackupRestoreCheckpointDao = db.backupRestoreCheckpointDao()+ @Provides fun provideBackupRestoreLedgerDao(db: StreamVaultDatabase): BackupRestoreLedgerDao = db.backupRestoreLedgerDao()@Provides fun provideProviderWorkflowDao(db: StreamVaultDatabase): ProviderWorkflowDao = db.providerWorkflowDao()@Provides fun provideM3uClassificationDao(db: StreamVaultDatabase): M3uClassificationDao = db.m3uClassificationDao()@Provides fun providePluginProviderOwnershipDao(db: StreamVaultDatabase): PluginProviderOwnershipDao = db.pluginProviderOwnershipDao()diff --git a/app/src/main/java/com/streamvault/app/di/RepositoryModule.kt b/app/src/main/java/com/streamvault/app/di/RepositoryModule.ktindex 06b9204c..7c87c610 100644--- a/app/src/main/java/com/streamvault/app/di/RepositoryModule.kt+++ b/app/src/main/java/com/streamvault/app/di/RepositoryModule.kt@@ -27,6 +27,8 @@ import com.streamvault.domain.manager.ProviderSyncStateReaderimport com.streamvault.data.repository.*import com.streamvault.domain.manager.ParentalControlSessionStoreimport com.streamvault.domain.repository.*+import com.streamvault.domain.manager.BackupRestoreStatusStore+import com.streamvault.data.manager.BackupRestoreStatusStoreImplimport com.streamvault.domain.provider.ProviderCapabilityRegistryimport com.streamvault.domain.provider.ProviderSourceRegistryimport com.streamvault.app.plugins.StreamVaultPluginManager@@ -43,6 +45,8 @@ import javax.inject.Singleton@Module@InstallIn(SingletonComponent::class)abstract class RepositoryModule {+ @Binds @Singleton+ abstract fun bindBackupRestoreStatusStore(impl: BackupRestoreStatusStoreImpl): BackupRestoreStatusStore@Binds @Singletonabstract fun bindProviderRepository(impl: ProviderRepositoryImpl): ProviderRepositorydiff --git a/app/src/main/java/com/streamvault/app/tvinput/TvInputCatalogRefreshWorker.kt b/app/src/main/java/com/streamvault/app/tvinput/TvInputCatalogRefreshWorker.ktnew file mode 100644index 00000000..ed360763--- /dev/null+++ b/app/src/main/java/com/streamvault/app/tvinput/TvInputCatalogRefreshWorker.kt@@ -0,0 +1,45 @@+package com.streamvault.app.tvinput++import android.content.Context+import androidx.work.CoroutineWorker+import androidx.work.ExistingWorkPolicy+import androidx.work.OneTimeWorkRequestBuilder+import androidx.work.WorkManager+import androidx.work.WorkerParameters+import dagger.hilt.EntryPoint+import dagger.hilt.InstallIn+import dagger.hilt.android.EntryPointAccessors+import dagger.hilt.components.SingletonComponent++/** Coalesces slow Android TV provider publication outside foreground provider sync UX. */+class TvInputCatalogRefreshWorker(+ appContext: Context,+ workerParams: WorkerParameters+) : CoroutineWorker(appContext, workerParams) {+ @EntryPoint+ @InstallIn(SingletonComponent::class)+ interface Entry {+ fun tvInputChannelSyncManager(): TvInputChannelSyncManager+ }++ override suspend fun doWork(): Result {+ val manager = EntryPointAccessors.fromApplication(applicationContext, Entry::class.java)+ .tvInputChannelSyncManager()+ return manager.refreshTvInputCatalogResult().fold(+ onSuccess = { Result.success() },+ onFailure = { Result.retry() }+ )+ }++ companion object {+ private const val UNIQUE_WORK_NAME = "tv-input-catalog-refresh"++ fun enqueue(context: Context) {+ WorkManager.getInstance(context).enqueueUniqueWork(+ UNIQUE_WORK_NAME,+ ExistingWorkPolicy.REPLACE,+ OneTimeWorkRequestBuilder<TvInputCatalogRefreshWorker>().build()+ )+ }+ }+}diff --git a/app/src/main/java/com/streamvault/app/tvinput/TvInputChannelSyncManager.kt b/app/src/main/java/com/streamvault/app/tvinput/TvInputChannelSyncManager.ktindex 5a1812ae..2a8fe921 100644--- a/app/src/main/java/com/streamvault/app/tvinput/TvInputChannelSyncManager.kt+++ b/app/src/main/java/com/streamvault/app/tvinput/TvInputChannelSyncManager.kt@@ -1,7 +1,7 @@package com.streamvault.app.tvinputimport android.content.ComponentName-import android.content.ContentResolver+import android.content.ContentProviderOperationimport android.content.ContentUrisimport android.content.ContentValuesimport android.content.Context@@ -14,6 +14,7 @@ import com.streamvault.app.device.isTelevisionDeviceimport com.streamvault.app.navigation.PlayerNavigationRequestimport com.streamvault.domain.model.Channelimport com.streamvault.domain.model.Program+import com.streamvault.domain.model.LegacyProvider as Providerimport com.streamvault.domain.repository.ChannelRepositoryimport com.streamvault.domain.repository.EpgRepositoryimport com.streamvault.domain.repository.ProviderRepository@@ -25,6 +26,9 @@ import kotlinx.coroutines.sync.withLockimport kotlinx.coroutines.withContextimport javax.inject.Injectimport javax.inject.Singleton+import java.net.URI+import java.security.MessageDigest+import java.util.Locale@Singletonclass TvInputChannelSyncManager @Inject constructor(@@ -53,53 +57,85 @@ class TvInputChannelSyncManager @Inject constructor(}val channels = channelRepository.getChannels(provider.id).first()- val existingChannelIds = loadExistingChannels().toMutableMap()- val targetKeys = channels.mapTo(mutableSetOf(), ::channelKey)-- existingChannelIds- .filterKeys { it !in targetKeys }- .values- .forEach(::deleteChannel)+ publishChannels(provider, channels)+ val publishedChannelIds = loadExistingChannels().toMutableMap()val programsByEpgId = loadPrograms(provider.id, channels)-- channels.forEach { channel ->- val key = channelKey(channel)- val channelId = ensureChannel(context.contentResolver, existingChannelIds[key], provider.id, channel)- ?: return@forEach- existingChannelIds[key] = channelId- replacePrograms(- channelId = channelId,- programs = programsByEpgId[channel.epgChannelId].orEmpty(),- providerId = provider.id,- channel = channel,- existingChannelIds = existingChannelIds- )- }+ publishPrograms(provider, channels, publishedChannelIds, programsByEpgId)}}}- private suspend fun loadPrograms(providerId: Long, channels: List<Channel>): Map<String, List<Program>> {- val epgIds = channels.mapNotNull { it.epgChannelId?.takeIf(String::isNotBlank) }- if (epgIds.isEmpty()) return emptyMap()-- val now = System.currentTimeMillis()- val start = now - PROGRAM_LOOKBACK_MS- val end = now + PROGRAM_LOOKAHEAD_MS- val merged = mutableMapOf<String, List<Program>>()+ private fun publishChannels(provider: Provider, channels: List<Channel>) {+ val existing = loadExistingChannelRows()+ val targets = channels.associateBy { stableTvChannelKey(provider, it) }+ val operations = ArrayList<ContentProviderOperation>()+ existing.filterKeys { it !in targets }.values.forEach { row ->+ operations += ContentProviderOperation.newDelete(+ ContentUris.withAppendedId(TvContract.Channels.CONTENT_URI, row.id)+ ).build()+ }+ targets.forEach { (key, channel) ->+ val values = buildChannelValues(provider, channel)+ val row = existing[key]+ when {+ row == null -> operations += ContentProviderOperation.newInsert(TvContract.Channels.CONTENT_URI)+ .withValues(values)+ .build()+ row.providerData != values.getAsString(CHANNEL_COLUMN_INTERNAL_PROVIDER_DATA) ->+ operations += ContentProviderOperation.newUpdate(+ ContentUris.withAppendedId(TvContract.Channels.CONTENT_URI, row.id)+ ).withValues(values).build()+ }+ }+ applyBatches(operations, "channels")+ }- epgIds.distinct().chunked(EPG_QUERY_CHUNK_SIZE).forEach { chunk ->- merged += epgRepository.getProgramsForChannelsSnapshot(providerId, chunk, start, end)+ private fun publishPrograms(+ provider: Provider,+ channels: List<Channel>,+ channelIds: Map<String, Long>,+ programsByEpgId: Map<String, List<Program>>+ ) {+ val desired = linkedMapOf<String, ContentValues>()+ val replaceableChannelIds = linkedSetOf<Long>()+ channels.forEach { channel ->+ val programs = programsByEpgId[channel.epgChannelId].orEmpty()+ if (!shouldReplaceTvPrograms(channel, programs)) return@forEach+ val tvChannelId = channelIds[stableTvChannelKey(provider, channel)] ?: return@forEach+ replaceableChannelIds += tvChannelId+ programs.sortedBy { it.startTime }.take(MAX_PROGRAMS_PER_CHANNEL).forEach { program ->+ val values = buildProgramValues(tvChannelId, provider.id, channel, program)+ val fingerprint = stableTvProgramKey(provider, channel, program)+ values.put(PROGRAM_COLUMN_INTERNAL_PROVIDER_DATA, fingerprint)+ desired[fingerprint] = values+ }}- return merged+ val existing = loadExistingPrograms(replaceableChannelIds)+ val operations = ArrayList<ContentProviderOperation>()+ existing.filterKeys { it !in desired }.values.forEach { programId ->+ operations += ContentProviderOperation.newDelete(+ ContentUris.withAppendedId(TvContract.Programs.CONTENT_URI, programId)+ ).build()+ }+ desired.filterKeys { it !in existing }.values.forEach { values ->+ operations += ContentProviderOperation.newInsert(TvContract.Programs.CONTENT_URI)+ .withValues(values)+ .build()+ }+ applyBatches(operations, "programs")}- private fun loadExistingChannels(): Map<String, Long> {+ private fun loadExistingChannelRows(): Map<String, ExistingTvChannel> {val targetInputId = inputId()return context.contentResolver.query(TvContract.Channels.CONTENT_URI,- arrayOf(BaseColumns._ID, CHANNEL_COLUMN_INPUT_ID, CHANNEL_COLUMN_INTERNAL_PROVIDER_ID),+ arrayOf(+ BaseColumns._ID,+ CHANNEL_COLUMN_INPUT_ID,+ CHANNEL_COLUMN_INTERNAL_PROVIDER_ID,+ CHANNEL_COLUMN_INTERNAL_PROVIDER_DATA+ ),null,null,null@@ -107,123 +143,98 @@ class TvInputChannelSyncManager @Inject constructor(val idIndex = cursor.getColumnIndexOrThrow(BaseColumns._ID)val inputIdIndex = cursor.getColumnIndexOrThrow(CHANNEL_COLUMN_INPUT_ID)val keyIndex = cursor.getColumnIndexOrThrow(CHANNEL_COLUMN_INTERNAL_PROVIDER_ID)+ val dataIndex = cursor.getColumnIndexOrThrow(CHANNEL_COLUMN_INTERNAL_PROVIDER_DATA)buildMap {while (cursor.moveToNext()) {if (cursor.getString(inputIdIndex) == targetInputId) {- put(cursor.getString(keyIndex), cursor.getLong(idIndex))+ put(+ cursor.getString(keyIndex),+ ExistingTvChannel(cursor.getLong(idIndex), cursor.getString(dataIndex).orEmpty())+ )}}}}.orEmpty()}- private fun insertChannel(providerId: Long, channel: Channel): Long? {- val uri = context.contentResolver.insert(- TvContract.Channels.CONTENT_URI,- buildChannelValues(providerId, channel)- ) ?: return null- return ContentUris.parseId(uri)+ private fun loadExistingPrograms(channelIds: Set<Long>): Map<String, Long> {+ if (channelIds.isEmpty()) return emptyMap()+ val result = linkedMapOf<String, Long>()+ channelIds.chunked(PROGRAM_QUERY_CHANNEL_CHUNK_SIZE).forEach { chunk ->+ val placeholders = chunk.joinToString(",") { "?" }+ context.contentResolver.query(+ TvContract.Programs.CONTENT_URI,+ arrayOf(BaseColumns._ID, PROGRAM_COLUMN_INTERNAL_PROVIDER_DATA),+ "$PROGRAM_COLUMN_CHANNEL_ID IN ($placeholders)",+ chunk.map(Long::toString).toTypedArray(),+ null+ )?.use { cursor ->+ val idIndex = cursor.getColumnIndexOrThrow(BaseColumns._ID)+ val dataIndex = cursor.getColumnIndexOrThrow(PROGRAM_COLUMN_INTERNAL_PROVIDER_DATA)+ while (cursor.moveToNext()) {+ cursor.getString(dataIndex)?.let { result[it] = cursor.getLong(idIndex) }+ }+ }+ }+ return result}- private fun updateChannel(channelId: Long, providerId: Long, channel: Channel): Boolean {- val rows = context.contentResolver.update(- ContentUris.withAppendedId(TvContract.Channels.CONTENT_URI, channelId),- buildChannelValues(providerId, channel),- null,- null- )- return rows > 0 && channelExists(context.contentResolver, channelId)+ private fun applyBatches(operations: List<ContentProviderOperation>, stage: String) {+ val startedAt = System.currentTimeMillis()+ operations.chunked(CONTENT_PROVIDER_BATCH_SIZE).forEach { chunk ->+ context.contentResolver.applyBatch(TvContract.AUTHORITY, ArrayList(chunk))+ }+ Log.i(TAG, "TV input $stage operations=${operations.size} took=${System.currentTimeMillis() - startedAt}ms")}- private fun ensureChannel(- resolver: ContentResolver,- existingChannelId: Long?,- providerId: Long,- channel: Channel- ): Long? {- val refreshedId = existingChannelId- ?.takeIf { channelExists(resolver, it) }- ?.takeIf { updateChannel(it, providerId, channel) }- return refreshedId ?: insertChannel(providerId, channel)- }+ private data class ExistingTvChannel(val id: Long, val providerData: String)- private fun replacePrograms(- channelId: Long,- programs: List<Program>,- providerId: Long,- channel: Channel,- existingChannelIds: MutableMap<String, Long>- ) {- if (!shouldReplaceTvPrograms(channel, programs)) return+ private suspend fun loadPrograms(providerId: Long, channels: List<Channel>): Map<String, List<Program>> {+ val epgIds = channels.mapNotNull { it.epgChannelId?.takeIf(String::isNotBlank) }+ if (epgIds.isEmpty()) return emptyMap()- val resolver = context.contentResolver- var activeChannelId = channelId+ val now = System.currentTimeMillis()+ val start = now - PROGRAM_LOOKBACK_MS+ val end = now + PROGRAM_LOOKAHEAD_MS+ val merged = mutableMapOf<String, List<Program>>()- if (!channelExists(resolver, activeChannelId)) {- activeChannelId = ensureChannel(resolver, null, providerId, channel) ?: return- existingChannelIds[channelKey(channel)] = activeChannelId+ epgIds.distinct().chunked(EPG_QUERY_CHUNK_SIZE).forEach { chunk ->+ merged += epgRepository.getProgramsForChannelsSnapshot(providerId, chunk, start, end)}+ return merged+ }- resolver.query(- TvContract.buildProgramsUriForChannel(activeChannelId),- arrayOf(BaseColumns._ID),+ private fun loadExistingChannels(): Map<String, Long> {+ val targetInputId = inputId()+ return context.contentResolver.query(+ TvContract.Channels.CONTENT_URI,+ arrayOf(BaseColumns._ID, CHANNEL_COLUMN_INPUT_ID, CHANNEL_COLUMN_INTERNAL_PROVIDER_ID),null,null,null)?.use { cursor ->val idIndex = cursor.getColumnIndexOrThrow(BaseColumns._ID)- while (cursor.moveToNext()) {- resolver.delete(- ContentUris.withAppendedId(TvContract.Programs.CONTENT_URI, cursor.getLong(idIndex)),- null,- null- )- }- }-- programs- .sortedBy { it.startTime }- .take(MAX_PROGRAMS_PER_CHANNEL)- .forEach { program ->- try {- resolver.insert(- TvContract.Programs.CONTENT_URI,- buildProgramValues(activeChannelId, providerId, channel, program)- )- } catch (throwable: Throwable) {- if (!channelExists(resolver, activeChannelId)) {- val recoveredChannelId = ensureChannel(resolver, null, providerId, channel) ?: return@forEach- existingChannelIds[channelKey(channel)] = recoveredChannelId- activeChannelId = recoveredChannelId- resolver.insert(- TvContract.Programs.CONTENT_URI,- buildProgramValues(activeChannelId, providerId, channel, program)- )- } else {- throw throwable+ val inputIdIndex = cursor.getColumnIndexOrThrow(CHANNEL_COLUMN_INPUT_ID)+ val keyIndex = cursor.getColumnIndexOrThrow(CHANNEL_COLUMN_INTERNAL_PROVIDER_ID)+ buildMap {+ while (cursor.moveToNext()) {+ if (cursor.getString(inputIdIndex) == targetInputId) {+ put(cursor.getString(keyIndex), cursor.getLong(idIndex))}}}+ }.orEmpty()}- private fun channelExists(resolver: ContentResolver, channelId: Long): Boolean =- resolver.query(- ContentUris.withAppendedId(TvContract.Channels.CONTENT_URI, channelId),- arrayOf(BaseColumns._ID),- null,- null,- null- )?.use { it.moveToFirst() } == true-- private fun buildChannelValues(providerId: Long, channel: Channel): ContentValues = ContentValues().apply {+ private fun buildChannelValues(provider: Provider, channel: Channel): ContentValues = ContentValues().apply {put(CHANNEL_COLUMN_INPUT_ID, inputId())put(CHANNEL_COLUMN_TYPE, TvContract.Channels.TYPE_OTHER)put(CHANNEL_COLUMN_SERVICE_TYPE, TvContract.Channels.SERVICE_TYPE_AUDIO_VIDEO)put(CHANNEL_COLUMN_DISPLAY_NUMBER, channel.number.toString())put(CHANNEL_COLUMN_DISPLAY_NAME, channel.name)put(CHANNEL_COLUMN_DESCRIPTION, channel.categoryName ?: "IPTV")- put(CHANNEL_COLUMN_INTERNAL_PROVIDER_ID, channelKey(channel))- put(CHANNEL_COLUMN_INTERNAL_PROVIDER_DATA, encodeChannelData(providerId, channel))+ put(CHANNEL_COLUMN_INTERNAL_PROVIDER_ID, stableTvChannelKey(provider, channel))+ put(CHANNEL_COLUMN_INTERNAL_PROVIDER_DATA, encodeChannelData(provider.id, channel))put(CHANNEL_COLUMN_APP_LINK_INTENT_URI, buildChannelIntent(channel).toUri(Intent.URI_INTENT_SCHEME))}@@ -254,23 +265,31 @@ class TvInputChannelSyncManager @Inject constructor(.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP)private fun deleteManagedChannels() {- loadExistingChannels().values.forEach(::deleteChannel)- }-- private fun deleteChannel(channelId: Long) {- context.contentResolver.delete(- ContentUris.withAppendedId(TvContract.Channels.CONTENT_URI, channelId),- null,- null- )+ val operations = loadExistingChannels().values.map { channelId ->+ ContentProviderOperation.newDelete(+ ContentUris.withAppendedId(TvContract.Channels.CONTENT_URI, channelId)+ ).build()+ }+ applyBatches(operations, "channel deletions")}private fun inputId(): String = ComponentName(context, StreamVaultTvInputService::class.java).flattenToShortString()- private fun channelKey(channel: Channel): String = "${channel.providerId}:${channel.id}"-private fun encodeChannelData(providerId: Long, channel: Channel): String =- listOf(providerId, channel.id, channel.epgChannelId.orEmpty()).joinToString(ENTRY_SEPARATOR)+ listOf(+ providerId,+ channel.id,+ channel.epgChannelId.orEmpty(),+ sha256Prefix(+ listOf(+ channel.streamId,+ channel.number,+ channel.name,+ channel.categoryName.orEmpty(),+ channel.streamUrl+ ).joinToString("|")+ )+ ).joinToString(ENTRY_SEPARATOR)private companion object {const val TAG = "TvInputChannelSync"@@ -291,6 +310,8 @@ class TvInputChannelSyncManager @Inject constructor(const val PROGRAM_COLUMN_END_TIME_UTC_MILLIS = "end_time_utc_millis"const val PROGRAM_COLUMN_INTERNAL_PROVIDER_DATA = "internal_provider_data"const val EPG_QUERY_CHUNK_SIZE = 200+ const val PROGRAM_QUERY_CHANNEL_CHUNK_SIZE = 500+ const val CONTENT_PROVIDER_BATCH_SIZE = 200const val MAX_PROGRAMS_PER_CHANNEL = 24const val PROGRAM_LOOKBACK_MS = 3 * 60 * 60 * 1000Lconst val PROGRAM_LOOKAHEAD_MS = 18 * 60 * 60 * 1000L@@ -299,6 +320,46 @@ class TvInputChannelSyncManager @Inject constructor(}}+internal fun stableTvChannelKey(provider: Provider, channel: Channel): String {+ val normalizedUrl = runCatching {+ val uri = URI(provider.serverUrl.trim())+ val scheme = uri.scheme?.lowercase(Locale.ROOT).orEmpty()+ val host = uri.host?.lowercase(Locale.ROOT).orEmpty()+ val port = when {+ uri.port < 0 -> ""+ scheme == "http" && uri.port == 80 -> ""+ scheme == "https" && uri.port == 443 -> ""+ else -> ":${uri.port}"+ }+ "$scheme://$host$port${uri.rawPath.orEmpty().trimEnd('/')}"+ }.getOrElse { provider.serverUrl.trim().trimEnd('/').lowercase(Locale.ROOT) }+ val providerIdentity = listOf(+ normalizedUrl,+ provider.username.trim(),+ provider.type.name,+ provider.stalkerMacAddress.trim().uppercase(Locale.ROOT)+ ).joinToString("|")+ val providerHash = sha256Prefix(providerIdentity)+ val remoteStreamId = channel.streamId.takeIf { it != 0L }+ ?: error("TV input channel '${channel.name}' has no portable stream identity")+ return "$providerHash:$remoteStreamId"+}++private fun stableTvProgramKey(provider: Provider, channel: Channel, program: Program): String {+ val channelKey = stableTvChannelKey(provider, channel)+ val contentHash = sha256Prefix(+ listOf(program.title, program.description.orEmpty()).joinToString("|"),+ byteCount = 6+ )+ return "$channelKey:${program.startTime}:${program.endTime}:$contentHash"+}++private fun sha256Prefix(value: String, byteCount: Int = 12): String =+ MessageDigest.getInstance("SHA-256")+ .digest(value.toByteArray(Charsets.UTF_8))+ .take(byteCount)+ .joinToString("") { byte -> "%02x".format(byte) }+internal fun shouldReplaceTvPrograms(channel: Channel, programs: List<Program>): Boolean {if (programs.isNotEmpty()) return truereturn channel.epgChannelId.isNullOrBlank()diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsBackupAboutSections.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsBackupAboutSections.ktindex 486e8bd8..d9229df7 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsBackupAboutSections.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsBackupAboutSections.kt@@ -30,6 +30,8 @@ import com.streamvault.app.ui.theme.Secondaryimport com.streamvault.domain.manager.DriveAuthStateinternal fun LazyListScope.settingsBackupSection(+ uiState: SettingsUiState,+ viewModel: SettingsViewModel,onCreateBackup: () -> Unit,onManageLocalBackups: () -> Unit,onShareBackup: () -> Unit,@@ -75,6 +77,71 @@ internal fun LazyListScope.settingsBackupSection(onClick = onRestoreBackup,modifier = Modifier.fillMaxWidth())+ uiState.backupRestoreJobs+ .filter { job -> job.status != "COMPLETE" || job.providers.any { provider -> provider.items.any { it.status != "APPLIED" && it.status != "DISMISSED" } } }+ .forEach { job ->+ Column(+ verticalArrangement = Arrangement.spacedBy(8.dp),+ modifier = Modifier.fillMaxWidth()+ ) {+ Text(+ text = "Restore ${job.jobId.take(8)} · ${job.status}",+ style = MaterialTheme.typography.titleMedium,+ color = OnSurface+ )+ job.providers.forEach { provider ->+ val waiting = provider.pendingCount + provider.unresolvedCount + provider.failedCount+ Text(+ text = "${provider.providerIdentityKey.substringBefore('|')} — " ++ "${provider.appliedCount} applied, $waiting waiting (${provider.failedCount} failed)",+ color = OnSurfaceDim+ )+ Row(+ horizontalArrangement = Arrangement.spacedBy(8.dp),+ modifier = Modifier.fillMaxWidth()+ ) {+ provider.localProviderId?.let { providerId ->+ BackupActionCard(+ icon = "↻",+ title = "Retry",+ subtitle = "Try available catalog data",+ accent = Primary,+ onClick = { viewModel.retryRestoreProvider(providerId) },+ modifier = Modifier.weight(1f)+ )+ }+ BackupActionCard(+ icon = "×",+ title = "Dismiss provider",+ subtitle = "Discard unresolved instructions",+ accent = Secondary,+ onClick = { viewModel.dismissRestoreProvider(job.jobId, provider.providerIdentityKey) },+ modifier = Modifier.weight(1f)+ )+ }+ provider.items+ .filter { it.status == "UNRESOLVED" || it.status == "FAILED_RETRYABLE" }+ .forEach { item ->+ BackupActionCard(+ icon = "!",+ title = "${item.section}${item.contentType?.let { " · $it" }.orEmpty()}",+ subtitle = item.lastError ?: item.status,+ accent = Secondary,+ onClick = { viewModel.dismissRestoreItem(item.id) },+ modifier = Modifier.fillMaxWidth()+ )+ }+ }+ BackupActionCard(+ icon = "×",+ title = "Dismiss entire restore",+ subtitle = "Discard all remaining instructions",+ accent = Secondary,+ onClick = { viewModel.dismissRestoreJob(job.jobId) },+ modifier = Modifier.fillMaxWidth()+ )+ }+ }BackupActionCard(icon = "≡",title = stringResource(R.string.settings_manage_local_backups),diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsBackupActions.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsBackupActions.ktindex eba51882..4a78c5c0 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsBackupActions.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsBackupActions.kt@@ -159,9 +159,9 @@ internal class SettingsBackupActions(scope.launch {val result = importBackup.confirm(ImportBackupCommand(uriString, plan))uiState.update { state ->- val completed = (result as? ImportBackupResult.Success)- ?.result- ?.outcome == BackupRestoreOutcome.COMPLETE+ val importResult = (result as? ImportBackupResult.Success)?.result+ val completed = importResult?.outcome == BackupRestoreOutcome.COMPLETE ||+ importResult?.outcome == BackupRestoreOutcome.WAITING_FOR_SYNCstate.copy(isImportingBackup = false,isSyncing = false,@@ -174,14 +174,39 @@ internal class SettingsBackupActions(// the user can retry the same durable checkpoint instead of starting over.backupPreview = if (completed) null else state.backupPreview,pendingBackupUri = if (completed) null else state.pendingBackupUri,- backupImportPlan = if (completed) BackupImportPlan() else state.backupImportPlan+ backupImportPlan = if (completed) BackupImportPlan() else state.backupImportPlan,+ pendingRestoreJobId = importResult?.restoreJobId,+ pendingRestoreProviders = importResult?.affectedProviders.orEmpty(),+ selectedRestoreProviderIndices = emptySet())}if (result is ImportBackupResult.Success &&- result.result.outcome == BackupRestoreOutcome.COMPLETE+ (result.result.outcome == BackupRestoreOutcome.COMPLETE ||+ result.result.outcome == BackupRestoreOutcome.WAITING_FOR_SYNC)) {onSuccess?.invoke()}}}++ fun toggleRestoreProvider(index: Int) {+ uiState.update { state ->+ val selected = state.selectedRestoreProviderIndices+ state.copy(+ selectedRestoreProviderIndices = if (index in selected) selected - index else selected + index+ )+ }+ }++ fun selectAllRestoreProviders() {+ uiState.update { state ->+ state.copy(selectedRestoreProviderIndices = state.pendingRestoreProviders.indices.toSet())+ }+ }++ fun dismissRestoreSyncChooser() {+ uiState.update { state ->+ state.copy(pendingRestoreProviders = emptyList(), selectedRestoreProviderIndices = emptySet())+ }+ }}diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsContentPane.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsContentPane.ktindex 2bcdff3b..6c5d60c6 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsContentPane.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsContentPane.kt@@ -169,6 +169,8 @@ internal fun SettingsContentPane()} else if (dialogState.selectedCategory == 5) {settingsBackupSection(+ uiState = uiState,+ viewModel = viewModel,onCreateBackup = onCreateBackup,onManageLocalBackups = onManageLocalBackups,onShareBackup = onShareBackup,diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsScreenDialogs.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsScreenDialogs.ktindex 51785dde..b24f7f42 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsScreenDialogs.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsScreenDialogs.kt@@ -6,6 +6,7 @@ import android.view.KeyEventimport androidx.compose.foundation.layout.Boximport androidx.compose.foundation.layout.Arrangementimport androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Rowimport androidx.compose.foundation.layout.fillMaxWidthimport androidx.compose.foundation.layout.heightInimport androidx.compose.foundation.shape.RoundedCornerShape@@ -14,6 +15,7 @@ import androidx.compose.foundation.rememberScrollStateimport androidx.compose.foundation.verticalScrollimport androidx.compose.material3.AlertDialogimport androidx.compose.material3.TextButton+import androidx.compose.material3.Checkboximport androidx.compose.runtime.Composableimport androidx.compose.runtime.LaunchedEffectimport androidx.compose.runtime.derivedStateOf@@ -290,6 +292,37 @@ internal fun SettingsScreenDialogs()}+ if (uiState.pendingRestoreProviders.isNotEmpty()) {+ AlertDialog(+ onDismissRequest = viewModel::restoreSyncLater,+ title = { Text("Restore waiting for sync") },+ text = {+ Column {+ Text("Choose providers to sync now. Nothing is selected by default; pending restore data is kept if you choose Later.")+ uiState.pendingRestoreProviders.forEachIndexed { index, provider ->+ Row {+ Checkbox(+ checked = index in uiState.selectedRestoreProviderIndices,+ onCheckedChange = { viewModel.toggleRestoreSyncProvider(index) }+ )+ Text(provider.serverUrl + provider.username.takeIf { it.isNotBlank() }?.let { " ($it)" }.orEmpty())+ }+ }+ TextButton(onClick = viewModel::selectAllRestoreSyncProviders) { Text("Select all") }+ }+ },+ confirmButton = {+ TextButton(+ enabled = uiState.selectedRestoreProviderIndices.isNotEmpty(),+ onClick = viewModel::syncSelectedRestoreProviders+ ) { Text("Sync selected") }+ },+ dismissButton = {+ TextButton(onClick = viewModel::restoreSyncLater) { Text("Later") }+ }+ )+ }+if (dialogState.showClearHistoryDialog) {AlertDialog(onDismissRequest = { dialogState.showClearHistoryDialog = false },diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsSyncActions.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsSyncActions.ktindex 1d940800..3aec9b7f 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsSyncActions.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsSyncActions.kt@@ -3,6 +3,7 @@ package com.streamvault.app.ui.screens.settingsimport android.app.Applicationimport com.streamvault.app.Rimport com.streamvault.app.tvinput.TvInputChannelSyncManager+import com.streamvault.app.tvinput.TvInputCatalogRefreshWorkerimport com.streamvault.data.sync.ProviderSyncCommandsimport com.streamvault.data.sync.SyncRepairSectionimport com.streamvault.domain.model.ProviderType@@ -232,7 +233,7 @@ internal class SettingsSyncActions(it == appContext.getString(R.string.settings_sync_option_tv)}) {- tvInputChannelSyncManager.refreshTvInputCatalog()+ TvInputCatalogRefreshWorker.enqueue(appContext)}uiState.update { state ->diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsUiStateModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsUiStateModel.ktindex c92b1cd6..3f54d502 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsUiStateModel.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsUiStateModel.kt@@ -5,6 +5,8 @@ import com.streamvault.app.ui.model.LiveTvQuickFilterVisibilityModeimport com.streamvault.app.ui.model.VodViewModeimport com.streamvault.domain.manager.BackupImportPlanimport com.streamvault.domain.manager.BackupPreview+import com.streamvault.domain.manager.BackupProviderReference+import com.streamvault.domain.manager.BackupRestoreJobStatusimport com.streamvault.domain.manager.DriveAuthStateimport com.streamvault.domain.manager.DriveBackupSnapshotimport com.streamvault.domain.manager.DriveSignInRequest@@ -116,6 +118,10 @@ data class SettingsUiState(val backupPreview: BackupPreview? = null,val pendingBackupUri: String? = null,val backupImportPlan: BackupImportPlan = BackupImportPlan(),+ val pendingRestoreJobId: String? = null,+ val pendingRestoreProviders: List<BackupProviderReference> = emptyList(),+ val selectedRestoreProviderIndices: Set<Int> = emptySet(),+ val backupRestoreJobs: List<BackupRestoreJobStatus> = emptyList(),// --- Drive sync (M2) ---val driveAuthState: DriveAuthState = DriveAuthState.SignedOut,val driveSyncStatus: DriveSyncStatus = DriveSyncStatus(),diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsViewModel.ktindex 255adb80..6f33c1df 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsViewModel.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsViewModel.kt@@ -29,6 +29,7 @@ import com.streamvault.domain.manager.BackupConflictStrategyimport com.streamvault.domain.manager.BackupImportPlanimport com.streamvault.domain.manager.BackupManagerimport com.streamvault.domain.manager.BackupPreview+import com.streamvault.domain.manager.BackupRestoreStatusStoreimport com.streamvault.domain.manager.DriveBackupSyncManagerimport com.streamvault.domain.manager.ParentalControlManagerimport com.streamvault.domain.manager.RecordingManager@@ -109,6 +110,7 @@ class SettingsViewModel @Inject constructor(private val preferencesRepository: PreferencesRepository,private val internetSpeedTestRunner: InternetSpeedTestRunner,private val backupManager: BackupManager,+ private val backupRestoreStatusStore: BackupRestoreStatusStore,private val driveBackupSyncManager: DriveBackupSyncManager,private val recordingManager: RecordingManager,private val parentalControlManager: ParentalControlManager,@@ -243,6 +245,11 @@ class SettingsViewModel @Inject constructor(uiState = _uiState)driveBackupActions.observeAuthState(viewModelScope)+ viewModelScope.launch {+ backupRestoreStatusStore.observeRestoreJobs().collect { jobs ->+ _uiState.update { it.copy(backupRestoreJobs = jobs) }+ }+ }}fun refreshCrashReport() {@@ -1192,6 +1199,63 @@ class SettingsViewModel @Inject constructor(}}+ fun toggleRestoreSyncProvider(index: Int) = backupActions.toggleRestoreProvider(index)++ fun selectAllRestoreSyncProviders() = backupActions.selectAllRestoreProviders()++ fun restoreSyncLater() = backupActions.dismissRestoreSyncChooser()++ fun retryRestoreProvider(providerId: Long) {+ viewModelScope.launch { backupRestoreStatusStore.retryProviders(setOf(providerId)) }+ }++ fun dismissRestoreItem(itemId: Long) {+ viewModelScope.launch { backupRestoreStatusStore.dismissItem(itemId) }+ }++ fun dismissRestoreProvider(jobId: String, providerIdentityKey: String) {+ viewModelScope.launch { backupRestoreStatusStore.dismissProvider(jobId, providerIdentityKey) }+ }++ fun dismissRestoreJob(jobId: String) {+ viewModelScope.launch { backupRestoreStatusStore.dismissRestore(jobId) }+ }++ fun syncSelectedRestoreProviders() {+ val state = _uiState.value+ val references = state.selectedRestoreProviderIndices.mapNotNull(state.pendingRestoreProviders::getOrNull)+ if (references.isEmpty()) return+ viewModelScope.launch {+ _uiState.update { it.copy(isSyncing = true, syncProgress = "Syncing restored providers…", syncCanCancel = false) }+ val failures = mutableListOf<String>()+ references.forEach { reference ->+ val provider = _uiState.value.providers.singleOrNull { candidate ->+ candidate.serverUrl.trim().trimEnd('/').equals(reference.serverUrl.trim().trimEnd('/'), true) &&+ candidate.username.trim() == reference.username.trim() &&+ (reference.providerType == null || candidate.type == reference.providerType) &&+ candidate.stalkerMacAddress.trim().equals(reference.stalkerMacAddress.orEmpty().trim(), true)+ }+ if (provider == null) {+ failures += reference.serverUrl+ } else if (syncManager.sync(provider.id, force = true) is Result.Error) {+ failures += provider.name+ }+ }+ backupActions.dismissRestoreSyncChooser()+ _uiState.update {+ it.copy(+ isSyncing = false,+ syncProgress = null,+ userMessage = if (failures.isEmpty()) {+ "Selected restored providers synced successfully"+ } else {+ "Some restored providers could not sync: ${failures.joinToString()}"+ }+ )+ }+ }+ }+fun beginDriveSignIn(launcher: ActivityResultLauncher<Intent>) {driveBackupActions.beginSignIn(viewModelScope, launcher)}diff --git a/app/src/test/java/com/streamvault/app/tvinput/TvInputChannelSyncManagerTest.kt b/app/src/test/java/com/streamvault/app/tvinput/TvInputChannelSyncManagerTest.ktindex 0d92a6af..d5f87a53 100644--- a/app/src/test/java/com/streamvault/app/tvinput/TvInputChannelSyncManagerTest.kt+++ b/app/src/test/java/com/streamvault/app/tvinput/TvInputChannelSyncManagerTest.kt@@ -3,10 +3,30 @@ package com.streamvault.app.tvinputimport com.google.common.truth.Truth.assertThatimport com.streamvault.domain.model.Channelimport com.streamvault.domain.model.Program+import com.streamvault.domain.model.LegacyProvider+import com.streamvault.domain.model.ProviderTypeimport org.junit.Testclass TvInputChannelSyncManagerTest {+ @Test+ fun stableTvChannelKey_survivesChangedLocalProviderAndChannelIds() {+ val beforeProvider = LegacyProvider(+ id = 1,+ name = "Provider",+ type = ProviderType.XTREAM_CODES,+ serverUrl = "HTTPS://EXAMPLE.COM/",+ username = "user",+ password = "pass"+ )+ val afterProvider = beforeProvider.copy(id = 99, serverUrl = "https://example.com")+ val beforeChannel = Channel(id = 5, streamId = 42, name = "News", providerId = 1)+ val afterChannel = beforeChannel.copy(id = 500, providerId = 99)++ assertThat(stableTvChannelKey(beforeProvider, beforeChannel))+ .isEqualTo(stableTvChannelKey(afterProvider, afterChannel))+ }+@Testfun shouldReplaceTvPrograms_preservesGuideWhenMappedChannelHasEmptySnapshot() {val channel = Channel(@@ -50,4 +70,4 @@ class TvInputChannelSyncManagerTest {assertThat(shouldReplaceTvPrograms(channel, emptyList())).isTrue()}-}\ No newline at end of file+}diff --git a/app/src/test/java/com/streamvault/app/ui/screens/home/HomeViewModelTest.kt b/app/src/test/java/com/streamvault/app/ui/screens/home/HomeViewModelTest.ktindex 1eb18fa1..6db7065d 100644--- a/app/src/test/java/com/streamvault/app/ui/screens/home/HomeViewModelTest.kt+++ b/app/src/test/java/com/streamvault/app/ui/screens/home/HomeViewModelTest.kt@@ -48,6 +48,7 @@ class HomeViewModelTest {private val channelRepository: ChannelRepository = mock()private val categoryRepository: CategoryRepository = mock()private val favoriteRepository: FavoriteRepository = mock()+ private val m3uClassificationRepository: M3uClassificationRepository = mock()private val preferencesRepository: PreferencesRepository = mock()private val epgRepository: EpgRepository = mock()private val playbackHistoryRepository: PlaybackHistoryRepository = mock()@@ -134,6 +135,7 @@ class HomeViewModelTest {channelRepository = channelRepository,categoryRepository = categoryRepository,favoriteRepository = favoriteRepository,+ m3uClassificationRepository = m3uClassificationRepository,preferencesRepository = preferencesRepository,epgRepository = epgRepository,playbackHistoryRepository = playbackHistoryRepository,diff --git a/data/schemas/com.streamvault.data.local.StreamVaultDatabase/77.json b/data/schemas/com.streamvault.data.local.StreamVaultDatabase/77.jsonnew file mode 100644index 00000000..a0c1642e--- /dev/null+++ b/data/schemas/com.streamvault.data.local.StreamVaultDatabase/77.json@@ -0,0 +1,7079 @@+{+ "formatVersion": 1,+ "database": {+ "version": 77,+ "identityHash": "1a6647887571bedb511009682c1b4129",+ "entities": [+ {+ "tableName": "providers",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `type` TEXT NOT NULL, `is_active` INTEGER NOT NULL, `status` TEXT NOT NULL, `last_synced_at` INTEGER NOT NULL, `created_at` INTEGER NOT NULL)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "type",+ "columnName": "type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "isActive",+ "columnName": "is_active",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "status",+ "columnName": "status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "lastSyncedAt",+ "columnName": "last_synced_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_providers_type",+ "unique": false,+ "columnNames": [+ "type"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_providers_type` ON `${TABLE_NAME}` (`type`)"+ },+ {+ "name": "index_providers_is_active",+ "unique": false,+ "columnNames": [+ "is_active"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_providers_is_active` ON `${TABLE_NAME}` (`is_active`)"+ }+ ]+ },+ {+ "tableName": "provider_configs",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `type` TEXT NOT NULL, `schema_version` INTEGER NOT NULL, `configuration_generation` INTEGER NOT NULL, `identity_key` TEXT NOT NULL, `encrypted_config_json` TEXT NOT NULL, `guide_source_policy` TEXT NOT NULL, `channel_logo_source_policy` TEXT NOT NULL, `updated_at` INTEGER NOT NULL, PRIMARY KEY(`provider_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "type",+ "columnName": "type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "schemaVersion",+ "columnName": "schema_version",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "configurationGeneration",+ "columnName": "configuration_generation",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "identityKey",+ "columnName": "identity_key",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "encryptedConfigJson",+ "columnName": "encrypted_config_json",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "guideSourcePolicy",+ "columnName": "guide_source_policy",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "channelLogoSourcePolicy",+ "columnName": "channel_logo_source_policy",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "provider_id"+ ]+ },+ "indices": [+ {+ "name": "index_provider_configs_provider_id",+ "unique": true,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_provider_configs_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_provider_configs_identity_key",+ "unique": true,+ "columnNames": [+ "identity_key"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_provider_configs_identity_key` ON `${TABLE_NAME}` (`identity_key`)"+ },+ {+ "name": "index_provider_configs_type",+ "unique": false,+ "columnNames": [+ "type"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_provider_configs_type` ON `${TABLE_NAME}` (`type`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "provider_account_runtime",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `max_connections` INTEGER NOT NULL, `expiration_date` INTEGER, `api_version` TEXT, `allowed_output_formats_json` TEXT NOT NULL, `catalog_layout` TEXT NOT NULL, `catalog_layout_detection_version` INTEGER NOT NULL, `observed_at` INTEGER NOT NULL, PRIMARY KEY(`provider_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "maxConnections",+ "columnName": "max_connections",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "expirationDate",+ "columnName": "expiration_date",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "apiVersion",+ "columnName": "api_version",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "allowedOutputFormatsJson",+ "columnName": "allowed_output_formats_json",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "catalogLayout",+ "columnName": "catalog_layout",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "catalogLayoutDetectionVersion",+ "columnName": "catalog_layout_detection_version",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "observedAt",+ "columnName": "observed_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "provider_id"+ ]+ },+ "indices": [+ {+ "name": "index_provider_account_runtime_provider_id",+ "unique": true,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_provider_account_runtime_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "channels",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `stream_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `logo_url` TEXT, `group_title` TEXT, `category_id` INTEGER, `category_name` TEXT, `stream_url` TEXT NOT NULL, `epg_channel_id` TEXT, `number` INTEGER NOT NULL, `catch_up_supported` INTEGER NOT NULL, `catch_up_days` INTEGER NOT NULL, `catchUpSource` TEXT, `provider_id` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, `logical_group_id` TEXT NOT NULL, `error_count` INTEGER NOT NULL, `quality_options_json` TEXT, `sync_fingerprint` TEXT NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "streamId",+ "columnName": "stream_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "logoUrl",+ "columnName": "logo_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "groupTitle",+ "columnName": "group_title",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "categoryName",+ "columnName": "category_name",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "epgChannelId",+ "columnName": "epg_channel_id",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "number",+ "columnName": "number",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "catchUpSupported",+ "columnName": "catch_up_supported",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "catchUpDays",+ "columnName": "catch_up_days",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "catchUpSource",+ "columnName": "catchUpSource",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isUserProtected",+ "columnName": "is_user_protected",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "logicalGroupId",+ "columnName": "logical_group_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "errorCount",+ "columnName": "error_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "qualityOptionsJson",+ "columnName": "quality_options_json",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "syncFingerprint",+ "columnName": "sync_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_channels_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_channels_provider_id_category_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "category_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_provider_id_category_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`)"+ },+ {+ "name": "index_channels_provider_id_stream_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "stream_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_channels_provider_id_stream_id` ON `${TABLE_NAME}` (`provider_id`, `stream_id`)"+ },+ {+ "name": "index_channels_logical_group_id",+ "unique": false,+ "columnNames": [+ "logical_group_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_logical_group_id` ON `${TABLE_NAME}` (`logical_group_id`)"+ },+ {+ "name": "index_channels_provider_id_category_id_logical_group_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "category_id",+ "logical_group_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_provider_id_category_id_logical_group_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`, `logical_group_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "channel_preferences",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `channel_id` INTEGER NOT NULL, `aspect_ratio` TEXT, `audio_video_offset_ms` INTEGER, `updated_at` INTEGER NOT NULL, FOREIGN KEY(`channel_id`) REFERENCES `channels`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelId",+ "columnName": "channel_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "aspectRatio",+ "columnName": "aspect_ratio",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "audioVideoOffsetMs",+ "columnName": "audio_video_offset_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_channel_preferences_channel_id",+ "unique": true,+ "columnNames": [+ "channel_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_channel_preferences_channel_id` ON `${TABLE_NAME}` (`channel_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "channels",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "channel_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "channels_fts",+ "createSql": "CREATE VIRTUAL TABLE IF NOT EXISTS `${TABLE_NAME}` USING FTS4(`name` TEXT NOT NULL, content=`channels`)",+ "fields": [+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": []+ },+ "ftsVersion": "FTS4",+ "ftsOptions": {+ "tokenizer": "simple",+ "tokenizerArgs": [],+ "contentTable": "channels",+ "languageIdColumnName": "",+ "matchInfo": "FTS4",+ "notIndexedColumns": [],+ "prefixSizes": [],+ "preferredOrder": "ASC"+ },+ "contentSyncTriggers": [+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_BEFORE_UPDATE BEFORE UPDATE ON `channels` BEGIN DELETE FROM `channels_fts` WHERE `docid`=OLD.`rowid`; END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_BEFORE_DELETE BEFORE DELETE ON `channels` BEGIN DELETE FROM `channels_fts` WHERE `docid`=OLD.`rowid`; END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_AFTER_UPDATE AFTER UPDATE ON `channels` BEGIN INSERT INTO `channels_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_AFTER_INSERT AFTER INSERT ON `channels` BEGIN INSERT INTO `channels_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END"+ ]+ },+ {+ "tableName": "movies",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `stream_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `poster_url` TEXT, `backdrop_url` TEXT, `category_id` INTEGER, `category_name` TEXT, `stream_url` TEXT NOT NULL, `container_extension` TEXT, `plot` TEXT, `cast` TEXT, `director` TEXT, `genre` TEXT, `release_date` TEXT, `duration` TEXT, `duration_seconds` INTEGER NOT NULL, `rating` REAL NOT NULL, `year` TEXT, `tmdb_id` INTEGER, `youtube_trailer` TEXT, `provider_id` INTEGER NOT NULL, `watch_progress` INTEGER NOT NULL, `watch_count` INTEGER NOT NULL, `last_watched_at` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, `added_at` INTEGER NOT NULL, `cache_state` TEXT NOT NULL, `detail_hydrated_at` INTEGER NOT NULL, `remote_stale_at` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "streamId",+ "columnName": "stream_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "posterUrl",+ "columnName": "poster_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "backdropUrl",+ "columnName": "backdrop_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "categoryName",+ "columnName": "category_name",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "containerExtension",+ "columnName": "container_extension",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "plot",+ "columnName": "plot",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "cast",+ "columnName": "cast",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "director",+ "columnName": "director",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "genre",+ "columnName": "genre",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "releaseDate",+ "columnName": "release_date",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "duration",+ "columnName": "duration",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "durationSeconds",+ "columnName": "duration_seconds",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "rating",+ "columnName": "rating",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "year",+ "columnName": "year",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "tmdbId",+ "columnName": "tmdb_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "youtubeTrailer",+ "columnName": "youtube_trailer",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "watchProgress",+ "columnName": "watch_progress",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "watchCount",+ "columnName": "watch_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastWatchedAt",+ "columnName": "last_watched_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isUserProtected",+ "columnName": "is_user_protected",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "syncFingerprint",+ "columnName": "sync_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "addedAt",+ "columnName": "added_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "cacheState",+ "columnName": "cache_state",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "detailHydratedAt",+ "columnName": "detail_hydrated_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "remoteStaleAt",+ "columnName": "remote_stale_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_movies_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_movies_provider_id_category_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "category_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id_category_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`)"+ },+ {+ "name": "index_movies_provider_id_stream_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "stream_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_movies_provider_id_stream_id` ON `${TABLE_NAME}` (`provider_id`, `stream_id`)"+ },+ {+ "name": "index_movies_provider_id_name_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "name",+ "id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id_name_id` ON `${TABLE_NAME}` (`provider_id`, `name`, `id`)"+ },+ {+ "name": "index_movies_provider_id_category_id_name_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "category_id",+ "name",+ "id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id_category_id_name_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`, `name`, `id`)"+ },+ {+ "name": "index_movies_provider_id_rating_name_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "rating",+ "name",+ "id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id_rating_name_id` ON `${TABLE_NAME}` (`provider_id`, `rating`, `name`, `id`)"+ },+ {+ "name": "index_movies_provider_id_added_at_release_date_name_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "added_at",+ "release_date",+ "name",+ "id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id_added_at_release_date_name_id` ON `${TABLE_NAME}` (`provider_id`, `added_at`, `release_date`, `name`, `id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "movies_fts",+ "createSql": "CREATE VIRTUAL TABLE IF NOT EXISTS `${TABLE_NAME}` USING FTS4(`name` TEXT NOT NULL, content=`movies`)",+ "fields": [+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": []+ },+ "ftsVersion": "FTS4",+ "ftsOptions": {+ "tokenizer": "simple",+ "tokenizerArgs": [],+ "contentTable": "movies",+ "languageIdColumnName": "",+ "matchInfo": "FTS4",+ "notIndexedColumns": [],+ "prefixSizes": [],+ "preferredOrder": "ASC"+ },+ "contentSyncTriggers": [+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_movies_fts_BEFORE_UPDATE BEFORE UPDATE ON `movies` BEGIN DELETE FROM `movies_fts` WHERE `docid`=OLD.`rowid`; END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_movies_fts_BEFORE_DELETE BEFORE DELETE ON `movies` BEGIN DELETE FROM `movies_fts` WHERE `docid`=OLD.`rowid`; END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_movies_fts_AFTER_UPDATE AFTER UPDATE ON `movies` BEGIN INSERT INTO `movies_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_movies_fts_AFTER_INSERT AFTER INSERT ON `movies` BEGIN INSERT INTO `movies_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END"+ ]+ },+ {+ "tableName": "series",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `series_id` INTEGER NOT NULL, `provider_series_id` TEXT, `name` TEXT NOT NULL, `poster_url` TEXT, `backdrop_url` TEXT, `category_id` INTEGER, `category_name` TEXT, `plot` TEXT, `cast` TEXT, `director` TEXT, `genre` TEXT, `release_date` TEXT, `rating` REAL NOT NULL, `tmdb_id` INTEGER, `youtube_trailer` TEXT, `episode_run_time` TEXT, `last_modified` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, `cache_state` TEXT NOT NULL, `detail_hydrated_at` INTEGER NOT NULL, `remote_stale_at` INTEGER NOT NULL, `catalog_origin` TEXT NOT NULL, `episode_playback_template_url` TEXT, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "seriesId",+ "columnName": "series_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerSeriesId",+ "columnName": "provider_series_id",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "posterUrl",+ "columnName": "poster_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "backdropUrl",+ "columnName": "backdrop_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "categoryName",+ "columnName": "category_name",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "plot",+ "columnName": "plot",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "cast",+ "columnName": "cast",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "director",+ "columnName": "director",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "genre",+ "columnName": "genre",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "releaseDate",+ "columnName": "release_date",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "rating",+ "columnName": "rating",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "tmdbId",+ "columnName": "tmdb_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "youtubeTrailer",+ "columnName": "youtube_trailer",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "episodeRunTime",+ "columnName": "episode_run_time",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lastModified",+ "columnName": "last_modified",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isUserProtected",+ "columnName": "is_user_protected",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "syncFingerprint",+ "columnName": "sync_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "cacheState",+ "columnName": "cache_state",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "detailHydratedAt",+ "columnName": "detail_hydrated_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "remoteStaleAt",+ "columnName": "remote_stale_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "catalogOrigin",+ "columnName": "catalog_origin",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "episodePlaybackTemplateUrl",+ "columnName": "episode_playback_template_url",+ "affinity": "TEXT"+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_series_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_series_provider_id_category_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "category_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_provider_id_category_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`)"+ },+ {+ "name": "index_series_provider_id_series_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "series_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_series_provider_id_series_id` ON `${TABLE_NAME}` (`provider_id`, `series_id`)"+ },+ {+ "name": "index_series_provider_id_name_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "name",+ "id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_provider_id_name_id` ON `${TABLE_NAME}` (`provider_id`, `name`, `id`)"+ },+ {+ "name": "index_series_provider_id_category_id_name_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "category_id",+ "name",+ "id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_provider_id_category_id_name_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`, `name`, `id`)"+ },+ {+ "name": "index_series_provider_id_rating_name_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "rating",+ "name",+ "id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_provider_id_rating_name_id` ON `${TABLE_NAME}` (`provider_id`, `rating`, `name`, `id`)"+ },+ {+ "name": "index_series_provider_id_last_modified_name_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "last_modified",+ "name",+ "id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_provider_id_last_modified_name_id` ON `${TABLE_NAME}` (`provider_id`, `last_modified`, `name`, `id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "series_fts",+ "createSql": "CREATE VIRTUAL TABLE IF NOT EXISTS `${TABLE_NAME}` USING FTS4(`name` TEXT NOT NULL, content=`series`)",+ "fields": [+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": []+ },+ "ftsVersion": "FTS4",+ "ftsOptions": {+ "tokenizer": "simple",+ "tokenizerArgs": [],+ "contentTable": "series",+ "languageIdColumnName": "",+ "matchInfo": "FTS4",+ "notIndexedColumns": [],+ "prefixSizes": [],+ "preferredOrder": "ASC"+ },+ "contentSyncTriggers": [+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_series_fts_BEFORE_UPDATE BEFORE UPDATE ON `series` BEGIN DELETE FROM `series_fts` WHERE `docid`=OLD.`rowid`; END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_series_fts_BEFORE_DELETE BEFORE DELETE ON `series` BEGIN DELETE FROM `series_fts` WHERE `docid`=OLD.`rowid`; END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_series_fts_AFTER_UPDATE AFTER UPDATE ON `series` BEGIN INSERT INTO `series_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_series_fts_AFTER_INSERT AFTER INSERT ON `series` BEGIN INSERT INTO `series_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END"+ ]+ },+ {+ "tableName": "episodes",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `episode_id` INTEGER NOT NULL, `title` TEXT NOT NULL, `episode_number` INTEGER NOT NULL, `season_number` INTEGER NOT NULL, `stream_url` TEXT NOT NULL, `container_extension` TEXT, `cover_url` TEXT, `plot` TEXT, `duration` TEXT, `duration_seconds` INTEGER NOT NULL, `rating` REAL NOT NULL, `release_date` TEXT, `series_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `watch_progress` INTEGER NOT NULL, `last_watched_at` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`series_id`) REFERENCES `series`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "episodeId",+ "columnName": "episode_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "title",+ "columnName": "title",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "episodeNumber",+ "columnName": "episode_number",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "seasonNumber",+ "columnName": "season_number",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "containerExtension",+ "columnName": "container_extension",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "coverUrl",+ "columnName": "cover_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "plot",+ "columnName": "plot",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "duration",+ "columnName": "duration",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "durationSeconds",+ "columnName": "duration_seconds",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "rating",+ "columnName": "rating",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "releaseDate",+ "columnName": "release_date",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "seriesId",+ "columnName": "series_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "watchProgress",+ "columnName": "watch_progress",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastWatchedAt",+ "columnName": "last_watched_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isUserProtected",+ "columnName": "is_user_protected",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_episodes_series_id",+ "unique": false,+ "columnNames": [+ "series_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_episodes_series_id` ON `${TABLE_NAME}` (`series_id`)"+ },+ {+ "name": "index_episodes_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_episodes_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_episodes_provider_id_episode_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "episode_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_episodes_provider_id_episode_id` ON `${TABLE_NAME}` (`provider_id`, `episode_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ },+ {+ "table": "series",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "series_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "categories",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `category_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `parent_id` INTEGER, `type` TEXT NOT NULL, `provider_id` INTEGER NOT NULL, `provider_order` INTEGER NOT NULL DEFAULT 0, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "parentId",+ "columnName": "parent_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "type",+ "columnName": "type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerOrder",+ "columnName": "provider_order",+ "affinity": "INTEGER",+ "notNull": true,+ "defaultValue": "0"+ },+ {+ "fieldPath": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isUserProtected",+ "columnName": "is_user_protected",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "syncFingerprint",+ "columnName": "sync_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_categories_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_categories_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_categories_provider_id_type",+ "unique": false,+ "columnNames": [+ "provider_id",+ "type"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_categories_provider_id_type` ON `${TABLE_NAME}` (`provider_id`, `type`)"+ },+ {+ "name": "index_categories_provider_id_category_id_type",+ "unique": true,+ "columnNames": [+ "provider_id",+ "category_id",+ "type"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_categories_provider_id_category_id_type` ON `${TABLE_NAME}` (`provider_id`, `category_id`, `type`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "channel_import_stage",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`session_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `stream_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `logo_url` TEXT, `group_title` TEXT, `category_id` INTEGER, `category_name` TEXT, `stream_url` TEXT NOT NULL, `epg_channel_id` TEXT, `number` INTEGER NOT NULL, `catch_up_supported` INTEGER NOT NULL, `catch_up_days` INTEGER NOT NULL, `catchUpSource` TEXT, `is_adult` INTEGER NOT NULL, `logical_group_id` TEXT NOT NULL, `error_count` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, PRIMARY KEY(`session_id`, `provider_id`, `stream_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "sessionId",+ "columnName": "session_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "streamId",+ "columnName": "stream_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "logoUrl",+ "columnName": "logo_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "groupTitle",+ "columnName": "group_title",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "categoryName",+ "columnName": "category_name",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "epgChannelId",+ "columnName": "epg_channel_id",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "number",+ "columnName": "number",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "catchUpSupported",+ "columnName": "catch_up_supported",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "catchUpDays",+ "columnName": "catch_up_days",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "catchUpSource",+ "columnName": "catchUpSource",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "logicalGroupId",+ "columnName": "logical_group_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "errorCount",+ "columnName": "error_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "syncFingerprint",+ "columnName": "sync_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "session_id",+ "provider_id",+ "stream_id"+ ]+ },+ "indices": [+ {+ "name": "index_channel_import_stage_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channel_import_stage_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_channel_import_stage_session_id_provider_id",+ "unique": false,+ "columnNames": [+ "session_id",+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channel_import_stage_session_id_provider_id` ON `${TABLE_NAME}` (`session_id`, `provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "movie_import_stage",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`session_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `stream_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `poster_url` TEXT, `backdrop_url` TEXT, `category_id` INTEGER, `category_name` TEXT, `stream_url` TEXT NOT NULL, `container_extension` TEXT, `plot` TEXT, `cast` TEXT, `director` TEXT, `genre` TEXT, `release_date` TEXT, `duration` TEXT, `duration_seconds` INTEGER NOT NULL, `rating` REAL NOT NULL, `year` TEXT, `tmdb_id` INTEGER, `youtube_trailer` TEXT, `is_adult` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, `added_at` INTEGER NOT NULL, PRIMARY KEY(`session_id`, `provider_id`, `stream_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "sessionId",+ "columnName": "session_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "streamId",+ "columnName": "stream_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "posterUrl",+ "columnName": "poster_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "backdropUrl",+ "columnName": "backdrop_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "categoryName",+ "columnName": "category_name",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "containerExtension",+ "columnName": "container_extension",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "plot",+ "columnName": "plot",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "cast",+ "columnName": "cast",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "director",+ "columnName": "director",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "genre",+ "columnName": "genre",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "releaseDate",+ "columnName": "release_date",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "duration",+ "columnName": "duration",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "durationSeconds",+ "columnName": "duration_seconds",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "rating",+ "columnName": "rating",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "year",+ "columnName": "year",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "tmdbId",+ "columnName": "tmdb_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "youtubeTrailer",+ "columnName": "youtube_trailer",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "syncFingerprint",+ "columnName": "sync_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "addedAt",+ "columnName": "added_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "session_id",+ "provider_id",+ "stream_id"+ ]+ },+ "indices": [+ {+ "name": "index_movie_import_stage_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movie_import_stage_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_movie_import_stage_session_id_provider_id",+ "unique": false,+ "columnNames": [+ "session_id",+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movie_import_stage_session_id_provider_id` ON `${TABLE_NAME}` (`session_id`, `provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "series_import_stage",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`session_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `series_id` INTEGER NOT NULL, `provider_series_id` TEXT, `provider_series_key` TEXT NOT NULL, `name` TEXT NOT NULL, `poster_url` TEXT, `backdrop_url` TEXT, `category_id` INTEGER, `category_name` TEXT, `plot` TEXT, `cast` TEXT, `director` TEXT, `genre` TEXT, `release_date` TEXT, `rating` REAL NOT NULL, `tmdb_id` INTEGER, `youtube_trailer` TEXT, `episode_run_time` TEXT, `last_modified` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, PRIMARY KEY(`session_id`, `provider_id`, `provider_series_key`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "sessionId",+ "columnName": "session_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "seriesId",+ "columnName": "series_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerSeriesId",+ "columnName": "provider_series_id",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "providerSeriesKey",+ "columnName": "provider_series_key",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "posterUrl",+ "columnName": "poster_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "backdropUrl",+ "columnName": "backdrop_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "categoryName",+ "columnName": "category_name",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "plot",+ "columnName": "plot",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "cast",+ "columnName": "cast",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "director",+ "columnName": "director",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "genre",+ "columnName": "genre",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "releaseDate",+ "columnName": "release_date",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "rating",+ "columnName": "rating",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "tmdbId",+ "columnName": "tmdb_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "youtubeTrailer",+ "columnName": "youtube_trailer",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "episodeRunTime",+ "columnName": "episode_run_time",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lastModified",+ "columnName": "last_modified",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "syncFingerprint",+ "columnName": "sync_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "session_id",+ "provider_id",+ "provider_series_key"+ ]+ },+ "indices": [+ {+ "name": "index_series_import_stage_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_import_stage_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_series_import_stage_session_id_provider_id",+ "unique": false,+ "columnNames": [+ "session_id",+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_import_stage_session_id_provider_id` ON `${TABLE_NAME}` (`session_id`, `provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "category_import_stage",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`session_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `category_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `parent_id` INTEGER, `type` TEXT NOT NULL, `provider_order` INTEGER NOT NULL DEFAULT 0, `is_adult` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, PRIMARY KEY(`session_id`, `provider_id`, `category_id`, `type`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "sessionId",+ "columnName": "session_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "parentId",+ "columnName": "parent_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "type",+ "columnName": "type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "providerOrder",+ "columnName": "provider_order",+ "affinity": "INTEGER",+ "notNull": true,+ "defaultValue": "0"+ },+ {+ "fieldPath": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "syncFingerprint",+ "columnName": "sync_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "session_id",+ "provider_id",+ "category_id",+ "type"+ ]+ },+ "indices": [+ {+ "name": "index_category_import_stage_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_category_import_stage_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_category_import_stage_session_id_provider_id",+ "unique": false,+ "columnNames": [+ "session_id",+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_category_import_stage_session_id_provider_id` ON `${TABLE_NAME}` (`session_id`, `provider_id`)"+ },+ {+ "name": "index_category_import_stage_provider_id_type",+ "unique": false,+ "columnNames": [+ "provider_id",+ "type"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_category_import_stage_provider_id_type` ON `${TABLE_NAME}` (`provider_id`, `type`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "programs",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `channel_id` TEXT NOT NULL, `title` TEXT NOT NULL, `description` TEXT NOT NULL, `start_time` INTEGER NOT NULL, `end_time` INTEGER NOT NULL, `lang` TEXT NOT NULL, `rating` TEXT, `image_url` TEXT, `genre` TEXT, `category` TEXT, `has_archive` INTEGER NOT NULL)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelId",+ "columnName": "channel_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "title",+ "columnName": "title",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "description",+ "columnName": "description",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "startTime",+ "columnName": "start_time",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "endTime",+ "columnName": "end_time",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lang",+ "columnName": "lang",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "rating",+ "columnName": "rating",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "imageUrl",+ "columnName": "image_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "genre",+ "columnName": "genre",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "category",+ "columnName": "category",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "hasArchive",+ "columnName": "has_archive",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_programs_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_programs_provider_id_channel_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "channel_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_channel_id` ON `${TABLE_NAME}` (`provider_id`, `channel_id`)"+ },+ {+ "name": "index_programs_provider_id_end_time_channel_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "end_time",+ "channel_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_end_time_channel_id` ON `${TABLE_NAME}` (`provider_id`, `end_time`, `channel_id`)"+ },+ {+ "name": "index_programs_provider_id_start_time_end_time",+ "unique": false,+ "columnNames": [+ "provider_id",+ "start_time",+ "end_time"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_start_time_end_time` ON `${TABLE_NAME}` (`provider_id`, `start_time`, `end_time`)"+ },+ {+ "name": "index_programs_start_time",+ "unique": false,+ "columnNames": [+ "start_time"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_start_time` ON `${TABLE_NAME}` (`start_time`)"+ },+ {+ "name": "index_programs_provider_id_channel_id_start_time",+ "unique": false,+ "columnNames": [+ "provider_id",+ "channel_id",+ "start_time"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_channel_id_start_time` ON `${TABLE_NAME}` (`provider_id`, `channel_id`, `start_time`)"+ },+ {+ "name": "index_programs_provider_id_channel_id_start_time_end_time",+ "unique": true,+ "columnNames": [+ "provider_id",+ "channel_id",+ "start_time",+ "end_time"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_programs_provider_id_channel_id_start_time_end_time` ON `${TABLE_NAME}` (`provider_id`, `channel_id`, `start_time`, `end_time`)"+ }+ ]+ },+ {+ "tableName": "favorites",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `content_id` INTEGER NOT NULL, `content_type` TEXT NOT NULL, `position` INTEGER NOT NULL, `group_id` INTEGER, `group_key` INTEGER NOT NULL, `added_at` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`group_id`) REFERENCES `virtual_groups`(`id`) ON UPDATE NO ACTION ON DELETE SET NULL )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentId",+ "columnName": "content_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentType",+ "columnName": "content_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "position",+ "columnName": "position",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "groupId",+ "columnName": "group_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "groupKey",+ "columnName": "group_key",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "addedAt",+ "columnName": "added_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_favorites_provider_id_content_id_content_type_group_key",+ "unique": true,+ "columnNames": [+ "provider_id",+ "content_id",+ "content_type",+ "group_key"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_favorites_provider_id_content_id_content_type_group_key` ON `${TABLE_NAME}` (`provider_id`, `content_id`, `content_type`, `group_key`)"+ },+ {+ "name": "index_favorites_provider_id_content_type_group_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "content_type",+ "group_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_favorites_provider_id_content_type_group_id` ON `${TABLE_NAME}` (`provider_id`, `content_type`, `group_id`)"+ },+ {+ "name": "index_favorites_group_id_position",+ "unique": false,+ "columnNames": [+ "group_id",+ "position"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_favorites_group_id_position` ON `${TABLE_NAME}` (`group_id`, `position`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ },+ {+ "table": "virtual_groups",+ "onDelete": "SET NULL",+ "onUpdate": "NO ACTION",+ "columns": [+ "group_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "virtual_groups",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `icon_emoji` TEXT, `position` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `content_type` TEXT NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "iconEmoji",+ "columnName": "icon_emoji",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "position",+ "columnName": "position",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentType",+ "columnName": "content_type",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_virtual_groups_provider_id_content_type",+ "unique": false,+ "columnNames": [+ "provider_id",+ "content_type"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_virtual_groups_provider_id_content_type` ON `${TABLE_NAME}` (`provider_id`, `content_type`)"+ },+ {+ "name": "index_virtual_groups_position",+ "unique": false,+ "columnNames": [+ "position"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_virtual_groups_position` ON `${TABLE_NAME}` (`position`)"+ },+ {+ "name": "index_virtual_groups_content_type",+ "unique": false,+ "columnNames": [+ "content_type"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_virtual_groups_content_type` ON `${TABLE_NAME}` (`content_type`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "playback_history",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `content_id` INTEGER NOT NULL, `content_type` TEXT NOT NULL, `provider_id` INTEGER NOT NULL, `title` TEXT NOT NULL, `poster_url` TEXT, `stream_url` TEXT NOT NULL, `resume_position_ms` INTEGER NOT NULL, `total_duration_ms` INTEGER NOT NULL, `last_watched_at` INTEGER NOT NULL, `watch_count` INTEGER NOT NULL, `watched_status` TEXT NOT NULL, `series_id` INTEGER, `season_number` INTEGER, `episode_number` INTEGER, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentId",+ "columnName": "content_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentType",+ "columnName": "content_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "title",+ "columnName": "title",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "posterUrl",+ "columnName": "poster_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "resumePositionMs",+ "columnName": "resume_position_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "totalDurationMs",+ "columnName": "total_duration_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastWatchedAt",+ "columnName": "last_watched_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "watchCount",+ "columnName": "watch_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "watchedStatus",+ "columnName": "watched_status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "seriesId",+ "columnName": "series_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "seasonNumber",+ "columnName": "season_number",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "episodeNumber",+ "columnName": "episode_number",+ "affinity": "INTEGER"+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_playback_history_content_id_content_type_provider_id",+ "unique": true,+ "columnNames": [+ "content_id",+ "content_type",+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_playback_history_content_id_content_type_provider_id` ON `${TABLE_NAME}` (`content_id`, `content_type`, `provider_id`)"+ },+ {+ "name": "index_playback_history_last_watched_at",+ "unique": false,+ "columnNames": [+ "last_watched_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_history_last_watched_at` ON `${TABLE_NAME}` (`last_watched_at`)"+ },+ {+ "name": "index_playback_history_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_history_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_playback_history_provider_id_content_type_content_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "content_type",+ "content_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_history_provider_id_content_type_content_id` ON `${TABLE_NAME}` (`provider_id`, `content_type`, `content_id`)"+ },+ {+ "name": "index_playback_history_provider_id_content_type_last_watched_at",+ "unique": false,+ "columnNames": [+ "provider_id",+ "content_type",+ "last_watched_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_history_provider_id_content_type_last_watched_at` ON `${TABLE_NAME}` (`provider_id`, `content_type`, `last_watched_at`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "tmdb_identity",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`tmdb_id` INTEGER NOT NULL, `content_type` TEXT NOT NULL, `canonical_provider_id` INTEGER NOT NULL, `first_seen_at` INTEGER NOT NULL, PRIMARY KEY(`tmdb_id`, `content_type`), FOREIGN KEY(`canonical_provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "tmdbId",+ "columnName": "tmdb_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentType",+ "columnName": "content_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "canonicalProviderId",+ "columnName": "canonical_provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "firstSeenAt",+ "columnName": "first_seen_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "tmdb_id",+ "content_type"+ ]+ },+ "indices": [+ {+ "name": "index_tmdb_identity_content_type",+ "unique": false,+ "columnNames": [+ "content_type"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_tmdb_identity_content_type` ON `${TABLE_NAME}` (`content_type`)"+ },+ {+ "name": "index_tmdb_identity_canonical_provider_id",+ "unique": false,+ "columnNames": [+ "canonical_provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_tmdb_identity_canonical_provider_id` ON `${TABLE_NAME}` (`canonical_provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "canonical_provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "search_history",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `query` TEXT NOT NULL, `content_scope` TEXT NOT NULL, `provider_id` INTEGER NOT NULL, `used_at` INTEGER NOT NULL, `use_count` INTEGER NOT NULL)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "query",+ "columnName": "query",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "contentScope",+ "columnName": "content_scope",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "usedAt",+ "columnName": "used_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "useCount",+ "columnName": "use_count",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_search_history_content_scope_provider_id_used_at",+ "unique": false,+ "columnNames": [+ "content_scope",+ "provider_id",+ "used_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_search_history_content_scope_provider_id_used_at` ON `${TABLE_NAME}` (`content_scope`, `provider_id`, `used_at`)"+ },+ {+ "name": "index_search_history_used_at",+ "unique": false,+ "columnNames": [+ "used_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_search_history_used_at` ON `${TABLE_NAME}` (`used_at`)"+ },+ {+ "name": "index_search_history_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_search_history_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_search_history_query_content_scope_provider_id",+ "unique": true,+ "columnNames": [+ "query",+ "content_scope",+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_search_history_query_content_scope_provider_id` ON `${TABLE_NAME}` (`query`, `content_scope`, `provider_id`)"+ }+ ]+ },+ {+ "tableName": "sync_metadata",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `last_live_sync` INTEGER NOT NULL, `last_live_success` INTEGER NOT NULL, `last_movie_sync` INTEGER NOT NULL, `last_series_sync` INTEGER NOT NULL, `last_series_success` INTEGER NOT NULL, `last_epg_sync` INTEGER NOT NULL, `last_epg_success` INTEGER NOT NULL, `last_movie_attempt` INTEGER NOT NULL, `last_movie_success` INTEGER NOT NULL, `last_movie_partial` INTEGER NOT NULL, `live_count` INTEGER NOT NULL, `movie_count` INTEGER NOT NULL, `series_count` INTEGER NOT NULL, `epg_count` INTEGER NOT NULL, `last_sync_status` TEXT NOT NULL, `movie_sync_mode` TEXT NOT NULL, `movie_warnings_count` INTEGER NOT NULL, `movie_catalog_stale` INTEGER NOT NULL, `live_avoid_full_until` INTEGER NOT NULL, `movie_avoid_full_until` INTEGER NOT NULL, `series_avoid_full_until` INTEGER NOT NULL, `live_sequential_failures_remembered` INTEGER NOT NULL, `live_healthy_sync_streak` INTEGER NOT NULL, `movie_parallel_failures_remembered` INTEGER NOT NULL, `movie_healthy_sync_streak` INTEGER NOT NULL, `series_sequential_failures_remembered` INTEGER NOT NULL, `series_healthy_sync_streak` INTEGER NOT NULL, PRIMARY KEY(`provider_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastLiveSync",+ "columnName": "last_live_sync",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastLiveSuccess",+ "columnName": "last_live_success",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastMovieSync",+ "columnName": "last_movie_sync",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastSeriesSync",+ "columnName": "last_series_sync",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastSeriesSuccess",+ "columnName": "last_series_success",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastEpgSync",+ "columnName": "last_epg_sync",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastEpgSuccess",+ "columnName": "last_epg_success",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastMovieAttempt",+ "columnName": "last_movie_attempt",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastMovieSuccess",+ "columnName": "last_movie_success",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastMoviePartial",+ "columnName": "last_movie_partial",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "liveCount",+ "columnName": "live_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "movieCount",+ "columnName": "movie_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "seriesCount",+ "columnName": "series_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "epgCount",+ "columnName": "epg_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastSyncStatus",+ "columnName": "last_sync_status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "movieSyncMode",+ "columnName": "movie_sync_mode",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "movieWarningsCount",+ "columnName": "movie_warnings_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "movieCatalogStale",+ "columnName": "movie_catalog_stale",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "liveAvoidFullUntil",+ "columnName": "live_avoid_full_until",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "movieAvoidFullUntil",+ "columnName": "movie_avoid_full_until",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "seriesAvoidFullUntil",+ "columnName": "series_avoid_full_until",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "liveSequentialFailuresRemembered",+ "columnName": "live_sequential_failures_remembered",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "liveHealthySyncStreak",+ "columnName": "live_healthy_sync_streak",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "movieParallelFailuresRemembered",+ "columnName": "movie_parallel_failures_remembered",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "movieHealthySyncStreak",+ "columnName": "movie_healthy_sync_streak",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "seriesSequentialFailuresRemembered",+ "columnName": "series_sequential_failures_remembered",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "seriesHealthySyncStreak",+ "columnName": "series_healthy_sync_streak",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "provider_id"+ ]+ },+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "movie_category_hydration",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `category_id` INTEGER NOT NULL, `last_hydrated_at` INTEGER NOT NULL, `item_count` INTEGER NOT NULL, `last_status` TEXT NOT NULL, `last_error` TEXT, `last_loaded_page` INTEGER NOT NULL, `last_attempted_page` INTEGER NOT NULL, `last_successful_page` INTEGER NOT NULL, `total_pages` INTEGER NOT NULL, `advertised_total_items` INTEGER, `advertised_total_pages` INTEGER, `is_complete` INTEGER NOT NULL, `page_size` INTEGER NOT NULL, `retry_after_ms` INTEGER NOT NULL, `failure_count` INTEGER NOT NULL, `retry_budget_remaining` INTEGER NOT NULL, `last_page_fingerprint` TEXT, PRIMARY KEY(`provider_id`, `category_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastHydratedAt",+ "columnName": "last_hydrated_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "itemCount",+ "columnName": "item_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastStatus",+ "columnName": "last_status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "lastError",+ "columnName": "last_error",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lastLoadedPage",+ "columnName": "last_loaded_page",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastAttemptedPage",+ "columnName": "last_attempted_page",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastSuccessfulPage",+ "columnName": "last_successful_page",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "totalPages",+ "columnName": "total_pages",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "advertisedTotalItems",+ "columnName": "advertised_total_items",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "advertisedTotalPages",+ "columnName": "advertised_total_pages",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "isComplete",+ "columnName": "is_complete",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "pageSize",+ "columnName": "page_size",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "retryAfterMs",+ "columnName": "retry_after_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "failureCount",+ "columnName": "failure_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "retryBudgetRemaining",+ "columnName": "retry_budget_remaining",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastPageFingerprint",+ "columnName": "last_page_fingerprint",+ "affinity": "TEXT"+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "provider_id",+ "category_id"+ ]+ },+ "indices": [+ {+ "name": "index_movie_category_hydration_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movie_category_hydration_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "series_category_hydration",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `category_id` INTEGER NOT NULL, `last_hydrated_at` INTEGER NOT NULL, `item_count` INTEGER NOT NULL, `last_status` TEXT NOT NULL, `last_error` TEXT, `last_loaded_page` INTEGER NOT NULL, `last_attempted_page` INTEGER NOT NULL, `last_successful_page` INTEGER NOT NULL, `total_pages` INTEGER NOT NULL, `advertised_total_items` INTEGER, `advertised_total_pages` INTEGER, `is_complete` INTEGER NOT NULL, `page_size` INTEGER NOT NULL, `retry_after_ms` INTEGER NOT NULL, `failure_count` INTEGER NOT NULL, `retry_budget_remaining` INTEGER NOT NULL, `last_page_fingerprint` TEXT, PRIMARY KEY(`provider_id`, `category_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastHydratedAt",+ "columnName": "last_hydrated_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "itemCount",+ "columnName": "item_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastStatus",+ "columnName": "last_status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "lastError",+ "columnName": "last_error",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lastLoadedPage",+ "columnName": "last_loaded_page",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastAttemptedPage",+ "columnName": "last_attempted_page",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastSuccessfulPage",+ "columnName": "last_successful_page",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "totalPages",+ "columnName": "total_pages",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "advertisedTotalItems",+ "columnName": "advertised_total_items",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "advertisedTotalPages",+ "columnName": "advertised_total_pages",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "isComplete",+ "columnName": "is_complete",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "pageSize",+ "columnName": "page_size",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "retryAfterMs",+ "columnName": "retry_after_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "failureCount",+ "columnName": "failure_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "retryBudgetRemaining",+ "columnName": "retry_budget_remaining",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastPageFingerprint",+ "columnName": "last_page_fingerprint",+ "affinity": "TEXT"+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "provider_id",+ "category_id"+ ]+ },+ "indices": [+ {+ "name": "index_series_category_hydration_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_category_hydration_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "vod_category_hydration",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `category_id` INTEGER NOT NULL, `last_loaded_page` INTEGER NOT NULL, `last_attempted_page` INTEGER NOT NULL, `last_successful_page` INTEGER NOT NULL, `total_pages` INTEGER NOT NULL, `advertised_total_items` INTEGER, `advertised_total_pages` INTEGER, `page_size` INTEGER NOT NULL, `item_count` INTEGER NOT NULL, `is_complete` INTEGER NOT NULL, `has_movies` INTEGER NOT NULL, `has_series` INTEGER NOT NULL, `last_hydrated_at` INTEGER NOT NULL, `last_status` TEXT NOT NULL, `last_error` TEXT, `retry_after_ms` INTEGER NOT NULL, `failure_count` INTEGER NOT NULL, `retry_budget_remaining` INTEGER NOT NULL, `last_page_fingerprint` TEXT, PRIMARY KEY(`provider_id`, `category_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastLoadedPage",+ "columnName": "last_loaded_page",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastAttemptedPage",+ "columnName": "last_attempted_page",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastSuccessfulPage",+ "columnName": "last_successful_page",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "totalPages",+ "columnName": "total_pages",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "advertisedTotalItems",+ "columnName": "advertised_total_items",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "advertisedTotalPages",+ "columnName": "advertised_total_pages",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "pageSize",+ "columnName": "page_size",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "itemCount",+ "columnName": "item_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isComplete",+ "columnName": "is_complete",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "hasMovies",+ "columnName": "has_movies",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "hasSeries",+ "columnName": "has_series",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastHydratedAt",+ "columnName": "last_hydrated_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastStatus",+ "columnName": "last_status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "lastError",+ "columnName": "last_error",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "retryAfterMs",+ "columnName": "retry_after_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "failureCount",+ "columnName": "failure_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "retryBudgetRemaining",+ "columnName": "retry_budget_remaining",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastPageFingerprint",+ "columnName": "last_page_fingerprint",+ "affinity": "TEXT"+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "provider_id",+ "category_id"+ ]+ },+ "indices": [+ {+ "name": "index_vod_category_hydration_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_vod_category_hydration_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "vod_catalog_entries",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `category_id` INTEGER NOT NULL, `raw_item_id` TEXT NOT NULL, `item_type` TEXT NOT NULL, `target_id` INTEGER NOT NULL, `raw_page` INTEGER NOT NULL, `raw_index` INTEGER NOT NULL, PRIMARY KEY(`provider_id`, `category_id`, `raw_item_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "rawItemId",+ "columnName": "raw_item_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "itemType",+ "columnName": "item_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "targetId",+ "columnName": "target_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "rawPage",+ "columnName": "raw_page",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "rawIndex",+ "columnName": "raw_index",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "provider_id",+ "category_id",+ "raw_item_id"+ ]+ },+ "indices": [+ {+ "name": "index_vod_catalog_entries_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_vod_catalog_entries_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_vod_catalog_entries_provider_id_category_id_raw_page_raw_index",+ "unique": false,+ "columnNames": [+ "provider_id",+ "category_id",+ "raw_page",+ "raw_index"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_vod_catalog_entries_provider_id_category_id_raw_page_raw_index` ON `${TABLE_NAME}` (`provider_id`, `category_id`, `raw_page`, `raw_index`)"+ },+ {+ "name": "index_vod_catalog_entries_provider_id_item_type_target_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "item_type",+ "target_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_vod_catalog_entries_provider_id_item_type_target_id` ON `${TABLE_NAME}` (`provider_id`, `item_type`, `target_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "epg_sources",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `url` TEXT NOT NULL, `enabled` INTEGER NOT NULL, `last_refresh_at` INTEGER NOT NULL, `last_success_at` INTEGER NOT NULL, `last_error` TEXT, `priority` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, `etag` TEXT, `last_modified_header` TEXT, `timezone_policy` TEXT NOT NULL, `timezone_id` TEXT)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "url",+ "columnName": "url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "enabled",+ "columnName": "enabled",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastRefreshAt",+ "columnName": "last_refresh_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastSuccessAt",+ "columnName": "last_success_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastError",+ "columnName": "last_error",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "priority",+ "columnName": "priority",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "etag",+ "columnName": "etag",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lastModifiedHeader",+ "columnName": "last_modified_header",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "timezonePolicy",+ "columnName": "timezone_policy",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "timezoneId",+ "columnName": "timezone_id",+ "affinity": "TEXT"+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_epg_sources_url",+ "unique": true,+ "columnNames": [+ "url"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_epg_sources_url` ON `${TABLE_NAME}` (`url`)"+ }+ ]+ },+ {+ "tableName": "provider_epg_sources",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `epg_source_id` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `enabled` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`epg_source_id`) REFERENCES `epg_sources`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "epgSourceId",+ "columnName": "epg_source_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "priority",+ "columnName": "priority",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "enabled",+ "columnName": "enabled",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_provider_epg_sources_provider_id_epg_source_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "epg_source_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_provider_epg_sources_provider_id_epg_source_id` ON `${TABLE_NAME}` (`provider_id`, `epg_source_id`)"+ },+ {+ "name": "index_provider_epg_sources_epg_source_id",+ "unique": false,+ "columnNames": [+ "epg_source_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_provider_epg_sources_epg_source_id` ON `${TABLE_NAME}` (`epg_source_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ },+ {+ "table": "epg_sources",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "epg_source_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "epg_channels",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `epg_source_id` INTEGER NOT NULL, `xmltv_channel_id` TEXT NOT NULL, `display_name` TEXT NOT NULL, `normalized_name` TEXT NOT NULL, `icon_url` TEXT, FOREIGN KEY(`epg_source_id`) REFERENCES `epg_sources`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "epgSourceId",+ "columnName": "epg_source_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "xmltvChannelId",+ "columnName": "xmltv_channel_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "displayName",+ "columnName": "display_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "normalizedName",+ "columnName": "normalized_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "iconUrl",+ "columnName": "icon_url",+ "affinity": "TEXT"+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_epg_channels_epg_source_id_xmltv_channel_id",+ "unique": true,+ "columnNames": [+ "epg_source_id",+ "xmltv_channel_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_epg_channels_epg_source_id_xmltv_channel_id` ON `${TABLE_NAME}` (`epg_source_id`, `xmltv_channel_id`)"+ },+ {+ "name": "index_epg_channels_epg_source_id",+ "unique": false,+ "columnNames": [+ "epg_source_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_channels_epg_source_id` ON `${TABLE_NAME}` (`epg_source_id`)"+ },+ {+ "name": "index_epg_channels_normalized_name",+ "unique": false,+ "columnNames": [+ "normalized_name"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_channels_normalized_name` ON `${TABLE_NAME}` (`normalized_name`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "epg_sources",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "epg_source_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "epg_programmes",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `epg_source_id` INTEGER NOT NULL, `xmltv_channel_id` TEXT NOT NULL, `start_time` INTEGER NOT NULL, `end_time` INTEGER NOT NULL, `title` TEXT NOT NULL, `subtitle` TEXT, `description` TEXT NOT NULL, `category` TEXT, `lang` TEXT NOT NULL, `rating` TEXT, `image_url` TEXT, `episode_info` TEXT, FOREIGN KEY(`epg_source_id`) REFERENCES `epg_sources`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "epgSourceId",+ "columnName": "epg_source_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "xmltvChannelId",+ "columnName": "xmltv_channel_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "startTime",+ "columnName": "start_time",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "endTime",+ "columnName": "end_time",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "title",+ "columnName": "title",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "subtitle",+ "columnName": "subtitle",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "description",+ "columnName": "description",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "category",+ "columnName": "category",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lang",+ "columnName": "lang",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "rating",+ "columnName": "rating",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "imageUrl",+ "columnName": "image_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "episodeInfo",+ "columnName": "episode_info",+ "affinity": "TEXT"+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_epg_programmes_epg_source_id_xmltv_channel_id_start_time",+ "unique": false,+ "columnNames": [+ "epg_source_id",+ "xmltv_channel_id",+ "start_time"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_programmes_epg_source_id_xmltv_channel_id_start_time` ON `${TABLE_NAME}` (`epg_source_id`, `xmltv_channel_id`, `start_time`)"+ },+ {+ "name": "index_epg_programmes_epg_source_id_xmltv_channel_id_start_time_end_time",+ "unique": true,+ "columnNames": [+ "epg_source_id",+ "xmltv_channel_id",+ "start_time",+ "end_time"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_epg_programmes_epg_source_id_xmltv_channel_id_start_time_end_time` ON `${TABLE_NAME}` (`epg_source_id`, `xmltv_channel_id`, `start_time`, `end_time`)"+ },+ {+ "name": "index_epg_programmes_epg_source_id",+ "unique": false,+ "columnNames": [+ "epg_source_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_programmes_epg_source_id` ON `${TABLE_NAME}` (`epg_source_id`)"+ },+ {+ "name": "index_epg_programmes_start_time",+ "unique": false,+ "columnNames": [+ "start_time"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_programmes_start_time` ON `${TABLE_NAME}` (`start_time`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "epg_sources",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "epg_source_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "channel_epg_mappings",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_channel_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `source_type` TEXT NOT NULL, `epg_source_id` INTEGER, `xmltv_channel_id` TEXT, `match_type` TEXT, `confidence` REAL NOT NULL, `matched_at` INTEGER NOT NULL, `failed_attempts` INTEGER NOT NULL, `source` TEXT, `is_manual_override` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerChannelId",+ "columnName": "provider_channel_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "sourceType",+ "columnName": "source_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "epgSourceId",+ "columnName": "epg_source_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "xmltvChannelId",+ "columnName": "xmltv_channel_id",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "matchType",+ "columnName": "match_type",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "confidence",+ "columnName": "confidence",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "matchedAt",+ "columnName": "matched_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "failedAttempts",+ "columnName": "failed_attempts",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "source",+ "columnName": "source",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "isManualOverride",+ "columnName": "is_manual_override",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_channel_epg_mappings_provider_id_provider_channel_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "provider_channel_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_channel_epg_mappings_provider_id_provider_channel_id` ON `${TABLE_NAME}` (`provider_id`, `provider_channel_id`)"+ },+ {+ "name": "index_channel_epg_mappings_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channel_epg_mappings_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "combined_m3u_profiles",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `enabled` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "enabled",+ "columnName": "enabled",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ }+ },+ {+ "tableName": "combined_m3u_profile_members",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `profile_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `enabled` INTEGER NOT NULL, FOREIGN KEY(`profile_id`) REFERENCES `combined_m3u_profiles`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "profileId",+ "columnName": "profile_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "priority",+ "columnName": "priority",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "enabled",+ "columnName": "enabled",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_combined_m3u_profile_members_profile_id",+ "unique": false,+ "columnNames": [+ "profile_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_combined_m3u_profile_members_profile_id` ON `${TABLE_NAME}` (`profile_id`)"+ },+ {+ "name": "index_combined_m3u_profile_members_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_combined_m3u_profile_members_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_combined_m3u_profile_members_profile_id_provider_id",+ "unique": true,+ "columnNames": [+ "profile_id",+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_combined_m3u_profile_members_profile_id_provider_id` ON `${TABLE_NAME}` (`profile_id`, `provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "combined_m3u_profiles",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "profile_id"+ ],+ "referencedColumns": [+ "id"+ ]+ },+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "recording_schedules",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, `channel_name` TEXT NOT NULL, `stream_url` TEXT NOT NULL, `program_title` TEXT, `requested_start_ms` INTEGER NOT NULL, `requested_end_ms` INTEGER NOT NULL, `recurrence` TEXT NOT NULL, `recurring_rule_id` TEXT, `enabled` INTEGER NOT NULL, `is_manual` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelId",+ "columnName": "channel_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelName",+ "columnName": "channel_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "programTitle",+ "columnName": "program_title",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "requestedStartMs",+ "columnName": "requested_start_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "requestedEndMs",+ "columnName": "requested_end_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "recurrence",+ "columnName": "recurrence",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "recurringRuleId",+ "columnName": "recurring_rule_id",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "enabled",+ "columnName": "enabled",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isManual",+ "columnName": "is_manual",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "priority",+ "columnName": "priority",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_recording_schedules_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_schedules_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_recording_schedules_enabled_requested_start_ms",+ "unique": false,+ "columnNames": [+ "enabled",+ "requested_start_ms"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_schedules_enabled_requested_start_ms` ON `${TABLE_NAME}` (`enabled`, `requested_start_ms`)"+ },+ {+ "name": "index_recording_schedules_recurring_rule_id",+ "unique": false,+ "columnNames": [+ "recurring_rule_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_schedules_recurring_rule_id` ON `${TABLE_NAME}` (`recurring_rule_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "recording_runs",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `schedule_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, `channel_name` TEXT NOT NULL, `stream_url` TEXT NOT NULL, `program_title` TEXT, `scheduled_start_ms` INTEGER NOT NULL, `scheduled_end_ms` INTEGER NOT NULL, `recurrence` TEXT NOT NULL, `recurring_rule_id` TEXT, `status` TEXT NOT NULL, `source_type` TEXT NOT NULL, `resolved_url` TEXT, `headers_json` TEXT NOT NULL, `user_agent` TEXT, `expiration_time` INTEGER, `provider_label` TEXT, `output_uri` TEXT, `output_display_path` TEXT, `bytes_written` INTEGER NOT NULL, `average_throughput_bps` INTEGER NOT NULL, `retry_count` INTEGER NOT NULL, `last_progress_at_ms` INTEGER, `failure_category` TEXT NOT NULL, `failure_reason` TEXT, `terminal_at_ms` INTEGER, `started_at_ms` INTEGER, `ended_at_ms` INTEGER, `schedule_enabled` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `alarm_start_at_ms` INTEGER, `alarm_stop_at_ms` INTEGER, `exact_alarm_armed` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`schedule_id`) REFERENCES `recording_schedules`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "scheduleId",+ "columnName": "schedule_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelId",+ "columnName": "channel_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelName",+ "columnName": "channel_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "programTitle",+ "columnName": "program_title",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "scheduledStartMs",+ "columnName": "scheduled_start_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "scheduledEndMs",+ "columnName": "scheduled_end_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "recurrence",+ "columnName": "recurrence",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "recurringRuleId",+ "columnName": "recurring_rule_id",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "status",+ "columnName": "status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "sourceType",+ "columnName": "source_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "resolvedUrl",+ "columnName": "resolved_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "headersJson",+ "columnName": "headers_json",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "userAgent",+ "columnName": "user_agent",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "expirationTime",+ "columnName": "expiration_time",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "providerLabel",+ "columnName": "provider_label",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "outputUri",+ "columnName": "output_uri",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "outputDisplayPath",+ "columnName": "output_display_path",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "bytesWritten",+ "columnName": "bytes_written",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "averageThroughputBytesPerSecond",+ "columnName": "average_throughput_bps",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "retryCount",+ "columnName": "retry_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastProgressAtMs",+ "columnName": "last_progress_at_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "failureCategory",+ "columnName": "failure_category",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "failureReason",+ "columnName": "failure_reason",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "terminalAtMs",+ "columnName": "terminal_at_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "startedAtMs",+ "columnName": "started_at_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "endedAtMs",+ "columnName": "ended_at_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "scheduleEnabled",+ "columnName": "schedule_enabled",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "priority",+ "columnName": "priority",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "alarmStartAtMs",+ "columnName": "alarm_start_at_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "alarmStopAtMs",+ "columnName": "alarm_stop_at_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "exactAlarmArmed",+ "columnName": "exact_alarm_armed",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_recording_runs_schedule_id",+ "unique": false,+ "columnNames": [+ "schedule_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_schedule_id` ON `${TABLE_NAME}` (`schedule_id`)"+ },+ {+ "name": "index_recording_runs_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_recording_runs_status_scheduled_start_ms",+ "unique": false,+ "columnNames": [+ "status",+ "scheduled_start_ms"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_status_scheduled_start_ms` ON `${TABLE_NAME}` (`status`, `scheduled_start_ms`)"+ },+ {+ "name": "index_recording_runs_alarm_start_at_ms",+ "unique": false,+ "columnNames": [+ "alarm_start_at_ms"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_alarm_start_at_ms` ON `${TABLE_NAME}` (`alarm_start_at_ms`)"+ },+ {+ "name": "index_recording_runs_alarm_stop_at_ms",+ "unique": false,+ "columnNames": [+ "alarm_stop_at_ms"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_alarm_stop_at_ms` ON `${TABLE_NAME}` (`alarm_stop_at_ms`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "recording_schedules",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "schedule_id"+ ],+ "referencedColumns": [+ "id"+ ]+ },+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "program_reminders",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `channel_id` TEXT NOT NULL, `channel_name` TEXT NOT NULL, `program_title` TEXT NOT NULL, `program_start_time` INTEGER NOT NULL, `remind_at` INTEGER NOT NULL, `lead_time_minutes` INTEGER NOT NULL, `is_dismissed` INTEGER NOT NULL, `notified_at` INTEGER, `exact_alarm_armed` INTEGER NOT NULL, `delivery_state` TEXT NOT NULL, `delivery_attempt_token` TEXT, `delivery_attempted_at` INTEGER, `delivery_attempt_count` INTEGER NOT NULL, `delivery_failure_reason` TEXT, `created_at` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelId",+ "columnName": "channel_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "channelName",+ "columnName": "channel_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "programTitle",+ "columnName": "program_title",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "programStartTime",+ "columnName": "program_start_time",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "remindAt",+ "columnName": "remind_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "leadTimeMinutes",+ "columnName": "lead_time_minutes",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isDismissed",+ "columnName": "is_dismissed",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "notifiedAt",+ "columnName": "notified_at",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "exactAlarmArmed",+ "columnName": "exact_alarm_armed",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "deliveryState",+ "columnName": "delivery_state",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "deliveryAttemptToken",+ "columnName": "delivery_attempt_token",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "deliveryAttemptedAt",+ "columnName": "delivery_attempted_at",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "deliveryAttemptCount",+ "columnName": "delivery_attempt_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "deliveryFailureReason",+ "columnName": "delivery_failure_reason",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_program_reminders_provider_id_remind_at",+ "unique": false,+ "columnNames": [+ "provider_id",+ "remind_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_program_reminders_provider_id_remind_at` ON `${TABLE_NAME}` (`provider_id`, `remind_at`)"+ },+ {+ "name": "index_program_reminders_is_dismissed_notified_at_remind_at",+ "unique": false,+ "columnNames": [+ "is_dismissed",+ "notified_at",+ "remind_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_program_reminders_is_dismissed_notified_at_remind_at` ON `${TABLE_NAME}` (`is_dismissed`, `notified_at`, `remind_at`)"+ },+ {+ "name": "index_program_reminders_provider_id_channel_id_program_start_time",+ "unique": false,+ "columnNames": [+ "provider_id",+ "channel_id",+ "program_start_time"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_program_reminders_provider_id_channel_id_program_start_time` ON `${TABLE_NAME}` (`provider_id`, `channel_id`, `program_start_time`)"+ },+ {+ "name": "index_program_reminders_provider_id_channel_id_program_title_program_start_time",+ "unique": true,+ "columnNames": [+ "provider_id",+ "channel_id",+ "program_title",+ "program_start_time"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_program_reminders_provider_id_channel_id_program_title_program_start_time` ON `${TABLE_NAME}` (`provider_id`, `channel_id`, `program_title`, `program_start_time`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "recording_storage",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER NOT NULL, `tree_uri` TEXT, `display_name` TEXT, `output_directory` TEXT, `available_bytes` INTEGER, `is_writable` INTEGER NOT NULL, `file_name_pattern` TEXT NOT NULL, `retention_days` INTEGER, `max_simultaneous_recordings` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, PRIMARY KEY(`id`))",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "treeUri",+ "columnName": "tree_uri",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "displayName",+ "columnName": "display_name",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "outputDirectory",+ "columnName": "output_directory",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "availableBytes",+ "columnName": "available_bytes",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "isWritable",+ "columnName": "is_writable",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "fileNamePattern",+ "columnName": "file_name_pattern",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "retentionDays",+ "columnName": "retention_days",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "maxSimultaneousRecordings",+ "columnName": "max_simultaneous_recordings",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "id"+ ]+ }+ },+ {+ "tableName": "playback_compatibility_records",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `device_fingerprint` TEXT NOT NULL, `device_model` TEXT NOT NULL, `android_sdk` INTEGER NOT NULL, `stream_type` TEXT NOT NULL, `video_mime_type` TEXT NOT NULL, `resolution_bucket` TEXT NOT NULL, `decoder_name` TEXT NOT NULL, `surface_type` TEXT NOT NULL, `failure_type` TEXT NOT NULL, `last_failed_at` INTEGER NOT NULL, `last_succeeded_at` INTEGER NOT NULL, `failure_count` INTEGER NOT NULL, `success_count` INTEGER NOT NULL)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "deviceFingerprint",+ "columnName": "device_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "deviceModel",+ "columnName": "device_model",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "androidSdk",+ "columnName": "android_sdk",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "streamType",+ "columnName": "stream_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "videoMimeType",+ "columnName": "video_mime_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "resolutionBucket",+ "columnName": "resolution_bucket",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "decoderName",+ "columnName": "decoder_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "surfaceType",+ "columnName": "surface_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "failureType",+ "columnName": "failure_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "lastFailedAt",+ "columnName": "last_failed_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastSucceededAt",+ "columnName": "last_succeeded_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "failureCount",+ "columnName": "failure_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "successCount",+ "columnName": "success_count",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_playback_compatibility_records_device_fingerprint_stream_type_video_mime_type_resolution_bucket_decoder_name_surface_type",+ "unique": true,+ "columnNames": [+ "device_fingerprint",+ "stream_type",+ "video_mime_type",+ "resolution_bucket",+ "decoder_name",+ "surface_type"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_playback_compatibility_records_device_fingerprint_stream_type_video_mime_type_resolution_bucket_decoder_name_surface_type` ON `${TABLE_NAME}` (`device_fingerprint`, `stream_type`, `video_mime_type`, `resolution_bucket`, `decoder_name`, `surface_type`)"+ },+ {+ "name": "index_playback_compatibility_records_device_fingerprint_stream_type_video_mime_type_resolution_bucket",+ "unique": false,+ "columnNames": [+ "device_fingerprint",+ "stream_type",+ "video_mime_type",+ "resolution_bucket"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_compatibility_records_device_fingerprint_stream_type_video_mime_type_resolution_bucket` ON `${TABLE_NAME}` (`device_fingerprint`, `stream_type`, `video_mime_type`, `resolution_bucket`)"+ },+ {+ "name": "index_playback_compatibility_records_last_failed_at",+ "unique": false,+ "columnNames": [+ "last_failed_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_compatibility_records_last_failed_at` ON `${TABLE_NAME}` (`last_failed_at`)"+ },+ {+ "name": "index_playback_compatibility_records_last_succeeded_at",+ "unique": false,+ "columnNames": [+ "last_succeeded_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_compatibility_records_last_succeeded_at` ON `${TABLE_NAME}` (`last_succeeded_at`)"+ }+ ]+ },+ {+ "tableName": "xtream_content_index",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `content_type` TEXT NOT NULL, `remote_id` TEXT NOT NULL, `local_content_id` INTEGER, `name` TEXT NOT NULL, `category_id` INTEGER, `category_name` TEXT, `image_url` TEXT, `container_extension` TEXT, `rating` REAL NOT NULL, `added_at` INTEGER NOT NULL, `remote_updated_at` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `indexed_at` INTEGER NOT NULL, `detail_hydrated_at` INTEGER NOT NULL, `stale_state` TEXT NOT NULL, `error_state` TEXT, `sync_fingerprint` TEXT NOT NULL, PRIMARY KEY(`provider_id`, `content_type`, `remote_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentType",+ "columnName": "content_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "remoteId",+ "columnName": "remote_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "localContentId",+ "columnName": "local_content_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "categoryName",+ "columnName": "category_name",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "imageUrl",+ "columnName": "image_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "containerExtension",+ "columnName": "container_extension",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "rating",+ "columnName": "rating",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "addedAt",+ "columnName": "added_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "remoteUpdatedAt",+ "columnName": "remote_updated_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "indexedAt",+ "columnName": "indexed_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "detailHydratedAt",+ "columnName": "detail_hydrated_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "staleState",+ "columnName": "stale_state",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "errorState",+ "columnName": "error_state",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "syncFingerprint",+ "columnName": "sync_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "provider_id",+ "content_type",+ "remote_id"+ ]+ },+ "indices": [+ {+ "name": "index_xtream_content_index_provider_id_content_type",+ "unique": false,+ "columnNames": [+ "provider_id",+ "content_type"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_xtream_content_index_provider_id_content_type` ON `${TABLE_NAME}` (`provider_id`, `content_type`)"+ },+ {+ "name": "index_xtream_content_index_provider_id_content_type_category_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "content_type",+ "category_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_xtream_content_index_provider_id_content_type_category_id` ON `${TABLE_NAME}` (`provider_id`, `content_type`, `category_id`)"+ },+ {+ "name": "index_xtream_content_index_provider_id_content_type_name",+ "unique": false,+ "columnNames": [+ "provider_id",+ "content_type",+ "name"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_xtream_content_index_provider_id_content_type_name` ON `${TABLE_NAME}` (`provider_id`, `content_type`, `name`)"+ },+ {+ "name": "index_xtream_content_index_provider_id_content_type_local_content_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "content_type",+ "local_content_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_xtream_content_index_provider_id_content_type_local_content_id` ON `${TABLE_NAME}` (`provider_id`, `content_type`, `local_content_id`)"+ },+ {+ "name": "index_xtream_content_index_provider_id_indexed_at",+ "unique": false,+ "columnNames": [+ "provider_id",+ "indexed_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_xtream_content_index_provider_id_indexed_at` ON `${TABLE_NAME}` (`provider_id`, `indexed_at`)"+ },+ {+ "name": "index_xtream_content_index_stale_state",+ "unique": false,+ "columnNames": [+ "stale_state"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_xtream_content_index_stale_state` ON `${TABLE_NAME}` (`stale_state`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "xtream_index_jobs",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `section` TEXT NOT NULL, `state` TEXT NOT NULL, `total_categories` INTEGER NOT NULL, `completed_categories` INTEGER NOT NULL, `next_category_index` INTEGER NOT NULL, `failed_categories` INTEGER NOT NULL, `indexed_rows` INTEGER NOT NULL, `skipped_malformed_rows` INTEGER NOT NULL, `deleted_pruned_rows` INTEGER NOT NULL, `priority_category_id` INTEGER, `priority_requested_at` INTEGER NOT NULL, `last_error` TEXT, `last_attempt_at` INTEGER NOT NULL, `last_success_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, PRIMARY KEY(`provider_id`, `section`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "section",+ "columnName": "section",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "state",+ "columnName": "state",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "totalCategories",+ "columnName": "total_categories",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "completedCategories",+ "columnName": "completed_categories",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "nextCategoryIndex",+ "columnName": "next_category_index",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "failedCategories",+ "columnName": "failed_categories",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "indexedRows",+ "columnName": "indexed_rows",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "skippedMalformedRows",+ "columnName": "skipped_malformed_rows",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "deletedPrunedRows",+ "columnName": "deleted_pruned_rows",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "priorityCategoryId",+ "columnName": "priority_category_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "priorityRequestedAt",+ "columnName": "priority_requested_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastError",+ "columnName": "last_error",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lastAttemptAt",+ "columnName": "last_attempt_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastSuccessAt",+ "columnName": "last_success_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "provider_id",+ "section"+ ]+ },+ "indices": [+ {+ "name": "index_xtream_index_jobs_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_xtream_index_jobs_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_xtream_index_jobs_section",+ "unique": false,+ "columnNames": [+ "section"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_xtream_index_jobs_section` ON `${TABLE_NAME}` (`section`)"+ },+ {+ "name": "index_xtream_index_jobs_state",+ "unique": false,+ "columnNames": [+ "state"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_xtream_index_jobs_state` ON `${TABLE_NAME}` (`state`)"+ },+ {+ "name": "index_xtream_index_jobs_updated_at",+ "unique": false,+ "columnNames": [+ "updated_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_xtream_index_jobs_updated_at` ON `${TABLE_NAME}` (`updated_at`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "xtream_live_onboarding_state",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `provider_type` TEXT NOT NULL, `content_type` TEXT NOT NULL, `phase` TEXT NOT NULL, `staged_session_id` INTEGER, `import_strategy` TEXT, `next_category_index` INTEGER NOT NULL, `accepted_row_count` INTEGER NOT NULL, `staged_flush_count` INTEGER NOT NULL, `sync_profile_tier` TEXT, `sync_profile_batch_size` INTEGER NOT NULL, `sync_profile_strategy` TEXT, `sync_profile_low_memory` INTEGER NOT NULL, `sync_profile_memory_class_mb` INTEGER NOT NULL, `sync_profile_available_mem_mb` INTEGER NOT NULL, `last_error` TEXT, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, `completed_at` INTEGER, PRIMARY KEY(`provider_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerType",+ "columnName": "provider_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "contentType",+ "columnName": "content_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "phase",+ "columnName": "phase",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stagedSessionId",+ "columnName": "staged_session_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "importStrategy",+ "columnName": "import_strategy",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "nextCategoryIndex",+ "columnName": "next_category_index",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "acceptedRowCount",+ "columnName": "accepted_row_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "stagedFlushCount",+ "columnName": "staged_flush_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "syncProfileTier",+ "columnName": "sync_profile_tier",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "syncProfileBatchSize",+ "columnName": "sync_profile_batch_size",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "syncProfileStrategy",+ "columnName": "sync_profile_strategy",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "syncProfileLowMemory",+ "columnName": "sync_profile_low_memory",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "syncProfileMemoryClassMb",+ "columnName": "sync_profile_memory_class_mb",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "syncProfileAvailableMemMb",+ "columnName": "sync_profile_available_mem_mb",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastError",+ "columnName": "last_error",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "completedAt",+ "columnName": "completed_at",+ "affinity": "INTEGER"+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "provider_id"+ ]+ },+ "indices": [+ {+ "name": "index_xtream_live_onboarding_state_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_xtream_live_onboarding_state_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_xtream_live_onboarding_state_phase",+ "unique": false,+ "columnNames": [+ "phase"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_xtream_live_onboarding_state_phase` ON `${TABLE_NAME}` (`phase`)"+ },+ {+ "name": "index_xtream_live_onboarding_state_updated_at",+ "unique": false,+ "columnNames": [+ "updated_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_xtream_live_onboarding_state_updated_at` ON `${TABLE_NAME}` (`updated_at`)"+ },+ {+ "name": "index_xtream_live_onboarding_state_staged_session_id",+ "unique": false,+ "columnNames": [+ "staged_session_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_xtream_live_onboarding_state_staged_session_id` ON `${TABLE_NAME}` (`staged_session_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "stalker_index_jobs",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `section` TEXT NOT NULL, `state` TEXT NOT NULL, `total_categories` INTEGER NOT NULL, `completed_categories` INTEGER NOT NULL, `next_category_index` INTEGER NOT NULL, `failed_categories` INTEGER NOT NULL, `indexed_rows` INTEGER NOT NULL, `skipped_malformed_rows` INTEGER NOT NULL, `deleted_pruned_rows` INTEGER NOT NULL, `last_error` TEXT, `last_attempt_at` INTEGER NOT NULL, `last_success_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, PRIMARY KEY(`provider_id`, `section`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "section",+ "columnName": "section",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "state",+ "columnName": "state",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "totalCategories",+ "columnName": "total_categories",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "completedCategories",+ "columnName": "completed_categories",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "nextCategoryIndex",+ "columnName": "next_category_index",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "failedCategories",+ "columnName": "failed_categories",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "indexedRows",+ "columnName": "indexed_rows",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "skippedMalformedRows",+ "columnName": "skipped_malformed_rows",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "deletedPrunedRows",+ "columnName": "deleted_pruned_rows",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastError",+ "columnName": "last_error",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lastAttemptAt",+ "columnName": "last_attempt_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastSuccessAt",+ "columnName": "last_success_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "provider_id",+ "section"+ ]+ },+ "indices": [+ {+ "name": "index_stalker_index_jobs_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_stalker_index_jobs_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_stalker_index_jobs_state",+ "unique": false,+ "columnNames": [+ "state"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_stalker_index_jobs_state` ON `${TABLE_NAME}` (`state`)"+ },+ {+ "name": "index_stalker_index_jobs_updated_at",+ "unique": false,+ "columnNames": [+ "updated_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_stalker_index_jobs_updated_at` ON `${TABLE_NAME}` (`updated_at`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "stalker_portal_state",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `working_endpoint` TEXT, `bootstrap_recipe` TEXT, `bulk_live_supported` INTEGER, `bulk_live_category_fidelity` INTEGER, `movie_wildcard_supported` INTEGER, `series_wildcard_supported` INTEGER, `epg_supported` INTEGER, `safe_metadata_concurrency` INTEGER NOT NULL, `stress_cooldown_until` INTEGER NOT NULL, `endpoint_health_json` TEXT NOT NULL, `endpoint_failed_until` INTEGER NOT NULL, `validated_at` INTEGER NOT NULL, `schema_version` INTEGER NOT NULL, `configuration_generation` INTEGER NOT NULL, `learning_json` TEXT NOT NULL, `observation_source` TEXT NOT NULL, `observed_at` INTEGER NOT NULL, PRIMARY KEY(`provider_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "workingEndpoint",+ "columnName": "working_endpoint",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "bootstrapRecipe",+ "columnName": "bootstrap_recipe",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "bulkLiveSupported",+ "columnName": "bulk_live_supported",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "bulkLiveCategoryFidelity",+ "columnName": "bulk_live_category_fidelity",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "movieWildcardSupported",+ "columnName": "movie_wildcard_supported",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "seriesWildcardSupported",+ "columnName": "series_wildcard_supported",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "epgSupported",+ "columnName": "epg_supported",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "safeMetadataConcurrency",+ "columnName": "safe_metadata_concurrency",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "stressCooldownUntil",+ "columnName": "stress_cooldown_until",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "endpointHealthJson",+ "columnName": "endpoint_health_json",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "endpointFailedUntil",+ "columnName": "endpoint_failed_until",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "validatedAt",+ "columnName": "validated_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "schemaVersion",+ "columnName": "schema_version",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "configurationGeneration",+ "columnName": "configuration_generation",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "learningJson",+ "columnName": "learning_json",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "observationSource",+ "columnName": "observation_source",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "observedAt",+ "columnName": "observed_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "provider_id"+ ]+ },+ "indices": [+ {+ "name": "index_stalker_portal_state_provider_id",+ "unique": true,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_stalker_portal_state_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "stalker_remote_identities",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `content_type` TEXT NOT NULL, `raw_id` TEXT NOT NULL, `surrogate_id` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, PRIMARY KEY(`provider_id`, `content_type`, `raw_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentType",+ "columnName": "content_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "rawId",+ "columnName": "raw_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "surrogateId",+ "columnName": "surrogate_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "provider_id",+ "content_type",+ "raw_id"+ ]+ },+ "indices": [+ {+ "name": "index_stalker_remote_identities_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_stalker_remote_identities_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_stalker_remote_identities_provider_id_content_type_surrogate_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "content_type",+ "surrogate_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_stalker_remote_identities_provider_id_content_type_surrogate_id` ON `${TABLE_NAME}` (`provider_id`, `content_type`, `surrogate_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "stalker_discovery_staging",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`discovery_id` TEXT NOT NULL, `provider_id` INTEGER, `configuration_generation` INTEGER NOT NULL, `sanitized_summary` TEXT NOT NULL, `categories_json` TEXT NOT NULL, `channels_json` TEXT NOT NULL, `created_at` INTEGER NOT NULL, PRIMARY KEY(`discovery_id`))",+ "fields": [+ {+ "fieldPath": "discoveryId",+ "columnName": "discovery_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "configurationGeneration",+ "columnName": "configuration_generation",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "sanitizedSummary",+ "columnName": "sanitized_summary",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "categoriesJson",+ "columnName": "categories_json",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "channelsJson",+ "columnName": "channels_json",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "discovery_id"+ ]+ },+ "indices": [+ {+ "name": "index_stalker_discovery_staging_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_stalker_discovery_staging_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_stalker_discovery_staging_created_at",+ "unique": false,+ "columnNames": [+ "created_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_stalker_discovery_staging_created_at` ON `${TABLE_NAME}` (`created_at`)"+ }+ ]+ },+ {+ "tableName": "downloads",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `provider_id` INTEGER NOT NULL, `content_type` TEXT NOT NULL, `content_id` INTEGER NOT NULL, `content_name` TEXT NOT NULL, `stream_url` TEXT NOT NULL, `source_stream_url` TEXT, `source_stream_id` INTEGER, `container_extension` TEXT, `poster_url` TEXT, `output_uri` TEXT, `output_display_path` TEXT, `status` TEXT NOT NULL, `bytes_written` INTEGER NOT NULL, `total_bytes` INTEGER, `supports_resume` INTEGER NOT NULL, `retry_count` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `completed_at` INTEGER, `failure_reason` TEXT, `owner_id` TEXT, `owner_epoch` INTEGER NOT NULL, `heartbeat_at` INTEGER, `series_id` INTEGER, `season_number` INTEGER, `episode_number` INTEGER, PRIMARY KEY(`id`))",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentType",+ "columnName": "content_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "contentId",+ "columnName": "content_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentName",+ "columnName": "content_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "sourceStreamUrl",+ "columnName": "source_stream_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "sourceStreamId",+ "columnName": "source_stream_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "containerExtension",+ "columnName": "container_extension",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "posterUrl",+ "columnName": "poster_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "outputUri",+ "columnName": "output_uri",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "outputDisplayPath",+ "columnName": "output_display_path",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "status",+ "columnName": "status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "bytesWritten",+ "columnName": "bytes_written",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "totalBytes",+ "columnName": "total_bytes",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "supportsResume",+ "columnName": "supports_resume",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "retryCount",+ "columnName": "retry_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "completedAt",+ "columnName": "completed_at",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "failureReason",+ "columnName": "failure_reason",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "ownerId",+ "columnName": "owner_id",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "ownerEpoch",+ "columnName": "owner_epoch",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "heartbeatAt",+ "columnName": "heartbeat_at",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "seriesId",+ "columnName": "series_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "seasonNumber",+ "columnName": "season_number",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "episodeNumber",+ "columnName": "episode_number",+ "affinity": "INTEGER"+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_downloads_status",+ "unique": false,+ "columnNames": [+ "status"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_downloads_status` ON `${TABLE_NAME}` (`status`)"+ },+ {+ "name": "index_downloads_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_downloads_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_downloads_content_type_content_id",+ "unique": false,+ "columnNames": [+ "content_type",+ "content_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_downloads_content_type_content_id` ON `${TABLE_NAME}` (`content_type`, `content_id`)"+ }+ ]+ },+ {+ "tableName": "provider_deletion_cleanup",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `action` TEXT NOT NULL, `target_id` TEXT NOT NULL, `created_at` INTEGER NOT NULL, `attempt_count` INTEGER NOT NULL, `last_error` TEXT)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "action",+ "columnName": "action",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "targetId",+ "columnName": "target_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "attemptCount",+ "columnName": "attempt_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastError",+ "columnName": "last_error",+ "affinity": "TEXT"+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_provider_deletion_cleanup_provider_id_action_target_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "action",+ "target_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_provider_deletion_cleanup_provider_id_action_target_id` ON `${TABLE_NAME}` (`provider_id`, `action`, `target_id`)"+ }+ ]+ },+ {+ "tableName": "plugin_provider_ownership",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`package_name` TEXT NOT NULL, `service_class_name` TEXT NOT NULL, `manifest_id` TEXT NOT NULL, `provider_id` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, PRIMARY KEY(`package_name`, `service_class_name`, `manifest_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "packageName",+ "columnName": "package_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "serviceClassName",+ "columnName": "service_class_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "manifestId",+ "columnName": "manifest_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "package_name",+ "service_class_name",+ "manifest_id"+ ]+ },+ "indices": [+ {+ "name": "index_plugin_provider_ownership_provider_id",+ "unique": true,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_plugin_provider_ownership_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "provider_config_revisions",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `revision` INTEGER NOT NULL, `config_json` TEXT NOT NULL, `state` TEXT NOT NULL, `attempt_count` INTEGER NOT NULL, `last_error` TEXT, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, PRIMARY KEY(`provider_id`, `revision`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "revision",+ "columnName": "revision",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "configJson",+ "columnName": "config_json",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "state",+ "columnName": "state",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "attemptCount",+ "columnName": "attempt_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastError",+ "columnName": "last_error",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "provider_id",+ "revision"+ ]+ },+ "indices": [+ {+ "name": "index_provider_config_revisions_provider_id_state",+ "unique": false,+ "columnNames": [+ "provider_id",+ "state"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_provider_config_revisions_provider_id_state` ON `${TABLE_NAME}` (`provider_id`, `state`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "backup_restore_checkpoints",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`restore_key` TEXT NOT NULL, `room_complete` INTEGER NOT NULL, `preferences_complete` INTEGER NOT NULL, `presets_complete` INTEGER NOT NULL, `schedules_complete` INTEGER NOT NULL, `state` TEXT NOT NULL, `preference_snapshot_json` TEXT, `last_error` TEXT, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, PRIMARY KEY(`restore_key`))",+ "fields": [+ {+ "fieldPath": "restoreKey",+ "columnName": "restore_key",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "roomComplete",+ "columnName": "room_complete",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "preferencesComplete",+ "columnName": "preferences_complete",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "presetsComplete",+ "columnName": "presets_complete",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "schedulesComplete",+ "columnName": "schedules_complete",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "state",+ "columnName": "state",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "preferenceSnapshotJson",+ "columnName": "preference_snapshot_json",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lastError",+ "columnName": "last_error",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "restore_key"+ ]+ }+ },+ {+ "tableName": "backup_restore_jobs",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `restore_key` TEXT NOT NULL, `backup_version` INTEGER NOT NULL, `conflict_strategy` TEXT NOT NULL, `status` TEXT NOT NULL, `total_count` INTEGER NOT NULL, `pending_count` INTEGER NOT NULL, `applied_count` INTEGER NOT NULL, `unresolved_count` INTEGER NOT NULL, `failed_count` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, PRIMARY KEY(`id`))",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "restoreKey",+ "columnName": "restore_key",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "backupVersion",+ "columnName": "backup_version",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "conflictStrategy",+ "columnName": "conflict_strategy",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "status",+ "columnName": "status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "totalCount",+ "columnName": "total_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "pendingCount",+ "columnName": "pending_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "appliedCount",+ "columnName": "applied_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "unresolvedCount",+ "columnName": "unresolved_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "failedCount",+ "columnName": "failed_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_backup_restore_jobs_restore_key",+ "unique": true,+ "columnNames": [+ "restore_key"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_backup_restore_jobs_restore_key` ON `${TABLE_NAME}` (`restore_key`)"+ },+ {+ "name": "index_backup_restore_jobs_status",+ "unique": false,+ "columnNames": [+ "status"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_backup_restore_jobs_status` ON `${TABLE_NAME}` (`status`)"+ },+ {+ "name": "index_backup_restore_jobs_updated_at",+ "unique": false,+ "columnNames": [+ "updated_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_backup_restore_jobs_updated_at` ON `${TABLE_NAME}` (`updated_at`)"+ }+ ]+ },+ {+ "tableName": "backup_restore_items",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `job_id` TEXT NOT NULL, `provider_identity_key` TEXT NOT NULL, `local_provider_id` INTEGER, `section` TEXT NOT NULL, `content_type` TEXT, `stable_reference_key` TEXT NOT NULL, `reference_json` TEXT NOT NULL, `payload_json` TEXT NOT NULL, `status` TEXT NOT NULL, `attempt_count` INTEGER NOT NULL, `last_error` TEXT, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, FOREIGN KEY(`job_id`) REFERENCES `backup_restore_jobs`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "jobId",+ "columnName": "job_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "providerIdentityKey",+ "columnName": "provider_identity_key",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "localProviderId",+ "columnName": "local_provider_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "section",+ "columnName": "section",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "contentType",+ "columnName": "content_type",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "stableReferenceKey",+ "columnName": "stable_reference_key",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "referenceJson",+ "columnName": "reference_json",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "payloadJson",+ "columnName": "payload_json",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "status",+ "columnName": "status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "attemptCount",+ "columnName": "attempt_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastError",+ "columnName": "last_error",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_backup_restore_items_job_id",+ "unique": false,+ "columnNames": [+ "job_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_backup_restore_items_job_id` ON `${TABLE_NAME}` (`job_id`)"+ },+ {+ "name": "index_backup_restore_items_provider_identity_key_status",+ "unique": false,+ "columnNames": [+ "provider_identity_key",+ "status"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_backup_restore_items_provider_identity_key_status` ON `${TABLE_NAME}` (`provider_identity_key`, `status`)"+ },+ {+ "name": "index_backup_restore_items_job_id_status",+ "unique": false,+ "columnNames": [+ "job_id",+ "status"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_backup_restore_items_job_id_status` ON `${TABLE_NAME}` (`job_id`, `status`)"+ },+ {+ "name": "index_backup_restore_items_job_id_section_stable_reference_key",+ "unique": true,+ "columnNames": [+ "job_id",+ "section",+ "stable_reference_key"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_backup_restore_items_job_id_section_stable_reference_key` ON `${TABLE_NAME}` (`job_id`, `section`, `stable_reference_key`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "backup_restore_jobs",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "job_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "provider_workflows",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `generation` INTEGER NOT NULL, `state` TEXT NOT NULL, `reason` TEXT NOT NULL, `priority` INTEGER NOT NULL, `force` INTEGER NOT NULL, `current_phase` TEXT, `lease_token` TEXT, `lease_expires_at` INTEGER, `heartbeat_at` INTEGER, `progress_message` TEXT, `last_error_code` TEXT, `last_error_message` TEXT, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, `completed_at` INTEGER, PRIMARY KEY(`provider_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "generation",+ "columnName": "generation",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "state",+ "columnName": "state",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "reason",+ "columnName": "reason",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "priority",+ "columnName": "priority",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "force",+ "columnName": "force",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "currentPhase",+ "columnName": "current_phase",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "leaseToken",+ "columnName": "lease_token",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "leaseExpiresAt",+ "columnName": "lease_expires_at",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "heartbeatAt",+ "columnName": "heartbeat_at",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "progressMessage",+ "columnName": "progress_message",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lastErrorCode",+ "columnName": "last_error_code",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lastErrorMessage",+ "columnName": "last_error_message",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "completedAt",+ "columnName": "completed_at",+ "affinity": "INTEGER"+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "provider_id"+ ]+ },+ "indices": [+ {+ "name": "index_provider_workflows_state",+ "unique": false,+ "columnNames": [+ "state"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_provider_workflows_state` ON `${TABLE_NAME}` (`state`)"+ },+ {+ "name": "index_provider_workflows_updated_at",+ "unique": false,+ "columnNames": [+ "updated_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_provider_workflows_updated_at` ON `${TABLE_NAME}` (`updated_at`)"+ },+ {+ "name": "index_provider_workflows_lease_expires_at",+ "unique": false,+ "columnNames": [+ "lease_expires_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_provider_workflows_lease_expires_at` ON `${TABLE_NAME}` (`lease_expires_at`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "provider_workflow_phases",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `generation` INTEGER NOT NULL, `phase` TEXT NOT NULL, `state` TEXT NOT NULL, `attempt_count` INTEGER NOT NULL, `checkpoint` TEXT, `last_error_code` TEXT, `last_error_message` TEXT, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, `completed_at` INTEGER, PRIMARY KEY(`provider_id`, `generation`, `phase`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "generation",+ "columnName": "generation",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "phase",+ "columnName": "phase",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "state",+ "columnName": "state",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "attemptCount",+ "columnName": "attempt_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "checkpoint",+ "columnName": "checkpoint",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lastErrorCode",+ "columnName": "last_error_code",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lastErrorMessage",+ "columnName": "last_error_message",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "completedAt",+ "columnName": "completed_at",+ "affinity": "INTEGER"+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "provider_id",+ "generation",+ "phase"+ ]+ },+ "indices": [+ {+ "name": "index_provider_workflow_phases_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_provider_workflow_phases_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_provider_workflow_phases_state",+ "unique": false,+ "columnNames": [+ "state"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_provider_workflow_phases_state` ON `${TABLE_NAME}` (`state`)"+ },+ {+ "name": "index_provider_workflow_phases_updated_at",+ "unique": false,+ "columnNames": [+ "updated_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_provider_workflow_phases_updated_at` ON `${TABLE_NAME}` (`updated_at`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "m3u_classification_overrides",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `source_key` TEXT NOT NULL, `stream_id` INTEGER NOT NULL, `target_type` TEXT NOT NULL, `group_key` TEXT NOT NULL, `series_key` TEXT, `series_name` TEXT, `season_number` INTEGER, `episode_number` INTEGER, `episode_title` TEXT, `updated_at` INTEGER NOT NULL, PRIMARY KEY(`provider_id`, `source_key`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "sourceKey",+ "columnName": "source_key",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "streamId",+ "columnName": "stream_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "targetType",+ "columnName": "target_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "groupKey",+ "columnName": "group_key",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "seriesKey",+ "columnName": "series_key",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "seriesName",+ "columnName": "series_name",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "seasonNumber",+ "columnName": "season_number",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "episodeNumber",+ "columnName": "episode_number",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "episodeTitle",+ "columnName": "episode_title",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "provider_id",+ "source_key"+ ]+ },+ "indices": [+ {+ "name": "index_m3u_classification_overrides_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_m3u_classification_overrides_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "m3u_category_classification_rules",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `group_key` TEXT NOT NULL, `target_type` TEXT NOT NULL, `updated_at` INTEGER NOT NULL, PRIMARY KEY(`provider_id`, `group_key`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "groupKey",+ "columnName": "group_key",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "targetType",+ "columnName": "target_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "provider_id",+ "group_key"+ ]+ },+ "indices": [+ {+ "name": "index_m3u_category_classification_rules_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_m3u_category_classification_rules_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ }+ ],+ "setupQueries": [+ "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",+ "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '1a6647887571bedb511009682c1b4129')"+ ]+ }+}\ No newline at end of filediff --git a/data/src/androidTest/java/com/streamvault/data/local/StreamVaultDatabaseMigrationTest.kt b/data/src/androidTest/java/com/streamvault/data/local/StreamVaultDatabaseMigrationTest.ktindex b0dd4794..36ab6048 100644--- a/data/src/androidTest/java/com/streamvault/data/local/StreamVaultDatabaseMigrationTest.kt+++ b/data/src/androidTest/java/com/streamvault/data/local/StreamVaultDatabaseMigrationTest.kt@@ -1659,6 +1659,25 @@ class StreamVaultDatabaseMigrationTest {migrated.close()}+ @Test+ fun migrate76To77_createsDurableBackupRestoreLedger() {+ val name = "streamvault-76-77-backup-restore-ledger"+ migrationTestHelper.createDatabase(name, 76).close()++ val migrated = migrationTestHelper.runMigrationsAndValidate(+ name,+ 77,+ true,+ *StreamVaultDatabaseMigrationRegistry.all.toTypedArray()+ )++ assertEquals(1, countRows(migrated, "SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name='backup_restore_jobs'"))+ assertEquals(1, countRows(migrated, "SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name='backup_restore_items'"))+ assertEquals(1, countRows(migrated, "SELECT COUNT(*) FROM pragma_foreign_key_list('backup_restore_items') WHERE `table`='backup_restore_jobs' AND on_delete='CASCADE'"))+ assertEquals(1, countRows(migrated, "SELECT COUNT(*) FROM pragma_index_list('backup_restore_items') WHERE name='index_backup_restore_items_job_id_section_stable_reference_key' AND `unique`=1"))+ migrated.close()+ }+private fun SupportSQLiteDatabase.insertProvider72(id: Long, name: String, type: String) {execSQL("""diff --git a/data/src/main/java/com/streamvault/data/local/FeatureMigrationsV76To77.kt b/data/src/main/java/com/streamvault/data/local/FeatureMigrationsV76To77.ktnew file mode 100644index 00000000..d66d668d--- /dev/null+++ b/data/src/main/java/com/streamvault/data/local/FeatureMigrationsV76To77.kt@@ -0,0 +1,61 @@+package com.streamvault.data.local++import androidx.room.migration.Migration+import androidx.sqlite.db.SupportSQLiteDatabase++object FeatureMigrationsV76To77 {+ val MIGRATION_76_77 = object : Migration(76, 77) {+ override fun migrate(db: SupportSQLiteDatabase) {+ db.execSQL(+ """+ CREATE TABLE IF NOT EXISTS backup_restore_jobs (+ id TEXT NOT NULL,+ restore_key TEXT NOT NULL,+ backup_version INTEGER NOT NULL,+ conflict_strategy TEXT NOT NULL,+ status TEXT NOT NULL,+ total_count INTEGER NOT NULL DEFAULT 0,+ pending_count INTEGER NOT NULL DEFAULT 0,+ applied_count INTEGER NOT NULL DEFAULT 0,+ unresolved_count INTEGER NOT NULL DEFAULT 0,+ failed_count INTEGER NOT NULL DEFAULT 0,+ created_at INTEGER NOT NULL,+ updated_at INTEGER NOT NULL,+ PRIMARY KEY(id)+ )+ """.trimIndent()+ )+ db.execSQL("CREATE UNIQUE INDEX IF NOT EXISTS index_backup_restore_jobs_restore_key ON backup_restore_jobs(restore_key)")+ db.execSQL("CREATE INDEX IF NOT EXISTS index_backup_restore_jobs_status ON backup_restore_jobs(status)")+ db.execSQL("CREATE INDEX IF NOT EXISTS index_backup_restore_jobs_updated_at ON backup_restore_jobs(updated_at)")+ db.execSQL(+ """+ CREATE TABLE IF NOT EXISTS backup_restore_items (+ id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,+ job_id TEXT NOT NULL,+ provider_identity_key TEXT NOT NULL,+ local_provider_id INTEGER,+ section TEXT NOT NULL,+ content_type TEXT,+ stable_reference_key TEXT NOT NULL,+ reference_json TEXT NOT NULL,+ payload_json TEXT NOT NULL,+ status TEXT NOT NULL,+ attempt_count INTEGER NOT NULL DEFAULT 0,+ last_error TEXT,+ created_at INTEGER NOT NULL,+ updated_at INTEGER NOT NULL,+ FOREIGN KEY(job_id) REFERENCES backup_restore_jobs(id) ON UPDATE NO ACTION ON DELETE CASCADE+ )+ """.trimIndent()+ )+ db.execSQL("CREATE INDEX IF NOT EXISTS index_backup_restore_items_job_id ON backup_restore_items(job_id)")+ db.execSQL("CREATE INDEX IF NOT EXISTS index_backup_restore_items_provider_identity_key_status ON backup_restore_items(provider_identity_key, status)")+ db.execSQL("CREATE INDEX IF NOT EXISTS index_backup_restore_items_job_id_status ON backup_restore_items(job_id, status)")+ db.execSQL(+ "CREATE UNIQUE INDEX IF NOT EXISTS index_backup_restore_items_job_id_section_stable_reference_key " ++ "ON backup_restore_items(job_id, section, stable_reference_key)"+ )+ }+ }+}diff --git a/data/src/main/java/com/streamvault/data/local/StreamVaultDatabase.kt b/data/src/main/java/com/streamvault/data/local/StreamVaultDatabase.ktindex 8611f7af..3ce22f75 100644--- a/data/src/main/java/com/streamvault/data/local/StreamVaultDatabase.kt+++ b/data/src/main/java/com/streamvault/data/local/StreamVaultDatabase.kt@@ -12,7 +12,7 @@ import org.json.JSONObjectimport java.net.URIimport java.security.MessageDigest-internal const val STREAM_VAULT_DATABASE_VERSION = 76+internal const val STREAM_VAULT_DATABASE_VERSION = 77@Database(entities = [@@ -67,6 +67,8 @@ internal const val STREAM_VAULT_DATABASE_VERSION = 76PluginProviderOwnershipEntity::class,ProviderConfigRevisionEntity::class,BackupRestoreCheckpointEntity::class,+ BackupRestoreJobEntity::class,+ BackupRestoreItemEntity::class,ProviderWorkflowEntity::class,ProviderWorkflowPhaseEntity::class,M3uClassificationOverrideEntity::class,@@ -122,6 +124,7 @@ abstract class StreamVaultDatabase : RoomDatabase() {abstract fun pluginProviderOwnershipDao(): PluginProviderOwnershipDaoabstract fun providerConfigRevisionDao(): ProviderConfigRevisionDaoabstract fun backupRestoreCheckpointDao(): BackupRestoreCheckpointDao+ abstract fun backupRestoreLedgerDao(): BackupRestoreLedgerDaoabstract fun providerWorkflowDao(): ProviderWorkflowDaoabstract fun m3uClassificationDao(): M3uClassificationDao@@ -201,5 +204,6 @@ abstract class StreamVaultDatabase : RoomDatabase() {val MIGRATION_73_74 = FeatureMigrationsV49To75.MIGRATION_73_74val MIGRATION_74_75 = FeatureMigrationsV49To75.MIGRATION_74_75val MIGRATION_75_76 = FeatureMigrationsV75To76.MIGRATION_75_76+ val MIGRATION_76_77 = FeatureMigrationsV76To77.MIGRATION_76_77}}diff --git a/data/src/main/java/com/streamvault/data/local/StreamVaultDatabaseMigrationRegistry.kt b/data/src/main/java/com/streamvault/data/local/StreamVaultDatabaseMigrationRegistry.ktindex 062facc9..bca6efd1 100644--- a/data/src/main/java/com/streamvault/data/local/StreamVaultDatabaseMigrationRegistry.kt+++ b/data/src/main/java/com/streamvault/data/local/StreamVaultDatabaseMigrationRegistry.kt@@ -13,7 +13,8 @@ object StreamVaultDatabaseMigrationRegistry {val v24To49: List<Migration> = LegacyMigrationsV24To49.allval v49To75: List<Migration> = FeatureMigrationsV49To75.allval v75To76: List<Migration> = listOf(FeatureMigrationsV75To76.MIGRATION_75_76)- val all: List<Migration> = (v1To24 + v24To49 + v49To75 + v75To76).also(::validate)+ val v76To77: List<Migration> = listOf(FeatureMigrationsV76To77.MIGRATION_76_77)+ val all: List<Migration> = (v1To24 + v24To49 + v49To75 + v75To76 + v76To77).also(::validate)private fun validate(migrations: List<Migration>) {require(migrations.map { it.startVersion }.distinct().size == migrations.size) {diff --git a/data/src/main/java/com/streamvault/data/local/dao/BackupRestoreLedgerDao.kt b/data/src/main/java/com/streamvault/data/local/dao/BackupRestoreLedgerDao.ktnew file mode 100644index 00000000..d4198b34--- /dev/null+++ b/data/src/main/java/com/streamvault/data/local/dao/BackupRestoreLedgerDao.kt@@ -0,0 +1,132 @@+package com.streamvault.data.local.dao++import androidx.room.Dao+import androidx.room.Insert+import androidx.room.OnConflictStrategy+import androidx.room.Query+import androidx.room.Transaction+import com.streamvault.data.local.entity.BackupRestoreItemEntity+import com.streamvault.data.local.entity.BackupRestoreJobEntity+import kotlinx.coroutines.flow.Flow++@Dao+interface BackupRestoreLedgerDao {+ @Insert(onConflict = OnConflictStrategy.IGNORE)+ suspend fun insertJob(job: BackupRestoreJobEntity): Long++ @Insert(onConflict = OnConflictStrategy.IGNORE)+ suspend fun insertItems(items: List<BackupRestoreItemEntity>): List<Long>++ @Query("SELECT * FROM backup_restore_jobs WHERE id = :jobId")+ suspend fun getJob(jobId: String): BackupRestoreJobEntity?++ @Query("SELECT * FROM backup_restore_jobs ORDER BY updated_at DESC")+ fun observeJobs(): Flow<List<BackupRestoreJobEntity>>++ @Query("SELECT * FROM backup_restore_items ORDER BY created_at, id")+ fun observeItems(): Flow<List<BackupRestoreItemEntity>>++ @Query("SELECT * FROM backup_restore_items WHERE job_id = :jobId ORDER BY id")+ suspend fun getItems(jobId: String): List<BackupRestoreItemEntity>++ @Query("SELECT * FROM backup_restore_items WHERE id = :itemId")+ suspend fun getItem(itemId: Long): BackupRestoreItemEntity?++ @Query(+ """+ SELECT * FROM backup_restore_items+ WHERE provider_identity_key = :providerIdentityKey+ AND status IN ('PENDING', 'UNRESOLVED', 'FAILED_RETRYABLE')+ ORDER BY created_at, id+ """+ )+ suspend fun getRetryableItems(providerIdentityKey: String): List<BackupRestoreItemEntity>++ @Query(+ """+ SELECT * FROM backup_restore_items+ WHERE local_provider_id = :providerId+ AND status IN ('PENDING', 'UNRESOLVED', 'FAILED_RETRYABLE')+ ORDER BY created_at, id+ """+ )+ suspend fun getRetryableItemsByLocalProviderId(providerId: Long): List<BackupRestoreItemEntity>++ @Query(+ """+ UPDATE backup_restore_items+ SET status = :status,+ local_provider_id = :localProviderId,+ attempt_count = attempt_count + :attemptIncrement,+ last_error = :lastError,+ updated_at = :updatedAt+ WHERE id = :itemId+ """+ )+ suspend fun updateItemStatus(+ itemId: Long,+ status: String,+ localProviderId: Long?,+ attemptIncrement: Int,+ lastError: String?,+ updatedAt: Long+ )++ @Query(+ """+ UPDATE backup_restore_items+ SET status = 'DISMISSED', updated_at = :updatedAt+ WHERE id = :itemId AND status != 'APPLIED'+ """+ )+ suspend fun dismissItem(itemId: Long, updatedAt: Long): Int++ @Query(+ """+ UPDATE backup_restore_items+ SET status = 'DISMISSED', updated_at = :updatedAt+ WHERE job_id = :jobId AND status != 'APPLIED'+ """+ )+ suspend fun dismissJobItems(jobId: String, updatedAt: Long): Int++ @Query(+ """+ UPDATE backup_restore_items SET status = 'DISMISSED', updated_at = :updatedAt+ WHERE job_id = :jobId AND provider_identity_key = :providerIdentityKey AND status != 'APPLIED'+ """+ )+ suspend fun dismissProvider(jobId: String, providerIdentityKey: String, updatedAt: Long): Int++ @Query(+ """+ UPDATE backup_restore_jobs+ SET total_count = (SELECT COUNT(*) FROM backup_restore_items WHERE job_id = :jobId AND section != 'REPLACE_SCOPE'),+ pending_count = (SELECT COUNT(*) FROM backup_restore_items WHERE job_id = :jobId AND section != 'REPLACE_SCOPE' AND status = 'PENDING'),+ applied_count = (SELECT COUNT(*) FROM backup_restore_items WHERE job_id = :jobId AND section != 'REPLACE_SCOPE' AND status = 'APPLIED'),+ unresolved_count = (SELECT COUNT(*) FROM backup_restore_items WHERE job_id = :jobId AND section != 'REPLACE_SCOPE' AND status = 'UNRESOLVED'),+ failed_count = (SELECT COUNT(*) FROM backup_restore_items WHERE job_id = :jobId AND section != 'REPLACE_SCOPE' AND status = 'FAILED_RETRYABLE'),+ status = CASE+ WHEN EXISTS(SELECT 1 FROM backup_restore_items WHERE job_id = :jobId AND status = 'FAILED_RETRYABLE') THEN 'PARTIAL'+ WHEN EXISTS(SELECT 1 FROM backup_restore_items WHERE job_id = :jobId AND status IN ('PENDING', 'UNRESOLVED')) THEN 'WAITING_FOR_SYNC'+ ELSE 'COMPLETE'+ END,+ updated_at = :updatedAt+ WHERE id = :jobId+ """+ )+ suspend fun refreshJobCounts(jobId: String, updatedAt: Long)++ @Transaction+ suspend fun insertLedger(job: BackupRestoreJobEntity, items: List<BackupRestoreItemEntity>) {+ insertJob(job)+ if (items.isNotEmpty()) insertItems(items)+ refreshJobCounts(job.id, job.updatedAt)+ }++ @Transaction+ suspend fun dismissJob(jobId: String, updatedAt: Long) {+ dismissJobItems(jobId, updatedAt)+ refreshJobCounts(jobId, updatedAt)+ }+}diff --git a/data/src/main/java/com/streamvault/data/local/dao/CatalogSyncDao.kt b/data/src/main/java/com/streamvault/data/local/dao/CatalogSyncDao.ktindex 5614f122..ddc5116e 100644--- a/data/src/main/java/com/streamvault/data/local/dao/CatalogSyncDao.kt+++ b/data/src/main/java/com/streamvault/data/local/dao/CatalogSyncDao.kt@@ -371,7 +371,13 @@ interface CatalogSyncDao {stage.error_count,stage.provider_id,stage.is_adult,- 0,+ CASE WHEN EXISTS (+ SELECT 1 FROM categories AS category+ WHERE category.provider_id = stage.provider_id+ AND category.category_id = stage.category_id+ AND category.type = 'LIVE'+ AND category.is_user_protected = 1+ ) THEN 1 ELSE 0 END,stage.sync_fingerprintFROM channel_import_stage AS stageWHERE stage.session_id = :sessionId@@ -613,7 +619,13 @@ interface CatalogSyncDao {0,0,stage.is_adult,- 0,+ CASE WHEN EXISTS (+ SELECT 1 FROM categories AS category+ WHERE category.provider_id = stage.provider_id+ AND category.category_id = stage.category_id+ AND category.type IN ('MOVIE', 'VOD')+ AND category.is_user_protected = 1+ ) THEN 1 ELSE 0 END,stage.sync_fingerprint,stage.added_atFROM movie_import_stage AS stage@@ -831,7 +843,13 @@ interface CatalogSyncDao {stage.last_modified,stage.provider_id,stage.is_adult,- 0,+ CASE WHEN EXISTS (+ SELECT 1 FROM categories AS category+ WHERE category.provider_id = stage.provider_id+ AND category.category_id = stage.category_id+ AND category.type = 'SERIES'+ AND category.is_user_protected = 1+ ) THEN 1 ELSE 0 END,stage.sync_fingerprintFROM series_import_stage AS stageWHERE stage.session_id = :sessionIddiff --git a/data/src/main/java/com/streamvault/data/local/dao/Daos.kt b/data/src/main/java/com/streamvault/data/local/dao/Daos.ktindex 2972b039..b2af80e3 100644--- a/data/src/main/java/com/streamvault/data/local/dao/Daos.kt+++ b/data/src/main/java/com/streamvault/data/local/dao/Daos.kt@@ -639,9 +639,18 @@ abstract class ChannelDao {@Query("UPDATE channels SET is_user_protected = :isProtected WHERE provider_id = :providerId AND category_id = :categoryId")abstract suspend fun updateProtectionStatus(providerId: Long, categoryId: Long, isProtected: Boolean)+ @Query("UPDATE channels SET is_user_protected = :isProtected WHERE id = :id AND provider_id = :providerId")+ abstract suspend fun updateItemProtection(id: Long, providerId: Long, isProtected: Boolean): Int+@Query("UPDATE channels SET is_user_protected = 0 WHERE provider_id = :providerId AND category_id IN (:categoryIds)")abstract suspend fun clearProtectionForCategories(providerId: Long, categoryIds: List<Long>)+ @Query("UPDATE channels SET is_user_protected = 0 WHERE provider_id = :providerId")+ abstract suspend fun clearItemProtectionByProvider(providerId: Long)++ @Query("UPDATE channels SET is_user_protected = CASE WHEN category_id IN (SELECT category_id FROM categories WHERE provider_id = :providerId AND type = 'LIVE' AND is_user_protected = 1) THEN 1 ELSE 0 END WHERE provider_id = :providerId")+ abstract suspend fun resetProtectionToCategoryState(providerId: Long)+@Query("UPDATE channels SET error_count = error_count + 1 WHERE id = :id")abstract suspend fun incrementErrorCount(id: Long)@@ -669,6 +678,9 @@ interface ChannelPreferenceDao {@Query("SELECT * FROM channel_preferences")suspend fun getAllSync(): List<ChannelPreferenceEntity>+ @Query("DELETE FROM channel_preferences WHERE channel_id IN (SELECT id FROM channels WHERE provider_id = :providerId)")+ suspend fun deleteByProvider(providerId: Long)+@Query("SELECT aspect_ratio FROM channel_preferences WHERE channel_id = :channelId LIMIT 1")fun observeAspectRatio(channelId: Long): Flow<String?>@@ -1854,8 +1866,17 @@ interface MovieDao {@Query("UPDATE movies SET is_user_protected = :isProtected WHERE provider_id = :providerId AND category_id = :categoryId")suspend fun updateProtectionStatus(providerId: Long, categoryId: Long, isProtected: Boolean)+ @Query("UPDATE movies SET is_user_protected = :isProtected WHERE id = :id AND provider_id = :providerId")+ suspend fun updateItemProtection(id: Long, providerId: Long, isProtected: Boolean): Int+@Query("UPDATE movies SET is_user_protected = 0 WHERE provider_id = :providerId AND category_id IN (:categoryIds)")suspend fun clearProtectionForCategories(providerId: Long, categoryIds: List<Long>)++ @Query("UPDATE movies SET is_user_protected = 0 WHERE provider_id = :providerId")+ suspend fun clearItemProtectionByProvider(providerId: Long)++ @Query("UPDATE movies SET is_user_protected = CASE WHEN category_id IN (SELECT category_id FROM categories WHERE provider_id = :providerId AND type IN ('MOVIE', 'VOD') AND is_user_protected = 1) THEN 1 ELSE 0 END WHERE provider_id = :providerId")+ suspend fun resetProtectionToCategoryState(providerId: Long)}@Dao@@ -2822,14 +2843,32 @@ interface SeriesDao {@Query("UPDATE series SET is_user_protected = :isProtected WHERE provider_id = :providerId AND category_id = :categoryId")suspend fun updateProtectionStatus(providerId: Long, categoryId: Long, isProtected: Boolean)+ @Query("UPDATE series SET is_user_protected = :isProtected WHERE id = :id AND provider_id = :providerId")+ suspend fun updateItemProtection(id: Long, providerId: Long, isProtected: Boolean): Int+@Query("UPDATE series SET is_user_protected = 0 WHERE provider_id = :providerId AND category_id IN (:categoryIds)")suspend fun clearProtectionForCategories(providerId: Long, categoryIds: List<Long>)++ @Query("UPDATE series SET is_user_protected = 0 WHERE provider_id = :providerId")+ suspend fun clearItemProtectionByProvider(providerId: Long)++ @Query("UPDATE series SET is_user_protected = CASE WHEN category_id IN (SELECT category_id FROM categories WHERE provider_id = :providerId AND type IN ('SERIES', 'VOD') AND is_user_protected = 1) THEN 1 ELSE 0 END WHERE provider_id = :providerId")+ suspend fun resetProtectionToCategoryState(providerId: Long)}@Dao@RewriteQueriesToDropUnusedColumnsinterface EpisodeDao {+ @Query("UPDATE episodes SET is_user_protected = :isProtected WHERE id = :id AND provider_id = :providerId")+ suspend fun updateItemProtection(id: Long, providerId: Long, isProtected: Boolean): Int++ @Query("UPDATE episodes SET is_user_protected = 0 WHERE provider_id = :providerId")+ suspend fun clearItemProtectionByProvider(providerId: Long)++ @Query("UPDATE episodes SET is_user_protected = CASE WHEN series_id IN (SELECT id FROM series WHERE provider_id = :providerId AND is_user_protected = 1) THEN 1 ELSE 0 END WHERE provider_id = :providerId")+ suspend fun resetProtectionToCategoryState(providerId: Long)+@Query("SELECT * FROM episodes WHERE series_id = :seriesId ORDER BY season_number ASC, episode_number ASC")fun getBySeries(seriesId: Long): Flow<List<EpisodeBrowseEntity>>@@ -2845,6 +2884,9 @@ interface EpisodeDao {@Query("SELECT * FROM episodes WHERE provider_id = :providerId AND episode_id = :episodeId LIMIT 1")suspend fun getByProviderAndEpisodeId(providerId: Long, episodeId: Long): EpisodeEntity?+ @Query("SELECT * FROM episodes WHERE provider_id = :providerId")+ suspend fun getByProviderSync(providerId: Long): List<EpisodeEntity>+@Insert(onConflict = OnConflictStrategy.REPLACE)suspend fun insert(episode: EpisodeEntity): Long@@ -3376,6 +3418,9 @@ abstract class FavoriteDao {@Query("DELETE FROM favorites WHERE provider_id = :providerId AND content_type = :contentType")abstract suspend fun deleteByProviderAndType(providerId: Long, contentType: String)+ @Query("DELETE FROM favorites WHERE provider_id = :providerId AND content_type = :contentType AND group_id IS NULL")+ abstract suspend fun deleteGlobalByProviderAndType(providerId: Long, contentType: String)+@Query("UPDATE favorites SET content_id = :newContentId, content_type = :newContentType, " +"group_id = NULL, group_key = 0 WHERE provider_id = :providerId " +@@ -3597,6 +3642,15 @@ interface PlaybackHistoryDao {@Daointerface SearchHistoryDao {+ @Query("SELECT * FROM search_history ORDER BY used_at DESC")+ suspend fun getAllSync(): List<SearchHistoryEntity>++ @Query("SELECT * FROM search_history WHERE query = :query AND content_scope = :contentScope AND provider_id = :providerId LIMIT 1")+ suspend fun get(query: String, contentScope: String, providerId: Long): SearchHistoryEntity?++ @Insert(onConflict = OnConflictStrategy.REPLACE)+ suspend fun upsert(entity: SearchHistoryEntity): Long+@Query("""SELECT * FROM search_history@@ -3645,6 +3699,9 @@ interface SearchHistoryDao {@Query("DELETE FROM search_history WHERE content_scope = :contentScope AND provider_id = :providerId")suspend fun deleteByScope(contentScope: String, providerId: Long)+ @Query("DELETE FROM search_history WHERE provider_id = :providerId")+ suspend fun deleteByProvider(providerId: Long)+@Query("DELETE FROM search_history WHERE used_at < :minUsedAt")suspend fun pruneOlderThan(minUsedAt: Long)diff --git a/data/src/main/java/com/streamvault/data/local/entity/BackupRestoreLedgerEntities.kt b/data/src/main/java/com/streamvault/data/local/entity/BackupRestoreLedgerEntities.ktnew file mode 100644index 00000000..93a07a2e--- /dev/null+++ b/data/src/main/java/com/streamvault/data/local/entity/BackupRestoreLedgerEntities.kt@@ -0,0 +1,76 @@+package com.streamvault.data.local.entity++import androidx.room.ColumnInfo+import androidx.room.Entity+import androidx.room.ForeignKey+import androidx.room.Index+import androidx.room.PrimaryKey++@Entity(+ tableName = "backup_restore_jobs",+ indices = [+ Index(value = ["restore_key"], unique = true),+ Index(value = ["status"]),+ Index(value = ["updated_at"])+ ]+)+data class BackupRestoreJobEntity(+ @PrimaryKey val id: String,+ @ColumnInfo(name = "restore_key") val restoreKey: String,+ @ColumnInfo(name = "backup_version") val backupVersion: Int,+ @ColumnInfo(name = "conflict_strategy") val conflictStrategy: String,+ val status: String,+ @ColumnInfo(name = "total_count") val totalCount: Int = 0,+ @ColumnInfo(name = "pending_count") val pendingCount: Int = 0,+ @ColumnInfo(name = "applied_count") val appliedCount: Int = 0,+ @ColumnInfo(name = "unresolved_count") val unresolvedCount: Int = 0,+ @ColumnInfo(name = "failed_count") val failedCount: Int = 0,+ @ColumnInfo(name = "created_at") val createdAt: Long,+ @ColumnInfo(name = "updated_at") val updatedAt: Long+)++@Entity(+ tableName = "backup_restore_items",+ foreignKeys = [+ ForeignKey(+ entity = BackupRestoreJobEntity::class,+ parentColumns = ["id"],+ childColumns = ["job_id"],+ onDelete = ForeignKey.CASCADE+ )+ ],+ indices = [+ Index(value = ["job_id"]),+ Index(value = ["provider_identity_key", "status"]),+ Index(value = ["job_id", "status"]),+ Index(+ name = "index_backup_restore_items_job_id_section_stable_reference_key",+ value = ["job_id", "section", "stable_reference_key"],+ unique = true+ )+ ]+)+data class BackupRestoreItemEntity(+ @PrimaryKey(autoGenerate = true) val id: Long = 0,+ @ColumnInfo(name = "job_id") val jobId: String,+ @ColumnInfo(name = "provider_identity_key") val providerIdentityKey: String,+ @ColumnInfo(name = "local_provider_id") val localProviderId: Long? = null,+ val section: String,+ @ColumnInfo(name = "content_type") val contentType: String? = null,+ @ColumnInfo(name = "stable_reference_key") val stableReferenceKey: String,+ @ColumnInfo(name = "reference_json") val referenceJson: String,+ @ColumnInfo(name = "payload_json") val payloadJson: String,+ val status: String = STATUS_PENDING,+ @ColumnInfo(name = "attempt_count") val attemptCount: Int = 0,+ @ColumnInfo(name = "last_error") val lastError: String? = null,+ @ColumnInfo(name = "created_at") val createdAt: Long,+ @ColumnInfo(name = "updated_at") val updatedAt: Long+) {+ companion object {+ const val STATUS_PENDING = "PENDING"+ const val STATUS_APPLIED = "APPLIED"+ const val STATUS_UNRESOLVED = "UNRESOLVED"+ const val STATUS_FAILED_RETRYABLE = "FAILED_RETRYABLE"+ const val STATUS_DISMISSED = "DISMISSED"+ }+}diff --git a/data/src/main/java/com/streamvault/data/manager/BackupManagerImpl.kt b/data/src/main/java/com/streamvault/data/manager/BackupManagerImpl.ktindex 8813932b..10c27887 100644--- a/data/src/main/java/com/streamvault/data/manager/BackupManagerImpl.kt+++ b/data/src/main/java/com/streamvault/data/manager/BackupManagerImpl.kt@@ -14,6 +14,7 @@ import com.google.gson.stream.JsonWriterimport com.google.gson.stream.MalformedJsonExceptionimport com.streamvault.data.local.DatabaseTransactionRunnerimport com.streamvault.data.local.dao.BackupRestoreCheckpointDao+import com.streamvault.data.local.dao.BackupRestoreLedgerDaoimport com.streamvault.data.local.dao.ChannelDaoimport com.streamvault.data.local.dao.CategoryDaoimport com.streamvault.data.local.dao.ChannelPreferenceDao@@ -31,12 +32,15 @@ import com.streamvault.data.local.dao.ProviderEpgSourceDaoimport com.streamvault.data.local.dao.ProviderSnapshotDaoimport com.streamvault.data.local.dao.RecordingScheduleDaoimport com.streamvault.data.local.dao.SeriesDao+import com.streamvault.data.local.dao.SearchHistoryDaoimport com.streamvault.data.local.dao.VirtualGroupDaoimport com.streamvault.data.local.entity.ProviderEntityimport com.streamvault.data.local.entity.CategoryEntityimport com.streamvault.data.local.entity.ProviderAccountRuntimeEntityimport com.streamvault.data.local.entity.ProviderConfigEntityimport com.streamvault.data.local.entity.BackupRestoreCheckpointEntity+import com.streamvault.data.local.entity.BackupRestoreItemEntity+import com.streamvault.data.local.entity.BackupRestoreJobEntityimport com.streamvault.data.local.entity.ChannelPreferenceEntityimport com.streamvault.data.local.entity.ChannelEpgMappingEntityimport com.streamvault.data.local.entity.ProviderEpgSourceEntity@@ -84,6 +88,17 @@ import com.streamvault.domain.manager.CombinedM3uProfileMemberBackupimport com.streamvault.domain.manager.PortableCategoryReferenceimport com.streamvault.domain.manager.PortableCategorySortReferenceimport com.streamvault.domain.manager.PortableChannelReference+import com.streamvault.domain.manager.PortableFavoriteBackup+import com.streamvault.domain.manager.PortableCustomGroupBackup+import com.streamvault.domain.manager.PortablePlaybackHistoryBackup+import com.streamvault.domain.manager.PortableProtectedContentBackup+import com.streamvault.domain.manager.PortableHiddenContentBackup+import com.streamvault.domain.manager.PortableContentPreferenceBackup+import com.streamvault.domain.manager.PortableContentReference+import com.streamvault.domain.manager.PortableVariantChoiceBackup+import com.streamvault.domain.manager.PortableManualEpgMappingV14Backup+import com.streamvault.domain.manager.PortableMultiViewPresetV14Backup+import com.streamvault.domain.manager.PortableSearchHistoryBackupimport com.streamvault.domain.manager.PortableChannelPreferenceReferenceimport com.streamvault.domain.manager.PortableEpgTimeShiftReferenceimport com.streamvault.domain.manager.PortableProviderPreferencesBackup@@ -159,6 +174,7 @@ class BackupManagerImpl @Inject constructor(private val providerSnapshotDao: ProviderSnapshotDao? = null,private val providerConfigurationCodec: ProviderConfigurationCodec? = null,private val backupRestoreCheckpointDao: BackupRestoreCheckpointDao? = null,+ private val backupRestoreLedgerDao: BackupRestoreLedgerDao? = null,private val channelDao: ChannelDao,private val seriesDao: SeriesDao,private val categoryDao: CategoryDao? = null,@@ -169,7 +185,9 @@ class BackupManagerImpl @Inject constructor(private val providerEpgSourceDao: ProviderEpgSourceDao? = null,private val channelEpgMappingDao: ChannelEpgMappingDao? = null,private val m3uClassificationDao: M3uClassificationDao? = null,- private val programReminderManager: ProgramReminderManager? = null+ private val programReminderManager: ProgramReminderManager? = null,+ private val searchHistoryDao: SearchHistoryDao? = null,+ private val pendingBackupRestoreCoordinator: PendingBackupRestoreCoordinator? = null) : BackupManager {override suspend fun exportConfig(uriString: String): com.streamvault.domain.model.Result<Unit> = withContext(Dispatchers.IO) {@@ -380,7 +398,8 @@ class BackupManagerImpl @Inject constructor(provider = provider.toBackupProviderReference(),streamId = channel.streamId,name = channel.name,- streamUrl = channel.streamUrl+ streamUrl = channel.streamUrl,+ remoteCategoryId = channel.categoryId)}}@@ -410,15 +429,17 @@ class BackupManagerImpl @Inject constructor(}val providerEpgAssignments = if (providerEpgSourceDao != null && epgSourceDao != null) {providers.flatMap { provider ->- providerEpgSourceDao.getForProviderSync(provider.id).mapNotNull { assignment ->- epgSourceDao.getById(assignment.epgSourceId)?.let { source ->- ProviderEpgAssignmentBackup(- provider = provider.toBackupProviderReference(),- sourceUrl = source.url,- priority = assignment.priority,- enabled = assignment.enabled+ providerEpgSourceDao.getForProviderSync(provider.id).map { assignment ->+ val source = epgSourceDao.getById(assignment.epgSourceId)+ ?: return@withContext Result.error(+ "Cannot export EPG Provider Assignments: '${provider.name}' references missing source ${assignment.epgSourceId}")- }+ ProviderEpgAssignmentBackup(+ provider = provider.toBackupProviderReference(),+ sourceUrl = source.url,+ priority = assignment.priority,+ enabled = assignment.enabled+ )}}} else {@@ -428,18 +449,27 @@ class BackupManagerImpl @Inject constructor(providers.flatMap { provider ->channelEpgMappingDao.getForProvider(provider.id).filter { it.isManualOverride }- .mapNotNull { mapping ->+ .map { mapping ->val channel = channelDao.getById(mapping.providerChannelId)?.takeIf { it.providerId == provider.id }- ?: return@mapNotNull null+ ?: return@withContext Result.error(+ "Cannot export Manual EPG Mappings: channel row ${mapping.providerChannelId} is missing for '${provider.name}'"+ )+ val sourceUrl = mapping.epgSourceId?.let { sourceId ->+ epgSourceDao.getById(sourceId)?.url+ ?: return@withContext Result.error(+ "Cannot export Manual EPG Mappings: source $sourceId is missing for channel '${channel.name}'"+ )+ }ManualEpgMappingBackup(channel = PortableChannelReference(provider = provider.toBackupProviderReference(),streamId = channel.streamId,name = channel.name,- streamUrl = channel.streamUrl+ streamUrl = channel.streamUrl,+ remoteCategoryId = channel.categoryId),- sourceUrl = mapping.epgSourceId?.let { epgSourceDao.getById(it)?.url },+ sourceUrl = sourceUrl,xmltvChannelId = mapping.xmltvChannelId,sourceType = mapping.sourceType,matchType = mapping.matchType,@@ -486,26 +516,36 @@ class BackupManagerImpl @Inject constructor(}val programReminders = programReminderManager?.observeUpcomingReminders()?.first()?.filter { it.programStartTime > System.currentTimeMillis() && !it.isDismissed }- ?.mapNotNull { reminder ->- providersById[reminder.providerId]?.let { provider ->- ProgramReminderBackup(- provider = provider.toBackupProviderReference(),- channelId = reminder.channelId,- channelName = reminder.channelName,- programTitle = reminder.programTitle,- programStartTime = reminder.programStartTime,- leadTimeMinutes = reminder.leadTimeMinutes+ ?.map { reminder ->+ val provider = providersById[reminder.providerId]+ ?: return@withContext Result.error(+ "Cannot export Program Reminders: '${reminder.programTitle}' references missing provider ${reminder.providerId}")- }+ ProgramReminderBackup(+ provider = provider.toBackupProviderReference(),+ channelId = reminder.channelId,+ channelName = reminder.channelName,+ programTitle = reminder.programTitle,+ programStartTime = reminder.programStartTime,+ leadTimeMinutes = reminder.leadTimeMinutes+ )}val scheduledRecordings = recordingManager.observeRecordingItems().first().filter { it.status == RecordingStatus.SCHEDULED && it.scheduledEndMs > System.currentTimeMillis() }.mapNotNull { item ->- val provider = providersById[item.providerId] ?: return@mapNotNull null- item.toScheduledRecordingBackup(+ val provider = providersById[item.providerId]+ ?: return@withContext Result.error(+ "Cannot export Recording Schedules: '${item.channelName}' references missing provider ${item.providerId}"+ )+ val legacy = item.toScheduledRecordingBackup(provider = provider,schedule = item.scheduleId?.let { scheduleId -> recordingScheduleDao.getById(scheduleId) })+ val channel = channelDao.getById(item.channelId)+ ?: return@withContext Result.error(+ "Cannot export Recording Schedules: channel '${item.channelName}' is not in the synced catalog"+ )+ legacy.copy(channel = channel.toPortableContentReference(provider.toBackupProviderReference()))}.normalizedRecurringBackups()val recordingStorage = recordingManager.observeStorageState().first().let { storage ->@@ -528,15 +568,213 @@ class BackupManagerImpl @Inject constructor()}+ val ungroupedFavorites = allFavorites.filter { it.groupId == null }+ val portableFavorites = ungroupedFavorites.mapNotNull { favorite ->+ favorite.toPortableContentReference(providersById, channelDao, movieDao, seriesDao)?.let { reference ->+ PortableFavoriteBackup(+ content = reference,+ position = favorite.position,+ addedAt = favorite.addedAt+ )+ }+ }+ if (portableFavorites.size != ungroupedFavorites.size) {+ return@withContext Result.error(+ "Cannot export Favorites: ${ungroupedFavorites.size - portableFavorites.size} item(s) lack portable catalog identity"+ )+ }+ val portableCustomGroups = allGroups.map { group ->+ val provider = providersById[group.providerId]+ ?: return@withContext Result.error("Cannot export custom group '${group.name}': provider is missing")+ val members = allFavorites.filter { favorite -> favorite.groupId == group.id }+ .mapNotNull { favorite ->+ favorite.toPortableContentReference(providersById, channelDao, movieDao, seriesDao)?.let { reference ->+ PortableFavoriteBackup(reference, favorite.position, favorite.addedAt)+ }+ }+ if (members.size != allFavorites.count { it.groupId == group.id }) {+ return@withContext Result.error(+ "Cannot export custom group '${group.name}': one or more members lack portable catalog identity"+ )+ }+ PortableCustomGroupBackup(+ provider = provider.toBackupProviderReference(),+ contentType = group.contentType,+ name = group.name,+ icon = group.iconEmoji,+ position = group.position,+ createdAt = group.createdAt,+ members = members+ )+ }+ val portablePlaybackHistory = playbackHistory.mapNotNull { history ->+ history.toPortableContentReference(providersById, channelDao, movieDao, seriesDao, episodeDao)?.let { reference ->+ PortablePlaybackHistoryBackup(+ content = reference,+ resumePositionMs = history.resumePositionMs,+ totalDurationMs = history.totalDurationMs,+ lastWatchedAt = history.lastWatchedAt,+ watchCount = history.watchCount,+ watchedStatus = history.watchedStatus.name,+ posterUrl = history.posterUrl,+ seasonNumber = history.seasonNumber,+ episodeNumber = history.episodeNumber+ )+ }+ }+ if (portablePlaybackHistory.size != playbackHistory.size) {+ return@withContext Result.error(+ "Cannot export Playback History: ${playbackHistory.size - portablePlaybackHistory.size} item(s) lack portable catalog identity"+ )+ }+ val portableProtectedContent = providers.flatMap { provider ->+ val reference = provider.toBackupProviderReference()+ val providerSeries = seriesDao.getByProviderSync(provider.id)+ val seriesByLocalId = providerSeries.associateBy { it.id }+ val protectedEpisodes = episodeDao.getByProviderSync(provider.id).filter { it.isUserProtected }+ val orphanedProtectedEpisode = protectedEpisodes.firstOrNull { it.seriesId !in seriesByLocalId }+ if (orphanedProtectedEpisode != null) {+ return@withContext Result.error(+ "Cannot export Protected Content: episode '${orphanedProtectedEpisode.title}' has no parent series identity"+ )+ }+ buildList {+ channelDao.getByProviderSync(provider.id).filter { it.isUserProtected }.forEach { channel ->+ add(PortableProtectedContentBackup(channel.toPortableContentReference(reference)))+ }+ movieDao.getByProviderSync(provider.id).filter { it.isUserProtected }.forEach { movie ->+ add(PortableProtectedContentBackup(movie.toPortableContentReference(reference)))+ }+ providerSeries.filter { it.isUserProtected }.forEach { series ->+ add(PortableProtectedContentBackup(series.toPortableContentReference(reference)))+ }+ protectedEpisodes.forEach { episode ->+ add(+ PortableProtectedContentBackup(+ episode.toPortableContentReference(reference, checkNotNull(seriesByLocalId[episode.seriesId]))+ )+ )+ }+ }+ }+ val portableHiddenContent = portableProviderPreferences.hiddenChannels.map { channel ->+ PortableHiddenContentBackup(+ com.streamvault.domain.manager.PortableContentReference(+ provider = channel.provider,+ contentType = ContentType.LIVE,+ remoteContentId = channel.streamId.toString(),+ remoteCategoryId = channel.remoteCategoryId?.toString(),+ name = channel.name,+ urlFallback = channel.streamUrl+ )+ )+ }+ val portableContentPreferences = portableProviderPreferences.channelPreferences.map { preference ->+ PortableContentPreferenceBackup(+ content = com.streamvault.domain.manager.PortableContentReference(+ provider = preference.channel.provider,+ contentType = ContentType.LIVE,+ remoteContentId = preference.channel.streamId.toString(),+ remoteCategoryId = preference.channel.remoteCategoryId?.toString(),+ name = preference.channel.name,+ urlFallback = preference.channel.streamUrl+ ),+ aspectRatio = preference.aspectRatio,+ audioVideoOffsetMs = preference.audioVideoOffsetMs+ )+ }+ val portableVariantChoices = buildList {+ portableProviderPreferences.liveVariantSelections.forEach { choice ->+ choice.remoteItemId?.let { remoteId ->+ add(+ PortableVariantChoiceBackup(+ logicalGroupId = choice.logicalGroupId,+ selectedContent = com.streamvault.domain.manager.PortableContentReference(+ provider = choice.provider,+ contentType = ContentType.LIVE,+ remoteContentId = remoteId,+ remoteCategoryId = choice.remoteCategoryId?.toString()+ )+ )+ )+ }+ }+ portableProviderPreferences.vodVariantSelections.forEach { choice ->+ choice.remoteItemId?.let { remoteId ->+ add(+ PortableVariantChoiceBackup(+ logicalGroupId = choice.logicalGroupId,+ selectedContent = com.streamvault.domain.manager.PortableContentReference(+ provider = choice.provider,+ contentType = choice.contentType ?: ContentType.MOVIE,+ remoteContentId = remoteId,+ remoteCategoryId = choice.remoteCategoryId?.toString()+ )+ )+ )+ }+ }+ }+ val portableManualEpgMappings = manualEpgMappings.orEmpty().map { mapping ->+ PortableManualEpgMappingV14Backup(+ content = com.streamvault.domain.manager.PortableContentReference(+ provider = mapping.channel.provider,+ contentType = ContentType.LIVE,+ remoteContentId = mapping.channel.streamId.toString(),+ remoteCategoryId = mapping.channel.remoteCategoryId?.toString(),+ name = mapping.channel.name,+ urlFallback = mapping.channel.streamUrl+ ),+ sourceUrl = mapping.sourceUrl,+ xmltvChannelId = mapping.xmltvChannelId,+ sourceType = mapping.sourceType,+ matchType = mapping.matchType,+ confidence = mapping.confidence,+ source = mapping.source+ )+ }+ val portableMultiViewPresetsV14 = portableMultiViewPresets.map { (name, channels) ->+ PortableMultiViewPresetV14Backup(+ name = name,+ channels = channels.map { channel ->+ com.streamvault.domain.manager.PortableContentReference(+ provider = channel.provider,+ contentType = ContentType.LIVE,+ remoteContentId = channel.streamId.toString(),+ remoteCategoryId = channel.remoteCategoryId?.toString(),+ name = channel.name,+ urlFallback = channel.streamUrl+ )+ }+ )+ }+ val portableSearchHistory = searchHistoryDao?.getAllSync()?.map { history ->+ val providerReference = if (history.providerId == 0L) {+ null+ } else {+ providersById[history.providerId]?.toBackupProviderReference()+ ?: return@withContext Result.error(+ "Cannot export Search History: '${history.query}' references missing provider ${history.providerId}"+ )+ }+ PortableSearchHistoryBackup(+ query = history.query,+ contentScope = history.contentScope,+ provider = providerReference,+ usedAt = history.usedAt,+ useCount = history.useCount+ )+ }+val backupData = BackupData(version = CURRENT_BACKUP_VERSION,preferences = prefs,providers = null,providerSnapshots = providerSnapshots,- favorites = allFavorites,- virtualGroups = allGroups,- playbackHistory = playbackHistory,- multiViewPresets = multiViewPresets,+ favorites = null,+ virtualGroups = null,+ playbackHistory = null,+ multiViewPresets = null,portableMultiViewPresets = portableMultiViewPresets,protectedCategories = protectedCategories,scheduledRecordings = scheduledRecordings,@@ -545,12 +783,22 @@ class BackupManagerImpl @Inject constructor(providerCredentials = providerCredentials.takeIf { it.isNotEmpty() },epgSources = epgSourceDao?.getAllSync()?.map { it.toDomain() },providerEpgAssignments = providerEpgAssignments,- manualEpgMappings = manualEpgMappings,+ manualEpgMappings = null,m3uClassificationOverrides = m3uClassificationOverrides,m3uClassificationRules = m3uClassificationRules,programReminders = programReminders,combinedM3uProfiles = combinedM3uProfiles,- activeLiveSource = activeLiveSource+ activeLiveSource = activeLiveSource,+ portableFavorites = portableFavorites,+ portableCustomGroups = portableCustomGroups,+ portablePlaybackHistory = portablePlaybackHistory,+ portableProtectedContent = portableProtectedContent,+ portableSearchHistory = portableSearchHistory,+ portableHiddenContent = portableHiddenContent,+ portableContentPreferences = portableContentPreferences,+ portableVariantChoices = portableVariantChoices,+ portableManualEpgMappings = portableManualEpgMappings,+ portableMultiViewPresetsV14 = portableMultiViewPresetsV14)// Compute checksum over the data without checksum field@@ -810,7 +1058,24 @@ class BackupManagerImpl @Inject constructor(restorePreferences(it, skipProviderScopedReferences = portablePreferences != null)}val preferenceUnresolved = portablePreferences?.let { portable ->- restorePortableProviderPreferences(portable, storedProviders)+ restorePortableProviderPreferences(+ if (backupData.version >= 14 && (+ backupData.portableHiddenContent != null ||+ backupData.portableContentPreferences != null ||+ backupData.portableVariantChoices != null+ )) {+ portable.copy(+ hiddenChannels = emptyList(),+ channelPreferences = emptyList(),+ channelPreferencesSpecified = false,+ liveVariantSelections = emptyList(),+ liveVariantSelectionsSpecified = false,+ vodVariantSelections = emptyList(),+ vodVariantSelectionsSpecified = false+ )+ } else portable,+ storedProviders+ )}.orEmpty()unresolvedReferences += preferenceUnresolvedval portableComplete = preferenceUnresolved.isEmpty()@@ -852,7 +1117,11 @@ class BackupManagerImpl @Inject constructor(else -> try {checkpoint = checkpoint.ensurePreferenceSnapshot()val portableUnresolved = portablePresets?.let {- restorePortableMultiViewPresets(it, storedProviders)+ if (backupData.version >= 14 && backupData.portableMultiViewPresetsV14 != null) {+ emptyList()+ } else {+ restorePortableMultiViewPresets(it, storedProviders)+ }}.orEmpty()unresolvedReferences += portableUnresolvedif (portablePresets == null) {@@ -884,7 +1153,11 @@ class BackupManagerImpl @Inject constructor(}} else skippedSections += "Split Screen Presets"- val recordingScheduleImport = if (plan.importRecordingSchedules && !checkpoint.schedulesComplete) {+ val recordingScheduleImport = if (+ plan.importRecordingSchedules &&+ !checkpoint.schedulesComplete &&+ !(backupData.version >= 14 && backupData.scheduledRecordings.orEmpty().any { it.channel != null })+ ) {backupData.scheduledRecordings?.let { recordings ->try {importScheduledRecordingBackups(@@ -942,9 +1215,38 @@ class BackupManagerImpl @Inject constructor(}} ?: skippedSections.add("Recording Storage Settings")- val outcome = if (failedSections.isEmpty()) BackupRestoreOutcome.COMPLETE else BackupRestoreOutcome.PARTIAL+ var queuedRestore = queuePortableRestoreItems(+ backupData = backupData,+ plan = plan,+ restoreKey = restoreKey,+ storedProviders = storedProviders+ )+ if (queuedRestore != null) {+ pendingBackupRestoreCoordinator?.applyGlobal()+ queuedRestore.affectedProviders.forEach { reference ->+ storedProviders.findUnambiguousPortableProvider(reference)?.id?.let { providerId ->+ pendingBackupRestoreCoordinator?.applyForProvider(providerId)+ }+ }+ backupRestoreLedgerDao?.getJob(queuedRestore.jobId)?.let { job ->+ queuedRestore = queuedRestore.copy(+ pendingCount = job.pendingCount + job.failedCount,+ unresolvedCount = job.unresolvedCount+ )+ }+ }+ val outcome = when {+ failedSections.isNotEmpty() -> BackupRestoreOutcome.PARTIAL+ queuedRestore != null && queuedRestore.pendingCount + queuedRestore.unresolvedCount > 0 ->+ BackupRestoreOutcome.WAITING_FOR_SYNC+ else -> BackupRestoreOutcome.COMPLETE+ }checkpoint = checkpoint.copy(- state = if (outcome == BackupRestoreOutcome.COMPLETE) RESTORE_STATE_COMPLETE else RESTORE_STATE_PARTIAL,+ state = when (outcome) {+ BackupRestoreOutcome.COMPLETE -> RESTORE_STATE_COMPLETE+ BackupRestoreOutcome.WAITING_FOR_SYNC -> RESTORE_STATE_WAITING_FOR_SYNC+ else -> RESTORE_STATE_PARTIAL+ },lastError = failedSections.joinToString().takeIf { it.isNotBlank() },updatedAt = System.currentTimeMillis()).persist()@@ -955,12 +1257,17 @@ class BackupManagerImpl @Inject constructor(skippedSections = skippedSections.distinct(),failedSections = failedSections.distinct(),unresolvedReferences = unresolvedReferences.distinct(),- recordingScheduleImport = recordingScheduleImport+ recordingScheduleImport = recordingScheduleImport,+ restoreJobId = queuedRestore?.jobId,+ pendingCount = queuedRestore?.pendingCount ?: 0,+ unresolvedCount = queuedRestore?.unresolvedCount ?: 0,+ affectedProviders = queuedRestore?.affectedProviders.orEmpty()))} catch (cancelled: CancellationException) {throw cancelled} catch (e: Exception) {+ android.util.Log.e("BackupManager", "Backup import failed", e)com.streamvault.domain.model.Result.error("Failed to import backup: ${e.message}", e)}}@@ -1206,6 +1513,41 @@ class BackupManagerImpl @Inject constructor(backupData.activeLiveSource,ACTIVE_LIVE_SOURCE_BACKUP_TYPE)+ writeNamedJsonField(jsonWriter, "portableFavorites", backupData.portableFavorites, PORTABLE_FAVORITE_LIST_TYPE)+ writeNamedJsonField(+ jsonWriter,+ "portableCustomGroups",+ backupData.portableCustomGroups,+ PORTABLE_CUSTOM_GROUP_LIST_TYPE+ )+ writeNamedJsonField(+ jsonWriter,+ "portablePlaybackHistory",+ backupData.portablePlaybackHistory,+ PORTABLE_PLAYBACK_HISTORY_LIST_TYPE+ )+ writeNamedJsonField(+ jsonWriter,+ "portableProtectedContent",+ backupData.portableProtectedContent,+ PORTABLE_PROTECTED_CONTENT_LIST_TYPE+ )+ writeNamedJsonField(+ jsonWriter,+ "portableSearchHistory",+ backupData.portableSearchHistory,+ PORTABLE_SEARCH_HISTORY_LIST_TYPE+ )+ writeNamedJsonField(+ jsonWriter,+ "portableHiddenContent",+ backupData.portableHiddenContent,+ PORTABLE_HIDDEN_CONTENT_LIST_TYPE+ )+ writeNamedJsonField(jsonWriter, "portableContentPreferences", backupData.portableContentPreferences, PORTABLE_CONTENT_PREFERENCE_LIST_TYPE)+ writeNamedJsonField(jsonWriter, "portableVariantChoices", backupData.portableVariantChoices, PORTABLE_VARIANT_CHOICE_LIST_TYPE)+ writeNamedJsonField(jsonWriter, "portableManualEpgMappings", backupData.portableManualEpgMappings, PORTABLE_MANUAL_EPG_V14_LIST_TYPE)+ writeNamedJsonField(jsonWriter, "portableMultiViewPresetsV14", backupData.portableMultiViewPresetsV14, PORTABLE_MULTIVIEW_V14_LIST_TYPE)jsonWriter.endObject()}}@@ -1315,6 +1657,16 @@ class BackupManagerImpl @Inject constructor(var programReminders: List<ProgramReminderBackup>? = nullvar combinedM3uProfiles: List<CombinedM3uProfileBackup>? = nullvar activeLiveSource: ActiveLiveSourceBackup? = null+ var portableFavorites: List<PortableFavoriteBackup>? = null+ var portableCustomGroups: List<PortableCustomGroupBackup>? = null+ var portablePlaybackHistory: List<PortablePlaybackHistoryBackup>? = null+ var portableProtectedContent: List<PortableProtectedContentBackup>? = null+ var portableSearchHistory: List<PortableSearchHistoryBackup>? = null+ var portableHiddenContent: List<PortableHiddenContentBackup>? = null+ var portableContentPreferences: List<PortableContentPreferenceBackup>? = null+ var portableVariantChoices: List<PortableVariantChoiceBackup>? = null+ var portableManualEpgMappings: List<PortableManualEpgMappingV14Backup>? = null+ var portableMultiViewPresetsV14: List<PortableMultiViewPresetV14Backup>? = nullval seenFields = hashSetOf<String>()var headerRead = false@@ -1412,6 +1764,26 @@ class BackupManagerImpl @Inject constructor()"activeLiveSource" -> activeLiveSource =readLegacyAwareValue(reader, ACTIVE_LIVE_SOURCE_BACKUP_TYPE)+ "portableFavorites" -> portableFavorites =+ readLimitedArray(reader, PORTABLE_FAVORITE_TYPE, MAX_SECTION_ITEMS, "portable favorites")+ "portableCustomGroups" -> portableCustomGroups =+ readLimitedArray(reader, PORTABLE_CUSTOM_GROUP_TYPE, MAX_SECTION_ITEMS, "portable custom groups")+ "portablePlaybackHistory" -> portablePlaybackHistory =+ readLimitedArray(reader, PORTABLE_PLAYBACK_HISTORY_TYPE, MAX_SECTION_ITEMS, "portable playback history")+ "portableProtectedContent" -> portableProtectedContent =+ readLimitedArray(reader, PORTABLE_PROTECTED_CONTENT_TYPE, MAX_SECTION_ITEMS, "portable protected content")+ "portableSearchHistory" -> portableSearchHistory =+ readLimitedArray(reader, PORTABLE_SEARCH_HISTORY_TYPE, MAX_SECTION_ITEMS, "portable search history")+ "portableHiddenContent" -> portableHiddenContent =+ readLimitedArray(reader, PORTABLE_HIDDEN_CONTENT_TYPE, MAX_SECTION_ITEMS, "portable hidden content")+ "portableContentPreferences" -> portableContentPreferences =+ readLimitedArray(reader, PORTABLE_CONTENT_PREFERENCE_TYPE, MAX_SECTION_ITEMS, "portable content preferences")+ "portableVariantChoices" -> portableVariantChoices =+ readLimitedArray(reader, PORTABLE_VARIANT_CHOICE_TYPE, MAX_SECTION_ITEMS, "portable variant choices")+ "portableManualEpgMappings" -> portableManualEpgMappings =+ readLimitedArray(reader, PORTABLE_MANUAL_EPG_V14_TYPE, MAX_SECTION_ITEMS, "portable manual EPG mappings")+ "portableMultiViewPresetsV14" -> portableMultiViewPresetsV14 =+ readLimitedArray(reader, PORTABLE_MULTIVIEW_V14_TYPE, MAX_SECTION_ITEMS, "portable multiview presets")else -> reader.skipValue()}}@@ -1452,7 +1824,17 @@ class BackupManagerImpl @Inject constructor(m3uClassificationRules = m3uClassificationRules,programReminders = programReminders,combinedM3uProfiles = combinedM3uProfiles,- activeLiveSource = activeLiveSource+ activeLiveSource = activeLiveSource,+ portableFavorites = portableFavorites,+ portableCustomGroups = portableCustomGroups,+ portablePlaybackHistory = portablePlaybackHistory,+ portableProtectedContent = portableProtectedContent,+ portableSearchHistory = portableSearchHistory,+ portableHiddenContent = portableHiddenContent,+ portableContentPreferences = portableContentPreferences,+ portableVariantChoices = portableVariantChoices,+ portableManualEpgMappings = portableManualEpgMappings,+ portableMultiViewPresetsV14 = portableMultiViewPresetsV14)}@@ -1977,6 +2359,27 @@ class BackupManagerImpl @Inject constructor(require(data.programReminders.orEmpty().size <= MAX_SECTION_ITEMS) {"Backup has too many program reminders"}+ require(data.portableFavorites.orEmpty().size <= MAX_SECTION_ITEMS) { "Backup has too many portable favorites" }+ require(data.portableCustomGroups.orEmpty().size <= MAX_SECTION_ITEMS) { "Backup has too many portable custom groups" }+ require(data.portableCustomGroups.orEmpty().sumOf { it.members.size } <= MAX_SECTION_ITEMS) {+ "Backup has too many portable custom-group members"+ }+ require(data.portablePlaybackHistory.orEmpty().size <= MAX_SECTION_ITEMS) {+ "Backup has too much portable playback history"+ }+ require(data.portableProtectedContent.orEmpty().size <= MAX_SECTION_ITEMS) {+ "Backup has too much portable protected content"+ }+ require(data.portableSearchHistory.orEmpty().size <= MAX_SECTION_ITEMS) {+ "Backup has too much portable search history"+ }+ require(data.portableHiddenContent.orEmpty().size <= MAX_SECTION_ITEMS) {+ "Backup has too much portable hidden content"+ }+ require(data.portableContentPreferences.orEmpty().size <= MAX_SECTION_ITEMS) { "Backup has too many portable content preferences" }+ require(data.portableVariantChoices.orEmpty().size <= MAX_SECTION_ITEMS) { "Backup has too many portable variant choices" }+ require(data.portableManualEpgMappings.orEmpty().size <= MAX_SECTION_ITEMS) { "Backup has too many portable manual EPG mappings" }+ require(data.portableMultiViewPresetsV14.orEmpty().sumOf { it.channels.size } <= MAX_SECTION_ITEMS) { "Backup has too many portable multiview entries" }require(data.multiViewPresets.orEmpty().values.sumOf { it.size } <= MAX_SECTION_ITEMS) { "Backup has too many preset entries" }require(data.portableMultiViewPresets.orEmpty().values.sumOf { it.size } <= MAX_SECTION_ITEMS) {"Backup has too many portable preset entries"@@ -2036,14 +2439,14 @@ class BackupManagerImpl @Inject constructor(CombinedM3uProfileBackup(name = profile.name,enabled = profile.enabled,- members = memberDao.getForProfileSync(profile.id).mapNotNull { member ->- referencesById[member.providerId]?.let { provider ->- CombinedM3uProfileMemberBackup(- provider = provider,- priority = member.priority,- enabled = member.enabled- )- }+ members = memberDao.getForProfileSync(profile.id).map { member ->+ val provider = referencesById[member.providerId]+ ?: error("Cannot export Combined M3U profile '${profile.name}': provider ${member.providerId} is missing")+ CombinedM3uProfileMemberBackup(+ provider = provider,+ priority = member.priority,+ enabled = member.enabled+ )},createdAt = profile.createdAt,updatedAt = profile.updatedAt@@ -2057,23 +2460,26 @@ class BackupManagerImpl @Inject constructor(val source = (preferencesRepository.activeLiveSource ?: flowOf(null)).first() ?: return nullval referencesById = providers.associate { it.id to it.toBackupProviderReference() }return when (source) {- is ActiveLiveSource.ProviderSource -> referencesById[source.providerId]?.let { provider ->- ActiveLiveSourceBackup(type = "provider", provider = provider)- }+ is ActiveLiveSource.ProviderSource -> ActiveLiveSourceBackup(+ type = "provider",+ provider = referencesById[source.providerId]+ ?: error("Cannot export Active Live Source: provider ${source.providerId} is missing")+ )is ActiveLiveSource.CombinedM3uSource -> {val profile = combinedM3uProfileDao?.getById(source.profileId)- val memberProviders = profile?.let {- combinedM3uProfileMemberDao?.getForProfileSync(it.id)- ?.sortedWith(compareBy({ member -> member.priority }, { member -> member.id }))- ?.mapNotNull { member -> referencesById[member.providerId] }- }.orEmpty()- profile?.let {- ActiveLiveSourceBackup(- type = "combined_m3u",- combinedProfileName = it.name,- combinedProfileProviders = memberProviders- )- }+ ?: error("Cannot export Active Live Source: combined profile ${source.profileId} is missing")+ val memberProviders = combinedM3uProfileMemberDao?.getForProfileSync(profile.id)+ ?.sortedWith(compareBy({ member -> member.priority }, { member -> member.id }))+ ?.map { member ->+ referencesById[member.providerId]+ ?: error("Cannot export Active Live Source: profile '${profile.name}' references missing provider ${member.providerId}")+ }+ ?: error("Cannot export Active Live Source: combined profile members are unavailable")+ ActiveLiveSourceBackup(+ type = "combined_m3u",+ combinedProfileName = profile.name,+ combinedProfileProviders = memberProviders+ )}}}@@ -2099,24 +2505,18 @@ class BackupManagerImpl @Inject constructor(val resolvedVariant = when (contentType) {ContentType.LIVE -> channelDao.getById(rawItemId)?.takeIf { it.providerId == providerId }- ?.streamId- ?.takeIf { it > 0L }- ?.toString()- ?.let { it to ContentType.LIVE }+ ?.takeIf { it.streamId > 0L }+ ?.let { Triple(it.streamId.toString(), ContentType.LIVE, it.categoryId) }ContentType.MOVIE -> movieDao.getById(rawItemId)?.takeIf { it.providerId == providerId }- ?.streamId- ?.takeIf { it > 0L }- ?.toString()- ?.let { it to ContentType.MOVIE }+ ?.takeIf { it.streamId > 0L }+ ?.let { Triple(it.streamId.toString(), ContentType.MOVIE, it.categoryId) }?: seriesDao.getById(rawItemId)?.takeIf { it.providerId == providerId }- ?.remoteKey()- ?.let { it to ContentType.SERIES }+ ?.let { series -> series.remoteKey()?.let { Triple(it, ContentType.SERIES, series.categoryId) } }ContentType.SERIES -> seriesDao.getById(rawItemId)?.takeIf { it.providerId == providerId }- ?.remoteKey()- ?.let { it to ContentType.SERIES }+ ?.let { series -> series.remoteKey()?.let { Triple(it, ContentType.SERIES, series.categoryId) } }ContentType.SERIES_EPISODE,ContentType.VOD -> null}@@ -2129,7 +2529,301 @@ class BackupManagerImpl @Inject constructor(logicalGroupId = logicalGroupId,rawItemId = rawItemId,remoteItemId = resolvedVariant.first,- contentType = resolvedVariant.second+ contentType = resolvedVariant.second,+ remoteCategoryId = resolvedVariant.third+ )+ }++ private data class QueuedPortableRestore(+ val jobId: String,+ val pendingCount: Int,+ val unresolvedCount: Int,+ val affectedProviders: List<BackupProviderReference>+ )++ private data class ReplaceScopePayload(+ val provider: BackupProviderReference?,+ val targetSection: String,+ val contentType: ContentType? = null+ )++ private suspend fun queuePortableRestoreItems(+ backupData: BackupData,+ plan: BackupImportPlan,+ restoreKey: String,+ storedProviders: List<Provider>+ ): QueuedPortableRestore? {+ val legacyProviders = backupData.providers.orEmpty().associate { provider ->+ provider.id to provider.toBackupProviderReference()+ }+ val legacyGroupsById = backupData.virtualGroups.orEmpty().associateBy { it.id }+ val allLegacyFavoritePayloads = mutableListOf<Triple<Long?, PortableFavoriteBackup, Boolean>>()+ if (backupData.version < 14 && plan.importSavedLibrary) {+ backupData.favorites.orEmpty().forEach { favorite ->+ val provider = legacyProviders[favorite.providerId] ?: return@forEach+ val reference = PortableContentReference(+ provider = provider,+ contentType = favorite.contentType,+ remoteContentId = favorite.remoteContentId+ ?: "$LEGACY_LOCAL_ID_PREFIX${favorite.contentId}"+ )+ val localProviderId = storedProviders.findUnambiguousPortableProvider(provider)?.id+ val resolved = localProviderId != null && resolvePortableContentId(+ localProviderId,+ favorite.contentType,+ favorite.remoteContentId,+ favorite.contentId+ ) != null+ allLegacyFavoritePayloads += Triple(+ favorite.groupId,+ PortableFavoriteBackup(reference, favorite.position, favorite.addedAt),+ resolved+ )+ }+ }+ val unresolvedFavoriteScopes = allLegacyFavoritePayloads.filterNot { it.third }+ .map { (_, backup) -> backup.content.provider.stableIdentityKey() to backup.content.contentType }+ .toSet()+ val legacyFavoritePayloads = allLegacyFavoritePayloads.filter { (_, backup, resolved) ->+ !resolved || (+ plan.conflictStrategy == BackupConflictStrategy.REPLACE_EXISTING &&+ backup.content.provider.stableIdentityKey() to backup.content.contentType in unresolvedFavoriteScopes+ )+ }.map { (groupId, backup) -> groupId to backup }+ val legacyCustomGroupPayloads = if (backupData.version < 14 && plan.importSavedLibrary) {+ legacyGroupsById.values.mapNotNull { group ->+ val provider = legacyProviders[group.providerId] ?: return@mapNotNull null+ val members = legacyFavoritePayloads.filter { (groupId) -> groupId == group.id }+ .map { (_, favorite) -> favorite }+ if (members.isEmpty()) return@mapNotNull null+ PortableCustomGroupBackup(+ provider = provider,+ contentType = group.contentType,+ name = group.name,+ icon = group.iconEmoji,+ position = group.position,+ createdAt = group.createdAt,+ members = members+ )+ }+ } else emptyList()+ val allLegacyHistoryPayloads = mutableListOf<Pair<PortablePlaybackHistoryBackup, Boolean>>()+ if (backupData.version < 14 && plan.importPlaybackHistory) {+ backupData.playbackHistory.orEmpty().forEach { history ->+ val provider = legacyProviders[history.providerId] ?: return@forEach+ val payload = PortablePlaybackHistoryBackup(+ content = PortableContentReference(+ provider = provider,+ contentType = history.contentType,+ remoteContentId = history.remoteContentId+ ?: "$LEGACY_LOCAL_ID_PREFIX${history.contentId}",+ parentRemoteContentId = history.remoteSeriesId,+ name = history.title,+ urlFallback = history.streamUrl+ ),+ resumePositionMs = history.resumePositionMs,+ totalDurationMs = history.totalDurationMs,+ lastWatchedAt = history.lastWatchedAt,+ watchCount = history.watchCount,+ watchedStatus = history.watchedStatus.name,+ posterUrl = history.posterUrl,+ seasonNumber = history.seasonNumber,+ episodeNumber = history.episodeNumber+ )+ val localProviderId = storedProviders.findUnambiguousPortableProvider(provider)?.id+ val resolved = localProviderId != null && resolvePortableHistoryIdentity(+ localProviderId,+ history+ ) != null+ allLegacyHistoryPayloads += payload to resolved+ }+ }+ val unresolvedHistoryProviders = allLegacyHistoryPayloads.filterNot { it.second }+ .map { it.first.content.provider.stableIdentityKey() }+ .toSet()+ val legacyHistoryPayloads = allLegacyHistoryPayloads.filter { (backup, resolved) ->+ !resolved || (+ plan.conflictStrategy == BackupConflictStrategy.REPLACE_EXISTING &&+ backup.content.provider.stableIdentityKey() in unresolvedHistoryProviders+ )+ }.map { it.first }+ val contentPayloads = buildList<Pair<String, Any>> {+ if (plan.importSavedLibrary) {+ backupData.portableFavorites.orEmpty().forEach { add(RESTORE_SECTION_FAVORITES to it) }+ backupData.portableCustomGroups.orEmpty().forEach { add(RESTORE_SECTION_CUSTOM_GROUPS to it) }+ backupData.portableProtectedContent.orEmpty().forEach { add(RESTORE_SECTION_PROTECTED_CONTENT to it) }+ backupData.portableHiddenContent.orEmpty().forEach { add(RESTORE_SECTION_HIDDEN_CONTENT to it) }+ backupData.portableManualEpgMappings.orEmpty().forEach { add(RESTORE_SECTION_MANUAL_EPG to it) }+ legacyFavoritePayloads.filter { (groupId) -> groupId == null }+ .forEach { (_, favorite) -> add(RESTORE_SECTION_FAVORITES to favorite) }+ legacyCustomGroupPayloads.forEach { add(RESTORE_SECTION_CUSTOM_GROUPS to it) }+ }+ if (plan.importPlaybackHistory) {+ backupData.portablePlaybackHistory.orEmpty().forEach { add(RESTORE_SECTION_PLAYBACK_HISTORY to it) }+ legacyHistoryPayloads.forEach { add(RESTORE_SECTION_PLAYBACK_HISTORY to it) }+ }+ if (plan.importPreferences) {+ backupData.portableSearchHistory.orEmpty().forEach { add(RESTORE_SECTION_SEARCH_HISTORY to it) }+ backupData.portableContentPreferences.orEmpty().forEach { add(RESTORE_SECTION_CONTENT_PREFERENCES to it) }+ backupData.portableVariantChoices.orEmpty().forEach { add(RESTORE_SECTION_VARIANT_CHOICES to it) }+ }+ if (plan.importMultiViewPresets) {+ backupData.portableMultiViewPresetsV14.orEmpty().forEach { add(RESTORE_SECTION_MULTIVIEW to it) }+ }+ if (plan.importRecordingSchedules) {+ backupData.scheduledRecordings.orEmpty().filter { it.channel != null }+ .forEach { add(RESTORE_SECTION_RECORDING_SCHEDULES to it) }+ }+ }+ val backupProviderReferences = buildSet {+ addAll(backupData.portableProviderPreferences?.providers.orEmpty())+ contentPayloads.forEach { (_, payload) ->+ when (payload) {+ is PortableCustomGroupBackup -> add(payload.provider)+ is PortableSearchHistoryBackup -> payload.provider?.let(::add)+ is PortableFavoriteBackup -> add(payload.content.provider)+ is PortablePlaybackHistoryBackup -> add(payload.content.provider)+ is PortableProtectedContentBackup -> add(payload.content.provider)+ is PortableHiddenContentBackup -> add(payload.content.provider)+ is PortableContentPreferenceBackup -> add(payload.content.provider)+ is PortableVariantChoiceBackup -> add(payload.selectedContent.provider)+ is PortableManualEpgMappingV14Backup -> add(payload.content.provider)+ is PortableMultiViewPresetV14Backup -> addAll(payload.channels.map { it.provider })+ is ScheduledRecordingBackup -> payload.channel?.provider?.let(::add)+ }+ }+ }+ val replacementMarkers = if (plan.conflictStrategy == BackupConflictStrategy.REPLACE_EXISTING) {+ buildList<Pair<String, Any>> {+ val persistedContentTypes = listOf(+ ContentType.LIVE,+ ContentType.MOVIE,+ ContentType.SERIES,+ ContentType.SERIES_EPISODE+ )+ backupProviderReferences.forEach { provider ->+ if (plan.importSavedLibrary) {+ persistedContentTypes.forEach { type ->+ add(RESTORE_SECTION_REPLACE_SCOPE to ReplaceScopePayload(provider, RESTORE_SECTION_FAVORITES, type))+ add(RESTORE_SECTION_REPLACE_SCOPE to ReplaceScopePayload(provider, RESTORE_SECTION_CUSTOM_GROUPS, type))+ add(RESTORE_SECTION_REPLACE_SCOPE to ReplaceScopePayload(provider, RESTORE_SECTION_PROTECTED_CONTENT, type))+ }+ add(RESTORE_SECTION_REPLACE_SCOPE to ReplaceScopePayload(provider, RESTORE_SECTION_HIDDEN_CONTENT, ContentType.LIVE))+ add(RESTORE_SECTION_REPLACE_SCOPE to ReplaceScopePayload(provider, RESTORE_SECTION_MANUAL_EPG, ContentType.LIVE))+ }+ if (plan.importPlaybackHistory) persistedContentTypes.forEach { type ->+ add(RESTORE_SECTION_REPLACE_SCOPE to ReplaceScopePayload(provider, RESTORE_SECTION_PLAYBACK_HISTORY, type))+ }+ if (plan.importPreferences) {+ add(RESTORE_SECTION_REPLACE_SCOPE to ReplaceScopePayload(provider, RESTORE_SECTION_SEARCH_HISTORY))+ add(RESTORE_SECTION_REPLACE_SCOPE to ReplaceScopePayload(provider, RESTORE_SECTION_CONTENT_PREFERENCES, ContentType.LIVE))+ add(RESTORE_SECTION_REPLACE_SCOPE to ReplaceScopePayload(provider, RESTORE_SECTION_VARIANT_CHOICES))+ }+ if (plan.importRecordingSchedules) {+ add(RESTORE_SECTION_REPLACE_SCOPE to ReplaceScopePayload(provider, RESTORE_SECTION_RECORDING_SCHEDULES, ContentType.LIVE))+ }+ }+ if (plan.importMultiViewPresets) {+ add(RESTORE_SECTION_REPLACE_SCOPE to ReplaceScopePayload(null, RESTORE_SECTION_MULTIVIEW))+ }+ }+ } else emptyList()+ val pendingPayloads = replacementMarkers + contentPayloads+ if (pendingPayloads.isEmpty()) return null+ val ledgerDao = backupRestoreLedgerDao ?: if (backupData.version < 14) {+ // Compatibility for callers built against the pre-ledger constructor. Production+ // schema 77 always supplies the DAO; unresolved legacy references remain reported.+ return null+ } else {+ error("Durable backup restore storage is unavailable")+ }+ val now = System.currentTimeMillis()+ val items = pendingPayloads.map { (section, payload) ->+ val reference = when (payload) {+ is PortableFavoriteBackup -> payload.content+ is PortableCustomGroupBackup -> null+ is PortablePlaybackHistoryBackup -> payload.content+ is PortableProtectedContentBackup -> payload.content+ is PortableHiddenContentBackup -> payload.content+ is PortableContentPreferenceBackup -> payload.content+ is PortableVariantChoiceBackup -> payload.selectedContent+ is PortableManualEpgMappingV14Backup -> payload.content+ is PortableMultiViewPresetV14Backup -> null+ is ScheduledRecordingBackup -> payload.channel+ is PortableSearchHistoryBackup -> null+ is ReplaceScopePayload -> null+ else -> error("Unsupported portable restore payload ${payload::class.java.simpleName}")+ }+ val providerReference = when (payload) {+ is PortableCustomGroupBackup -> payload.provider+ is PortableSearchHistoryBackup -> payload.provider+ is PortableMultiViewPresetV14Backup -> null+ is ScheduledRecordingBackup -> payload.channel?.provider+ is ReplaceScopePayload -> payload.provider+ else -> checkNotNull(reference).provider+ }+ val providerKey = providerReference?.stableIdentityKey() ?: GLOBAL_RESTORE_PROVIDER_KEY+ val stableKey = when (payload) {+ is PortableCustomGroupBackup ->+ "$providerKey|${payload.contentType.name}:group:${payload.name.trim().lowercase(Locale.ROOT)}"+ is PortableSearchHistoryBackup ->+ "$providerKey|search:${payload.contentScope}:${payload.query.trim().lowercase(Locale.ROOT)}"+ is PortableMultiViewPresetV14Backup -> "$providerKey|multiview:${payload.name}"+ is ScheduledRecordingBackup -> "$providerKey|recording:${payload.recurringRuleId ?: "${payload.scheduledStartMs}:${payload.channel?.remoteContentId}"}"+ is ReplaceScopePayload -> "$providerKey|scope:${payload.targetSection}:${payload.contentType?.name.orEmpty()}"+ else -> "$providerKey|${reference!!.contentType.name}:${reference.remoteContentId}"+ }+ BackupRestoreItemEntity(+ jobId = restoreKey,+ providerIdentityKey = providerKey,+ localProviderId = providerReference?.let { portable ->+ storedProviders.findUnambiguousPortableProvider(portable)?.id+ },+ section = section,+ contentType = reference?.contentType?.name+ ?: (payload as? PortableCustomGroupBackup)?.contentType?.name+ ?: (payload as? ReplaceScopePayload)?.contentType?.name,+ stableReferenceKey = stableKey,+ referenceJson = gson.toJson(reference ?: providerReference),+ payloadJson = gson.toJson(payload),+ createdAt = now,+ updatedAt = now+ )+ }+ ledgerDao.insertLedger(+ BackupRestoreJobEntity(+ id = restoreKey,+ restoreKey = restoreKey,+ backupVersion = backupData.version,+ conflictStrategy = plan.conflictStrategy.name,+ status = RESTORE_STATE_WAITING_FOR_SYNC,+ createdAt = now,+ updatedAt = now+ ),+ items+ )+ return QueuedPortableRestore(+ jobId = restoreKey,+ pendingCount = items.size,+ unresolvedCount = 0,+ affectedProviders = buildList {+ pendingPayloads.forEach { (_, payload) ->+ when (payload) {+ is PortableCustomGroupBackup -> add(payload.provider)+ is PortableSearchHistoryBackup -> payload.provider?.let(::add)+ is PortableFavoriteBackup -> add(payload.content.provider)+ is PortablePlaybackHistoryBackup -> add(payload.content.provider)+ is PortableProtectedContentBackup -> add(payload.content.provider)+ is PortableHiddenContentBackup -> add(payload.content.provider)+ is PortableContentPreferenceBackup -> add(payload.content.provider)+ is PortableVariantChoiceBackup -> add(payload.selectedContent.provider)+ is PortableManualEpgMappingV14Backup -> add(payload.content.provider)+ is PortableMultiViewPresetV14Backup -> addAll(payload.channels.map { it.provider })+ is ScheduledRecordingBackup -> payload.channel?.provider?.let(::add)+ is ReplaceScopePayload -> payload.provider?.let(::add)+ }+ }+ }.distinct())}@@ -2227,7 +2921,13 @@ class BackupManagerImpl @Inject constructor(preferencesRepository.getHiddenChannelIds(provider.id).first().mapNotNull { channelId ->channels.getById(channelId)?.takeIf { it.providerId == provider.id }?.let { channel ->referencesById[provider.id]?.let { reference ->- PortableChannelReference(reference, channel.streamId, channel.name, channel.streamUrl)+ PortableChannelReference(+ reference,+ channel.streamId,+ channel.name,+ channel.streamUrl,+ channel.categoryId+ )}} ?: run {unresolved += "Hidden channel id $channelId for provider ${provider.name} was not found during export"@@ -2308,7 +3008,8 @@ class BackupManagerImpl @Inject constructor(provider = provider,streamId = channel.streamId,name = channel.name,- streamUrl = channel.streamUrl+ streamUrl = channel.streamUrl,+ remoteCategoryId = channel.categoryId),aspectRatio = aspectRatio,audioVideoOffsetMs = audioVideoOffsetMs@@ -2406,7 +3107,17 @@ class BackupManagerImpl @Inject constructor(m3uClassificationRules.isNullOrEmpty() &&programReminders.isNullOrEmpty() &&combinedM3uProfiles.isNullOrEmpty() &&- activeLiveSource == null+ activeLiveSource == null &&+ portableFavorites.isNullOrEmpty() &&+ portableCustomGroups.isNullOrEmpty() &&+ portablePlaybackHistory.isNullOrEmpty() &&+ portableProtectedContent.isNullOrEmpty() &&+ portableSearchHistory.isNullOrEmpty() &&+ portableHiddenContent.isNullOrEmpty()+ && portableContentPreferences.isNullOrEmpty()+ && portableVariantChoices.isNullOrEmpty()+ && portableManualEpgMappings.isNullOrEmpty()+ && portableMultiViewPresetsV14.isNullOrEmpty()private suspend fun capturePreferenceSnapshot(providerEntities: List<ProviderEntity>): Map<String, String> {val parentalPinBackup = preferencesRepository.exportParentalPinBackup()@@ -2541,6 +3252,8 @@ class BackupManagerImpl @Inject constructor(.joinToString("\n") { (key, rawItemId) -> "${key.substringAfter('|')}=$rawItemId" })}+ }.also { snapshot ->+ PreferenceBackupRegistry.requirePortableCodecs(snapshot.keys)}}@@ -3204,7 +3917,9 @@ class BackupManagerImpl @Inject constructor(plan: BackupImportPlan,initialStoredProviders: List<Provider>): RoomRestoreResult {- if (!plan.importProviders && !plan.importSavedLibrary && !plan.importPlaybackHistory) {+ val importProviders = plan.importProviders ||+ (backupData.version >= 14 && backupData.providerSnapshots != null)+ if (!importProviders && !plan.importSavedLibrary && !plan.importPlaybackHistory) {return RoomRestoreResult(storedProviders = initialStoredProviders,importedSections = emptyList(),@@ -3224,7 +3939,7 @@ class BackupManagerImpl @Inject constructor(val unresolvedReferences = mutableListOf<String>()transactionRunner.inTransaction {- if (plan.importProviders) {+ if (importProviders) {backupData.providers?.let { providers ->providers.forEach { provider ->val existing = storedProviders@@ -3956,7 +4671,18 @@ class BackupManagerImpl @Inject constructor(remoteContentId: String?,legacyContentId: Long): Long? {- if (remoteContentId == null) return legacyContentId+ if (remoteContentId == null) {+ return when (contentType) {+ ContentType.LIVE -> channelDao.getById(legacyContentId)+ ?.takeIf { it.providerId == providerId }?.id+ ContentType.MOVIE, ContentType.VOD -> movieDao.getById(legacyContentId)+ ?.takeIf { it.providerId == providerId }?.id+ ContentType.SERIES -> seriesDao.getById(legacyContentId)+ ?.takeIf { it.providerId == providerId }?.id+ ContentType.SERIES_EPISODE -> episodeDao.getById(legacyContentId)+ ?.takeIf { it.providerId == providerId }?.id+ }+ }return when (contentType) {ContentType.LIVE -> remoteContentId.toLongOrNull()?.let { channelDao.getByStreamId(providerId, it)?.id }ContentType.MOVIE -> remoteContentId.toLongOrNull()?.let { movieDao.getByStreamId(providerId, it)?.id }@@ -4079,7 +4805,25 @@ class BackupManagerImpl @Inject constructor(item: com.streamvault.domain.model.PlaybackHistory): ResolvedContentIdentity? {if (item.remoteContentId == null && item.remoteSeriesId == null) {- return ResolvedContentIdentity(contentId = item.contentId, seriesId = item.seriesId)+ return when (item.contentType) {+ ContentType.LIVE -> channelDao.getById(item.contentId)+ ?.takeIf { it.providerId == providerId }+ ?.let { ResolvedContentIdentity(it.id) }+ ContentType.MOVIE, ContentType.VOD -> movieDao.getById(item.contentId)+ ?.takeIf { it.providerId == providerId }+ ?.let { ResolvedContentIdentity(it.id) }+ ContentType.SERIES -> seriesDao.getById(item.contentId)+ ?.takeIf { it.providerId == providerId }+ ?.let { ResolvedContentIdentity(it.id) }+ ContentType.SERIES_EPISODE -> episodeDao.getById(item.contentId)+ ?.takeIf { it.providerId == providerId }+ ?.let { episode ->+ val parentId = item.seriesId?.takeIf { seriesId ->+ seriesDao.getById(seriesId)?.providerId == providerId+ }+ ResolvedContentIdentity(episode.id, parentId)+ }+ }}return when (item.contentType) {@@ -4350,11 +5094,129 @@ private fun Provider.backupIdentity(): Triple<String, String, String> =private fun Provider.toBackupProviderReference() = BackupProviderReference(serverUrl = normalizeProviderServerUrl(serverUrl),- username = username.trim(),+ username = username.trim().takeUnless { type == ProviderType.M3U }.orEmpty(),stalkerMacAddress = stalkerMacAddress.takeIf { it.isNotBlank() },providerType = type)+private suspend fun com.streamvault.domain.model.Favorite.toPortableContentReference(+ providersById: Map<Long, Provider>,+ channelDao: ChannelDao,+ movieDao: MovieDao,+ seriesDao: SeriesDao+): com.streamvault.domain.manager.PortableContentReference? {+ val remoteId = remoteContentId?.takeIf { it.isNotBlank() } ?: return null+ val provider = providersById[providerId] ?: return null+ val providerReference = provider.toBackupProviderReference()+ when (contentType) {+ ContentType.LIVE -> channelDao.getById(contentId)+ ?.takeIf { it.providerId == providerId }+ ?.let { return it.toPortableContentReference(providerReference) }+ ContentType.MOVIE, ContentType.VOD -> movieDao.getById(contentId)+ ?.takeIf { it.providerId == providerId }+ ?.let { return it.toPortableContentReference(providerReference) }+ ContentType.SERIES -> seriesDao.getById(contentId)+ ?.takeIf { it.providerId == providerId }+ ?.let { return it.toPortableContentReference(providerReference) }+ ContentType.SERIES_EPISODE -> Unit+ }+ return com.streamvault.domain.manager.PortableContentReference(+ provider = providerReference,+ contentType = contentType,+ remoteContentId = remoteId+ )+}++private suspend fun com.streamvault.domain.model.PlaybackHistory.toPortableContentReference(+ providersById: Map<Long, Provider>,+ channelDao: ChannelDao,+ movieDao: MovieDao,+ seriesDao: SeriesDao,+ episodeDao: EpisodeDao+): com.streamvault.domain.manager.PortableContentReference? {+ val remoteId = remoteContentId?.takeIf { it.isNotBlank() } ?: return null+ val provider = providersById[providerId] ?: return null+ val providerReference = provider.toBackupProviderReference()+ when (contentType) {+ ContentType.LIVE -> channelDao.getById(contentId)+ ?.takeIf { it.providerId == providerId }+ ?.let { return it.toPortableContentReference(providerReference) }+ ContentType.MOVIE, ContentType.VOD -> movieDao.getById(contentId)+ ?.takeIf { it.providerId == providerId }+ ?.let { return it.toPortableContentReference(providerReference) }+ ContentType.SERIES -> seriesDao.getById(contentId)+ ?.takeIf { it.providerId == providerId }+ ?.let { return it.toPortableContentReference(providerReference) }+ ContentType.SERIES_EPISODE -> episodeDao.getById(contentId)+ ?.takeIf { it.providerId == providerId }+ ?.let { episode ->+ seriesDao.getById(episode.seriesId)+ ?.takeIf { it.providerId == providerId }+ ?.let { series -> return episode.toPortableContentReference(providerReference, series) }+ }+ }+ return com.streamvault.domain.manager.PortableContentReference(+ provider = providerReference,+ contentType = contentType,+ remoteContentId = remoteId,+ parentRemoteContentId = remoteSeriesId,+ name = title,+ urlFallback = streamUrl.takeIf { it.isNotBlank() }+ )+}++private fun com.streamvault.data.local.entity.ChannelEntity.toPortableContentReference(+ provider: BackupProviderReference+) = com.streamvault.domain.manager.PortableContentReference(+ provider = provider,+ contentType = ContentType.LIVE,+ remoteContentId = streamId.toString(),+ remoteCategoryId = categoryId?.toString(),+ name = name,+ urlFallback = streamUrl.takeIf { it.isNotBlank() }+)++private fun com.streamvault.data.local.entity.MovieEntity.toPortableContentReference(+ provider: BackupProviderReference+) = com.streamvault.domain.manager.PortableContentReference(+ provider = provider,+ contentType = ContentType.MOVIE,+ remoteContentId = streamId.toString(),+ remoteCategoryId = categoryId?.toString(),+ name = name,+ urlFallback = streamUrl.takeIf { it.isNotBlank() }+)++private fun com.streamvault.data.local.entity.SeriesEntity.toPortableContentReference(+ provider: BackupProviderReference+) = com.streamvault.domain.manager.PortableContentReference(+ provider = provider,+ contentType = ContentType.SERIES,+ remoteContentId = providerSeriesId?.takeIf { it.isNotBlank() } ?: seriesId.toString(),+ remoteCategoryId = categoryId?.toString(),+ name = name+)++private fun com.streamvault.data.local.entity.EpisodeEntity.toPortableContentReference(+ provider: BackupProviderReference,+ series: com.streamvault.data.local.entity.SeriesEntity+) = com.streamvault.domain.manager.PortableContentReference(+ provider = provider,+ contentType = ContentType.SERIES_EPISODE,+ remoteContentId = episodeId.toString(),+ parentRemoteContentId = series.providerSeriesId?.takeIf { it.isNotBlank() } ?: series.seriesId.toString(),+ remoteCategoryId = series.categoryId?.toString(),+ name = title,+ urlFallback = streamUrl.takeIf { it.isNotBlank() }+)++private fun BackupProviderReference.stableIdentityKey(): String = listOf(+ normalizeProviderServerUrl(serverUrl),+ username.trim(),+ providerType?.name.orEmpty(),+ stalkerMacAddress.normalizedIdentity()+).joinToString("|")+private fun Iterable<Provider>.findUnambiguousPortableProvider(reference: BackupProviderReference): Provider? {@@ -4362,7 +5224,7 @@ private fun Iterable<Provider>.findUnambiguousPortableProvider(return filter { provider ->normalizeProviderServerUrl(provider.serverUrl) == normalizeProviderServerUrl(reference.serverUrl) &&(reference.providerType == null || provider.type == reference.providerType) &&- (provider.type == ProviderType.M3U || provider.username.trim() == reference.username.trim()) &&+ provider.username.trim() == reference.username.trim() &&provider.stalkerMacAddress.normalizedIdentity() == normalizedMac}.singleOrNull()}@@ -4797,12 +5659,27 @@ private val RAW_CHECKSUM_FIELD_PATTERN = Regex("\\\"checksum\\\"\\s*:\\s*\\\"[^\private const val RESTORE_STATE_RUNNING = "RUNNING"private const val RESTORE_STATE_COMPLETE = "COMPLETE"private const val RESTORE_STATE_PARTIAL = "PARTIAL"+private const val RESTORE_STATE_WAITING_FOR_SYNC = "WAITING_FOR_SYNC"private const val RESTORE_STATE_FAILED_BEFORE_COMMIT = "FAILED_BEFORE_COMMIT"private const val RESTORE_SNAPSHOT_PRESET_1 = "__restore_snapshot_preset_1"private const val RESTORE_SNAPSHOT_PRESET_2 = "__restore_snapshot_preset_2"private const val RESTORE_SNAPSHOT_PRESET_3 = "__restore_snapshot_preset_3"private const val RESTORE_SNAPSHOT_CHANNEL_PREFERENCES = "__restore_snapshot_channel_preferences"-private const val CURRENT_BACKUP_VERSION = 13+private const val CURRENT_BACKUP_VERSION = 14+private const val RESTORE_SECTION_FAVORITES = "FAVORITES"+private const val RESTORE_SECTION_CUSTOM_GROUPS = "CUSTOM_GROUPS"+private const val RESTORE_SECTION_PLAYBACK_HISTORY = "PLAYBACK_HISTORY"+private const val RESTORE_SECTION_PROTECTED_CONTENT = "PROTECTED_CONTENT"+private const val RESTORE_SECTION_HIDDEN_CONTENT = "HIDDEN_CONTENT"+private const val RESTORE_SECTION_CONTENT_PREFERENCES = "CONTENT_PREFERENCES"+private const val RESTORE_SECTION_VARIANT_CHOICES = "VARIANT_CHOICES"+private const val RESTORE_SECTION_MANUAL_EPG = "MANUAL_EPG"+private const val RESTORE_SECTION_MULTIVIEW = "MULTIVIEW"+private const val RESTORE_SECTION_RECORDING_SCHEDULES = "RECORDING_SCHEDULES"+private const val RESTORE_SECTION_SEARCH_HISTORY = "SEARCH_HISTORY"+private const val RESTORE_SECTION_REPLACE_SCOPE = "REPLACE_SCOPE"+private const val LEGACY_LOCAL_ID_PREFIX = "legacy-local-id:"+private const val GLOBAL_RESTORE_PROVIDER_KEY = "__GLOBAL__"private const val LEGACY_NO_ACTIVE_PROVIDER_WARNING ="Active provider id -1 was not found during export"private const val FILE_URI_SCHEME = "file"@@ -4849,8 +5726,32 @@ private val M3U_CLASSIFICATION_RULE_TYPE: Type = M3uClassificationRuleBackup::clprivate val M3U_CLASSIFICATION_RULE_LIST_TYPE: Type =object : TypeToken<List<M3uClassificationRuleBackup>>() {}.typeprivate val PROGRAM_REMINDER_TYPE: Type = ProgramReminderBackup::class.java+private val PORTABLE_FAVORITE_TYPE: Type = PortableFavoriteBackup::class.java+private val PORTABLE_CUSTOM_GROUP_TYPE: Type = PortableCustomGroupBackup::class.java+private val PORTABLE_PLAYBACK_HISTORY_TYPE: Type = PortablePlaybackHistoryBackup::class.java+private val PORTABLE_PROTECTED_CONTENT_TYPE: Type = PortableProtectedContentBackup::class.java+private val PORTABLE_SEARCH_HISTORY_TYPE: Type = PortableSearchHistoryBackup::class.java+private val PORTABLE_HIDDEN_CONTENT_TYPE: Type = PortableHiddenContentBackup::class.java+private val PORTABLE_CONTENT_PREFERENCE_TYPE: Type = PortableContentPreferenceBackup::class.java+private val PORTABLE_VARIANT_CHOICE_TYPE: Type = PortableVariantChoiceBackup::class.java+private val PORTABLE_MANUAL_EPG_V14_TYPE: Type = PortableManualEpgMappingV14Backup::class.java+private val PORTABLE_MULTIVIEW_V14_TYPE: Type = PortableMultiViewPresetV14Backup::class.javaprivate val PROGRAM_REMINDER_LIST_TYPE: Type =object : TypeToken<List<ProgramReminderBackup>>() {}.type+private val PORTABLE_FAVORITE_LIST_TYPE: Type = object : TypeToken<List<PortableFavoriteBackup>>() {}.type+private val PORTABLE_CUSTOM_GROUP_LIST_TYPE: Type = object : TypeToken<List<PortableCustomGroupBackup>>() {}.type+private val PORTABLE_PLAYBACK_HISTORY_LIST_TYPE: Type =+ object : TypeToken<List<PortablePlaybackHistoryBackup>>() {}.type+private val PORTABLE_PROTECTED_CONTENT_LIST_TYPE: Type =+ object : TypeToken<List<PortableProtectedContentBackup>>() {}.type+private val PORTABLE_SEARCH_HISTORY_LIST_TYPE: Type =+ object : TypeToken<List<PortableSearchHistoryBackup>>() {}.type+private val PORTABLE_HIDDEN_CONTENT_LIST_TYPE: Type =+ object : TypeToken<List<PortableHiddenContentBackup>>() {}.type+private val PORTABLE_CONTENT_PREFERENCE_LIST_TYPE: Type = object : TypeToken<List<PortableContentPreferenceBackup>>() {}.type+private val PORTABLE_VARIANT_CHOICE_LIST_TYPE: Type = object : TypeToken<List<PortableVariantChoiceBackup>>() {}.type+private val PORTABLE_MANUAL_EPG_V14_LIST_TYPE: Type = object : TypeToken<List<PortableManualEpgMappingV14Backup>>() {}.type+private val PORTABLE_MULTIVIEW_V14_LIST_TYPE: Type = object : TypeToken<List<PortableMultiViewPresetV14Backup>>() {}.typeprivate val FAVORITE_LIST_TYPE: Type = object : TypeToken<List<com.streamvault.domain.model.Favorite>>() {}.typeprivate val VIRTUAL_GROUP_LIST_TYPE: Type = object : TypeToken<List<com.streamvault.domain.model.VirtualGroup>>() {}.typeprivate val PLAYBACK_HISTORY_LIST_TYPE: Type = object : TypeToken<List<com.streamvault.domain.model.PlaybackHistory>>() {}.typediff --git a/data/src/main/java/com/streamvault/data/manager/BackupRestoreStatusStoreImpl.kt b/data/src/main/java/com/streamvault/data/manager/BackupRestoreStatusStoreImpl.ktnew file mode 100644index 00000000..a2a0147f--- /dev/null+++ b/data/src/main/java/com/streamvault/data/manager/BackupRestoreStatusStoreImpl.kt@@ -0,0 +1,74 @@+package com.streamvault.data.manager++import com.streamvault.data.local.dao.BackupRestoreLedgerDao+import com.streamvault.data.local.entity.BackupRestoreItemEntity+import com.streamvault.domain.manager.BackupRestoreJobStatus+import com.streamvault.domain.manager.BackupRestoreItemStatus+import com.streamvault.domain.manager.BackupRestoreProviderStatus+import com.streamvault.domain.manager.BackupRestoreStatusStore+import javax.inject.Inject+import javax.inject.Singleton+import kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.combine++@Singleton+class BackupRestoreStatusStoreImpl @Inject constructor(+ private val ledgerDao: BackupRestoreLedgerDao,+ private val coordinator: PendingBackupRestoreCoordinator+) : BackupRestoreStatusStore {+ override fun observeRestoreJobs(): Flow<List<BackupRestoreJobStatus>> =+ combine(ledgerDao.observeJobs(), ledgerDao.observeItems()) { jobs, items ->+ jobs.map { job ->+ val jobItems = items.filter {+ it.jobId == job.id && it.section != "REPLACE_SCOPE"+ }+ BackupRestoreJobStatus(+ jobId = job.id,+ backupVersion = job.backupVersion,+ status = job.status,+ providers = jobItems.groupBy { it.providerIdentityKey }.map { (key, providerItems) ->+ BackupRestoreProviderStatus(+ providerIdentityKey = key,+ localProviderId = providerItems.mapNotNull { it.localProviderId }.distinct().singleOrNull(),+ appliedCount = providerItems.count { it.status == BackupRestoreItemEntity.STATUS_APPLIED },+ pendingCount = providerItems.count { it.status == BackupRestoreItemEntity.STATUS_PENDING },+ unresolvedCount = providerItems.count { it.status == BackupRestoreItemEntity.STATUS_UNRESOLVED },+ failedCount = providerItems.count { it.status == BackupRestoreItemEntity.STATUS_FAILED_RETRYABLE },+ items = providerItems.map { item ->+ BackupRestoreItemStatus(+ id = item.id,+ section = item.section,+ contentType = item.contentType,+ status = item.status,+ attempts = item.attemptCount,+ lastError = item.lastError+ )+ }+ )+ },+ updatedAt = job.updatedAt+ )+ }+ }++ override suspend fun retryProviders(providerIds: Set<Long>) {+ providerIds.forEach { coordinator.applyForProvider(it) }+ }++ override suspend fun dismissItem(itemId: Long) {+ val item = ledgerDao.getItem(itemId) ?: return+ val now = System.currentTimeMillis()+ ledgerDao.dismissItem(itemId, now)+ ledgerDao.refreshJobCounts(item.jobId, now)+ }++ override suspend fun dismissProvider(jobId: String, providerIdentityKey: String) {+ val now = System.currentTimeMillis()+ ledgerDao.dismissProvider(jobId, providerIdentityKey, now)+ ledgerDao.refreshJobCounts(jobId, now)+ }++ override suspend fun dismissRestore(jobId: String) {+ ledgerDao.dismissJob(jobId, System.currentTimeMillis())+ }+}diff --git a/data/src/main/java/com/streamvault/data/manager/PendingBackupRestoreCoordinator.kt b/data/src/main/java/com/streamvault/data/manager/PendingBackupRestoreCoordinator.ktnew file mode 100644index 00000000..62ca1a13--- /dev/null+++ b/data/src/main/java/com/streamvault/data/manager/PendingBackupRestoreCoordinator.kt@@ -0,0 +1,649 @@+package com.streamvault.data.manager++import com.google.gson.Gson+import com.streamvault.data.local.dao.BackupRestoreLedgerDao+import com.streamvault.data.local.dao.ChannelDao+import com.streamvault.data.local.dao.ChannelPreferenceDao+import com.streamvault.data.local.dao.ChannelEpgMappingDao+import com.streamvault.data.local.dao.EpgSourceDao+import com.streamvault.data.local.dao.EpisodeDao+import com.streamvault.data.local.dao.FavoriteDao+import com.streamvault.data.local.dao.MovieDao+import com.streamvault.data.local.dao.PlaybackHistoryDao+import com.streamvault.data.local.dao.ProviderDao+import com.streamvault.data.local.dao.SearchHistoryDao+import com.streamvault.data.local.dao.SeriesDao+import com.streamvault.data.local.dao.VirtualGroupDao+import com.streamvault.data.local.entity.BackupRestoreItemEntity+import com.streamvault.data.local.entity.FavoriteEntity+import com.streamvault.data.local.entity.ChannelPreferenceEntity+import com.streamvault.data.local.entity.ChannelEpgMappingEntity+import com.streamvault.data.local.entity.PlaybackHistoryEntity+import com.streamvault.data.local.entity.SearchHistoryEntity+import com.streamvault.data.local.entity.VirtualGroupEntity+import com.streamvault.domain.manager.PortableContentReference+import com.streamvault.domain.manager.PortableCustomGroupBackup+import com.streamvault.domain.manager.PortableFavoriteBackup+import com.streamvault.domain.manager.PortablePlaybackHistoryBackup+import com.streamvault.domain.manager.PortableProtectedContentBackup+import com.streamvault.domain.manager.PortableHiddenContentBackup+import com.streamvault.domain.manager.PortableContentPreferenceBackup+import com.streamvault.domain.manager.PortableVariantChoiceBackup+import com.streamvault.domain.manager.PortableManualEpgMappingV14Backup+import com.streamvault.domain.manager.PortableMultiViewPresetV14Backup+import com.streamvault.domain.manager.BackupProviderReference+import com.streamvault.domain.repository.ProviderSnapshotRepository+import com.streamvault.domain.manager.RecordingManager+import com.streamvault.domain.manager.ScheduledRecordingBackup+import com.streamvault.domain.model.RecordingStatus+import com.streamvault.domain.model.Result+import com.streamvault.data.provider.toLegacyProvider+import java.net.URI+import com.streamvault.data.preferences.PreferencesRepository+import com.streamvault.domain.manager.PortableSearchHistoryBackup+import com.streamvault.domain.model.ContentType+import com.streamvault.domain.model.ProviderType+import java.util.Locale+import java.util.concurrent.ConcurrentHashMap+import javax.inject.Inject+import javax.inject.Singleton+import kotlinx.coroutines.CancellationException+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.sync.Mutex+import kotlinx.coroutines.sync.withLock++data class RestoreResolutionSummary(+ val appliedCount: Int = 0,+ val unresolvedCount: Int = 0,+ val failedCount: Int = 0+)++/** Applies durable v14 restore intentions after provider catalog transactions commit. */+@Singleton+class PendingBackupRestoreCoordinator @Inject constructor(+ private val ledgerDao: BackupRestoreLedgerDao,+ private val providerDao: ProviderDao,+ private val favoriteDao: FavoriteDao,+ private val virtualGroupDao: VirtualGroupDao,+ private val playbackHistoryDao: PlaybackHistoryDao,+ private val channelDao: ChannelDao,+ private val movieDao: MovieDao,+ private val seriesDao: SeriesDao,+ private val episodeDao: EpisodeDao,+ private val searchHistoryDao: SearchHistoryDao,+ private val channelPreferenceDao: ChannelPreferenceDao,+ private val channelEpgMappingDao: ChannelEpgMappingDao,+ private val epgSourceDao: EpgSourceDao,+ private val preferencesRepository: PreferencesRepository,+ private val providerSnapshotRepository: ProviderSnapshotRepository,+ private val recordingManager: RecordingManager,+ private val gson: Gson+) {+ private data class ReplaceScopePayload(+ val provider: BackupProviderReference?,+ val targetSection: String,+ val contentType: ContentType? = null+ )++ private val providerLocks = ConcurrentHashMap<Long, Mutex>()++ suspend fun applyForProvider(providerId: Long): RestoreResolutionSummary {+ val providerSummary = providerLocks.getOrPut(providerId) { Mutex() }.withLock {+ providerDao.getById(providerId) ?: return@withLock RestoreResolutionSummary()+ applyItems(retryableItemsForProvider(providerId), providerId)+ }+ // Global records such as multiview presets can span providers. Retry them after every+ // provider commit so the final required catalog becoming available applies the preset.+ return providerSummary + applyGlobal()+ }++ suspend fun applyGlobal(): RestoreResolutionSummary = providerLocks.getOrPut(0L) { Mutex() }.withLock {+ applyItems(ledgerDao.getRetryableItems(GLOBAL_PROVIDER_KEY).orEmpty(), providerId = 0L)+ }++ suspend fun applyAllAvailable() {+ applyGlobal()+ providerDao.getAllSync().forEach { provider -> applyForProvider(provider.id) }+ }++ /** Hidden categories normally skip item downloads. Pending user state is the one-time exception. */+ suspend fun requiredHiddenCategoryIds(providerId: Long, contentType: ContentType): Set<Long> {+ val hidden = preferencesRepository.getHiddenCategoryIds(providerId, contentType).first()+ if (hidden.isEmpty()) return emptySet()+ val providerItems = retryableItemsForProvider(providerId)+ val globalItems = ledgerDao.getRetryableItems(GLOBAL_PROVIDER_KEY).orEmpty()+ .filterNot { global -> providerItems.any { it.id == global.id } }+ val required = linkedSetOf<Long>()+ (providerItems.map { it to false } + globalItems.map { it to true }).forEach { (item, isGlobal) ->+ portableReferences(item).forEach { reference ->+ if (reference.contentType != contentType) return@forEach+ if (isGlobal && resolveProviderId(reference.provider) != providerId) return@forEach+ reference.remoteCategoryId?.toLongOrNull()?.let(required::add)+ }+ }+ return required.intersect(hidden)+ }++ /** Some restore sections contain several content references inside their payload. */+ private fun portableReferences(item: BackupRestoreItemEntity): List<PortableContentReference> = runCatching {+ when (item.section) {+ SECTION_FAVORITES -> listOf(gson.fromJson(item.payloadJson, PortableFavoriteBackup::class.java).content)+ SECTION_CUSTOM_GROUPS -> gson.fromJson(item.payloadJson, PortableCustomGroupBackup::class.java)+ .members.map { it.content }+ SECTION_PLAYBACK_HISTORY -> listOf(gson.fromJson(item.payloadJson, PortablePlaybackHistoryBackup::class.java).content)+ SECTION_PROTECTED_CONTENT -> listOf(gson.fromJson(item.payloadJson, PortableProtectedContentBackup::class.java).content)+ SECTION_HIDDEN_CONTENT -> listOf(gson.fromJson(item.payloadJson, PortableHiddenContentBackup::class.java).content)+ SECTION_CONTENT_PREFERENCES -> listOf(gson.fromJson(item.payloadJson, PortableContentPreferenceBackup::class.java).content)+ SECTION_VARIANT_CHOICES -> listOf(gson.fromJson(item.payloadJson, PortableVariantChoiceBackup::class.java).selectedContent)+ SECTION_MANUAL_EPG -> listOf(gson.fromJson(item.payloadJson, PortableManualEpgMappingV14Backup::class.java).content)+ SECTION_MULTIVIEW -> gson.fromJson(item.payloadJson, PortableMultiViewPresetV14Backup::class.java).channels+ SECTION_RECORDING_SCHEDULES -> listOfNotNull(+ gson.fromJson(item.payloadJson, ScheduledRecordingBackup::class.java).channel+ )+ else -> emptyList()+ }+ }.getOrDefault(emptyList())++ private suspend fun applyItems(+ items: List<BackupRestoreItemEntity>,+ providerId: Long+ ): RestoreResolutionSummary {+ var applied = 0+ var unresolved = 0+ var failed = 0+ val affectedJobs = linkedSetOf<String>()+ val itemsAppliedByScopeMarker = mutableSetOf<Long>()+ items.forEach { item ->+ if (item.id in itemsAppliedByScopeMarker) return@forEach+ affectedJobs += item.jobId+ val now = System.currentTimeMillis()+ try {+ val didApply = applyItem(item, providerId, itemsAppliedByScopeMarker)+ if (didApply) {+ applied += 1+ ledgerDao.updateItemStatus(+ item.id,+ BackupRestoreItemEntity.STATUS_APPLIED,+ providerId.takeIf { it != 0L },+ 1,+ null,+ now+ )+ } else {+ unresolved += 1+ ledgerDao.updateItemStatus(+ item.id,+ BackupRestoreItemEntity.STATUS_UNRESOLVED,+ providerId.takeIf { it != 0L },+ 1,+ "Catalog identity is not available yet",+ now+ )+ }+ } catch (cancelled: CancellationException) {+ throw cancelled+ } catch (error: Exception) {+ failed += 1+ ledgerDao.updateItemStatus(+ item.id,+ BackupRestoreItemEntity.STATUS_FAILED_RETRYABLE,+ providerId.takeIf { it != 0L },+ 1,+ error.message ?: error::class.java.simpleName,+ now+ )+ }+ }+ affectedJobs.forEach { ledgerDao.refreshJobCounts(it, System.currentTimeMillis()) }+ return RestoreResolutionSummary(applied, unresolved, failed)+ }++ private suspend fun applyItem(+ item: BackupRestoreItemEntity,+ providerId: Long,+ itemsAppliedByScopeMarker: MutableSet<Long> = mutableSetOf()+ ): Boolean = when (item.section) {+ SECTION_REPLACE_SCOPE -> applyReplaceScope(item, providerId, itemsAppliedByScopeMarker)+ SECTION_FAVORITES -> applyFavorite(item, providerId)+ SECTION_CUSTOM_GROUPS -> applyCustomGroup(item, providerId)+ SECTION_PLAYBACK_HISTORY -> applyPlaybackHistory(item, providerId)+ SECTION_PROTECTED_CONTENT -> applyProtectedContent(item, providerId)+ SECTION_HIDDEN_CONTENT -> applyHiddenContent(item, providerId)+ SECTION_CONTENT_PREFERENCES -> applyContentPreference(item, providerId)+ SECTION_VARIANT_CHOICES -> applyVariantChoice(item, providerId)+ SECTION_MANUAL_EPG -> applyManualEpg(item, providerId)+ SECTION_MULTIVIEW -> applyMultiView(item)+ SECTION_RECORDING_SCHEDULES -> applyRecordingSchedule(item, providerId)+ SECTION_SEARCH_HISTORY -> applySearchHistory(item, providerId)+ else -> false+ }++ private suspend fun applyReplaceScope(+ marker: BackupRestoreItemEntity,+ providerId: Long,+ itemsAppliedByScopeMarker: MutableSet<Long>+ ): Boolean {+ val scope = gson.fromJson(marker.payloadJson, ReplaceScopePayload::class.java)+ val targets = ledgerDao.getItems(marker.jobId).filter { candidate ->+ candidate.providerIdentityKey == marker.providerIdentityKey &&+ candidate.section == scope.targetSection &&+ candidate.status != BackupRestoreItemEntity.STATUS_DISMISSED &&+ (scope.contentType == null || candidate.contentType == scope.contentType.name)+ }+ if (targets.any { !canResolve(it, providerId) }) return false+ clearScope(providerId, scope)+ val now = System.currentTimeMillis()+ targets.forEach { target ->+ check(applyItem(target, providerId)) { "Resolved restore item could not be applied" }+ ledgerDao.updateItemStatus(+ target.id,+ BackupRestoreItemEntity.STATUS_APPLIED,+ providerId.takeIf { it != 0L },+ 1,+ null,+ now+ )+ itemsAppliedByScopeMarker += target.id+ }+ return true+ }++ private suspend fun canResolve(item: BackupRestoreItemEntity, providerId: Long): Boolean = when (item.section) {+ SECTION_FAVORITES -> resolveContent(providerId, gson.fromJson(item.payloadJson, PortableFavoriteBackup::class.java).content) != null+ SECTION_CUSTOM_GROUPS -> gson.fromJson(item.payloadJson, PortableCustomGroupBackup::class.java)+ .members.all { resolveContent(providerId, it.content) != null }+ SECTION_PLAYBACK_HISTORY -> {+ val backup = gson.fromJson(item.payloadJson, PortablePlaybackHistoryBackup::class.java)+ val parentRemoteId = backup.content.parentRemoteContentId+ resolveContent(providerId, backup.content) != null &&+ (parentRemoteId == null || resolveContent(+ providerId,+ backup.content.copy(contentType = ContentType.SERIES, remoteContentId = parentRemoteId)+ ) != null)+ }+ SECTION_PROTECTED_CONTENT -> resolveContent(providerId, gson.fromJson(item.payloadJson, PortableProtectedContentBackup::class.java).content) != null+ SECTION_HIDDEN_CONTENT -> resolveContent(providerId, gson.fromJson(item.payloadJson, PortableHiddenContentBackup::class.java).content) != null+ SECTION_CONTENT_PREFERENCES -> resolveContent(providerId, gson.fromJson(item.payloadJson, PortableContentPreferenceBackup::class.java).content) != null+ SECTION_VARIANT_CHOICES -> resolveContent(providerId, gson.fromJson(item.payloadJson, PortableVariantChoiceBackup::class.java).selectedContent) != null+ SECTION_MANUAL_EPG -> {+ val backup = gson.fromJson(item.payloadJson, PortableManualEpgMappingV14Backup::class.java)+ val sourceUrl = backup.sourceUrl+ resolveContent(providerId, backup.content) != null &&+ (sourceUrl == null || epgSourceDao.getByUrl(sourceUrl) != null)+ }+ SECTION_MULTIVIEW -> gson.fromJson(item.payloadJson, PortableMultiViewPresetV14Backup::class.java).channels.all { reference ->+ resolveProviderId(reference.provider)?.let { resolveContent(it, reference) } != null+ }+ SECTION_RECORDING_SCHEDULES -> gson.fromJson(item.payloadJson, ScheduledRecordingBackup::class.java).channel+ ?.let { resolveContent(providerId, it) } != null+ SECTION_SEARCH_HISTORY -> true+ else -> false+ }++ private suspend fun clearScope(providerId: Long, scope: ReplaceScopePayload) {+ when (scope.targetSection) {+ SECTION_FAVORITES -> scope.contentType?.let { favoriteDao.deleteGlobalByProviderAndType(providerId, it.name) }+ SECTION_CUSTOM_GROUPS -> scope.contentType?.let { virtualGroupDao.deleteByProviderAndType(providerId, it.name) }+ SECTION_PLAYBACK_HISTORY -> scope.contentType?.let { playbackHistoryDao.deleteByProviderAndType(providerId, it.name) }+ SECTION_PROTECTED_CONTENT -> when (scope.contentType) {+ ContentType.LIVE -> channelDao.resetProtectionToCategoryState(providerId)+ ContentType.MOVIE, ContentType.VOD -> movieDao.resetProtectionToCategoryState(providerId)+ ContentType.SERIES -> seriesDao.resetProtectionToCategoryState(providerId)+ ContentType.SERIES_EPISODE -> episodeDao.resetProtectionToCategoryState(providerId)+ null -> Unit+ }+ SECTION_HIDDEN_CONTENT -> preferencesRepository.setHiddenChannelIds(providerId, emptySet())+ SECTION_CONTENT_PREFERENCES -> channelPreferenceDao.deleteByProvider(providerId)+ SECTION_VARIANT_CHOICES -> {+ preferencesRepository.clearPreferredLiveVariants(providerId)+ preferencesRepository.clearPreferredVodVariants(providerId)+ }+ SECTION_MANUAL_EPG -> channelEpgMappingDao.deleteByProvider(providerId)+ SECTION_SEARCH_HISTORY -> searchHistoryDao.deleteByProvider(providerId)+ SECTION_MULTIVIEW -> repeat(3) { preferencesRepository.setMultiViewPreset(it, emptyList()) }+ SECTION_RECORDING_SCHEDULES -> recordingManager.observeRecordingItems().first()+ .filter { it.providerId == providerId && it.status == RecordingStatus.SCHEDULED }+ .forEach { recordingManager.cancelRecording(it.id) }+ }+ }++ private suspend fun applyFavorite(item: BackupRestoreItemEntity, providerId: Long): Boolean {+ val backup = gson.fromJson(item.payloadJson, PortableFavoriteBackup::class.java)+ val resolved = resolveContent(providerId, backup.content) ?: return false+ if (favoriteDao.get(providerId, resolved.localId, resolved.favoriteType.name, null) == null) {+ favoriteDao.insert(+ FavoriteEntity(+ providerId = providerId,+ contentId = resolved.localId,+ contentType = resolved.favoriteType,+ position = backup.position,+ addedAt = backup.addedAt+ )+ )+ }+ return true+ }++ private suspend fun applyCustomGroup(item: BackupRestoreItemEntity, providerId: Long): Boolean {+ val backup = gson.fromJson(item.payloadJson, PortableCustomGroupBackup::class.java)+ val resolvedMembers = backup.members.map { member ->+ member to (resolveContent(providerId, member.content) ?: return false)+ }+ val matchingGroups = virtualGroupDao.getByType(providerId, backup.contentType.name).first()+ .filter { it.name.normalized() == backup.name.normalized() }+ val groupId = when (matchingGroups.size) {+ 0 -> virtualGroupDao.insert(+ VirtualGroupEntity(+ providerId = providerId,+ name = backup.name,+ iconEmoji = backup.icon,+ position = backup.position,+ createdAt = backup.createdAt,+ contentType = backup.contentType+ )+ )+ 1 -> matchingGroups.single().id+ else -> return false+ }+ resolvedMembers.forEach { (member, resolved) ->+ if (favoriteDao.get(providerId, resolved.localId, resolved.favoriteType.name, groupId) == null) {+ favoriteDao.insert(+ FavoriteEntity(+ providerId = providerId,+ contentId = resolved.localId,+ contentType = resolved.favoriteType,+ position = member.position,+ groupId = groupId,+ groupKey = groupId,+ addedAt = member.addedAt+ )+ )+ }+ }+ return true+ }++ private suspend fun applyPlaybackHistory(item: BackupRestoreItemEntity, providerId: Long): Boolean {+ val backup = gson.fromJson(item.payloadJson, PortablePlaybackHistoryBackup::class.java)+ val resolved = resolveContent(providerId, backup.content) ?: return false+ val parentSeriesId = backup.content.parentRemoteContentId?.let { remoteParent ->+ resolveContent(+ providerId,+ backup.content.copy(contentType = ContentType.SERIES, remoteContentId = remoteParent)+ )?.localId+ }+ playbackHistoryDao.insertOrUpdate(+ PlaybackHistoryEntity(+ contentId = resolved.localId,+ contentType = backup.content.contentType,+ providerId = providerId,+ title = backup.content.name.orEmpty(),+ posterUrl = backup.posterUrl,+ streamUrl = backup.content.urlFallback.orEmpty(),+ resumePositionMs = backup.resumePositionMs,+ totalDurationMs = backup.totalDurationMs,+ lastWatchedAt = backup.lastWatchedAt,+ watchCount = backup.watchCount.coerceAtLeast(1),+ watchedStatus = backup.watchedStatus,+ seriesId = parentSeriesId,+ seasonNumber = backup.seasonNumber,+ episodeNumber = backup.episodeNumber+ )+ )+ return true+ }++ private suspend fun applyProtectedContent(item: BackupRestoreItemEntity, providerId: Long): Boolean {+ val backup = gson.fromJson(item.payloadJson, PortableProtectedContentBackup::class.java)+ val resolved = resolveContent(providerId, backup.content) ?: return false+ return when (backup.content.contentType) {+ ContentType.LIVE -> channelDao.updateItemProtection(resolved.localId, providerId, true) > 0+ ContentType.VOD, ContentType.MOVIE -> movieDao.updateItemProtection(resolved.localId, providerId, true) > 0+ ContentType.SERIES -> seriesDao.updateItemProtection(resolved.localId, providerId, true) > 0+ ContentType.SERIES_EPISODE -> episodeDao.updateItemProtection(resolved.localId, providerId, true) > 0+ }+ }++ private suspend fun applyHiddenContent(item: BackupRestoreItemEntity, providerId: Long): Boolean {+ val backup = gson.fromJson(item.payloadJson, PortableHiddenContentBackup::class.java)+ val resolved = resolveContent(providerId, backup.content) ?: return false+ if (backup.content.contentType != ContentType.LIVE) return false+ preferencesRepository.setChannelHidden(providerId, resolved.localId, true)+ return true+ }++ private suspend fun applyContentPreference(item: BackupRestoreItemEntity, providerId: Long): Boolean {+ val backup = gson.fromJson(item.payloadJson, PortableContentPreferenceBackup::class.java)+ val resolved = resolveContent(providerId, backup.content) ?: return false+ channelPreferenceDao.upsert(+ ChannelPreferenceEntity(+ channelId = resolved.localId,+ aspectRatio = backup.aspectRatio,+ audioVideoOffsetMs = backup.audioVideoOffsetMs+ )+ )+ return true+ }++ private suspend fun applyVariantChoice(item: BackupRestoreItemEntity, providerId: Long): Boolean {+ val backup = gson.fromJson(item.payloadJson, PortableVariantChoiceBackup::class.java)+ val resolved = resolveContent(providerId, backup.selectedContent) ?: return false+ when (backup.selectedContent.contentType) {+ ContentType.LIVE -> preferencesRepository.setPreferredLiveVariant(providerId, backup.logicalGroupId, resolved.localId)+ ContentType.VOD, ContentType.MOVIE, ContentType.SERIES, ContentType.SERIES_EPISODE ->+ preferencesRepository.setPreferredVodVariant(providerId, backup.logicalGroupId, resolved.localId)+ }+ return true+ }++ private suspend fun applyManualEpg(item: BackupRestoreItemEntity, providerId: Long): Boolean {+ val backup = gson.fromJson(item.payloadJson, PortableManualEpgMappingV14Backup::class.java)+ val resolved = resolveContent(providerId, backup.content) ?: return false+ val sourceId = backup.sourceUrl?.let { epgSourceDao.getByUrl(it)?.id ?: return false }+ channelEpgMappingDao.upsert(+ ChannelEpgMappingEntity(+ providerChannelId = resolved.localId,+ providerId = providerId,+ sourceType = backup.sourceType,+ epgSourceId = sourceId,+ xmltvChannelId = backup.xmltvChannelId,+ matchType = backup.matchType,+ confidence = backup.confidence,+ source = backup.source,+ isManualOverride = true+ )+ )+ return true+ }++ private suspend fun applyMultiView(item: BackupRestoreItemEntity): Boolean {+ val backup = gson.fromJson(item.payloadJson, PortableMultiViewPresetV14Backup::class.java)+ val channelIds = backup.channels.map { reference ->+ val providerId = resolveProviderId(reference.provider) ?: return false+ resolveContent(providerId, reference)?.localId ?: return false+ }+ val index = backup.name.removePrefix("preset_").toIntOrNull()?.minus(1)+ ?.takeIf { it in 0..2 } ?: return false+ preferencesRepository.setMultiViewPreset(index, channelIds)+ return true+ }++ private suspend fun applyRecordingSchedule(item: BackupRestoreItemEntity, providerId: Long): Boolean {+ val backup = gson.fromJson(item.payloadJson, ScheduledRecordingBackup::class.java)+ if (backup.scheduledEndMs <= System.currentTimeMillis() && backup.recurrence.name == "NONE") return true+ val reference = backup.channel ?: return false+ val resolved = resolveContent(providerId, reference) ?: return false+ val restored = backup.copy(channelId = resolved.localId)+ val duplicate = recordingManager.observeRecordingItems().first().any { existing ->+ existing.status == RecordingStatus.SCHEDULED &&+ existing.providerId == providerId &&+ existing.channelId == resolved.localId &&+ existing.scheduledStartMs == restored.scheduledStartMs &&+ existing.scheduledEndMs == restored.scheduledEndMs+ }+ if (duplicate) return true+ return when (recordingManager.scheduleRecording(restored.toRecordingRequest(providerId))) {+ is Result.Success -> true+ is Result.Error, Result.Loading -> false+ }+ }++ private suspend fun resolveProviderId(reference: BackupProviderReference): Long? {+ val matches = providerDao.getAllSync().mapNotNull { entity ->+ providerSnapshotRepository.getSnapshot(entity.id)?.toLegacyProvider()+ }.filter { provider ->+ normalizeUrl(provider.serverUrl) == normalizeUrl(reference.serverUrl) &&+ (reference.providerType == null || provider.type == reference.providerType) &&+ provider.username.trim() == reference.username.trim() &&+ provider.stalkerMacAddress.trim().uppercase(Locale.ROOT) ==+ reference.stalkerMacAddress.orEmpty().trim().uppercase(Locale.ROOT)+ }+ return matches.singleOrNull()?.id+ }++ private suspend fun retryableItemsForProvider(providerId: Long): List<BackupRestoreItemEntity> {+ val byLocalId = ledgerDao.getRetryableItemsByLocalProviderId(providerId).orEmpty()+ val provider = providerSnapshotRepository.getSnapshot(providerId)?.toLegacyProvider()+ ?: return byLocalId+ val identityKey = BackupProviderReference(+ serverUrl = normalizeUrl(provider.serverUrl),+ username = provider.username.trim().takeUnless { provider.type == ProviderType.M3U }.orEmpty(),+ stalkerMacAddress = provider.stalkerMacAddress.takeIf { it.isNotBlank() },+ providerType = provider.type+ ).stableIdentityKey()+ return (byLocalId + ledgerDao.getRetryableItems(identityKey).orEmpty()).distinctBy { it.id }+ }++ private fun BackupProviderReference.stableIdentityKey(): String = listOf(+ normalizeUrl(serverUrl),+ username.trim(),+ providerType?.name.orEmpty(),+ stalkerMacAddress.orEmpty().trim().uppercase(Locale.ROOT)+ ).joinToString("|")++ private fun normalizeUrl(value: String): String = runCatching {+ val uri = URI(value.trim())+ val scheme = uri.scheme?.lowercase(Locale.ROOT).orEmpty()+ val host = uri.host?.lowercase(Locale.ROOT).orEmpty()+ val port = when {+ uri.port < 0 -> ""+ scheme == "http" && uri.port == 80 -> ""+ scheme == "https" && uri.port == 443 -> ""+ else -> ":${uri.port}"+ }+ "$scheme://$host$port${uri.rawPath.orEmpty().trimEnd('/')}"+ }.getOrElse { value.trim().trimEnd('/').lowercase(Locale.ROOT) }++ private suspend fun applySearchHistory(item: BackupRestoreItemEntity, providerId: Long): Boolean {+ val backup = gson.fromJson(item.payloadJson, PortableSearchHistoryBackup::class.java)+ if (searchHistoryDao.get(backup.query, backup.contentScope, providerId) == null) {+ searchHistoryDao.upsert(+ SearchHistoryEntity(+ query = backup.query,+ contentScope = backup.contentScope,+ providerId = providerId,+ usedAt = backup.usedAt,+ useCount = backup.useCount.coerceAtLeast(1)+ )+ )+ }+ return true+ }++ private suspend fun resolveContent(providerId: Long, reference: PortableContentReference): ResolvedContent? {+ reference.remoteContentId.removePrefix(LEGACY_LOCAL_ID_PREFIX)+ .takeIf { reference.remoteContentId.startsWith(LEGACY_LOCAL_ID_PREFIX) }+ ?.toLongOrNull()+ ?.let { localId ->+ return when (reference.contentType) {+ ContentType.LIVE -> channelDao.getById(localId)+ ?.takeIf { it.providerId == providerId }+ ?.let { ResolvedContent(it.id, ContentType.LIVE) }+ ContentType.VOD, ContentType.MOVIE -> movieDao.getById(localId)+ ?.takeIf { it.providerId == providerId }+ ?.let { ResolvedContent(it.id, ContentType.MOVIE) }+ ContentType.SERIES -> seriesDao.getById(localId)+ ?.takeIf { it.providerId == providerId }+ ?.let { ResolvedContent(it.id, ContentType.SERIES) }+ ContentType.SERIES_EPISODE -> episodeDao.getById(localId)+ ?.takeIf { it.providerId == providerId }+ ?.let { ResolvedContent(it.id, ContentType.SERIES_EPISODE) }+ }+ }+ val remoteLong = reference.remoteContentId.toLongOrNull()+ return when (reference.contentType) {+ ContentType.LIVE -> {+ remoteLong?.let { channelDao.getByStreamId(providerId, it) }+ ?.let { ResolvedContent(it.id, ContentType.LIVE) }+ ?: channelDao.getByProviderSync(providerId)+ .resolveUnique(reference, { it.name }, { it.streamUrl })+ ?.let { ResolvedContent(it.id, ContentType.LIVE) }+ }+ ContentType.VOD, ContentType.MOVIE -> {+ remoteLong?.let { movieDao.getByStreamId(providerId, it) }+ ?.let { ResolvedContent(it.id, ContentType.MOVIE) }+ ?: movieDao.getByProviderSync(providerId)+ .resolveUnique(reference, { it.name }, { it.streamUrl })+ ?.let { ResolvedContent(it.id, ContentType.MOVIE) }+ }+ ContentType.SERIES -> {+ val rows = seriesDao.getByProviderSync(providerId)+ rows.filter {+ it.providerSeriesId == reference.remoteContentId ||+ (remoteLong != null && it.seriesId == remoteLong)+ }.singleOrNull()?.let { ResolvedContent(it.id, ContentType.SERIES) }+ ?: rows.resolveUnique(reference, { it.name }, { null })+ ?.let { ResolvedContent(it.id, ContentType.SERIES) }+ }+ ContentType.SERIES_EPISODE -> {+ val episode = remoteLong?.let { episodeDao.getByProviderAndEpisodeId(providerId, it) }+ if (episode != null) {+ ResolvedContent(episode.id, ContentType.SERIES_EPISODE)+ } else {+ episodeDao.getByProviderSync(providerId)+ .resolveUnique(reference, { it.title }, { it.streamUrl })+ ?.let { ResolvedContent(it.id, ContentType.SERIES_EPISODE) }+ }+ }+ }+ }++ private data class ResolvedContent(val localId: Long, val favoriteType: ContentType)++ private operator fun RestoreResolutionSummary.plus(other: RestoreResolutionSummary) = RestoreResolutionSummary(+ appliedCount = appliedCount + other.appliedCount,+ unresolvedCount = unresolvedCount + other.unresolvedCount,+ failedCount = failedCount + other.failedCount+ )++ private fun <T> List<T>.resolveUnique(+ reference: PortableContentReference,+ name: (T) -> String,+ url: (T) -> String?+ ): T? {+ reference.urlFallback?.takeIf { it.isNotBlank() }?.let { expected ->+ filter { url(it) == expected }.singleOrNull()?.let { return it }+ }+ val expectedName = reference.name?.normalized()?.takeIf { it.isNotBlank() } ?: return null+ return filter { name(it).normalized() == expectedName }.singleOrNull()+ }++ private fun String.normalized(): String = trim().lowercase(Locale.ROOT)++ private companion object {+ const val GLOBAL_PROVIDER_KEY = "__GLOBAL__"+ const val SECTION_FAVORITES = "FAVORITES"+ const val SECTION_CUSTOM_GROUPS = "CUSTOM_GROUPS"+ const val SECTION_PLAYBACK_HISTORY = "PLAYBACK_HISTORY"+ const val SECTION_PROTECTED_CONTENT = "PROTECTED_CONTENT"+ const val SECTION_HIDDEN_CONTENT = "HIDDEN_CONTENT"+ const val SECTION_CONTENT_PREFERENCES = "CONTENT_PREFERENCES"+ const val SECTION_VARIANT_CHOICES = "VARIANT_CHOICES"+ const val SECTION_MANUAL_EPG = "MANUAL_EPG"+ const val SECTION_MULTIVIEW = "MULTIVIEW"+ const val SECTION_RECORDING_SCHEDULES = "RECORDING_SCHEDULES"+ const val SECTION_SEARCH_HISTORY = "SEARCH_HISTORY"+ const val SECTION_REPLACE_SCOPE = "REPLACE_SCOPE"+ const val LEGACY_LOCAL_ID_PREFIX = "legacy-local-id:"+ }+}diff --git a/data/src/main/java/com/streamvault/data/manager/PreferenceBackupRegistry.kt b/data/src/main/java/com/streamvault/data/manager/PreferenceBackupRegistry.ktnew file mode 100644index 00000000..420c9031--- /dev/null+++ b/data/src/main/java/com/streamvault/data/manager/PreferenceBackupRegistry.kt@@ -0,0 +1,156 @@+package com.streamvault.data.manager++enum class PreferenceBackupClassification {+ PORTABLE_GLOBAL,+ PORTABLE_PROVIDER_CONTENT,+ DEVICE_BOUND,+ RUNTIME_CACHE+}++/** Single review point for every preference admitted to a portable backup. */+internal object PreferenceBackupRegistry {+ private val portableStorageKeys = setOf(+ "last_active_provider_id", "active_live_source_type", "active_live_source_id",+ "default_view_mode", "parental_control_level", "parental_pin_hash", "parental_pin_salt",+ "default_category_id", "app_language", "app_landing_destination", "app_top_level_destinations",+ "app_home_dashboard_shelves", "app_time_format", "live_tv_channel_mode",+ "show_live_source_switcher", "show_favorites_category", "show_all_channels_category",+ "show_recent_channels_category", "live_tv_category_filters", "live_tv_quick_filter_visibility",+ "hide_decorative_live_rows", "live_channel_numbering_mode", "live_channel_grouping_mode",+ "grouped_channel_label_mode", "live_variant_preference_mode", "live_variant_selections",+ "vod_view_mode", "vod_infinite_scroll", "vod_category_load_mode", "vod_duplicate_handling_mode",+ "vod_variant_preference_mode", "vod_variant_selections", "guide_density", "guide_channel_mode",+ "guide_default_category_id", "guide_favorites_only", "guide_anchor_time",+ "epg_time_shift_by_provider", "promoted_live_group_ids", "multiview_preset_1",+ "multiview_preset_2", "multiview_preset_3", "multiview_performance_mode",+ "multiview_center_two_slot_layout", "multiview_respect_provider_connection_limit",+ "is_incognito_mode", "player_muted", "player_media_session_enabled",+ "player_fast_retry_on_transient_failures", "player_audio_decoder_mode", "player_video_decoder_mode",+ "player_playback_buffer_mode", "player_live_stream_format_mode", "player_vod_http_protocol_mode",+ "player_audio_output_preference", "player_compatibility_memory_enabled", "player_surface_mode",+ "player_playback_speed", "player_external_playback_mode", "player_av_sync_enabled",+ "player_av_offset_ms", "preferred_audio_language", "player_subtitle_text_scale",+ "player_subtitle_text_color", "player_subtitle_background_color", "player_live_translation_enabled",+ "player_live_translation_endpoint", "player_controls_timeout_seconds",+ "player_live_overlay_timeout_seconds", "player_notice_timeout_seconds",+ "player_diagnostics_timeout_seconds", "player_wifi_max_video_height",+ "player_ethernet_max_video_height", "player_timeshift_enabled", "player_timeshift_depth_minutes",+ "player_timeshift_backend", "default_stop_playback_timer_minutes",+ "default_idle_standby_timer_minutes", "guide_scheduled_only", "xtream_text_classification",+ "xtream_base64_text_compatibility", "zap_auto_revert", "prevent_standby_during_playback",+ "auto_play_next_episode", "auto_check_app_updates", "auto_download_app_updates",+ "recording_wifi_only", "recording_padding_before_minutes", "recording_padding_after_minutes",+ "max_concurrent_streams"+ )+ private val deviceBoundStorageKeys = setOf("download_tree_uri")+ private val runtimeStorageKeys = setOf(+ "parental_v2_migrated", "parental_pin", "live_variant_observations", "vod_variant_observations",+ "player_decoder_mode", "player_movie_http_protocol_mode", "last_speed_test_megabits",+ "last_speed_test_timestamp", "last_speed_test_transport", "last_speed_test_recommended_height",+ "last_speed_test_estimated", "recent_search_queries", "xtream_text_import_generation",+ "last_app_update_check_timestamp", "last_app_update_attempt_timestamp",+ "last_app_update_failure_timestamp", "last_app_update_outcome", "app_update_download_id",+ "app_update_download_version_name", "app_update_downloaded_version_name",+ "app_update_latest_version_name", "app_update_latest_version_code", "app_update_release_url",+ "app_update_download_url", "app_update_download_sha256", "app_update_release_notes",+ "app_update_published_at", "last_maintenance_at", "last_maintenance_deleted_programs",+ "last_maintenance_deleted_external_programmes", "last_maintenance_deleted_orphan_episodes",+ "last_maintenance_deleted_stale_favorites", "last_maintenance_vacuum_ran",+ "last_maintenance_main_db_bytes", "last_maintenance_wal_bytes",+ "last_maintenance_reclaimable_bytes", "last_maintenance_channel_rows",+ "last_maintenance_movie_rows", "last_maintenance_series_rows", "last_maintenance_episode_rows",+ "last_maintenance_program_rows", "last_maintenance_epg_programme_rows",+ "last_maintenance_playback_history_rows", "last_maintenance_favorite_rows"+ )+ private val providerStoragePrefixes = setOf(+ "hidden_channels_", "hidden_categories_", "pinned_categories_", "category_sort_"+ )+ private val globalStoragePrefixes = setOf("remote_shortcut_")+ private val runtimeStoragePrefixes = setOf(+ "xtream_text_import_applied_generation_", "last_live_category_id_",+ "last_split_catalog_type_", "aspect_ratio_"+ )++ private val providerKeys = setOf(+ "guideDefaultCategoryId",+ "lastActiveProviderId",+ "promotedLiveGroupIds"+ )+ private val providerPrefixes = setOf(+ "hiddenChannels_",+ "hiddenCategories_",+ "pinnedCategories_",+ "categorySortMode_",+ "epgTimeShift_",+ "liveVariantSelections_",+ "vodVariantSelections_"+ )+ private val globalKeys = setOf(+ "parentalControlLevel", "parentalPinHash", "parentalPinSalt", "appLanguage", "appTimeFormat",+ "defaultViewMode", "appLandingDestination", "appTopLevelDestinations", "appHomeDashboardShelves",+ "remoteShortcutPreferences", "liveTvCategoryFilters", "liveTvQuickFilterVisibility", "liveTvChannelMode",+ "showLiveSourceSwitcher", "showFavoritesCategory", "showAllChannelsCategory", "showRecentChannelsCategory",+ "hideDecorativeLiveRows", "liveChannelNumberingMode", "liveChannelGroupingMode", "groupedChannelLabelMode",+ "liveVariantPreferenceMode", "vodViewMode", "vodInfiniteScroll", "vodCategoryLoadMode",+ "vodDuplicateHandlingMode", "vodVariantPreferenceMode", "playerMediaSessionEnabled",+ "playerFastRetryOnTransientFailures", "playerAudioDecoderMode", "playerVideoDecoderMode",+ "playerPlaybackBufferMode", "playerAudioOutputPreference", "playerCompatibilityMemoryEnabled",+ "playerSurfaceMode", "playerLiveStreamFormatMode", "playerVodHttpProtocolMode", "playerPlaybackSpeed",+ "playerExternalPlaybackMode", "playerAudioVideoSyncEnabled", "playerAudioVideoOffsetMs", "playerMuted",+ "multiViewPerformanceMode", "multiViewCenterTwoSlotLayout", "multiViewRespectProviderConnectionLimit",+ "preferredAudioLanguage", "playerSubtitleTextScale", "playerSubtitleTextColor",+ "playerSubtitleBackgroundColor", "playerLiveTranslationEnabled", "playerLiveTranslationEndpoint",+ "playerControlsTimeoutSeconds", "playerLiveOverlayTimeoutSeconds", "playerNoticeTimeoutSeconds",+ "playerDiagnosticsTimeoutSeconds", "playerWifiMaxVideoHeight", "playerEthernetMaxVideoHeight",+ "playerTimeshiftEnabled", "playerTimeshiftDepthMinutes", "playerTimeshiftBackend",+ "defaultStopPlaybackTimerMinutes", "defaultIdleStandbyTimerMinutes", "preventStandbyDuringPlayback",+ "zapAutoRevert", "autoPlayNextEpisode", "autoCheckAppUpdates", "autoDownloadAppUpdates",+ "recordingWifiOnly", "recordingPaddingBeforeMinutes", "recordingPaddingAfterMinutes",+ "maxConcurrentStreams", "isIncognitoMode", "useXtreamTextClassification",+ "xtreamBase64TextCompatibility", "guideDensity", "guideChannelMode", "guideFavoritesOnly",+ "guideScheduledOnly", "guideAnchorTime"+ )++ fun classification(key: String): PreferenceBackupClassification? = when {+ key in globalKeys -> PreferenceBackupClassification.PORTABLE_GLOBAL+ key in providerKeys || providerPrefixes.any(key::startsWith) ->+ PreferenceBackupClassification.PORTABLE_PROVIDER_CONTENT+ else -> null+ }++ fun storageClassification(key: String): PreferenceBackupClassification? = when {+ key in portableStorageKeys -> if (+ key in setOf(+ "last_active_provider_id", "active_live_source_type", "active_live_source_id",+ "default_category_id", "guide_default_category_id", "epg_time_shift_by_provider",+ "promoted_live_group_ids", "live_variant_selections", "vod_variant_selections"+ )+ ) PreferenceBackupClassification.PORTABLE_PROVIDER_CONTENT+ else PreferenceBackupClassification.PORTABLE_GLOBAL+ key in deviceBoundStorageKeys -> PreferenceBackupClassification.DEVICE_BOUND+ key in runtimeStorageKeys -> PreferenceBackupClassification.RUNTIME_CACHE+ providerStoragePrefixes.any(key::startsWith) -> PreferenceBackupClassification.PORTABLE_PROVIDER_CONTENT+ globalStoragePrefixes.any(key::startsWith) -> PreferenceBackupClassification.PORTABLE_GLOBAL+ runtimeStoragePrefixes.any(key::startsWith) -> PreferenceBackupClassification.RUNTIME_CACHE+ else -> null+ }++ fun portableCodecForStorageKey(key: String): String? = when {+ storageClassification(key) == PreferenceBackupClassification.PORTABLE_GLOBAL -> "preferences"+ storageClassification(key) == PreferenceBackupClassification.PORTABLE_PROVIDER_CONTENT -> when (key) {+ "active_live_source_type", "active_live_source_id" -> "activeLiveSource"+ "live_variant_selections", "vod_variant_selections" -> "portableVariantChoices"+ "epg_time_shift_by_provider", "last_active_provider_id", "default_category_id",+ "guide_default_category_id", "promoted_live_group_ids" -> "portableProviderPreferences"+ else -> "portableProviderPreferences"+ }+ else -> null+ }++ fun requirePortableCodecs(keys: Set<String>) {+ val unclassified = keys.filter { classification(it) == null }+ require(unclassified.isEmpty()) {+ "Portable preference codec/classification missing for: ${unclassified.sorted().joinToString()}"+ }+ }+}diff --git a/data/src/main/java/com/streamvault/data/preferences/PreferencesRepository.kt b/data/src/main/java/com/streamvault/data/preferences/PreferencesRepository.ktindex 109c4f61..9a8d1a80 100644--- a/data/src/main/java/com/streamvault/data/preferences/PreferencesRepository.kt+++ b/data/src/main/java/com/streamvault/data/preferences/PreferencesRepository.kt@@ -1702,6 +1702,16 @@ class PreferencesRepository @Inject constructor(}}+ suspend fun clearPreferredLiveVariants(providerId: Long) {+ if (providerId <= 0L) return+ context.dataStore.edit { preferences ->+ val updated = decodeLiveVariantSelections(preferences[PreferencesKeys.LIVE_VARIANT_SELECTIONS])+ .filterKeys { !it.startsWith("$providerId|") }+ if (updated.isEmpty()) preferences.remove(PreferencesKeys.LIVE_VARIANT_SELECTIONS)+ else preferences[PreferencesKeys.LIVE_VARIANT_SELECTIONS] = encodeLiveVariantSelections(updated)+ }+ }+val liveVariantObservations: Flow<Map<Long, LiveChannelObservedQuality>> = context.dataStore.data.map { preferences ->decodeLiveVariantObservations(preferences[PreferencesKeys.LIVE_VARIANT_OBSERVATIONS])}@@ -1761,6 +1771,16 @@ class PreferencesRepository @Inject constructor(}}+ suspend fun clearPreferredVodVariants(providerId: Long) {+ if (providerId <= 0L) return+ context.dataStore.edit { preferences ->+ val updated = decodeVodVariantSelections(preferences[PreferencesKeys.VOD_VARIANT_SELECTIONS])+ .filterKeys { !it.startsWith("$providerId|") }+ if (updated.isEmpty()) preferences.remove(PreferencesKeys.VOD_VARIANT_SELECTIONS)+ else preferences[PreferencesKeys.VOD_VARIANT_SELECTIONS] = encodeVodVariantSelections(updated)+ }+ }+val vodVariantObservations: Flow<Map<Long, VodVariantObservation>> = context.dataStore.data.map { preferences ->decodeVodVariantObservations(preferences[PreferencesKeys.VOD_VARIANT_OBSERVATIONS])}diff --git a/data/src/main/java/com/streamvault/data/sync/StalkerCatalogSyncExecutor.kt b/data/src/main/java/com/streamvault/data/sync/StalkerCatalogSyncExecutor.ktindex 2726fc87..ccd091a5 100644--- a/data/src/main/java/com/streamvault/data/sync/StalkerCatalogSyncExecutor.kt+++ b/data/src/main/java/com/streamvault/data/sync/StalkerCatalogSyncExecutor.kt@@ -79,7 +79,8 @@ internal class StalkerCatalogSyncExecutor(private val progress: (Long, ((String) -> Unit)?, String) -> Unit,private val emitCatalogProgress: (Long, Section, Int?, Int?) -> Unit,private val categoryFailureWarning: (String, String, Throwable) -> String,- private val sanitizeThrowableMessage: (Throwable?) -> String+ private val sanitizeThrowableMessage: (Throwable?) -> String,+ private val requiredHiddenCategoryIds: suspend (Long, ContentType) -> Set<Long> = { _, _ -> emptySet() }) {suspend fun syncFull(provider: Provider,@@ -156,10 +157,12 @@ internal class StalkerCatalogSyncExecutor(if (force || ContentCachePolicy.shouldRefresh(metadata.lastLiveSuccess, ContentCachePolicy.CATALOG_TTL_MILLIS, now)) {progress(provider.id, onProgress, "Downloading Live TV...")val hiddenLiveCategoryIds = preferencesRepository.getHiddenCategoryIds(provider.id, ContentType.LIVE).first()+ val requiredHiddenLiveCategoryIds = requiredHiddenCategoryIds(provider.id, ContentType.LIVE)val liveCatalogResult = syncLiveCatalogStaged(api = api,provider = provider,hiddenLiveCategoryIds = hiddenLiveCategoryIds,+ requiredHiddenLiveCategoryIds = requiredHiddenLiveCategoryIds,onProgress = onProgress,afterCatalogApply = catalogCommitCallback)@@ -352,7 +355,14 @@ internal class StalkerCatalogSyncExecutor(progress(provider.id, onProgress, "Retrying Live TV...")val api = createProvider(provider)val hiddenLiveCategoryIds = preferencesRepository.getHiddenCategoryIds(provider.id, ContentType.LIVE).first()- val liveCatalogResult = syncLiveCatalogStaged(api, provider, hiddenLiveCategoryIds, onProgress)+ val requiredHiddenLiveCategoryIds = requiredHiddenCategoryIds(provider.id, ContentType.LIVE)+ val liveCatalogResult = syncLiveCatalogStaged(+ api,+ provider,+ hiddenLiveCategoryIds,+ requiredHiddenLiveCategoryIds,+ onProgress+ )val metadata = (syncMetadataRepository.getMetadata(provider.id) ?: SyncMetadata(provider.id)).copy(lastLiveSync = now,lastLiveSuccess = now,@@ -377,6 +387,7 @@ internal class StalkerCatalogSyncExecutor(api: StalkerProvider,provider: Provider,hiddenLiveCategoryIds: Set<Long>,+ requiredHiddenLiveCategoryIds: Set<Long>,onProgress: ((String) -> Unit)?,afterCatalogApply: suspend () -> Unit = {}): StagedStalkerLiveCatalogResult {@@ -385,7 +396,7 @@ internal class StalkerCatalogSyncExecutor(val preferredCategories = when (val categoriesResult = api.getLiveCategories()) {is Result.Success -> categoriesResult.data.map { it.toEntity(provider.id) }- .filterNot { it.categoryId in hiddenLiveCategoryIds }+ .filterNot { it.categoryId in hiddenLiveCategoryIds && it.categoryId !in requiredHiddenLiveCategoryIds }is Result.Error -> {Log.w(STALKER_EXECUTOR_TAG,@@ -472,7 +483,7 @@ internal class StalkerCatalogSyncExecutor(withBulkLiveStallTimeout { markBulkProgress ->api.streamLiveStreams { channel ->markBulkProgress()- if (channel.categoryId != null && channel.categoryId in hiddenLiveCategoryIds) return@streamLiveStreams+ if (channel.categoryId != null && channel.categoryId in hiddenLiveCategoryIds && channel.categoryId !in requiredHiddenLiveCategoryIds) return@streamLiveStreamsif (channel.categoryId != null) bulkRowsWithResolvedCategories++batch += channelif (batch.size >= FALLBACK_STAGE_BATCH_SIZE) {@@ -532,7 +543,7 @@ internal class StalkerCatalogSyncExecutor()warnings += fallbackResult.warningsfallbackResult.channels.forEach { channel ->- if (channel.categoryId != null && channel.categoryId in hiddenLiveCategoryIds) return@forEach+ if (channel.categoryId != null && channel.categoryId in hiddenLiveCategoryIds && channel.categoryId !in requiredHiddenLiveCategoryIds) return@forEachbatch += channelif (batch.size >= FALLBACK_STAGE_BATCH_SIZE) flushBatch()}diff --git a/data/src/main/java/com/streamvault/data/sync/SyncCatalogStore.kt b/data/src/main/java/com/streamvault/data/sync/SyncCatalogStore.ktindex ae15df01..f25a3eb8 100644--- a/data/src/main/java/com/streamvault/data/sync/SyncCatalogStore.kt+++ b/data/src/main/java/com/streamvault/data/sync/SyncCatalogStore.kt@@ -159,10 +159,10 @@ internal class SyncCatalogStore() {try {providerTransaction(providerId) {- categories?.let { stageCategories(providerId, sessionId, it) }- categories?.let { applyCategories(providerId, sessionId, "LIVE") }- applyChannels(providerId, sessionId)- catalogSyncDao.rebuildChannelFts()+ categories?.let { timed(providerId, "category-staging") { stageCategories(providerId, sessionId, it) } }+ categories?.let { timed(providerId, "category-commit") { applyCategories(providerId, sessionId, "LIVE") } }+ timed(providerId, "channel-insert-update-delete") { applyChannels(providerId, sessionId) }+ timed(providerId, "channel-fts-rebuild") { catalogSyncDao.rebuildChannelFts() }afterCatalogApply()}} finally {@@ -368,14 +368,25 @@ internal class SyncCatalogStore(}suspend fun stageChannelBatch(providerId: Long, sessionId: Long, channels: List<ChannelEntity>) {- providerTransaction(providerId) {- requireStageCapacity(- currentCount = catalogSyncDao.countChannelStages(providerId, sessionId),- incomingCount = channels.distinctBy { it.streamId }.size,- maximum = sizeLimits.maxChannelsPerProvider,- label = "channel"- )- insertStageRows(buildChannelStages(providerId, sessionId, channels), catalogSyncDao::insertChannelStages)+ timed(providerId, "channel-staging-batch(${channels.size})") {+ providerTransaction(providerId) {+ requireStageCapacity(+ currentCount = catalogSyncDao.countChannelStages(providerId, sessionId),+ incomingCount = channels.distinctBy { it.streamId }.size,+ maximum = sizeLimits.maxChannelsPerProvider,+ label = "channel"+ )+ insertStageRows(buildChannelStages(providerId, sessionId, channels), catalogSyncDao::insertChannelStages)+ }+ }+ }++ private suspend fun <T> timed(providerId: Long, stage: String, block: suspend () -> T): T {+ val startedAt = System.currentTimeMillis()+ return try {+ block()+ } finally {+ Log.i(TAG, "catalog timing provider=$providerId stage=$stage took=${System.currentTimeMillis() - startedAt}ms")}}diff --git a/data/src/main/java/com/streamvault/data/sync/SyncManager.kt b/data/src/main/java/com/streamvault/data/sync/SyncManager.ktindex 9a8ad188..f289bce6 100644--- a/data/src/main/java/com/streamvault/data/sync/SyncManager.kt+++ b/data/src/main/java/com/streamvault/data/sync/SyncManager.kt@@ -30,6 +30,7 @@ import com.streamvault.data.local.entity.VodCategoryHydrationEntityimport com.streamvault.data.local.entity.XtreamContentIndexEntityimport com.streamvault.data.local.entity.XtreamLiveOnboardingStateEntityimport com.streamvault.data.mapper.toDomain+import com.streamvault.data.manager.PendingBackupRestoreCoordinatorimport com.streamvault.data.mapper.toEntityimport com.streamvault.data.parser.M3uParserimport com.streamvault.data.remote.http.buildAppRequestProfile@@ -219,7 +220,8 @@ class SyncManager @Inject constructor(private val stalkerPlaybackCapabilityCache: StalkerPlaybackCapabilityCache,private val providerSyncWorkScheduler: ProviderSyncWorkScheduler,private val m3uClassificationDao: M3uClassificationDao? = null,- private val m3uClassificationRepository: M3uClassificationRepository? = null+ private val m3uClassificationRepository: M3uClassificationRepository? = null,+ private val pendingBackupRestoreCoordinator: PendingBackupRestoreCoordinator? = null) : ProviderSyncCommands, CatalogHydrationCommands, ProviderSyncStateSource, ProviderSyncLifecycle {private val syncProviderSnapshotAdapter = SyncProviderSnapshotAdapter(providerSnapshotRepository)private val syncStatusPublicationCoordinator = SyncStatusPublicationCoordinator(@@ -592,7 +594,10 @@ class SyncManager @Inject constructor(progress = ::progress,emitProgress = ::emitProviderProgress,sanitizeThrowableMessage = ::sanitizeThrowableMessage,- userMessage = { error, fallback -> syncErrorSanitizer.userMessage(error, fallback) }+ userMessage = { error, fallback -> syncErrorSanitizer.userMessage(error, fallback) },+ requiredHiddenCategoryIds = { providerId, type ->+ pendingBackupRestoreCoordinator?.requiredHiddenCategoryIds(providerId, type).orEmpty()+ })}private val stalkerSyncExecutor by lazy {@@ -623,7 +628,10 @@ class SyncManager @Inject constructor(emitCatalogSyncProgress(providerId, section, total ?: 0, itemsIndexed ?: 0)},categoryFailureWarning = ::categoryFailureWarning,- sanitizeThrowableMessage = ::sanitizeThrowableMessage+ sanitizeThrowableMessage = ::sanitizeThrowableMessage,+ requiredHiddenCategoryIds = { providerId, type ->+ pendingBackupRestoreCoordinator?.requiredHiddenCategoryIds(providerId, type).orEmpty()+ })}private val syncCoordinator: SyncCoordinator by lazy {@@ -671,29 +679,35 @@ class SyncManager @Inject constructor(providerId: Long,categoryId: Long,request: com.streamvault.domain.model.VodCategoryHydrationRequest- ): Result<Unit> = vodCategoryHydrationCoordinator.hydrateUnifiedVodCategory(providerId, categoryId, request)+ ): Result<Unit> = vodCategoryHydrationCoordinator+ .hydrateUnifiedVodCategory(providerId, categoryId, request)+ .alsoApplyPendingRestore(providerId)override suspend fun hydrateSplitVodCategory(providerId: Long,movieCategoryId: Long,request: com.streamvault.domain.model.VodCategoryHydrationRequest,requestedProjection: ContentType- ): Result<Unit> = vodCategoryHydrationCoordinator.hydrateSplitVodCategory(- providerId,- movieCategoryId,- request,- requestedProjection- )+ ): Result<Unit> = vodCategoryHydrationCoordinator+ .hydrateSplitVodCategory(providerId, movieCategoryId, request, requestedProjection)+ .alsoApplyPendingRestore(providerId)override suspend fun hydrateSplitVodSeriesCategory(providerId: Long,seriesCategoryId: Long,request: com.streamvault.domain.model.VodCategoryHydrationRequest- ): Result<Unit> = vodCategoryHydrationCoordinator.hydrateSplitVodSeriesCategory(- providerId,- seriesCategoryId,- request- )+ ): Result<Unit> = vodCategoryHydrationCoordinator+ .hydrateSplitVodSeriesCategory(providerId, seriesCategoryId, request)+ .alsoApplyPendingRestore(providerId)++ private suspend fun Result<Unit>.alsoApplyPendingRestore(providerId: Long): Result<Unit> {+ if (this is Result.Success) {+ val startedAt = System.currentTimeMillis()+ pendingBackupRestoreCoordinator?.applyForProvider(providerId)+ Log.i(TAG, "backup restore resolution provider=$providerId took=${System.currentTimeMillis() - startedAt}ms")+ }+ return this+ }private val xtreamCatalogHttpService: OkHttpXtreamApiService by lazy {OkHttpXtreamApiService(@@ -1160,6 +1174,10 @@ class SyncManager @Inject constructor(status = if (outcome.requiresPartialActivation) "PARTIAL" else "SUCCESS")}+ val restoreStartedAt = System.currentTimeMillis()+ progress(providerId, onProgress, "Restoring backup choices...")+ pendingBackupRestoreCoordinator?.applyForProvider(providerId)+ Log.i(TAG, "backup restore resolution provider=$providerId took=${System.currentTimeMillis() - restoreStartedAt}ms")publishSyncState(providerId, if (outcome.requiresPartialActivation) {SyncState.Partial("Sync completed with warnings", outcome.warnings)} else {@@ -1338,6 +1356,8 @@ class SyncManager @Inject constructor(providerId = providerId,status = if (outcome.requiresPartialActivation) "PARTIAL" else "SUCCESS")+ progress(providerId, onProgress, "Restoring backup choices...")+ pendingBackupRestoreCoordinator?.applyForProvider(providerId)publishSyncState(providerId,if (outcome.requiresPartialActivation) {@@ -1431,7 +1451,7 @@ class SyncManager @Inject constructor(}}- if (warnings.isNotEmpty()) {+ val result = if (warnings.isNotEmpty()) {val message = warnings.joinToString("; ")val cause = failures.firstOrNull()val exception = if (sawRetryableFailure) IOException(message, cause) else IllegalStateException(message, cause)@@ -1439,6 +1459,7 @@ class SyncManager @Inject constructor(} else {com.streamvault.domain.model.Result.success(Unit)}+ result.alsoApplyPendingRestore(providerId)}override fun cancelStalkerIndexSync(providerId: Long) {@@ -1532,7 +1553,7 @@ class SyncManager @Inject constructor(warnings += "${contentType.name.lowercase().replaceFirstChar { it.titlecase() }} indexing failed: ${sanitizeThrowableMessage(failure)}"}- if (warnings.isNotEmpty()) {+ val result = if (warnings.isNotEmpty()) {val message = warnings.joinToString("; ")val cause = failures.firstOrNull()val exception = if (sawRetryableFailure) IOException(message, cause) else IllegalStateException(message, cause)@@ -1542,6 +1563,7 @@ class SyncManager @Inject constructor(stalkerIndexContinuationCoordinator.scheduleEpgIfCatalogIdle(provider)com.streamvault.domain.model.Result.success(Unit)}+ result.alsoApplyPendingRestore(providerId)}}@@ -1706,7 +1728,12 @@ class SyncManager @Inject constructor(categories: List<CategoryEntity>): List<CategoryEntity> {val hiddenCategoryIds = preferencesRepository.getHiddenCategoryIds(providerId, contentType).first()- return categories.filterNot { category -> category.categoryId in hiddenCategoryIds }+ val requiredHiddenIds = pendingBackupRestoreCoordinator+ ?.requiredHiddenCategoryIds(providerId, contentType)+ .orEmpty()+ return categories.filterNot { category ->+ category.categoryId in hiddenCategoryIds && category.categoryId !in requiredHiddenIds+ }}private suspend fun visibleStalkerIndexCategories(diff --git a/data/src/main/java/com/streamvault/data/sync/SyncManagerXtreamLiveStrategy.kt b/data/src/main/java/com/streamvault/data/sync/SyncManagerXtreamLiveStrategy.ktindex de6db57d..aadf88a1 100644--- a/data/src/main/java/com/streamvault/data/sync/SyncManagerXtreamLiveStrategy.kt+++ b/data/src/main/java/com/streamvault/data/sync/SyncManagerXtreamLiveStrategy.kt@@ -53,7 +53,8 @@ internal class SyncManagerXtreamLiveStrategy(onProgress: ((String) -> Unit)?,runtimeProfile: CatalogSyncRuntimeProfile,trackInitialLiveOnboarding: Boolean,- effectiveLiveSyncMethod: EffectiveXtreamLiveSyncMethod = EffectiveXtreamLiveSyncMethod.STREAM_ALL+ effectiveLiveSyncMethod: EffectiveXtreamLiveSyncMethod = EffectiveXtreamLiveSyncMethod.STREAM_ALL,+ requiredHiddenLiveCategoryIds: Set<Long> = emptySet()): CatalogSyncPayload<Channel> {Log.i(XTREAM_LIVE_STRATEGY_TAG, "Xtream live strategy start for provider ${provider.id}.")val rawLiveCategories = when (val attempt = xtreamSupport.attemptNonCancellation {@@ -84,7 +85,8 @@ internal class SyncManagerXtreamLiveStrategy(?.map { category -> category.toEntity(provider.id) }?.takeIf { it.isNotEmpty() }val filteredRawLiveCategories = rawLiveCategories.orEmpty().filterNot { category ->- category.categoryId.toLongOrNull() in hiddenLiveCategoryIds+ val id = category.categoryId.toLongOrNull()+ id in hiddenLiveCategoryIds && id !in requiredHiddenLiveCategoryIds}// Hidden categories still need a catalog shell after a provider is restored. The// channel fetch intentionally skips them, but filtering them out of the categorydiff --git a/data/src/main/java/com/streamvault/data/sync/XtreamCatalogSyncExecutor.kt b/data/src/main/java/com/streamvault/data/sync/XtreamCatalogSyncExecutor.ktindex d3ad1e5d..4c8f8d28 100644--- a/data/src/main/java/com/streamvault/data/sync/XtreamCatalogSyncExecutor.kt+++ b/data/src/main/java/com/streamvault/data/sync/XtreamCatalogSyncExecutor.kt@@ -63,7 +63,8 @@ internal class XtreamCatalogSyncExecutor(private val progress: (Long, ((String) -> Unit)?, String) -> Unit,private val emitProgress: (Long, SyncProgress) -> Unit,private val sanitizeThrowableMessage: (Throwable?) -> String,- private val userMessage: (Throwable, String) -> String+ private val userMessage: (Throwable, String) -> String,+ private val requiredHiddenCategoryIds: suspend (Long, ContentType) -> Set<Long> = { _, _ -> emptySet() }) {suspend fun syncFull(provider: Provider,@@ -86,6 +87,7 @@ internal class XtreamCatalogSyncExecutor(val useTextClassification = preferencesRepository.useXtreamTextClassification.first()val enableBase64TextCompatibility = preferencesRepository.xtreamBase64TextCompatibility.first()val hiddenLiveCategoryIds = preferencesRepository.getHiddenCategoryIds(provider.id, ContentType.LIVE).first()+ val requiredHiddenLiveCategoryIds = requiredHiddenCategoryIds(provider.id, ContentType.LIVE)val api = createProvider(provider, useTextClassification, enableBase64TextCompatibility)val runtimeProfile = CatalogSyncRuntimeProfile.from(applicationContext)val now = System.currentTimeMillis()@@ -157,6 +159,7 @@ internal class XtreamCatalogSyncExecutor(api = api,existingMetadata = metadata,hiddenLiveCategoryIds = hiddenLiveCategoryIds,+ requiredHiddenLiveCategoryIds = requiredHiddenLiveCategoryIds,onProgress = onProgress,runtimeProfile = runtimeProfile,trackInitialLiveOnboarding = trackInitialLiveOnboarding,@@ -472,6 +475,7 @@ internal class XtreamCatalogSyncExecutor(val useTextClassification = preferencesRepository.useXtreamTextClassification.first()val enableBase64TextCompatibility = preferencesRepository.xtreamBase64TextCompatibility.first()val hiddenLiveCategoryIds = preferencesRepository.getHiddenCategoryIds(provider.id, ContentType.LIVE).first()+ val requiredHiddenLiveCategoryIds = requiredHiddenCategoryIds(provider.id, ContentType.LIVE)val api = createProvider(provider, useTextClassification, enableBase64TextCompatibility)val currentMetadata = syncMetadataRepository.getMetadata(provider.id) ?: SyncMetadata(provider.id)val runtimeProfile = CatalogSyncRuntimeProfile.from(applicationContext)@@ -481,6 +485,7 @@ internal class XtreamCatalogSyncExecutor(api,currentMetadata,hiddenLiveCategoryIds,+ requiredHiddenLiveCategoryIds,onProgress,runtimeProfile,trackInitialLiveOnboarding = false,@@ -602,6 +607,7 @@ internal class XtreamCatalogSyncExecutor(api: XtreamProvider,existingMetadata: SyncMetadata,hiddenLiveCategoryIds: Set<Long>,+ requiredHiddenLiveCategoryIds: Set<Long>,onProgress: ((String) -> Unit)?,runtimeProfile: CatalogSyncRuntimeProfile,trackInitialLiveOnboarding: Boolean,@@ -632,7 +638,8 @@ internal class XtreamCatalogSyncExecutor(onProgress,runtimeProfile,trackInitialLiveOnboarding,- effectiveMethod+ effectiveMethod,+ requiredHiddenLiveCategoryIds)}diff --git a/data/src/test/java/com/streamvault/data/manager/BackupManagerImplTest.kt b/data/src/test/java/com/streamvault/data/manager/BackupManagerImplTest.ktindex 8ce3f382..e6f06935 100644--- a/data/src/test/java/com/streamvault/data/manager/BackupManagerImplTest.kt+++ b/data/src/test/java/com/streamvault/data/manager/BackupManagerImplTest.kt@@ -14,6 +14,7 @@ import com.streamvault.data.local.dao.PlaybackHistoryDaoimport com.streamvault.data.local.dao.ProviderDaoimport com.streamvault.data.local.dao.ProviderSnapshotDaoimport com.streamvault.data.local.dao.BackupRestoreCheckpointDao+import com.streamvault.data.local.dao.BackupRestoreLedgerDaoimport com.streamvault.data.local.dao.ChannelDaoimport com.streamvault.data.local.dao.CategoryDaoimport com.streamvault.data.local.dao.RecordingScheduleDao@@ -44,6 +45,12 @@ import com.streamvault.domain.manager.BackupProviderReferenceimport com.streamvault.domain.manager.PortableCategoryReferenceimport com.streamvault.domain.manager.PortableCategorySortReferenceimport com.streamvault.domain.manager.PortableChannelReference+import com.streamvault.domain.manager.PortableContentReference+import com.streamvault.domain.manager.PortableFavoriteBackup+import com.streamvault.domain.manager.PortableCustomGroupBackup+import com.streamvault.domain.manager.PortablePlaybackHistoryBackup+import com.streamvault.domain.manager.PortableProtectedContentBackup+import com.streamvault.domain.manager.PortableSearchHistoryBackupimport com.streamvault.domain.manager.PortableEpgTimeShiftReferenceimport com.streamvault.domain.manager.PortableProviderPreferencesBackupimport com.streamvault.domain.manager.PortableVariantSelectionReference@@ -106,6 +113,146 @@ import org.mockito.kotlin.wheneverclass BackupManagerImplTest {+ @Test+ fun `v14 import durably queues catalog state that is unavailable before sync`() = runBlocking {+ val context: Context = mock()+ val resolver: ContentResolver = mock()+ val ledgerDao: BackupRestoreLedgerDao = mock()+ val providerDao: ProviderDao = mock()+ val provider = BackupProviderReference(+ serverUrl = "https://example.com/",+ username = "user",+ providerType = ProviderType.XTREAM_CODES+ )+ val content = PortableContentReference(+ provider = provider,+ contentType = ContentType.LIVE,+ remoteContentId = "42",+ name = "News"+ )+ val backup = BackupData(+ version = 14,+ portableFavorites = listOf(PortableFavoriteBackup(content, position = 3))+ )+ whenever(context.contentResolver).thenReturn(resolver)+ whenever(resolver.openInputStream(anyOrNull())).thenReturn(+ ByteArrayInputStream(Gson().toJson(backup).toByteArray())+ )+ whenever(providerDao.getAllSync()).thenReturn(emptyList())++ val result = backupManagerForValidation(+ context = context,+ providerDao = providerDao,+ restoreLedgerDao = ledgerDao+ ).importConfig(+ "content://v14-pending",+ BackupImportPlan(+ importPreferences = false,+ importProviders = false,+ importSavedLibrary = true,+ importPlaybackHistory = false,+ importMultiViewPresets = false,+ importRecordingSchedules = false+ )+ )++ assertThat(result).isInstanceOf(Result.Success::class.java)+ assertThat(result).isInstanceOf(Result.Success::class.java)+ val imported = (result as Result.Success).data+ assertThat(imported.outcome).isEqualTo(BackupRestoreOutcome.WAITING_FOR_SYNC)+ assertThat(imported.restoreJobId).isNotEmpty()+ assertThat(imported.pendingCount).isEqualTo(1)+ assertThat(imported.affectedProviders).containsExactly(provider)+ verify(ledgerDao).insertLedger(+ argThat { backupVersion == 14 && id == imported.restoreJobId },+ argThat { items ->+ items.single().section == "FAVORITES" &&+ items.single().stableReferenceKey.contains("LIVE:42") &&+ items.single().payloadJson.contains("\"position\":3")+ }+ )+ }++ @Test+ fun `v14 parser preserves portable content state without local database ids`() = runBlocking {+ val context: Context = mock()+ val contentResolver: ContentResolver = mock()+ val provider = BackupProviderReference(+ serverUrl = "https://example.com/",+ username = "user",+ providerType = ProviderType.XTREAM_CODES+ )+ val channel = PortableContentReference(+ provider = provider,+ contentType = ContentType.LIVE,+ remoteContentId = "42",+ remoteCategoryId = "7",+ name = "News",+ urlFallback = "https://example.com/live/user/pass/42.ts"+ )+ val episode = PortableContentReference(+ provider = provider,+ contentType = ContentType.SERIES_EPISODE,+ remoteContentId = "episode-9",+ parentRemoteContentId = "series-3",+ name = "Pilot"+ )+ val backup = BackupData(+ version = 14,+ portableFavorites = listOf(PortableFavoriteBackup(channel, position = 2)),+ portableCustomGroups = listOf(+ PortableCustomGroupBackup(+ provider = provider,+ contentType = ContentType.LIVE,+ name = "Family",+ icon = "★",+ position = 1,+ members = listOf(PortableFavoriteBackup(channel, position = 0))+ )+ ),+ portablePlaybackHistory = listOf(+ PortablePlaybackHistoryBackup(+ content = episode,+ resumePositionMs = 12_000,+ totalDurationMs = 60_000,+ lastWatchedAt = 1234,+ watchCount = 2,+ watchedStatus = "IN_PROGRESS"+ )+ ),+ portableProtectedContent = listOf(PortableProtectedContentBackup(channel)),+ portableSearchHistory = listOf(+ PortableSearchHistoryBackup(+ query = "news",+ contentScope = "LIVE",+ provider = provider,+ usedAt = 5678,+ useCount = 3+ )+ )+ )+ whenever(context.contentResolver).thenReturn(contentResolver)+ whenever(contentResolver.openInputStream(anyOrNull())).thenReturn(+ ByteArrayInputStream(Gson().toJson(backup).toByteArray())+ )++ val manager = backupManagerForValidation(context)+ val readMethod = BackupManagerImpl::class.java+ .getDeclaredMethod("readBackupData", String::class.java)+ .apply { isAccessible = true }+ val parsed = readMethod.invoke(manager, "content://v14-portable-state")+ val dataField = parsed!!::class.java.getDeclaredField("data").apply { isAccessible = true }+ val parsedData = dataField.get(parsed) as BackupData++ assertThat(parsedData.version).isEqualTo(14)+ assertThat(parsedData.portableFavorites?.single()?.content).isEqualTo(channel)+ assertThat(parsedData.portableCustomGroups?.single()?.members?.single()?.position).isEqualTo(0)+ assertThat(parsedData.portablePlaybackHistory?.single()?.content?.parentRemoteContentId)+ .isEqualTo("series-3")+ assertThat(parsedData.portableProtectedContent?.single()?.content?.remoteContentId).isEqualTo("42")+ assertThat(parsedData.portableSearchHistory?.single()?.useCount).isEqualTo(3)+ }+@Testfun `import creates protected category placeholder when provider catalog was deleted`() = runBlocking {val context: Context = mock()@@ -464,7 +611,7 @@ class BackupManagerImplTest {fun `inspectBackup rejects unsupported version before reading sections`() = runBlocking {val error = inspectAdmissionFailure("unsupported-version",- """{"version":14,"preferences":{"value":"${"x".repeat(8_193)}"}}"""+ """{"version":15,"preferences":{"value":"${"x".repeat(8_193)}"}}""")assertThat(error.reason).isEqualTo(BackupAdmissionReason.UNSUPPORTED_VERSION)@@ -736,6 +883,9 @@ class BackupManagerImplTest {)))+ whenever(movieDao.getById(55L)).thenReturn(+ MovieEntity(id = 55L, streamId = 5500L, name = "Movie", providerId = 7L)+ )val manager = BackupManagerImpl(context = context,@@ -842,6 +992,12 @@ class BackupManagerImplTest {)))+ whenever(movieDao.getById(88L)).thenReturn(+ MovieEntity(id = 88L, streamId = 8800L, name = "Favorite", providerId = 7L)+ )+ whenever(movieDao.getById(55L)).thenReturn(+ MovieEntity(id = 55L, streamId = 5500L, name = "Movie", providerId = 7L)+ )whenever(favoriteDao.get(any(), any(), any(), any())).thenReturn(null)doAnswer {assertThat(transactionRunner.isInTransaction).isTrue()@@ -1363,6 +1519,7 @@ class BackupManagerImplTest {val providerDao: ProviderDao = mock()val favoriteDao: FavoriteDao = mock()+ val movieDao: MovieDao = mock()val preferencesRepository: PreferencesRepository = mock()val gson = Gson()val backupProvider = Provider(@@ -1400,6 +1557,9 @@ class BackupManagerImplTest {)))+ whenever(movieDao.getById(88L)).thenReturn(+ MovieEntity(id = 88L, streamId = 8800L, name = "Favorite", providerId = 7L)+ )whenever(favoriteDao.get(any(), any(), any(), any())).thenReturn(null)whenever(favoriteDao.insert(any())).thenThrow(IllegalStateException("favorite insert failed"))@@ -1411,7 +1571,7 @@ class BackupManagerImplTest {favoriteDao = favoriteDao,virtualGroupDao = mock<VirtualGroupDao>(),playbackHistoryDao = mock<PlaybackHistoryDao>(),- movieDao = mock<MovieDao>(),+ movieDao = movieDao,episodeDao = mock<EpisodeDao>(),categoryRepository = mock<CategoryRepository>(),recordingScheduleDao = mock<RecordingScheduleDao>(),@@ -2296,6 +2456,7 @@ class BackupManagerImplTest {))+ assertThat(result).isInstanceOf(Result.Success::class.java)val imported = (result as Result.Success).dataassertThat(imported.outcome).isEqualTo(BackupRestoreOutcome.COMPLETE)assertThat(imported.unresolvedReferences).isEmpty()@@ -2684,6 +2845,7 @@ class BackupManagerImplTest {))+ assertThat(result).isInstanceOf(Result.Success::class.java)assertThat((result as Result.Success).data.outcome).isEqualTo(BackupRestoreOutcome.COMPLETE)verify(preferencesRepository).setHiddenChannelIds(targetProvider.id, emptySet())@@ -3496,6 +3658,7 @@ class BackupManagerImplTest {providerDao: ProviderDao = mock(),favoriteDao: FavoriteDao = mock(),checkpointDao: BackupRestoreCheckpointDao? = null,+ restoreLedgerDao: BackupRestoreLedgerDao? = null,channelDao: ChannelDao = mock(),movieDao: MovieDao = mock(),categoryRepository: CategoryRepository = mock(),@@ -3543,6 +3706,7 @@ class BackupManagerImplTest {providerSnapshotDao = acceptingSnapshotDao(),providerConfigurationCodec = ProviderConfigurationCodec(Gson(), credentialCrypto),backupRestoreCheckpointDao = checkpointDao,+ backupRestoreLedgerDao = restoreLedgerDao,channelDao = channelDao,seriesDao = mock(),epgSourceDao = epgSourceDaodiff --git a/data/src/test/java/com/streamvault/data/manager/PendingBackupRestoreCoordinatorTest.kt b/data/src/test/java/com/streamvault/data/manager/PendingBackupRestoreCoordinatorTest.ktnew file mode 100644index 00000000..1b95081a--- /dev/null+++ b/data/src/test/java/com/streamvault/data/manager/PendingBackupRestoreCoordinatorTest.kt@@ -0,0 +1,435 @@+package com.streamvault.data.manager++import com.google.common.truth.Truth.assertThat+import com.google.gson.Gson+import com.streamvault.data.local.dao.BackupRestoreLedgerDao+import com.streamvault.data.local.dao.ChannelDao+import com.streamvault.data.local.dao.ChannelPreferenceDao+import com.streamvault.data.local.dao.ChannelEpgMappingDao+import com.streamvault.data.local.dao.EpgSourceDao+import com.streamvault.data.local.dao.EpisodeDao+import com.streamvault.data.local.dao.FavoriteDao+import com.streamvault.data.local.dao.MovieDao+import com.streamvault.data.local.dao.PlaybackHistoryDao+import com.streamvault.data.local.dao.ProviderDao+import com.streamvault.data.local.dao.SearchHistoryDao+import com.streamvault.data.local.dao.SeriesDao+import com.streamvault.data.local.dao.VirtualGroupDao+import com.streamvault.data.local.entity.BackupRestoreItemEntity+import com.streamvault.data.local.entity.ChannelEntity+import com.streamvault.data.local.entity.FavoriteEntity+import com.streamvault.data.local.entity.ProviderEntity+import com.streamvault.data.provider.toProviderSnapshot+import com.streamvault.domain.manager.BackupProviderReference+import com.streamvault.domain.manager.PortableContentReference+import com.streamvault.domain.manager.PortableCustomGroupBackup+import com.streamvault.domain.manager.PortableFavoriteBackup+import com.streamvault.domain.manager.PortableMultiViewPresetV14Backup+import com.streamvault.domain.model.ContentType+import com.streamvault.domain.model.ProviderType+import com.streamvault.domain.model.LegacyProvider+import com.streamvault.data.preferences.PreferencesRepository+import com.streamvault.domain.repository.ProviderSnapshotRepository+import com.streamvault.domain.manager.RecordingManager+import kotlinx.coroutines.runBlocking+import kotlinx.coroutines.CancellationException+import kotlinx.coroutines.flow.flowOf+import org.junit.Test+import org.mockito.kotlin.any+import org.mockito.kotlin.argThat+import org.mockito.kotlin.eq+import org.mockito.kotlin.mock+import org.mockito.kotlin.isNull+import org.mockito.kotlin.verify+import org.mockito.kotlin.inOrder+import org.mockito.kotlin.atLeastOnce+import org.mockito.kotlin.whenever+import org.mockito.kotlin.never++class PendingBackupRestoreCoordinatorTest {+ @Test+ fun `cancellation leaves restore instruction retryable`() = runBlocking {+ val ledger: BackupRestoreLedgerDao = mock()+ val providerDao: ProviderDao = mock()+ val channelDao: ChannelDao = mock()+ val gson = Gson()+ val reference = PortableContentReference(+ BackupProviderReference("https://example.com", "user", providerType = ProviderType.XTREAM_CODES),+ ContentType.LIVE,+ "42"+ )+ val item = BackupRestoreItemEntity(+ id = 10,+ jobId = "job",+ providerIdentityKey = "provider",+ localProviderId = 77,+ section = "FAVORITES",+ contentType = "LIVE",+ stableReferenceKey = "LIVE:42",+ referenceJson = gson.toJson(reference),+ payloadJson = gson.toJson(PortableFavoriteBackup(reference)),+ createdAt = 1,+ updatedAt = 1+ )+ whenever(providerDao.getById(77)).thenReturn(+ ProviderEntity(id = 77, name = "Provider", type = ProviderType.XTREAM_CODES)+ )+ whenever(ledger.getRetryableItemsByLocalProviderId(77)).thenReturn(listOf(item))+ whenever(channelDao.getByStreamId(77, 42)).thenThrow(CancellationException("cancelled"))++ var cancelled = false+ try {+ coordinator(ledger, providerDao, mock(), channelDao, gson).applyForProvider(77)+ } catch (_: CancellationException) {+ cancelled = true+ }++ assertThat(cancelled).isTrue()+ verify(ledger, never()).updateItemStatus(any(), any(), any(), any(), any(), any())+ }++ @Test+ fun `replace scope clears existing favorites only after every backup reference resolves`() = runBlocking {+ val ledger: BackupRestoreLedgerDao = mock()+ val providerDao: ProviderDao = mock()+ val favoriteDao: FavoriteDao = mock()+ val channelDao: ChannelDao = mock()+ val gson = Gson()+ val provider = ProviderEntity(id = 77, name = "Provider", type = ProviderType.XTREAM_CODES)+ val reference = PortableContentReference(+ provider = BackupProviderReference("https://example.com", "user", providerType = ProviderType.XTREAM_CODES),+ contentType = ContentType.LIVE,+ remoteContentId = "42"+ )+ val marker = BackupRestoreItemEntity(+ id = 1, jobId = "job", providerIdentityKey = "provider", localProviderId = 77,+ section = "REPLACE_SCOPE", contentType = "LIVE", stableReferenceKey = "scope:FAVORITES:LIVE",+ referenceJson = "{}",+ payloadJson = """{"provider":null,"targetSection":"FAVORITES","contentType":"LIVE"}""",+ createdAt = 1, updatedAt = 1+ )+ val favorite = BackupRestoreItemEntity(+ id = 2, jobId = "job", providerIdentityKey = "provider", localProviderId = 77,+ section = "FAVORITES", contentType = "LIVE", stableReferenceKey = "LIVE:42",+ referenceJson = gson.toJson(reference), payloadJson = gson.toJson(PortableFavoriteBackup(reference)),+ createdAt = 1, updatedAt = 1+ )+ val otherProviderFavorite = favorite.copy(+ id = 3,+ providerIdentityKey = "other-provider",+ stableReferenceKey = "LIVE:99",+ referenceJson = gson.toJson(reference.copy(remoteContentId = "99")),+ payloadJson = gson.toJson(PortableFavoriteBackup(reference.copy(remoteContentId = "99")))+ )+ whenever(providerDao.getById(77)).thenReturn(provider)+ whenever(ledger.getRetryableItemsByLocalProviderId(77)).thenReturn(listOf(marker, favorite))+ whenever(ledger.getRetryableItems("__GLOBAL__")).thenReturn(emptyList())+ whenever(ledger.getItems("job")).thenReturn(listOf(marker, favorite, otherProviderFavorite))+ whenever(channelDao.getByStreamId(77, 42)).thenReturn(ChannelEntity(id = 900, streamId = 42, name = "News", providerId = 77))+ whenever(favoriteDao.get(77, 900, "LIVE", null)).thenReturn(null)++ coordinator(ledger, providerDao, favoriteDao, channelDao, gson).applyForProvider(77)++ inOrder(favoriteDao) {+ verify(favoriteDao).deleteGlobalByProviderAndType(77, "LIVE")+ verify(favoriteDao, atLeastOnce()).insert(any())+ }+ }++ @Test+ fun `provider pass rebinds pending items when local provider id changes again`() = runBlocking {+ val ledger: BackupRestoreLedgerDao = mock()+ val providerDao: ProviderDao = mock()+ val channelDao: ChannelDao = mock()+ val favoriteDao: FavoriteDao = mock()+ val snapshots: ProviderSnapshotRepository = mock()+ val gson = Gson()+ val provider = LegacyProvider(+ id = 88,+ name = "Recreated",+ type = ProviderType.XTREAM_CODES,+ serverUrl = "https://example.com",+ username = "user"+ )+ val reference = PortableContentReference(+ provider = BackupProviderReference(+ serverUrl = "https://example.com",+ username = "user",+ providerType = ProviderType.XTREAM_CODES+ ),+ contentType = ContentType.LIVE,+ remoteContentId = "42"+ )+ val item = BackupRestoreItemEntity(+ id = 7,+ jobId = "job",+ providerIdentityKey = "https://example.com|user|XTREAM_CODES|",+ localProviderId = 77,+ section = "FAVORITES",+ contentType = "LIVE",+ stableReferenceKey = "LIVE:42",+ referenceJson = gson.toJson(reference),+ payloadJson = gson.toJson(PortableFavoriteBackup(reference)),+ createdAt = 1,+ updatedAt = 1+ )+ whenever(providerDao.getById(88)).thenReturn(provider.copy().let {+ ProviderEntity(id = it.id, name = it.name, type = it.type, serverUrl = it.serverUrl, username = it.username)+ })+ whenever(snapshots.getSnapshot(88)).thenReturn(provider.toProviderSnapshot())+ whenever(ledger.getRetryableItemsByLocalProviderId(88)).thenReturn(emptyList())+ whenever(ledger.getRetryableItems(item.providerIdentityKey)).thenReturn(listOf(item))+ whenever(channelDao.getByStreamId(88, 42)).thenReturn(+ ChannelEntity(id = 901, streamId = 42, name = "News", providerId = 88)+ )+ whenever(favoriteDao.get(88, 901, "LIVE", null)).thenReturn(null)++ val coordinator = PendingBackupRestoreCoordinator(+ ledger, providerDao, favoriteDao, mock(), mock(), channelDao, mock(), mock(), mock(),+ mock(), mock(), mock(), mock(), mock(), snapshots, mock(), gson+ )++ assertThat(coordinator.applyForProvider(88).appliedCount).isEqualTo(1)+ verify(ledger).updateItemStatus(eq(7), eq(BackupRestoreItemEntity.STATUS_APPLIED), eq(88), eq(1), isNull(), any())+ }++ @Test+ fun `hidden category fetch requirements include only categories referenced by pending restore items`() = runBlocking {+ val ledger: BackupRestoreLedgerDao = mock()+ val preferences: PreferencesRepository = mock()+ val gson = Gson()+ val reference = PortableContentReference(+ provider = BackupProviderReference("https://example.com", "user", providerType = ProviderType.XTREAM_CODES),+ contentType = ContentType.LIVE,+ remoteContentId = "42",+ remoteCategoryId = "9",+ name = "News"+ )+ whenever(preferences.getHiddenCategoryIds(77, ContentType.LIVE)).thenReturn(flowOf(setOf(9, 10)))+ whenever(ledger.getRetryableItemsByLocalProviderId(77)).thenReturn(+ listOf(+ BackupRestoreItemEntity(+ id = 1,+ jobId = "job",+ providerIdentityKey = "provider",+ localProviderId = 77,+ section = "FAVORITES",+ contentType = "LIVE",+ stableReferenceKey = "LIVE:42",+ referenceJson = gson.toJson(reference),+ payloadJson = gson.toJson(PortableFavoriteBackup(reference)),+ createdAt = 1,+ updatedAt = 1+ )+ )+ )+ whenever(ledger.getRetryableItems("__GLOBAL__")).thenReturn(emptyList())++ val coordinator = PendingBackupRestoreCoordinator(+ ledgerDao = ledger,+ providerDao = mock(),+ favoriteDao = mock(),+ virtualGroupDao = mock(),+ playbackHistoryDao = mock(),+ channelDao = mock(),+ movieDao = mock(),+ seriesDao = mock(),+ episodeDao = mock(),+ searchHistoryDao = mock(),+ channelPreferenceDao = mock(),+ channelEpgMappingDao = mock(),+ epgSourceDao = mock(),+ preferencesRepository = preferences,+ providerSnapshotRepository = mock(),+ recordingManager = mock(),+ gson = gson+ )++ assertThat(coordinator.requiredHiddenCategoryIds(77, ContentType.LIVE)).containsExactly(9L)+ Unit+ }++ @Test+ fun `hidden category requirements inspect nested provider and global restore payloads`() = runBlocking {+ val ledger: BackupRestoreLedgerDao = mock()+ val providerDao: ProviderDao = mock()+ val preferences: PreferencesRepository = mock()+ val snapshots: ProviderSnapshotRepository = mock()+ val gson = Gson()+ val provider = LegacyProvider(+ id = 77,+ name = "Provider",+ type = ProviderType.XTREAM_CODES,+ serverUrl = "https://example.com",+ username = "user"+ )+ val providerReference = BackupProviderReference(+ provider.serverUrl,+ provider.username,+ providerType = provider.type+ )+ val groupMember = PortableContentReference(+ providerReference,+ ContentType.LIVE,+ remoteContentId = "42",+ remoteCategoryId = "9"+ )+ val multiviewChannel = groupMember.copy(remoteContentId = "43", remoteCategoryId = "10")+ val customGroup = PortableCustomGroupBackup(+ provider = providerReference,+ contentType = ContentType.LIVE,+ name = "News",+ members = listOf(PortableFavoriteBackup(groupMember))+ )+ val multiview = PortableMultiViewPresetV14Backup("preset_1", listOf(multiviewChannel))+ whenever(preferences.getHiddenCategoryIds(77, ContentType.LIVE)).thenReturn(flowOf(setOf(9, 10, 11)))+ whenever(ledger.getRetryableItemsByLocalProviderId(77)).thenReturn(+ listOf(restoreItem(1, "CUSTOM_GROUPS", gson.toJson(customGroup)))+ )+ whenever(ledger.getRetryableItems("__GLOBAL__")).thenReturn(+ listOf(restoreItem(2, "MULTIVIEW", gson.toJson(multiview), providerKey = "__GLOBAL__"))+ )+ whenever(ledger.getRetryableItems("https://example.com|user|XTREAM_CODES|"))+ .thenReturn(emptyList())+ whenever(providerDao.getAllSync()).thenReturn(+ listOf(ProviderEntity(id = 77, name = provider.name, type = provider.type))+ )+ whenever(snapshots.getSnapshot(77)).thenReturn(provider.toProviderSnapshot())++ val coordinator = PendingBackupRestoreCoordinator(+ ledger, providerDao, mock(), mock(), mock(), mock(), mock(), mock(), mock(), mock(),+ mock(), mock(), mock(), preferences, snapshots, mock(), gson+ )++ assertThat(coordinator.requiredHiddenCategoryIds(77, ContentType.LIVE))+ .containsExactly(9L, 10L)+ Unit+ }++ private fun restoreItem(+ id: Long,+ section: String,+ payloadJson: String,+ providerKey: String = "provider"+ ) = BackupRestoreItemEntity(+ id = id,+ jobId = "job",+ providerIdentityKey = providerKey,+ localProviderId = if (providerKey == "__GLOBAL__") null else 77,+ section = section,+ contentType = "LIVE",+ stableReferenceKey = "$section:$id",+ referenceJson = "{}",+ payloadJson = payloadJson,+ createdAt = 1,+ updatedAt = 1+ )++ @Test+ fun `provider pass resolves favorite by remote id after local ids changed`() = runBlocking {+ val ledger: BackupRestoreLedgerDao = mock()+ val providerDao: ProviderDao = mock()+ val channelDao: ChannelDao = mock()+ val favoriteDao: FavoriteDao = mock()+ val gson = Gson()+ val provider = ProviderEntity(+ id = 77,+ name = "Provider",+ type = ProviderType.XTREAM_CODES+ )+ val reference = PortableContentReference(+ provider = BackupProviderReference(+ serverUrl = "https://example.com/",+ username = "user",+ providerType = provider.type+ ),+ contentType = ContentType.LIVE,+ remoteContentId = "42",+ name = "News"+ )+ val payload = PortableFavoriteBackup(reference, position = 4, addedAt = 123)+ val item = BackupRestoreItemEntity(+ id = 5,+ jobId = "job",+ providerIdentityKey = "https://example.com|user|XTREAM_CODES|",+ section = "FAVORITES",+ contentType = "LIVE",+ stableReferenceKey = "provider|LIVE:42",+ referenceJson = gson.toJson(reference),+ payloadJson = gson.toJson(payload),+ createdAt = 1,+ updatedAt = 1+ )+ whenever(providerDao.getById(77)).thenReturn(provider)+ whenever(ledger.getRetryableItemsByLocalProviderId(77)).thenReturn(listOf(item))+ whenever(ledger.getRetryableItems("__GLOBAL__")).thenReturn(emptyList())+ whenever(channelDao.getByStreamId(77, 42)).thenReturn(+ ChannelEntity(id = 900, streamId = 42, name = "News", providerId = 77)+ )+ whenever(favoriteDao.get(77, 900, "LIVE", null)).thenReturn(null)++ val result = PendingBackupRestoreCoordinator(+ ledgerDao = ledger,+ providerDao = providerDao,+ favoriteDao = favoriteDao,+ virtualGroupDao = mock<VirtualGroupDao>(),+ playbackHistoryDao = mock<PlaybackHistoryDao>(),+ channelDao = channelDao,+ movieDao = mock<MovieDao>(),+ seriesDao = mock<SeriesDao>(),+ episodeDao = mock<EpisodeDao>(),+ searchHistoryDao = mock<SearchHistoryDao>(),+ channelPreferenceDao = mock<ChannelPreferenceDao>(),+ channelEpgMappingDao = mock<ChannelEpgMappingDao>(),+ epgSourceDao = mock<EpgSourceDao>(),+ preferencesRepository = mock<PreferencesRepository>(),+ providerSnapshotRepository = mock<ProviderSnapshotRepository>(),+ recordingManager = mock<RecordingManager>(),+ gson = gson+ ).applyForProvider(77)++ assertThat(result.appliedCount).isEqualTo(1)+ assertThat(result.unresolvedCount).isEqualTo(0)+ verify(favoriteDao).insert(+ argThat<FavoriteEntity> {+ providerId == 77L && contentId == 900L && contentType == ContentType.LIVE && position == 4+ }+ )+ verify(ledger).updateItemStatus(+ itemId = eq(5),+ status = eq(BackupRestoreItemEntity.STATUS_APPLIED),+ localProviderId = eq(77),+ attemptIncrement = eq(1),+ lastError = isNull(),+ updatedAt = any()+ )+ verify(ledger).refreshJobCounts(eq("job"), any())+ Unit+ }++ private fun coordinator(+ ledger: BackupRestoreLedgerDao,+ providerDao: ProviderDao,+ favoriteDao: FavoriteDao,+ channelDao: ChannelDao,+ gson: Gson+ ) = PendingBackupRestoreCoordinator(+ ledgerDao = ledger,+ providerDao = providerDao,+ favoriteDao = favoriteDao,+ virtualGroupDao = mock(),+ playbackHistoryDao = mock(),+ channelDao = channelDao,+ movieDao = mock(),+ seriesDao = mock(),+ episodeDao = mock(),+ searchHistoryDao = mock(),+ channelPreferenceDao = mock(),+ channelEpgMappingDao = mock(),+ epgSourceDao = mock(),+ preferencesRepository = mock(),+ providerSnapshotRepository = mock(),+ recordingManager = mock(),+ gson = gson+ )+}diff --git a/data/src/test/java/com/streamvault/data/manager/PreferenceBackupRegistryTest.kt b/data/src/test/java/com/streamvault/data/manager/PreferenceBackupRegistryTest.ktnew file mode 100644index 00000000..48493f78--- /dev/null+++ b/data/src/test/java/com/streamvault/data/manager/PreferenceBackupRegistryTest.kt@@ -0,0 +1,56 @@+package com.streamvault.data.manager++import com.google.common.truth.Truth.assertThat+import java.io.File+import org.junit.Test++class PreferenceBackupRegistryTest {+ @Test+ fun `every datastore preference has a classification and portable codec`() {+ val source = sequenceOf(+ File("src/main/java/com/streamvault/data/preferences/PreferencesRepository.kt"),+ File("data/src/main/java/com/streamvault/data/preferences/PreferencesRepository.kt")+ ).first { it.isFile }.readText()++ val literalKeys = Regex("(?:boolean|int|long|float|double|string)PreferencesKey\\(\"([^\"]+)\"\\)")+ .findAll(source)+ .map { it.groupValues[1] }+ .toSet()+ val dynamicSamples = setOf(+ "xtream_text_import_applied_generation_42",+ "last_live_category_id_42",+ "last_split_catalog_type_42",+ "remote_shortcut_live_red",+ "hidden_categories_42_LIVE",+ "hidden_channels_42",+ "pinned_categories_42_LIVE",+ "category_sort_42_LIVE",+ "aspect_ratio_123"+ )+ val allKeys = literalKeys + dynamicSamples+ val knownDynamicFactories = setOf(+ "xtreamTextImportAppliedGenerationKey(providerId",+ "remoteShortcutKey(profile, button",+ "hiddenCategoriesKey(providerId, type",+ "hiddenChannelsKey(providerId",+ "pinnedCategoriesKey(providerId, type",+ "categorySortModeKey(providerId, type"+ )+ val unknownDynamicFactories = Regex("(?:boolean|int|long|float|double|string)PreferencesKey\\(([^)\\r\\n]+)")+ .findAll(source)+ .map { it.groupValues[1].trim() }+ .filterNot { it.startsWith("\"") }+ .filterNot { it in knownDynamicFactories }+ .toSet()++ assertThat(unknownDynamicFactories).isEmpty()+ assertThat(allKeys.filter { PreferenceBackupRegistry.storageClassification(it) == null })+ .isEmpty()+ assertThat(allKeys.filter {+ PreferenceBackupRegistry.storageClassification(it) in setOf(+ PreferenceBackupClassification.PORTABLE_GLOBAL,+ PreferenceBackupClassification.PORTABLE_PROVIDER_CONTENT+ ) && PreferenceBackupRegistry.portableCodecForStorageKey(it) == null+ }).isEmpty()+ }+}diff --git a/data/src/test/java/com/streamvault/data/sync/SyncManagerXtreamLiveStrategyTest.kt b/data/src/test/java/com/streamvault/data/sync/SyncManagerXtreamLiveStrategyTest.ktindex 7ea928c7..c11e5d4b 100644--- a/data/src/test/java/com/streamvault/data/sync/SyncManagerXtreamLiveStrategyTest.kt+++ b/data/src/test/java/com/streamvault/data/sync/SyncManagerXtreamLiveStrategyTest.kt@@ -711,6 +711,28 @@ class SyncManagerXtreamLiveStrategyTest {assertThat(payload.stagedAcceptedCount).isEqualTo(1)assertThat(requestedCategoryIds).containsExactly("12")assertThat(requestCount.get()).isEqualTo(1)++ requestedCategoryIds.clear()+ requestCount.set(0)+ val restorePayload = strategy.syncXtreamLiveCatalog(+ provider = provider,+ api = xtreamProvider,+ existingMetadata = SyncMetadata(provider.id),+ hiddenLiveCategoryIds = setOf(13L),+ onProgress = null,+ runtimeProfile = testRuntimeProfile(+ tier = DeviceSyncTier.HIGH,+ batchSize = 100,+ maxCategoryConcurrency = 2+ ),+ trackInitialLiveOnboarding = false,+ effectiveLiveSyncMethod = EffectiveXtreamLiveSyncMethod.STREAM_ALL,+ requiredHiddenLiveCategoryIds = setOf(13L)+ )++ assertThat(restorePayload.stagedAcceptedCount).isEqualTo(2)+ assertThat(requestedCategoryIds).containsExactly("12", "13")+ Unit}@Testdiff --git a/domain/src/main/java/com/streamvault/domain/manager/BackupManager.kt b/domain/src/main/java/com/streamvault/domain/manager/BackupManager.ktindex 4928cc8c..5fedb1e3 100644--- a/domain/src/main/java/com/streamvault/domain/manager/BackupManager.kt+++ b/domain/src/main/java/com/streamvault/domain/manager/BackupManager.kt@@ -41,7 +41,18 @@ data class BackupData(/** User-created combined M3U sources, represented by portable provider identities. */val combinedM3uProfiles: List<CombinedM3uProfileBackup>? = null,/** The selected live source, represented without local provider/profile IDs. */- val activeLiveSource: ActiveLiveSourceBackup? = null+ val activeLiveSource: ActiveLiveSourceBackup? = null,+ /** v14 user-owned catalog state. These records never contain local Room identifiers. */+ val portableFavorites: List<PortableFavoriteBackup>? = null,+ val portableCustomGroups: List<PortableCustomGroupBackup>? = null,+ val portablePlaybackHistory: List<PortablePlaybackHistoryBackup>? = null,+ val portableProtectedContent: List<PortableProtectedContentBackup>? = null,+ val portableSearchHistory: List<PortableSearchHistoryBackup>? = null,+ val portableHiddenContent: List<PortableHiddenContentBackup>? = null,+ val portableContentPreferences: List<PortableContentPreferenceBackup>? = null,+ val portableVariantChoices: List<PortableVariantChoiceBackup>? = null,+ val portableManualEpgMappings: List<PortableManualEpgMappingV14Backup>? = null,+ val portableMultiViewPresetsV14: List<PortableMultiViewPresetV14Backup>? = null)data class ProviderBackupSnapshot(@@ -121,7 +132,9 @@ data class PortableChannelReference(val provider: BackupProviderReference,val streamId: Long,val name: String,- val streamUrl: String+ val streamUrl: String,+ /** Remote category identity used to hydrate hidden categories before deferred restore. */+ val remoteCategoryId: Long? = null)data class PortableChannelPreferenceReference(@@ -148,7 +161,96 @@ data class PortableVariantSelectionReference(val rawItemId: Long,/** Provider/catalog identity used by current backups; never a local Room id. */val remoteItemId: String? = null,- val contentType: ContentType? = null+ val contentType: ContentType? = null,+ val remoteCategoryId: Long? = null+)++/**+ * Stable identity for provider-owned catalog content in v14 backups.+ *+ * [remoteContentId] is the provider's identity, never a Room primary key. Parent and category+ * identities are included where providers only guarantee identity inside that scope. Name and URL+ * are matching fallbacks and may only be used when they identify exactly one local row.+ */+data class PortableContentReference(+ val provider: BackupProviderReference,+ val contentType: ContentType,+ val remoteContentId: String,+ val parentRemoteContentId: String? = null,+ val remoteCategoryId: String? = null,+ val name: String? = null,+ val urlFallback: String? = null+)++data class PortableFavoriteBackup(+ val content: PortableContentReference,+ val position: Int = 0,+ val addedAt: Long = 0L+)++data class PortableCustomGroupBackup(+ val provider: BackupProviderReference,+ val contentType: ContentType,+ val name: String,+ val icon: String? = null,+ val position: Int = 0,+ val createdAt: Long = 0L,+ val members: List<PortableFavoriteBackup> = emptyList()+)++data class PortablePlaybackHistoryBackup(+ val content: PortableContentReference,+ val resumePositionMs: Long = 0L,+ val totalDurationMs: Long = 0L,+ val lastWatchedAt: Long = 0L,+ val watchCount: Int = 1,+ val watchedStatus: String = "IN_PROGRESS",+ val posterUrl: String? = null,+ val seasonNumber: Int? = null,+ val episodeNumber: Int? = null+)++data class PortableProtectedContentBackup(+ val content: PortableContentReference+)++data class PortableHiddenContentBackup(+ val content: PortableContentReference+)++data class PortableContentPreferenceBackup(+ val content: PortableContentReference,+ val aspectRatio: String? = null,+ val audioVideoOffsetMs: Int? = null+)++data class PortableVariantChoiceBackup(+ val logicalGroupId: String,+ val selectedContent: PortableContentReference+)++data class PortableManualEpgMappingV14Backup(+ val content: PortableContentReference,+ val sourceUrl: String? = null,+ val xmltvChannelId: String? = null,+ val sourceType: String = "NONE",+ val matchType: String? = null,+ val confidence: Float = 0f,+ val source: String? = null+)++data class PortableMultiViewPresetV14Backup(+ val name: String,+ val channels: List<PortableContentReference>+)++data class PortableSearchHistoryBackup(+ val query: String,+ val contentScope: String,+ /** Null means the search was global rather than provider-scoped. */+ val provider: BackupProviderReference? = null,+ val usedAt: Long,+ val useCount: Int = 1)data class CombinedM3uProfileBackup(@@ -199,7 +301,9 @@ data class ScheduledRecordingBackup(val programTitle: String? = null,val recurrence: RecordingRecurrence = RecordingRecurrence.NONE,val recurringRuleId: String? = null,- val providerType: ProviderType? = null+ val providerType: ProviderType? = null,+ /** v14 portable channel identity; [channelId] remains only for v0-v13 compatibility. */+ val channel: PortableContentReference? = null)data class RecordingStorageBackup(@@ -331,6 +435,7 @@ data class RecordingScheduleImportSummary(*/enum class BackupRestoreOutcome {COMPLETE,+ WAITING_FOR_SYNC,PARTIAL,FAILED_BEFORE_COMMIT}@@ -341,7 +446,11 @@ data class BackupImportResult(val skippedSections: List<String> = emptyList(),val failedSections: List<String> = emptyList(),val unresolvedReferences: List<String> = emptyList(),- val recordingScheduleImport: RecordingScheduleImportSummary? = null+ val recordingScheduleImport: RecordingScheduleImportSummary? = null,+ val restoreJobId: String? = null,+ val pendingCount: Int = 0,+ val unresolvedCount: Int = 0,+ val affectedProviders: List<BackupProviderReference> = emptyList())interface BackupManager {@@ -363,3 +472,38 @@ interface BackupManager {plan: BackupImportPlan = BackupImportPlan()): Result<BackupImportResult>}++data class BackupRestoreProviderStatus(+ val providerIdentityKey: String,+ val localProviderId: Long? = null,+ val appliedCount: Int = 0,+ val pendingCount: Int = 0,+ val unresolvedCount: Int = 0,+ val failedCount: Int = 0,+ val items: List<BackupRestoreItemStatus> = emptyList()+)++data class BackupRestoreItemStatus(+ val id: Long,+ val section: String,+ val contentType: String? = null,+ val status: String,+ val attempts: Int,+ val lastError: String? = null+)++data class BackupRestoreJobStatus(+ val jobId: String,+ val backupVersion: Int,+ val status: String,+ val providers: List<BackupRestoreProviderStatus>,+ val updatedAt: Long+)++interface BackupRestoreStatusStore {+ fun observeRestoreJobs(): Flow<List<BackupRestoreJobStatus>>+ suspend fun retryProviders(providerIds: Set<Long>)+ suspend fun dismissItem(itemId: Long)+ suspend fun dismissProvider(jobId: String, providerIdentityKey: String)+ suspend fun dismissRestore(jobId: String)+}diff --git a/domain/src/main/java/com/streamvault/domain/usecase/ImportBackup.kt b/domain/src/main/java/com/streamvault/domain/usecase/ImportBackup.ktindex d63047cd..c171c287 100644--- a/domain/src/main/java/com/streamvault/domain/usecase/ImportBackup.kt+++ b/domain/src/main/java/com/streamvault/domain/usecase/ImportBackup.kt@@ -34,6 +34,8 @@ sealed class ImportBackupResult {val baseSummary = when (result.outcome) {BackupRestoreOutcome.COMPLETE ->result.importedSections.joinToString().ifBlank { "Nothing imported" }+ BackupRestoreOutcome.WAITING_FOR_SYNC ->+ "Imported; ${result.pendingCount + result.unresolvedCount} item(s) are waiting for provider sync"BackupRestoreOutcome.PARTIAL ->"Partially imported: ${result.importedSections.joinToString().ifBlank { "nothing" }}"BackupRestoreOutcome.FAILED_BEFORE_COMMIT -> "Nothing was committed"