StreamVault is a TV-first free IPTV player for Android TV built with Kotlin, Jetpack Compose, Room, Hilt, and Media3.
Kotlin iptv-player
Add unit tests for download recovery state machine, reminder notifier policy, preferences corruption recovery, and provider sync functionality
David Nashashe6a715f5d10c
diff --git a/app/src/main/java/com/streamvault/app/StartupWorkRegistry.kt b/app/src/main/java/com/streamvault/app/StartupWorkRegistry.ktnew file mode 100644index 00000000..21430f8f--- /dev/null+++ b/app/src/main/java/com/streamvault/app/StartupWorkRegistry.kt@@ -0,0 +1,50 @@+package com.streamvault.app++import android.content.Context+import androidx.work.ExistingPeriodicWorkPolicy+import androidx.work.PeriodicWorkRequestBuilder+import androidx.work.WorkManager+import com.streamvault.app.update.AppUpdateCheckWorker+import com.streamvault.data.manager.recording.RecordingReconcileWorker+import com.streamvault.data.repository.ProviderDeletionCleanupWorker+import com.streamvault.data.sync.ProviderSyncWorker+import com.streamvault.data.sync.SyncWorker+import com.streamvault.data.sync.XtreamIndexWorker+import dagger.hilt.android.qualifiers.ApplicationContext+import java.util.concurrent.TimeUnit+import javax.inject.Inject++/**+ * The single application-start entry point for durable background-work registration.+ *+ * Provider workers still retain their own request builders while ARCH-008 is migrated, but+ * process startup no longer knows or independently selects their identities and policies.+ */+class StartupWorkRegistry @Inject constructor(+ @param:ApplicationContext private val context: Context+) {+ fun register() {+ AppUpdateCheckWorker.enqueue(context)++ val dataMaintenance = PeriodicWorkRequestBuilder<SyncWorker>(24, TimeUnit.HOURS)+ .setConstraints(dataMaintenanceConstraints())+ .build()+ WorkManager.getInstance(context).enqueueUniquePeriodicWork(+ DATA_MAINTENANCE_WORK_NAME,+ ExistingPeriodicWorkPolicy.UPDATE,+ dataMaintenance+ )++ ProviderSyncWorker.enqueuePeriodic(context)+ ProviderSyncWorker.enqueueLaunchStaleCheck(context)+ XtreamIndexWorker.enqueuePeriodic(context)+ XtreamIndexWorker.enqueueLaunchStaleCheck(context)+ RecordingReconcileWorker.enqueuePeriodic(context)+ RecordingReconcileWorker.enqueueOneShot(context)+ ProviderDeletionCleanupWorker.enqueue(context)+ }++ private companion object {+ const val DATA_MAINTENANCE_WORK_NAME = "DataMaintenanceWorker"+ }+}diff --git a/app/src/main/java/com/streamvault/app/StreamVaultApp.kt b/app/src/main/java/com/streamvault/app/StreamVaultApp.ktindex 6be22bff..96096a72 100644--- a/app/src/main/java/com/streamvault/app/StreamVaultApp.kt+++ b/app/src/main/java/com/streamvault/app/StreamVaultApp.kt@@ -10,30 +10,19 @@ import coil3.network.okhttp.OkHttpNetworkFetcherFactoryimport coil3.request.crossfadeimport com.streamvault.app.diagnostics.CrashReportStoreimport com.streamvault.app.diagnostics.RuntimeDiagnosticsManager-import com.streamvault.app.update.GitHubReleaseChecker-import com.streamvault.app.update.AppUpdateCheckPolicyimport com.streamvault.app.plugins.StreamVaultPluginManagerimport com.streamvault.app.ui.accessibility.isReducedMotionEnabledimport com.streamvault.data.remote.jellyfin.JellyfinImageAuthInterceptor-import com.streamvault.data.preferences.PreferencesRepositoryimport com.streamvault.domain.repository.DownloadManager-import com.streamvault.domain.model.Result+import com.streamvault.domain.manager.ProgramReminderManagerimport dagger.hilt.android.HiltAndroidAppimport kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.SupervisorJob-import kotlinx.coroutines.flow.firstimport kotlinx.coroutines.launchimport okio.Path.Companion.toOkioPathimport androidx.work.Constraints-import androidx.work.ExistingPeriodicWorkPolicy-import androidx.work.PeriodicWorkRequestBuilder-import androidx.work.WorkManager-import com.streamvault.data.manager.recording.RecordingReconcileWorker-import com.streamvault.data.repository.ProviderDeletionCleanupWorker-import com.streamvault.data.sync.ProviderSyncWorker-import com.streamvault.data.sync.XtreamIndexWorkerimport com.streamvault.player.timeshift.TimeshiftDiskManagerimport javax.inject.Injectimport okhttp3.OkHttpClient@@ -43,12 +32,6 @@ class StreamVaultApp : Application(), SingletonImageLoader.Factory {private val runtimeDiagnosticsManager by lazy { RuntimeDiagnosticsManager(this) }private val applicationScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)- @Inject- lateinit var preferencesRepository: PreferencesRepository-- @Inject- lateinit var gitHubReleaseChecker: GitHubReleaseChecker-@Injectlateinit var okHttpClient: OkHttpClient@@ -61,6 +44,12 @@ class StreamVaultApp : Application(), SingletonImageLoader.Factory {@Injectlateinit var streamVaultPluginManager: StreamVaultPluginManager+ @Inject+ lateinit var programReminderManager: ProgramReminderManager++ @Inject+ lateinit var startupWorkRegistry: StartupWorkRegistry+private val imageOkHttpClient: OkHttpClient by lazy {okHttpClient.newBuilder().addInterceptor(jellyfinImageAuthInterceptor)@@ -76,37 +65,17 @@ class StreamVaultApp : Application(), SingletonImageLoader.Factory {// force-stops from the previous run. activeSessionDir = null means wipe everything.TimeshiftDiskManager(applicationContext).cleanupStaleDirectories(activeSessionDir = null)}- applicationScope.launch {- refreshCachedAppUpdateIfNeeded()- }applicationScope.launch {downloadManager.recoverInterruptedDownloads()}applicationScope.launch {streamVaultPluginManager.reconcilePluginProviders()}+ applicationScope.launch {+ programReminderManager.restoreScheduledReminders()+ }- // Schedule daily data maintenance: EPG pruning, stale-favorite cleanup, and DB compaction checks.- // This work is local-only and must also run for offline/local-playlist devices.- val gcConstraints = dataMaintenanceConstraints()-- val gcWorkRequest = PeriodicWorkRequestBuilder<com.streamvault.data.sync.SyncWorker>(24, java.util.concurrent.TimeUnit.HOURS)- .setConstraints(gcConstraints)- .build()-- WorkManager.getInstance(this).enqueueUniquePeriodicWork(- "DataMaintenanceWorker",- ExistingPeriodicWorkPolicy.KEEP,- gcWorkRequest- )-- ProviderSyncWorker.enqueuePeriodic(this)- ProviderSyncWorker.enqueueLaunchStaleCheck(this)- XtreamIndexWorker.enqueuePeriodic(this)- XtreamIndexWorker.enqueueLaunchStaleCheck(this)- RecordingReconcileWorker.enqueuePeriodic(this)- RecordingReconcileWorker.enqueueOneShot(this)- ProviderDeletionCleanupWorker.enqueue(this)+ startupWorkRegistry.register()}override fun onTerminate() {@@ -114,37 +83,6 @@ class StreamVaultApp : Application(), SingletonImageLoader.Factory {super.onTerminate()}- private suspend fun refreshCachedAppUpdateIfNeeded() {- val autoCheckEnabled = preferencesRepository.autoCheckAppUpdates.first()- if (!autoCheckEnabled) {- return- }-- val lastSuccessfulCheckAt = preferencesRepository.lastAppUpdateCheckTimestamp.first()- val lastFailedCheckAt = preferencesRepository.lastAppUpdateFailureTimestamp.first()- val now = System.currentTimeMillis()- if (!AppUpdateCheckPolicy.shouldAutoCheck(now, lastSuccessfulCheckAt, lastFailedCheckAt)) {- return- }-- when (val result = gitHubReleaseChecker.fetchLatestRelease()) {- is Result.Success -> {- preferencesRepository.setCachedAppUpdateRelease(- versionName = result.data.versionName,- versionCode = result.data.versionCode,- releaseUrl = result.data.releaseUrl,- downloadUrl = result.data.downloadUrl,- downloadSha256 = result.data.downloadSha256,- releaseNotes = result.data.releaseNotes,- publishedAt = result.data.publishedAt- )- preferencesRepository.setLastAppUpdateCheckTimestamp(now)- preferencesRepository.setLastAppUpdateFailureTimestamp(null)- }- else -> preferencesRepository.setLastAppUpdateFailureTimestamp(now)- }- }-override fun newImageLoader(context: PlatformContext): ImageLoader {return ImageLoader.Builder(context).components {diff --git a/app/src/main/java/com/streamvault/app/di/DatabaseModule.kt b/app/src/main/java/com/streamvault/app/di/DatabaseModule.ktindex 2f3fdc41..a948b2fa 100644--- a/app/src/main/java/com/streamvault/app/di/DatabaseModule.kt+++ b/app/src/main/java/com/streamvault/app/di/DatabaseModule.kt@@ -106,7 +106,12 @@ object DatabaseModule {StreamVaultDatabase.MIGRATION_62_63,StreamVaultDatabase.MIGRATION_63_64,StreamVaultDatabase.MIGRATION_64_65,- StreamVaultDatabase.MIGRATION_65_66+ StreamVaultDatabase.MIGRATION_65_66,+ StreamVaultDatabase.MIGRATION_66_67,+ StreamVaultDatabase.MIGRATION_67_68,+ StreamVaultDatabase.MIGRATION_68_69,+ StreamVaultDatabase.MIGRATION_69_70,+ StreamVaultDatabase.MIGRATION_70_71)// NOTE: fallbackToDestructiveMigration() intentionally removed.// All future schema changes MUST add a corresponding Migration in StreamVaultDatabase.@@ -150,5 +155,8 @@ object DatabaseModule {@Provides fun provideXtreamLiveOnboardingDao(db: StreamVaultDatabase): XtreamLiveOnboardingDao = db.xtreamLiveOnboardingDao()@Provides fun provideDownloadDao(db: StreamVaultDatabase): DownloadDao = db.downloadDao()@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 provideProviderWorkflowDao(db: StreamVaultDatabase): ProviderWorkflowDao = db.providerWorkflowDao()@Provides fun providePluginProviderOwnershipDao(db: StreamVaultDatabase): PluginProviderOwnershipDao = db.pluginProviderOwnershipDao()}diff --git a/app/src/main/java/com/streamvault/app/service/DownloadForegroundService.kt b/app/src/main/java/com/streamvault/app/service/DownloadForegroundService.ktindex b522517f..360ec3be 100644--- a/app/src/main/java/com/streamvault/app/service/DownloadForegroundService.kt+++ b/app/src/main/java/com/streamvault/app/service/DownloadForegroundService.kt@@ -49,19 +49,12 @@ class DownloadForegroundService : Service() {override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {val downloadId = intent?.getStringExtra(EXTRA_DOWNLOAD_ID)- if (downloadId.isNullOrBlank()) {- Log.w(TAG, " onStartCommand called without download_id extra; stopping self")- stopSelf(startId)- return START_NOT_STICKY- }-+ val startMode = resolveDownloadServiceStartMode(downloadId)currentDownloadId = downloadIdval entryPoint = entryPoint()- val downloadFlow = entryPoint.downloadManager().observeDownload(downloadId)-beginPendingCommand()- runCatching {+ val foregroundStarted = runCatching {startForeground(NOTIFICATION_ID,buildNotification(@@ -69,12 +62,37 @@ class DownloadForegroundService : Service() {pendingCommand = true))+ true}.onFailure { error ->Log.e(TAG, "Unable to enter foreground", error)+ }.getOrDefault(false)+ if (!foregroundStarted) {stopSelf(startId)return START_NOT_STICKY}+ observeJob?.cancel()+ if (startMode == DownloadServiceStartMode.RECOVER_INTERRUPTED) {+ Log.w(TAG, "Sticky restart without download_id; reconciling interrupted downloads")+ observeJob = serviceScope.launch {+ val manager = entryPoint.downloadManager()+ if (manager.recoverInterruptedDownloads() is com.streamvault.domain.model.Result.Error) {+ stopSelf(startId)+ return@launch+ }+ manager.observeAllDownloads().collectLatest { downloads ->+ val active = downloads.firstOrNull {+ it.status == DownloadStatus.DOWNLOADING || it.status == DownloadStatus.PENDING+ }+ currentDownloadId = active?.id+ updateNotification(active)+ if (active == null) stopSelf(startId)+ }+ }+ return START_STICKY+ }++ val downloadFlow = entryPoint.downloadManager().observeDownload(requireNotNull(downloadId))observeJob = serviceScope.launch {downloadFlow.collectLatest { downloadItem ->updateNotification(downloadItem)@@ -238,3 +256,15 @@ class DownloadForegroundService : Service() {}}}++internal enum class DownloadServiceStartMode {+ OBSERVE_REQUESTED,+ RECOVER_INTERRUPTED+}++internal fun resolveDownloadServiceStartMode(downloadId: String?): DownloadServiceStartMode =+ if (downloadId.isNullOrBlank()) {+ DownloadServiceStartMode.RECOVER_INTERRUPTED+ } else {+ DownloadServiceStartMode.OBSERVE_REQUESTED+ }diff --git a/app/src/main/java/com/streamvault/app/ui/screens/epg/EpgScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/epg/EpgScreen.ktindex b1bc1736..b70f274e 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/epg/EpgScreen.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/epg/EpgScreen.kt@@ -79,7 +79,9 @@ import androidx.compose.ui.unit.spimport androidx.compose.ui.window.Dialogimport androidx.compose.ui.window.DialogPropertiesimport androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel+import androidx.lifecycle.Lifecycleimport androidx.lifecycle.compose.collectAsStateWithLifecycle+import androidx.lifecycle.compose.LifecycleEventEffectimport androidx.tv.material3.Borderimport androidx.tv.material3.Buttonimport androidx.tv.material3.ButtonDefaults@@ -148,6 +150,9 @@ fun FullEpgScreen(val uiState by viewModel.uiState.collectAsStateWithLifecycle()val overrideUiState by viewModel.overrideUiState.collectAsStateWithLifecycle()val programReminderUiState by viewModel.programReminderUiState.collectAsStateWithLifecycle()+ LifecycleEventEffect(Lifecycle.Event.ON_START) {+ viewModel.reconcileProgramReminders()+ }var selectedProgram by remember { mutableStateOf<Pair<Channel, Program>?>(null) }var focusedChannel by remember { mutableStateOf<Channel?>(null) }var focusedProgram by remember { mutableStateOf<Program?>(null) }@@ -253,6 +258,12 @@ fun FullEpgScreen(viewModel.clearRecordingMessage()}}+ uiState.reminderMessage?.let { message ->+ LaunchedEffect(message) {+ android.widget.Toast.makeText(context, message, android.widget.Toast.LENGTH_LONG).show()+ viewModel.clearReminderMessage()+ }+ }uiState.pendingRecordingConflict?.let { conflict ->androidx.compose.material3.AlertDialog(diff --git a/app/src/main/java/com/streamvault/app/ui/screens/epg/EpgViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/epg/EpgViewModel.ktindex 14a621ea..d6c1f633 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/epg/EpgViewModel.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/epg/EpgViewModel.kt@@ -18,6 +18,8 @@ import com.streamvault.domain.model.EpgOverrideCandidateimport com.streamvault.domain.model.Favoriteimport com.streamvault.domain.model.GuideSourcePolicyimport com.streamvault.domain.model.Program+import com.streamvault.domain.model.ProgramReminder+import com.streamvault.domain.model.ProgramReminderDeliveryStateimport com.streamvault.domain.model.VirtualCategoryIdsimport com.streamvault.domain.repository.ChannelRepositoryimport com.streamvault.domain.repository.CombinedM3uRepository@@ -106,6 +108,7 @@ data class EpgUiState(val guideWindowStart: Long = DEFAULT_NOW - EpgViewModel.LOOKBACK_MS,val guideWindowEnd: Long = DEFAULT_NOW + EpgViewModel.LOOKAHEAD_MS,val recordingMessage: String? = null,+ val reminderMessage: String? = null,val pendingRecordingConflict: RecordingConflictInfo? = null,val hasMoreChannels: Boolean = false,val previewPlayerEngine: PlayerEngine? = null,@@ -143,6 +146,17 @@ data class ProgramReminderUiState(this.programStartTime == programStartTime}+internal fun programReminderDeliveryIssueMessage(reminders: List<ProgramReminder>): String? {+ val issue = reminders.firstOrNull {+ it.deliveryState == ProgramReminderDeliveryState.BLOCKED ||+ it.deliveryState == ProgramReminderDeliveryState.FAILED+ } ?: return null+ val reason = issue.deliveryFailureReason+ ?.takeIf { it.isNotBlank() }+ ?: "The notification was not accepted."+ return "Reminder for ${issue.programTitle} was not delivered: $reason"+}+enum class GuideChannelMode {ALL,ANCHORED,@@ -320,6 +334,7 @@ class EpgViewModel @Inject constructor(restoreGuidePreferences()observeGuideBase()observeGuidePresentation()+ observeReminderDeliveryIssues()viewModelScope.launch {livePreviewHandoffManager.reverseSessionFlow.collect { session ->if (session != null && session.source == PreviewHandoffSource.GUIDE) {@@ -329,6 +344,19 @@ class EpgViewModel @Inject constructor(}}+ private fun observeReminderDeliveryIssues() {+ viewModelScope.launch {+ programReminderManager.observeUpcomingReminders()+ .map(::programReminderDeliveryIssueMessage)+ .distinctUntilChanged()+ .collectLatest { message ->+ if (message != null) {+ _uiState.update { it.copy(reminderMessage = message) }+ }+ }+ }+ }+fun selectCategory(categoryId: Long) {startupCategoryId.value = nullif (selectedCategoryId.value == categoryId) return@@ -838,6 +866,16 @@ class EpgViewModel @Inject constructor(_uiState.update { it.copy(recordingMessage = null) }}+ fun clearReminderMessage() {+ _uiState.update { it.copy(reminderMessage = null) }+ }++ fun reconcileProgramReminders() {+ viewModelScope.launch {+ programReminderManager.restoreScheduledReminders()+ }+ }+fun updateEpgOverrideSearch(query: String) {val channel = _overrideUiState.value.channel ?: return_overrideUiState.update {diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerPreparationSetupActions.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerPreparationSetupActions.ktindex 9e0a09eb..36d80501 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerPreparationSetupActions.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerPreparationSetupActions.kt@@ -117,7 +117,7 @@ internal fun PlayerViewModel.applyPrepareSessionState(clearSeriesEpisodeContext()}if (currentContentType != ContentType.LIVE) {- livePlaybackRecordTracker.reset()+ livePlaybackRecordCoordinator.reset()recentChannelsJob?.cancel()recentChannelsFlow.value = emptyList()lastVisitedCategoryJob?.cancel()diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModel.ktindex 5eb60b9c..e1c546f1 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModel.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModel.kt@@ -265,7 +265,8 @@ class PlayerViewModel @Inject constructor(internal var hasRetriedXtreamAuthRefresh = falseinternal val probePassedPlaybackKeys = mutableSetOf<String>()private val notifiedRecordingFailureIds = mutableSetOf<String>()- internal val livePlaybackRecordTracker = LivePlaybackRecordTracker()+ internal val livePlaybackRecordCoordinator =+ LivePlaybackRecordCoordinator(playbackHistoryRepository::recordPlayback)private var currentStreamClassLabel: String = "Primary"internal var lastRecordedVariantObservationSignature: String? = nullinternal var lastRecordedVodVariantObservationSignature: String? = nulldiff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerZapActions.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerZapActions.ktindex c00d0712..56c8cc49 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerZapActions.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerZapActions.kt@@ -6,11 +6,15 @@ import com.streamvault.domain.model.ChannelNumberingModeimport com.streamvault.domain.model.ContentTypeimport com.streamvault.domain.model.PlaybackHistoryimport com.streamvault.domain.model.ProviderType+import kotlinx.coroutines.currentCoroutineContextimport kotlinx.coroutines.delay+import kotlinx.coroutines.ensureActiveimport kotlinx.coroutines.flow.updateimport kotlinx.coroutines.flow.filterimport kotlinx.coroutines.flow.firstimport kotlinx.coroutines.launch+import kotlinx.coroutines.sync.Mutex+import kotlinx.coroutines.sync.withLockinternal const val MAX_NUMERIC_CHANNEL_INPUT_DIGITS = 6@@ -28,30 +32,71 @@ internal data class LivePlaybackRecordCandidate(val history: PlaybackHistory)-internal class LivePlaybackRecordTracker {- private var latestGeneration = 0L+internal data class LivePlaybackRecordAttempt(+ val candidate: LivePlaybackRecordCandidate,+ val attemptId: Long+)++internal class LivePlaybackRecordCoordinator(+ private val recordPlayback: suspend (PlaybackHistory) -> com.streamvault.domain.model.Result<Unit>+) {+ private val stateLock = Any()+ private val writeMutex = Mutex()+ private var nextAttemptId = 0L+ private var latestRequestedKey: Pair<Long, Long>? = nullprivate var lastSuccessfulKey: Pair<Long, Long>? = nullprivate val inFlightGenerations = mutableMapOf<Pair<Long, Long>, Long>()- fun begin(playbackKey: Pair<Long, Long>): Long? {- if (playbackKey == lastSuccessfulKey || playbackKey in inFlightGenerations) return null- return (++latestGeneration).also { generation ->- inFlightGenerations[playbackKey] = generation+ fun begin(candidate: LivePlaybackRecordCandidate): LivePlaybackRecordAttempt? = synchronized(stateLock) {+ val playbackKey = candidate.playbackKey+ val isUninterruptedDuplicate = latestRequestedKey == playbackKey+ latestRequestedKey = playbackKey+ if (isUninterruptedDuplicate && playbackKey in inFlightGenerations) return@synchronized null+ if (playbackKey == lastSuccessfulKey && inFlightGenerations.isEmpty()) return@synchronized null++ LivePlaybackRecordAttempt(candidate, ++nextAttemptId).also { attempt ->+ inFlightGenerations[playbackKey] = attempt.attemptId}}- fun complete(playbackKey: Pair<Long, Long>, generation: Long, succeeded: Boolean) {- if (inFlightGenerations[playbackKey] != generation) return- inFlightGenerations.remove(playbackKey)- if (succeeded && generation == latestGeneration) {- lastSuccessfulKey = playbackKey+ suspend fun execute(+ attempt: LivePlaybackRecordAttempt+ ): com.streamvault.domain.model.Result<Unit>? {+ var succeeded = false+ try {+ return writeMutex.withLock {+ if (!isLatestRequest(attempt.candidate.playbackKey)) return@withLock null+ recordPlayback(attempt.candidate.history).also { result ->+ currentCoroutineContext().ensureActive()+ succeeded = result is com.streamvault.domain.model.Result.Success+ }+ }+ } finally {+ complete(attempt, succeeded)}}fun reset() {- latestGeneration++- lastSuccessfulKey = null- inFlightGenerations.clear()+ synchronized(stateLock) {+ latestRequestedKey = null+ lastSuccessfulKey = null+ inFlightGenerations.clear()+ }+ }++ private fun isLatestRequest(playbackKey: Pair<Long, Long>): Boolean = synchronized(stateLock) {+ latestRequestedKey == playbackKey+ }++ private fun complete(attempt: LivePlaybackRecordAttempt, succeeded: Boolean) {+ synchronized(stateLock) {+ val playbackKey = attempt.candidate.playbackKey+ if (inFlightGenerations[playbackKey] != attempt.attemptId) return+ inFlightGenerations.remove(playbackKey)+ if (succeeded && latestRequestedKey == playbackKey) {+ lastSuccessfulKey = playbackKey+ }+ }}}@@ -337,16 +382,11 @@ internal fun PlayerViewModel.recordActiveLivePlayback(channel: Channel? = currenchannel = channel) ?: return- val generation = livePlaybackRecordTracker.begin(candidate.playbackKey) ?: return+ val attempt = livePlaybackRecordCoordinator.begin(candidate) ?: returnviewModelScope.launch {- var succeeded = false- try {- val result = playbackHistoryRepository.recordPlayback(candidate.history)- succeeded = result is com.streamvault.domain.model.Result.Success+ livePlaybackRecordCoordinator.execute(attempt)?.let { result ->logRepositoryFailure(operation = "Record live playback", result = result)- } finally {- livePlaybackRecordTracker.complete(candidate.playbackKey, generation, succeeded)}}}diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsAppUpdateActions.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsAppUpdateActions.ktindex 4a8f4900..45c3a0d7 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsAppUpdateActions.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsAppUpdateActions.kt@@ -35,6 +35,8 @@ internal class SettingsAppUpdateActions(updateCheckInFlight = truescope.launch {val checkedAt = System.currentTimeMillis()+ preferencesRepository.setLastAppUpdateAttemptTimestamp(checkedAt)+ preferencesRepository.setLastAppUpdateOutcome("ATTEMPTED")uiState.update {it.copy(isCheckingForUpdates = true,@@ -44,6 +46,7 @@ internal class SettingsAppUpdateActions(when (val result = gitHubReleaseChecker.fetchLatestRelease()) {is Result.Error -> {preferencesRepository.setLastAppUpdateFailureTimestamp(checkedAt)+ preferencesRepository.setLastAppUpdateOutcome("FAILURE: ${result.message}")uiState.update {it.copy(isCheckingForUpdates = false,@@ -68,6 +71,7 @@ internal class SettingsAppUpdateActions()preferencesRepository.setLastAppUpdateCheckTimestamp(checkedAt)preferencesRepository.setLastAppUpdateFailureTimestamp(null)+ preferencesRepository.setLastAppUpdateOutcome("SUCCESS")val updateAvailable = isRemoteVersionNewer(release.versionCode,release.versionName,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 01c16345..78d39a18 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@@ -2,6 +2,7 @@ package com.streamvault.app.ui.screens.settingsimport com.streamvault.domain.manager.BackupConflictStrategyimport com.streamvault.domain.manager.BackupImportPlan+import com.streamvault.domain.manager.BackupRestoreOutcomeimport com.streamvault.domain.usecase.ExportBackupimport com.streamvault.domain.usecase.ExportBackupCommandimport com.streamvault.domain.usecase.ExportBackupResult@@ -148,6 +149,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.COMPLETEstate.copy(isImportingBackup = false,isSyncing = false,@@ -156,12 +160,16 @@ internal class SettingsBackupActions(} else {"Configuration imported: ${(result as ImportBackupResult.Success).importedSummary}"},- backupPreview = null,- pendingBackupUri = null,- backupImportPlan = BackupImportPlan()+ // Preserve the source and plan after partial/failed-before-commit outcomes so+ // 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)}- if (result is ImportBackupResult.Success) {+ if (result is ImportBackupResult.Success &&+ result.result.outcome == BackupRestoreOutcome.COMPLETE+ ) {onSuccess?.invoke()}}diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsProviderActions.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsProviderActions.ktindex b6b2be4d..0c051a88 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsProviderActions.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsProviderActions.kt@@ -16,6 +16,7 @@ import com.streamvault.domain.repository.SyncMetadataRepositoryimport com.streamvault.domain.usecase.SyncProviderimport com.streamvault.domain.usecase.SyncProviderCommandimport com.streamvault.domain.usecase.SyncProviderResult+import com.streamvault.domain.util.PersistedTimestampPolicyimport com.streamvault.data.sync.SyncManagerimport com.streamvault.data.preferences.PreferencesRepositoryimport kotlinx.coroutines.CancellationException@@ -26,6 +27,12 @@ import kotlinx.coroutines.flow.updateimport kotlinx.coroutines.launchimport kotlin.time.Duration.Companion.hours+internal fun shouldAutoSyncProvider(+ lastSyncedAt: Long,+ now: Long,+ staleAfterMillis: Long+): Boolean = !PersistedTimestampPolicy.isFresh(lastSyncedAt, now, staleAfterMillis)+internal class SettingsProviderActions(private val providerRepository: ProviderRepository,private val combinedM3uRepository: CombinedM3uRepository,@@ -64,9 +71,11 @@ internal class SettingsProviderActions(watchNextManager.refreshWatchNext()launcherRecommendationsManager.refreshRecommendations(force = true)tvInputChannelSyncManager.refreshTvInputCatalog()- val lastSyncedAt = provider.lastSyncedAt- val shouldAutoSync = lastSyncedAt <= 0L ||- System.currentTimeMillis() - lastSyncedAt >= AUTO_SWITCH_SYNC_STALE_AFTER_MS+ val shouldAutoSync = shouldAutoSyncProvider(+ lastSyncedAt = provider.lastSyncedAt,+ now = System.currentTimeMillis(),+ staleAfterMillis = AUTO_SWITCH_SYNC_STALE_AFTER_MS+ )if (shouldAutoSync) {refreshProvider(scope = scope,@@ -497,12 +506,17 @@ internal class SettingsProviderActions(}}) {is Result.Success -> {+ val outcome = result.datauiState.update {it.copy(isDeletingProvider = false,deleteProviderProgressMessage = null,deleteProviderProgressFraction = null,- userMessage = "Provider deleted"+ userMessage = if (outcome.cleanupPending) {+ "Provider library deleted; final cleanup continues"+ } else {+ "Provider deleted"+ })}onSuccess()diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsRecordingActions.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsRecordingActions.ktindex 1406b203..1e80026e 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsRecordingActions.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsRecordingActions.kt@@ -4,6 +4,7 @@ import android.app.Applicationimport com.streamvault.app.Rimport com.streamvault.domain.manager.RecordingManagerimport com.streamvault.domain.model.RecordingStorageConfig+import com.streamvault.domain.model.RecordingReconciliationResultimport com.streamvault.domain.model.Resultimport kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.flow.MutableStateFlow@@ -120,10 +121,14 @@ internal class SettingsRecordingActions(val result = recordingManager.reconcileRecordingState()uiState.update {it.copy(- userMessage = if (result is Result.Error) {- appContext.getString(R.string.settings_recording_reconcile_failed, result.message)- } else {- appContext.getString(R.string.settings_recording_reconcile_complete)+ userMessage = when (result) {+ is RecordingReconciliationResult.TransientFailure ->+ appContext.getString(R.string.settings_recording_reconcile_failed, result.message)+ is RecordingReconciliationResult.PermanentFailure ->+ appContext.getString(R.string.settings_recording_reconcile_failed, result.message)+ is RecordingReconciliationResult.Complete,+ is RecordingReconciliationResult.Partial ->+ appContext.getString(R.string.settings_recording_reconcile_complete)})}diff --git a/app/src/main/java/com/streamvault/app/update/AppUpdateCheckPolicy.kt b/app/src/main/java/com/streamvault/app/update/AppUpdateCheckPolicy.ktindex 4e58f665..86c085bf 100644--- a/app/src/main/java/com/streamvault/app/update/AppUpdateCheckPolicy.kt+++ b/app/src/main/java/com/streamvault/app/update/AppUpdateCheckPolicy.kt@@ -1,5 +1,7 @@package com.streamvault.app.update+import com.streamvault.domain.util.PersistedTimestampPolicy+internal object AppUpdateCheckPolicy {private const val SUCCESS_INTERVAL_MS = 24L * 60L * 60L * 1000Lprivate const val FAILURE_BACKOFF_MS = 15L * 60L * 1000L@@ -9,9 +11,9 @@ internal object AppUpdateCheckPolicy {lastSuccessfulCheckAt: Long?,lastFailedCheckAt: Long?,): Boolean {- if (lastSuccessfulCheckAt != null && now - lastSuccessfulCheckAt < SUCCESS_INTERVAL_MS) {+ if (PersistedTimestampPolicy.isFresh(lastSuccessfulCheckAt, now, SUCCESS_INTERVAL_MS)) {return false}- return lastFailedCheckAt == null || now - lastFailedCheckAt >= FAILURE_BACKOFF_MS+ return !PersistedTimestampPolicy.isFresh(lastFailedCheckAt, now, FAILURE_BACKOFF_MS)}}diff --git a/app/src/main/java/com/streamvault/app/update/AppUpdateCheckWorker.kt b/app/src/main/java/com/streamvault/app/update/AppUpdateCheckWorker.ktnew file mode 100644index 00000000..adf9656e--- /dev/null+++ b/app/src/main/java/com/streamvault/app/update/AppUpdateCheckWorker.kt@@ -0,0 +1,94 @@+package com.streamvault.app.update++import android.content.Context+import androidx.work.BackoffPolicy+import androidx.work.Constraints+import androidx.work.CoroutineWorker+import androidx.work.ExistingWorkPolicy+import androidx.work.NetworkType+import androidx.work.OneTimeWorkRequestBuilder+import androidx.work.WorkManager+import androidx.work.WorkerParameters+import com.streamvault.data.preferences.PreferencesRepository+import com.streamvault.domain.model.Result as DomainResult+import dagger.hilt.EntryPoint+import dagger.hilt.InstallIn+import dagger.hilt.android.EntryPointAccessors+import dagger.hilt.components.SingletonComponent+import kotlinx.coroutines.flow.first+import java.util.concurrent.TimeUnit++class AppUpdateCheckWorker(+ appContext: Context,+ workerParams: WorkerParameters+) : CoroutineWorker(appContext, workerParams) {++ @EntryPoint+ @InstallIn(SingletonComponent::class)+ interface Entry {+ fun preferencesRepository(): PreferencesRepository+ fun gitHubReleaseChecker(): GitHubReleaseChecker+ }++ override suspend fun doWork(): androidx.work.ListenableWorker.Result {+ val entry = EntryPointAccessors.fromApplication(applicationContext, Entry::class.java)+ val preferences = entry.preferencesRepository()+ if (!preferences.autoCheckAppUpdates.first()) return Result.success()++ val now = System.currentTimeMillis()+ if (runAttemptCount == 0 && !AppUpdateCheckPolicy.shouldAutoCheck(+ now,+ preferences.lastAppUpdateCheckTimestamp.first(),+ preferences.lastAppUpdateFailureTimestamp.first()+ )+ ) {+ return Result.success()+ }++ preferences.setLastAppUpdateAttemptTimestamp(now)+ preferences.setLastAppUpdateOutcome("ATTEMPTED")+ return when (val result = entry.gitHubReleaseChecker().fetchLatestRelease()) {+ is DomainResult.Success -> {+ preferences.setCachedAppUpdateRelease(+ versionName = result.data.versionName,+ versionCode = result.data.versionCode,+ releaseUrl = result.data.releaseUrl,+ downloadUrl = result.data.downloadUrl,+ downloadSha256 = result.data.downloadSha256,+ releaseNotes = result.data.releaseNotes,+ publishedAt = result.data.publishedAt+ )+ preferences.setLastAppUpdateCheckTimestamp(now)+ preferences.setLastAppUpdateFailureTimestamp(null)+ preferences.setLastAppUpdateOutcome("SUCCESS")+ Result.success()+ }+ is DomainResult.Error -> {+ preferences.setLastAppUpdateFailureTimestamp(now)+ preferences.setLastAppUpdateOutcome("FAILURE: ${result.message}")+ Result.retry()+ }+ DomainResult.Loading -> Result.retry()+ }+ }++ companion object {+ private const val UNIQUE_WORK_NAME = "app-update-check"++ fun enqueue(context: Context) {+ val request = OneTimeWorkRequestBuilder<AppUpdateCheckWorker>()+ .setConstraints(+ Constraints.Builder()+ .setRequiredNetworkType(NetworkType.CONNECTED)+ .build()+ )+ .setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 15L, TimeUnit.MINUTES)+ .build()+ WorkManager.getInstance(context).enqueueUniqueWork(+ UNIQUE_WORK_NAME,+ ExistingWorkPolicy.KEEP,+ request+ )+ }+ }+}diff --git a/app/src/test/java/com/streamvault/app/service/DownloadForegroundServicePolicyTest.kt b/app/src/test/java/com/streamvault/app/service/DownloadForegroundServicePolicyTest.ktnew file mode 100644index 00000000..d1b8d39a--- /dev/null+++ b/app/src/test/java/com/streamvault/app/service/DownloadForegroundServicePolicyTest.kt@@ -0,0 +1,25 @@+package com.streamvault.app.service++import com.google.common.truth.Truth.assertThat+import org.junit.Test++class DownloadForegroundServicePolicyTest {++ @Test+ fun `sticky null intent enters interrupted download recovery`() {+ assertThat(resolveDownloadServiceStartMode(null))+ .isEqualTo(DownloadServiceStartMode.RECOVER_INTERRUPTED)+ }++ @Test+ fun `blank sticky download id enters interrupted download recovery`() {+ assertThat(resolveDownloadServiceStartMode(" "))+ .isEqualTo(DownloadServiceStartMode.RECOVER_INTERRUPTED)+ }++ @Test+ fun `explicit download command observes requested download`() {+ assertThat(resolveDownloadServiceStartMode("download-1"))+ .isEqualTo(DownloadServiceStartMode.OBSERVE_REQUESTED)+ }+}diff --git a/app/src/test/java/com/streamvault/app/ui/screens/epg/EpgViewModelTest.kt b/app/src/test/java/com/streamvault/app/ui/screens/epg/EpgViewModelTest.ktindex f5cb9dc1..765d4e7d 100644--- a/app/src/test/java/com/streamvault/app/ui/screens/epg/EpgViewModelTest.kt+++ b/app/src/test/java/com/streamvault/app/ui/screens/epg/EpgViewModelTest.kt@@ -105,6 +105,7 @@ class EpgViewModelTest {whenever(channelRepository.getChannelsByCategoryPage(any(), any(), any())).thenReturn(flowOf(emptyList()))whenever(channelRepository.getChannelsWithoutErrorsPage(any(), any(), any())).thenReturn(flowOf(emptyList()))whenever(recordingManager.observeRecordingItems()).thenReturn(flowOf(emptyList()))+ whenever(programReminderManager.observeUpcomingReminders()).thenReturn(flowOf(emptyList()))}@Afterdiff --git a/app/src/test/java/com/streamvault/app/ui/screens/epg/ProgramReminderIssueMessageTest.kt b/app/src/test/java/com/streamvault/app/ui/screens/epg/ProgramReminderIssueMessageTest.ktnew file mode 100644index 00000000..f26bf56a--- /dev/null+++ b/app/src/test/java/com/streamvault/app/ui/screens/epg/ProgramReminderIssueMessageTest.kt@@ -0,0 +1,47 @@+package com.streamvault.app.ui.screens.epg++import com.google.common.truth.Truth.assertThat+import com.streamvault.domain.model.ProgramReminder+import com.streamvault.domain.model.ProgramReminderDeliveryState+import org.junit.Test++class ProgramReminderIssueMessageTest {++ @Test+ fun `blocked persisted reminder is surfaced with its reason`() {+ val reminder = ProgramReminder(+ id = 42L,+ providerId = 7L,+ channelId = "bbc1",+ channelName = "BBC One",+ programTitle = "World News",+ programStartTime = 10_000L,+ remindAt = 5_000L,+ deliveryState = ProgramReminderDeliveryState.BLOCKED,+ deliveryFailureReason = "Program reminders channel is disabled"+ )++ assertThat(programReminderDeliveryIssueMessage(listOf(reminder)))+ .isEqualTo(+ "Reminder for World News was not delivered: " ++ "Program reminders channel is disabled"+ )+ }++ @Test+ fun `delivered reminders do not surface an issue`() {+ val reminder = ProgramReminder(+ id = 42L,+ providerId = 7L,+ channelId = "bbc1",+ channelName = "BBC One",+ programTitle = "World News",+ programStartTime = 10_000L,+ remindAt = 5_000L,+ deliveryState = ProgramReminderDeliveryState.DELIVERED,+ notifiedAt = 5_000L+ )++ assertThat(programReminderDeliveryIssueMessage(listOf(reminder))).isNull()+ }+}diff --git a/app/src/test/java/com/streamvault/app/ui/screens/player/PlayerZapActionsLivePlaybackTest.kt b/app/src/test/java/com/streamvault/app/ui/screens/player/PlayerZapActionsLivePlaybackTest.ktindex a5688cf3..1bebde97 100644--- a/app/src/test/java/com/streamvault/app/ui/screens/player/PlayerZapActionsLivePlaybackTest.kt+++ b/app/src/test/java/com/streamvault/app/ui/screens/player/PlayerZapActionsLivePlaybackTest.kt@@ -3,40 +3,151 @@ package com.streamvault.app.ui.screens.playerimport com.google.common.truth.Truth.assertThatimport com.streamvault.domain.model.Channelimport com.streamvault.domain.model.ContentType+import com.streamvault.domain.model.PlaybackHistory+import com.streamvault.domain.model.Result+import kotlinx.coroutines.CompletableDeferred+import kotlinx.coroutines.ExperimentalCoroutinesApi+import kotlinx.coroutines.awaitCancellation+import kotlinx.coroutines.cancelAndJoin+import kotlinx.coroutines.launch+import kotlinx.coroutines.test.advanceUntilIdle+import kotlinx.coroutines.test.runCurrent+import kotlinx.coroutines.test.runTestimport org.junit.Test+@OptIn(ExperimentalCoroutinesApi::class)class PlayerZapActionsLivePlaybackTest {@Test- fun `live playback tracker retries a failed write and deduplicates a successful one`() {- val tracker = LivePlaybackRecordTracker()- val key = 9L to 42L+ fun `failed live history write is retryable and success is deduplicated`() = runTest {+ val results = ArrayDeque<Result<Unit>>().apply {+ add(Result.error("disk unavailable"))+ add(Result.success(Unit))+ }+ var writes = 0+ val coordinator = LivePlaybackRecordCoordinator {+ writes+++ results.removeFirst()+ }+ val candidate = liveCandidate(channelId = 42L)++ assertThat(coordinator.execute(coordinator.begin(candidate)!!)).isInstanceOf(Result.Error::class.java)+ assertThat(coordinator.execute(coordinator.begin(candidate)!!)).isInstanceOf(Result.Success::class.java)++ assertThat(coordinator.begin(candidate)).isNull()+ assertThat(writes).isEqualTo(2)+ }- val firstAttempt = tracker.begin(key)- assertThat(firstAttempt).isNotNull()- assertThat(tracker.begin(key)).isNull()+ @Test+ fun `A to B to A retries latest A after first A fails and drops queued B`() = runTest {+ val firstWriteStarted = CompletableDeferred<Unit>()+ val releaseFirstWrite = CompletableDeferred<Unit>()+ val writes = mutableListOf<Long>()+ val coordinator = LivePlaybackRecordCoordinator { history ->+ writes += history.contentId+ if (writes.size == 1) {+ firstWriteStarted.complete(Unit)+ releaseFirstWrite.await()+ Result.error("first A failed")+ } else {+ Result.success(Unit)+ }+ }+ val channelA = liveCandidate(channelId = 42L)+ val channelB = liveCandidate(channelId = 43L)++ launch { coordinator.execute(coordinator.begin(channelA)!!) }+ firstWriteStarted.await()+ val queuedChannelB = coordinator.begin(channelB)!!+ launch { coordinator.execute(queuedChannelB) }+ val returnedChannelA = coordinator.begin(channelA)+ assertThat(returnedChannelA).isNotNull()+ launch { coordinator.execute(returnedChannelA!!) }+ releaseFirstWrite.complete(Unit)+ advanceUntilIdle()++ assertThat(writes).containsExactly(42L, 42L).inOrder()+ assertThat(coordinator.begin(channelA)).isNull()+ assertThat(coordinator.begin(channelB)).isNotNull()+ }- tracker.complete(key, firstAttempt!!, succeeded = false)- val retry = tracker.begin(key)- assertThat(retry).isNotNull()+ @Test+ fun `concurrent duplicate events launch one repository write`() = runTest {+ val writeStarted = CompletableDeferred<Unit>()+ val releaseWrite = CompletableDeferred<Unit>()+ var writes = 0+ val coordinator = LivePlaybackRecordCoordinator {+ writes+++ writeStarted.complete(Unit)+ releaseWrite.await()+ Result.success(Unit)+ }+ val candidate = liveCandidate(channelId = 42L)+ val attempt = coordinator.begin(candidate)!!++ launch { coordinator.execute(attempt) }+ writeStarted.await()++ assertThat(coordinator.begin(candidate)).isNull()+ releaseWrite.complete(Unit)+ advanceUntilIdle()+ assertThat(writes).isEqualTo(1)+ }- tracker.complete(key, retry!!, succeeded = true)- assertThat(tracker.begin(key)).isNull()+ @Test+ fun `cancelled repository write clears in flight marker and permits retry`() = runTest {+ val firstWriteStarted = CompletableDeferred<Unit>()+ var writes = 0+ val coordinator = LivePlaybackRecordCoordinator {+ writes+++ if (writes == 1) {+ firstWriteStarted.complete(Unit)+ awaitCancellation()+ }+ Result.success(Unit)+ }+ val candidate = liveCandidate(channelId = 42L)+ val cancelledWrite = launch {+ coordinator.execute(coordinator.begin(candidate)!!)+ }+ firstWriteStarted.await()++ cancelledWrite.cancelAndJoin()+ val retryResult = coordinator.execute(coordinator.begin(candidate)!!)++ assertThat(retryResult).isInstanceOf(Result.Success::class.java)+ assertThat(writes).isEqualTo(2)}@Test- fun `live playback tracker ignores stale completion when a newer channel started`() {- val tracker = LivePlaybackRecordTracker()- val firstKey = 9L to 42L- val secondKey = 9L to 43L-- val firstAttempt = tracker.begin(firstKey)!!- val secondAttempt = tracker.begin(secondKey)!!- tracker.complete(firstKey, firstAttempt, succeeded = true)- tracker.complete(secondKey, secondAttempt, succeeded = true)-- assertThat(tracker.begin(firstKey)).isNotNull()- assertThat(tracker.begin(secondKey)).isNull()+ fun `stale completion is followed by latest channel write`() = runTest {+ val staleWriteStarted = CompletableDeferred<Unit>()+ val releaseStaleWrite = CompletableDeferred<Unit>()+ val writes = mutableListOf<Long>()+ val coordinator = LivePlaybackRecordCoordinator { history ->+ writes += history.contentId+ if (writes.size == 2) {+ staleWriteStarted.complete(Unit)+ releaseStaleWrite.await()+ }+ Result.success(Unit)+ }+ val channelA = liveCandidate(channelId = 42L)+ val channelB = liveCandidate(channelId = 43L)++ coordinator.execute(coordinator.begin(channelA)!!)+ val staleChannelB = coordinator.begin(channelB)!!+ launch { coordinator.execute(staleChannelB) }+ staleWriteStarted.await()+ val restoreLatest = coordinator.begin(channelA)+ assertThat(restoreLatest).isNotNull()+ launch { coordinator.execute(restoreLatest!!) }+ runCurrent()+ releaseStaleWrite.complete(Unit)+ advanceUntilIdle()++ assertThat(writes).containsExactly(42L, 43L, 42L).inOrder()+ assertThat(coordinator.begin(channelA)).isNull()}@Test@@ -98,4 +209,16 @@ class PlayerZapActionsLivePlaybackTest {assertThat(candidate).isNull()}++ private fun liveCandidate(channelId: Long): LivePlaybackRecordCandidate =+ LivePlaybackRecordCandidate(+ playbackKey = 9L to channelId,+ history = PlaybackHistory(+ contentId = channelId,+ contentType = ContentType.LIVE,+ providerId = 9L,+ title = "Channel $channelId",+ streamUrl = "https://example.com/live/$channelId.m3u8"+ )+ )}diff --git a/app/src/test/java/com/streamvault/app/ui/screens/settings/SettingsAppUpdateActionsTest.kt b/app/src/test/java/com/streamvault/app/ui/screens/settings/SettingsAppUpdateActionsTest.ktnew file mode 100644index 00000000..f30c02c0--- /dev/null+++ b/app/src/test/java/com/streamvault/app/ui/screens/settings/SettingsAppUpdateActionsTest.kt@@ -0,0 +1,62 @@+package com.streamvault.app.ui.screens.settings++import android.app.Application+import com.google.common.truth.Truth.assertThat+import com.streamvault.app.update.AppUpdateInstaller+import com.streamvault.app.update.GitHubReleaseChecker+import com.streamvault.data.preferences.PreferencesRepository+import com.streamvault.domain.model.Result+import kotlinx.coroutines.ExperimentalCoroutinesApi+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.test.StandardTestDispatcher+import kotlinx.coroutines.test.advanceUntilIdle+import kotlinx.coroutines.test.runTest+import org.junit.Test+import org.mockito.kotlin.any+import org.mockito.kotlin.anyOrNull+import org.mockito.kotlin.mock+import org.mockito.kotlin.never+import org.mockito.kotlin.verify+import org.mockito.kotlin.whenever++@OptIn(ExperimentalCoroutinesApi::class)+class SettingsAppUpdateActionsTest {+ @Test+ fun `failed check records failure without replacing cached release`() = runTest(StandardTestDispatcher()) {+ val application = mock<Application>()+ val preferences = mock<PreferencesRepository>()+ val checker = mock<GitHubReleaseChecker>()+ val installer = mock<AppUpdateInstaller>()+ val uiState = MutableStateFlow(SettingsUiState())+ whenever(checker.fetchLatestRelease()).thenReturn(Result.error("HTTP 500"))++ val actions = SettingsAppUpdateActions(+ appContext = application,+ preferencesRepository = preferences,+ gitHubReleaseChecker = checker,+ appUpdateInstaller = installer,+ uiState = uiState+ )++ actions.checkForAppUpdates(+ scope = this,+ manual = false,+ isRemoteVersionNewer = { _, _, _ -> false }+ )+ advanceUntilIdle()++ assertThat(uiState.value.appUpdate.errorMessage).isEqualTo("HTTP 500")+ verify(preferences).setLastAppUpdateAttemptTimestamp(any())+ verify(preferences).setLastAppUpdateFailureTimestamp(any())+ verify(preferences).setLastAppUpdateOutcome("FAILURE: HTTP 500")+ verify(preferences, never()).setCachedAppUpdateRelease(+ versionName = anyOrNull(),+ versionCode = anyOrNull(),+ releaseUrl = anyOrNull(),+ downloadUrl = anyOrNull(),+ downloadSha256 = anyOrNull(),+ releaseNotes = anyOrNull(),+ publishedAt = anyOrNull()+ )+ }+}diff --git a/app/src/test/java/com/streamvault/app/ui/screens/settings/SettingsBackupActionsTest.kt b/app/src/test/java/com/streamvault/app/ui/screens/settings/SettingsBackupActionsTest.ktnew file mode 100644index 00000000..028732b0--- /dev/null+++ b/app/src/test/java/com/streamvault/app/ui/screens/settings/SettingsBackupActionsTest.kt@@ -0,0 +1,73 @@+package com.streamvault.app.ui.screens.settings++import com.google.common.truth.Truth.assertThat+import com.streamvault.domain.manager.BackupImportPlan+import com.streamvault.domain.manager.BackupImportResult+import com.streamvault.domain.manager.BackupRestoreOutcome+import com.streamvault.domain.usecase.ExportBackup+import com.streamvault.domain.usecase.ImportBackup+import com.streamvault.domain.usecase.ImportBackupResult+import kotlinx.coroutines.ExperimentalCoroutinesApi+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.test.StandardTestDispatcher+import kotlinx.coroutines.test.advanceUntilIdle+import kotlinx.coroutines.test.runTest+import org.junit.Test+import org.mockito.kotlin.mock+import org.mockito.kotlin.whenever++@OptIn(ExperimentalCoroutinesApi::class)+class SettingsBackupActionsTest {++ private val exportBackup: ExportBackup = mock()+ private val importBackup: ImportBackup = mock()++ @Test+ fun partialImport_retainsSourceAndPlanForCheckpointRetry() = runTest(StandardTestDispatcher()) {+ val plan = BackupImportPlan(importPreferences = true, importProviders = false)+ val uiState = MutableStateFlow(+ SettingsUiState(+ pendingBackupUri = "content://backup",+ backupImportPlan = plan+ )+ )+ val actions = SettingsBackupActions(exportBackup, importBackup, uiState)+ whenever(importBackup.confirm(org.mockito.kotlin.any())).thenReturn(+ ImportBackupResult.Success(+ BackupImportResult(+ outcome = BackupRestoreOutcome.PARTIAL,+ importedSections = listOf("Providers"),+ failedSections = listOf("Preferences: unavailable")+ )+ )+ )+ var onSuccessCalled = false++ actions.confirmBackupImport(this, onSuccess = { onSuccessCalled = true })+ advanceUntilIdle()++ assertThat(uiState.value.pendingBackupUri).isEqualTo("content://backup")+ assertThat(uiState.value.backupImportPlan).isEqualTo(plan)+ assertThat(uiState.value.isImportingBackup).isFalse()+ assertThat(onSuccessCalled).isFalse()+ }++ @Test+ fun completeImport_clearsSourceAndRunsFollowUp() = runTest(StandardTestDispatcher()) {+ val uiState = MutableStateFlow(+ SettingsUiState(pendingBackupUri = "content://backup")+ )+ val actions = SettingsBackupActions(exportBackup, importBackup, uiState)+ whenever(importBackup.confirm(org.mockito.kotlin.any())).thenReturn(+ ImportBackupResult.Success(BackupImportResult(outcome = BackupRestoreOutcome.COMPLETE))+ )+ var onSuccessCalled = false++ actions.confirmBackupImport(this, onSuccess = { onSuccessCalled = true })+ advanceUntilIdle()++ assertThat(uiState.value.pendingBackupUri).isNull()+ assertThat(uiState.value.backupImportPlan).isEqualTo(BackupImportPlan())+ assertThat(onSuccessCalled).isTrue()+ }+}diff --git a/app/src/test/java/com/streamvault/app/ui/screens/settings/SettingsProviderActionsTest.kt b/app/src/test/java/com/streamvault/app/ui/screens/settings/SettingsProviderActionsTest.ktindex 092e6dcc..6475ec99 100644--- a/app/src/test/java/com/streamvault/app/ui/screens/settings/SettingsProviderActionsTest.kt+++ b/app/src/test/java/com/streamvault/app/ui/screens/settings/SettingsProviderActionsTest.kt@@ -55,6 +55,17 @@ class SettingsProviderActionsTest {uiState = uiState)+ @Test+ fun providerWithFutureSyncTimestampIsStaleAfterBackwardClockJump() {+ assertThat(+ shouldAutoSyncProvider(+ lastSyncedAt = 10_001L,+ now = 10_000L,+ staleAfterMillis = 86_400_000L+ )+ ).isTrue()+ }+@Testfun setActiveProvider_refreshesProviderScopedTvSurfaces() = runTest(StandardTestDispatcher()) {val provider = Provider(@@ -80,7 +91,15 @@ class SettingsProviderActionsTest {@Testfun deleteProvider_refreshesProviderScopedTvSurfaces() = runTest(StandardTestDispatcher()) {- whenever(providerRepository.deleteProvider(eq(7L), any())).thenReturn(Result.success(Unit))+ whenever(providerRepository.deleteProvider(eq(7L), any())).thenReturn(+ Result.success(+ com.streamvault.domain.repository.ProviderDeleteOutcome(+ providerId = 7L,+ pendingCleanupActions = 0,+ reconciliationRequested = true+ )+ )+ )actions.deleteProvider(this, 7L)advanceUntilIdle()@@ -92,9 +111,36 @@ class SettingsProviderActionsTest {assertThat(uiState.value.userMessage).isEqualTo("Provider deleted")}+ @Test+ fun deleteProvider_surfacesLibraryDeletedWhileCleanupIsPending() = runTest(StandardTestDispatcher()) {+ whenever(providerRepository.deleteProvider(eq(7L), any())).thenReturn(+ Result.success(+ com.streamvault.domain.repository.ProviderDeleteOutcome(+ providerId = 7L,+ pendingCleanupActions = 3,+ reconciliationRequested = true+ )+ )+ )++ actions.deleteProvider(this, 7L)+ advanceUntilIdle()++ assertThat(uiState.value.userMessage)+ .isEqualTo("Provider library deleted; final cleanup continues")+ }+@Testfun deleteProvider_stillCompletesSuccessWhenFollowUpRefreshFails() = runTest(StandardTestDispatcher()) {- whenever(providerRepository.deleteProvider(eq(7L), any())).thenReturn(Result.success(Unit))+ whenever(providerRepository.deleteProvider(eq(7L), any())).thenReturn(+ Result.success(+ com.streamvault.domain.repository.ProviderDeleteOutcome(+ providerId = 7L,+ pendingCleanupActions = 0,+ reconciliationRequested = true+ )+ )+ )doThrow(IllegalStateException("refresh boom")).whenever(launcherRecommendationsManager).refreshRecommendations(force = true)var onSuccessCalled = falsediff --git a/app/src/test/java/com/streamvault/app/update/AppUpdateCheckPolicyTest.kt b/app/src/test/java/com/streamvault/app/update/AppUpdateCheckPolicyTest.ktindex 6f4357b9..a2cb5264 100644--- a/app/src/test/java/com/streamvault/app/update/AppUpdateCheckPolicyTest.kt+++ b/app/src/test/java/com/streamvault/app/update/AppUpdateCheckPolicyTest.kt@@ -16,4 +16,10 @@ class AppUpdateCheckPolicyTest {assertThat(AppUpdateCheckPolicy.shouldAutoCheck(1_000L, null, 1_000L)).isFalse()assertThat(AppUpdateCheckPolicy.shouldAutoCheck(901_000L, null, 1_000L)).isTrue()}++ @Test+ fun `future persisted checks do not suppress retry after backward clock jump`() {+ assertThat(AppUpdateCheckPolicy.shouldAutoCheck(1_000L, 1_001L, null)).isTrue()+ assertThat(AppUpdateCheckPolicy.shouldAutoCheck(1_000L, null, 1_001L)).isTrue()+ }}diff --git a/app/src/test/java/com/streamvault/app/update/GitHubReleaseCheckerTest.kt b/app/src/test/java/com/streamvault/app/update/GitHubReleaseCheckerTest.ktindex 500fe9ad..ac9ecd3e 100644--- a/app/src/test/java/com/streamvault/app/update/GitHubReleaseCheckerTest.kt+++ b/app/src/test/java/com/streamvault/app/update/GitHubReleaseCheckerTest.kt@@ -1,7 +1,15 @@package com.streamvault.app.updateimport com.google.common.truth.Truth.assertThat+import java.io.ByteArrayInputStream+import okhttp3.Call+import okhttp3.OkHttpClient+import okhttp3.Response+import okhttp3.ResponseBodyimport org.junit.Test+import org.mockito.kotlin.any+import org.mockito.kotlin.mock+import org.mockito.kotlin.wheneverclass GitHubReleaseCheckerTest {@Test@@ -18,4 +26,41 @@ class GitHubReleaseCheckerTest {assertThat(parseReleaseAssetSha256Digest("sha256:not-a-hash")).isNull()assertThat(parseReleaseAssetSha256Digest("")).isNull()}++ @Test+ fun `http failures are returned as errors`() = kotlinx.coroutines.test.runTest {+ val client = mock<OkHttpClient>()+ val call = mock<Call>()+ val response = mock<Response>()+ whenever(client.newCall(any())).thenReturn(call)+ whenever(call.execute()).thenReturn(response)+ whenever(response.isSuccessful).thenReturn(false)+ whenever(response.code).thenReturn(429)++ val result = GitHubReleaseChecker(client).fetchLatestRelease()++ assertThat(result).isInstanceOf(com.streamvault.domain.model.Result.Error::class.java)+ assertThat((result as com.streamvault.domain.model.Result.Error).message).contains("429")+ }++ @Test+ fun `malformed successful response is returned as an error`() = kotlinx.coroutines.test.runTest {+ val client = mock<OkHttpClient>()+ val call = mock<Call>()+ val response = mock<Response>()+ val body = mock<ResponseBody>()+ whenever(client.newCall(any())).thenReturn(call)+ whenever(call.execute()).thenReturn(response)+ whenever(response.isSuccessful).thenReturn(true)+ whenever(response.body).thenReturn(body)+ whenever(body.contentLength()).thenReturn(-1L)+ whenever(body.contentType()).thenReturn(null)+ whenever(body.byteStream()).thenReturn(ByteArrayInputStream("{not-json".toByteArray()))++ val result = GitHubReleaseChecker(client).fetchLatestRelease()++ assertThat(result).isInstanceOf(com.streamvault.domain.model.Result.Error::class.java)+ assertThat((result as com.streamvault.domain.model.Result.Error).message)+ .contains("Update check failed")+ }}diff --git a/data/build.gradle.kts b/data/build.gradle.ktsindex 3c834090..a0b6ef13 100644--- a/data/build.gradle.kts+++ b/data/build.gradle.kts@@ -14,6 +14,7 @@ android {defaultConfig {minSdk = 25+ testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"}compileOptions {@@ -91,6 +92,8 @@ dependencies {testImplementation(libs.junit)testImplementation(libs.truth)testImplementation(libs.coroutines.test)+ testImplementation(libs.room.testing)+ testImplementation(libs.robolectric)// kxml2: JVM XmlPullParser implementation needed for XmltvParser unit tests// (Android platform provides its own impl; the JVM test runner needs an explicit one)testImplementation(libs.kxml2)@@ -104,3 +107,21 @@ dependencies {androidTestImplementation(libs.truth)androidTestImplementation(libs.coroutines.test)}++afterEvaluate {+ val debugUnitTests = tasks.named<org.gradle.api.tasks.testing.Test>("testDebugUnitTest")+ tasks.register<org.gradle.api.tasks.testing.Test>("lowHeapBackupAdmissionTest") {+ group = "verification"+ description = "Runs backup admission tests with a TV-class constrained heap."+ dependsOn(+ "transformDebugUnitTestClassesWithAsm",+ "processDebugUnitTestJavaRes"+ )+ testClassesDirs = debugUnitTests.get().testClassesDirs+ classpath = debugUnitTests.get().classpath+ maxHeapSize = "128m"+ filter {+ includeTestsMatching("com.streamvault.data.manager.BackupManagerImplTest")+ }+ }+}diff --git a/data/schemas/com.streamvault.data.local.StreamVaultDatabase/67.json b/data/schemas/com.streamvault.data.local.StreamVaultDatabase/67.jsonnew file mode 100644index 00000000..46f060ef--- /dev/null+++ b/data/schemas/com.streamvault.data.local.StreamVaultDatabase/67.json@@ -0,0 +1,5593 @@+{+ "formatVersion": 1,+ "database": {+ "version": 67,+ "identityHash": "653530c59e6e2bd7562d0b3ab0a2ec40",+ "entities": [+ {+ "tableName": "providers",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `type` TEXT NOT NULL, `server_url` TEXT NOT NULL, `username` TEXT NOT NULL, `password` TEXT NOT NULL, `m3u_url` TEXT NOT NULL, `epg_url` TEXT NOT NULL, `http_user_agent` TEXT NOT NULL, `http_headers` TEXT NOT NULL, `stalker_mac_address` TEXT NOT NULL, `stalker_device_profile` TEXT NOT NULL, `stalker_device_timezone` TEXT NOT NULL, `stalker_device_locale` TEXT NOT NULL, `stalker_serial_number` TEXT NOT NULL, `stalker_device_id` TEXT NOT NULL, `stalker_device_id2` TEXT NOT NULL, `stalker_signature` TEXT NOT NULL, `stalker_advanced_options_json` TEXT NOT NULL, `stalker_auth_mode` TEXT NOT NULL, `stalker_portal_profile` TEXT NOT NULL, `stalker_portal_fingerprint` TEXT NOT NULL, `stalker_mag_preset` TEXT NOT NULL, `stalker_last_bootstrap_recipe` TEXT NOT NULL, `stalker_endpoint_preference` TEXT NOT NULL, `stalker_cookie_mode` TEXT NOT NULL, `stalker_playback_backend_hint` TEXT NOT NULL, `stalker_last_playback_mode` TEXT, `stalker_credentials_required` INTEGER NOT NULL, `stalker_mac_required` INTEGER NOT NULL, `stalker_uses_temp_links` INTEGER NOT NULL, `stalker_module_restricted` INTEGER NOT NULL, `stalker_strict_fingerprint_required` INTEGER NOT NULL, `stalker_recipe_fallback_used` INTEGER NOT NULL, `stalker_recipe_rediscovery_attempts` INTEGER NOT NULL, `is_active` INTEGER NOT NULL, `max_connections` INTEGER NOT NULL, `expiration_date` INTEGER, `api_version` TEXT, `allowed_output_formats_json` TEXT NOT NULL, `epg_sync_mode` TEXT NOT NULL, `guide_source_policy` TEXT NOT NULL, `channel_logo_source_policy` TEXT NOT NULL, `xtream_fast_sync_enabled` INTEGER NOT NULL, `xtream_live_sync_mode` TEXT NOT NULL, `m3u_vod_classification_enabled` INTEGER NOT NULL, `status` TEXT NOT NULL, `last_synced_at` INTEGER NOT NULL, `created_at` INTEGER NOT NULL)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "type",+ "columnName": "type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "serverUrl",+ "columnName": "server_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "username",+ "columnName": "username",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "password",+ "columnName": "password",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "m3uUrl",+ "columnName": "m3u_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "epgUrl",+ "columnName": "epg_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "httpUserAgent",+ "columnName": "http_user_agent",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "httpHeaders",+ "columnName": "http_headers",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerMacAddress",+ "columnName": "stalker_mac_address",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerDeviceProfile",+ "columnName": "stalker_device_profile",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerDeviceTimezone",+ "columnName": "stalker_device_timezone",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerDeviceLocale",+ "columnName": "stalker_device_locale",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerSerialNumber",+ "columnName": "stalker_serial_number",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerDeviceId",+ "columnName": "stalker_device_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerDeviceId2",+ "columnName": "stalker_device_id2",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerSignature",+ "columnName": "stalker_signature",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerAdvancedOptionsJson",+ "columnName": "stalker_advanced_options_json",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerAuthMode",+ "columnName": "stalker_auth_mode",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerPortalProfile",+ "columnName": "stalker_portal_profile",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerPortalFingerprint",+ "columnName": "stalker_portal_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerMagPreset",+ "columnName": "stalker_mag_preset",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerLastBootstrapRecipe",+ "columnName": "stalker_last_bootstrap_recipe",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerEndpointPreference",+ "columnName": "stalker_endpoint_preference",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerCookieMode",+ "columnName": "stalker_cookie_mode",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerPlaybackBackendHint",+ "columnName": "stalker_playback_backend_hint",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerLastPlaybackMode",+ "columnName": "stalker_last_playback_mode",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "stalkerCredentialsRequired",+ "columnName": "stalker_credentials_required",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "stalkerMacRequired",+ "columnName": "stalker_mac_required",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "stalkerUsesTemporaryLinks",+ "columnName": "stalker_uses_temp_links",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "stalkerModuleRestricted",+ "columnName": "stalker_module_restricted",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "stalkerStrictFingerprintRequired",+ "columnName": "stalker_strict_fingerprint_required",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "stalkerRecipeFallbackUsed",+ "columnName": "stalker_recipe_fallback_used",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "stalkerRecipeRediscoveryAttempts",+ "columnName": "stalker_recipe_rediscovery_attempts",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isActive",+ "columnName": "is_active",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "maxConnections",+ "columnName": "max_connections",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "expirationDate",+ "columnName": "expiration_date",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "apiVersion",+ "columnName": "api_version",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "allowedOutputFormatsJson",+ "columnName": "allowed_output_formats_json",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "epgSyncMode",+ "columnName": "epg_sync_mode",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "guideSourcePolicy",+ "columnName": "guide_source_policy",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "channelLogoSourcePolicy",+ "columnName": "channel_logo_source_policy",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "xtreamFastSyncEnabled",+ "columnName": "xtream_fast_sync_enabled",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "xtreamLiveSyncMode",+ "columnName": "xtream_live_sync_mode",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "m3uVodClassificationEnabled",+ "columnName": "m3u_vod_classification_enabled",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "status",+ "columnName": "status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "lastSyncedAt",+ "columnName": "last_synced_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_providers_server_url_username_stalker_mac_address",+ "unique": true,+ "columnNames": [+ "server_url",+ "username",+ "stalker_mac_address"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_providers_server_url_username_stalker_mac_address` ON `${TABLE_NAME}` (`server_url`, `username`, `stalker_mac_address`)"+ }+ ]+ },+ {+ "tableName": "channels",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `stream_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `logo_url` TEXT, `group_title` TEXT, `category_id` INTEGER, `category_name` TEXT, `stream_url` TEXT NOT NULL, `epg_channel_id` TEXT, `number` INTEGER NOT NULL, `catch_up_supported` INTEGER NOT NULL, `catch_up_days` INTEGER NOT NULL, `catchUpSource` TEXT, `provider_id` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, `logical_group_id` TEXT NOT NULL, `error_count` INTEGER NOT NULL, `quality_options_json` TEXT, `sync_fingerprint` TEXT NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "streamId",+ "columnName": "stream_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "logoUrl",+ "columnName": "logo_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "groupTitle",+ "columnName": "group_title",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "categoryName",+ "columnName": "category_name",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "epgChannelId",+ "columnName": "epg_channel_id",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "number",+ "columnName": "number",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "catchUpSupported",+ "columnName": "catch_up_supported",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "catchUpDays",+ "columnName": "catch_up_days",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "catchUpSource",+ "columnName": "catchUpSource",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isUserProtected",+ "columnName": "is_user_protected",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "logicalGroupId",+ "columnName": "logical_group_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "errorCount",+ "columnName": "error_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "qualityOptionsJson",+ "columnName": "quality_options_json",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "syncFingerprint",+ "columnName": "sync_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_channels_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_channels_provider_id_category_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "category_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_provider_id_category_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`)"+ },+ {+ "name": "index_channels_provider_id_stream_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "stream_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_channels_provider_id_stream_id` ON `${TABLE_NAME}` (`provider_id`, `stream_id`)"+ },+ {+ "name": "index_channels_logical_group_id",+ "unique": false,+ "columnNames": [+ "logical_group_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_logical_group_id` ON `${TABLE_NAME}` (`logical_group_id`)"+ },+ {+ "name": "index_channels_provider_id_category_id_logical_group_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "category_id",+ "logical_group_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_provider_id_category_id_logical_group_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`, `logical_group_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "channel_preferences",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `channel_id` INTEGER NOT NULL, `aspect_ratio` TEXT, `audio_video_offset_ms` INTEGER, `updated_at` INTEGER NOT NULL, FOREIGN KEY(`channel_id`) REFERENCES `channels`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelId",+ "columnName": "channel_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "aspectRatio",+ "columnName": "aspect_ratio",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "audioVideoOffsetMs",+ "columnName": "audio_video_offset_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_channel_preferences_channel_id",+ "unique": true,+ "columnNames": [+ "channel_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_channel_preferences_channel_id` ON `${TABLE_NAME}` (`channel_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "channels",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "channel_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "channels_fts",+ "createSql": "CREATE VIRTUAL TABLE IF NOT EXISTS `${TABLE_NAME}` USING FTS4(`name` TEXT NOT NULL, content=`channels`)",+ "fields": [+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": []+ },+ "ftsVersion": "FTS4",+ "ftsOptions": {+ "tokenizer": "simple",+ "tokenizerArgs": [],+ "contentTable": "channels",+ "languageIdColumnName": "",+ "matchInfo": "FTS4",+ "notIndexedColumns": [],+ "prefixSizes": [],+ "preferredOrder": "ASC"+ },+ "contentSyncTriggers": [+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_BEFORE_UPDATE BEFORE UPDATE ON `channels` BEGIN DELETE FROM `channels_fts` WHERE `docid`=OLD.`rowid`; END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_BEFORE_DELETE BEFORE DELETE ON `channels` BEGIN DELETE FROM `channels_fts` WHERE `docid`=OLD.`rowid`; END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_AFTER_UPDATE AFTER UPDATE ON `channels` BEGIN INSERT INTO `channels_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_AFTER_INSERT AFTER INSERT ON `channels` BEGIN INSERT INTO `channels_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END"+ ]+ },+ {+ "tableName": "movies",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `stream_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `poster_url` TEXT, `backdrop_url` TEXT, `category_id` INTEGER, `category_name` TEXT, `stream_url` TEXT NOT NULL, `container_extension` TEXT, `plot` TEXT, `cast` TEXT, `director` TEXT, `genre` TEXT, `release_date` TEXT, `duration` TEXT, `duration_seconds` INTEGER NOT NULL, `rating` REAL NOT NULL, `year` TEXT, `tmdb_id` INTEGER, `youtube_trailer` TEXT, `provider_id` INTEGER NOT NULL, `watch_progress` INTEGER NOT NULL, `watch_count` INTEGER NOT NULL, `last_watched_at` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, `added_at` INTEGER NOT NULL, `cache_state` TEXT NOT NULL, `detail_hydrated_at` INTEGER NOT NULL, `remote_stale_at` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "streamId",+ "columnName": "stream_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "posterUrl",+ "columnName": "poster_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "backdropUrl",+ "columnName": "backdrop_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "categoryName",+ "columnName": "category_name",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "containerExtension",+ "columnName": "container_extension",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "plot",+ "columnName": "plot",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "cast",+ "columnName": "cast",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "director",+ "columnName": "director",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "genre",+ "columnName": "genre",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "releaseDate",+ "columnName": "release_date",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "duration",+ "columnName": "duration",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "durationSeconds",+ "columnName": "duration_seconds",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "rating",+ "columnName": "rating",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "year",+ "columnName": "year",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "tmdbId",+ "columnName": "tmdb_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "youtubeTrailer",+ "columnName": "youtube_trailer",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "watchProgress",+ "columnName": "watch_progress",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "watchCount",+ "columnName": "watch_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastWatchedAt",+ "columnName": "last_watched_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isUserProtected",+ "columnName": "is_user_protected",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "syncFingerprint",+ "columnName": "sync_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "addedAt",+ "columnName": "added_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "cacheState",+ "columnName": "cache_state",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "detailHydratedAt",+ "columnName": "detail_hydrated_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "remoteStaleAt",+ "columnName": "remote_stale_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_movies_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_movies_provider_id_category_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "category_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id_category_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`)"+ },+ {+ "name": "index_movies_provider_id_stream_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "stream_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_movies_provider_id_stream_id` ON `${TABLE_NAME}` (`provider_id`, `stream_id`)"+ },+ {+ "name": "index_movies_provider_id_name_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "name",+ "id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id_name_id` ON `${TABLE_NAME}` (`provider_id`, `name`, `id`)"+ },+ {+ "name": "index_movies_provider_id_category_id_name_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "category_id",+ "name",+ "id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id_category_id_name_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`, `name`, `id`)"+ },+ {+ "name": "index_movies_provider_id_rating_name_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "rating",+ "name",+ "id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id_rating_name_id` ON `${TABLE_NAME}` (`provider_id`, `rating`, `name`, `id`)"+ },+ {+ "name": "index_movies_provider_id_added_at_release_date_name_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "added_at",+ "release_date",+ "name",+ "id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id_added_at_release_date_name_id` ON `${TABLE_NAME}` (`provider_id`, `added_at`, `release_date`, `name`, `id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "movies_fts",+ "createSql": "CREATE VIRTUAL TABLE IF NOT EXISTS `${TABLE_NAME}` USING FTS4(`name` TEXT NOT NULL, content=`movies`)",+ "fields": [+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": []+ },+ "ftsVersion": "FTS4",+ "ftsOptions": {+ "tokenizer": "simple",+ "tokenizerArgs": [],+ "contentTable": "movies",+ "languageIdColumnName": "",+ "matchInfo": "FTS4",+ "notIndexedColumns": [],+ "prefixSizes": [],+ "preferredOrder": "ASC"+ },+ "contentSyncTriggers": [+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_movies_fts_BEFORE_UPDATE BEFORE UPDATE ON `movies` BEGIN DELETE FROM `movies_fts` WHERE `docid`=OLD.`rowid`; END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_movies_fts_BEFORE_DELETE BEFORE DELETE ON `movies` BEGIN DELETE FROM `movies_fts` WHERE `docid`=OLD.`rowid`; END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_movies_fts_AFTER_UPDATE AFTER UPDATE ON `movies` BEGIN INSERT INTO `movies_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_movies_fts_AFTER_INSERT AFTER INSERT ON `movies` BEGIN INSERT INTO `movies_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END"+ ]+ },+ {+ "tableName": "series",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `series_id` INTEGER NOT NULL, `provider_series_id` TEXT, `name` TEXT NOT NULL, `poster_url` TEXT, `backdrop_url` TEXT, `category_id` INTEGER, `category_name` TEXT, `plot` TEXT, `cast` TEXT, `director` TEXT, `genre` TEXT, `release_date` TEXT, `rating` REAL NOT NULL, `tmdb_id` INTEGER, `youtube_trailer` TEXT, `episode_run_time` TEXT, `last_modified` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, `cache_state` TEXT NOT NULL, `detail_hydrated_at` INTEGER NOT NULL, `remote_stale_at` INTEGER NOT NULL, 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+ }+ ],+ "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, `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": "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, `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": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "syncFingerprint",+ "columnName": "sync_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "session_id",+ "provider_id",+ "category_id",+ "type"+ ]+ },+ "indices": [+ {+ "name": "index_category_import_stage_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_category_import_stage_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_category_import_stage_session_id_provider_id",+ "unique": false,+ "columnNames": [+ "session_id",+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_category_import_stage_session_id_provider_id` ON `${TABLE_NAME}` (`session_id`, `provider_id`)"+ },+ {+ "name": "index_category_import_stage_provider_id_type",+ "unique": false,+ "columnNames": [+ "provider_id",+ "type"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_category_import_stage_provider_id_type` ON `${TABLE_NAME}` (`provider_id`, `type`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "programs",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `channel_id` TEXT NOT NULL, `title` TEXT NOT NULL, `description` TEXT NOT NULL, `start_time` INTEGER NOT NULL, `end_time` INTEGER NOT NULL, `lang` TEXT NOT NULL, `rating` TEXT, `image_url` TEXT, `genre` TEXT, `category` TEXT, `has_archive` INTEGER NOT NULL)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelId",+ "columnName": "channel_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "title",+ "columnName": "title",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "description",+ "columnName": "description",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "startTime",+ "columnName": "start_time",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "endTime",+ "columnName": "end_time",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lang",+ "columnName": "lang",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "rating",+ "columnName": "rating",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "imageUrl",+ "columnName": "image_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "genre",+ "columnName": "genre",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "category",+ "columnName": "category",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "hasArchive",+ "columnName": "has_archive",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_programs_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_programs_provider_id_channel_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "channel_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_channel_id` ON `${TABLE_NAME}` (`provider_id`, `channel_id`)"+ },+ {+ "name": "index_programs_provider_id_end_time_channel_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "end_time",+ "channel_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_end_time_channel_id` ON `${TABLE_NAME}` (`provider_id`, `end_time`, `channel_id`)"+ },+ {+ "name": "index_programs_provider_id_start_time_end_time",+ "unique": false,+ "columnNames": [+ "provider_id",+ "start_time",+ "end_time"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_start_time_end_time` ON `${TABLE_NAME}` (`provider_id`, `start_time`, `end_time`)"+ },+ {+ "name": "index_programs_start_time",+ "unique": false,+ "columnNames": [+ "start_time"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_start_time` ON `${TABLE_NAME}` (`start_time`)"+ },+ {+ "name": "index_programs_provider_id_channel_id_start_time",+ "unique": false,+ "columnNames": [+ "provider_id",+ "channel_id",+ "start_time"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_channel_id_start_time` ON `${TABLE_NAME}` (`provider_id`, `channel_id`, `start_time`)"+ },+ {+ "name": "index_programs_provider_id_channel_id_start_time_end_time",+ "unique": true,+ "columnNames": [+ "provider_id",+ "channel_id",+ "start_time",+ "end_time"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_programs_provider_id_channel_id_start_time_end_time` ON `${TABLE_NAME}` (`provider_id`, `channel_id`, `start_time`, `end_time`)"+ }+ ]+ },+ {+ "tableName": "favorites",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `content_id` INTEGER NOT NULL, `content_type` TEXT NOT NULL, `position` INTEGER NOT NULL, `group_id` INTEGER, `group_key` INTEGER NOT NULL, `added_at` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`group_id`) REFERENCES `virtual_groups`(`id`) ON UPDATE NO ACTION ON DELETE SET NULL )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentId",+ "columnName": "content_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentType",+ "columnName": "content_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "position",+ "columnName": "position",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "groupId",+ "columnName": "group_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "groupKey",+ "columnName": "group_key",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "addedAt",+ "columnName": "added_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_favorites_provider_id_content_id_content_type_group_key",+ "unique": true,+ "columnNames": [+ "provider_id",+ "content_id",+ "content_type",+ "group_key"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_favorites_provider_id_content_id_content_type_group_key` ON `${TABLE_NAME}` (`provider_id`, `content_id`, `content_type`, `group_key`)"+ },+ {+ "name": "index_favorites_provider_id_content_type_group_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "content_type",+ "group_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_favorites_provider_id_content_type_group_id` ON `${TABLE_NAME}` (`provider_id`, `content_type`, `group_id`)"+ },+ {+ "name": "index_favorites_group_id_position",+ "unique": false,+ "columnNames": [+ "group_id",+ "position"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_favorites_group_id_position` ON `${TABLE_NAME}` (`group_id`, `position`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ },+ {+ "table": "virtual_groups",+ "onDelete": "SET NULL",+ "onUpdate": "NO ACTION",+ "columns": [+ "group_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "virtual_groups",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `icon_emoji` TEXT, `position` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `content_type` TEXT NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "iconEmoji",+ "columnName": "icon_emoji",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "position",+ "columnName": "position",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentType",+ "columnName": "content_type",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_virtual_groups_provider_id_content_type",+ "unique": false,+ "columnNames": [+ "provider_id",+ "content_type"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_virtual_groups_provider_id_content_type` ON `${TABLE_NAME}` (`provider_id`, `content_type`)"+ },+ {+ "name": "index_virtual_groups_position",+ "unique": false,+ "columnNames": [+ "position"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_virtual_groups_position` ON `${TABLE_NAME}` (`position`)"+ },+ {+ "name": "index_virtual_groups_content_type",+ "unique": false,+ "columnNames": [+ "content_type"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_virtual_groups_content_type` ON `${TABLE_NAME}` (`content_type`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "playback_history",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `content_id` INTEGER NOT NULL, `content_type` TEXT NOT NULL, `provider_id` INTEGER NOT NULL, `title` TEXT NOT NULL, `poster_url` TEXT, `stream_url` TEXT NOT NULL, `resume_position_ms` INTEGER NOT NULL, `total_duration_ms` INTEGER NOT NULL, `last_watched_at` INTEGER NOT NULL, `watch_count` INTEGER NOT NULL, `watched_status` TEXT NOT NULL, `series_id` INTEGER, `season_number` INTEGER, `episode_number` INTEGER, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentId",+ "columnName": "content_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentType",+ "columnName": "content_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "title",+ "columnName": "title",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "posterUrl",+ "columnName": "poster_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "resumePositionMs",+ "columnName": "resume_position_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "totalDurationMs",+ "columnName": "total_duration_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastWatchedAt",+ "columnName": "last_watched_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "watchCount",+ "columnName": "watch_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "watchedStatus",+ "columnName": "watched_status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "seriesId",+ "columnName": "series_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "seasonNumber",+ "columnName": "season_number",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "episodeNumber",+ "columnName": "episode_number",+ "affinity": "INTEGER"+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_playback_history_content_id_content_type_provider_id",+ "unique": true,+ "columnNames": [+ "content_id",+ "content_type",+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_playback_history_content_id_content_type_provider_id` ON `${TABLE_NAME}` (`content_id`, `content_type`, `provider_id`)"+ },+ {+ "name": "index_playback_history_last_watched_at",+ "unique": false,+ "columnNames": [+ "last_watched_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_history_last_watched_at` ON `${TABLE_NAME}` (`last_watched_at`)"+ },+ {+ "name": "index_playback_history_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_history_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_playback_history_provider_id_content_type_content_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "content_type",+ "content_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_history_provider_id_content_type_content_id` ON `${TABLE_NAME}` (`provider_id`, `content_type`, `content_id`)"+ },+ {+ "name": "index_playback_history_provider_id_content_type_last_watched_at",+ "unique": false,+ "columnNames": [+ "provider_id",+ "content_type",+ "last_watched_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_history_provider_id_content_type_last_watched_at` ON `${TABLE_NAME}` (`provider_id`, `content_type`, `last_watched_at`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "tmdb_identity",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`tmdb_id` INTEGER NOT NULL, `content_type` TEXT NOT NULL, `canonical_provider_id` INTEGER NOT NULL, `first_seen_at` INTEGER NOT NULL, PRIMARY KEY(`tmdb_id`, `content_type`), FOREIGN KEY(`canonical_provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "tmdbId",+ "columnName": "tmdb_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentType",+ "columnName": "content_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "canonicalProviderId",+ "columnName": "canonical_provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "firstSeenAt",+ "columnName": "first_seen_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "tmdb_id",+ "content_type"+ ]+ },+ "indices": [+ {+ "name": "index_tmdb_identity_content_type",+ "unique": false,+ "columnNames": [+ "content_type"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_tmdb_identity_content_type` ON `${TABLE_NAME}` (`content_type`)"+ },+ {+ "name": "index_tmdb_identity_canonical_provider_id",+ "unique": false,+ "columnNames": [+ "canonical_provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_tmdb_identity_canonical_provider_id` ON `${TABLE_NAME}` (`canonical_provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "canonical_provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "search_history",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `query` TEXT NOT NULL, `content_scope` TEXT NOT NULL, `provider_id` INTEGER NOT NULL, `used_at` INTEGER NOT NULL, `use_count` INTEGER NOT NULL)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "query",+ "columnName": "query",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "contentScope",+ "columnName": "content_scope",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "usedAt",+ "columnName": "used_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "useCount",+ "columnName": "use_count",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_search_history_content_scope_provider_id_used_at",+ "unique": false,+ "columnNames": [+ "content_scope",+ "provider_id",+ "used_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_search_history_content_scope_provider_id_used_at` ON `${TABLE_NAME}` (`content_scope`, `provider_id`, `used_at`)"+ },+ {+ "name": "index_search_history_used_at",+ "unique": false,+ "columnNames": [+ "used_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_search_history_used_at` ON `${TABLE_NAME}` (`used_at`)"+ },+ {+ "name": "index_search_history_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_search_history_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_search_history_query_content_scope_provider_id",+ "unique": true,+ "columnNames": [+ "query",+ "content_scope",+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_search_history_query_content_scope_provider_id` ON `${TABLE_NAME}` (`query`, `content_scope`, `provider_id`)"+ }+ ]+ },+ {+ "tableName": "sync_metadata",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `last_live_sync` INTEGER NOT NULL, `last_live_success` INTEGER NOT NULL, `last_movie_sync` INTEGER NOT NULL, `last_series_sync` INTEGER NOT NULL, `last_series_success` INTEGER NOT NULL, `last_epg_sync` INTEGER NOT NULL, `last_epg_success` INTEGER NOT NULL, `last_movie_attempt` INTEGER NOT NULL, `last_movie_success` INTEGER NOT NULL, `last_movie_partial` INTEGER NOT NULL, `live_count` INTEGER NOT NULL, `movie_count` INTEGER NOT NULL, `series_count` INTEGER NOT NULL, `epg_count` INTEGER NOT NULL, `last_sync_status` TEXT NOT NULL, `movie_sync_mode` TEXT NOT NULL, `movie_warnings_count` INTEGER NOT NULL, `movie_catalog_stale` INTEGER NOT NULL, `live_avoid_full_until` INTEGER NOT NULL, `movie_avoid_full_until` INTEGER NOT NULL, `series_avoid_full_until` INTEGER NOT NULL, `live_sequential_failures_remembered` INTEGER NOT NULL, `live_healthy_sync_streak` INTEGER NOT NULL, `movie_parallel_failures_remembered` INTEGER NOT NULL, `movie_healthy_sync_streak` INTEGER NOT NULL, `series_sequential_failures_remembered` INTEGER NOT NULL, `series_healthy_sync_streak` INTEGER NOT NULL, PRIMARY KEY(`provider_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastLiveSync",+ "columnName": "last_live_sync",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastLiveSuccess",+ "columnName": "last_live_success",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastMovieSync",+ "columnName": "last_movie_sync",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastSeriesSync",+ "columnName": "last_series_sync",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastSeriesSuccess",+ "columnName": "last_series_success",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastEpgSync",+ "columnName": "last_epg_sync",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastEpgSuccess",+ "columnName": "last_epg_success",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastMovieAttempt",+ "columnName": "last_movie_attempt",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastMovieSuccess",+ "columnName": "last_movie_success",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastMoviePartial",+ "columnName": "last_movie_partial",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "liveCount",+ "columnName": "live_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "movieCount",+ "columnName": "movie_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "seriesCount",+ "columnName": "series_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "epgCount",+ "columnName": "epg_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastSyncStatus",+ "columnName": "last_sync_status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "movieSyncMode",+ "columnName": "movie_sync_mode",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "movieWarningsCount",+ "columnName": "movie_warnings_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "movieCatalogStale",+ "columnName": "movie_catalog_stale",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "liveAvoidFullUntil",+ "columnName": "live_avoid_full_until",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "movieAvoidFullUntil",+ "columnName": "movie_avoid_full_until",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "seriesAvoidFullUntil",+ "columnName": "series_avoid_full_until",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "liveSequentialFailuresRemembered",+ "columnName": "live_sequential_failures_remembered",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "liveHealthySyncStreak",+ "columnName": "live_healthy_sync_streak",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "movieParallelFailuresRemembered",+ "columnName": "movie_parallel_failures_remembered",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "movieHealthySyncStreak",+ "columnName": "movie_healthy_sync_streak",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "seriesSequentialFailuresRemembered",+ "columnName": "series_sequential_failures_remembered",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "seriesHealthySyncStreak",+ "columnName": "series_healthy_sync_streak",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "provider_id"+ ]+ },+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "movie_category_hydration",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `category_id` INTEGER NOT NULL, `last_hydrated_at` INTEGER NOT NULL, `item_count` INTEGER NOT NULL, `last_status` TEXT NOT NULL, `last_error` TEXT, `last_loaded_page` INTEGER NOT NULL, `last_attempted_page` INTEGER NOT NULL, `last_successful_page` INTEGER NOT NULL, `total_pages` INTEGER NOT NULL, `is_complete` INTEGER NOT NULL, `page_size` INTEGER NOT NULL, `retry_after_ms` INTEGER NOT NULL, `failure_count` INTEGER NOT NULL, `retry_budget_remaining` INTEGER NOT NULL, `last_page_fingerprint` TEXT, PRIMARY KEY(`provider_id`, `category_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastHydratedAt",+ "columnName": "last_hydrated_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "itemCount",+ "columnName": "item_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastStatus",+ "columnName": "last_status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "lastError",+ "columnName": "last_error",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lastLoadedPage",+ "columnName": "last_loaded_page",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastAttemptedPage",+ "columnName": "last_attempted_page",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastSuccessfulPage",+ "columnName": "last_successful_page",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "totalPages",+ "columnName": "total_pages",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isComplete",+ "columnName": "is_complete",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "pageSize",+ "columnName": "page_size",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "retryAfterMs",+ "columnName": "retry_after_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "failureCount",+ "columnName": "failure_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "retryBudgetRemaining",+ "columnName": "retry_budget_remaining",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastPageFingerprint",+ "columnName": "last_page_fingerprint",+ "affinity": "TEXT"+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "provider_id",+ "category_id"+ ]+ },+ "indices": [+ {+ "name": "index_movie_category_hydration_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movie_category_hydration_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "series_category_hydration",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `category_id` INTEGER NOT NULL, `last_hydrated_at` INTEGER NOT NULL, `item_count` INTEGER NOT NULL, `last_status` TEXT NOT NULL, `last_error` TEXT, `last_loaded_page` INTEGER NOT NULL, `last_attempted_page` INTEGER NOT NULL, `last_successful_page` INTEGER NOT NULL, `total_pages` INTEGER NOT NULL, `is_complete` INTEGER NOT NULL, `page_size` INTEGER NOT NULL, `retry_after_ms` INTEGER NOT NULL, `failure_count` INTEGER NOT NULL, `retry_budget_remaining` INTEGER NOT NULL, `last_page_fingerprint` TEXT, PRIMARY KEY(`provider_id`, `category_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastHydratedAt",+ "columnName": "last_hydrated_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "itemCount",+ "columnName": "item_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastStatus",+ "columnName": "last_status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "lastError",+ "columnName": "last_error",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lastLoadedPage",+ "columnName": "last_loaded_page",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastAttemptedPage",+ "columnName": "last_attempted_page",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastSuccessfulPage",+ "columnName": "last_successful_page",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "totalPages",+ "columnName": "total_pages",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isComplete",+ "columnName": "is_complete",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "pageSize",+ "columnName": "page_size",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "retryAfterMs",+ "columnName": "retry_after_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "failureCount",+ "columnName": "failure_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "retryBudgetRemaining",+ "columnName": "retry_budget_remaining",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastPageFingerprint",+ "columnName": "last_page_fingerprint",+ "affinity": "TEXT"+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "provider_id",+ "category_id"+ ]+ },+ "indices": [+ {+ "name": "index_series_category_hydration_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_category_hydration_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "epg_sources",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `url` TEXT NOT NULL, `enabled` INTEGER NOT NULL, `last_refresh_at` INTEGER NOT NULL, `last_success_at` INTEGER NOT NULL, `last_error` TEXT, `priority` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, `etag` TEXT, `last_modified_header` TEXT)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "url",+ "columnName": "url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "enabled",+ "columnName": "enabled",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastRefreshAt",+ "columnName": "last_refresh_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastSuccessAt",+ "columnName": "last_success_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastError",+ "columnName": "last_error",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "priority",+ "columnName": "priority",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "etag",+ "columnName": "etag",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lastModifiedHeader",+ "columnName": "last_modified_header",+ "affinity": "TEXT"+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_epg_sources_url",+ "unique": true,+ "columnNames": [+ "url"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_epg_sources_url` ON `${TABLE_NAME}` (`url`)"+ }+ ]+ },+ {+ "tableName": "provider_epg_sources",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `epg_source_id` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `enabled` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`epg_source_id`) REFERENCES `epg_sources`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "epgSourceId",+ "columnName": "epg_source_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "priority",+ "columnName": "priority",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "enabled",+ "columnName": "enabled",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_provider_epg_sources_provider_id_epg_source_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "epg_source_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_provider_epg_sources_provider_id_epg_source_id` ON `${TABLE_NAME}` (`provider_id`, `epg_source_id`)"+ },+ {+ "name": "index_provider_epg_sources_epg_source_id",+ "unique": false,+ "columnNames": [+ "epg_source_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_provider_epg_sources_epg_source_id` ON `${TABLE_NAME}` (`epg_source_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ },+ {+ "table": "epg_sources",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "epg_source_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "epg_channels",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `epg_source_id` INTEGER NOT NULL, `xmltv_channel_id` TEXT NOT NULL, `display_name` TEXT NOT NULL, `normalized_name` TEXT NOT NULL, `icon_url` TEXT, FOREIGN KEY(`epg_source_id`) REFERENCES `epg_sources`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "epgSourceId",+ "columnName": "epg_source_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "xmltvChannelId",+ "columnName": "xmltv_channel_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "displayName",+ "columnName": "display_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "normalizedName",+ "columnName": "normalized_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "iconUrl",+ "columnName": "icon_url",+ "affinity": "TEXT"+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_epg_channels_epg_source_id_xmltv_channel_id",+ "unique": true,+ "columnNames": [+ "epg_source_id",+ "xmltv_channel_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_epg_channels_epg_source_id_xmltv_channel_id` ON `${TABLE_NAME}` (`epg_source_id`, `xmltv_channel_id`)"+ },+ {+ "name": "index_epg_channels_epg_source_id",+ "unique": false,+ "columnNames": [+ "epg_source_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_channels_epg_source_id` ON `${TABLE_NAME}` (`epg_source_id`)"+ },+ {+ "name": "index_epg_channels_normalized_name",+ "unique": false,+ "columnNames": [+ "normalized_name"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_channels_normalized_name` ON `${TABLE_NAME}` (`normalized_name`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "epg_sources",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "epg_source_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "epg_programmes",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `epg_source_id` INTEGER NOT NULL, `xmltv_channel_id` TEXT NOT NULL, `start_time` INTEGER NOT NULL, `end_time` INTEGER NOT NULL, `title` TEXT NOT NULL, `subtitle` TEXT, `description` TEXT NOT NULL, `category` TEXT, `lang` TEXT NOT NULL, `rating` TEXT, `image_url` TEXT, `episode_info` TEXT, FOREIGN KEY(`epg_source_id`) REFERENCES `epg_sources`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "epgSourceId",+ "columnName": "epg_source_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "xmltvChannelId",+ "columnName": "xmltv_channel_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "startTime",+ "columnName": "start_time",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "endTime",+ "columnName": "end_time",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "title",+ "columnName": "title",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "subtitle",+ "columnName": "subtitle",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "description",+ "columnName": "description",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "category",+ "columnName": "category",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lang",+ "columnName": "lang",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "rating",+ "columnName": "rating",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "imageUrl",+ "columnName": "image_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "episodeInfo",+ "columnName": "episode_info",+ "affinity": "TEXT"+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_epg_programmes_epg_source_id_xmltv_channel_id_start_time",+ "unique": false,+ "columnNames": [+ "epg_source_id",+ "xmltv_channel_id",+ "start_time"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_programmes_epg_source_id_xmltv_channel_id_start_time` ON `${TABLE_NAME}` (`epg_source_id`, `xmltv_channel_id`, `start_time`)"+ },+ {+ "name": "index_epg_programmes_epg_source_id_xmltv_channel_id_start_time_end_time",+ "unique": true,+ "columnNames": [+ "epg_source_id",+ "xmltv_channel_id",+ "start_time",+ "end_time"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_epg_programmes_epg_source_id_xmltv_channel_id_start_time_end_time` ON `${TABLE_NAME}` (`epg_source_id`, `xmltv_channel_id`, `start_time`, `end_time`)"+ },+ {+ "name": "index_epg_programmes_epg_source_id",+ "unique": false,+ "columnNames": [+ "epg_source_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_programmes_epg_source_id` ON `${TABLE_NAME}` (`epg_source_id`)"+ },+ {+ "name": "index_epg_programmes_start_time",+ "unique": false,+ "columnNames": [+ "start_time"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_programmes_start_time` ON `${TABLE_NAME}` (`start_time`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "epg_sources",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "epg_source_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "channel_epg_mappings",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_channel_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `source_type` TEXT NOT NULL, `epg_source_id` INTEGER, `xmltv_channel_id` TEXT, `match_type` TEXT, `confidence` REAL NOT NULL, `matched_at` INTEGER NOT NULL, `failed_attempts` INTEGER NOT NULL, `source` TEXT, `is_manual_override` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerChannelId",+ "columnName": "provider_channel_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "sourceType",+ "columnName": "source_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "epgSourceId",+ "columnName": "epg_source_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "xmltvChannelId",+ "columnName": "xmltv_channel_id",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "matchType",+ "columnName": "match_type",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "confidence",+ "columnName": "confidence",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "matchedAt",+ "columnName": "matched_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "failedAttempts",+ "columnName": "failed_attempts",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "source",+ "columnName": "source",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "isManualOverride",+ "columnName": "is_manual_override",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_channel_epg_mappings_provider_id_provider_channel_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "provider_channel_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_channel_epg_mappings_provider_id_provider_channel_id` ON `${TABLE_NAME}` (`provider_id`, `provider_channel_id`)"+ },+ {+ "name": "index_channel_epg_mappings_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channel_epg_mappings_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "combined_m3u_profiles",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `enabled` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "enabled",+ "columnName": "enabled",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ }+ },+ {+ "tableName": "combined_m3u_profile_members",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `profile_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `enabled` INTEGER NOT NULL, FOREIGN KEY(`profile_id`) REFERENCES `combined_m3u_profiles`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "profileId",+ "columnName": "profile_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "priority",+ "columnName": "priority",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "enabled",+ "columnName": "enabled",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_combined_m3u_profile_members_profile_id",+ "unique": false,+ "columnNames": [+ "profile_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_combined_m3u_profile_members_profile_id` ON `${TABLE_NAME}` (`profile_id`)"+ },+ {+ "name": "index_combined_m3u_profile_members_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_combined_m3u_profile_members_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_combined_m3u_profile_members_profile_id_provider_id",+ "unique": true,+ "columnNames": [+ "profile_id",+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_combined_m3u_profile_members_profile_id_provider_id` ON `${TABLE_NAME}` (`profile_id`, `provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "combined_m3u_profiles",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "profile_id"+ ],+ "referencedColumns": [+ "id"+ ]+ },+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "recording_schedules",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, `channel_name` TEXT NOT NULL, `stream_url` TEXT NOT NULL, `program_title` TEXT, `requested_start_ms` INTEGER NOT NULL, `requested_end_ms` INTEGER NOT NULL, `recurrence` TEXT NOT NULL, `recurring_rule_id` TEXT, `enabled` INTEGER NOT NULL, `is_manual` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelId",+ "columnName": "channel_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelName",+ "columnName": "channel_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "programTitle",+ "columnName": "program_title",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "requestedStartMs",+ "columnName": "requested_start_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "requestedEndMs",+ "columnName": "requested_end_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "recurrence",+ "columnName": "recurrence",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "recurringRuleId",+ "columnName": "recurring_rule_id",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "enabled",+ "columnName": "enabled",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isManual",+ "columnName": "is_manual",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "priority",+ "columnName": "priority",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_recording_schedules_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_schedules_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_recording_schedules_enabled_requested_start_ms",+ "unique": false,+ "columnNames": [+ "enabled",+ "requested_start_ms"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_schedules_enabled_requested_start_ms` ON `${TABLE_NAME}` (`enabled`, `requested_start_ms`)"+ },+ {+ "name": "index_recording_schedules_recurring_rule_id",+ "unique": false,+ "columnNames": [+ "recurring_rule_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_schedules_recurring_rule_id` ON `${TABLE_NAME}` (`recurring_rule_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "recording_runs",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `schedule_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, `channel_name` TEXT NOT NULL, `stream_url` TEXT NOT NULL, `program_title` TEXT, `scheduled_start_ms` INTEGER NOT NULL, `scheduled_end_ms` INTEGER NOT NULL, `recurrence` TEXT NOT NULL, `recurring_rule_id` TEXT, `status` TEXT NOT NULL, `source_type` TEXT NOT NULL, `resolved_url` TEXT, `headers_json` TEXT NOT NULL, `user_agent` TEXT, `expiration_time` INTEGER, `provider_label` TEXT, `output_uri` TEXT, `output_display_path` TEXT, `bytes_written` INTEGER NOT NULL, `average_throughput_bps` INTEGER NOT NULL, `retry_count` INTEGER NOT NULL, `last_progress_at_ms` INTEGER, `failure_category` TEXT NOT NULL, `failure_reason` TEXT, `terminal_at_ms` INTEGER, `started_at_ms` INTEGER, `ended_at_ms` INTEGER, `schedule_enabled` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `alarm_start_at_ms` INTEGER, `alarm_stop_at_ms` INTEGER, `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, `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": "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": "downloads",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `provider_id` INTEGER NOT NULL, `content_type` TEXT NOT NULL, `content_id` INTEGER NOT NULL, `content_name` TEXT NOT NULL, `stream_url` TEXT NOT NULL, `source_stream_url` TEXT, `source_stream_id` INTEGER, `container_extension` TEXT, `poster_url` TEXT, `output_uri` TEXT, `output_display_path` TEXT, `status` TEXT NOT NULL, `bytes_written` INTEGER NOT NULL, `total_bytes` INTEGER, `supports_resume` INTEGER NOT NULL, `retry_count` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `completed_at` INTEGER, `failure_reason` TEXT, `series_id` INTEGER, `season_number` INTEGER, `episode_number` INTEGER, PRIMARY KEY(`id`))",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentType",+ "columnName": "content_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "contentId",+ "columnName": "content_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentName",+ "columnName": "content_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "sourceStreamUrl",+ "columnName": "source_stream_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "sourceStreamId",+ "columnName": "source_stream_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "containerExtension",+ "columnName": "container_extension",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "posterUrl",+ "columnName": "poster_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "outputUri",+ "columnName": "output_uri",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "outputDisplayPath",+ "columnName": "output_display_path",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "status",+ "columnName": "status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "bytesWritten",+ "columnName": "bytes_written",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "totalBytes",+ "columnName": "total_bytes",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "supportsResume",+ "columnName": "supports_resume",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "retryCount",+ "columnName": "retry_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "completedAt",+ "columnName": "completed_at",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "failureReason",+ "columnName": "failure_reason",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "seriesId",+ "columnName": "series_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "seasonNumber",+ "columnName": "season_number",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "episodeNumber",+ "columnName": "episode_number",+ "affinity": "INTEGER"+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_downloads_status",+ "unique": false,+ "columnNames": [+ "status"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_downloads_status` ON `${TABLE_NAME}` (`status`)"+ },+ {+ "name": "index_downloads_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_downloads_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_downloads_content_type_content_id",+ "unique": false,+ "columnNames": [+ "content_type",+ "content_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_downloads_content_type_content_id` ON `${TABLE_NAME}` (`content_type`, `content_id`)"+ }+ ]+ },+ {+ "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"+ ]+ }+ ]+ }+ ],+ "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, '653530c59e6e2bd7562d0b3ab0a2ec40')"+ ]+ }+}\ No newline at end of filediff --git a/data/schemas/com.streamvault.data.local.StreamVaultDatabase/68.json b/data/schemas/com.streamvault.data.local.StreamVaultDatabase/68.jsonnew file mode 100644index 00000000..de702b0a--- /dev/null+++ b/data/schemas/com.streamvault.data.local.StreamVaultDatabase/68.json@@ -0,0 +1,5663 @@+{+ "formatVersion": 1,+ "database": {+ "version": 68,+ "identityHash": "5602ff82f4270e22b880b71c8401731d",+ "entities": [+ {+ "tableName": "providers",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `type` TEXT NOT NULL, `server_url` TEXT NOT NULL, `username` TEXT NOT NULL, `password` TEXT NOT NULL, `m3u_url` TEXT NOT NULL, `epg_url` TEXT NOT NULL, `http_user_agent` TEXT NOT NULL, `http_headers` TEXT NOT NULL, `stalker_mac_address` TEXT NOT NULL, `stalker_device_profile` TEXT NOT NULL, `stalker_device_timezone` TEXT NOT NULL, `stalker_device_locale` TEXT NOT NULL, `stalker_serial_number` TEXT NOT NULL, `stalker_device_id` TEXT NOT NULL, `stalker_device_id2` TEXT NOT NULL, `stalker_signature` TEXT NOT NULL, `stalker_advanced_options_json` TEXT NOT NULL, `stalker_auth_mode` TEXT NOT NULL, `stalker_portal_profile` TEXT NOT NULL, `stalker_portal_fingerprint` TEXT NOT NULL, `stalker_mag_preset` TEXT NOT NULL, `stalker_last_bootstrap_recipe` TEXT NOT NULL, `stalker_endpoint_preference` TEXT NOT NULL, `stalker_cookie_mode` TEXT NOT NULL, `stalker_playback_backend_hint` TEXT NOT NULL, `stalker_last_playback_mode` TEXT, `stalker_credentials_required` INTEGER NOT NULL, `stalker_mac_required` INTEGER NOT NULL, `stalker_uses_temp_links` INTEGER NOT NULL, `stalker_module_restricted` INTEGER NOT NULL, `stalker_strict_fingerprint_required` INTEGER NOT NULL, `stalker_recipe_fallback_used` INTEGER NOT NULL, `stalker_recipe_rediscovery_attempts` INTEGER NOT NULL, `is_active` INTEGER NOT NULL, `max_connections` INTEGER NOT NULL, `expiration_date` INTEGER, `api_version` TEXT, `allowed_output_formats_json` TEXT NOT NULL, `epg_sync_mode` TEXT NOT NULL, `guide_source_policy` TEXT NOT NULL, `channel_logo_source_policy` TEXT NOT NULL, `xtream_fast_sync_enabled` INTEGER NOT NULL, `xtream_live_sync_mode` TEXT NOT NULL, `m3u_vod_classification_enabled` INTEGER NOT NULL, `status` TEXT NOT NULL, `last_synced_at` INTEGER NOT NULL, `created_at` INTEGER NOT NULL)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "type",+ "columnName": "type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "serverUrl",+ "columnName": "server_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "username",+ "columnName": "username",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "password",+ "columnName": "password",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "m3uUrl",+ "columnName": "m3u_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "epgUrl",+ "columnName": "epg_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "httpUserAgent",+ "columnName": "http_user_agent",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "httpHeaders",+ "columnName": "http_headers",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerMacAddress",+ "columnName": "stalker_mac_address",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerDeviceProfile",+ "columnName": "stalker_device_profile",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerDeviceTimezone",+ "columnName": "stalker_device_timezone",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerDeviceLocale",+ "columnName": "stalker_device_locale",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerSerialNumber",+ "columnName": "stalker_serial_number",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerDeviceId",+ "columnName": "stalker_device_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerDeviceId2",+ "columnName": "stalker_device_id2",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerSignature",+ "columnName": "stalker_signature",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerAdvancedOptionsJson",+ "columnName": "stalker_advanced_options_json",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerAuthMode",+ "columnName": "stalker_auth_mode",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerPortalProfile",+ "columnName": "stalker_portal_profile",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerPortalFingerprint",+ "columnName": "stalker_portal_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerMagPreset",+ "columnName": "stalker_mag_preset",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerLastBootstrapRecipe",+ "columnName": "stalker_last_bootstrap_recipe",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerEndpointPreference",+ "columnName": "stalker_endpoint_preference",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerCookieMode",+ "columnName": "stalker_cookie_mode",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerPlaybackBackendHint",+ "columnName": "stalker_playback_backend_hint",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerLastPlaybackMode",+ "columnName": "stalker_last_playback_mode",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "stalkerCredentialsRequired",+ "columnName": "stalker_credentials_required",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "stalkerMacRequired",+ "columnName": "stalker_mac_required",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "stalkerUsesTemporaryLinks",+ "columnName": "stalker_uses_temp_links",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "stalkerModuleRestricted",+ "columnName": "stalker_module_restricted",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "stalkerStrictFingerprintRequired",+ "columnName": "stalker_strict_fingerprint_required",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "stalkerRecipeFallbackUsed",+ "columnName": "stalker_recipe_fallback_used",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "stalkerRecipeRediscoveryAttempts",+ "columnName": "stalker_recipe_rediscovery_attempts",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isActive",+ "columnName": "is_active",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "maxConnections",+ "columnName": "max_connections",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "expirationDate",+ "columnName": "expiration_date",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "apiVersion",+ "columnName": "api_version",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "allowedOutputFormatsJson",+ "columnName": "allowed_output_formats_json",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "epgSyncMode",+ "columnName": "epg_sync_mode",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "guideSourcePolicy",+ "columnName": "guide_source_policy",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "channelLogoSourcePolicy",+ "columnName": "channel_logo_source_policy",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "xtreamFastSyncEnabled",+ "columnName": "xtream_fast_sync_enabled",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "xtreamLiveSyncMode",+ "columnName": "xtream_live_sync_mode",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "m3uVodClassificationEnabled",+ "columnName": "m3u_vod_classification_enabled",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "status",+ "columnName": "status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "lastSyncedAt",+ "columnName": "last_synced_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_providers_server_url_username_stalker_mac_address",+ "unique": true,+ "columnNames": [+ "server_url",+ "username",+ "stalker_mac_address"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_providers_server_url_username_stalker_mac_address` ON `${TABLE_NAME}` (`server_url`, `username`, `stalker_mac_address`)"+ }+ ]+ },+ {+ "tableName": "channels",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `stream_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `logo_url` TEXT, `group_title` TEXT, `category_id` INTEGER, `category_name` TEXT, `stream_url` TEXT NOT NULL, `epg_channel_id` TEXT, `number` INTEGER NOT NULL, `catch_up_supported` INTEGER NOT NULL, `catch_up_days` INTEGER NOT NULL, `catchUpSource` TEXT, `provider_id` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, `logical_group_id` TEXT NOT NULL, `error_count` INTEGER NOT NULL, `quality_options_json` TEXT, `sync_fingerprint` TEXT NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "streamId",+ "columnName": "stream_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "logoUrl",+ "columnName": "logo_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "groupTitle",+ "columnName": "group_title",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "categoryName",+ "columnName": "category_name",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "epgChannelId",+ "columnName": "epg_channel_id",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "number",+ "columnName": "number",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "catchUpSupported",+ "columnName": "catch_up_supported",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "catchUpDays",+ "columnName": "catch_up_days",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "catchUpSource",+ "columnName": "catchUpSource",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isUserProtected",+ "columnName": "is_user_protected",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "logicalGroupId",+ "columnName": "logical_group_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "errorCount",+ "columnName": "error_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "qualityOptionsJson",+ "columnName": "quality_options_json",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "syncFingerprint",+ "columnName": "sync_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_channels_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_channels_provider_id_category_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "category_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_provider_id_category_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`)"+ },+ {+ "name": "index_channels_provider_id_stream_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "stream_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_channels_provider_id_stream_id` ON `${TABLE_NAME}` (`provider_id`, `stream_id`)"+ },+ {+ "name": "index_channels_logical_group_id",+ "unique": false,+ "columnNames": [+ "logical_group_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_logical_group_id` ON `${TABLE_NAME}` (`logical_group_id`)"+ },+ {+ "name": "index_channels_provider_id_category_id_logical_group_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "category_id",+ "logical_group_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_provider_id_category_id_logical_group_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`, `logical_group_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "channel_preferences",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `channel_id` INTEGER NOT NULL, `aspect_ratio` TEXT, `audio_video_offset_ms` INTEGER, `updated_at` INTEGER NOT NULL, FOREIGN KEY(`channel_id`) REFERENCES `channels`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelId",+ "columnName": "channel_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "aspectRatio",+ "columnName": "aspect_ratio",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "audioVideoOffsetMs",+ "columnName": "audio_video_offset_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_channel_preferences_channel_id",+ "unique": true,+ "columnNames": [+ "channel_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_channel_preferences_channel_id` ON `${TABLE_NAME}` (`channel_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "channels",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "channel_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "channels_fts",+ "createSql": "CREATE VIRTUAL TABLE IF NOT EXISTS `${TABLE_NAME}` USING FTS4(`name` TEXT NOT NULL, content=`channels`)",+ "fields": [+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": []+ },+ "ftsVersion": "FTS4",+ "ftsOptions": {+ "tokenizer": "simple",+ "tokenizerArgs": [],+ "contentTable": "channels",+ "languageIdColumnName": "",+ "matchInfo": "FTS4",+ "notIndexedColumns": [],+ "prefixSizes": [],+ "preferredOrder": "ASC"+ },+ "contentSyncTriggers": [+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_BEFORE_UPDATE BEFORE UPDATE ON `channels` BEGIN DELETE FROM `channels_fts` WHERE `docid`=OLD.`rowid`; END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_BEFORE_DELETE BEFORE DELETE ON `channels` BEGIN DELETE FROM `channels_fts` WHERE `docid`=OLD.`rowid`; END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_AFTER_UPDATE AFTER UPDATE ON `channels` BEGIN INSERT INTO `channels_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_AFTER_INSERT AFTER INSERT ON `channels` BEGIN INSERT INTO `channels_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END"+ ]+ },+ {+ "tableName": "movies",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `stream_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `poster_url` TEXT, `backdrop_url` TEXT, `category_id` INTEGER, `category_name` TEXT, `stream_url` TEXT NOT NULL, `container_extension` TEXT, `plot` TEXT, `cast` TEXT, `director` TEXT, `genre` TEXT, `release_date` TEXT, `duration` TEXT, `duration_seconds` INTEGER NOT NULL, `rating` REAL NOT NULL, `year` TEXT, `tmdb_id` INTEGER, `youtube_trailer` TEXT, `provider_id` INTEGER NOT NULL, `watch_progress` INTEGER NOT NULL, `watch_count` INTEGER NOT NULL, `last_watched_at` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, `added_at` INTEGER NOT NULL, `cache_state` TEXT NOT NULL, `detail_hydrated_at` INTEGER NOT NULL, `remote_stale_at` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "streamId",+ "columnName": "stream_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "posterUrl",+ "columnName": "poster_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "backdropUrl",+ "columnName": "backdrop_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "categoryName",+ "columnName": "category_name",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "containerExtension",+ "columnName": "container_extension",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "plot",+ "columnName": "plot",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "cast",+ "columnName": "cast",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "director",+ "columnName": "director",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "genre",+ "columnName": "genre",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "releaseDate",+ "columnName": "release_date",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "duration",+ "columnName": "duration",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "durationSeconds",+ "columnName": "duration_seconds",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "rating",+ "columnName": "rating",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "year",+ "columnName": "year",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "tmdbId",+ "columnName": "tmdb_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "youtubeTrailer",+ "columnName": "youtube_trailer",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "watchProgress",+ "columnName": "watch_progress",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "watchCount",+ "columnName": "watch_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastWatchedAt",+ "columnName": "last_watched_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isUserProtected",+ "columnName": "is_user_protected",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "syncFingerprint",+ "columnName": "sync_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "addedAt",+ "columnName": "added_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "cacheState",+ "columnName": "cache_state",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "detailHydratedAt",+ "columnName": "detail_hydrated_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "remoteStaleAt",+ "columnName": "remote_stale_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_movies_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_movies_provider_id_category_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "category_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id_category_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`)"+ },+ {+ "name": "index_movies_provider_id_stream_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "stream_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_movies_provider_id_stream_id` ON `${TABLE_NAME}` (`provider_id`, `stream_id`)"+ },+ {+ "name": "index_movies_provider_id_name_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "name",+ "id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id_name_id` ON `${TABLE_NAME}` (`provider_id`, `name`, `id`)"+ },+ {+ "name": "index_movies_provider_id_category_id_name_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "category_id",+ "name",+ "id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id_category_id_name_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`, `name`, `id`)"+ },+ {+ "name": "index_movies_provider_id_rating_name_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "rating",+ "name",+ "id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id_rating_name_id` ON `${TABLE_NAME}` (`provider_id`, `rating`, `name`, `id`)"+ },+ {+ "name": "index_movies_provider_id_added_at_release_date_name_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "added_at",+ "release_date",+ "name",+ "id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id_added_at_release_date_name_id` ON `${TABLE_NAME}` (`provider_id`, `added_at`, `release_date`, `name`, `id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "movies_fts",+ "createSql": "CREATE VIRTUAL TABLE IF NOT EXISTS `${TABLE_NAME}` USING FTS4(`name` TEXT NOT NULL, content=`movies`)",+ "fields": [+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": []+ },+ "ftsVersion": "FTS4",+ "ftsOptions": {+ "tokenizer": "simple",+ "tokenizerArgs": [],+ "contentTable": "movies",+ "languageIdColumnName": "",+ "matchInfo": "FTS4",+ "notIndexedColumns": [],+ "prefixSizes": [],+ "preferredOrder": "ASC"+ },+ "contentSyncTriggers": [+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_movies_fts_BEFORE_UPDATE BEFORE UPDATE ON `movies` BEGIN DELETE FROM `movies_fts` WHERE `docid`=OLD.`rowid`; END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_movies_fts_BEFORE_DELETE BEFORE DELETE ON `movies` BEGIN DELETE FROM `movies_fts` WHERE `docid`=OLD.`rowid`; END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_movies_fts_AFTER_UPDATE AFTER UPDATE ON `movies` BEGIN INSERT INTO `movies_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_movies_fts_AFTER_INSERT AFTER INSERT ON `movies` BEGIN INSERT INTO `movies_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END"+ ]+ },+ {+ "tableName": "series",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `series_id` INTEGER NOT NULL, `provider_series_id` TEXT, `name` TEXT NOT NULL, `poster_url` TEXT, `backdrop_url` TEXT, `category_id` INTEGER, `category_name` TEXT, `plot` TEXT, `cast` TEXT, `director` TEXT, `genre` TEXT, `release_date` TEXT, `rating` REAL NOT NULL, `tmdb_id` INTEGER, `youtube_trailer` TEXT, `episode_run_time` TEXT, `last_modified` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, `cache_state` TEXT NOT NULL, `detail_hydrated_at` INTEGER NOT NULL, `remote_stale_at` INTEGER NOT NULL, 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+ }+ ],+ "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, `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": "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, `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": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "syncFingerprint",+ "columnName": "sync_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "session_id",+ "provider_id",+ "category_id",+ "type"+ ]+ },+ "indices": [+ {+ "name": "index_category_import_stage_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_category_import_stage_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_category_import_stage_session_id_provider_id",+ "unique": false,+ "columnNames": [+ "session_id",+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_category_import_stage_session_id_provider_id` ON `${TABLE_NAME}` (`session_id`, `provider_id`)"+ },+ {+ "name": "index_category_import_stage_provider_id_type",+ "unique": false,+ "columnNames": [+ "provider_id",+ "type"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_category_import_stage_provider_id_type` ON `${TABLE_NAME}` (`provider_id`, `type`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "programs",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `channel_id` TEXT NOT NULL, `title` TEXT NOT NULL, `description` TEXT NOT NULL, `start_time` INTEGER NOT NULL, `end_time` INTEGER NOT NULL, `lang` TEXT NOT NULL, `rating` TEXT, `image_url` TEXT, `genre` TEXT, `category` TEXT, `has_archive` INTEGER NOT NULL)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelId",+ "columnName": "channel_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "title",+ "columnName": "title",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "description",+ "columnName": "description",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "startTime",+ "columnName": "start_time",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "endTime",+ "columnName": "end_time",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lang",+ "columnName": "lang",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "rating",+ "columnName": "rating",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "imageUrl",+ "columnName": "image_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "genre",+ "columnName": "genre",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "category",+ "columnName": "category",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "hasArchive",+ "columnName": "has_archive",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_programs_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_programs_provider_id_channel_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "channel_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_channel_id` ON `${TABLE_NAME}` (`provider_id`, `channel_id`)"+ },+ {+ "name": "index_programs_provider_id_end_time_channel_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "end_time",+ "channel_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_end_time_channel_id` ON `${TABLE_NAME}` (`provider_id`, `end_time`, `channel_id`)"+ },+ {+ "name": "index_programs_provider_id_start_time_end_time",+ "unique": false,+ "columnNames": [+ "provider_id",+ "start_time",+ "end_time"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_start_time_end_time` ON `${TABLE_NAME}` (`provider_id`, `start_time`, `end_time`)"+ },+ {+ "name": "index_programs_start_time",+ "unique": false,+ "columnNames": [+ "start_time"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_start_time` ON `${TABLE_NAME}` (`start_time`)"+ },+ {+ "name": "index_programs_provider_id_channel_id_start_time",+ "unique": false,+ "columnNames": [+ "provider_id",+ "channel_id",+ "start_time"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_channel_id_start_time` ON `${TABLE_NAME}` (`provider_id`, `channel_id`, `start_time`)"+ },+ {+ "name": "index_programs_provider_id_channel_id_start_time_end_time",+ "unique": true,+ "columnNames": [+ "provider_id",+ "channel_id",+ "start_time",+ "end_time"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_programs_provider_id_channel_id_start_time_end_time` ON `${TABLE_NAME}` (`provider_id`, `channel_id`, `start_time`, `end_time`)"+ }+ ]+ },+ {+ "tableName": "favorites",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `content_id` INTEGER NOT NULL, `content_type` TEXT NOT NULL, `position` INTEGER NOT NULL, `group_id` INTEGER, `group_key` INTEGER NOT NULL, `added_at` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`group_id`) REFERENCES `virtual_groups`(`id`) ON UPDATE NO ACTION ON DELETE SET NULL )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentId",+ "columnName": "content_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentType",+ "columnName": "content_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "position",+ "columnName": "position",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "groupId",+ "columnName": "group_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "groupKey",+ "columnName": "group_key",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "addedAt",+ "columnName": "added_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_favorites_provider_id_content_id_content_type_group_key",+ "unique": true,+ "columnNames": [+ "provider_id",+ "content_id",+ "content_type",+ "group_key"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_favorites_provider_id_content_id_content_type_group_key` ON `${TABLE_NAME}` (`provider_id`, `content_id`, `content_type`, `group_key`)"+ },+ {+ "name": "index_favorites_provider_id_content_type_group_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "content_type",+ "group_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_favorites_provider_id_content_type_group_id` ON `${TABLE_NAME}` (`provider_id`, `content_type`, `group_id`)"+ },+ {+ "name": "index_favorites_group_id_position",+ "unique": false,+ "columnNames": [+ "group_id",+ "position"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_favorites_group_id_position` ON `${TABLE_NAME}` (`group_id`, `position`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ },+ {+ "table": "virtual_groups",+ "onDelete": "SET NULL",+ "onUpdate": "NO ACTION",+ "columns": [+ "group_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "virtual_groups",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `icon_emoji` TEXT, `position` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `content_type` TEXT NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "iconEmoji",+ "columnName": "icon_emoji",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "position",+ "columnName": "position",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentType",+ "columnName": "content_type",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_virtual_groups_provider_id_content_type",+ "unique": false,+ "columnNames": [+ "provider_id",+ "content_type"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_virtual_groups_provider_id_content_type` ON `${TABLE_NAME}` (`provider_id`, `content_type`)"+ },+ {+ "name": "index_virtual_groups_position",+ "unique": false,+ "columnNames": [+ "position"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_virtual_groups_position` ON `${TABLE_NAME}` (`position`)"+ },+ {+ "name": "index_virtual_groups_content_type",+ "unique": false,+ "columnNames": [+ "content_type"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_virtual_groups_content_type` ON `${TABLE_NAME}` (`content_type`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "playback_history",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `content_id` INTEGER NOT NULL, `content_type` TEXT NOT NULL, `provider_id` INTEGER NOT NULL, `title` TEXT NOT NULL, `poster_url` TEXT, `stream_url` TEXT NOT NULL, `resume_position_ms` INTEGER NOT NULL, `total_duration_ms` INTEGER NOT NULL, `last_watched_at` INTEGER NOT NULL, `watch_count` INTEGER NOT NULL, `watched_status` TEXT NOT NULL, `series_id` INTEGER, `season_number` INTEGER, `episode_number` INTEGER, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentId",+ "columnName": "content_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentType",+ "columnName": "content_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "title",+ "columnName": "title",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "posterUrl",+ "columnName": "poster_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "resumePositionMs",+ "columnName": "resume_position_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "totalDurationMs",+ "columnName": "total_duration_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastWatchedAt",+ "columnName": "last_watched_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "watchCount",+ "columnName": "watch_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "watchedStatus",+ "columnName": "watched_status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "seriesId",+ "columnName": "series_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "seasonNumber",+ "columnName": "season_number",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "episodeNumber",+ "columnName": "episode_number",+ "affinity": "INTEGER"+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_playback_history_content_id_content_type_provider_id",+ "unique": true,+ "columnNames": [+ "content_id",+ "content_type",+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_playback_history_content_id_content_type_provider_id` ON `${TABLE_NAME}` (`content_id`, `content_type`, `provider_id`)"+ },+ {+ "name": "index_playback_history_last_watched_at",+ "unique": false,+ "columnNames": [+ "last_watched_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_history_last_watched_at` ON `${TABLE_NAME}` (`last_watched_at`)"+ },+ {+ "name": "index_playback_history_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_history_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_playback_history_provider_id_content_type_content_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "content_type",+ "content_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_history_provider_id_content_type_content_id` ON `${TABLE_NAME}` (`provider_id`, `content_type`, `content_id`)"+ },+ {+ "name": "index_playback_history_provider_id_content_type_last_watched_at",+ "unique": false,+ "columnNames": [+ "provider_id",+ "content_type",+ "last_watched_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_history_provider_id_content_type_last_watched_at` ON `${TABLE_NAME}` (`provider_id`, `content_type`, `last_watched_at`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "tmdb_identity",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`tmdb_id` INTEGER NOT NULL, `content_type` TEXT NOT NULL, `canonical_provider_id` INTEGER NOT NULL, `first_seen_at` INTEGER NOT NULL, PRIMARY KEY(`tmdb_id`, `content_type`), FOREIGN KEY(`canonical_provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "tmdbId",+ "columnName": "tmdb_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentType",+ "columnName": "content_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "canonicalProviderId",+ "columnName": "canonical_provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "firstSeenAt",+ "columnName": "first_seen_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "tmdb_id",+ "content_type"+ ]+ },+ "indices": [+ {+ "name": "index_tmdb_identity_content_type",+ "unique": false,+ "columnNames": [+ "content_type"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_tmdb_identity_content_type` ON `${TABLE_NAME}` (`content_type`)"+ },+ {+ "name": "index_tmdb_identity_canonical_provider_id",+ "unique": false,+ "columnNames": [+ "canonical_provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_tmdb_identity_canonical_provider_id` ON `${TABLE_NAME}` (`canonical_provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "canonical_provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "search_history",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `query` TEXT NOT NULL, `content_scope` TEXT NOT NULL, `provider_id` INTEGER NOT NULL, `used_at` INTEGER NOT NULL, `use_count` INTEGER NOT NULL)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "query",+ "columnName": "query",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "contentScope",+ "columnName": "content_scope",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "usedAt",+ "columnName": "used_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "useCount",+ "columnName": "use_count",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_search_history_content_scope_provider_id_used_at",+ "unique": false,+ "columnNames": [+ "content_scope",+ "provider_id",+ "used_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_search_history_content_scope_provider_id_used_at` ON `${TABLE_NAME}` (`content_scope`, `provider_id`, `used_at`)"+ },+ {+ "name": "index_search_history_used_at",+ "unique": false,+ "columnNames": [+ "used_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_search_history_used_at` ON `${TABLE_NAME}` (`used_at`)"+ },+ {+ "name": "index_search_history_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_search_history_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_search_history_query_content_scope_provider_id",+ "unique": true,+ "columnNames": [+ "query",+ "content_scope",+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_search_history_query_content_scope_provider_id` ON `${TABLE_NAME}` (`query`, `content_scope`, `provider_id`)"+ }+ ]+ },+ {+ "tableName": "sync_metadata",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `last_live_sync` INTEGER NOT NULL, `last_live_success` INTEGER NOT NULL, `last_movie_sync` INTEGER NOT NULL, `last_series_sync` INTEGER NOT NULL, `last_series_success` INTEGER NOT NULL, `last_epg_sync` INTEGER NOT NULL, `last_epg_success` INTEGER NOT NULL, `last_movie_attempt` INTEGER NOT NULL, `last_movie_success` INTEGER NOT NULL, `last_movie_partial` INTEGER NOT NULL, `live_count` INTEGER NOT NULL, `movie_count` INTEGER NOT NULL, `series_count` INTEGER NOT NULL, `epg_count` INTEGER NOT NULL, `last_sync_status` TEXT NOT NULL, `movie_sync_mode` TEXT NOT NULL, `movie_warnings_count` INTEGER NOT NULL, `movie_catalog_stale` INTEGER NOT NULL, `live_avoid_full_until` INTEGER NOT NULL, `movie_avoid_full_until` INTEGER NOT NULL, `series_avoid_full_until` INTEGER NOT NULL, `live_sequential_failures_remembered` INTEGER NOT NULL, `live_healthy_sync_streak` INTEGER NOT NULL, `movie_parallel_failures_remembered` INTEGER NOT NULL, `movie_healthy_sync_streak` INTEGER NOT NULL, `series_sequential_failures_remembered` INTEGER NOT NULL, `series_healthy_sync_streak` INTEGER NOT NULL, PRIMARY KEY(`provider_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastLiveSync",+ "columnName": "last_live_sync",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastLiveSuccess",+ "columnName": "last_live_success",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastMovieSync",+ "columnName": "last_movie_sync",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastSeriesSync",+ "columnName": "last_series_sync",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastSeriesSuccess",+ "columnName": "last_series_success",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastEpgSync",+ "columnName": "last_epg_sync",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastEpgSuccess",+ "columnName": "last_epg_success",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastMovieAttempt",+ "columnName": "last_movie_attempt",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastMovieSuccess",+ "columnName": "last_movie_success",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastMoviePartial",+ "columnName": "last_movie_partial",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "liveCount",+ "columnName": "live_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "movieCount",+ "columnName": "movie_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "seriesCount",+ "columnName": "series_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "epgCount",+ "columnName": "epg_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastSyncStatus",+ "columnName": "last_sync_status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "movieSyncMode",+ "columnName": "movie_sync_mode",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "movieWarningsCount",+ "columnName": "movie_warnings_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "movieCatalogStale",+ "columnName": "movie_catalog_stale",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "liveAvoidFullUntil",+ "columnName": "live_avoid_full_until",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "movieAvoidFullUntil",+ "columnName": "movie_avoid_full_until",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "seriesAvoidFullUntil",+ "columnName": "series_avoid_full_until",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "liveSequentialFailuresRemembered",+ "columnName": "live_sequential_failures_remembered",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "liveHealthySyncStreak",+ "columnName": "live_healthy_sync_streak",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "movieParallelFailuresRemembered",+ "columnName": "movie_parallel_failures_remembered",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "movieHealthySyncStreak",+ "columnName": "movie_healthy_sync_streak",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "seriesSequentialFailuresRemembered",+ "columnName": "series_sequential_failures_remembered",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "seriesHealthySyncStreak",+ "columnName": "series_healthy_sync_streak",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "provider_id"+ ]+ },+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "movie_category_hydration",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `category_id` INTEGER NOT NULL, `last_hydrated_at` INTEGER NOT NULL, `item_count` INTEGER NOT NULL, `last_status` TEXT NOT NULL, `last_error` TEXT, `last_loaded_page` INTEGER NOT NULL, `last_attempted_page` INTEGER NOT NULL, `last_successful_page` INTEGER NOT NULL, `total_pages` INTEGER NOT NULL, `is_complete` INTEGER NOT NULL, `page_size` INTEGER NOT NULL, `retry_after_ms` INTEGER NOT NULL, `failure_count` INTEGER NOT NULL, `retry_budget_remaining` INTEGER NOT NULL, `last_page_fingerprint` TEXT, PRIMARY KEY(`provider_id`, `category_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastHydratedAt",+ "columnName": "last_hydrated_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "itemCount",+ "columnName": "item_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastStatus",+ "columnName": "last_status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "lastError",+ "columnName": "last_error",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lastLoadedPage",+ "columnName": "last_loaded_page",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastAttemptedPage",+ "columnName": "last_attempted_page",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastSuccessfulPage",+ "columnName": "last_successful_page",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "totalPages",+ "columnName": "total_pages",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isComplete",+ "columnName": "is_complete",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "pageSize",+ "columnName": "page_size",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "retryAfterMs",+ "columnName": "retry_after_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "failureCount",+ "columnName": "failure_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "retryBudgetRemaining",+ "columnName": "retry_budget_remaining",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastPageFingerprint",+ "columnName": "last_page_fingerprint",+ "affinity": "TEXT"+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "provider_id",+ "category_id"+ ]+ },+ "indices": [+ {+ "name": "index_movie_category_hydration_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movie_category_hydration_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "series_category_hydration",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `category_id` INTEGER NOT NULL, `last_hydrated_at` INTEGER NOT NULL, `item_count` INTEGER NOT NULL, `last_status` TEXT NOT NULL, `last_error` TEXT, `last_loaded_page` INTEGER NOT NULL, `last_attempted_page` INTEGER NOT NULL, `last_successful_page` INTEGER NOT NULL, `total_pages` INTEGER NOT NULL, `is_complete` INTEGER NOT NULL, `page_size` INTEGER NOT NULL, `retry_after_ms` INTEGER NOT NULL, `failure_count` INTEGER NOT NULL, `retry_budget_remaining` INTEGER NOT NULL, `last_page_fingerprint` TEXT, PRIMARY KEY(`provider_id`, `category_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastHydratedAt",+ "columnName": "last_hydrated_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "itemCount",+ "columnName": "item_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastStatus",+ "columnName": "last_status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "lastError",+ "columnName": "last_error",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lastLoadedPage",+ "columnName": "last_loaded_page",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastAttemptedPage",+ "columnName": "last_attempted_page",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastSuccessfulPage",+ "columnName": "last_successful_page",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "totalPages",+ "columnName": "total_pages",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isComplete",+ "columnName": "is_complete",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "pageSize",+ "columnName": "page_size",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "retryAfterMs",+ "columnName": "retry_after_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "failureCount",+ "columnName": "failure_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "retryBudgetRemaining",+ "columnName": "retry_budget_remaining",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastPageFingerprint",+ "columnName": "last_page_fingerprint",+ "affinity": "TEXT"+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "provider_id",+ "category_id"+ ]+ },+ "indices": [+ {+ "name": "index_series_category_hydration_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_category_hydration_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "epg_sources",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `url` TEXT NOT NULL, `enabled` INTEGER NOT NULL, `last_refresh_at` INTEGER NOT NULL, `last_success_at` INTEGER NOT NULL, `last_error` TEXT, `priority` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, `etag` TEXT, `last_modified_header` TEXT)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "url",+ "columnName": "url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "enabled",+ "columnName": "enabled",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastRefreshAt",+ "columnName": "last_refresh_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastSuccessAt",+ "columnName": "last_success_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastError",+ "columnName": "last_error",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "priority",+ "columnName": "priority",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "etag",+ "columnName": "etag",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lastModifiedHeader",+ "columnName": "last_modified_header",+ "affinity": "TEXT"+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_epg_sources_url",+ "unique": true,+ "columnNames": [+ "url"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_epg_sources_url` ON `${TABLE_NAME}` (`url`)"+ }+ ]+ },+ {+ "tableName": "provider_epg_sources",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `epg_source_id` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `enabled` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`epg_source_id`) REFERENCES `epg_sources`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "epgSourceId",+ "columnName": "epg_source_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "priority",+ "columnName": "priority",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "enabled",+ "columnName": "enabled",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_provider_epg_sources_provider_id_epg_source_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "epg_source_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_provider_epg_sources_provider_id_epg_source_id` ON `${TABLE_NAME}` (`provider_id`, `epg_source_id`)"+ },+ {+ "name": "index_provider_epg_sources_epg_source_id",+ "unique": false,+ "columnNames": [+ "epg_source_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_provider_epg_sources_epg_source_id` ON `${TABLE_NAME}` (`epg_source_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ },+ {+ "table": "epg_sources",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "epg_source_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "epg_channels",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `epg_source_id` INTEGER NOT NULL, `xmltv_channel_id` TEXT NOT NULL, `display_name` TEXT NOT NULL, `normalized_name` TEXT NOT NULL, `icon_url` TEXT, FOREIGN KEY(`epg_source_id`) REFERENCES `epg_sources`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "epgSourceId",+ "columnName": "epg_source_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "xmltvChannelId",+ "columnName": "xmltv_channel_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "displayName",+ "columnName": "display_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "normalizedName",+ "columnName": "normalized_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "iconUrl",+ "columnName": "icon_url",+ "affinity": "TEXT"+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_epg_channels_epg_source_id_xmltv_channel_id",+ "unique": true,+ "columnNames": [+ "epg_source_id",+ "xmltv_channel_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_epg_channels_epg_source_id_xmltv_channel_id` ON `${TABLE_NAME}` (`epg_source_id`, `xmltv_channel_id`)"+ },+ {+ "name": "index_epg_channels_epg_source_id",+ "unique": false,+ "columnNames": [+ "epg_source_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_channels_epg_source_id` ON `${TABLE_NAME}` (`epg_source_id`)"+ },+ {+ "name": "index_epg_channels_normalized_name",+ "unique": false,+ "columnNames": [+ "normalized_name"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_channels_normalized_name` ON `${TABLE_NAME}` (`normalized_name`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "epg_sources",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "epg_source_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "epg_programmes",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `epg_source_id` INTEGER NOT NULL, `xmltv_channel_id` TEXT NOT NULL, `start_time` INTEGER NOT NULL, `end_time` INTEGER NOT NULL, `title` TEXT NOT NULL, `subtitle` TEXT, `description` TEXT NOT NULL, `category` TEXT, `lang` TEXT NOT NULL, `rating` TEXT, `image_url` TEXT, `episode_info` TEXT, FOREIGN KEY(`epg_source_id`) REFERENCES `epg_sources`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "epgSourceId",+ "columnName": "epg_source_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "xmltvChannelId",+ "columnName": "xmltv_channel_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "startTime",+ "columnName": "start_time",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "endTime",+ "columnName": "end_time",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "title",+ "columnName": "title",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "subtitle",+ "columnName": "subtitle",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "description",+ "columnName": "description",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "category",+ "columnName": "category",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lang",+ "columnName": "lang",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "rating",+ "columnName": "rating",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "imageUrl",+ "columnName": "image_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "episodeInfo",+ "columnName": "episode_info",+ "affinity": "TEXT"+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_epg_programmes_epg_source_id_xmltv_channel_id_start_time",+ "unique": false,+ "columnNames": [+ "epg_source_id",+ "xmltv_channel_id",+ "start_time"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_programmes_epg_source_id_xmltv_channel_id_start_time` ON `${TABLE_NAME}` (`epg_source_id`, `xmltv_channel_id`, `start_time`)"+ },+ {+ "name": "index_epg_programmes_epg_source_id_xmltv_channel_id_start_time_end_time",+ "unique": true,+ "columnNames": [+ "epg_source_id",+ "xmltv_channel_id",+ "start_time",+ "end_time"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_epg_programmes_epg_source_id_xmltv_channel_id_start_time_end_time` ON `${TABLE_NAME}` (`epg_source_id`, `xmltv_channel_id`, `start_time`, `end_time`)"+ },+ {+ "name": "index_epg_programmes_epg_source_id",+ "unique": false,+ "columnNames": [+ "epg_source_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_programmes_epg_source_id` ON `${TABLE_NAME}` (`epg_source_id`)"+ },+ {+ "name": "index_epg_programmes_start_time",+ "unique": false,+ "columnNames": [+ "start_time"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_programmes_start_time` ON `${TABLE_NAME}` (`start_time`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "epg_sources",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "epg_source_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "channel_epg_mappings",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_channel_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `source_type` TEXT NOT NULL, `epg_source_id` INTEGER, `xmltv_channel_id` TEXT, `match_type` TEXT, `confidence` REAL NOT NULL, `matched_at` INTEGER NOT NULL, `failed_attempts` INTEGER NOT NULL, `source` TEXT, `is_manual_override` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerChannelId",+ "columnName": "provider_channel_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "sourceType",+ "columnName": "source_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "epgSourceId",+ "columnName": "epg_source_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "xmltvChannelId",+ "columnName": "xmltv_channel_id",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "matchType",+ "columnName": "match_type",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "confidence",+ "columnName": "confidence",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "matchedAt",+ "columnName": "matched_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "failedAttempts",+ "columnName": "failed_attempts",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "source",+ "columnName": "source",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "isManualOverride",+ "columnName": "is_manual_override",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_channel_epg_mappings_provider_id_provider_channel_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "provider_channel_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_channel_epg_mappings_provider_id_provider_channel_id` ON `${TABLE_NAME}` (`provider_id`, `provider_channel_id`)"+ },+ {+ "name": "index_channel_epg_mappings_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channel_epg_mappings_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "combined_m3u_profiles",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `enabled` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "enabled",+ "columnName": "enabled",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ }+ },+ {+ "tableName": "combined_m3u_profile_members",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `profile_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `enabled` INTEGER NOT NULL, FOREIGN KEY(`profile_id`) REFERENCES `combined_m3u_profiles`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "profileId",+ "columnName": "profile_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "priority",+ "columnName": "priority",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "enabled",+ "columnName": "enabled",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_combined_m3u_profile_members_profile_id",+ "unique": false,+ "columnNames": [+ "profile_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_combined_m3u_profile_members_profile_id` ON `${TABLE_NAME}` (`profile_id`)"+ },+ {+ "name": "index_combined_m3u_profile_members_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_combined_m3u_profile_members_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_combined_m3u_profile_members_profile_id_provider_id",+ "unique": true,+ "columnNames": [+ "profile_id",+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_combined_m3u_profile_members_profile_id_provider_id` ON `${TABLE_NAME}` (`profile_id`, `provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "combined_m3u_profiles",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "profile_id"+ ],+ "referencedColumns": [+ "id"+ ]+ },+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "recording_schedules",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, `channel_name` TEXT NOT NULL, `stream_url` TEXT NOT NULL, `program_title` TEXT, `requested_start_ms` INTEGER NOT NULL, `requested_end_ms` INTEGER NOT NULL, `recurrence` TEXT NOT NULL, `recurring_rule_id` TEXT, `enabled` INTEGER NOT NULL, `is_manual` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelId",+ "columnName": "channel_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelName",+ "columnName": "channel_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "programTitle",+ "columnName": "program_title",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "requestedStartMs",+ "columnName": "requested_start_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "requestedEndMs",+ "columnName": "requested_end_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "recurrence",+ "columnName": "recurrence",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "recurringRuleId",+ "columnName": "recurring_rule_id",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "enabled",+ "columnName": "enabled",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isManual",+ "columnName": "is_manual",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "priority",+ "columnName": "priority",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_recording_schedules_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_schedules_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_recording_schedules_enabled_requested_start_ms",+ "unique": false,+ "columnNames": [+ "enabled",+ "requested_start_ms"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_schedules_enabled_requested_start_ms` ON `${TABLE_NAME}` (`enabled`, `requested_start_ms`)"+ },+ {+ "name": "index_recording_schedules_recurring_rule_id",+ "unique": false,+ "columnNames": [+ "recurring_rule_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_schedules_recurring_rule_id` ON `${TABLE_NAME}` (`recurring_rule_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "recording_runs",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `schedule_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, `channel_name` TEXT NOT NULL, `stream_url` TEXT NOT NULL, `program_title` TEXT, `scheduled_start_ms` INTEGER NOT NULL, `scheduled_end_ms` INTEGER NOT NULL, `recurrence` TEXT NOT NULL, `recurring_rule_id` TEXT, `status` TEXT NOT NULL, `source_type` TEXT NOT NULL, `resolved_url` TEXT, `headers_json` TEXT NOT NULL, `user_agent` TEXT, `expiration_time` INTEGER, `provider_label` TEXT, `output_uri` TEXT, `output_display_path` TEXT, `bytes_written` INTEGER NOT NULL, `average_throughput_bps` INTEGER NOT NULL, `retry_count` INTEGER NOT NULL, `last_progress_at_ms` INTEGER, `failure_category` TEXT NOT NULL, `failure_reason` TEXT, `terminal_at_ms` INTEGER, `started_at_ms` INTEGER, `ended_at_ms` INTEGER, `schedule_enabled` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `alarm_start_at_ms` INTEGER, `alarm_stop_at_ms` INTEGER, `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, `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": "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": "downloads",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `provider_id` INTEGER NOT NULL, `content_type` TEXT NOT NULL, `content_id` INTEGER NOT NULL, `content_name` TEXT NOT NULL, `stream_url` TEXT NOT NULL, `source_stream_url` TEXT, `source_stream_id` INTEGER, `container_extension` TEXT, `poster_url` TEXT, `output_uri` TEXT, `output_display_path` TEXT, `status` TEXT NOT NULL, `bytes_written` INTEGER NOT NULL, `total_bytes` INTEGER, `supports_resume` INTEGER NOT NULL, `retry_count` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `completed_at` INTEGER, `failure_reason` TEXT, `series_id` INTEGER, `season_number` INTEGER, `episode_number` INTEGER, PRIMARY KEY(`id`))",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentType",+ "columnName": "content_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "contentId",+ "columnName": "content_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentName",+ "columnName": "content_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "sourceStreamUrl",+ "columnName": "source_stream_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "sourceStreamId",+ "columnName": "source_stream_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "containerExtension",+ "columnName": "container_extension",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "posterUrl",+ "columnName": "poster_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "outputUri",+ "columnName": "output_uri",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "outputDisplayPath",+ "columnName": "output_display_path",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "status",+ "columnName": "status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "bytesWritten",+ "columnName": "bytes_written",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "totalBytes",+ "columnName": "total_bytes",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "supportsResume",+ "columnName": "supports_resume",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "retryCount",+ "columnName": "retry_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "completedAt",+ "columnName": "completed_at",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "failureReason",+ "columnName": "failure_reason",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "seriesId",+ "columnName": "series_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "seasonNumber",+ "columnName": "season_number",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "episodeNumber",+ "columnName": "episode_number",+ "affinity": "INTEGER"+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_downloads_status",+ "unique": false,+ "columnNames": [+ "status"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_downloads_status` ON `${TABLE_NAME}` (`status`)"+ },+ {+ "name": "index_downloads_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_downloads_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_downloads_content_type_content_id",+ "unique": false,+ "columnNames": [+ "content_type",+ "content_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_downloads_content_type_content_id` ON `${TABLE_NAME}` (`content_type`, `content_id`)"+ }+ ]+ },+ {+ "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"+ ]+ }+ }+ ],+ "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, '5602ff82f4270e22b880b71c8401731d')"+ ]+ }+}\ No newline at end of filediff --git a/data/schemas/com.streamvault.data.local.StreamVaultDatabase/69.json b/data/schemas/com.streamvault.data.local.StreamVaultDatabase/69.jsonnew file mode 100644index 00000000..05ed1463--- /dev/null+++ b/data/schemas/com.streamvault.data.local.StreamVaultDatabase/69.json@@ -0,0 +1,5679 @@+{+ "formatVersion": 1,+ "database": {+ "version": 69,+ "identityHash": "0d861f0a1b10ce876e377cd8ec30c6dc",+ "entities": [+ {+ "tableName": "providers",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `type` TEXT NOT NULL, `server_url` TEXT NOT NULL, `username` TEXT NOT NULL, `password` TEXT NOT NULL, `m3u_url` TEXT NOT NULL, `epg_url` TEXT NOT NULL, `http_user_agent` TEXT NOT NULL, `http_headers` TEXT NOT NULL, `stalker_mac_address` TEXT NOT NULL, `stalker_device_profile` TEXT NOT NULL, `stalker_device_timezone` TEXT NOT NULL, `stalker_device_locale` TEXT NOT NULL, `stalker_serial_number` TEXT NOT NULL, `stalker_device_id` TEXT NOT NULL, `stalker_device_id2` TEXT NOT NULL, `stalker_signature` TEXT NOT NULL, `stalker_advanced_options_json` TEXT NOT NULL, `stalker_auth_mode` TEXT NOT NULL, `stalker_portal_profile` TEXT NOT NULL, `stalker_portal_fingerprint` TEXT NOT NULL, `stalker_mag_preset` TEXT NOT NULL, `stalker_last_bootstrap_recipe` TEXT NOT NULL, `stalker_endpoint_preference` TEXT NOT NULL, `stalker_cookie_mode` TEXT NOT NULL, `stalker_playback_backend_hint` TEXT NOT NULL, `stalker_last_playback_mode` TEXT, `stalker_credentials_required` INTEGER NOT NULL, `stalker_mac_required` INTEGER NOT NULL, `stalker_uses_temp_links` INTEGER NOT NULL, `stalker_module_restricted` INTEGER NOT NULL, `stalker_strict_fingerprint_required` INTEGER NOT NULL, `stalker_recipe_fallback_used` INTEGER NOT NULL, `stalker_recipe_rediscovery_attempts` INTEGER NOT NULL, `is_active` INTEGER NOT NULL, `max_connections` INTEGER NOT NULL, `expiration_date` INTEGER, `api_version` TEXT, `allowed_output_formats_json` TEXT NOT NULL, `epg_sync_mode` TEXT NOT NULL, `guide_source_policy` TEXT NOT NULL, `channel_logo_source_policy` TEXT NOT NULL, `xtream_fast_sync_enabled` INTEGER NOT NULL, `xtream_live_sync_mode` TEXT NOT NULL, `m3u_vod_classification_enabled` INTEGER NOT NULL, `status` TEXT NOT NULL, `last_synced_at` INTEGER NOT NULL, `created_at` INTEGER NOT NULL)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "type",+ "columnName": "type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "serverUrl",+ "columnName": "server_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "username",+ "columnName": "username",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "password",+ "columnName": "password",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "m3uUrl",+ "columnName": "m3u_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "epgUrl",+ "columnName": "epg_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "httpUserAgent",+ "columnName": "http_user_agent",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "httpHeaders",+ "columnName": "http_headers",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerMacAddress",+ "columnName": "stalker_mac_address",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerDeviceProfile",+ "columnName": "stalker_device_profile",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerDeviceTimezone",+ "columnName": "stalker_device_timezone",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerDeviceLocale",+ "columnName": "stalker_device_locale",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerSerialNumber",+ "columnName": "stalker_serial_number",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerDeviceId",+ "columnName": "stalker_device_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerDeviceId2",+ "columnName": "stalker_device_id2",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerSignature",+ "columnName": "stalker_signature",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerAdvancedOptionsJson",+ "columnName": "stalker_advanced_options_json",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerAuthMode",+ "columnName": "stalker_auth_mode",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerPortalProfile",+ "columnName": "stalker_portal_profile",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerPortalFingerprint",+ "columnName": "stalker_portal_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerMagPreset",+ "columnName": "stalker_mag_preset",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerLastBootstrapRecipe",+ "columnName": "stalker_last_bootstrap_recipe",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerEndpointPreference",+ "columnName": "stalker_endpoint_preference",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerCookieMode",+ "columnName": "stalker_cookie_mode",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerPlaybackBackendHint",+ "columnName": "stalker_playback_backend_hint",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerLastPlaybackMode",+ "columnName": "stalker_last_playback_mode",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "stalkerCredentialsRequired",+ "columnName": "stalker_credentials_required",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "stalkerMacRequired",+ "columnName": "stalker_mac_required",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "stalkerUsesTemporaryLinks",+ "columnName": "stalker_uses_temp_links",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "stalkerModuleRestricted",+ "columnName": "stalker_module_restricted",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "stalkerStrictFingerprintRequired",+ "columnName": "stalker_strict_fingerprint_required",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "stalkerRecipeFallbackUsed",+ "columnName": "stalker_recipe_fallback_used",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "stalkerRecipeRediscoveryAttempts",+ "columnName": "stalker_recipe_rediscovery_attempts",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isActive",+ "columnName": "is_active",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "maxConnections",+ "columnName": "max_connections",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "expirationDate",+ "columnName": "expiration_date",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "apiVersion",+ "columnName": "api_version",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "allowedOutputFormatsJson",+ "columnName": "allowed_output_formats_json",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "epgSyncMode",+ "columnName": "epg_sync_mode",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "guideSourcePolicy",+ "columnName": "guide_source_policy",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "channelLogoSourcePolicy",+ "columnName": "channel_logo_source_policy",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "xtreamFastSyncEnabled",+ "columnName": "xtream_fast_sync_enabled",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "xtreamLiveSyncMode",+ "columnName": "xtream_live_sync_mode",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "m3uVodClassificationEnabled",+ "columnName": "m3u_vod_classification_enabled",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "status",+ "columnName": "status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "lastSyncedAt",+ "columnName": "last_synced_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_providers_server_url_username_stalker_mac_address",+ "unique": true,+ "columnNames": [+ "server_url",+ "username",+ "stalker_mac_address"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_providers_server_url_username_stalker_mac_address` ON `${TABLE_NAME}` (`server_url`, `username`, `stalker_mac_address`)"+ }+ ]+ },+ {+ "tableName": "channels",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `stream_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `logo_url` TEXT, `group_title` TEXT, `category_id` INTEGER, `category_name` TEXT, `stream_url` TEXT NOT NULL, `epg_channel_id` TEXT, `number` INTEGER NOT NULL, `catch_up_supported` INTEGER NOT NULL, `catch_up_days` INTEGER NOT NULL, `catchUpSource` TEXT, `provider_id` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, `logical_group_id` TEXT NOT NULL, `error_count` INTEGER NOT NULL, `quality_options_json` TEXT, `sync_fingerprint` TEXT NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "streamId",+ "columnName": "stream_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "logoUrl",+ "columnName": "logo_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "groupTitle",+ "columnName": "group_title",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "categoryName",+ "columnName": "category_name",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "epgChannelId",+ "columnName": "epg_channel_id",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "number",+ "columnName": "number",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "catchUpSupported",+ "columnName": "catch_up_supported",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "catchUpDays",+ "columnName": "catch_up_days",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "catchUpSource",+ "columnName": "catchUpSource",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isUserProtected",+ "columnName": "is_user_protected",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "logicalGroupId",+ "columnName": "logical_group_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "errorCount",+ "columnName": "error_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "qualityOptionsJson",+ "columnName": "quality_options_json",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "syncFingerprint",+ "columnName": "sync_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_channels_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_channels_provider_id_category_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "category_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_provider_id_category_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`)"+ },+ {+ "name": "index_channels_provider_id_stream_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "stream_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_channels_provider_id_stream_id` ON `${TABLE_NAME}` (`provider_id`, `stream_id`)"+ },+ {+ "name": "index_channels_logical_group_id",+ "unique": false,+ "columnNames": [+ "logical_group_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_logical_group_id` ON `${TABLE_NAME}` (`logical_group_id`)"+ },+ {+ "name": "index_channels_provider_id_category_id_logical_group_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "category_id",+ "logical_group_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_provider_id_category_id_logical_group_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`, `logical_group_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "channel_preferences",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `channel_id` INTEGER NOT NULL, `aspect_ratio` TEXT, `audio_video_offset_ms` INTEGER, `updated_at` INTEGER NOT NULL, FOREIGN KEY(`channel_id`) REFERENCES `channels`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelId",+ "columnName": "channel_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "aspectRatio",+ "columnName": "aspect_ratio",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "audioVideoOffsetMs",+ "columnName": "audio_video_offset_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_channel_preferences_channel_id",+ "unique": true,+ "columnNames": [+ "channel_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_channel_preferences_channel_id` ON `${TABLE_NAME}` (`channel_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "channels",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "channel_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "channels_fts",+ "createSql": "CREATE VIRTUAL TABLE IF NOT EXISTS `${TABLE_NAME}` USING FTS4(`name` TEXT NOT NULL, content=`channels`)",+ "fields": [+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": []+ },+ "ftsVersion": "FTS4",+ "ftsOptions": {+ "tokenizer": "simple",+ "tokenizerArgs": [],+ "contentTable": "channels",+ "languageIdColumnName": "",+ "matchInfo": "FTS4",+ "notIndexedColumns": [],+ "prefixSizes": [],+ "preferredOrder": "ASC"+ },+ "contentSyncTriggers": [+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_BEFORE_UPDATE BEFORE UPDATE ON `channels` BEGIN DELETE FROM `channels_fts` WHERE `docid`=OLD.`rowid`; END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_BEFORE_DELETE BEFORE DELETE ON `channels` BEGIN DELETE FROM `channels_fts` WHERE `docid`=OLD.`rowid`; END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_AFTER_UPDATE AFTER UPDATE ON `channels` BEGIN INSERT INTO `channels_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_AFTER_INSERT AFTER INSERT ON `channels` BEGIN INSERT INTO `channels_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END"+ ]+ },+ {+ "tableName": "movies",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `stream_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `poster_url` TEXT, `backdrop_url` TEXT, `category_id` INTEGER, `category_name` TEXT, `stream_url` TEXT NOT NULL, `container_extension` TEXT, `plot` TEXT, `cast` TEXT, `director` TEXT, `genre` TEXT, `release_date` TEXT, `duration` TEXT, `duration_seconds` INTEGER NOT NULL, `rating` REAL NOT NULL, `year` TEXT, `tmdb_id` INTEGER, `youtube_trailer` TEXT, `provider_id` INTEGER NOT NULL, `watch_progress` INTEGER NOT NULL, `watch_count` INTEGER NOT NULL, `last_watched_at` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, `added_at` INTEGER NOT NULL, `cache_state` TEXT NOT NULL, `detail_hydrated_at` INTEGER NOT NULL, `remote_stale_at` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "streamId",+ "columnName": "stream_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "posterUrl",+ "columnName": "poster_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "backdropUrl",+ "columnName": "backdrop_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "categoryName",+ "columnName": "category_name",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "containerExtension",+ "columnName": "container_extension",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "plot",+ "columnName": "plot",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "cast",+ "columnName": "cast",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "director",+ "columnName": "director",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "genre",+ "columnName": "genre",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "releaseDate",+ "columnName": "release_date",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "duration",+ "columnName": "duration",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "durationSeconds",+ "columnName": "duration_seconds",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "rating",+ "columnName": "rating",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "year",+ "columnName": "year",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "tmdbId",+ "columnName": "tmdb_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "youtubeTrailer",+ "columnName": "youtube_trailer",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "watchProgress",+ "columnName": "watch_progress",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "watchCount",+ "columnName": "watch_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastWatchedAt",+ "columnName": "last_watched_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isUserProtected",+ "columnName": "is_user_protected",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "syncFingerprint",+ "columnName": "sync_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "addedAt",+ "columnName": "added_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "cacheState",+ "columnName": "cache_state",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "detailHydratedAt",+ "columnName": "detail_hydrated_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "remoteStaleAt",+ "columnName": "remote_stale_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_movies_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_movies_provider_id_category_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "category_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id_category_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`)"+ },+ {+ "name": "index_movies_provider_id_stream_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "stream_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_movies_provider_id_stream_id` ON `${TABLE_NAME}` (`provider_id`, `stream_id`)"+ },+ {+ "name": "index_movies_provider_id_name_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "name",+ "id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id_name_id` ON `${TABLE_NAME}` (`provider_id`, `name`, `id`)"+ },+ {+ "name": "index_movies_provider_id_category_id_name_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "category_id",+ "name",+ "id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id_category_id_name_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`, `name`, `id`)"+ },+ {+ "name": "index_movies_provider_id_rating_name_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "rating",+ "name",+ "id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id_rating_name_id` ON `${TABLE_NAME}` (`provider_id`, `rating`, `name`, `id`)"+ },+ {+ "name": "index_movies_provider_id_added_at_release_date_name_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "added_at",+ "release_date",+ "name",+ "id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id_added_at_release_date_name_id` ON `${TABLE_NAME}` (`provider_id`, `added_at`, `release_date`, `name`, `id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "movies_fts",+ "createSql": "CREATE VIRTUAL TABLE IF NOT EXISTS `${TABLE_NAME}` USING FTS4(`name` TEXT NOT NULL, content=`movies`)",+ "fields": [+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": []+ },+ "ftsVersion": "FTS4",+ "ftsOptions": {+ "tokenizer": "simple",+ "tokenizerArgs": [],+ "contentTable": "movies",+ "languageIdColumnName": "",+ "matchInfo": "FTS4",+ "notIndexedColumns": [],+ "prefixSizes": [],+ "preferredOrder": "ASC"+ },+ "contentSyncTriggers": [+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_movies_fts_BEFORE_UPDATE BEFORE UPDATE ON `movies` BEGIN DELETE FROM `movies_fts` WHERE `docid`=OLD.`rowid`; END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_movies_fts_BEFORE_DELETE BEFORE DELETE ON `movies` BEGIN DELETE FROM `movies_fts` WHERE `docid`=OLD.`rowid`; END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_movies_fts_AFTER_UPDATE AFTER UPDATE ON `movies` BEGIN INSERT INTO `movies_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_movies_fts_AFTER_INSERT AFTER INSERT ON `movies` BEGIN INSERT INTO `movies_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END"+ ]+ },+ {+ "tableName": "series",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `series_id` INTEGER NOT NULL, `provider_series_id` TEXT, `name` TEXT NOT NULL, `poster_url` TEXT, `backdrop_url` TEXT, `category_id` INTEGER, `category_name` TEXT, `plot` TEXT, `cast` TEXT, `director` TEXT, `genre` TEXT, `release_date` TEXT, `rating` REAL NOT NULL, `tmdb_id` INTEGER, `youtube_trailer` TEXT, `episode_run_time` TEXT, `last_modified` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, `cache_state` TEXT NOT NULL, `detail_hydrated_at` INTEGER NOT NULL, `remote_stale_at` INTEGER NOT NULL, 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+ }+ ],+ "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, `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": "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, `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": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "syncFingerprint",+ "columnName": "sync_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "session_id",+ "provider_id",+ "category_id",+ "type"+ ]+ },+ "indices": [+ {+ "name": "index_category_import_stage_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_category_import_stage_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_category_import_stage_session_id_provider_id",+ "unique": false,+ "columnNames": [+ "session_id",+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_category_import_stage_session_id_provider_id` ON `${TABLE_NAME}` (`session_id`, `provider_id`)"+ },+ {+ "name": "index_category_import_stage_provider_id_type",+ "unique": false,+ "columnNames": [+ "provider_id",+ "type"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_category_import_stage_provider_id_type` ON `${TABLE_NAME}` (`provider_id`, `type`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "programs",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `channel_id` TEXT NOT NULL, `title` TEXT NOT NULL, `description` TEXT NOT NULL, `start_time` INTEGER NOT NULL, `end_time` INTEGER NOT NULL, `lang` TEXT NOT NULL, `rating` TEXT, `image_url` TEXT, `genre` TEXT, `category` TEXT, `has_archive` INTEGER NOT NULL)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelId",+ "columnName": "channel_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "title",+ "columnName": "title",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "description",+ "columnName": "description",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "startTime",+ "columnName": "start_time",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "endTime",+ "columnName": "end_time",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lang",+ "columnName": "lang",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "rating",+ "columnName": "rating",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "imageUrl",+ "columnName": "image_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "genre",+ "columnName": "genre",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "category",+ "columnName": "category",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "hasArchive",+ "columnName": "has_archive",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_programs_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_programs_provider_id_channel_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "channel_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_channel_id` ON `${TABLE_NAME}` (`provider_id`, `channel_id`)"+ },+ {+ "name": "index_programs_provider_id_end_time_channel_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "end_time",+ "channel_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_end_time_channel_id` ON `${TABLE_NAME}` (`provider_id`, `end_time`, `channel_id`)"+ },+ {+ "name": "index_programs_provider_id_start_time_end_time",+ "unique": false,+ "columnNames": [+ "provider_id",+ "start_time",+ "end_time"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_start_time_end_time` ON `${TABLE_NAME}` (`provider_id`, `start_time`, `end_time`)"+ },+ {+ "name": "index_programs_start_time",+ "unique": false,+ "columnNames": [+ "start_time"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_start_time` ON `${TABLE_NAME}` (`start_time`)"+ },+ {+ "name": "index_programs_provider_id_channel_id_start_time",+ "unique": false,+ "columnNames": [+ "provider_id",+ "channel_id",+ "start_time"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_channel_id_start_time` ON `${TABLE_NAME}` (`provider_id`, `channel_id`, `start_time`)"+ },+ {+ "name": "index_programs_provider_id_channel_id_start_time_end_time",+ "unique": true,+ "columnNames": [+ "provider_id",+ "channel_id",+ "start_time",+ "end_time"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_programs_provider_id_channel_id_start_time_end_time` ON `${TABLE_NAME}` (`provider_id`, `channel_id`, `start_time`, `end_time`)"+ }+ ]+ },+ {+ "tableName": "favorites",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `content_id` INTEGER NOT NULL, `content_type` TEXT NOT NULL, `position` INTEGER NOT NULL, `group_id` INTEGER, `group_key` INTEGER NOT NULL, `added_at` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`group_id`) REFERENCES `virtual_groups`(`id`) ON UPDATE NO ACTION ON DELETE SET NULL )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentId",+ "columnName": "content_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentType",+ "columnName": "content_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "position",+ "columnName": "position",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "groupId",+ "columnName": "group_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "groupKey",+ "columnName": "group_key",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "addedAt",+ "columnName": "added_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_favorites_provider_id_content_id_content_type_group_key",+ "unique": true,+ "columnNames": [+ "provider_id",+ "content_id",+ "content_type",+ "group_key"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_favorites_provider_id_content_id_content_type_group_key` ON `${TABLE_NAME}` (`provider_id`, `content_id`, `content_type`, `group_key`)"+ },+ {+ "name": "index_favorites_provider_id_content_type_group_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "content_type",+ "group_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_favorites_provider_id_content_type_group_id` ON `${TABLE_NAME}` (`provider_id`, `content_type`, `group_id`)"+ },+ {+ "name": "index_favorites_group_id_position",+ "unique": false,+ "columnNames": [+ "group_id",+ "position"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_favorites_group_id_position` ON `${TABLE_NAME}` (`group_id`, `position`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ },+ {+ "table": "virtual_groups",+ "onDelete": "SET NULL",+ "onUpdate": "NO ACTION",+ "columns": [+ "group_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "virtual_groups",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `icon_emoji` TEXT, `position` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `content_type` TEXT NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "iconEmoji",+ "columnName": "icon_emoji",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "position",+ "columnName": "position",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentType",+ "columnName": "content_type",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_virtual_groups_provider_id_content_type",+ "unique": false,+ "columnNames": [+ "provider_id",+ "content_type"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_virtual_groups_provider_id_content_type` ON `${TABLE_NAME}` (`provider_id`, `content_type`)"+ },+ {+ "name": "index_virtual_groups_position",+ "unique": false,+ "columnNames": [+ "position"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_virtual_groups_position` ON `${TABLE_NAME}` (`position`)"+ },+ {+ "name": "index_virtual_groups_content_type",+ "unique": false,+ "columnNames": [+ "content_type"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_virtual_groups_content_type` ON `${TABLE_NAME}` (`content_type`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "playback_history",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `content_id` INTEGER NOT NULL, `content_type` TEXT NOT NULL, `provider_id` INTEGER NOT NULL, `title` TEXT NOT NULL, `poster_url` TEXT, `stream_url` TEXT NOT NULL, `resume_position_ms` INTEGER NOT NULL, `total_duration_ms` INTEGER NOT NULL, `last_watched_at` INTEGER NOT NULL, `watch_count` INTEGER NOT NULL, `watched_status` TEXT NOT NULL, `series_id` INTEGER, `season_number` INTEGER, `episode_number` INTEGER, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentId",+ "columnName": "content_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentType",+ "columnName": "content_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "title",+ "columnName": "title",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "posterUrl",+ "columnName": "poster_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "resumePositionMs",+ "columnName": "resume_position_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "totalDurationMs",+ "columnName": "total_duration_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastWatchedAt",+ "columnName": "last_watched_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "watchCount",+ "columnName": "watch_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "watchedStatus",+ "columnName": "watched_status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "seriesId",+ "columnName": "series_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "seasonNumber",+ "columnName": "season_number",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "episodeNumber",+ "columnName": "episode_number",+ "affinity": "INTEGER"+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_playback_history_content_id_content_type_provider_id",+ "unique": true,+ "columnNames": [+ "content_id",+ "content_type",+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_playback_history_content_id_content_type_provider_id` ON `${TABLE_NAME}` (`content_id`, `content_type`, `provider_id`)"+ },+ {+ "name": "index_playback_history_last_watched_at",+ "unique": false,+ "columnNames": [+ "last_watched_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_history_last_watched_at` ON `${TABLE_NAME}` (`last_watched_at`)"+ },+ {+ "name": "index_playback_history_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_history_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_playback_history_provider_id_content_type_content_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "content_type",+ "content_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_history_provider_id_content_type_content_id` ON `${TABLE_NAME}` (`provider_id`, `content_type`, `content_id`)"+ },+ {+ "name": "index_playback_history_provider_id_content_type_last_watched_at",+ "unique": false,+ "columnNames": [+ "provider_id",+ "content_type",+ "last_watched_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_history_provider_id_content_type_last_watched_at` ON `${TABLE_NAME}` (`provider_id`, `content_type`, `last_watched_at`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "tmdb_identity",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`tmdb_id` INTEGER NOT NULL, `content_type` TEXT NOT NULL, `canonical_provider_id` INTEGER NOT NULL, `first_seen_at` INTEGER NOT NULL, PRIMARY KEY(`tmdb_id`, `content_type`), FOREIGN KEY(`canonical_provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "tmdbId",+ "columnName": "tmdb_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentType",+ "columnName": "content_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "canonicalProviderId",+ "columnName": "canonical_provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "firstSeenAt",+ "columnName": "first_seen_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "tmdb_id",+ "content_type"+ ]+ },+ "indices": [+ {+ "name": "index_tmdb_identity_content_type",+ "unique": false,+ "columnNames": [+ "content_type"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_tmdb_identity_content_type` ON `${TABLE_NAME}` (`content_type`)"+ },+ {+ "name": "index_tmdb_identity_canonical_provider_id",+ "unique": false,+ "columnNames": [+ "canonical_provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_tmdb_identity_canonical_provider_id` ON `${TABLE_NAME}` (`canonical_provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "canonical_provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "search_history",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `query` TEXT NOT NULL, `content_scope` TEXT NOT NULL, `provider_id` INTEGER NOT NULL, `used_at` INTEGER NOT NULL, `use_count` INTEGER NOT NULL)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "query",+ "columnName": "query",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "contentScope",+ "columnName": "content_scope",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "usedAt",+ "columnName": "used_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "useCount",+ "columnName": "use_count",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_search_history_content_scope_provider_id_used_at",+ "unique": false,+ "columnNames": [+ "content_scope",+ "provider_id",+ "used_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_search_history_content_scope_provider_id_used_at` ON `${TABLE_NAME}` (`content_scope`, `provider_id`, `used_at`)"+ },+ {+ "name": "index_search_history_used_at",+ "unique": false,+ "columnNames": [+ "used_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_search_history_used_at` ON `${TABLE_NAME}` (`used_at`)"+ },+ {+ "name": "index_search_history_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_search_history_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_search_history_query_content_scope_provider_id",+ "unique": true,+ "columnNames": [+ "query",+ "content_scope",+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_search_history_query_content_scope_provider_id` ON `${TABLE_NAME}` (`query`, `content_scope`, `provider_id`)"+ }+ ]+ },+ {+ "tableName": "sync_metadata",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `last_live_sync` INTEGER NOT NULL, `last_live_success` INTEGER NOT NULL, `last_movie_sync` INTEGER NOT NULL, `last_series_sync` INTEGER NOT NULL, `last_series_success` INTEGER NOT NULL, `last_epg_sync` INTEGER NOT NULL, `last_epg_success` INTEGER NOT NULL, `last_movie_attempt` INTEGER NOT NULL, `last_movie_success` INTEGER NOT NULL, `last_movie_partial` INTEGER NOT NULL, `live_count` INTEGER NOT NULL, `movie_count` INTEGER NOT NULL, `series_count` INTEGER NOT NULL, `epg_count` INTEGER NOT NULL, `last_sync_status` TEXT NOT NULL, `movie_sync_mode` TEXT NOT NULL, `movie_warnings_count` INTEGER NOT NULL, `movie_catalog_stale` INTEGER NOT NULL, `live_avoid_full_until` INTEGER NOT NULL, `movie_avoid_full_until` INTEGER NOT NULL, `series_avoid_full_until` INTEGER NOT NULL, `live_sequential_failures_remembered` INTEGER NOT NULL, `live_healthy_sync_streak` INTEGER NOT NULL, `movie_parallel_failures_remembered` INTEGER NOT NULL, `movie_healthy_sync_streak` INTEGER NOT NULL, `series_sequential_failures_remembered` INTEGER NOT NULL, `series_healthy_sync_streak` INTEGER NOT NULL, PRIMARY KEY(`provider_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastLiveSync",+ "columnName": "last_live_sync",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastLiveSuccess",+ "columnName": "last_live_success",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastMovieSync",+ "columnName": "last_movie_sync",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastSeriesSync",+ "columnName": "last_series_sync",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastSeriesSuccess",+ "columnName": "last_series_success",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastEpgSync",+ "columnName": "last_epg_sync",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastEpgSuccess",+ "columnName": "last_epg_success",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastMovieAttempt",+ "columnName": "last_movie_attempt",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastMovieSuccess",+ "columnName": "last_movie_success",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastMoviePartial",+ "columnName": "last_movie_partial",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "liveCount",+ "columnName": "live_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "movieCount",+ "columnName": "movie_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "seriesCount",+ "columnName": "series_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "epgCount",+ "columnName": "epg_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastSyncStatus",+ "columnName": "last_sync_status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "movieSyncMode",+ "columnName": "movie_sync_mode",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "movieWarningsCount",+ "columnName": "movie_warnings_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "movieCatalogStale",+ "columnName": "movie_catalog_stale",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "liveAvoidFullUntil",+ "columnName": "live_avoid_full_until",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "movieAvoidFullUntil",+ "columnName": "movie_avoid_full_until",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "seriesAvoidFullUntil",+ "columnName": "series_avoid_full_until",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "liveSequentialFailuresRemembered",+ "columnName": "live_sequential_failures_remembered",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "liveHealthySyncStreak",+ "columnName": "live_healthy_sync_streak",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "movieParallelFailuresRemembered",+ "columnName": "movie_parallel_failures_remembered",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "movieHealthySyncStreak",+ "columnName": "movie_healthy_sync_streak",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "seriesSequentialFailuresRemembered",+ "columnName": "series_sequential_failures_remembered",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "seriesHealthySyncStreak",+ "columnName": "series_healthy_sync_streak",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "provider_id"+ ]+ },+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "movie_category_hydration",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `category_id` INTEGER NOT NULL, `last_hydrated_at` INTEGER NOT NULL, `item_count` INTEGER NOT NULL, `last_status` TEXT NOT NULL, `last_error` TEXT, `last_loaded_page` INTEGER NOT NULL, `last_attempted_page` INTEGER NOT NULL, `last_successful_page` INTEGER NOT NULL, `total_pages` INTEGER NOT NULL, `is_complete` INTEGER NOT NULL, `page_size` INTEGER NOT NULL, `retry_after_ms` INTEGER NOT NULL, `failure_count` INTEGER NOT NULL, `retry_budget_remaining` INTEGER NOT NULL, `last_page_fingerprint` TEXT, PRIMARY KEY(`provider_id`, `category_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastHydratedAt",+ "columnName": "last_hydrated_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "itemCount",+ "columnName": "item_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastStatus",+ "columnName": "last_status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "lastError",+ "columnName": "last_error",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lastLoadedPage",+ "columnName": "last_loaded_page",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastAttemptedPage",+ "columnName": "last_attempted_page",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastSuccessfulPage",+ "columnName": "last_successful_page",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "totalPages",+ "columnName": "total_pages",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isComplete",+ "columnName": "is_complete",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "pageSize",+ "columnName": "page_size",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "retryAfterMs",+ "columnName": "retry_after_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "failureCount",+ "columnName": "failure_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "retryBudgetRemaining",+ "columnName": "retry_budget_remaining",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastPageFingerprint",+ "columnName": "last_page_fingerprint",+ "affinity": "TEXT"+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "provider_id",+ "category_id"+ ]+ },+ "indices": [+ {+ "name": "index_movie_category_hydration_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movie_category_hydration_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "series_category_hydration",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `category_id` INTEGER NOT NULL, `last_hydrated_at` INTEGER NOT NULL, `item_count` INTEGER NOT NULL, `last_status` TEXT NOT NULL, `last_error` TEXT, `last_loaded_page` INTEGER NOT NULL, `last_attempted_page` INTEGER NOT NULL, `last_successful_page` INTEGER NOT NULL, `total_pages` INTEGER NOT NULL, `is_complete` INTEGER NOT NULL, `page_size` INTEGER NOT NULL, `retry_after_ms` INTEGER NOT NULL, `failure_count` INTEGER NOT NULL, `retry_budget_remaining` INTEGER NOT NULL, `last_page_fingerprint` TEXT, PRIMARY KEY(`provider_id`, `category_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastHydratedAt",+ "columnName": "last_hydrated_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "itemCount",+ "columnName": "item_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastStatus",+ "columnName": "last_status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "lastError",+ "columnName": "last_error",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lastLoadedPage",+ "columnName": "last_loaded_page",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastAttemptedPage",+ "columnName": "last_attempted_page",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastSuccessfulPage",+ "columnName": "last_successful_page",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "totalPages",+ "columnName": "total_pages",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isComplete",+ "columnName": "is_complete",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "pageSize",+ "columnName": "page_size",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "retryAfterMs",+ "columnName": "retry_after_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "failureCount",+ "columnName": "failure_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "retryBudgetRemaining",+ "columnName": "retry_budget_remaining",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastPageFingerprint",+ "columnName": "last_page_fingerprint",+ "affinity": "TEXT"+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "provider_id",+ "category_id"+ ]+ },+ "indices": [+ {+ "name": "index_series_category_hydration_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_category_hydration_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "epg_sources",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `url` TEXT NOT NULL, `enabled` INTEGER NOT NULL, `last_refresh_at` INTEGER NOT NULL, `last_success_at` INTEGER NOT NULL, `last_error` TEXT, `priority` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, `etag` TEXT, `last_modified_header` TEXT)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "url",+ "columnName": "url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "enabled",+ "columnName": "enabled",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastRefreshAt",+ "columnName": "last_refresh_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastSuccessAt",+ "columnName": "last_success_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastError",+ "columnName": "last_error",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "priority",+ "columnName": "priority",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "etag",+ "columnName": "etag",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lastModifiedHeader",+ "columnName": "last_modified_header",+ "affinity": "TEXT"+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_epg_sources_url",+ "unique": true,+ "columnNames": [+ "url"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_epg_sources_url` ON `${TABLE_NAME}` (`url`)"+ }+ ]+ },+ {+ "tableName": "provider_epg_sources",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `epg_source_id` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `enabled` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`epg_source_id`) REFERENCES `epg_sources`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "epgSourceId",+ "columnName": "epg_source_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "priority",+ "columnName": "priority",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "enabled",+ "columnName": "enabled",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_provider_epg_sources_provider_id_epg_source_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "epg_source_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_provider_epg_sources_provider_id_epg_source_id` ON `${TABLE_NAME}` (`provider_id`, `epg_source_id`)"+ },+ {+ "name": "index_provider_epg_sources_epg_source_id",+ "unique": false,+ "columnNames": [+ "epg_source_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_provider_epg_sources_epg_source_id` ON `${TABLE_NAME}` (`epg_source_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ },+ {+ "table": "epg_sources",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "epg_source_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "epg_channels",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `epg_source_id` INTEGER NOT NULL, `xmltv_channel_id` TEXT NOT NULL, `display_name` TEXT NOT NULL, `normalized_name` TEXT NOT NULL, `icon_url` TEXT, FOREIGN KEY(`epg_source_id`) REFERENCES `epg_sources`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "epgSourceId",+ "columnName": "epg_source_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "xmltvChannelId",+ "columnName": "xmltv_channel_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "displayName",+ "columnName": "display_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "normalizedName",+ "columnName": "normalized_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "iconUrl",+ "columnName": "icon_url",+ "affinity": "TEXT"+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_epg_channels_epg_source_id_xmltv_channel_id",+ "unique": true,+ "columnNames": [+ "epg_source_id",+ "xmltv_channel_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_epg_channels_epg_source_id_xmltv_channel_id` ON `${TABLE_NAME}` (`epg_source_id`, `xmltv_channel_id`)"+ },+ {+ "name": "index_epg_channels_epg_source_id",+ "unique": false,+ "columnNames": [+ "epg_source_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_channels_epg_source_id` ON `${TABLE_NAME}` (`epg_source_id`)"+ },+ {+ "name": "index_epg_channels_normalized_name",+ "unique": false,+ "columnNames": [+ "normalized_name"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_channels_normalized_name` ON `${TABLE_NAME}` (`normalized_name`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "epg_sources",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "epg_source_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "epg_programmes",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `epg_source_id` INTEGER NOT NULL, `xmltv_channel_id` TEXT NOT NULL, `start_time` INTEGER NOT NULL, `end_time` INTEGER NOT NULL, `title` TEXT NOT NULL, `subtitle` TEXT, `description` TEXT NOT NULL, `category` TEXT, `lang` TEXT NOT NULL, `rating` TEXT, `image_url` TEXT, `episode_info` TEXT, FOREIGN KEY(`epg_source_id`) REFERENCES `epg_sources`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "epgSourceId",+ "columnName": "epg_source_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "xmltvChannelId",+ "columnName": "xmltv_channel_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "startTime",+ "columnName": "start_time",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "endTime",+ "columnName": "end_time",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "title",+ "columnName": "title",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "subtitle",+ "columnName": "subtitle",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "description",+ "columnName": "description",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "category",+ "columnName": "category",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lang",+ "columnName": "lang",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "rating",+ "columnName": "rating",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "imageUrl",+ "columnName": "image_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "episodeInfo",+ "columnName": "episode_info",+ "affinity": "TEXT"+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_epg_programmes_epg_source_id_xmltv_channel_id_start_time",+ "unique": false,+ "columnNames": [+ "epg_source_id",+ "xmltv_channel_id",+ "start_time"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_programmes_epg_source_id_xmltv_channel_id_start_time` ON `${TABLE_NAME}` (`epg_source_id`, `xmltv_channel_id`, `start_time`)"+ },+ {+ "name": "index_epg_programmes_epg_source_id_xmltv_channel_id_start_time_end_time",+ "unique": true,+ "columnNames": [+ "epg_source_id",+ "xmltv_channel_id",+ "start_time",+ "end_time"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_epg_programmes_epg_source_id_xmltv_channel_id_start_time_end_time` ON `${TABLE_NAME}` (`epg_source_id`, `xmltv_channel_id`, `start_time`, `end_time`)"+ },+ {+ "name": "index_epg_programmes_epg_source_id",+ "unique": false,+ "columnNames": [+ "epg_source_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_programmes_epg_source_id` ON `${TABLE_NAME}` (`epg_source_id`)"+ },+ {+ "name": "index_epg_programmes_start_time",+ "unique": false,+ "columnNames": [+ "start_time"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_programmes_start_time` ON `${TABLE_NAME}` (`start_time`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "epg_sources",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "epg_source_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "channel_epg_mappings",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_channel_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `source_type` TEXT NOT NULL, `epg_source_id` INTEGER, `xmltv_channel_id` TEXT, `match_type` TEXT, `confidence` REAL NOT NULL, `matched_at` INTEGER NOT NULL, `failed_attempts` INTEGER NOT NULL, `source` TEXT, `is_manual_override` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerChannelId",+ "columnName": "provider_channel_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "sourceType",+ "columnName": "source_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "epgSourceId",+ "columnName": "epg_source_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "xmltvChannelId",+ "columnName": "xmltv_channel_id",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "matchType",+ "columnName": "match_type",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "confidence",+ "columnName": "confidence",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "matchedAt",+ "columnName": "matched_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "failedAttempts",+ "columnName": "failed_attempts",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "source",+ "columnName": "source",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "isManualOverride",+ "columnName": "is_manual_override",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_channel_epg_mappings_provider_id_provider_channel_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "provider_channel_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_channel_epg_mappings_provider_id_provider_channel_id` ON `${TABLE_NAME}` (`provider_id`, `provider_channel_id`)"+ },+ {+ "name": "index_channel_epg_mappings_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channel_epg_mappings_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "combined_m3u_profiles",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `enabled` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "enabled",+ "columnName": "enabled",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ }+ },+ {+ "tableName": "combined_m3u_profile_members",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `profile_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `enabled` INTEGER NOT NULL, FOREIGN KEY(`profile_id`) REFERENCES `combined_m3u_profiles`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "profileId",+ "columnName": "profile_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "priority",+ "columnName": "priority",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "enabled",+ "columnName": "enabled",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_combined_m3u_profile_members_profile_id",+ "unique": false,+ "columnNames": [+ "profile_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_combined_m3u_profile_members_profile_id` ON `${TABLE_NAME}` (`profile_id`)"+ },+ {+ "name": "index_combined_m3u_profile_members_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_combined_m3u_profile_members_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_combined_m3u_profile_members_profile_id_provider_id",+ "unique": true,+ "columnNames": [+ "profile_id",+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_combined_m3u_profile_members_profile_id_provider_id` ON `${TABLE_NAME}` (`profile_id`, `provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "combined_m3u_profiles",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "profile_id"+ ],+ "referencedColumns": [+ "id"+ ]+ },+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "recording_schedules",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, `channel_name` TEXT NOT NULL, `stream_url` TEXT NOT NULL, `program_title` TEXT, `requested_start_ms` INTEGER NOT NULL, `requested_end_ms` INTEGER NOT NULL, `recurrence` TEXT NOT NULL, `recurring_rule_id` TEXT, `enabled` INTEGER NOT NULL, `is_manual` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelId",+ "columnName": "channel_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelName",+ "columnName": "channel_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "programTitle",+ "columnName": "program_title",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "requestedStartMs",+ "columnName": "requested_start_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "requestedEndMs",+ "columnName": "requested_end_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "recurrence",+ "columnName": "recurrence",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "recurringRuleId",+ "columnName": "recurring_rule_id",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "enabled",+ "columnName": "enabled",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isManual",+ "columnName": "is_manual",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "priority",+ "columnName": "priority",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_recording_schedules_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_schedules_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_recording_schedules_enabled_requested_start_ms",+ "unique": false,+ "columnNames": [+ "enabled",+ "requested_start_ms"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_schedules_enabled_requested_start_ms` ON `${TABLE_NAME}` (`enabled`, `requested_start_ms`)"+ },+ {+ "name": "index_recording_schedules_recurring_rule_id",+ "unique": false,+ "columnNames": [+ "recurring_rule_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_schedules_recurring_rule_id` ON `${TABLE_NAME}` (`recurring_rule_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "recording_runs",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `schedule_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, `channel_name` TEXT NOT NULL, `stream_url` TEXT NOT NULL, `program_title` TEXT, `scheduled_start_ms` INTEGER NOT NULL, `scheduled_end_ms` INTEGER NOT NULL, `recurrence` TEXT NOT NULL, `recurring_rule_id` TEXT, `status` TEXT NOT NULL, `source_type` TEXT NOT NULL, `resolved_url` TEXT, `headers_json` TEXT NOT NULL, `user_agent` TEXT, `expiration_time` INTEGER, `provider_label` TEXT, `output_uri` TEXT, `output_display_path` TEXT, `bytes_written` INTEGER NOT NULL, `average_throughput_bps` INTEGER NOT NULL, `retry_count` INTEGER NOT NULL, `last_progress_at_ms` INTEGER, `failure_category` TEXT NOT NULL, `failure_reason` TEXT, `terminal_at_ms` INTEGER, `started_at_ms` INTEGER, `ended_at_ms` INTEGER, `schedule_enabled` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `alarm_start_at_ms` INTEGER, `alarm_stop_at_ms` INTEGER, `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, `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": "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": "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"+ ]+ }+ }+ ],+ "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, '0d861f0a1b10ce876e377cd8ec30c6dc')"+ ]+ }+}\ No newline at end of filediff --git a/data/schemas/com.streamvault.data.local.StreamVaultDatabase/70.json b/data/schemas/com.streamvault.data.local.StreamVaultDatabase/70.jsonnew file mode 100644index 00000000..201282be--- /dev/null+++ b/data/schemas/com.streamvault.data.local.StreamVaultDatabase/70.json@@ -0,0 +1,5706 @@+{+ "formatVersion": 1,+ "database": {+ "version": 70,+ "identityHash": "f8248619b42d1a301f9008cccc603eab",+ "entities": [+ {+ "tableName": "providers",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `type` TEXT NOT NULL, `server_url` TEXT NOT NULL, `username` TEXT NOT NULL, `password` TEXT NOT NULL, `m3u_url` TEXT NOT NULL, `epg_url` TEXT NOT NULL, `http_user_agent` TEXT NOT NULL, `http_headers` TEXT NOT NULL, `stalker_mac_address` TEXT NOT NULL, `stalker_device_profile` TEXT NOT NULL, `stalker_device_timezone` TEXT NOT NULL, `stalker_device_locale` TEXT NOT NULL, `stalker_serial_number` TEXT NOT NULL, `stalker_device_id` TEXT NOT NULL, `stalker_device_id2` TEXT NOT NULL, `stalker_signature` TEXT NOT NULL, `stalker_advanced_options_json` TEXT NOT NULL, `stalker_auth_mode` TEXT NOT NULL, `stalker_portal_profile` TEXT NOT NULL, `stalker_portal_fingerprint` TEXT NOT NULL, `stalker_mag_preset` TEXT NOT NULL, `stalker_last_bootstrap_recipe` TEXT NOT NULL, `stalker_endpoint_preference` TEXT NOT NULL, `stalker_cookie_mode` TEXT NOT NULL, `stalker_playback_backend_hint` TEXT NOT NULL, `stalker_last_playback_mode` TEXT, `stalker_credentials_required` INTEGER NOT NULL, `stalker_mac_required` INTEGER NOT NULL, `stalker_uses_temp_links` INTEGER NOT NULL, `stalker_module_restricted` INTEGER NOT NULL, `stalker_strict_fingerprint_required` INTEGER NOT NULL, `stalker_recipe_fallback_used` INTEGER NOT NULL, `stalker_recipe_rediscovery_attempts` INTEGER NOT NULL, `is_active` INTEGER NOT NULL, `max_connections` INTEGER NOT NULL, `expiration_date` INTEGER, `api_version` TEXT, `allowed_output_formats_json` TEXT NOT NULL, `epg_sync_mode` TEXT NOT NULL, `guide_source_policy` TEXT NOT NULL, `channel_logo_source_policy` TEXT NOT NULL, `xtream_fast_sync_enabled` INTEGER NOT NULL, `xtream_live_sync_mode` TEXT NOT NULL, `m3u_vod_classification_enabled` INTEGER NOT NULL, `status` TEXT NOT NULL, `last_synced_at` INTEGER NOT NULL, `created_at` INTEGER NOT NULL)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "type",+ "columnName": "type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "serverUrl",+ "columnName": "server_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "username",+ "columnName": "username",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "password",+ "columnName": "password",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "m3uUrl",+ "columnName": "m3u_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "epgUrl",+ "columnName": "epg_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "httpUserAgent",+ "columnName": "http_user_agent",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "httpHeaders",+ "columnName": "http_headers",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerMacAddress",+ "columnName": "stalker_mac_address",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerDeviceProfile",+ "columnName": "stalker_device_profile",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerDeviceTimezone",+ "columnName": "stalker_device_timezone",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerDeviceLocale",+ "columnName": "stalker_device_locale",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerSerialNumber",+ "columnName": "stalker_serial_number",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerDeviceId",+ "columnName": "stalker_device_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerDeviceId2",+ "columnName": "stalker_device_id2",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerSignature",+ "columnName": "stalker_signature",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerAdvancedOptionsJson",+ "columnName": "stalker_advanced_options_json",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerAuthMode",+ "columnName": "stalker_auth_mode",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerPortalProfile",+ "columnName": "stalker_portal_profile",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerPortalFingerprint",+ "columnName": "stalker_portal_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerMagPreset",+ "columnName": "stalker_mag_preset",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerLastBootstrapRecipe",+ "columnName": "stalker_last_bootstrap_recipe",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerEndpointPreference",+ "columnName": "stalker_endpoint_preference",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerCookieMode",+ "columnName": "stalker_cookie_mode",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerPlaybackBackendHint",+ "columnName": "stalker_playback_backend_hint",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerLastPlaybackMode",+ "columnName": "stalker_last_playback_mode",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "stalkerCredentialsRequired",+ "columnName": "stalker_credentials_required",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "stalkerMacRequired",+ "columnName": "stalker_mac_required",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "stalkerUsesTemporaryLinks",+ "columnName": "stalker_uses_temp_links",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "stalkerModuleRestricted",+ "columnName": "stalker_module_restricted",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "stalkerStrictFingerprintRequired",+ "columnName": "stalker_strict_fingerprint_required",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "stalkerRecipeFallbackUsed",+ "columnName": "stalker_recipe_fallback_used",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "stalkerRecipeRediscoveryAttempts",+ "columnName": "stalker_recipe_rediscovery_attempts",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isActive",+ "columnName": "is_active",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "maxConnections",+ "columnName": "max_connections",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "expirationDate",+ "columnName": "expiration_date",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "apiVersion",+ "columnName": "api_version",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "allowedOutputFormatsJson",+ "columnName": "allowed_output_formats_json",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "epgSyncMode",+ "columnName": "epg_sync_mode",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "guideSourcePolicy",+ "columnName": "guide_source_policy",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "channelLogoSourcePolicy",+ "columnName": "channel_logo_source_policy",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "xtreamFastSyncEnabled",+ "columnName": "xtream_fast_sync_enabled",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "xtreamLiveSyncMode",+ "columnName": "xtream_live_sync_mode",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "m3uVodClassificationEnabled",+ "columnName": "m3u_vod_classification_enabled",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "status",+ "columnName": "status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "lastSyncedAt",+ "columnName": "last_synced_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_providers_server_url_username_stalker_mac_address",+ "unique": true,+ "columnNames": [+ "server_url",+ "username",+ "stalker_mac_address"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_providers_server_url_username_stalker_mac_address` ON `${TABLE_NAME}` (`server_url`, `username`, `stalker_mac_address`)"+ }+ ]+ },+ {+ "tableName": "channels",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `stream_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `logo_url` TEXT, `group_title` TEXT, `category_id` INTEGER, `category_name` TEXT, `stream_url` TEXT NOT NULL, `epg_channel_id` TEXT, `number` INTEGER NOT NULL, `catch_up_supported` INTEGER NOT NULL, `catch_up_days` INTEGER NOT NULL, `catchUpSource` TEXT, `provider_id` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, `logical_group_id` TEXT NOT NULL, `error_count` INTEGER NOT NULL, `quality_options_json` TEXT, `sync_fingerprint` TEXT NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "streamId",+ "columnName": "stream_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "logoUrl",+ "columnName": "logo_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "groupTitle",+ "columnName": "group_title",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "categoryName",+ "columnName": "category_name",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "epgChannelId",+ "columnName": "epg_channel_id",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "number",+ "columnName": "number",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "catchUpSupported",+ "columnName": "catch_up_supported",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "catchUpDays",+ "columnName": "catch_up_days",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "catchUpSource",+ "columnName": "catchUpSource",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isUserProtected",+ "columnName": "is_user_protected",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "logicalGroupId",+ "columnName": "logical_group_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "errorCount",+ "columnName": "error_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "qualityOptionsJson",+ "columnName": "quality_options_json",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "syncFingerprint",+ "columnName": "sync_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_channels_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_channels_provider_id_category_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "category_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_provider_id_category_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`)"+ },+ {+ "name": "index_channels_provider_id_stream_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "stream_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_channels_provider_id_stream_id` ON `${TABLE_NAME}` (`provider_id`, `stream_id`)"+ },+ {+ "name": "index_channels_logical_group_id",+ "unique": false,+ "columnNames": [+ "logical_group_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_logical_group_id` ON `${TABLE_NAME}` (`logical_group_id`)"+ },+ {+ "name": "index_channels_provider_id_category_id_logical_group_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "category_id",+ "logical_group_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_provider_id_category_id_logical_group_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`, `logical_group_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "channel_preferences",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `channel_id` INTEGER NOT NULL, `aspect_ratio` TEXT, `audio_video_offset_ms` INTEGER, `updated_at` INTEGER NOT NULL, FOREIGN KEY(`channel_id`) REFERENCES `channels`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelId",+ "columnName": "channel_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "aspectRatio",+ "columnName": "aspect_ratio",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "audioVideoOffsetMs",+ "columnName": "audio_video_offset_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_channel_preferences_channel_id",+ "unique": true,+ "columnNames": [+ "channel_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_channel_preferences_channel_id` ON `${TABLE_NAME}` (`channel_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "channels",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "channel_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "channels_fts",+ "createSql": "CREATE VIRTUAL TABLE IF NOT EXISTS `${TABLE_NAME}` USING FTS4(`name` TEXT NOT NULL, content=`channels`)",+ "fields": [+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": []+ },+ "ftsVersion": "FTS4",+ "ftsOptions": {+ "tokenizer": "simple",+ "tokenizerArgs": [],+ "contentTable": "channels",+ "languageIdColumnName": "",+ "matchInfo": "FTS4",+ "notIndexedColumns": [],+ "prefixSizes": [],+ "preferredOrder": "ASC"+ },+ "contentSyncTriggers": [+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_BEFORE_UPDATE BEFORE UPDATE ON `channels` BEGIN DELETE FROM `channels_fts` WHERE `docid`=OLD.`rowid`; END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_BEFORE_DELETE BEFORE DELETE ON `channels` BEGIN DELETE FROM `channels_fts` WHERE `docid`=OLD.`rowid`; END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_AFTER_UPDATE AFTER UPDATE ON `channels` BEGIN INSERT INTO `channels_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_AFTER_INSERT AFTER INSERT ON `channels` BEGIN INSERT INTO `channels_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END"+ ]+ },+ {+ "tableName": "movies",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `stream_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `poster_url` TEXT, `backdrop_url` TEXT, `category_id` INTEGER, `category_name` TEXT, `stream_url` TEXT NOT NULL, `container_extension` TEXT, `plot` TEXT, `cast` TEXT, `director` TEXT, `genre` TEXT, `release_date` TEXT, `duration` TEXT, `duration_seconds` INTEGER NOT NULL, `rating` REAL NOT NULL, `year` TEXT, `tmdb_id` INTEGER, `youtube_trailer` TEXT, `provider_id` INTEGER NOT NULL, `watch_progress` INTEGER NOT NULL, `watch_count` INTEGER NOT NULL, `last_watched_at` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, `added_at` INTEGER NOT NULL, `cache_state` TEXT NOT NULL, `detail_hydrated_at` INTEGER NOT NULL, `remote_stale_at` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "streamId",+ "columnName": "stream_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "posterUrl",+ "columnName": "poster_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "backdropUrl",+ "columnName": "backdrop_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "categoryName",+ "columnName": "category_name",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "containerExtension",+ "columnName": "container_extension",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "plot",+ "columnName": "plot",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "cast",+ "columnName": "cast",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "director",+ "columnName": "director",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "genre",+ "columnName": "genre",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "releaseDate",+ "columnName": "release_date",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "duration",+ "columnName": "duration",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "durationSeconds",+ "columnName": "duration_seconds",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "rating",+ "columnName": "rating",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "year",+ "columnName": "year",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "tmdbId",+ "columnName": "tmdb_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "youtubeTrailer",+ "columnName": "youtube_trailer",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "watchProgress",+ "columnName": "watch_progress",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "watchCount",+ "columnName": "watch_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastWatchedAt",+ "columnName": "last_watched_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isUserProtected",+ "columnName": "is_user_protected",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "syncFingerprint",+ "columnName": "sync_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "addedAt",+ "columnName": "added_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "cacheState",+ "columnName": "cache_state",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "detailHydratedAt",+ "columnName": "detail_hydrated_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "remoteStaleAt",+ "columnName": "remote_stale_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_movies_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_movies_provider_id_category_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "category_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id_category_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`)"+ },+ {+ "name": "index_movies_provider_id_stream_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "stream_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_movies_provider_id_stream_id` ON `${TABLE_NAME}` (`provider_id`, `stream_id`)"+ },+ {+ "name": "index_movies_provider_id_name_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "name",+ "id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id_name_id` ON `${TABLE_NAME}` (`provider_id`, `name`, `id`)"+ },+ {+ "name": "index_movies_provider_id_category_id_name_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "category_id",+ "name",+ "id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id_category_id_name_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`, `name`, `id`)"+ },+ {+ "name": "index_movies_provider_id_rating_name_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "rating",+ "name",+ "id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id_rating_name_id` ON `${TABLE_NAME}` (`provider_id`, `rating`, `name`, `id`)"+ },+ {+ "name": "index_movies_provider_id_added_at_release_date_name_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "added_at",+ "release_date",+ "name",+ "id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id_added_at_release_date_name_id` ON `${TABLE_NAME}` (`provider_id`, `added_at`, `release_date`, `name`, `id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "movies_fts",+ "createSql": "CREATE VIRTUAL TABLE IF NOT EXISTS `${TABLE_NAME}` USING FTS4(`name` TEXT NOT NULL, content=`movies`)",+ "fields": [+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": []+ },+ "ftsVersion": "FTS4",+ "ftsOptions": {+ "tokenizer": "simple",+ "tokenizerArgs": [],+ "contentTable": "movies",+ "languageIdColumnName": "",+ "matchInfo": "FTS4",+ "notIndexedColumns": [],+ "prefixSizes": [],+ "preferredOrder": "ASC"+ },+ "contentSyncTriggers": [+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_movies_fts_BEFORE_UPDATE BEFORE UPDATE ON `movies` BEGIN DELETE FROM `movies_fts` WHERE `docid`=OLD.`rowid`; END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_movies_fts_BEFORE_DELETE BEFORE DELETE ON `movies` BEGIN DELETE FROM `movies_fts` WHERE `docid`=OLD.`rowid`; END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_movies_fts_AFTER_UPDATE AFTER UPDATE ON `movies` BEGIN INSERT INTO `movies_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_movies_fts_AFTER_INSERT AFTER INSERT ON `movies` BEGIN INSERT INTO `movies_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END"+ ]+ },+ {+ "tableName": "series",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `series_id` INTEGER NOT NULL, `provider_series_id` TEXT, `name` TEXT NOT NULL, `poster_url` TEXT, `backdrop_url` TEXT, `category_id` INTEGER, `category_name` TEXT, `plot` TEXT, `cast` TEXT, `director` TEXT, `genre` TEXT, `release_date` TEXT, `rating` REAL NOT NULL, `tmdb_id` INTEGER, `youtube_trailer` TEXT, `episode_run_time` TEXT, `last_modified` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, `cache_state` TEXT NOT NULL, `detail_hydrated_at` INTEGER NOT NULL, `remote_stale_at` INTEGER NOT NULL, 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+ }+ ],+ "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, `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": "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, `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": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "syncFingerprint",+ "columnName": "sync_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "session_id",+ "provider_id",+ "category_id",+ "type"+ ]+ },+ "indices": [+ {+ "name": "index_category_import_stage_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_category_import_stage_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_category_import_stage_session_id_provider_id",+ "unique": false,+ "columnNames": [+ "session_id",+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_category_import_stage_session_id_provider_id` ON `${TABLE_NAME}` (`session_id`, `provider_id`)"+ },+ {+ "name": "index_category_import_stage_provider_id_type",+ "unique": false,+ "columnNames": [+ "provider_id",+ "type"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_category_import_stage_provider_id_type` ON `${TABLE_NAME}` (`provider_id`, `type`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "programs",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `channel_id` TEXT NOT NULL, `title` TEXT NOT NULL, `description` TEXT NOT NULL, `start_time` INTEGER NOT NULL, `end_time` INTEGER NOT NULL, `lang` TEXT NOT NULL, `rating` TEXT, `image_url` TEXT, `genre` TEXT, `category` TEXT, `has_archive` INTEGER NOT NULL)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelId",+ "columnName": "channel_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "title",+ "columnName": "title",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "description",+ "columnName": "description",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "startTime",+ "columnName": "start_time",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "endTime",+ "columnName": "end_time",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lang",+ "columnName": "lang",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "rating",+ "columnName": "rating",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "imageUrl",+ "columnName": "image_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "genre",+ "columnName": "genre",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "category",+ "columnName": "category",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "hasArchive",+ "columnName": "has_archive",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_programs_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_programs_provider_id_channel_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "channel_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_channel_id` ON `${TABLE_NAME}` (`provider_id`, `channel_id`)"+ },+ {+ "name": "index_programs_provider_id_end_time_channel_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "end_time",+ "channel_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_end_time_channel_id` ON `${TABLE_NAME}` (`provider_id`, `end_time`, `channel_id`)"+ },+ {+ "name": "index_programs_provider_id_start_time_end_time",+ "unique": false,+ "columnNames": [+ "provider_id",+ "start_time",+ "end_time"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_start_time_end_time` ON `${TABLE_NAME}` (`provider_id`, `start_time`, `end_time`)"+ },+ {+ "name": "index_programs_start_time",+ "unique": false,+ "columnNames": [+ "start_time"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_start_time` ON `${TABLE_NAME}` (`start_time`)"+ },+ {+ "name": "index_programs_provider_id_channel_id_start_time",+ "unique": false,+ "columnNames": [+ "provider_id",+ "channel_id",+ "start_time"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_channel_id_start_time` ON `${TABLE_NAME}` (`provider_id`, `channel_id`, `start_time`)"+ },+ {+ "name": "index_programs_provider_id_channel_id_start_time_end_time",+ "unique": true,+ "columnNames": [+ "provider_id",+ "channel_id",+ "start_time",+ "end_time"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_programs_provider_id_channel_id_start_time_end_time` ON `${TABLE_NAME}` (`provider_id`, `channel_id`, `start_time`, `end_time`)"+ }+ ]+ },+ {+ "tableName": "favorites",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `content_id` INTEGER NOT NULL, `content_type` TEXT NOT NULL, `position` INTEGER NOT NULL, `group_id` INTEGER, `group_key` INTEGER NOT NULL, `added_at` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`group_id`) REFERENCES `virtual_groups`(`id`) ON UPDATE NO ACTION ON DELETE SET NULL )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentId",+ "columnName": "content_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentType",+ "columnName": "content_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "position",+ "columnName": "position",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "groupId",+ "columnName": "group_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "groupKey",+ "columnName": "group_key",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "addedAt",+ "columnName": "added_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_favorites_provider_id_content_id_content_type_group_key",+ "unique": true,+ "columnNames": [+ "provider_id",+ "content_id",+ "content_type",+ "group_key"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_favorites_provider_id_content_id_content_type_group_key` ON `${TABLE_NAME}` (`provider_id`, `content_id`, `content_type`, `group_key`)"+ },+ {+ "name": "index_favorites_provider_id_content_type_group_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "content_type",+ "group_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_favorites_provider_id_content_type_group_id` ON `${TABLE_NAME}` (`provider_id`, `content_type`, `group_id`)"+ },+ {+ "name": "index_favorites_group_id_position",+ "unique": false,+ "columnNames": [+ "group_id",+ "position"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_favorites_group_id_position` ON `${TABLE_NAME}` (`group_id`, `position`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ },+ {+ "table": "virtual_groups",+ "onDelete": "SET NULL",+ "onUpdate": "NO ACTION",+ "columns": [+ "group_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "virtual_groups",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `icon_emoji` TEXT, `position` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `content_type` TEXT NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "iconEmoji",+ "columnName": "icon_emoji",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "position",+ "columnName": "position",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentType",+ "columnName": "content_type",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_virtual_groups_provider_id_content_type",+ "unique": false,+ "columnNames": [+ "provider_id",+ "content_type"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_virtual_groups_provider_id_content_type` ON `${TABLE_NAME}` (`provider_id`, `content_type`)"+ },+ {+ "name": "index_virtual_groups_position",+ "unique": false,+ "columnNames": [+ "position"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_virtual_groups_position` ON `${TABLE_NAME}` (`position`)"+ },+ {+ "name": "index_virtual_groups_content_type",+ "unique": false,+ "columnNames": [+ "content_type"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_virtual_groups_content_type` ON `${TABLE_NAME}` (`content_type`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "playback_history",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `content_id` INTEGER NOT NULL, `content_type` TEXT NOT NULL, `provider_id` INTEGER NOT NULL, `title` TEXT NOT NULL, `poster_url` TEXT, `stream_url` TEXT NOT NULL, `resume_position_ms` INTEGER NOT NULL, `total_duration_ms` INTEGER NOT NULL, `last_watched_at` INTEGER NOT NULL, `watch_count` INTEGER NOT NULL, `watched_status` TEXT NOT NULL, `series_id` INTEGER, `season_number` INTEGER, `episode_number` INTEGER, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentId",+ "columnName": "content_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentType",+ "columnName": "content_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "title",+ "columnName": "title",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "posterUrl",+ "columnName": "poster_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "resumePositionMs",+ "columnName": "resume_position_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "totalDurationMs",+ "columnName": "total_duration_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastWatchedAt",+ "columnName": "last_watched_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "watchCount",+ "columnName": "watch_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "watchedStatus",+ "columnName": "watched_status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "seriesId",+ "columnName": "series_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "seasonNumber",+ "columnName": "season_number",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "episodeNumber",+ "columnName": "episode_number",+ "affinity": "INTEGER"+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_playback_history_content_id_content_type_provider_id",+ "unique": true,+ "columnNames": [+ "content_id",+ "content_type",+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_playback_history_content_id_content_type_provider_id` ON `${TABLE_NAME}` (`content_id`, `content_type`, `provider_id`)"+ },+ {+ "name": "index_playback_history_last_watched_at",+ "unique": false,+ "columnNames": [+ "last_watched_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_history_last_watched_at` ON `${TABLE_NAME}` (`last_watched_at`)"+ },+ {+ "name": "index_playback_history_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_history_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_playback_history_provider_id_content_type_content_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "content_type",+ "content_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_history_provider_id_content_type_content_id` ON `${TABLE_NAME}` (`provider_id`, `content_type`, `content_id`)"+ },+ {+ "name": "index_playback_history_provider_id_content_type_last_watched_at",+ "unique": false,+ "columnNames": [+ "provider_id",+ "content_type",+ "last_watched_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_history_provider_id_content_type_last_watched_at` ON `${TABLE_NAME}` (`provider_id`, `content_type`, `last_watched_at`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "tmdb_identity",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`tmdb_id` INTEGER NOT NULL, `content_type` TEXT NOT NULL, `canonical_provider_id` INTEGER NOT NULL, `first_seen_at` INTEGER NOT NULL, PRIMARY KEY(`tmdb_id`, `content_type`), FOREIGN KEY(`canonical_provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "tmdbId",+ "columnName": "tmdb_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentType",+ "columnName": "content_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "canonicalProviderId",+ "columnName": "canonical_provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "firstSeenAt",+ "columnName": "first_seen_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "tmdb_id",+ "content_type"+ ]+ },+ "indices": [+ {+ "name": "index_tmdb_identity_content_type",+ "unique": false,+ "columnNames": [+ "content_type"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_tmdb_identity_content_type` ON `${TABLE_NAME}` (`content_type`)"+ },+ {+ "name": "index_tmdb_identity_canonical_provider_id",+ "unique": false,+ "columnNames": [+ "canonical_provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_tmdb_identity_canonical_provider_id` ON `${TABLE_NAME}` (`canonical_provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "canonical_provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "search_history",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `query` TEXT NOT NULL, `content_scope` TEXT NOT NULL, `provider_id` INTEGER NOT NULL, `used_at` INTEGER NOT NULL, `use_count` INTEGER NOT NULL)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "query",+ "columnName": "query",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "contentScope",+ "columnName": "content_scope",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "usedAt",+ "columnName": "used_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "useCount",+ "columnName": "use_count",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_search_history_content_scope_provider_id_used_at",+ "unique": false,+ "columnNames": [+ "content_scope",+ "provider_id",+ "used_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_search_history_content_scope_provider_id_used_at` ON `${TABLE_NAME}` (`content_scope`, `provider_id`, `used_at`)"+ },+ {+ "name": "index_search_history_used_at",+ "unique": false,+ "columnNames": [+ "used_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_search_history_used_at` ON `${TABLE_NAME}` (`used_at`)"+ },+ {+ "name": "index_search_history_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_search_history_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_search_history_query_content_scope_provider_id",+ "unique": true,+ "columnNames": [+ "query",+ "content_scope",+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_search_history_query_content_scope_provider_id` ON `${TABLE_NAME}` (`query`, `content_scope`, `provider_id`)"+ }+ ]+ },+ {+ "tableName": "sync_metadata",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `last_live_sync` INTEGER NOT NULL, `last_live_success` INTEGER NOT NULL, `last_movie_sync` INTEGER NOT NULL, `last_series_sync` INTEGER NOT NULL, `last_series_success` INTEGER NOT NULL, `last_epg_sync` INTEGER NOT NULL, `last_epg_success` INTEGER NOT NULL, `last_movie_attempt` INTEGER NOT NULL, `last_movie_success` INTEGER NOT NULL, `last_movie_partial` INTEGER NOT NULL, `live_count` INTEGER NOT NULL, `movie_count` INTEGER NOT NULL, `series_count` INTEGER NOT NULL, `epg_count` INTEGER NOT NULL, `last_sync_status` TEXT NOT NULL, `movie_sync_mode` TEXT NOT NULL, `movie_warnings_count` INTEGER NOT NULL, `movie_catalog_stale` INTEGER NOT NULL, `live_avoid_full_until` INTEGER NOT NULL, `movie_avoid_full_until` INTEGER NOT NULL, `series_avoid_full_until` INTEGER NOT NULL, `live_sequential_failures_remembered` INTEGER NOT NULL, `live_healthy_sync_streak` INTEGER NOT NULL, `movie_parallel_failures_remembered` INTEGER NOT NULL, `movie_healthy_sync_streak` INTEGER NOT NULL, `series_sequential_failures_remembered` INTEGER NOT NULL, `series_healthy_sync_streak` INTEGER NOT NULL, PRIMARY KEY(`provider_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastLiveSync",+ "columnName": "last_live_sync",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastLiveSuccess",+ "columnName": "last_live_success",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastMovieSync",+ "columnName": "last_movie_sync",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastSeriesSync",+ "columnName": "last_series_sync",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastSeriesSuccess",+ "columnName": "last_series_success",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastEpgSync",+ "columnName": "last_epg_sync",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastEpgSuccess",+ "columnName": "last_epg_success",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastMovieAttempt",+ "columnName": "last_movie_attempt",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastMovieSuccess",+ "columnName": "last_movie_success",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastMoviePartial",+ "columnName": "last_movie_partial",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "liveCount",+ "columnName": "live_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "movieCount",+ "columnName": "movie_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "seriesCount",+ "columnName": "series_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "epgCount",+ "columnName": "epg_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastSyncStatus",+ "columnName": "last_sync_status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "movieSyncMode",+ "columnName": "movie_sync_mode",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "movieWarningsCount",+ "columnName": "movie_warnings_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "movieCatalogStale",+ "columnName": "movie_catalog_stale",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "liveAvoidFullUntil",+ "columnName": "live_avoid_full_until",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "movieAvoidFullUntil",+ "columnName": "movie_avoid_full_until",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "seriesAvoidFullUntil",+ "columnName": "series_avoid_full_until",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "liveSequentialFailuresRemembered",+ "columnName": "live_sequential_failures_remembered",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "liveHealthySyncStreak",+ "columnName": "live_healthy_sync_streak",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "movieParallelFailuresRemembered",+ "columnName": "movie_parallel_failures_remembered",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "movieHealthySyncStreak",+ "columnName": "movie_healthy_sync_streak",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "seriesSequentialFailuresRemembered",+ "columnName": "series_sequential_failures_remembered",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "seriesHealthySyncStreak",+ "columnName": "series_healthy_sync_streak",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "provider_id"+ ]+ },+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "movie_category_hydration",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `category_id` INTEGER NOT NULL, `last_hydrated_at` INTEGER NOT NULL, `item_count` INTEGER NOT NULL, `last_status` TEXT NOT NULL, `last_error` TEXT, `last_loaded_page` INTEGER NOT NULL, `last_attempted_page` INTEGER NOT NULL, `last_successful_page` INTEGER NOT NULL, `total_pages` INTEGER NOT NULL, `is_complete` INTEGER NOT NULL, `page_size` INTEGER NOT NULL, `retry_after_ms` INTEGER NOT NULL, `failure_count` INTEGER NOT NULL, `retry_budget_remaining` INTEGER NOT NULL, `last_page_fingerprint` TEXT, PRIMARY KEY(`provider_id`, `category_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastHydratedAt",+ "columnName": "last_hydrated_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "itemCount",+ "columnName": "item_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastStatus",+ "columnName": "last_status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "lastError",+ "columnName": "last_error",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lastLoadedPage",+ "columnName": "last_loaded_page",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastAttemptedPage",+ "columnName": "last_attempted_page",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastSuccessfulPage",+ "columnName": "last_successful_page",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "totalPages",+ "columnName": "total_pages",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isComplete",+ "columnName": "is_complete",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "pageSize",+ "columnName": "page_size",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "retryAfterMs",+ "columnName": "retry_after_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "failureCount",+ "columnName": "failure_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "retryBudgetRemaining",+ "columnName": "retry_budget_remaining",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastPageFingerprint",+ "columnName": "last_page_fingerprint",+ "affinity": "TEXT"+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "provider_id",+ "category_id"+ ]+ },+ "indices": [+ {+ "name": "index_movie_category_hydration_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movie_category_hydration_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "series_category_hydration",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `category_id` INTEGER NOT NULL, `last_hydrated_at` INTEGER NOT NULL, `item_count` INTEGER NOT NULL, `last_status` TEXT NOT NULL, `last_error` TEXT, `last_loaded_page` INTEGER NOT NULL, `last_attempted_page` INTEGER NOT NULL, `last_successful_page` INTEGER NOT NULL, `total_pages` INTEGER NOT NULL, `is_complete` INTEGER NOT NULL, `page_size` INTEGER NOT NULL, `retry_after_ms` INTEGER NOT NULL, `failure_count` INTEGER NOT NULL, `retry_budget_remaining` INTEGER NOT NULL, `last_page_fingerprint` TEXT, PRIMARY KEY(`provider_id`, `category_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastHydratedAt",+ "columnName": "last_hydrated_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "itemCount",+ "columnName": "item_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastStatus",+ "columnName": "last_status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "lastError",+ "columnName": "last_error",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lastLoadedPage",+ "columnName": "last_loaded_page",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastAttemptedPage",+ "columnName": "last_attempted_page",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastSuccessfulPage",+ "columnName": "last_successful_page",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "totalPages",+ "columnName": "total_pages",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isComplete",+ "columnName": "is_complete",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "pageSize",+ "columnName": "page_size",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "retryAfterMs",+ "columnName": "retry_after_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "failureCount",+ "columnName": "failure_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "retryBudgetRemaining",+ "columnName": "retry_budget_remaining",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastPageFingerprint",+ "columnName": "last_page_fingerprint",+ "affinity": "TEXT"+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "provider_id",+ "category_id"+ ]+ },+ "indices": [+ {+ "name": "index_series_category_hydration_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_category_hydration_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "epg_sources",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `url` TEXT NOT NULL, `enabled` INTEGER NOT NULL, `last_refresh_at` INTEGER NOT NULL, `last_success_at` INTEGER NOT NULL, `last_error` TEXT, `priority` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, `etag` TEXT, `last_modified_header` TEXT)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "url",+ "columnName": "url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "enabled",+ "columnName": "enabled",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastRefreshAt",+ "columnName": "last_refresh_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastSuccessAt",+ "columnName": "last_success_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastError",+ "columnName": "last_error",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "priority",+ "columnName": "priority",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "etag",+ "columnName": "etag",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lastModifiedHeader",+ "columnName": "last_modified_header",+ "affinity": "TEXT"+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_epg_sources_url",+ "unique": true,+ "columnNames": [+ "url"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_epg_sources_url` ON `${TABLE_NAME}` (`url`)"+ }+ ]+ },+ {+ "tableName": "provider_epg_sources",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `epg_source_id` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `enabled` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`epg_source_id`) REFERENCES `epg_sources`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "epgSourceId",+ "columnName": "epg_source_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "priority",+ "columnName": "priority",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "enabled",+ "columnName": "enabled",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_provider_epg_sources_provider_id_epg_source_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "epg_source_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_provider_epg_sources_provider_id_epg_source_id` ON `${TABLE_NAME}` (`provider_id`, `epg_source_id`)"+ },+ {+ "name": "index_provider_epg_sources_epg_source_id",+ "unique": false,+ "columnNames": [+ "epg_source_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_provider_epg_sources_epg_source_id` ON `${TABLE_NAME}` (`epg_source_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ },+ {+ "table": "epg_sources",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "epg_source_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "epg_channels",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `epg_source_id` INTEGER NOT NULL, `xmltv_channel_id` TEXT NOT NULL, `display_name` TEXT NOT NULL, `normalized_name` TEXT NOT NULL, `icon_url` TEXT, FOREIGN KEY(`epg_source_id`) REFERENCES `epg_sources`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "epgSourceId",+ "columnName": "epg_source_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "xmltvChannelId",+ "columnName": "xmltv_channel_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "displayName",+ "columnName": "display_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "normalizedName",+ "columnName": "normalized_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "iconUrl",+ "columnName": "icon_url",+ "affinity": "TEXT"+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_epg_channels_epg_source_id_xmltv_channel_id",+ "unique": true,+ "columnNames": [+ "epg_source_id",+ "xmltv_channel_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_epg_channels_epg_source_id_xmltv_channel_id` ON `${TABLE_NAME}` (`epg_source_id`, `xmltv_channel_id`)"+ },+ {+ "name": "index_epg_channels_epg_source_id",+ "unique": false,+ "columnNames": [+ "epg_source_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_channels_epg_source_id` ON `${TABLE_NAME}` (`epg_source_id`)"+ },+ {+ "name": "index_epg_channels_normalized_name",+ "unique": false,+ "columnNames": [+ "normalized_name"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_channels_normalized_name` ON `${TABLE_NAME}` (`normalized_name`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "epg_sources",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "epg_source_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "epg_programmes",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `epg_source_id` INTEGER NOT NULL, `xmltv_channel_id` TEXT NOT NULL, `start_time` INTEGER NOT NULL, `end_time` INTEGER NOT NULL, `title` TEXT NOT NULL, `subtitle` TEXT, `description` TEXT NOT NULL, `category` TEXT, `lang` TEXT NOT NULL, `rating` TEXT, `image_url` TEXT, `episode_info` TEXT, FOREIGN KEY(`epg_source_id`) REFERENCES `epg_sources`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "epgSourceId",+ "columnName": "epg_source_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "xmltvChannelId",+ "columnName": "xmltv_channel_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "startTime",+ "columnName": "start_time",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "endTime",+ "columnName": "end_time",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "title",+ "columnName": "title",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "subtitle",+ "columnName": "subtitle",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "description",+ "columnName": "description",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "category",+ "columnName": "category",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lang",+ "columnName": "lang",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "rating",+ "columnName": "rating",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "imageUrl",+ "columnName": "image_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "episodeInfo",+ "columnName": "episode_info",+ "affinity": "TEXT"+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_epg_programmes_epg_source_id_xmltv_channel_id_start_time",+ "unique": false,+ "columnNames": [+ "epg_source_id",+ "xmltv_channel_id",+ "start_time"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_programmes_epg_source_id_xmltv_channel_id_start_time` ON `${TABLE_NAME}` (`epg_source_id`, `xmltv_channel_id`, `start_time`)"+ },+ {+ "name": "index_epg_programmes_epg_source_id_xmltv_channel_id_start_time_end_time",+ "unique": true,+ "columnNames": [+ "epg_source_id",+ "xmltv_channel_id",+ "start_time",+ "end_time"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_epg_programmes_epg_source_id_xmltv_channel_id_start_time_end_time` ON `${TABLE_NAME}` (`epg_source_id`, `xmltv_channel_id`, `start_time`, `end_time`)"+ },+ {+ "name": "index_epg_programmes_epg_source_id",+ "unique": false,+ "columnNames": [+ "epg_source_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_programmes_epg_source_id` ON `${TABLE_NAME}` (`epg_source_id`)"+ },+ {+ "name": "index_epg_programmes_start_time",+ "unique": false,+ "columnNames": [+ "start_time"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_programmes_start_time` ON `${TABLE_NAME}` (`start_time`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "epg_sources",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "epg_source_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "channel_epg_mappings",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_channel_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `source_type` TEXT NOT NULL, `epg_source_id` INTEGER, `xmltv_channel_id` TEXT, `match_type` TEXT, `confidence` REAL NOT NULL, `matched_at` INTEGER NOT NULL, `failed_attempts` INTEGER NOT NULL, `source` TEXT, `is_manual_override` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerChannelId",+ "columnName": "provider_channel_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "sourceType",+ "columnName": "source_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "epgSourceId",+ "columnName": "epg_source_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "xmltvChannelId",+ "columnName": "xmltv_channel_id",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "matchType",+ "columnName": "match_type",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "confidence",+ "columnName": "confidence",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "matchedAt",+ "columnName": "matched_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "failedAttempts",+ "columnName": "failed_attempts",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "source",+ "columnName": "source",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "isManualOverride",+ "columnName": "is_manual_override",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_channel_epg_mappings_provider_id_provider_channel_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "provider_channel_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_channel_epg_mappings_provider_id_provider_channel_id` ON `${TABLE_NAME}` (`provider_id`, `provider_channel_id`)"+ },+ {+ "name": "index_channel_epg_mappings_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channel_epg_mappings_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "combined_m3u_profiles",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `enabled` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "enabled",+ "columnName": "enabled",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ }+ },+ {+ "tableName": "combined_m3u_profile_members",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `profile_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `enabled` INTEGER NOT NULL, FOREIGN KEY(`profile_id`) REFERENCES `combined_m3u_profiles`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "profileId",+ "columnName": "profile_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "priority",+ "columnName": "priority",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "enabled",+ "columnName": "enabled",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_combined_m3u_profile_members_profile_id",+ "unique": false,+ "columnNames": [+ "profile_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_combined_m3u_profile_members_profile_id` ON `${TABLE_NAME}` (`profile_id`)"+ },+ {+ "name": "index_combined_m3u_profile_members_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_combined_m3u_profile_members_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_combined_m3u_profile_members_profile_id_provider_id",+ "unique": true,+ "columnNames": [+ "profile_id",+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_combined_m3u_profile_members_profile_id_provider_id` ON `${TABLE_NAME}` (`profile_id`, `provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "combined_m3u_profiles",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "profile_id"+ ],+ "referencedColumns": [+ "id"+ ]+ },+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "recording_schedules",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, `channel_name` TEXT NOT NULL, `stream_url` TEXT NOT NULL, `program_title` TEXT, `requested_start_ms` INTEGER NOT NULL, `requested_end_ms` INTEGER NOT NULL, `recurrence` TEXT NOT NULL, `recurring_rule_id` TEXT, `enabled` INTEGER NOT NULL, `is_manual` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelId",+ "columnName": "channel_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelName",+ "columnName": "channel_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "programTitle",+ "columnName": "program_title",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "requestedStartMs",+ "columnName": "requested_start_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "requestedEndMs",+ "columnName": "requested_end_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "recurrence",+ "columnName": "recurrence",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "recurringRuleId",+ "columnName": "recurring_rule_id",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "enabled",+ "columnName": "enabled",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isManual",+ "columnName": "is_manual",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "priority",+ "columnName": "priority",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_recording_schedules_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_schedules_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_recording_schedules_enabled_requested_start_ms",+ "unique": false,+ "columnNames": [+ "enabled",+ "requested_start_ms"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_schedules_enabled_requested_start_ms` ON `${TABLE_NAME}` (`enabled`, `requested_start_ms`)"+ },+ {+ "name": "index_recording_schedules_recurring_rule_id",+ "unique": false,+ "columnNames": [+ "recurring_rule_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_schedules_recurring_rule_id` ON `${TABLE_NAME}` (`recurring_rule_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "recording_runs",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `schedule_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, `channel_name` TEXT NOT NULL, `stream_url` TEXT NOT NULL, `program_title` TEXT, `scheduled_start_ms` INTEGER NOT NULL, `scheduled_end_ms` INTEGER NOT NULL, `recurrence` TEXT NOT NULL, `recurring_rule_id` TEXT, `status` TEXT NOT NULL, `source_type` TEXT NOT NULL, `resolved_url` TEXT, `headers_json` TEXT NOT NULL, `user_agent` TEXT, `expiration_time` INTEGER, `provider_label` TEXT, `output_uri` TEXT, `output_display_path` TEXT, `bytes_written` INTEGER NOT NULL, `average_throughput_bps` INTEGER NOT NULL, `retry_count` INTEGER NOT NULL, `last_progress_at_ms` INTEGER, `failure_category` TEXT NOT NULL, `failure_reason` TEXT, `terminal_at_ms` INTEGER, `started_at_ms` INTEGER, `ended_at_ms` INTEGER, `schedule_enabled` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `alarm_start_at_ms` INTEGER, `alarm_stop_at_ms` INTEGER, `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": "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"+ ]+ }+ }+ ],+ "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, 'f8248619b42d1a301f9008cccc603eab')"+ ]+ }+}\ No newline at end of filediff --git a/data/schemas/com.streamvault.data.local.StreamVaultDatabase/71.json b/data/schemas/com.streamvault.data.local.StreamVaultDatabase/71.jsonnew file mode 100644index 00000000..491ec350--- /dev/null+++ b/data/schemas/com.streamvault.data.local.StreamVaultDatabase/71.json@@ -0,0 +1,5966 @@+{+ "formatVersion": 1,+ "database": {+ "version": 71,+ "identityHash": "e54785d2d9a682a544b0922df46d1285",+ "entities": [+ {+ "tableName": "providers",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `type` TEXT NOT NULL, `server_url` TEXT NOT NULL, `username` TEXT NOT NULL, `password` TEXT NOT NULL, `m3u_url` TEXT NOT NULL, `epg_url` TEXT NOT NULL, `http_user_agent` TEXT NOT NULL, `http_headers` TEXT NOT NULL, `stalker_mac_address` TEXT NOT NULL, `stalker_device_profile` TEXT NOT NULL, `stalker_device_timezone` TEXT NOT NULL, `stalker_device_locale` TEXT NOT NULL, `stalker_serial_number` TEXT NOT NULL, `stalker_device_id` TEXT NOT NULL, `stalker_device_id2` TEXT NOT NULL, `stalker_signature` TEXT NOT NULL, `stalker_advanced_options_json` TEXT NOT NULL, `stalker_auth_mode` TEXT NOT NULL, `stalker_portal_profile` TEXT NOT NULL, `stalker_portal_fingerprint` TEXT NOT NULL, `stalker_mag_preset` TEXT NOT NULL, `stalker_last_bootstrap_recipe` TEXT NOT NULL, `stalker_endpoint_preference` TEXT NOT NULL, `stalker_cookie_mode` TEXT NOT NULL, `stalker_playback_backend_hint` TEXT NOT NULL, `stalker_last_playback_mode` TEXT, `stalker_credentials_required` INTEGER NOT NULL, `stalker_mac_required` INTEGER NOT NULL, `stalker_uses_temp_links` INTEGER NOT NULL, `stalker_module_restricted` INTEGER NOT NULL, `stalker_strict_fingerprint_required` INTEGER NOT NULL, `stalker_recipe_fallback_used` INTEGER NOT NULL, `stalker_recipe_rediscovery_attempts` INTEGER NOT NULL, `is_active` INTEGER NOT NULL, `max_connections` INTEGER NOT NULL, `expiration_date` INTEGER, `api_version` TEXT, `allowed_output_formats_json` TEXT NOT NULL, `epg_sync_mode` TEXT NOT NULL, `guide_source_policy` TEXT NOT NULL, `channel_logo_source_policy` TEXT NOT NULL, `xtream_fast_sync_enabled` INTEGER NOT NULL, `xtream_live_sync_mode` TEXT NOT NULL, `m3u_vod_classification_enabled` INTEGER NOT NULL, `status` TEXT NOT NULL, `last_synced_at` INTEGER NOT NULL, `created_at` INTEGER NOT NULL)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "type",+ "columnName": "type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "serverUrl",+ "columnName": "server_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "username",+ "columnName": "username",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "password",+ "columnName": "password",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "m3uUrl",+ "columnName": "m3u_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "epgUrl",+ "columnName": "epg_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "httpUserAgent",+ "columnName": "http_user_agent",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "httpHeaders",+ "columnName": "http_headers",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerMacAddress",+ "columnName": "stalker_mac_address",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerDeviceProfile",+ "columnName": "stalker_device_profile",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerDeviceTimezone",+ "columnName": "stalker_device_timezone",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerDeviceLocale",+ "columnName": "stalker_device_locale",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerSerialNumber",+ "columnName": "stalker_serial_number",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerDeviceId",+ "columnName": "stalker_device_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerDeviceId2",+ "columnName": "stalker_device_id2",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerSignature",+ "columnName": "stalker_signature",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerAdvancedOptionsJson",+ "columnName": "stalker_advanced_options_json",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerAuthMode",+ "columnName": "stalker_auth_mode",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerPortalProfile",+ "columnName": "stalker_portal_profile",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerPortalFingerprint",+ "columnName": "stalker_portal_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerMagPreset",+ "columnName": "stalker_mag_preset",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerLastBootstrapRecipe",+ "columnName": "stalker_last_bootstrap_recipe",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerEndpointPreference",+ "columnName": "stalker_endpoint_preference",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerCookieMode",+ "columnName": "stalker_cookie_mode",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerPlaybackBackendHint",+ "columnName": "stalker_playback_backend_hint",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerLastPlaybackMode",+ "columnName": "stalker_last_playback_mode",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "stalkerCredentialsRequired",+ "columnName": "stalker_credentials_required",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "stalkerMacRequired",+ "columnName": "stalker_mac_required",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "stalkerUsesTemporaryLinks",+ "columnName": "stalker_uses_temp_links",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "stalkerModuleRestricted",+ "columnName": "stalker_module_restricted",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "stalkerStrictFingerprintRequired",+ "columnName": "stalker_strict_fingerprint_required",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "stalkerRecipeFallbackUsed",+ "columnName": "stalker_recipe_fallback_used",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "stalkerRecipeRediscoveryAttempts",+ "columnName": "stalker_recipe_rediscovery_attempts",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isActive",+ "columnName": "is_active",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "maxConnections",+ "columnName": "max_connections",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "expirationDate",+ "columnName": "expiration_date",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "apiVersion",+ "columnName": "api_version",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "allowedOutputFormatsJson",+ "columnName": "allowed_output_formats_json",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "epgSyncMode",+ "columnName": "epg_sync_mode",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "guideSourcePolicy",+ "columnName": "guide_source_policy",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "channelLogoSourcePolicy",+ "columnName": "channel_logo_source_policy",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "xtreamFastSyncEnabled",+ "columnName": "xtream_fast_sync_enabled",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "xtreamLiveSyncMode",+ "columnName": "xtream_live_sync_mode",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "m3uVodClassificationEnabled",+ "columnName": "m3u_vod_classification_enabled",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "status",+ "columnName": "status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "lastSyncedAt",+ "columnName": "last_synced_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_providers_server_url_username_stalker_mac_address",+ "unique": true,+ "columnNames": [+ "server_url",+ "username",+ "stalker_mac_address"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_providers_server_url_username_stalker_mac_address` ON `${TABLE_NAME}` (`server_url`, `username`, `stalker_mac_address`)"+ }+ ]+ },+ {+ "tableName": "channels",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `stream_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `logo_url` TEXT, `group_title` TEXT, `category_id` INTEGER, `category_name` TEXT, `stream_url` TEXT NOT NULL, `epg_channel_id` TEXT, `number` INTEGER NOT NULL, `catch_up_supported` INTEGER NOT NULL, `catch_up_days` INTEGER NOT NULL, `catchUpSource` TEXT, `provider_id` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, `logical_group_id` TEXT NOT NULL, `error_count` INTEGER NOT NULL, `quality_options_json` TEXT, `sync_fingerprint` TEXT NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "streamId",+ "columnName": "stream_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "logoUrl",+ "columnName": "logo_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "groupTitle",+ "columnName": "group_title",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "categoryName",+ "columnName": "category_name",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "epgChannelId",+ "columnName": "epg_channel_id",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "number",+ "columnName": "number",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "catchUpSupported",+ "columnName": "catch_up_supported",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "catchUpDays",+ "columnName": "catch_up_days",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "catchUpSource",+ "columnName": "catchUpSource",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isUserProtected",+ "columnName": "is_user_protected",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "logicalGroupId",+ "columnName": "logical_group_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "errorCount",+ "columnName": "error_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "qualityOptionsJson",+ "columnName": "quality_options_json",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "syncFingerprint",+ "columnName": "sync_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_channels_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_channels_provider_id_category_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "category_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_provider_id_category_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`)"+ },+ {+ "name": "index_channels_provider_id_stream_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "stream_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_channels_provider_id_stream_id` ON `${TABLE_NAME}` (`provider_id`, `stream_id`)"+ },+ {+ "name": "index_channels_logical_group_id",+ "unique": false,+ "columnNames": [+ "logical_group_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_logical_group_id` ON `${TABLE_NAME}` (`logical_group_id`)"+ },+ {+ "name": "index_channels_provider_id_category_id_logical_group_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "category_id",+ "logical_group_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_provider_id_category_id_logical_group_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`, `logical_group_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "channel_preferences",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `channel_id` INTEGER NOT NULL, `aspect_ratio` TEXT, `audio_video_offset_ms` INTEGER, `updated_at` INTEGER NOT NULL, FOREIGN KEY(`channel_id`) REFERENCES `channels`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelId",+ "columnName": "channel_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "aspectRatio",+ "columnName": "aspect_ratio",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "audioVideoOffsetMs",+ "columnName": "audio_video_offset_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_channel_preferences_channel_id",+ "unique": true,+ "columnNames": [+ "channel_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_channel_preferences_channel_id` ON `${TABLE_NAME}` (`channel_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "channels",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "channel_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "channels_fts",+ "createSql": "CREATE VIRTUAL TABLE IF NOT EXISTS `${TABLE_NAME}` USING FTS4(`name` TEXT NOT NULL, content=`channels`)",+ "fields": [+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": []+ },+ "ftsVersion": "FTS4",+ "ftsOptions": {+ "tokenizer": "simple",+ "tokenizerArgs": [],+ "contentTable": "channels",+ "languageIdColumnName": "",+ "matchInfo": "FTS4",+ "notIndexedColumns": [],+ "prefixSizes": [],+ "preferredOrder": "ASC"+ },+ "contentSyncTriggers": [+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_BEFORE_UPDATE BEFORE UPDATE ON `channels` BEGIN DELETE FROM `channels_fts` WHERE `docid`=OLD.`rowid`; END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_BEFORE_DELETE BEFORE DELETE ON `channels` BEGIN DELETE FROM `channels_fts` WHERE `docid`=OLD.`rowid`; END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_AFTER_UPDATE AFTER UPDATE ON `channels` BEGIN INSERT INTO `channels_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_AFTER_INSERT AFTER INSERT ON `channels` BEGIN INSERT INTO `channels_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END"+ ]+ },+ {+ "tableName": "movies",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `stream_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `poster_url` TEXT, `backdrop_url` TEXT, `category_id` INTEGER, `category_name` TEXT, `stream_url` TEXT NOT NULL, `container_extension` TEXT, `plot` TEXT, `cast` TEXT, `director` TEXT, `genre` TEXT, `release_date` TEXT, `duration` TEXT, `duration_seconds` INTEGER NOT NULL, `rating` REAL NOT NULL, `year` TEXT, `tmdb_id` INTEGER, `youtube_trailer` TEXT, `provider_id` INTEGER NOT NULL, `watch_progress` INTEGER NOT NULL, `watch_count` INTEGER NOT NULL, `last_watched_at` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, `added_at` INTEGER NOT NULL, `cache_state` TEXT NOT NULL, `detail_hydrated_at` INTEGER NOT NULL, `remote_stale_at` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "streamId",+ "columnName": "stream_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "posterUrl",+ "columnName": "poster_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "backdropUrl",+ "columnName": "backdrop_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "categoryName",+ "columnName": "category_name",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "containerExtension",+ "columnName": "container_extension",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "plot",+ "columnName": "plot",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "cast",+ "columnName": "cast",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "director",+ "columnName": "director",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "genre",+ "columnName": "genre",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "releaseDate",+ "columnName": "release_date",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "duration",+ "columnName": "duration",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "durationSeconds",+ "columnName": "duration_seconds",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "rating",+ "columnName": "rating",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "year",+ "columnName": "year",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "tmdbId",+ "columnName": "tmdb_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "youtubeTrailer",+ "columnName": "youtube_trailer",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "watchProgress",+ "columnName": "watch_progress",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "watchCount",+ "columnName": "watch_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastWatchedAt",+ "columnName": "last_watched_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isUserProtected",+ "columnName": "is_user_protected",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "syncFingerprint",+ "columnName": "sync_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "addedAt",+ "columnName": "added_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "cacheState",+ "columnName": "cache_state",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "detailHydratedAt",+ "columnName": "detail_hydrated_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "remoteStaleAt",+ "columnName": "remote_stale_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_movies_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_movies_provider_id_category_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "category_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id_category_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`)"+ },+ {+ "name": "index_movies_provider_id_stream_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "stream_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_movies_provider_id_stream_id` ON `${TABLE_NAME}` (`provider_id`, `stream_id`)"+ },+ {+ "name": "index_movies_provider_id_name_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "name",+ "id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id_name_id` ON `${TABLE_NAME}` (`provider_id`, `name`, `id`)"+ },+ {+ "name": "index_movies_provider_id_category_id_name_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "category_id",+ "name",+ "id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id_category_id_name_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`, `name`, `id`)"+ },+ {+ "name": "index_movies_provider_id_rating_name_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "rating",+ "name",+ "id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id_rating_name_id` ON `${TABLE_NAME}` (`provider_id`, `rating`, `name`, `id`)"+ },+ {+ "name": "index_movies_provider_id_added_at_release_date_name_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "added_at",+ "release_date",+ "name",+ "id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id_added_at_release_date_name_id` ON `${TABLE_NAME}` (`provider_id`, `added_at`, `release_date`, `name`, `id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "movies_fts",+ "createSql": "CREATE VIRTUAL TABLE IF NOT EXISTS `${TABLE_NAME}` USING FTS4(`name` TEXT NOT NULL, content=`movies`)",+ "fields": [+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": []+ },+ "ftsVersion": "FTS4",+ "ftsOptions": {+ "tokenizer": "simple",+ "tokenizerArgs": [],+ "contentTable": "movies",+ "languageIdColumnName": "",+ "matchInfo": "FTS4",+ "notIndexedColumns": [],+ "prefixSizes": [],+ "preferredOrder": "ASC"+ },+ "contentSyncTriggers": [+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_movies_fts_BEFORE_UPDATE BEFORE UPDATE ON `movies` BEGIN DELETE FROM `movies_fts` WHERE `docid`=OLD.`rowid`; END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_movies_fts_BEFORE_DELETE BEFORE DELETE ON `movies` BEGIN DELETE FROM `movies_fts` WHERE `docid`=OLD.`rowid`; END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_movies_fts_AFTER_UPDATE AFTER UPDATE ON `movies` BEGIN INSERT INTO `movies_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_movies_fts_AFTER_INSERT AFTER INSERT ON `movies` BEGIN INSERT INTO `movies_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END"+ ]+ },+ {+ "tableName": "series",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `series_id` INTEGER NOT NULL, `provider_series_id` TEXT, `name` TEXT NOT NULL, `poster_url` TEXT, `backdrop_url` TEXT, `category_id` INTEGER, `category_name` TEXT, `plot` TEXT, `cast` TEXT, `director` TEXT, `genre` TEXT, `release_date` TEXT, `rating` REAL NOT NULL, `tmdb_id` INTEGER, `youtube_trailer` TEXT, `episode_run_time` TEXT, `last_modified` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, `cache_state` TEXT NOT NULL, `detail_hydrated_at` INTEGER NOT NULL, `remote_stale_at` INTEGER NOT NULL, 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+ }+ ],+ "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, `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": "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, `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": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "syncFingerprint",+ "columnName": "sync_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "session_id",+ "provider_id",+ "category_id",+ "type"+ ]+ },+ "indices": [+ {+ "name": "index_category_import_stage_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_category_import_stage_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_category_import_stage_session_id_provider_id",+ "unique": false,+ "columnNames": [+ "session_id",+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_category_import_stage_session_id_provider_id` ON `${TABLE_NAME}` (`session_id`, `provider_id`)"+ },+ {+ "name": "index_category_import_stage_provider_id_type",+ "unique": false,+ "columnNames": [+ "provider_id",+ "type"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_category_import_stage_provider_id_type` ON `${TABLE_NAME}` (`provider_id`, `type`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "programs",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `channel_id` TEXT NOT NULL, `title` TEXT NOT NULL, `description` TEXT NOT NULL, `start_time` INTEGER NOT NULL, `end_time` INTEGER NOT NULL, `lang` TEXT NOT NULL, `rating` TEXT, `image_url` TEXT, `genre` TEXT, `category` TEXT, `has_archive` INTEGER NOT NULL)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelId",+ "columnName": "channel_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "title",+ "columnName": "title",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "description",+ "columnName": "description",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "startTime",+ "columnName": "start_time",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "endTime",+ "columnName": "end_time",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lang",+ "columnName": "lang",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "rating",+ "columnName": "rating",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "imageUrl",+ "columnName": "image_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "genre",+ "columnName": "genre",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "category",+ "columnName": "category",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "hasArchive",+ "columnName": "has_archive",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_programs_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_programs_provider_id_channel_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "channel_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_channel_id` ON `${TABLE_NAME}` (`provider_id`, `channel_id`)"+ },+ {+ "name": "index_programs_provider_id_end_time_channel_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "end_time",+ "channel_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_end_time_channel_id` ON `${TABLE_NAME}` (`provider_id`, `end_time`, `channel_id`)"+ },+ {+ "name": "index_programs_provider_id_start_time_end_time",+ "unique": false,+ "columnNames": [+ "provider_id",+ "start_time",+ "end_time"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_start_time_end_time` ON `${TABLE_NAME}` (`provider_id`, `start_time`, `end_time`)"+ },+ {+ "name": "index_programs_start_time",+ "unique": false,+ "columnNames": [+ "start_time"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_start_time` ON `${TABLE_NAME}` (`start_time`)"+ },+ {+ "name": "index_programs_provider_id_channel_id_start_time",+ "unique": false,+ "columnNames": [+ "provider_id",+ "channel_id",+ "start_time"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_channel_id_start_time` ON `${TABLE_NAME}` (`provider_id`, `channel_id`, `start_time`)"+ },+ {+ "name": "index_programs_provider_id_channel_id_start_time_end_time",+ "unique": true,+ "columnNames": [+ "provider_id",+ "channel_id",+ "start_time",+ "end_time"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_programs_provider_id_channel_id_start_time_end_time` ON `${TABLE_NAME}` (`provider_id`, `channel_id`, `start_time`, `end_time`)"+ }+ ]+ },+ {+ "tableName": "favorites",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `content_id` INTEGER NOT NULL, `content_type` TEXT NOT NULL, `position` INTEGER NOT NULL, `group_id` INTEGER, `group_key` INTEGER NOT NULL, `added_at` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`group_id`) REFERENCES `virtual_groups`(`id`) ON UPDATE NO ACTION ON DELETE SET NULL )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentId",+ "columnName": "content_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentType",+ "columnName": "content_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "position",+ "columnName": "position",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "groupId",+ "columnName": "group_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "groupKey",+ "columnName": "group_key",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "addedAt",+ "columnName": "added_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_favorites_provider_id_content_id_content_type_group_key",+ "unique": true,+ "columnNames": [+ "provider_id",+ "content_id",+ "content_type",+ "group_key"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_favorites_provider_id_content_id_content_type_group_key` ON `${TABLE_NAME}` (`provider_id`, `content_id`, `content_type`, `group_key`)"+ },+ {+ "name": "index_favorites_provider_id_content_type_group_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "content_type",+ "group_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_favorites_provider_id_content_type_group_id` ON `${TABLE_NAME}` (`provider_id`, `content_type`, `group_id`)"+ },+ {+ "name": "index_favorites_group_id_position",+ "unique": false,+ "columnNames": [+ "group_id",+ "position"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_favorites_group_id_position` ON `${TABLE_NAME}` (`group_id`, `position`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ },+ {+ "table": "virtual_groups",+ "onDelete": "SET NULL",+ "onUpdate": "NO ACTION",+ "columns": [+ "group_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "virtual_groups",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `icon_emoji` TEXT, `position` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `content_type` TEXT NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "iconEmoji",+ "columnName": "icon_emoji",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "position",+ "columnName": "position",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentType",+ "columnName": "content_type",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_virtual_groups_provider_id_content_type",+ "unique": false,+ "columnNames": [+ "provider_id",+ "content_type"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_virtual_groups_provider_id_content_type` ON `${TABLE_NAME}` (`provider_id`, `content_type`)"+ },+ {+ "name": "index_virtual_groups_position",+ "unique": false,+ "columnNames": [+ "position"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_virtual_groups_position` ON `${TABLE_NAME}` (`position`)"+ },+ {+ "name": "index_virtual_groups_content_type",+ "unique": false,+ "columnNames": [+ "content_type"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_virtual_groups_content_type` ON `${TABLE_NAME}` (`content_type`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "playback_history",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `content_id` INTEGER NOT NULL, `content_type` TEXT NOT NULL, `provider_id` INTEGER NOT NULL, `title` TEXT NOT NULL, `poster_url` TEXT, `stream_url` TEXT NOT NULL, `resume_position_ms` INTEGER NOT NULL, `total_duration_ms` INTEGER NOT NULL, `last_watched_at` INTEGER NOT NULL, `watch_count` INTEGER NOT NULL, `watched_status` TEXT NOT NULL, `series_id` INTEGER, `season_number` INTEGER, `episode_number` INTEGER, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentId",+ "columnName": "content_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentType",+ "columnName": "content_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "title",+ "columnName": "title",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "posterUrl",+ "columnName": "poster_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "resumePositionMs",+ "columnName": "resume_position_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "totalDurationMs",+ "columnName": "total_duration_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastWatchedAt",+ "columnName": "last_watched_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "watchCount",+ "columnName": "watch_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "watchedStatus",+ "columnName": "watched_status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "seriesId",+ "columnName": "series_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "seasonNumber",+ "columnName": "season_number",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "episodeNumber",+ "columnName": "episode_number",+ "affinity": "INTEGER"+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_playback_history_content_id_content_type_provider_id",+ "unique": true,+ "columnNames": [+ "content_id",+ "content_type",+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_playback_history_content_id_content_type_provider_id` ON `${TABLE_NAME}` (`content_id`, `content_type`, `provider_id`)"+ },+ {+ "name": "index_playback_history_last_watched_at",+ "unique": false,+ "columnNames": [+ "last_watched_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_history_last_watched_at` ON `${TABLE_NAME}` (`last_watched_at`)"+ },+ {+ "name": "index_playback_history_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_history_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_playback_history_provider_id_content_type_content_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "content_type",+ "content_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_history_provider_id_content_type_content_id` ON `${TABLE_NAME}` (`provider_id`, `content_type`, `content_id`)"+ },+ {+ "name": "index_playback_history_provider_id_content_type_last_watched_at",+ "unique": false,+ "columnNames": [+ "provider_id",+ "content_type",+ "last_watched_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_history_provider_id_content_type_last_watched_at` ON `${TABLE_NAME}` (`provider_id`, `content_type`, `last_watched_at`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "tmdb_identity",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`tmdb_id` INTEGER NOT NULL, `content_type` TEXT NOT NULL, `canonical_provider_id` INTEGER NOT NULL, `first_seen_at` INTEGER NOT NULL, PRIMARY KEY(`tmdb_id`, `content_type`), FOREIGN KEY(`canonical_provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "tmdbId",+ "columnName": "tmdb_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentType",+ "columnName": "content_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "canonicalProviderId",+ "columnName": "canonical_provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "firstSeenAt",+ "columnName": "first_seen_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "tmdb_id",+ "content_type"+ ]+ },+ "indices": [+ {+ "name": "index_tmdb_identity_content_type",+ "unique": false,+ "columnNames": [+ "content_type"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_tmdb_identity_content_type` ON `${TABLE_NAME}` (`content_type`)"+ },+ {+ "name": "index_tmdb_identity_canonical_provider_id",+ "unique": false,+ "columnNames": [+ "canonical_provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_tmdb_identity_canonical_provider_id` ON `${TABLE_NAME}` (`canonical_provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "canonical_provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "search_history",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `query` TEXT NOT NULL, `content_scope` TEXT NOT NULL, `provider_id` INTEGER NOT NULL, `used_at` INTEGER NOT NULL, `use_count` INTEGER NOT NULL)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "query",+ "columnName": "query",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "contentScope",+ "columnName": "content_scope",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "usedAt",+ "columnName": "used_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "useCount",+ "columnName": "use_count",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_search_history_content_scope_provider_id_used_at",+ "unique": false,+ "columnNames": [+ "content_scope",+ "provider_id",+ "used_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_search_history_content_scope_provider_id_used_at` ON `${TABLE_NAME}` (`content_scope`, `provider_id`, `used_at`)"+ },+ {+ "name": "index_search_history_used_at",+ "unique": false,+ "columnNames": [+ "used_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_search_history_used_at` ON `${TABLE_NAME}` (`used_at`)"+ },+ {+ "name": "index_search_history_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_search_history_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_search_history_query_content_scope_provider_id",+ "unique": true,+ "columnNames": [+ "query",+ "content_scope",+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_search_history_query_content_scope_provider_id` ON `${TABLE_NAME}` (`query`, `content_scope`, `provider_id`)"+ }+ ]+ },+ {+ "tableName": "sync_metadata",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `last_live_sync` INTEGER NOT NULL, `last_live_success` INTEGER NOT NULL, `last_movie_sync` INTEGER NOT NULL, `last_series_sync` INTEGER NOT NULL, `last_series_success` INTEGER NOT NULL, `last_epg_sync` INTEGER NOT NULL, `last_epg_success` INTEGER NOT NULL, `last_movie_attempt` INTEGER NOT NULL, `last_movie_success` INTEGER NOT NULL, `last_movie_partial` INTEGER NOT NULL, `live_count` INTEGER NOT NULL, `movie_count` INTEGER NOT NULL, `series_count` INTEGER NOT NULL, `epg_count` INTEGER NOT NULL, `last_sync_status` TEXT NOT NULL, `movie_sync_mode` TEXT NOT NULL, `movie_warnings_count` INTEGER NOT NULL, `movie_catalog_stale` INTEGER NOT NULL, `live_avoid_full_until` INTEGER NOT NULL, `movie_avoid_full_until` INTEGER NOT NULL, `series_avoid_full_until` INTEGER NOT NULL, `live_sequential_failures_remembered` INTEGER NOT NULL, `live_healthy_sync_streak` INTEGER NOT NULL, `movie_parallel_failures_remembered` INTEGER NOT NULL, `movie_healthy_sync_streak` INTEGER NOT NULL, `series_sequential_failures_remembered` INTEGER NOT NULL, `series_healthy_sync_streak` INTEGER NOT NULL, PRIMARY KEY(`provider_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastLiveSync",+ "columnName": "last_live_sync",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastLiveSuccess",+ "columnName": "last_live_success",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastMovieSync",+ "columnName": "last_movie_sync",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastSeriesSync",+ "columnName": "last_series_sync",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastSeriesSuccess",+ "columnName": "last_series_success",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastEpgSync",+ "columnName": "last_epg_sync",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastEpgSuccess",+ "columnName": "last_epg_success",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastMovieAttempt",+ "columnName": "last_movie_attempt",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastMovieSuccess",+ "columnName": "last_movie_success",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastMoviePartial",+ "columnName": "last_movie_partial",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "liveCount",+ "columnName": "live_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "movieCount",+ "columnName": "movie_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "seriesCount",+ "columnName": "series_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "epgCount",+ "columnName": "epg_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastSyncStatus",+ "columnName": "last_sync_status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "movieSyncMode",+ "columnName": "movie_sync_mode",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "movieWarningsCount",+ "columnName": "movie_warnings_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "movieCatalogStale",+ "columnName": "movie_catalog_stale",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "liveAvoidFullUntil",+ "columnName": "live_avoid_full_until",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "movieAvoidFullUntil",+ "columnName": "movie_avoid_full_until",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "seriesAvoidFullUntil",+ "columnName": "series_avoid_full_until",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "liveSequentialFailuresRemembered",+ "columnName": "live_sequential_failures_remembered",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "liveHealthySyncStreak",+ "columnName": "live_healthy_sync_streak",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "movieParallelFailuresRemembered",+ "columnName": "movie_parallel_failures_remembered",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "movieHealthySyncStreak",+ "columnName": "movie_healthy_sync_streak",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "seriesSequentialFailuresRemembered",+ "columnName": "series_sequential_failures_remembered",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "seriesHealthySyncStreak",+ "columnName": "series_healthy_sync_streak",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "provider_id"+ ]+ },+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "movie_category_hydration",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `category_id` INTEGER NOT NULL, `last_hydrated_at` INTEGER NOT NULL, `item_count` INTEGER NOT NULL, `last_status` TEXT NOT NULL, `last_error` TEXT, `last_loaded_page` INTEGER NOT NULL, `last_attempted_page` INTEGER NOT NULL, `last_successful_page` INTEGER NOT NULL, `total_pages` INTEGER NOT NULL, `is_complete` INTEGER NOT NULL, `page_size` INTEGER NOT NULL, `retry_after_ms` INTEGER NOT NULL, `failure_count` INTEGER NOT NULL, `retry_budget_remaining` INTEGER NOT NULL, `last_page_fingerprint` TEXT, PRIMARY KEY(`provider_id`, `category_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastHydratedAt",+ "columnName": "last_hydrated_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "itemCount",+ "columnName": "item_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastStatus",+ "columnName": "last_status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "lastError",+ "columnName": "last_error",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lastLoadedPage",+ "columnName": "last_loaded_page",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastAttemptedPage",+ "columnName": "last_attempted_page",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastSuccessfulPage",+ "columnName": "last_successful_page",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "totalPages",+ "columnName": "total_pages",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isComplete",+ "columnName": "is_complete",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "pageSize",+ "columnName": "page_size",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "retryAfterMs",+ "columnName": "retry_after_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "failureCount",+ "columnName": "failure_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "retryBudgetRemaining",+ "columnName": "retry_budget_remaining",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastPageFingerprint",+ "columnName": "last_page_fingerprint",+ "affinity": "TEXT"+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "provider_id",+ "category_id"+ ]+ },+ "indices": [+ {+ "name": "index_movie_category_hydration_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movie_category_hydration_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "series_category_hydration",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `category_id` INTEGER NOT NULL, `last_hydrated_at` INTEGER NOT NULL, `item_count` INTEGER NOT NULL, `last_status` TEXT NOT NULL, `last_error` TEXT, `last_loaded_page` INTEGER NOT NULL, `last_attempted_page` INTEGER NOT NULL, `last_successful_page` INTEGER NOT NULL, `total_pages` INTEGER NOT NULL, `is_complete` INTEGER NOT NULL, `page_size` INTEGER NOT NULL, `retry_after_ms` INTEGER NOT NULL, `failure_count` INTEGER NOT NULL, `retry_budget_remaining` INTEGER NOT NULL, `last_page_fingerprint` TEXT, PRIMARY KEY(`provider_id`, `category_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastHydratedAt",+ "columnName": "last_hydrated_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "itemCount",+ "columnName": "item_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastStatus",+ "columnName": "last_status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "lastError",+ "columnName": "last_error",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lastLoadedPage",+ "columnName": "last_loaded_page",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastAttemptedPage",+ "columnName": "last_attempted_page",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastSuccessfulPage",+ "columnName": "last_successful_page",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "totalPages",+ "columnName": "total_pages",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isComplete",+ "columnName": "is_complete",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "pageSize",+ "columnName": "page_size",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "retryAfterMs",+ "columnName": "retry_after_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "failureCount",+ "columnName": "failure_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "retryBudgetRemaining",+ "columnName": "retry_budget_remaining",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastPageFingerprint",+ "columnName": "last_page_fingerprint",+ "affinity": "TEXT"+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "provider_id",+ "category_id"+ ]+ },+ "indices": [+ {+ "name": "index_series_category_hydration_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_category_hydration_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "epg_sources",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `url` TEXT NOT NULL, `enabled` INTEGER NOT NULL, `last_refresh_at` INTEGER NOT NULL, `last_success_at` INTEGER NOT NULL, `last_error` TEXT, `priority` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, `etag` TEXT, `last_modified_header` TEXT)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "url",+ "columnName": "url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "enabled",+ "columnName": "enabled",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastRefreshAt",+ "columnName": "last_refresh_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastSuccessAt",+ "columnName": "last_success_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastError",+ "columnName": "last_error",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "priority",+ "columnName": "priority",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "etag",+ "columnName": "etag",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lastModifiedHeader",+ "columnName": "last_modified_header",+ "affinity": "TEXT"+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_epg_sources_url",+ "unique": true,+ "columnNames": [+ "url"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_epg_sources_url` ON `${TABLE_NAME}` (`url`)"+ }+ ]+ },+ {+ "tableName": "provider_epg_sources",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `epg_source_id` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `enabled` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`epg_source_id`) REFERENCES `epg_sources`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "epgSourceId",+ "columnName": "epg_source_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "priority",+ "columnName": "priority",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "enabled",+ "columnName": "enabled",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_provider_epg_sources_provider_id_epg_source_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "epg_source_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_provider_epg_sources_provider_id_epg_source_id` ON `${TABLE_NAME}` (`provider_id`, `epg_source_id`)"+ },+ {+ "name": "index_provider_epg_sources_epg_source_id",+ "unique": false,+ "columnNames": [+ "epg_source_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_provider_epg_sources_epg_source_id` ON `${TABLE_NAME}` (`epg_source_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ },+ {+ "table": "epg_sources",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "epg_source_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "epg_channels",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `epg_source_id` INTEGER NOT NULL, `xmltv_channel_id` TEXT NOT NULL, `display_name` TEXT NOT NULL, `normalized_name` TEXT NOT NULL, `icon_url` TEXT, FOREIGN KEY(`epg_source_id`) REFERENCES `epg_sources`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "epgSourceId",+ "columnName": "epg_source_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "xmltvChannelId",+ "columnName": "xmltv_channel_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "displayName",+ "columnName": "display_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "normalizedName",+ "columnName": "normalized_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "iconUrl",+ "columnName": "icon_url",+ "affinity": "TEXT"+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_epg_channels_epg_source_id_xmltv_channel_id",+ "unique": true,+ "columnNames": [+ "epg_source_id",+ "xmltv_channel_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_epg_channels_epg_source_id_xmltv_channel_id` ON `${TABLE_NAME}` (`epg_source_id`, `xmltv_channel_id`)"+ },+ {+ "name": "index_epg_channels_epg_source_id",+ "unique": false,+ "columnNames": [+ "epg_source_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_channels_epg_source_id` ON `${TABLE_NAME}` (`epg_source_id`)"+ },+ {+ "name": "index_epg_channels_normalized_name",+ "unique": false,+ "columnNames": [+ "normalized_name"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_channels_normalized_name` ON `${TABLE_NAME}` (`normalized_name`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "epg_sources",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "epg_source_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "epg_programmes",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `epg_source_id` INTEGER NOT NULL, `xmltv_channel_id` TEXT NOT NULL, `start_time` INTEGER NOT NULL, `end_time` INTEGER NOT NULL, `title` TEXT NOT NULL, `subtitle` TEXT, `description` TEXT NOT NULL, `category` TEXT, `lang` TEXT NOT NULL, `rating` TEXT, `image_url` TEXT, `episode_info` TEXT, FOREIGN KEY(`epg_source_id`) REFERENCES `epg_sources`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "epgSourceId",+ "columnName": "epg_source_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "xmltvChannelId",+ "columnName": "xmltv_channel_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "startTime",+ "columnName": "start_time",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "endTime",+ "columnName": "end_time",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "title",+ "columnName": "title",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "subtitle",+ "columnName": "subtitle",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "description",+ "columnName": "description",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "category",+ "columnName": "category",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lang",+ "columnName": "lang",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "rating",+ "columnName": "rating",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "imageUrl",+ "columnName": "image_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "episodeInfo",+ "columnName": "episode_info",+ "affinity": "TEXT"+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_epg_programmes_epg_source_id_xmltv_channel_id_start_time",+ "unique": false,+ "columnNames": [+ "epg_source_id",+ "xmltv_channel_id",+ "start_time"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_programmes_epg_source_id_xmltv_channel_id_start_time` ON `${TABLE_NAME}` (`epg_source_id`, `xmltv_channel_id`, `start_time`)"+ },+ {+ "name": "index_epg_programmes_epg_source_id_xmltv_channel_id_start_time_end_time",+ "unique": true,+ "columnNames": [+ "epg_source_id",+ "xmltv_channel_id",+ "start_time",+ "end_time"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_epg_programmes_epg_source_id_xmltv_channel_id_start_time_end_time` ON `${TABLE_NAME}` (`epg_source_id`, `xmltv_channel_id`, `start_time`, `end_time`)"+ },+ {+ "name": "index_epg_programmes_epg_source_id",+ "unique": false,+ "columnNames": [+ "epg_source_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_programmes_epg_source_id` ON `${TABLE_NAME}` (`epg_source_id`)"+ },+ {+ "name": "index_epg_programmes_start_time",+ "unique": false,+ "columnNames": [+ "start_time"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_programmes_start_time` ON `${TABLE_NAME}` (`start_time`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "epg_sources",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "epg_source_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "channel_epg_mappings",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_channel_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `source_type` TEXT NOT NULL, `epg_source_id` INTEGER, `xmltv_channel_id` TEXT, `match_type` TEXT, `confidence` REAL NOT NULL, `matched_at` INTEGER NOT NULL, `failed_attempts` INTEGER NOT NULL, `source` TEXT, `is_manual_override` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerChannelId",+ "columnName": "provider_channel_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "sourceType",+ "columnName": "source_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "epgSourceId",+ "columnName": "epg_source_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "xmltvChannelId",+ "columnName": "xmltv_channel_id",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "matchType",+ "columnName": "match_type",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "confidence",+ "columnName": "confidence",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "matchedAt",+ "columnName": "matched_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "failedAttempts",+ "columnName": "failed_attempts",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "source",+ "columnName": "source",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "isManualOverride",+ "columnName": "is_manual_override",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_channel_epg_mappings_provider_id_provider_channel_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "provider_channel_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_channel_epg_mappings_provider_id_provider_channel_id` ON `${TABLE_NAME}` (`provider_id`, `provider_channel_id`)"+ },+ {+ "name": "index_channel_epg_mappings_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channel_epg_mappings_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "combined_m3u_profiles",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `enabled` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "enabled",+ "columnName": "enabled",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ }+ },+ {+ "tableName": "combined_m3u_profile_members",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `profile_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `enabled` INTEGER NOT NULL, FOREIGN KEY(`profile_id`) REFERENCES `combined_m3u_profiles`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "profileId",+ "columnName": "profile_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "priority",+ "columnName": "priority",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "enabled",+ "columnName": "enabled",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_combined_m3u_profile_members_profile_id",+ "unique": false,+ "columnNames": [+ "profile_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_combined_m3u_profile_members_profile_id` ON `${TABLE_NAME}` (`profile_id`)"+ },+ {+ "name": "index_combined_m3u_profile_members_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_combined_m3u_profile_members_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_combined_m3u_profile_members_profile_id_provider_id",+ "unique": true,+ "columnNames": [+ "profile_id",+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_combined_m3u_profile_members_profile_id_provider_id` ON `${TABLE_NAME}` (`profile_id`, `provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "combined_m3u_profiles",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "profile_id"+ ],+ "referencedColumns": [+ "id"+ ]+ },+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "recording_schedules",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, `channel_name` TEXT NOT NULL, `stream_url` TEXT NOT NULL, `program_title` TEXT, `requested_start_ms` INTEGER NOT NULL, `requested_end_ms` INTEGER NOT NULL, `recurrence` TEXT NOT NULL, `recurring_rule_id` TEXT, `enabled` INTEGER NOT NULL, `is_manual` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelId",+ "columnName": "channel_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelName",+ "columnName": "channel_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "programTitle",+ "columnName": "program_title",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "requestedStartMs",+ "columnName": "requested_start_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "requestedEndMs",+ "columnName": "requested_end_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "recurrence",+ "columnName": "recurrence",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "recurringRuleId",+ "columnName": "recurring_rule_id",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "enabled",+ "columnName": "enabled",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isManual",+ "columnName": "is_manual",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "priority",+ "columnName": "priority",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_recording_schedules_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_schedules_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_recording_schedules_enabled_requested_start_ms",+ "unique": false,+ "columnNames": [+ "enabled",+ "requested_start_ms"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_schedules_enabled_requested_start_ms` ON `${TABLE_NAME}` (`enabled`, `requested_start_ms`)"+ },+ {+ "name": "index_recording_schedules_recurring_rule_id",+ "unique": false,+ "columnNames": [+ "recurring_rule_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_schedules_recurring_rule_id` ON `${TABLE_NAME}` (`recurring_rule_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "recording_runs",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `schedule_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, `channel_name` TEXT NOT NULL, `stream_url` TEXT NOT NULL, `program_title` TEXT, `scheduled_start_ms` INTEGER NOT NULL, `scheduled_end_ms` INTEGER NOT NULL, `recurrence` TEXT NOT NULL, `recurring_rule_id` TEXT, `status` TEXT NOT NULL, `source_type` TEXT NOT NULL, `resolved_url` TEXT, `headers_json` TEXT NOT NULL, `user_agent` TEXT, `expiration_time` INTEGER, `provider_label` TEXT, `output_uri` TEXT, `output_display_path` TEXT, `bytes_written` INTEGER NOT NULL, `average_throughput_bps` INTEGER NOT NULL, `retry_count` INTEGER NOT NULL, `last_progress_at_ms` INTEGER, `failure_category` TEXT NOT NULL, `failure_reason` TEXT, `terminal_at_ms` INTEGER, `started_at_ms` INTEGER, `ended_at_ms` INTEGER, `schedule_enabled` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `alarm_start_at_ms` INTEGER, `alarm_stop_at_ms` INTEGER, `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": "downloads",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `provider_id` INTEGER NOT NULL, `content_type` TEXT NOT NULL, `content_id` INTEGER NOT NULL, `content_name` TEXT NOT NULL, `stream_url` TEXT NOT NULL, `source_stream_url` TEXT, `source_stream_id` INTEGER, `container_extension` TEXT, `poster_url` TEXT, `output_uri` TEXT, `output_display_path` TEXT, `status` TEXT NOT NULL, `bytes_written` INTEGER NOT NULL, `total_bytes` INTEGER, `supports_resume` INTEGER NOT NULL, `retry_count` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `completed_at` INTEGER, `failure_reason` TEXT, `owner_id` TEXT, `owner_epoch` INTEGER NOT NULL, `heartbeat_at` INTEGER, `series_id` INTEGER, `season_number` INTEGER, `episode_number` INTEGER, PRIMARY KEY(`id`))",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentType",+ "columnName": "content_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "contentId",+ "columnName": "content_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentName",+ "columnName": "content_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "sourceStreamUrl",+ "columnName": "source_stream_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "sourceStreamId",+ "columnName": "source_stream_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "containerExtension",+ "columnName": "container_extension",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "posterUrl",+ "columnName": "poster_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "outputUri",+ "columnName": "output_uri",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "outputDisplayPath",+ "columnName": "output_display_path",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "status",+ "columnName": "status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "bytesWritten",+ "columnName": "bytes_written",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "totalBytes",+ "columnName": "total_bytes",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "supportsResume",+ "columnName": "supports_resume",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "retryCount",+ "columnName": "retry_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "completedAt",+ "columnName": "completed_at",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "failureReason",+ "columnName": "failure_reason",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "ownerId",+ "columnName": "owner_id",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "ownerEpoch",+ "columnName": "owner_epoch",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "heartbeatAt",+ "columnName": "heartbeat_at",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "seriesId",+ "columnName": "series_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "seasonNumber",+ "columnName": "season_number",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "episodeNumber",+ "columnName": "episode_number",+ "affinity": "INTEGER"+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_downloads_status",+ "unique": false,+ "columnNames": [+ "status"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_downloads_status` ON `${TABLE_NAME}` (`status`)"+ },+ {+ "name": "index_downloads_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_downloads_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_downloads_content_type_content_id",+ "unique": false,+ "columnNames": [+ "content_type",+ "content_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_downloads_content_type_content_id` ON `${TABLE_NAME}` (`content_type`, `content_id`)"+ }+ ]+ },+ {+ "tableName": "provider_deletion_cleanup",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `action` TEXT NOT NULL, `target_id` TEXT NOT NULL, `created_at` INTEGER NOT NULL, `attempt_count` INTEGER NOT NULL, `last_error` TEXT)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "action",+ "columnName": "action",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "targetId",+ "columnName": "target_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "attemptCount",+ "columnName": "attempt_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastError",+ "columnName": "last_error",+ "affinity": "TEXT"+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_provider_deletion_cleanup_provider_id_action_target_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "action",+ "target_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_provider_deletion_cleanup_provider_id_action_target_id` ON `${TABLE_NAME}` (`provider_id`, `action`, `target_id`)"+ }+ ]+ },+ {+ "tableName": "plugin_provider_ownership",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`package_name` TEXT NOT NULL, `service_class_name` TEXT NOT NULL, `manifest_id` TEXT NOT NULL, `provider_id` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, PRIMARY KEY(`package_name`, `service_class_name`, `manifest_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "packageName",+ "columnName": "package_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "serviceClassName",+ "columnName": "service_class_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "manifestId",+ "columnName": "manifest_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "package_name",+ "service_class_name",+ "manifest_id"+ ]+ },+ "indices": [+ {+ "name": "index_plugin_provider_ownership_provider_id",+ "unique": true,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_plugin_provider_ownership_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "provider_config_revisions",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `revision` INTEGER NOT NULL, `config_json` TEXT NOT NULL, `state` TEXT NOT NULL, `attempt_count` INTEGER NOT NULL, `last_error` TEXT, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, PRIMARY KEY(`provider_id`, `revision`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "revision",+ "columnName": "revision",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "configJson",+ "columnName": "config_json",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "state",+ "columnName": "state",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "attemptCount",+ "columnName": "attempt_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastError",+ "columnName": "last_error",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "provider_id",+ "revision"+ ]+ },+ "indices": [+ {+ "name": "index_provider_config_revisions_provider_id_state",+ "unique": false,+ "columnNames": [+ "provider_id",+ "state"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_provider_config_revisions_provider_id_state` ON `${TABLE_NAME}` (`provider_id`, `state`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "backup_restore_checkpoints",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`restore_key` TEXT NOT NULL, `room_complete` INTEGER NOT NULL, `preferences_complete` INTEGER NOT NULL, `presets_complete` INTEGER NOT NULL, `schedules_complete` INTEGER NOT NULL, `state` TEXT NOT NULL, `preference_snapshot_json` TEXT, `last_error` TEXT, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, PRIMARY KEY(`restore_key`))",+ "fields": [+ {+ "fieldPath": "restoreKey",+ "columnName": "restore_key",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "roomComplete",+ "columnName": "room_complete",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "preferencesComplete",+ "columnName": "preferences_complete",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "presetsComplete",+ "columnName": "presets_complete",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "schedulesComplete",+ "columnName": "schedules_complete",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "state",+ "columnName": "state",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "preferenceSnapshotJson",+ "columnName": "preference_snapshot_json",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lastError",+ "columnName": "last_error",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "restore_key"+ ]+ }+ },+ {+ "tableName": "provider_workflows",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `generation` INTEGER NOT NULL, `state` TEXT NOT NULL, `reason` TEXT NOT NULL, `priority` INTEGER NOT NULL, `force` INTEGER NOT NULL, `current_phase` TEXT, `lease_token` TEXT, `lease_expires_at` INTEGER, `heartbeat_at` INTEGER, `progress_message` TEXT, `last_error_code` TEXT, `last_error_message` TEXT, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, `completed_at` INTEGER, PRIMARY KEY(`provider_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "generation",+ "columnName": "generation",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "state",+ "columnName": "state",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "reason",+ "columnName": "reason",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "priority",+ "columnName": "priority",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "force",+ "columnName": "force",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "currentPhase",+ "columnName": "current_phase",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "leaseToken",+ "columnName": "lease_token",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "leaseExpiresAt",+ "columnName": "lease_expires_at",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "heartbeatAt",+ "columnName": "heartbeat_at",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "progressMessage",+ "columnName": "progress_message",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lastErrorCode",+ "columnName": "last_error_code",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lastErrorMessage",+ "columnName": "last_error_message",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "completedAt",+ "columnName": "completed_at",+ "affinity": "INTEGER"+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "provider_id"+ ]+ },+ "indices": [+ {+ "name": "index_provider_workflows_state",+ "unique": false,+ "columnNames": [+ "state"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_provider_workflows_state` ON `${TABLE_NAME}` (`state`)"+ },+ {+ "name": "index_provider_workflows_updated_at",+ "unique": false,+ "columnNames": [+ "updated_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_provider_workflows_updated_at` ON `${TABLE_NAME}` (`updated_at`)"+ },+ {+ "name": "index_provider_workflows_lease_expires_at",+ "unique": false,+ "columnNames": [+ "lease_expires_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_provider_workflows_lease_expires_at` ON `${TABLE_NAME}` (`lease_expires_at`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "provider_workflow_phases",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `generation` INTEGER NOT NULL, `phase` TEXT NOT NULL, `state` TEXT NOT NULL, `attempt_count` INTEGER NOT NULL, `checkpoint` TEXT, `last_error_code` TEXT, `last_error_message` TEXT, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, `completed_at` INTEGER, PRIMARY KEY(`provider_id`, `generation`, `phase`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "generation",+ "columnName": "generation",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "phase",+ "columnName": "phase",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "state",+ "columnName": "state",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "attemptCount",+ "columnName": "attempt_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "checkpoint",+ "columnName": "checkpoint",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lastErrorCode",+ "columnName": "last_error_code",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lastErrorMessage",+ "columnName": "last_error_message",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "completedAt",+ "columnName": "completed_at",+ "affinity": "INTEGER"+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "provider_id",+ "generation",+ "phase"+ ]+ },+ "indices": [+ {+ "name": "index_provider_workflow_phases_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_provider_workflow_phases_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_provider_workflow_phases_state",+ "unique": false,+ "columnNames": [+ "state"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_provider_workflow_phases_state` ON `${TABLE_NAME}` (`state`)"+ },+ {+ "name": "index_provider_workflow_phases_updated_at",+ "unique": false,+ "columnNames": [+ "updated_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_provider_workflow_phases_updated_at` ON `${TABLE_NAME}` (`updated_at`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ }+ ],+ "setupQueries": [+ "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",+ "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, 'e54785d2d9a682a544b0922df46d1285')"+ ]+ }+}\ No newline at end of filediff --git a/data/src/androidTest/java/com/streamvault/data/local/ProviderWorkflowIntegrationTest.kt b/data/src/androidTest/java/com/streamvault/data/local/ProviderWorkflowIntegrationTest.ktnew file mode 100644index 00000000..4a323048--- /dev/null+++ b/data/src/androidTest/java/com/streamvault/data/local/ProviderWorkflowIntegrationTest.kt@@ -0,0 +1,189 @@+package com.streamvault.data.local++import android.content.Context+import androidx.room.Room+import androidx.test.ext.junit.runners.AndroidJUnit4+import androidx.test.platform.app.InstrumentationRegistry+import com.google.common.truth.Truth.assertThat+import com.streamvault.data.local.entity.ProviderEntity+import com.streamvault.data.local.entity.ProviderWorkflowPhase+import com.streamvault.data.local.entity.ProviderWorkflowReason+import com.streamvault.domain.model.ProviderType+import kotlinx.coroutines.test.runTest+import org.junit.After+import org.junit.Before+import org.junit.Test+import org.junit.runner.RunWith++@RunWith(AndroidJUnit4::class)+class ProviderWorkflowIntegrationTest {+ private val context: Context = InstrumentationRegistry.getInstrumentation().targetContext+ private var database: StreamVaultDatabase? = null++ @Before+ fun setUp() {+ context.deleteDatabase(DATABASE_NAME)+ }++ @After+ fun tearDown() {+ database?.close()+ database = null+ context.deleteDatabase(DATABASE_NAME)+ }++ @Test+ fun processRestart_reopensDurableLeaseAndReclaimsExpiredPhase() = runTest {+ var db = openDatabase()+ db.providerDao().insert(provider(PROVIDER_ID))+ val originalTicket = db.providerWorkflowDao().request(+ providerId = PROVIDER_ID,+ phase = ProviderWorkflowPhase.EPG,+ reason = ProviderWorkflowReason.PERIODIC,+ now = 100L+ )+ checkNotNull(+ db.providerWorkflowDao().claim(+ originalTicket,+ token = "dead-process",+ now = 101L,+ leaseDurationMs = 100L,+ staleHeartbeatBefore = 0L+ )+ )+ db.close()+ database = null++ db = openDatabase()+ val restartedTicket = db.providerWorkflowDao().request(+ providerId = PROVIDER_ID,+ phase = ProviderWorkflowPhase.EPG,+ reason = ProviderWorkflowReason.RECOVERY,+ now = 202L,+ staleHeartbeatBefore = 150L+ )+ val recovered = db.providerWorkflowDao().claim(+ restartedTicket,+ token = "new-process",+ now = 202L,+ leaseDurationMs = 1_000L,+ staleHeartbeatBefore = 150L+ )++ assertThat(recovered).isNotNull()+ assertThat(recovered!!.generation).isEqualTo(originalTicket.generation)+ assertThat(+ db.providerWorkflowDao()+ .getPhases(PROVIDER_ID, originalTicket.generation)+ .single()+ .attemptCount+ ).isEqualTo(2)+ }++ @Test+ fun forcedManualRefresh_supersedesEveryBackgroundWorkerPhase() = runTest {+ val db = openDatabase()+ val backgroundPhases = listOf(+ ProviderWorkflowPhase.PRIMARY_CATALOG,+ ProviderWorkflowPhase.CONTENT_INDEX,+ ProviderWorkflowPhase.MOVIE_INDEX,+ ProviderWorkflowPhase.SERIES_INDEX,+ ProviderWorkflowPhase.EPG,+ ProviderWorkflowPhase.FINALIZE+ )++ backgroundPhases.forEachIndexed { index, phase ->+ val providerId = index + 1L+ db.providerDao().insert(provider(providerId))+ val background = db.providerWorkflowDao().request(+ providerId = providerId,+ phase = phase,+ reason = ProviderWorkflowReason.PERIODIC,+ now = 100L + index,+ priority = 0+ )+ val oldLease = checkNotNull(+ db.providerWorkflowDao().claim(+ background,+ token = "background-$phase",+ now = 200L + index,+ leaseDurationMs = 10_000L,+ staleHeartbeatBefore = 0L+ )+ )++ val manual = db.providerWorkflowDao().request(+ providerId = providerId,+ phase = ProviderWorkflowPhase.PRIMARY_CATALOG,+ reason = ProviderWorkflowReason.MANUAL,+ now = 300L + index,+ supersede = true,+ priority = 50,+ force = true+ )++ assertThat(manual.admitted).isTrue()+ assertThat(manual.generation).isEqualTo(background.generation + 1L)+ assertThat(db.providerWorkflowDao().complete(oldLease, now = 400L + index)).isFalse()+ assertThat(+ db.providerWorkflowDao().claim(+ manual,+ token = "manual-$phase",+ now = 400L + index,+ leaseDurationMs = 10_000L,+ staleHeartbeatBefore = 0L+ )+ ).isNotNull()+ }+ }++ @Test+ fun forcedManualRefresh_cannotSupersedeConfigurationMigration() = runTest {+ val db = openDatabase()+ db.providerDao().insert(provider(PROVIDER_ID))+ val config = db.providerWorkflowDao().request(+ providerId = PROVIDER_ID,+ phase = ProviderWorkflowPhase.PREPARE,+ reason = ProviderWorkflowReason.CONFIG_CHANGE,+ now = 100L,+ supersede = true,+ priority = 100,+ force = true+ )++ val manual = db.providerWorkflowDao().request(+ providerId = PROVIDER_ID,+ phase = ProviderWorkflowPhase.PRIMARY_CATALOG,+ reason = ProviderWorkflowReason.MANUAL,+ now = 101L,+ supersede = true,+ priority = 50,+ force = true+ )++ assertThat(manual.admitted).isFalse()+ assertThat(manual.generation).isEqualTo(config.generation)+ assertThat(db.providerWorkflowDao().getWorkflow(PROVIDER_ID)!!.reason)+ .isEqualTo(ProviderWorkflowReason.CONFIG_CHANGE)+ }++ private fun openDatabase(): StreamVaultDatabase {+ return Room.databaseBuilder(+ context,+ StreamVaultDatabase::class.java,+ DATABASE_NAME+ ).allowMainThreadQueries().build().also { database = it }+ }++ private fun provider(id: Long) = ProviderEntity(+ id = id,+ name = "Provider $id",+ type = ProviderType.M3U,+ serverUrl = "https://example.com/$id"+ )++ private companion object {+ const val DATABASE_NAME = "provider-workflow-integration.db"+ const val PROVIDER_ID = 1L+ }+}diff --git a/data/src/androidTest/java/com/streamvault/data/local/StreamVaultDatabaseMigrationTest.kt b/data/src/androidTest/java/com/streamvault/data/local/StreamVaultDatabaseMigrationTest.ktindex 27d7e8e2..5d805825 100644--- a/data/src/androidTest/java/com/streamvault/data/local/StreamVaultDatabaseMigrationTest.kt+++ b/data/src/androidTest/java/com/streamvault/data/local/StreamVaultDatabaseMigrationTest.kt@@ -1352,6 +1352,196 @@ class StreamVaultDatabaseMigrationTest {migratedDb.close()}+ @Test+ fun migrate66To67_createsDurableProviderConfigRevisionTable() {+ migrationTestHelper.createDatabase("streamvault-66-67-test", 66).close()++ val migratedDb = migrationTestHelper.runMigrationsAndValidate(+ "streamvault-66-67-test",+ 67,+ true,+ StreamVaultDatabase.MIGRATION_66_67+ )++ assertEquals(+ 1,+ countRows(+ migratedDb,+ "SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = 'provider_config_revisions'"+ )+ )+ assertEquals(+ 1,+ countRows(+ migratedDb,+ "SELECT COUNT(*) FROM sqlite_master WHERE type = 'index' AND name = 'index_provider_config_revisions_provider_id_state'"+ )+ )+ assertEquals(+ 1,+ countRows(+ migratedDb,+ "SELECT COUNT(*) FROM pragma_foreign_key_list('provider_config_revisions') WHERE \"table\" = 'providers' AND \"from\" = 'provider_id' AND on_delete = 'CASCADE'"+ )+ )+ migratedDb.close()+ }++ @Test+ fun migrate67To68_createsBackupRestoreCheckpointTable() {+ migrationTestHelper.createDatabase("streamvault-67-68-test", 67).close()++ val migratedDb = migrationTestHelper.runMigrationsAndValidate(+ "streamvault-67-68-test",+ 68,+ true,+ StreamVaultDatabase.MIGRATION_67_68+ )++ assertEquals(+ 1,+ countRows(+ migratedDb,+ "SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = 'backup_restore_checkpoints'"+ )+ )+ assertEquals(+ 1,+ countRows(+ migratedDb,+ "SELECT COUNT(*) FROM pragma_table_info('backup_restore_checkpoints') WHERE name = 'preference_snapshot_json'"+ )+ )+ migratedDb.close()+ }++ @Test+ fun migrate68To69_addsDurableDownloadOwnershipColumns() {+ migrationTestHelper.createDatabase("streamvault-68-69-test", 68).close()++ val migratedDb = migrationTestHelper.runMigrationsAndValidate(+ "streamvault-68-69-test",+ 69,+ true,+ StreamVaultDatabase.MIGRATION_68_69+ )++ assertEquals(1, countRows(migratedDb, "SELECT COUNT(*) FROM pragma_table_info('downloads') WHERE name = 'owner_id'"))+ assertEquals(1, countRows(migratedDb, "SELECT COUNT(*) FROM pragma_table_info('downloads') WHERE name = 'owner_epoch'"))+ assertEquals(1, countRows(migratedDb, "SELECT COUNT(*) FROM pragma_table_info('downloads') WHERE name = 'heartbeat_at'"))+ assertEquals(+ 1,+ countRows(+ migratedDb,+ "SELECT COUNT(*) FROM pragma_table_info('downloads') WHERE name = 'owner_epoch' AND \"notnull\" = 1 AND dflt_value = '0'"+ )+ )+ migratedDb.close()+ }++ @Test+ fun migrate69To70_addsDurableReminderDeliveryState() {+ val databaseName = "streamvault-69-70-test"+ migrationTestHelper.createDatabase(databaseName, 69).apply {+ execSQL(+ """+ INSERT INTO program_reminders (+ provider_id, channel_id, channel_name, program_title,+ program_start_time, remind_at, lead_time_minutes,+ is_dismissed, notified_at, exact_alarm_armed, created_at+ ) VALUES+ (1, 'one', 'One', 'Delivered', 1000, 500, 5, 0, 600, 1, 100),+ (1, 'two', 'Two', 'Dismissed', 2000, 1500, 5, 1, NULL, 0, 100),+ (1, 'three', 'Three', 'Pending', 3000, 2500, 5, 0, NULL, 1, 100)+ """.trimIndent()+ )+ close()+ }++ val migratedDb = migrationTestHelper.runMigrationsAndValidate(+ databaseName,+ 70,+ true,+ StreamVaultDatabase.MIGRATION_69_70+ )++ assertEquals(+ 5,+ countRows(+ migratedDb,+ """+ SELECT COUNT(*) FROM pragma_table_info('program_reminders')+ WHERE name IN (+ 'delivery_state',+ 'delivery_attempt_token',+ 'delivery_attempted_at',+ 'delivery_attempt_count',+ 'delivery_failure_reason'+ )+ """.trimIndent()+ )+ )+ assertEquals(1, countRows(migratedDb, "SELECT COUNT(*) FROM program_reminders WHERE delivery_state = 'DELIVERED'"))+ assertEquals(1, countRows(migratedDb, "SELECT COUNT(*) FROM program_reminders WHERE delivery_state = 'DISMISSED'"))+ assertEquals(1, countRows(migratedDb, "SELECT COUNT(*) FROM program_reminders WHERE delivery_state = 'PENDING'"))+ migratedDb.close()+ }++ @Test+ fun migrate70To71_createsDurableProviderWorkflowTables() {+ val databaseName = "streamvault-70-71-test"+ migrationTestHelper.createDatabase(databaseName, 70).close()++ val migratedDb = migrationTestHelper.runMigrationsAndValidate(+ databaseName,+ 71,+ true,+ StreamVaultDatabase.MIGRATION_70_71+ )++ assertEquals(+ 2,+ countRows(+ migratedDb,+ """+ SELECT COUNT(*) FROM sqlite_master+ WHERE type = 'table'+ AND name IN ('provider_workflows', 'provider_workflow_phases')+ """.trimIndent()+ )+ )+ assertEquals(+ 3,+ countRows(+ migratedDb,+ """+ SELECT COUNT(*) FROM sqlite_master+ WHERE type = 'index'+ AND name IN (+ 'index_provider_workflows_state',+ 'index_provider_workflows_updated_at',+ 'index_provider_workflows_lease_expires_at'+ )+ """.trimIndent()+ )+ )+ assertEquals(+ 2,+ countRows(+ migratedDb,+ """+ SELECT+ (SELECT COUNT(*) FROM pragma_foreign_key_list('provider_workflows')+ WHERE "table" = 'providers' AND "from" = 'provider_id' AND on_delete = 'CASCADE')+ ++ (SELECT COUNT(*) FROM pragma_foreign_key_list('provider_workflow_phases')+ WHERE "table" = 'providers' AND "from" = 'provider_id' AND on_delete = 'CASCADE')+ """.trimIndent()+ )+ )+ migratedDb.close()+ }+private fun countRows(db: androidx.sqlite.db.SupportSQLiteDatabase, sql: String): Int {db.query(sql).use { cursor ->if (!cursor.moveToFirst()) return 0diff --git a/data/src/main/java/com/streamvault/data/local/RoomEnumConverters.kt b/data/src/main/java/com/streamvault/data/local/RoomEnumConverters.ktindex c7d5697a..a89b4078 100644--- a/data/src/main/java/com/streamvault/data/local/RoomEnumConverters.kt+++ b/data/src/main/java/com/streamvault/data/local/RoomEnumConverters.kt@@ -1,6 +1,11 @@package com.streamvault.data.localimport androidx.room.TypeConverter+import com.streamvault.data.local.entity.ProviderConfigRevisionState+import com.streamvault.data.local.entity.ProviderWorkflowPhase+import com.streamvault.data.local.entity.ProviderWorkflowPhaseState+import com.streamvault.data.local.entity.ProviderWorkflowReason+import com.streamvault.data.local.entity.ProviderWorkflowStateimport com.streamvault.domain.model.ContentTypeimport com.streamvault.domain.model.ChannelLogoSourcePolicyimport com.streamvault.domain.model.GuideSourcePolicy@@ -8,6 +13,7 @@ import com.streamvault.domain.model.ProviderEpgSyncModeimport com.streamvault.domain.model.ProviderStatusimport com.streamvault.domain.model.ProviderTypeimport com.streamvault.domain.model.ProviderXtreamLiveSyncMode+import com.streamvault.domain.model.ProgramReminderDeliveryStateimport com.streamvault.domain.model.StalkerAuthModeimport com.streamvault.domain.model.StalkerBootstrapRecipeimport com.streamvault.domain.model.StalkerCookieMode@@ -36,6 +42,48 @@ class RoomEnumConverters {@TypeConverterfun toProviderStatus(value: String?): ProviderStatus? = enumValueOrDefault(value, ProviderStatus.UNKNOWN)+ @TypeConverter+ fun fromProviderConfigRevisionState(value: ProviderConfigRevisionState?): String? = value?.name++ @TypeConverter+ fun toProviderConfigRevisionState(value: String?): ProviderConfigRevisionState? =+ enumValueOrDefault(value, ProviderConfigRevisionState.FAILED)++ @TypeConverter+ fun fromProviderWorkflowState(value: ProviderWorkflowState?): String? = value?.name++ @TypeConverter+ fun toProviderWorkflowState(value: String?): ProviderWorkflowState? =+ enumValueOrDefault(value, ProviderWorkflowState.FAILED)++ @TypeConverter+ fun fromProviderWorkflowPhase(value: ProviderWorkflowPhase?): String? = value?.name++ @TypeConverter+ fun toProviderWorkflowPhase(value: String?): ProviderWorkflowPhase? =+ enumValueOrDefault(value, ProviderWorkflowPhase.PREPARE)++ @TypeConverter+ fun fromProviderWorkflowPhaseState(value: ProviderWorkflowPhaseState?): String? = value?.name++ @TypeConverter+ fun toProviderWorkflowPhaseState(value: String?): ProviderWorkflowPhaseState? =+ enumValueOrDefault(value, ProviderWorkflowPhaseState.FAILED_PERMANENT)++ @TypeConverter+ fun fromProviderWorkflowReason(value: ProviderWorkflowReason?): String? = value?.name++ @TypeConverter+ fun toProviderWorkflowReason(value: String?): ProviderWorkflowReason? =+ enumValueOrDefault(value, ProviderWorkflowReason.RECOVERY)++ @TypeConverter+ fun fromProgramReminderDeliveryState(value: ProgramReminderDeliveryState?): String? = value?.name++ @TypeConverter+ fun toProgramReminderDeliveryState(value: String?): ProgramReminderDeliveryState? =+ enumValueOrDefault(value, ProgramReminderDeliveryState.PENDING)+@TypeConverterfun fromProviderEpgSyncMode(value: ProviderEpgSyncMode?): String? = value?.namediff --git a/data/src/main/java/com/streamvault/data/local/StreamVaultDatabase.kt b/data/src/main/java/com/streamvault/data/local/StreamVaultDatabase.ktindex 48ea6ce6..e156bc43 100644--- a/data/src/main/java/com/streamvault/data/local/StreamVaultDatabase.kt+++ b/data/src/main/java/com/streamvault/data/local/StreamVaultDatabase.kt@@ -50,9 +50,13 @@ import com.streamvault.data.local.entity.*XtreamLiveOnboardingStateEntity::class,DownloadEntity::class,ProviderDeletionCleanupEntity::class,- PluginProviderOwnershipEntity::class+ PluginProviderOwnershipEntity::class,+ ProviderConfigRevisionEntity::class,+ BackupRestoreCheckpointEntity::class,+ ProviderWorkflowEntity::class,+ ProviderWorkflowPhaseEntity::class],- version = 66,+ version = 71,exportSchema = true // ← was false; schema JSON now tracked in version control)@TypeConverters(RoomEnumConverters::class)@@ -93,6 +97,9 @@ abstract class StreamVaultDatabase : RoomDatabase() {abstract fun downloadDao(): DownloadDaoabstract fun providerDeletionCleanupDao(): ProviderDeletionCleanupDaoabstract fun pluginProviderOwnershipDao(): PluginProviderOwnershipDao+ abstract fun providerConfigRevisionDao(): ProviderConfigRevisionDao+ abstract fun backupRestoreCheckpointDao(): BackupRestoreCheckpointDao+ abstract fun providerWorkflowDao(): ProviderWorkflowDaocompanion object {/**@@ -2769,6 +2776,193 @@ abstract class StreamVaultDatabase : RoomDatabase() {}}+ /** Migration 66 -> 67: retain candidate provider edits until they are atomically promoted. */+ val MIGRATION_66_67 = object : Migration(66, 67) {+ override fun migrate(database: SupportSQLiteDatabase) {+ database.execSQL(+ """+ CREATE TABLE IF NOT EXISTS provider_config_revisions (+ provider_id INTEGER NOT NULL,+ revision INTEGER NOT NULL,+ config_json TEXT NOT NULL,+ state TEXT NOT NULL,+ attempt_count INTEGER NOT NULL DEFAULT 0,+ last_error TEXT,+ created_at INTEGER NOT NULL,+ updated_at INTEGER NOT NULL,+ PRIMARY KEY(provider_id, revision),+ FOREIGN KEY(provider_id) REFERENCES providers(id) ON DELETE CASCADE+ )+ """.trimIndent()+ )+ database.execSQL(+ "CREATE INDEX IF NOT EXISTS index_provider_config_revisions_provider_id_state ON provider_config_revisions(provider_id, state)"+ )+ validateForeignKeys(database, "provider_config_revisions")+ }+ }++ /** Migration 67 -> 68: retain cross-store backup restore progress for safe retry. */+ val MIGRATION_67_68 = object : Migration(67, 68) {+ override fun migrate(database: SupportSQLiteDatabase) {+ database.execSQL(+ """+ CREATE TABLE IF NOT EXISTS backup_restore_checkpoints (+ restore_key TEXT NOT NULL,+ room_complete INTEGER NOT NULL DEFAULT 0,+ preferences_complete INTEGER NOT NULL DEFAULT 0,+ presets_complete INTEGER NOT NULL DEFAULT 0,+ schedules_complete INTEGER NOT NULL DEFAULT 0,+ state TEXT NOT NULL,+ preference_snapshot_json TEXT,+ last_error TEXT,+ created_at INTEGER NOT NULL,+ updated_at INTEGER NOT NULL,+ PRIMARY KEY(restore_key)+ )+ """.trimIndent()+ )+ }+ }++ /** Migration 68 -> 69: make active download ownership durable and reclaimable. */+ val MIGRATION_68_69 = object : Migration(68, 69) {+ override fun migrate(database: SupportSQLiteDatabase) {+ addColumnIfMissing(+ database,+ tableName = "downloads",+ columnName = "owner_id",+ columnDefinition = "TEXT"+ )+ addColumnIfMissing(+ database,+ tableName = "downloads",+ columnName = "owner_epoch",+ columnDefinition = "INTEGER NOT NULL DEFAULT 0"+ )+ addColumnIfMissing(+ database,+ tableName = "downloads",+ columnName = "heartbeat_at",+ columnDefinition = "INTEGER"+ )+ }+ }++ /** Migration 69 -> 70: make reminder delivery outcomes durable and recoverable. */+ val MIGRATION_69_70 = object : Migration(69, 70) {+ override fun migrate(database: SupportSQLiteDatabase) {+ addColumnIfMissing(+ database,+ tableName = "program_reminders",+ columnName = "delivery_state",+ columnDefinition = "TEXT NOT NULL DEFAULT 'PENDING'"+ )+ addColumnIfMissing(+ database,+ tableName = "program_reminders",+ columnName = "delivery_attempt_token",+ columnDefinition = "TEXT"+ )+ addColumnIfMissing(+ database,+ tableName = "program_reminders",+ columnName = "delivery_attempted_at",+ columnDefinition = "INTEGER"+ )+ addColumnIfMissing(+ database,+ tableName = "program_reminders",+ columnName = "delivery_attempt_count",+ columnDefinition = "INTEGER NOT NULL DEFAULT 0"+ )+ addColumnIfMissing(+ database,+ tableName = "program_reminders",+ columnName = "delivery_failure_reason",+ columnDefinition = "TEXT"+ )+ database.execSQL(+ """+ UPDATE program_reminders+ SET delivery_state = CASE+ WHEN notified_at IS NOT NULL THEN 'DELIVERED'+ WHEN is_dismissed = 1 THEN 'DISMISSED'+ ELSE 'PENDING'+ END+ """.trimIndent()+ )+ }+ }++ /** Migration 70 -> 71: persist the provider workflow generation, lease, and phase ledger. */+ val MIGRATION_70_71 = object : Migration(70, 71) {+ override fun migrate(database: SupportSQLiteDatabase) {+ database.execSQL(+ """+ CREATE TABLE IF NOT EXISTS provider_workflows (+ provider_id INTEGER NOT NULL,+ generation INTEGER NOT NULL,+ state TEXT NOT NULL,+ reason TEXT NOT NULL,+ priority INTEGER NOT NULL,+ force INTEGER NOT NULL,+ current_phase TEXT,+ lease_token TEXT,+ lease_expires_at INTEGER,+ heartbeat_at INTEGER,+ progress_message TEXT,+ last_error_code TEXT,+ last_error_message TEXT,+ created_at INTEGER NOT NULL,+ updated_at INTEGER NOT NULL,+ completed_at INTEGER,+ PRIMARY KEY(provider_id),+ FOREIGN KEY(provider_id) REFERENCES providers(id) ON UPDATE NO ACTION ON DELETE CASCADE+ )+ """.trimIndent()+ )+ database.execSQL(+ "CREATE INDEX IF NOT EXISTS index_provider_workflows_state ON provider_workflows(state)"+ )+ database.execSQL(+ "CREATE INDEX IF NOT EXISTS index_provider_workflows_updated_at ON provider_workflows(updated_at)"+ )+ database.execSQL(+ "CREATE INDEX IF NOT EXISTS index_provider_workflows_lease_expires_at ON provider_workflows(lease_expires_at)"+ )+ database.execSQL(+ """+ CREATE TABLE IF NOT EXISTS provider_workflow_phases (+ provider_id INTEGER NOT NULL,+ generation INTEGER NOT NULL,+ phase TEXT NOT NULL,+ state TEXT NOT NULL,+ attempt_count INTEGER NOT NULL,+ checkpoint TEXT,+ last_error_code TEXT,+ last_error_message TEXT,+ created_at INTEGER NOT NULL,+ updated_at INTEGER NOT NULL,+ completed_at INTEGER,+ PRIMARY KEY(provider_id, generation, phase),+ FOREIGN KEY(provider_id) REFERENCES providers(id) ON UPDATE NO ACTION ON DELETE CASCADE+ )+ """.trimIndent()+ )+ database.execSQL(+ "CREATE INDEX IF NOT EXISTS index_provider_workflow_phases_provider_id ON provider_workflow_phases(provider_id)"+ )+ database.execSQL(+ "CREATE INDEX IF NOT EXISTS index_provider_workflow_phases_state ON provider_workflow_phases(state)"+ )+ database.execSQL(+ "CREATE INDEX IF NOT EXISTS index_provider_workflow_phases_updated_at ON provider_workflow_phases(updated_at)"+ )+ validateForeignKeys(database, "provider_workflows", "provider_workflow_phases")+ }+ }+private fun imageUrlMigrationSql(table: String, column: String): String = """UPDATE $table SET $column = CASEWHEN instr($column, 'streamvault_provider_id=') > 0 THEN $columndiff --git a/data/src/main/java/com/streamvault/data/local/dao/BackupRestoreCheckpointDao.kt b/data/src/main/java/com/streamvault/data/local/dao/BackupRestoreCheckpointDao.ktnew file mode 100644index 00000000..ac4e5e16--- /dev/null+++ b/data/src/main/java/com/streamvault/data/local/dao/BackupRestoreCheckpointDao.kt@@ -0,0 +1,42 @@+package com.streamvault.data.local.dao++import androidx.room.Dao+import androidx.room.Insert+import androidx.room.OnConflictStrategy+import androidx.room.Query+import com.streamvault.data.local.entity.BackupRestoreCheckpointEntity++/** Durable progress for a restore whose sections span Room, DataStore, and alarms. */+@Dao+interface BackupRestoreCheckpointDao {+ @Query("SELECT * FROM backup_restore_checkpoints WHERE restore_key = :restoreKey")+ suspend fun get(restoreKey: String): BackupRestoreCheckpointEntity?++ @Insert(onConflict = OnConflictStrategy.IGNORE)+ suspend fun insertIfAbsent(checkpoint: BackupRestoreCheckpointEntity): Long++ @Query("""+ UPDATE backup_restore_checkpoints+ SET room_complete = :roomComplete,+ preferences_complete = :preferencesComplete,+ presets_complete = :presetsComplete,+ schedules_complete = :schedulesComplete,+ state = :state,+ last_error = :lastError,+ updated_at = :updatedAt+ WHERE restore_key = :restoreKey+ """)+ suspend fun update(+ restoreKey: String,+ roomComplete: Boolean,+ preferencesComplete: Boolean,+ presetsComplete: Boolean,+ schedulesComplete: Boolean,+ state: String,+ lastError: String?,+ updatedAt: Long+ ): Int++ @Query("UPDATE backup_restore_checkpoints SET preference_snapshot_json = :snapshotJson, updated_at = :updatedAt WHERE restore_key = :restoreKey")+ suspend fun setPreferenceSnapshot(restoreKey: String, snapshotJson: String?, updatedAt: Long): Int+}diff --git a/data/src/main/java/com/streamvault/data/local/dao/DownloadDao.kt b/data/src/main/java/com/streamvault/data/local/dao/DownloadDao.ktindex 9861d8de..206c91e4 100644--- a/data/src/main/java/com/streamvault/data/local/dao/DownloadDao.kt+++ b/data/src/main/java/com/streamvault/data/local/dao/DownloadDao.kt@@ -29,9 +29,23 @@ interface DownloadDao {@Query("SELECT * FROM downloads WHERE status = 'PAUSED' AND retry_count < :maxRetries ORDER BY created_at ASC")suspend fun getRetryablePausedOnce(maxRetries: Int): List<DownloadEntity>- /** A DOWNLOADING row is valid only while an in-process job owns it. */- @Query("UPDATE downloads SET status = 'PENDING', failure_reason = :reason WHERE status = 'DOWNLOADING'")- suspend fun recoverOrphanedDownloading(reason: String): Int+ @Query("SELECT * FROM downloads WHERE status = 'DOWNLOADING' AND (owner_id IS NULL OR owner_id != :ownerId)")+ suspend fun getOrphanedDownloading(ownerId: String): List<DownloadEntity>++ @Query(+ """+ UPDATE downloads+ SET status = 'DOWNLOADING',+ owner_id = :ownerId,+ owner_epoch = owner_epoch + 1,+ heartbeat_at = :now,+ failure_reason = NULL+ WHERE id = :id+ AND status IN ('PENDING', 'PAUSED')+ AND owner_id IS NULL+ """+ )+ suspend fun claimForDownload(id: String, ownerId: String, now: Long): Int@Insert(onConflict = OnConflictStrategy.REPLACE)suspend fun insert(entity: DownloadEntity)diff --git a/data/src/main/java/com/streamvault/data/local/dao/ProviderConfigRevisionDao.kt b/data/src/main/java/com/streamvault/data/local/dao/ProviderConfigRevisionDao.ktnew file mode 100644index 00000000..0347f18c--- /dev/null+++ b/data/src/main/java/com/streamvault/data/local/dao/ProviderConfigRevisionDao.kt@@ -0,0 +1,73 @@+package com.streamvault.data.local.dao++import androidx.room.Dao+import androidx.room.Insert+import androidx.room.OnConflictStrategy+import androidx.room.Query+import com.streamvault.data.local.entity.ProviderConfigRevisionEntity+import com.streamvault.data.local.entity.ProviderConfigRevisionState++/** Durable state for a provider edit which has not yet been promoted. */+@Dao+interface ProviderConfigRevisionDao {+ @Insert(onConflict = OnConflictStrategy.REPLACE)+ suspend fun upsert(revision: ProviderConfigRevisionEntity)++ @Query("SELECT COALESCE(MAX(revision), 0) FROM provider_config_revisions WHERE provider_id = :providerId")+ suspend fun latestRevision(providerId: Long): Long++ @Query("SELECT * FROM provider_config_revisions WHERE provider_id = :providerId AND state IN ('PENDING', 'SYNCING', 'FAILED') ORDER BY revision DESC LIMIT 1")+ suspend fun latestRecoverable(providerId: Long): ProviderConfigRevisionEntity?++ @Query("SELECT * FROM provider_config_revisions WHERE state IN ('PENDING', 'SYNCING', 'FAILED') ORDER BY provider_id, revision DESC")+ suspend fun getRecoverable(): List<ProviderConfigRevisionEntity>++ @Query("SELECT state FROM provider_config_revisions WHERE provider_id = :providerId AND revision = :revision")+ suspend fun getState(providerId: Long, revision: Long): ProviderConfigRevisionState?++ @Query("SELECT * FROM provider_config_revisions WHERE provider_id = :providerId AND revision = :revision")+ suspend fun get(providerId: Long, revision: Long): ProviderConfigRevisionEntity?++ @Query("""+ SELECT * FROM provider_config_revisions+ WHERE state IN ('PENDING', 'FAILED')+ OR (+ state = 'SYNCING'+ AND (+ updated_at <= 0+ OR updated_at > :now+ OR updated_at <= :staleSyncingBefore+ )+ )+ ORDER BY provider_id, revision DESC+ """)+ suspend fun getRecoveryCandidates(+ now: Long,+ staleSyncingBefore: Long+ ): List<ProviderConfigRevisionEntity>++ @Query("UPDATE provider_config_revisions SET state = 'SYNCING', attempt_count = attempt_count + 1, last_error = NULL, updated_at = :updatedAt WHERE provider_id = :providerId AND revision = :revision AND state IN ('PENDING', 'FAILED')")+ suspend fun claimForSync(providerId: Long, revision: Long, updatedAt: Long): Int++ @Query("UPDATE provider_config_revisions SET state = 'FAILED', last_error = :error, updated_at = :updatedAt WHERE provider_id = :providerId AND revision = :revision AND state = 'SYNCING'")+ suspend fun markFailed(providerId: Long, revision: Long, error: String, updatedAt: Long): Int++ @Query("UPDATE provider_config_revisions SET state = 'PENDING', last_error = NULL, updated_at = :updatedAt WHERE provider_id = :providerId AND revision = :revision AND state = 'SYNCING'")+ suspend fun releaseForRetry(providerId: Long, revision: Long, updatedAt: Long): Int++ @Query("UPDATE provider_config_revisions SET state = 'SUPERSEDED', updated_at = :updatedAt WHERE provider_id = :providerId AND revision < :revision AND state IN ('PENDING', 'SYNCING', 'FAILED')")+ suspend fun supersedeOlder(providerId: Long, revision: Long, updatedAt: Long)++ @Query("""+ UPDATE provider_config_revisions+ SET state = 'COMMITTED', last_error = NULL, updated_at = :updatedAt+ WHERE provider_id = :providerId+ AND revision = :revision+ AND state = 'SYNCING'+ AND NOT EXISTS (+ SELECT 1 FROM provider_config_revisions newer+ WHERE newer.provider_id = :providerId AND newer.revision > :revision+ )+ """)+ suspend fun markCommitted(providerId: Long, revision: Long, updatedAt: Long): Int+}diff --git a/data/src/main/java/com/streamvault/data/local/dao/ProviderDeletionCleanupDao.kt b/data/src/main/java/com/streamvault/data/local/dao/ProviderDeletionCleanupDao.ktindex 3c59e0c1..574a5094 100644--- a/data/src/main/java/com/streamvault/data/local/dao/ProviderDeletionCleanupDao.kt+++ b/data/src/main/java/com/streamvault/data/local/dao/ProviderDeletionCleanupDao.kt@@ -11,8 +11,11 @@ interface ProviderDeletionCleanupDao {@Insert(onConflict = OnConflictStrategy.IGNORE)suspend fun insertAll(items: List<ProviderDeletionCleanupEntity>)- @Query("SELECT * FROM provider_deletion_cleanup ORDER BY id")- suspend fun getAll(): List<ProviderDeletionCleanupEntity>+ @Query("SELECT * FROM provider_deletion_cleanup ORDER BY id LIMIT :limit")+ suspend fun getBatch(limit: Int): List<ProviderDeletionCleanupEntity>++ @Query("SELECT COUNT(*) FROM provider_deletion_cleanup WHERE provider_id = :providerId")+ suspend fun countByProvider(providerId: Long): Int@Query("DELETE FROM provider_deletion_cleanup WHERE id = :id")suspend fun delete(id: Long)diff --git a/data/src/main/java/com/streamvault/data/local/dao/ProviderWorkflowDao.kt b/data/src/main/java/com/streamvault/data/local/dao/ProviderWorkflowDao.ktnew file mode 100644index 00000000..0099ea1e--- /dev/null+++ b/data/src/main/java/com/streamvault/data/local/dao/ProviderWorkflowDao.kt@@ -0,0 +1,629 @@+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.ProviderWorkflowEntity+import com.streamvault.data.local.entity.ProviderWorkflowPhase+import com.streamvault.data.local.entity.ProviderWorkflowPhaseEntity+import com.streamvault.data.local.entity.ProviderWorkflowPhaseState+import com.streamvault.data.local.entity.ProviderWorkflowReason+import com.streamvault.data.local.entity.ProviderWorkflowState+import kotlinx.coroutines.flow.Flow++data class ProviderWorkflowTicket(+ val providerId: Long,+ val generation: Long,+ val phase: ProviderWorkflowPhase,+ val admitted: Boolean = true+)++data class ProviderWorkflowLease(+ val providerId: Long,+ val generation: Long,+ val phase: ProviderWorkflowPhase,+ val token: String,+ val expiresAt: Long+)++/**+ * Persistent ownership boundary for provider work.+ *+ * All state-changing operations include both the generation and lease token. This is deliberate:+ * process-local cancellation cannot stop a worker that is already inside provider/network code,+ * while the database fencing check can stop that worker from committing stale state.+ */+@Dao+abstract class ProviderWorkflowDao {+ @Query("SELECT * FROM provider_workflows WHERE provider_id = :providerId")+ abstract suspend fun getWorkflow(providerId: Long): ProviderWorkflowEntity?++ @Query("SELECT * FROM provider_workflows WHERE provider_id = :providerId")+ abstract fun observeWorkflow(providerId: Long): Flow<ProviderWorkflowEntity?>++ @Query(+ """+ SELECT phase FROM provider_workflow_phases+ WHERE provider_id = :providerId+ AND generation = (+ SELECT generation FROM provider_workflows WHERE provider_id = :providerId+ )+ AND state IN ('PENDING', 'RUNNING', 'FAILED_RETRYABLE')+ """+ )+ abstract fun observeActivePhases(providerId: Long): Flow<List<ProviderWorkflowPhase>>++ @Query(+ """+ SELECT * FROM provider_workflow_phases+ WHERE provider_id = :providerId AND generation = :generation+ ORDER BY phase+ """+ )+ abstract suspend fun getPhases(+ providerId: Long,+ generation: Long+ ): List<ProviderWorkflowPhaseEntity>++ @Insert(onConflict = OnConflictStrategy.IGNORE)+ protected abstract suspend fun insertWorkflow(workflow: ProviderWorkflowEntity): Long++ @Insert(onConflict = OnConflictStrategy.IGNORE)+ protected abstract suspend fun insertPhase(phase: ProviderWorkflowPhaseEntity): Long++ @Query(+ """+ UPDATE provider_workflows+ SET generation = generation + 1,+ state = 'PENDING',+ reason = :reason,+ priority = :priority,+ force = :force,+ current_phase = NULL,+ lease_token = NULL,+ lease_expires_at = NULL,+ heartbeat_at = NULL,+ progress_message = NULL,+ last_error_code = NULL,+ last_error_message = NULL,+ updated_at = :now,+ completed_at = NULL+ WHERE provider_id = :providerId+ AND (+ :priority >= priority+ OR state IN ('SUCCEEDED', 'PARTIAL', 'FAILED', 'CANCELLED')+ )+ """+ )+ protected abstract suspend fun supersedeWorkflow(+ providerId: Long,+ reason: ProviderWorkflowReason,+ priority: Int,+ force: Boolean,+ now: Long+ ): Int++ @Query(+ """+ UPDATE provider_workflow_phases+ SET state = 'SUPERSEDED', updated_at = :now, completed_at = :now+ WHERE provider_id = :providerId+ AND generation < :generation+ AND state NOT IN ('SUCCEEDED', 'PARTIAL', 'FAILED_PERMANENT', 'SUPERSEDED')+ """+ )+ protected abstract suspend fun supersedeOlderPhases(+ providerId: Long,+ generation: Long,+ now: Long+ )++ @Query(+ """+ UPDATE provider_workflows+ SET state = CASE+ WHEN state IN ('SUCCEEDED', 'PARTIAL', 'FAILED', 'CANCELLED') THEN 'PENDING'+ ELSE state+ END,+ reason = :reason,+ priority = CASE+ WHEN state IN ('SUCCEEDED', 'PARTIAL', 'FAILED', 'CANCELLED') THEN :priority+ ELSE MAX(priority, :priority)+ END,+ force = CASE+ WHEN state IN ('SUCCEEDED', 'PARTIAL', 'FAILED', 'CANCELLED') THEN :force+ WHEN force = 1 OR :force = 1 THEN 1+ ELSE 0+ END,+ updated_at = :now,+ completed_at = CASE+ WHEN state IN ('SUCCEEDED', 'PARTIAL', 'FAILED', 'CANCELLED') THEN NULL+ ELSE completed_at+ END+ WHERE provider_id = :providerId+ AND (+ :priority >= priority+ OR state IN ('SUCCEEDED', 'PARTIAL', 'FAILED', 'CANCELLED')+ )+ """+ )+ protected abstract suspend fun joinWorkflow(+ providerId: Long,+ reason: ProviderWorkflowReason,+ priority: Int,+ force: Boolean,+ now: Long+ ): Int++ @Query(+ """+ UPDATE provider_workflow_phases+ SET state = 'PENDING',+ checkpoint = CASE WHEN :force = 1 THEN NULL ELSE checkpoint END,+ last_error_code = NULL,+ last_error_message = NULL,+ updated_at = :now,+ completed_at = NULL+ WHERE provider_id = :providerId+ AND generation = :generation+ AND phase = :phase+ AND state != 'RUNNING'+ """+ )+ protected abstract suspend fun requeuePhase(+ providerId: Long,+ generation: Long,+ phase: ProviderWorkflowPhase,+ force: Boolean,+ now: Long+ ): Int++ @Query(+ """+ UPDATE provider_workflow_phases+ SET state = 'FAILED_RETRYABLE',+ last_error_code = 'LEASE_RECOVERY',+ last_error_message = 'The prior worker lease expired or stopped heartbeating.',+ updated_at = :now,+ completed_at = NULL+ WHERE provider_id = :providerId+ AND generation = :generation+ AND phase = :phase+ AND state = 'RUNNING'+ AND EXISTS (+ SELECT 1 FROM provider_workflows workflow+ WHERE workflow.provider_id = :providerId+ AND workflow.generation = :generation+ AND workflow.current_phase = :phase+ AND (+ workflow.lease_token IS NULL+ OR workflow.lease_expires_at IS NULL+ OR workflow.lease_expires_at <= :now+ OR workflow.heartbeat_at IS NULL+ OR workflow.heartbeat_at <= :staleHeartbeatBefore+ OR workflow.heartbeat_at > :now+ )+ )+ """+ )+ protected abstract suspend fun recoverStaleRunningPhase(+ providerId: Long,+ generation: Long,+ phase: ProviderWorkflowPhase,+ now: Long,+ staleHeartbeatBefore: Long+ ): Int++ @Transaction+ open suspend fun request(+ providerId: Long,+ phase: ProviderWorkflowPhase,+ reason: ProviderWorkflowReason,+ now: Long,+ supersede: Boolean = false,+ priority: Int = 0,+ force: Boolean = false,+ staleHeartbeatBefore: Long = now - DEFAULT_STALE_HEARTBEAT_MILLIS+ ): ProviderWorkflowTicket {+ val inserted = insertWorkflow(+ ProviderWorkflowEntity(+ providerId = providerId,+ generation = 1L,+ state = ProviderWorkflowState.PENDING,+ reason = reason,+ priority = priority,+ force = force,+ createdAt = now,+ updatedAt = now+ )+ )++ var admitted = true+ if (inserted == -1L) {+ if (supersede) {+ admitted = supersedeWorkflow(providerId, reason, priority, force, now) == 1+ } else {+ admitted = joinWorkflow(providerId, reason, priority, force, now) == 1+ }+ }++ val workflow = checkNotNull(getWorkflow(providerId))+ if (!admitted) {+ return ProviderWorkflowTicket(+ providerId = providerId,+ generation = workflow.generation,+ phase = phase,+ admitted = false+ )+ }+ if (supersede && inserted == -1L) {+ supersedeOlderPhases(providerId, workflow.generation, now)+ }+ val phaseEntity = ProviderWorkflowPhaseEntity(+ providerId = providerId,+ generation = workflow.generation,+ phase = phase,+ state = ProviderWorkflowPhaseState.PENDING,+ createdAt = now,+ updatedAt = now+ )+ if (insertPhase(phaseEntity) == -1L) {+ if (requeuePhase(providerId, workflow.generation, phase, force, now) == 0) {+ recoverStaleRunningPhase(+ providerId,+ workflow.generation,+ phase,+ now,+ staleHeartbeatBefore+ )+ }+ }+ return ProviderWorkflowTicket(providerId, workflow.generation, phase)+ }++ @Query(+ """+ UPDATE provider_workflows+ SET state = 'RUNNING',+ current_phase = :phase,+ lease_token = :token,+ lease_expires_at = :expiresAt,+ heartbeat_at = :now,+ progress_message = NULL,+ last_error_code = NULL,+ last_error_message = NULL,+ updated_at = :now,+ completed_at = NULL+ WHERE provider_id = :providerId+ AND generation = :generation+ AND EXISTS (+ SELECT 1 FROM provider_workflow_phases phase_row+ WHERE phase_row.provider_id = :providerId+ AND phase_row.generation = :generation+ AND phase_row.phase = :phase+ AND phase_row.state IN ('PENDING', 'FAILED_RETRYABLE')+ )+ AND (+ lease_token IS NULL+ OR lease_expires_at IS NULL+ OR lease_expires_at <= :now+ OR heartbeat_at IS NULL+ OR heartbeat_at <= :staleHeartbeatBefore+ OR heartbeat_at > :now+ )+ """+ )+ protected abstract suspend fun claimWorkflow(+ providerId: Long,+ generation: Long,+ phase: ProviderWorkflowPhase,+ token: String,+ now: Long,+ expiresAt: Long,+ staleHeartbeatBefore: Long+ ): Int++ @Query(+ """+ UPDATE provider_workflow_phases+ SET state = 'RUNNING',+ attempt_count = attempt_count + 1,+ last_error_code = NULL,+ last_error_message = NULL,+ updated_at = :now,+ completed_at = NULL+ WHERE provider_id = :providerId+ AND generation = :generation+ AND phase = :phase+ AND state IN ('PENDING', 'FAILED_RETRYABLE')+ """+ )+ protected abstract suspend fun markPhaseRunning(+ providerId: Long,+ generation: Long,+ phase: ProviderWorkflowPhase,+ now: Long+ ): Int++ @Transaction+ open suspend fun claim(+ ticket: ProviderWorkflowTicket,+ token: String,+ now: Long,+ leaseDurationMs: Long,+ staleHeartbeatBefore: Long+ ): ProviderWorkflowLease? {+ require(leaseDurationMs > 0L)+ if (!ticket.admitted) return null+ val expiresAt = now + leaseDurationMs+ if (+ claimWorkflow(+ providerId = ticket.providerId,+ generation = ticket.generation,+ phase = ticket.phase,+ token = token,+ now = now,+ expiresAt = expiresAt,+ staleHeartbeatBefore = staleHeartbeatBefore+ ) != 1+ ) {+ return null+ }+ check(+ markPhaseRunning(+ ticket.providerId,+ ticket.generation,+ ticket.phase,+ now+ ) == 1+ )+ return ProviderWorkflowLease(+ providerId = ticket.providerId,+ generation = ticket.generation,+ phase = ticket.phase,+ token = token,+ expiresAt = expiresAt+ )+ }++ @Query(+ """+ UPDATE provider_workflows+ SET heartbeat_at = :now,+ lease_expires_at = :expiresAt,+ progress_message = :progressMessage,+ updated_at = :now+ WHERE provider_id = :providerId+ AND generation = :generation+ AND state = 'RUNNING'+ AND current_phase = :phase+ AND lease_token = :token+ """+ )+ abstract suspend fun renewLease(+ providerId: Long,+ generation: Long,+ phase: ProviderWorkflowPhase,+ token: String,+ now: Long,+ expiresAt: Long,+ progressMessage: String? = null+ ): Int++ @Query(+ """+ SELECT COUNT(*) FROM provider_workflows+ WHERE provider_id = :providerId+ AND generation = :generation+ AND state = 'RUNNING'+ AND current_phase = :phase+ AND lease_token = :token+ """+ )+ protected abstract suspend fun ownsLease(+ providerId: Long,+ generation: Long,+ phase: ProviderWorkflowPhase,+ token: String+ ): Int++ @Query(+ """+ SELECT COUNT(*) FROM provider_workflows+ WHERE provider_id = :providerId+ AND generation = :generation+ AND state = 'RUNNING'+ AND current_phase = :phase+ AND lease_token = :token+ """+ )+ abstract suspend fun isCurrentOwner(+ providerId: Long,+ generation: Long,+ phase: ProviderWorkflowPhase,+ token: String+ ): Int++ @Query(+ """+ UPDATE provider_workflow_phases+ SET state = :state,+ checkpoint = :checkpoint,+ last_error_code = :errorCode,+ last_error_message = :errorMessage,+ updated_at = :now,+ completed_at = CASE+ WHEN :state IN ('SUCCEEDED', 'PARTIAL', 'FAILED_PERMANENT') THEN :now+ ELSE NULL+ END+ WHERE provider_id = :providerId+ AND generation = :generation+ AND phase = :phase+ AND state = 'RUNNING'+ """+ )+ protected abstract suspend fun finishPhase(+ providerId: Long,+ generation: Long,+ phase: ProviderWorkflowPhase,+ state: ProviderWorkflowPhaseState,+ checkpoint: String?,+ errorCode: String?,+ errorMessage: String?,+ now: Long+ ): Int++ @Query(+ """+ SELECT COUNT(*) FROM provider_workflow_phases+ WHERE provider_id = :providerId+ AND generation = :generation+ AND state IN ('PENDING', 'RUNNING', 'FAILED_RETRYABLE')+ """+ )+ protected abstract suspend fun unfinishedPhaseCount(+ providerId: Long,+ generation: Long+ ): Int++ @Query(+ """+ UPDATE provider_workflows+ SET state = :state,+ current_phase = NULL,+ lease_token = NULL,+ lease_expires_at = NULL,+ heartbeat_at = NULL,+ progress_message = NULL,+ last_error_code = :errorCode,+ last_error_message = :errorMessage,+ updated_at = :now,+ completed_at = CASE+ WHEN :state IN ('SUCCEEDED', 'PARTIAL', 'FAILED', 'CANCELLED') THEN :now+ ELSE NULL+ END+ WHERE provider_id = :providerId+ AND generation = :generation+ AND lease_token = :token+ """+ )+ protected abstract suspend fun finishWorkflowOwnership(+ providerId: Long,+ generation: Long,+ token: String,+ state: ProviderWorkflowState,+ errorCode: String?,+ errorMessage: String?,+ now: Long+ ): Int++ @Transaction+ open suspend fun complete(+ lease: ProviderWorkflowLease,+ now: Long,+ checkpoint: String? = null,+ partial: Boolean = false+ ): Boolean {+ if (ownsLease(lease.providerId, lease.generation, lease.phase, lease.token) != 1) {+ return false+ }+ val phaseState = if (partial) {+ ProviderWorkflowPhaseState.PARTIAL+ } else {+ ProviderWorkflowPhaseState.SUCCEEDED+ }+ check(+ finishPhase(+ lease.providerId,+ lease.generation,+ lease.phase,+ phaseState,+ checkpoint,+ null,+ null,+ now+ ) == 1+ )+ val hasMoreWork = unfinishedPhaseCount(lease.providerId, lease.generation) > 0+ val workflowState = when {+ hasMoreWork -> ProviderWorkflowState.PENDING+ partial -> ProviderWorkflowState.PARTIAL+ else -> ProviderWorkflowState.SUCCEEDED+ }+ return finishWorkflowOwnership(+ lease.providerId,+ lease.generation,+ lease.token,+ workflowState,+ null,+ null,+ now+ ) == 1+ }++ @Transaction+ open suspend fun fail(+ lease: ProviderWorkflowLease,+ now: Long,+ errorCode: String,+ errorMessage: String?,+ retryable: Boolean,+ checkpoint: String? = null+ ): Boolean {+ if (ownsLease(lease.providerId, lease.generation, lease.phase, lease.token) != 1) {+ return false+ }+ val phaseState = if (retryable) {+ ProviderWorkflowPhaseState.FAILED_RETRYABLE+ } else {+ ProviderWorkflowPhaseState.FAILED_PERMANENT+ }+ check(+ finishPhase(+ lease.providerId,+ lease.generation,+ lease.phase,+ phaseState,+ checkpoint,+ errorCode,+ errorMessage,+ now+ ) == 1+ )+ return finishWorkflowOwnership(+ lease.providerId,+ lease.generation,+ lease.token,+ if (retryable) ProviderWorkflowState.PENDING else ProviderWorkflowState.FAILED,+ errorCode,+ errorMessage,+ now+ ) == 1+ }++ @Query(+ """+ SELECT * FROM provider_workflows+ WHERE state = 'RUNNING'+ AND (+ lease_token IS NULL+ OR lease_expires_at IS NULL+ OR lease_expires_at <= :now+ OR heartbeat_at IS NULL+ OR heartbeat_at <= :staleHeartbeatBefore+ OR heartbeat_at > :now+ )+ ORDER BY updated_at+ """+ )+ abstract suspend fun getRecoveryCandidates(+ now: Long,+ staleHeartbeatBefore: Long+ ): List<ProviderWorkflowEntity>++ private companion object {+ const val DEFAULT_STALE_HEARTBEAT_MILLIS = 2 * 60_000L+ }+}diff --git a/data/src/main/java/com/streamvault/data/local/dao/RecordingDaos.kt b/data/src/main/java/com/streamvault/data/local/dao/RecordingDaos.ktindex 93dc200b..127f34a6 100644--- a/data/src/main/java/com/streamvault/data/local/dao/RecordingDaos.kt+++ b/data/src/main/java/com/streamvault/data/local/dao/RecordingDaos.kt@@ -10,6 +10,7 @@ import com.streamvault.data.local.entity.RecordingRunWithScheduleimport com.streamvault.data.local.entity.RecordingScheduleEntityimport com.streamvault.data.local.entity.RecordingStorageEntityimport com.streamvault.data.local.entity.ProgramReminderEntity+import com.streamvault.domain.model.ProgramReminderDeliveryStateimport com.streamvault.domain.model.RecordingStatusimport kotlinx.coroutines.flow.Flow@@ -200,11 +201,11 @@ interface ProgramReminderDao {SELECT * FROM program_remindersWHERE is_dismissed = 0AND notified_at IS NULL- AND program_start_time > :now+ AND program_start_time >= :activeAfterORDER BY remind_at ASC""")- suspend fun getPendingActive(now: Long = System.currentTimeMillis()): List<ProgramReminderEntity>+ suspend fun getPendingActive(activeAfter: Long): List<ProgramReminderEntity>@Insert(onConflict = OnConflictStrategy.REPLACE)suspend fun insert(reminder: ProgramReminderEntity): Long@@ -215,6 +216,69 @@ interface ProgramReminderDao {@Query("UPDATE program_reminders SET exact_alarm_armed = :armed WHERE id = :id")suspend fun setExactAlarmArmed(id: Long, armed: Boolean)+ @Query(+ """+ UPDATE program_reminders+ SET delivery_state = 'DELIVERING',+ delivery_attempt_token = :attemptToken,+ delivery_attempted_at = :attemptedAt,+ delivery_attempt_count = delivery_attempt_count + 1,+ delivery_failure_reason = NULL,+ exact_alarm_armed = 0+ WHERE id = :id+ AND is_dismissed = 0+ AND notified_at IS NULL+ AND delivery_state IN ('PENDING', 'BLOCKED', 'FAILED')+ """+ )+ suspend fun claimDelivery(id: Long, attemptToken: String, attemptedAt: Long): Int++ @Query(+ """+ UPDATE program_reminders+ SET delivery_state = 'DELIVERED',+ notified_at = :notifiedAt,+ delivery_attempt_token = NULL,+ delivery_failure_reason = NULL,+ exact_alarm_armed = 0+ WHERE id = :id+ AND delivery_state = 'DELIVERING'+ AND delivery_attempt_token = :attemptToken+ """+ )+ suspend fun markDelivered(id: Long, attemptToken: String, notifiedAt: Long): Int++ @Query(+ """+ UPDATE program_reminders+ SET delivery_state = :state,+ delivery_attempt_token = NULL,+ delivery_failure_reason = :reason,+ exact_alarm_armed = 0+ WHERE id = :id+ AND delivery_state = 'DELIVERING'+ AND delivery_attempt_token = :attemptToken+ """+ )+ suspend fun markDeliveryIssue(+ id: Long,+ attemptToken: String,+ state: ProgramReminderDeliveryState,+ reason: String+ ): Int++ @Query(+ """+ UPDATE program_reminders+ SET delivery_state = 'PENDING',+ delivery_attempt_token = NULL+ WHERE id = :id+ AND delivery_state = 'DELIVERING'+ AND delivery_attempt_token = :attemptToken+ """+ )+ suspend fun resetInterruptedDelivery(id: Long, attemptToken: String): Int+@Query("""DELETE FROM program_remindersdiff --git a/data/src/main/java/com/streamvault/data/local/entity/DownloadEntity.kt b/data/src/main/java/com/streamvault/data/local/entity/DownloadEntity.ktindex 4e207e3d..e6e01698 100644--- a/data/src/main/java/com/streamvault/data/local/entity/DownloadEntity.kt+++ b/data/src/main/java/com/streamvault/data/local/entity/DownloadEntity.kt@@ -39,6 +39,9 @@ data class DownloadEntity(@ColumnInfo(name = "created_at") val createdAt: Long = System.currentTimeMillis(),@ColumnInfo(name = "completed_at") val completedAt: Long? = null,@ColumnInfo(name = "failure_reason") val failureReason: String? = null,+ @ColumnInfo(name = "owner_id") val ownerId: String? = null,+ @ColumnInfo(name = "owner_epoch") val ownerEpoch: Long = 0L,+ @ColumnInfo(name = "heartbeat_at") val heartbeatAt: Long? = null,@ColumnInfo(name = "series_id") val seriesId: Long? = null,@ColumnInfo(name = "season_number") val seasonNumber: Int? = null,@ColumnInfo(name = "episode_number") val episodeNumber: Int? = nulldiff --git a/data/src/main/java/com/streamvault/data/local/entity/Entities.kt b/data/src/main/java/com/streamvault/data/local/entity/Entities.ktindex d5ba355d..898a32ab 100644--- a/data/src/main/java/com/streamvault/data/local/entity/Entities.kt+++ b/data/src/main/java/com/streamvault/data/local/entity/Entities.kt@@ -79,6 +79,63 @@ data class ProviderEntity(@ColumnInfo(name = "created_at") val createdAt: Long = System.currentTimeMillis())+/** Lifecycle of a provider configuration which has not yet replaced the committed row. */+enum class ProviderConfigRevisionState {+ PENDING,+ SYNCING,+ FAILED,+ COMMITTED,+ SUPERSEDED+}++/**+ * A candidate provider configuration that has not yet replaced the committed provider row.+ *+ * The configuration payload always contains an already-encrypted password. Keeping it outside+ * of [ProviderEntity] lets an active provider continue to resolve and play its committed catalog+ * while a replacement configuration is authenticated and synchronized.+ */+@Entity(+ tableName = "provider_config_revisions",+ primaryKeys = ["provider_id", "revision"],+ foreignKeys = [ForeignKey(+ entity = ProviderEntity::class,+ parentColumns = ["id"],+ childColumns = ["provider_id"],+ onDelete = ForeignKey.CASCADE+ )],+ indices = [Index(value = ["provider_id", "state"])]+)+data class ProviderConfigRevisionEntity(+ @ColumnInfo(name = "provider_id") val providerId: Long,+ val revision: Long,+ @ColumnInfo(name = "config_json") val configJson: String,+ val state: ProviderConfigRevisionState,+ @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+)++/**+ * Checkpoints a cross-store backup restore. Room is transactional, while DataStore and alarm+ * scheduling are not; keeping each completed boundary durable lets a retry resume truthfully.+ */+@Entity(tableName = "backup_restore_checkpoints")+data class BackupRestoreCheckpointEntity(+ @PrimaryKey+ @ColumnInfo(name = "restore_key") val restoreKey: String,+ @ColumnInfo(name = "room_complete") val roomComplete: Boolean = false,+ @ColumnInfo(name = "preferences_complete") val preferencesComplete: Boolean = false,+ @ColumnInfo(name = "presets_complete") val presetsComplete: Boolean = false,+ @ColumnInfo(name = "schedules_complete") val schedulesComplete: Boolean = false,+ val state: String,+ @ColumnInfo(name = "preference_snapshot_json") val preferenceSnapshotJson: String? = null,+ @ColumnInfo(name = "last_error") val lastError: String? = null,+ @ColumnInfo(name = "created_at") val createdAt: Long,+ @ColumnInfo(name = "updated_at") val updatedAt: Long+)+@Entity(tableName = "channels",foreignKeys = [ForeignKey(diff --git a/data/src/main/java/com/streamvault/data/local/entity/ProviderWorkflowEntities.kt b/data/src/main/java/com/streamvault/data/local/entity/ProviderWorkflowEntities.ktnew file mode 100644index 00000000..4afabe40--- /dev/null+++ b/data/src/main/java/com/streamvault/data/local/entity/ProviderWorkflowEntities.kt@@ -0,0 +1,139 @@+package com.streamvault.data.local.entity++import androidx.room.ColumnInfo+import androidx.room.Entity+import androidx.room.ForeignKey+import androidx.room.Index++enum class ProviderWorkflowState {+ PENDING,+ RUNNING,+ SUCCEEDED,+ PARTIAL,+ FAILED,+ CANCELLED+}++enum class ProviderWorkflowPhase {+ PREPARE,+ PRIMARY_CATALOG,+ CONTENT_INDEX,+ MOVIE_INDEX,+ SERIES_INDEX,+ EPG,+ FINALIZE+}++enum class ProviderWorkflowPhaseState {+ PENDING,+ RUNNING,+ SUCCEEDED,+ PARTIAL,+ FAILED_RETRYABLE,+ FAILED_PERMANENT,+ SUPERSEDED+}++enum class ProviderWorkflowReason {+ STARTUP,+ PERIODIC,+ MANUAL,+ CONFIG_CHANGE,+ RECOVERY,+ REPAIR+}++/**+ * Durable coordinator state for all catalog and EPG work belonging to one provider.+ *+ * [generation] is a fencing epoch. Any operation that supersedes the active workflow increments+ * it, so an older worker can no longer renew its lease or commit a phase result.+ */+@Entity(+ tableName = "provider_workflows",+ foreignKeys = [+ ForeignKey(+ entity = ProviderEntity::class,+ parentColumns = ["id"],+ childColumns = ["provider_id"],+ onDelete = ForeignKey.CASCADE+ )+ ],+ indices = [+ Index(value = ["state"]),+ Index(value = ["updated_at"]),+ Index(value = ["lease_expires_at"])+ ]+)+data class ProviderWorkflowEntity(+ @androidx.room.PrimaryKey+ @ColumnInfo(name = "provider_id")+ val providerId: Long,+ val generation: Long,+ val state: ProviderWorkflowState,+ val reason: ProviderWorkflowReason,+ val priority: Int = 0,+ val force: Boolean = false,+ @ColumnInfo(name = "current_phase")+ val currentPhase: ProviderWorkflowPhase? = null,+ @ColumnInfo(name = "lease_token")+ val leaseToken: String? = null,+ @ColumnInfo(name = "lease_expires_at")+ val leaseExpiresAt: Long? = null,+ @ColumnInfo(name = "heartbeat_at")+ val heartbeatAt: Long? = null,+ @ColumnInfo(name = "progress_message")+ val progressMessage: String? = null,+ @ColumnInfo(name = "last_error_code")+ val lastErrorCode: String? = null,+ @ColumnInfo(name = "last_error_message")+ val lastErrorMessage: String? = null,+ @ColumnInfo(name = "created_at")+ val createdAt: Long,+ @ColumnInfo(name = "updated_at")+ val updatedAt: Long,+ @ColumnInfo(name = "completed_at")+ val completedAt: Long? = null+)++/**+ * Per-generation phase ledger. Older generations are retained as an audit trail and explicitly+ * marked [ProviderWorkflowPhaseState.SUPERSEDED] when a new generation replaces them.+ */+@Entity(+ tableName = "provider_workflow_phases",+ primaryKeys = ["provider_id", "generation", "phase"],+ foreignKeys = [+ ForeignKey(+ entity = ProviderEntity::class,+ parentColumns = ["id"],+ childColumns = ["provider_id"],+ onDelete = ForeignKey.CASCADE+ )+ ],+ indices = [+ Index(value = ["provider_id"]),+ Index(value = ["state"]),+ Index(value = ["updated_at"])+ ]+)+data class ProviderWorkflowPhaseEntity(+ @ColumnInfo(name = "provider_id")+ val providerId: Long,+ val generation: Long,+ val phase: ProviderWorkflowPhase,+ val state: ProviderWorkflowPhaseState,+ @ColumnInfo(name = "attempt_count")+ val attemptCount: Int = 0,+ val checkpoint: String? = null,+ @ColumnInfo(name = "last_error_code")+ val lastErrorCode: String? = null,+ @ColumnInfo(name = "last_error_message")+ val lastErrorMessage: String? = null,+ @ColumnInfo(name = "created_at")+ val createdAt: Long,+ @ColumnInfo(name = "updated_at")+ val updatedAt: Long,+ @ColumnInfo(name = "completed_at")+ val completedAt: Long? = null+)diff --git a/data/src/main/java/com/streamvault/data/local/entity/RecordingEntities.kt b/data/src/main/java/com/streamvault/data/local/entity/RecordingEntities.ktindex fe4ac999..0d13f5dd 100644--- a/data/src/main/java/com/streamvault/data/local/entity/RecordingEntities.kt+++ b/data/src/main/java/com/streamvault/data/local/entity/RecordingEntities.kt@@ -9,6 +9,7 @@ import com.streamvault.domain.model.RecordingFailureCategoryimport com.streamvault.domain.model.RecordingRecurrenceimport com.streamvault.domain.model.RecordingSourceTypeimport com.streamvault.domain.model.RecordingStatus+import com.streamvault.domain.model.ProgramReminderDeliveryState@Entity(tableName = "recording_schedules",@@ -157,6 +158,12 @@ data class ProgramReminderEntity(@ColumnInfo(name = "is_dismissed") val isDismissed: Boolean = false,@ColumnInfo(name = "notified_at") val notifiedAt: Long? = null,@ColumnInfo(name = "exact_alarm_armed") val exactAlarmArmed: Boolean = true,+ @ColumnInfo(name = "delivery_state")+ val deliveryState: ProgramReminderDeliveryState = ProgramReminderDeliveryState.PENDING,+ @ColumnInfo(name = "delivery_attempt_token") val deliveryAttemptToken: String? = null,+ @ColumnInfo(name = "delivery_attempted_at") val deliveryAttemptedAt: Long? = null,+ @ColumnInfo(name = "delivery_attempt_count") val deliveryAttemptCount: Int = 0,+ @ColumnInfo(name = "delivery_failure_reason") val deliveryFailureReason: String? = null,@ColumnInfo(name = "created_at") val createdAt: Long = System.currentTimeMillis())diff --git a/data/src/main/java/com/streamvault/data/manager/BackupManagerImpl.kt b/data/src/main/java/com/streamvault/data/manager/BackupManagerImpl.ktindex 44e786dd..011dfe48 100644--- a/data/src/main/java/com/streamvault/data/manager/BackupManagerImpl.kt+++ b/data/src/main/java/com/streamvault/data/manager/BackupManagerImpl.kt@@ -3,9 +3,15 @@ package com.streamvault.data.managerimport android.content.Contextimport android.net.Uriimport com.google.gson.Gson+import com.google.gson.JsonParseExceptionimport com.google.gson.reflect.TypeToken+import com.google.gson.stream.JsonReader+import com.google.gson.stream.JsonTokenimport com.google.gson.stream.JsonWriter+import com.google.gson.stream.MalformedJsonExceptionimport com.streamvault.data.local.DatabaseTransactionRunner+import com.streamvault.data.local.dao.BackupRestoreCheckpointDao+import com.streamvault.data.local.dao.ChannelDaoimport com.streamvault.data.local.dao.EpisodeDaoimport com.streamvault.data.local.dao.FavoriteDaoimport com.streamvault.data.local.dao.MovieDao@@ -14,6 +20,7 @@ import com.streamvault.data.local.dao.ProviderDaoimport com.streamvault.data.local.dao.RecordingScheduleDaoimport com.streamvault.data.local.dao.VirtualGroupDaoimport com.streamvault.data.local.entity.ProviderEntity+import com.streamvault.data.local.entity.BackupRestoreCheckpointEntityimport com.streamvault.data.local.entity.RecordingScheduleEntityimport com.streamvault.data.mapper.toDomainimport com.streamvault.data.mapper.toEntity@@ -24,12 +31,18 @@ import com.streamvault.domain.manager.BackupDataimport com.streamvault.domain.manager.BackupConflictStrategyimport com.streamvault.domain.manager.BackupImportPlanimport com.streamvault.domain.manager.BackupImportResult+import com.streamvault.domain.manager.BackupRestoreOutcomeimport com.streamvault.domain.manager.BackupManagerimport com.streamvault.domain.manager.BackupPreviewimport com.streamvault.domain.manager.RecordingScheduleImportDispositionimport com.streamvault.domain.manager.RecordingScheduleImportOutcomeimport com.streamvault.domain.manager.RecordingScheduleImportSummaryimport com.streamvault.domain.manager.ProtectedCategoryBackup+import com.streamvault.domain.manager.BackupProviderReference+import com.streamvault.domain.manager.PortableCategoryReference+import com.streamvault.domain.manager.PortableChannelReference+import com.streamvault.domain.manager.PortableProviderPreferencesBackup+import com.streamvault.domain.manager.PortableVirtualGroupReferenceimport com.streamvault.domain.manager.RecordingManagerimport com.streamvault.domain.manager.ScheduledRecordingBackupimport com.streamvault.domain.model.AppTopLevelDestination@@ -42,13 +55,16 @@ import com.streamvault.domain.model.Resultimport com.streamvault.domain.repository.CategoryRepositoryimport dagger.hilt.android.qualifiers.ApplicationContextimport kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.CancellationExceptionimport kotlinx.coroutines.flow.firstimport kotlinx.coroutines.withContextimport java.io.OutputStreamimport java.io.Fileimport java.io.FileInputStreamimport java.io.FileOutputStream+import java.io.EOFExceptionimport java.io.FilterInputStream+import java.io.FilterReaderimport java.io.IOExceptionimport java.io.InputStreamReaderimport java.io.OutputStreamWriter@@ -74,7 +90,9 @@ class BackupManagerImpl @Inject constructor(private val recordingScheduleDao: RecordingScheduleDao,private val recordingManager: RecordingManager,private val transactionRunner: DatabaseTransactionRunner,- private val gson: Gson+ private val gson: Gson,+ private val backupRestoreCheckpointDao: BackupRestoreCheckpointDao? = null,+ private val channelDao: ChannelDao) : BackupManager {override suspend fun exportConfig(uriString: String): com.streamvault.domain.model.Result<Unit> = withContext(Dispatchers.IO) {@@ -212,7 +230,8 @@ class BackupManagerImpl @Inject constructor(playbackHistory = playbackHistory,multiViewPresets = multiViewPresets,protectedCategories = protectedCategories,- scheduledRecordings = scheduledRecordings+ scheduledRecordings = scheduledRecordings,+ portableProviderPreferences = buildPortableProviderPreferences(providerEntities))// Compute checksum over the data without checksum field@@ -277,9 +296,6 @@ class BackupManagerImpl @Inject constructor(val protectedCategoryKeys = existingProtectedCategories.mapTo(hashSetOf()) { (provider, name, type) ->Triple(provider.id, name, type)}- val recordingKeys = existingScheduledRecordings.mapTo(hashSetOf()) {- RecordingConflictKey(it.providerId, it.scheduledStartMs, it.channelId, it.streamUrl)- }val providerConflicts = backupData.providers.orEmpty().count { it.backupIdentity() in providersByIdentity }val groupConflicts = backupData.virtualGroups.orEmpty().count { (it.name.lowercase() to it.contentType) in groupKeys }val favoriteConflicts = backupData.favorites.orEmpty().count {@@ -292,13 +308,11 @@ class BackupManagerImpl @Inject constructor(val provider = providersByIdentity[incoming.backupIdentity()] ?: return@count falseTriple(provider.id, incoming.categoryName.lowercase(), incoming.type) in protectedCategoryKeys}- val recordingConflicts = backupData.scheduledRecordings.orEmpty().normalizedRecurringBackups().count { incoming ->- val provider = providersByIdentity[incoming.backupIdentity()] ?: return@count false- recordingKeys.any { key ->- key.providerId == provider.id && key.startMs == incoming.scheduledStartMs &&- (key.channelId == incoming.channelId || key.streamUrl == incoming.streamUrl)- }- }+ val recordingConflicts = countScheduledRecordingConflicts(+ incoming = backupData.scheduledRecordings.orEmpty().normalizedRecurringBackups(),+ providersByIdentity = providersByIdentity,+ existing = existingScheduledRecordings+ )Result.success(BackupPreview(@@ -319,6 +333,8 @@ class BackupManagerImpl @Inject constructor(recordingConflicts = recordingConflicts))+ } catch (cancelled: CancellationException) {+ throw cancelled} catch (e: Exception) {Result.error("Failed to inspect backup: ${e.message}", e)}@@ -342,81 +358,312 @@ class BackupManagerImpl @Inject constructor(return@withContext com.streamvault.domain.model.Result.error("Backup file is corrupted (checksum mismatch)")}- var storedProviders = providerDao.getAllSync()+ val restoreKey = buildRestoreKey(backupData, plan)+ var checkpoint = loadOrCreateCheckpoint(restoreKey)+ if (checkpoint.state == RESTORE_STATE_COMPLETE) {+ return@withContext com.streamvault.domain.model.Result.success(+ checkpoint.toImportResult(plan, backupData)+ )+ }+ var storedProviders = providerDao.getAllSync()val importedSections = mutableListOf<String>()val skippedSections = mutableListOf<String>()-- val importedPreferences = if (plan.importPreferences) backupData.preferences else null- if (!plan.importPreferences) {- skippedSections += "Preferences"+ val failedSections = mutableListOf<String>()+ val unresolvedReferences = mutableListOf<String>()++ if (!checkpoint.roomComplete) {+ val roomCheckpoint = checkpoint.copy(+ roomComplete = true,+ state = RESTORE_STATE_RUNNING,+ lastError = null,+ updatedAt = System.currentTimeMillis()+ )+ val roomRestoreResult = try {+ restoreRoomBackedSections(+ backupData = backupData,+ plan = plan,+ initialStoredProviders = storedProviders,+ onRoomCommitted = { roomCheckpoint.persist() }+ )+ } catch (error: Exception) {+ checkpoint = checkpoint.copy(+ state = RESTORE_STATE_FAILED_BEFORE_COMMIT,+ lastError = "Room: ${error.message}",+ updatedAt = System.currentTimeMillis()+ ).persist()+ return@withContext com.streamvault.domain.model.Result.success(+ BackupImportResult(+ outcome = BackupRestoreOutcome.FAILED_BEFORE_COMMIT,+ failedSections = listOf("Room: ${error.message ?: "restore failed"}")+ )+ )+ }+ storedProviders = roomRestoreResult.storedProviders+ importedSections += roomRestoreResult.importedSections+ skippedSections += roomRestoreResult.skippedSections+ checkpoint = roomCheckpoint+ } else {+ importedSections += importedRoomSections(backupData, plan)+ skippedSections += skippedRoomSections(backupData, plan)}- val roomRestoreResult = restoreRoomBackedSections(- backupData = backupData,- plan = plan,- initialStoredProviders = storedProviders- )- storedProviders = roomRestoreResult.storedProviders- importedSections += roomRestoreResult.importedSections- skippedSections += roomRestoreResult.skippedSections-if (plan.importPreferences) {- importedPreferences?.let { prefs ->- restorePreferences(prefs)- importedSections += "Preferences"- } ?: run { skippedSections += "Preferences" }- }+ val preferences = backupData.preferences+ val portablePreferences = backupData.portableProviderPreferences+ when {+ preferences == null && portablePreferences == null -> skippedSections += "Preferences"+ checkpoint.preferencesComplete -> importedSections += "Preferences"+ else -> try {+ checkpoint = checkpoint.ensurePreferenceSnapshot()+ checkpoint.preferenceSnapshotJson?.let { snapshotJson ->+ val snapshot = gson.fromJson<Map<String, String>>(snapshotJson, MAP_STRING_STRING_TYPE)+ // An incomplete checkpoint may be the result of process death between+ // DataStore writes. Restore the durable pre-import snapshot first.+ restoreCheckpointPreferenceSnapshot(snapshot)+ }+ preferences?.let {+ restorePreferences(it, skipProviderScopedReferences = portablePreferences != null)+ }+ portablePreferences?.let { portable ->+ unresolvedReferences += restorePortableProviderPreferences(portable, storedProviders)+ }+ val portableComplete = unresolvedReferences.isEmpty()+ if (!portableComplete) {+ failedSections += "Provider-scoped preferences: ${unresolvedReferences.size} unresolved"+ }+ checkpoint = checkpoint.copy(+ preferencesComplete = portableComplete,+ preferenceSnapshotJson = checkpoint.preferenceSnapshotJson.takeIf {+ !portableComplete ||+ (plan.importMultiViewPresets && backupData.multiViewPresets != null)+ },+ updatedAt = System.currentTimeMillis()+ ).persist(clearPreferenceSnapshot = portableComplete && !(+ plan.importMultiViewPresets && backupData.multiViewPresets != null+ ))+ importedSections += "Preferences"+ } catch (error: Exception) {+ val suffix = if (checkpoint.preferenceSnapshotJson == null) {+ "; no rollback snapshot was available"+ } else {+ runCatchingPreferenceRollback(checkpoint)+ ?.let { "; previous settings could not be restored: ${it.message}" }+ ?: "; previous settings restored"+ }+ failedSections += "Preferences: ${error.message ?: "restore failed"}$suffix"+ }+ }+ } else skippedSections += "Preferences"if (plan.importMultiViewPresets) {- backupData.multiViewPresets?.let { presets ->- preferencesRepository.setMultiViewPreset(0, presets["preset_1"].orEmpty())- preferencesRepository.setMultiViewPreset(1, presets["preset_2"].orEmpty())- preferencesRepository.setMultiViewPreset(2, presets["preset_3"].orEmpty())- importedSections += "Split Screen Presets"- } ?: run { skippedSections += "Split Screen Presets" }- } else {- skippedSections += "Split Screen Presets"- }+ val presets = backupData.multiViewPresets+ when {+ presets == null -> skippedSections += "Split Screen Presets"+ checkpoint.presetsComplete -> importedSections += "Split Screen Presets"+ else -> try {+ checkpoint = checkpoint.ensurePreferenceSnapshot()+ preferencesRepository.setMultiViewPreset(0, presets["preset_1"].orEmpty())+ preferencesRepository.setMultiViewPreset(1, presets["preset_2"].orEmpty())+ preferencesRepository.setMultiViewPreset(2, presets["preset_3"].orEmpty())+ checkpoint = checkpoint.copy(+ presetsComplete = true,+ preferenceSnapshotJson = null,+ updatedAt = System.currentTimeMillis()+ ).persist(clearPreferenceSnapshot = true)+ importedSections += "Split Screen Presets"+ } catch (error: Exception) {+ val suffix = if (checkpoint.preferenceSnapshotJson == null) {+ "; no rollback snapshot was available"+ } else {+ runCatchingPresetRollback(checkpoint)+ ?.let { "; previous presets could not be restored: ${it.message}" }+ ?: "; previous presets restored"+ }+ failedSections += "Split Screen Presets: ${error.message ?: "restore failed"}$suffix"+ }+ }+ } else skippedSections += "Split Screen Presets"- val recordingScheduleImport = if (plan.importRecordingSchedules) {+ val recordingScheduleImport = if (plan.importRecordingSchedules && !checkpoint.schedulesComplete) {backupData.scheduledRecordings?.let { recordings ->- importScheduledRecordingBackups(- recordings = recordings.normalizedRecurringBackups(),- storedProviders = storedProviders,- existingSchedules = recordingManager.observeRecordingItems().first()- .filter { it.status == RecordingStatus.SCHEDULED }- .toMutableList(),- conflictStrategy = plan.conflictStrategy,- recordingManager = recordingManager- )+ try {+ importScheduledRecordingBackups(+ recordings = recordings.normalizedRecurringBackups(),+ storedProviders = storedProviders,+ existingSchedules = recordingManager.observeRecordingItems().first()+ .filter { it.status == RecordingStatus.SCHEDULED }+ .toMutableList(),+ conflictStrategy = plan.conflictStrategy,+ recordingManager = recordingManager+ )+ } catch (error: Exception) {+ failedSections += "Recording Schedules: ${error.message ?: "restore failed"}"+ null+ }}- } else {- null- }+ } else nullif (plan.importRecordingSchedules) {when {- recordingScheduleImport == null -> skippedSections += "Recording Schedules"- recordingScheduleImport.importedCount > 0 -> importedSections += "Recording Schedules"- else -> skippedSections += "Recording Schedules"+ backupData.scheduledRecordings == null -> skippedSections += "Recording Schedules"+ checkpoint.schedulesComplete -> importedSections += "Recording Schedules"+ recordingScheduleImport == null -> Unit+ recordingScheduleImport.failedCount > 0 -> failedSections += "Recording Schedules: ${recordingScheduleImport.failedCount} failed"+ else -> {+ checkpoint = checkpoint.copy(+ schedulesComplete = true,+ updatedAt = System.currentTimeMillis()+ ).persist()+ if (recordingScheduleImport.importedCount > 0) importedSections += "Recording Schedules"+ else skippedSections += "Recording Schedules"+ }}- } else {- skippedSections += "Recording Schedules"- }-+ } else skippedSections += "Recording Schedules"++ val outcome = if (failedSections.isEmpty()) BackupRestoreOutcome.COMPLETE else BackupRestoreOutcome.PARTIAL+ checkpoint = checkpoint.copy(+ state = if (outcome == BackupRestoreOutcome.COMPLETE) RESTORE_STATE_COMPLETE else RESTORE_STATE_PARTIAL,+ lastError = failedSections.joinToString().takeIf { it.isNotBlank() },+ updatedAt = System.currentTimeMillis()+ ).persist()com.streamvault.domain.model.Result.success(BackupImportResult(+ outcome = outcome,importedSections = importedSections.distinct(),skippedSections = skippedSections.distinct(),+ failedSections = failedSections.distinct(),+ unresolvedReferences = unresolvedReferences.distinct(),recordingScheduleImport = recordingScheduleImport))+ } catch (cancelled: CancellationException) {+ throw cancelled} catch (e: Exception) {com.streamvault.domain.model.Result.error("Failed to import backup: ${e.message}", e)}}+ private suspend fun loadOrCreateCheckpoint(restoreKey: String): BackupRestoreCheckpointEntity {+ val now = System.currentTimeMillis()+ val fresh = BackupRestoreCheckpointEntity(+ restoreKey = restoreKey,+ state = RESTORE_STATE_RUNNING,+ createdAt = now,+ updatedAt = now+ )+ val dao = backupRestoreCheckpointDao ?: return fresh+ dao.insertIfAbsent(fresh)+ return dao.get(restoreKey) ?: fresh+ }++ private suspend fun BackupRestoreCheckpointEntity.persist(+ clearPreferenceSnapshot: Boolean = false+ ): BackupRestoreCheckpointEntity {+ val dao = backupRestoreCheckpointDao ?: return this+ dao.update(+ restoreKey = restoreKey,+ roomComplete = roomComplete,+ preferencesComplete = preferencesComplete,+ presetsComplete = presetsComplete,+ schedulesComplete = schedulesComplete,+ state = state,+ lastError = lastError,+ updatedAt = updatedAt+ )+ if (clearPreferenceSnapshot) {+ dao.setPreferenceSnapshot(restoreKey, null, updatedAt)+ }+ return dao.get(restoreKey) ?: this+ }++ private suspend fun BackupRestoreCheckpointEntity.ensurePreferenceSnapshot(): BackupRestoreCheckpointEntity {+ if (preferenceSnapshotJson != null) return this+ val dao = backupRestoreCheckpointDao ?: return this+ val snapshot = gson.toJson(capturePreferenceSnapshot(providerDao.getAllSync()), MAP_STRING_STRING_TYPE)+ dao.setPreferenceSnapshot(restoreKey, snapshot, System.currentTimeMillis())+ return copy(preferenceSnapshotJson = snapshot, updatedAt = System.currentTimeMillis())+ }++ private suspend fun runCatchingPreferenceRollback(+ checkpoint: BackupRestoreCheckpointEntity+ ): Exception? = try {+ checkpoint.preferenceSnapshotJson?.let { snapshotJson ->+ restoreCheckpointPreferenceSnapshot(+ gson.fromJson<Map<String, String>>(snapshotJson, MAP_STRING_STRING_TYPE)+ )+ }+ null+ } catch (error: Exception) {+ error+ }++ private suspend fun runCatchingPresetRollback(+ checkpoint: BackupRestoreCheckpointEntity+ ): Exception? = try {+ checkpoint.preferenceSnapshotJson?.let { snapshotJson ->+ restoreCheckpointMultiViewPresets(+ gson.fromJson<Map<String, String>>(snapshotJson, MAP_STRING_STRING_TYPE)+ )+ }+ null+ } catch (error: Exception) {+ error+ }++ private fun buildRestoreKey(backupData: BackupData, plan: BackupImportPlan): String {+ val canonicalBackupChecksum = buildSha256Checksum(backupData.copy(checksum = null))+ val digest = MessageDigest.getInstance("SHA-256")+ digest.update(canonicalBackupChecksum.toByteArray(Charsets.UTF_8))+ digest.update(0)+ digest.update(gson.toJson(plan).toByteArray(Charsets.UTF_8))+ return digest.digest().joinToString(separator = "") { "%02x".format(it) }+ }++ private fun importedRoomSections(backupData: BackupData, plan: BackupImportPlan): List<String> = buildList {+ if (plan.importProviders && backupData.providers != null) add("Providers")+ if (plan.importSavedLibrary) add("Saved Library")+ if (plan.importPlaybackHistory && backupData.playbackHistory != null) add("Playback History")+ }++ private fun skippedRoomSections(backupData: BackupData, plan: BackupImportPlan): List<String> = buildList {+ if (!plan.importProviders || backupData.providers == null) add("Providers")+ if (!plan.importSavedLibrary) add("Saved Library")+ if (!plan.importPlaybackHistory || backupData.playbackHistory == null) add("Playback History")+ }++ private fun BackupRestoreCheckpointEntity.toImportResult(+ plan: BackupImportPlan,+ backupData: BackupData+ ): BackupImportResult {+ val imported = buildList {+ if (roomComplete) addAll(importedRoomSections(backupData, plan))+ if (preferencesComplete) add("Preferences")+ if (presetsComplete) add("Split Screen Presets")+ if (schedulesComplete) add("Recording Schedules")+ }+ val skipped = buildList {+ if (!roomComplete) addAll(skippedRoomSections(backupData, plan))+ if (!plan.importPreferences ||+ (backupData.preferences == null && backupData.portableProviderPreferences == null)+ ) {+ add("Preferences")+ }+ if (!plan.importMultiViewPresets || backupData.multiViewPresets == null) add("Split Screen Presets")+ if (!plan.importRecordingSchedules || backupData.scheduledRecordings == null) add("Recording Schedules")+ }+ return BackupImportResult(+ outcome = when (state) {+ RESTORE_STATE_COMPLETE -> BackupRestoreOutcome.COMPLETE+ RESTORE_STATE_FAILED_BEFORE_COMMIT -> BackupRestoreOutcome.FAILED_BEFORE_COMMIT+ else -> BackupRestoreOutcome.PARTIAL+ },+ importedSections = imported.distinct(),+ skippedSections = skipped.distinct(),+ failedSections = lastError?.let(::listOf).orEmpty()+ )+ }+private fun verifyChecksum(backupData: BackupData): Boolean {val storedChecksum = backupData.checksum ?: return true // no checksum = legacy backup, skip verificationval dataWithoutChecksum = backupData.copy(checksum = null)@@ -459,6 +706,12 @@ class BackupManagerImpl @Inject constructor(writeNamedJsonField(jsonWriter, "multiViewPresets", backupData.multiViewPresets, MULTIVIEW_PRESETS_TYPE)writeNamedJsonField(jsonWriter, "protectedCategories", backupData.protectedCategories, PROTECTED_CATEGORY_LIST_TYPE)writeNamedJsonField(jsonWriter, "scheduledRecordings", backupData.scheduledRecordings, SCHEDULED_RECORDING_LIST_TYPE)+ writeNamedJsonField(+ jsonWriter,+ "portableProviderPreferences",+ backupData.portableProviderPreferences,+ PortableProviderPreferencesBackup::class.java+ )jsonWriter.endObject()}}@@ -496,13 +749,315 @@ class BackupManagerImpl @Inject constructor(private fun readBackupData(uriString: String): BackupData? {return openBackupInputStream(uriString)?.use { inputStream ->BoundedInputStream(inputStream, MAX_BACKUP_BYTES).use { boundedInput ->- InputStreamReader(boundedInput).use { reader ->- gson.fromJson(reader, BackupData::class.java).also(::validateBackupDataLimits)+ AdmissionCheckingReader(+ InputStreamReader(boundedInput, Charsets.UTF_8),+ MAX_JSON_DEPTH,+ MAX_FIELD_CHARS+ ).use { admissionReader ->+ try {+ JsonReader(admissionReader).use { jsonReader ->+ readBackupData(jsonReader).also(::validateBackupDataLimits)+ }+ } catch (cancelled: CancellationException) {+ throw cancelled+ } catch (admission: BackupAdmissionException) {+ throw admission+ } catch (error: Exception) {+ if (error is MalformedJsonException ||+ error is EOFException ||+ error is JsonParseException ||+ error is IllegalStateException+ ) {+ throw BackupAdmissionException(+ BackupAdmissionReason.MALFORMED,+ "Backup JSON is malformed or truncated"+ ).also { it.initCause(error) }+ }+ throw error+ }}}}}+ private fun readBackupData(reader: JsonReader): BackupData {+ var version = 0+ var checksum: String? = null+ var preferences: Map<String, String>? = null+ var providers: List<com.streamvault.domain.model.Provider>? = null+ var favorites: List<com.streamvault.domain.model.Favorite>? = null+ var virtualGroups: List<com.streamvault.domain.model.VirtualGroup>? = null+ var playbackHistory: List<com.streamvault.domain.model.PlaybackHistory>? = null+ var multiViewPresets: Map<String, List<Long>>? = null+ var protectedCategories: List<ProtectedCategoryBackup>? = null+ var scheduledRecordings: List<ScheduledRecordingBackup>? = null+ var portableProviderPreferences: PortableProviderPreferencesBackup? = null+ val seenFields = hashSetOf<String>()+ var headerRead = false++ reader.beginObject()+ while (reader.hasNext()) {+ val field = reader.nextName()+ if (!seenFields.add(field)) {+ throw BackupAdmissionException(+ BackupAdmissionReason.DUPLICATE_FIELD,+ "Backup contains duplicate field '$field'"+ )+ }+ if (!headerRead && field != "version") {+ throw BackupAdmissionException(+ BackupAdmissionReason.MALFORMED,+ "Backup header must begin with version"+ )+ }+ when (field) {+ "version" -> {+ version = reader.nextInt()+ headerRead = true+ if (version > CURRENT_BACKUP_VERSION) {+ throw BackupAdmissionException(+ BackupAdmissionReason.UNSUPPORTED_VERSION,+ "Unsupported backup version $version"+ )+ }+ }+ "checksum" -> checksum = reader.nextString()+ "preferences" -> preferences = readStringMap(reader, MAX_PREFERENCES, "preferences")+ "providers" -> providers = readLimitedArray(reader, PROVIDER_TYPE, MAX_PROVIDERS, "providers")+ "favorites" -> favorites = readLimitedArray(reader, FAVORITE_TYPE, MAX_SECTION_ITEMS, "favorites")+ "virtualGroups" -> virtualGroups =+ readLimitedArray(reader, VIRTUAL_GROUP_TYPE, MAX_SECTION_ITEMS, "groups")+ "playbackHistory" -> playbackHistory =+ readLimitedArray(reader, PLAYBACK_HISTORY_TYPE, MAX_SECTION_ITEMS, "playback history")+ "multiViewPresets" -> multiViewPresets = readMultiViewPresets(reader)+ "protectedCategories" -> protectedCategories =+ readLimitedArray(reader, PROTECTED_CATEGORY_TYPE, MAX_SECTION_ITEMS, "protected categories")+ "scheduledRecordings" -> scheduledRecordings =+ readLimitedArray(reader, SCHEDULED_RECORDING_TYPE, MAX_SECTION_ITEMS, "recording schedules")+ "portableProviderPreferences" -> portableProviderPreferences =+ readPortableProviderPreferences(reader)+ else -> reader.skipValue()+ }+ }+ reader.endObject()+ if (!headerRead) {+ throw BackupAdmissionException(+ BackupAdmissionReason.MALFORMED,+ "Backup header is missing version"+ )+ }+ if (reader.peek() != JsonToken.END_DOCUMENT) {+ throw BackupAdmissionException(+ BackupAdmissionReason.MALFORMED,+ "Backup contains trailing JSON content"+ )+ }++ return BackupData(+ version = version,+ checksum = checksum,+ preferences = preferences,+ providers = providers,+ favorites = favorites,+ virtualGroups = virtualGroups,+ playbackHistory = playbackHistory,+ multiViewPresets = multiViewPresets,+ protectedCategories = protectedCategories,+ scheduledRecordings = scheduledRecordings,+ portableProviderPreferences = portableProviderPreferences+ )+ }++ private fun <T : Any> readLimitedArray(+ reader: JsonReader,+ type: Type,+ maxItems: Int,+ label: String+ ): List<T>? {+ if (reader.peek() == JsonToken.NULL) {+ reader.nextNull()+ return null+ }+ val result = ArrayList<T>()+ reader.beginArray()+ while (reader.hasNext()) {+ if (result.size >= maxItems) {+ throw BackupAdmissionException(+ BackupAdmissionReason.SECTION_LIMIT,+ "Backup has too many $label"+ )+ }+ val item = gson.fromJson<T>(reader, type)+ ?: throw BackupAdmissionException(+ BackupAdmissionReason.MALFORMED,+ "Backup contains a null $label entry"+ )+ result += item+ }+ reader.endArray()+ return result+ }++ private fun readStringMap(+ reader: JsonReader,+ maxItems: Int,+ label: String+ ): Map<String, String>? {+ if (reader.peek() == JsonToken.NULL) {+ reader.nextNull()+ return null+ }+ val result = linkedMapOf<String, String>()+ reader.beginObject()+ while (reader.hasNext()) {+ if (result.size >= maxItems) {+ throw BackupAdmissionException(+ BackupAdmissionReason.SECTION_LIMIT,+ "Backup has too many $label"+ )+ }+ val key = reader.nextName()+ if (key in result) {+ throw BackupAdmissionException(+ BackupAdmissionReason.DUPLICATE_FIELD,+ "Backup contains duplicate $label key '$key'"+ )+ }+ result[key] = reader.nextString()+ }+ reader.endObject()+ return result+ }++ private fun readMultiViewPresets(reader: JsonReader): Map<String, List<Long>>? {+ if (reader.peek() == JsonToken.NULL) {+ reader.nextNull()+ return null+ }+ val result = linkedMapOf<String, List<Long>>()+ var totalEntries = 0+ reader.beginObject()+ while (reader.hasNext()) {+ if (result.size >= MAX_PREFERENCES) {+ throw BackupAdmissionException(+ BackupAdmissionReason.SECTION_LIMIT,+ "Backup has too many split-screen presets"+ )+ }+ val name = reader.nextName()+ if (name in result) {+ throw BackupAdmissionException(+ BackupAdmissionReason.DUPLICATE_FIELD,+ "Backup contains duplicate split-screen preset '$name'"+ )+ }+ val values = readLimitedArray<Long>(+ reader,+ LONG_TYPE,+ MAX_SECTION_ITEMS - totalEntries,+ "preset entries"+ ).orEmpty()+ totalEntries += values.size+ result[name] = values+ }+ reader.endObject()+ return result+ }++ private fun readPortableProviderPreferences(reader: JsonReader): PortableProviderPreferencesBackup? {+ if (reader.peek() == JsonToken.NULL) {+ reader.nextNull()+ return null+ }+ var providers = emptyList<BackupProviderReference>()+ var activeProvider: BackupProviderReference? = null+ var guideDefaultCategory: PortableCategoryReference? = null+ var guideDefaultVirtualCategoryId: Long? = null+ var guideDefaultCategorySpecified = false+ var promotedLiveGroups = emptyList<PortableVirtualGroupReference>()+ var hiddenChannels = emptyList<PortableChannelReference>()+ var hiddenCategories = emptyList<PortableCategoryReference>()+ var unresolvedReferences = emptyList<String>()+ val seenFields = hashSetOf<String>()++ reader.beginObject()+ while (reader.hasNext()) {+ val field = reader.nextName()+ if (!seenFields.add(field)) {+ throw BackupAdmissionException(+ BackupAdmissionReason.DUPLICATE_FIELD,+ "Portable preferences contain duplicate field '$field'"+ )+ }+ when (field) {+ "providers" -> providers =+ readLimitedArray<BackupProviderReference>(+ reader,+ BACKUP_PROVIDER_REFERENCE_TYPE,+ MAX_PROVIDERS,+ "portable providers"+ ).orEmpty()+ "activeProvider" -> activeProvider =+ gson.fromJson(reader, BACKUP_PROVIDER_REFERENCE_TYPE)+ "guideDefaultCategory" -> guideDefaultCategory =+ gson.fromJson(reader, PORTABLE_CATEGORY_REFERENCE_TYPE)+ "guideDefaultVirtualCategoryId" -> guideDefaultVirtualCategoryId =+ reader.nextNullableLong()+ "guideDefaultCategorySpecified" -> guideDefaultCategorySpecified =+ reader.nextBoolean()+ "promotedLiveGroups" -> promotedLiveGroups =+ readLimitedArray<PortableVirtualGroupReference>(+ reader,+ PORTABLE_GROUP_REFERENCE_TYPE,+ MAX_SECTION_ITEMS,+ "promoted groups"+ ).orEmpty()+ "hiddenChannels" -> hiddenChannels =+ readLimitedArray<PortableChannelReference>(+ reader,+ PORTABLE_CHANNEL_REFERENCE_TYPE,+ MAX_SECTION_ITEMS,+ "hidden channels"+ ).orEmpty()+ "hiddenCategories" -> hiddenCategories =+ readLimitedArray<PortableCategoryReference>(+ reader,+ PORTABLE_CATEGORY_REFERENCE_TYPE,+ MAX_SECTION_ITEMS,+ "hidden categories"+ ).orEmpty()+ "unresolvedReferences" -> unresolvedReferences =+ readLimitedArray<String>(+ reader,+ STRING_TYPE,+ MAX_SECTION_ITEMS,+ "unresolved references"+ ).orEmpty()+ else -> reader.skipValue()+ }+ }+ reader.endObject()+ return PortableProviderPreferencesBackup(+ providers = providers,+ activeProvider = activeProvider,+ guideDefaultCategory = guideDefaultCategory,+ guideDefaultVirtualCategoryId = guideDefaultVirtualCategoryId,+ guideDefaultCategorySpecified = guideDefaultCategorySpecified,+ promotedLiveGroups = promotedLiveGroups,+ hiddenChannels = hiddenChannels,+ hiddenCategories = hiddenCategories,+ unresolvedReferences = unresolvedReferences+ )+ }++ private fun JsonReader.nextNullableLong(): Long? =+ if (peek() == JsonToken.NULL) {+ nextNull()+ null+ } else {+ nextLong()+ }+private fun validateBackupDataLimits(data: BackupData) {require(data.preferences.orEmpty().size <= MAX_PREFERENCES) { "Backup has too many preferences" }require(data.providers.orEmpty().size <= MAX_PROVIDERS) { "Backup has too many providers" }@@ -544,6 +1099,109 @@ class BackupManagerImpl @Inject constructor(runCatching { File(java.net.URI(this)) }.getOrNull()?: Uri.parse(this).path?.let(::File)+ internal suspend fun buildPortableProviderPreferences(+ providers: List<ProviderEntity>+ ): PortableProviderPreferencesBackup {+ val channels = channelDao+ val referencesById = providers.associate { it.id to it.toBackupProviderReference() }+ val unresolved = mutableListOf<String>()+ val categoriesByProvider = providers.associate { provider ->+ provider.id to ContentType.entries.flatMap { type ->+ categoryRepository.getCategories(provider.id).first().filter { it.type == type }+ }+ }+ val activeProviderId = preferencesRepository.lastActiveProviderId.first()+ val activeProvider = activeProviderId?.let(referencesById::get).also { reference ->+ if (activeProviderId != null && reference == null) {+ unresolved += "Active provider id $activeProviderId was not found during export"+ }+ }+ val guideId = preferencesRepository.guideDefaultCategoryId.first()+ val guideDefaultCategory = guideId+ ?.takeUnless { it == 0L }+ ?.takeUnless { it in PORTABLE_VIRTUAL_CATEGORY_IDS }+ ?.let { categoryId ->+ val preferredProvider = activeProviderId?.let(categoriesByProvider::get)+ ?.filter { it.id == categoryId }+ ?.singleOrNull()+ val match = preferredProvider ?: categoriesByProvider.entries+ .mapNotNull { (providerId, categories) ->+ categories.filter { it.id == categoryId }.singleOrNull()?.let { providerId to it }+ }+ .singleOrNull()+ ?.second+ val providerId = when {+ preferredProvider != null -> activeProviderId+ else -> categoriesByProvider.entries.firstOrNull { (_, categories) ->+ categories.any { it.id == categoryId && it == match }+ }?.key+ }+ providerId?.let { id ->+ match?.let { category ->+ referencesById[id]?.let { provider ->+ PortableCategoryReference(provider, category.name, category.type, category.id)+ }+ }+ }+ }.also { reference ->+ if (guideId != null &&+ guideId != 0L &&+ guideId !in PORTABLE_VIRTUAL_CATEGORY_IDS &&+ reference == null+ ) {+ unresolved += "Guide category id $guideId was not found unambiguously during export"+ }+ }+ val promotedGroups = preferencesRepository.promotedLiveGroupIds.first().mapNotNull { groupId ->+ virtualGroupDao.getById(groupId)?.let { group ->+ referencesById[group.providerId]?.let { provider ->+ PortableVirtualGroupReference(provider, group.name, group.contentType)+ }+ } ?: run {+ unresolved += "Promoted group id $groupId was not found during export"+ null+ }+ }+ val hiddenChannels = providers.flatMap { provider ->+ 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)+ }+ } ?: run {+ unresolved += "Hidden channel id $channelId for provider ${provider.name} was not found during export"+ null+ }+ }+ }+ val hiddenCategories = providers.flatMap { provider ->+ val categories = categoriesByProvider[provider.id].orEmpty()+ ContentType.entries.flatMap { type ->+ preferencesRepository.getHiddenCategoryIds(provider.id, type).first().mapNotNull { categoryId ->+ categories.firstOrNull { it.id == categoryId && it.type == type }?.let { category ->+ referencesById[provider.id]?.let { reference ->+ PortableCategoryReference(reference, category.name, type, category.id)+ }+ } ?: run {+ unresolved += "Hidden ${type.name} category id $categoryId for provider ${provider.name} was not found during export"+ null+ }+ }+ }+ }+ return PortableProviderPreferencesBackup(+ providers = referencesById.values.toList(),+ activeProvider = activeProvider,+ guideDefaultCategory = guideDefaultCategory,+ guideDefaultVirtualCategoryId = guideId?.takeIf { it in PORTABLE_VIRTUAL_CATEGORY_IDS },+ guideDefaultCategorySpecified = guideId != null && guideId != 0L,+ promotedLiveGroups = promotedGroups.distinct(),+ hiddenChannels = hiddenChannels.distinct(),+ hiddenCategories = hiddenCategories.distinct(),+ unresolvedReferences = unresolved.distinct()+ )+ }+private fun BackupData.isStructurallyEmpty(): Boolean =preferences.isNullOrEmpty() &&providers.isNullOrEmpty() &&@@ -552,9 +1210,170 @@ class BackupManagerImpl @Inject constructor(playbackHistory.isNullOrEmpty() &&multiViewPresets.orEmpty().all { it.value.isEmpty() } &&protectedCategories.isNullOrEmpty() &&- scheduledRecordings.isNullOrEmpty()+ scheduledRecordings.isNullOrEmpty() &&+ portableProviderPreferences == null++ private suspend fun capturePreferenceSnapshot(providerEntities: List<ProviderEntity>): Map<String, String> {+ val parentalPinBackup = preferencesRepository.exportParentalPinBackup()+ return buildMap {+ put("parentalControlLevel", preferencesRepository.parentalControlLevel.first().toString())+ put("parentalPinHash", parentalPinBackup?.hash.orEmpty())+ put("parentalPinSalt", parentalPinBackup?.saltBase64.orEmpty())+ put("appLanguage", preferencesRepository.appLanguage.first())+ put("appLandingDestination", preferencesRepository.appLandingDestination.first().storageValue)+ put("appTopLevelDestinations", preferencesRepository.appTopLevelDestinations.first().joinToString(",") { it.storageValue })+ put("appHomeDashboardShelves", preferencesRepository.appHomeDashboardShelves.first().joinToString(",") { it.storageValue })+ put("liveTvCategoryFilters", preferencesRepository.liveTvCategoryFilters.first().joinToString("\n"))+ put("liveTvQuickFilterVisibility", preferencesRepository.liveTvQuickFilterVisibility.first() ?: "always")+ put("playerMediaSessionEnabled", preferencesRepository.playerMediaSessionEnabled.first().toString())+ put("playerAudioDecoderMode", preferencesRepository.playerAudioDecoderMode.first().name)+ put("playerVideoDecoderMode", preferencesRepository.playerVideoDecoderMode.first().name)+ put("playerAudioOutputPreference", preferencesRepository.playerAudioOutputPreference.first().name)+ put("playerCompatibilityMemoryEnabled", preferencesRepository.playerCompatibilityMemoryEnabled.first().toString())+ put("playerSurfaceMode", preferencesRepository.playerSurfaceMode.first().name)+ put("playerLiveStreamFormatMode", preferencesRepository.playerLiveStreamFormatMode.first().name)+ put("playerVodHttpProtocolMode", preferencesRepository.playerVodHttpProtocolMode.first().name)+ put("playerPlaybackSpeed", preferencesRepository.playerPlaybackSpeed.first().toString())+ put("playerAudioVideoSyncEnabled", preferencesRepository.playerAudioVideoSyncEnabled.first().toString())+ put("playerAudioVideoOffsetMs", preferencesRepository.playerAudioVideoOffsetMs.first().toString())+ put("multiViewRespectProviderConnectionLimit", preferencesRepository.multiViewRespectProviderConnectionLimit.first().toString())+ put("preferredAudioLanguage", preferencesRepository.preferredAudioLanguage.first() ?: "auto")+ put("playerSubtitleTextScale", preferencesRepository.playerSubtitleTextScale.first().toString())+ put("playerSubtitleTextColor", preferencesRepository.playerSubtitleTextColor.first().toString())+ put("playerSubtitleBackgroundColor", preferencesRepository.playerSubtitleBackgroundColor.first().toString())+ put("playerWifiMaxVideoHeight", (preferencesRepository.playerWifiMaxVideoHeight.first() ?: 0).toString())+ put("playerEthernetMaxVideoHeight", (preferencesRepository.playerEthernetMaxVideoHeight.first() ?: 0).toString())+ put("guideDensity", preferencesRepository.guideDensity.first() ?: "")+ put("guideChannelMode", preferencesRepository.guideChannelMode.first() ?: "")+ put("guideDefaultCategoryId", (preferencesRepository.guideDefaultCategoryId.first() ?: 0L).toString())+ put("guideFavoritesOnly", preferencesRepository.guideFavoritesOnly.first().toString())+ put("guideAnchorTime", (preferencesRepository.guideAnchorTime.first() ?: 0L).toString())+ put("lastActiveProviderId", (preferencesRepository.lastActiveProviderId.first() ?: -1L).toString())+ put("promotedLiveGroupIds", preferencesRepository.promotedLiveGroupIds.first().sorted().joinToString(","))+ put(RESTORE_SNAPSHOT_PRESET_1, preferencesRepository.getMultiViewPreset(0).first().joinToString(","))+ put(RESTORE_SNAPSHOT_PRESET_2, preferencesRepository.getMultiViewPreset(1).first().joinToString(","))+ put(RESTORE_SNAPSHOT_PRESET_3, preferencesRepository.getMultiViewPreset(2).first().joinToString(","))+ providerEntities.forEach { provider ->+ put(+ "hiddenChannels_${provider.id}",+ preferencesRepository.getHiddenChannelIds(provider.id).first().sorted().joinToString(",")+ )+ ContentType.entries.forEach { type ->+ put(+ "hiddenCategories_${provider.id}_${type.name}",+ preferencesRepository.getHiddenCategoryIds(provider.id, type).first().sorted().joinToString(",")+ )+ }+ }+ }+ }++ private suspend fun restoreCheckpointPreferenceSnapshot(snapshot: Map<String, String>) {+ restorePreferences(snapshot)+ snapshot["lastActiveProviderId"]?.toLongOrNull()?.let {+ preferencesRepository.setLastActiveProviderId(it)+ }+ restoreCheckpointMultiViewPresets(snapshot)+ }++ private suspend fun restoreCheckpointMultiViewPresets(snapshot: Map<String, String>) {+ preferencesRepository.setMultiViewPreset(+ 0,+ snapshot[RESTORE_SNAPSHOT_PRESET_1].orEmpty().split(",").mapNotNull(String::toLongOrNull)+ )+ preferencesRepository.setMultiViewPreset(+ 1,+ snapshot[RESTORE_SNAPSHOT_PRESET_2].orEmpty().split(",").mapNotNull(String::toLongOrNull)+ )+ preferencesRepository.setMultiViewPreset(+ 2,+ snapshot[RESTORE_SNAPSHOT_PRESET_3].orEmpty().split(",").mapNotNull(String::toLongOrNull)+ )+ }++ private suspend fun restorePortableProviderPreferences(+ portable: PortableProviderPreferencesBackup,+ storedProviders: List<ProviderEntity>+ ): List<String> {+ val unresolved = portable.unresolvedReferences.toMutableList()+ val channels = channelDao+ fun resolveProvider(reference: BackupProviderReference) =+ storedProviders.findUnambiguousPortableProvider(reference)+ val referencedProviders = buildSet {+ addAll(portable.providers)+ portable.activeProvider?.let(::add)+ portable.guideDefaultCategory?.provider?.let(::add)+ portable.promotedLiveGroups.forEach { add(it.provider) }+ portable.hiddenChannels.forEach { add(it.provider) }+ portable.hiddenCategories.forEach { add(it.provider) }+ }+ val resolvedProviders = referencedProviders.mapNotNull { reference ->+ resolveProvider(reference)?.let { reference to it }+ ?: run { unresolved += reference.unresolvedLabel("Provider"); null }+ }.toMap()+ val categories = resolvedProviders.values.associate { provider ->+ provider.id to categoryRepository.getCategories(provider.id).first()+ }+ portable.activeProvider?.let { reference ->+ resolveProvider(reference)?.let { provider ->+ preferencesRepository.setLastActiveProviderId(provider.id)+ } ?: run {+ unresolved += reference.unresolvedLabel("Active provider")+ }+ }+ val guideVirtualCategoryId = portable.guideDefaultVirtualCategoryId+ val guideCategoryReference = portable.guideDefaultCategory+ when {+ guideVirtualCategoryId != null ->+ preferencesRepository.setGuideDefaultCategoryId(guideVirtualCategoryId)+ guideCategoryReference != null -> {+ val reference = guideCategoryReference+ val provider = resolveProvider(reference.provider)+ categories[provider?.id].orEmpty()+ .resolvePortableCategory(reference)+ ?.let { preferencesRepository.setGuideDefaultCategoryId(it.id) }+ ?: run { unresolved += reference.unresolvedLabel("Guide category") }+ }+ !portable.guideDefaultCategorySpecified ->+ preferencesRepository.clearGuideDefaultCategoryId()+ }+ val promoted = portable.promotedLiveGroups.mapNotNull { reference ->+ val provider = resolveProvider(reference.provider) ?: return@mapNotNull null+ virtualGroupDao.getByType(provider.id, reference.contentType.name).first()+ .filter { it.name.equals(reference.name, true) }.singleOrNull()?.id+ ?: run { unresolved += reference.unresolvedLabel("Group"); null }+ }.toSet()+ preferencesRepository.setPromotedLiveGroupIds(promoted)+ resolvedProviders.forEach { (reference, provider) ->+ val matchingChannels = portable.hiddenChannels.filter { it.provider == reference }+ val providerChannels = channels.getByProviderSync(provider.id)+ val channelIds = matchingChannels.mapNotNull { requested ->+ providerChannels.resolvePortableChannel(requested)?.id+ ?: run {+ unresolved += requested.unresolvedLabel("Hidden channel")+ null+ }+ }.toSet()+ preferencesRepository.setHiddenChannelIds(provider.id, channelIds)+ ContentType.entries.forEach { type ->+ val requested = portable.hiddenCategories.filter { it.provider == reference && it.type == type }+ val ids = requested.mapNotNull { categoryReference ->+ categories[provider.id].orEmpty().resolvePortableCategory(categoryReference)?.id+ ?: run {+ unresolved += categoryReference.unresolvedLabel("Hidden ${type.name} category")+ null+ }+ }.toSet()+ preferencesRepository.setHiddenCategoryIds(provider.id, type, ids)+ }+ }+ return unresolved.distinct()+ }- private suspend fun restorePreferences(prefs: Map<String, String>) {+ private suspend fun restorePreferences(+ prefs: Map<String, String>,+ skipProviderScopedReferences: Boolean = false+ ) {prefs["parentalControlLevel"]?.toIntOrNull()?.let {preferencesRepository.setParentalControlLevel(it)}@@ -658,18 +1477,28 @@ class BackupManagerImpl @Inject constructor(preferencesRepository.setPlayerEthernetMaxVideoHeight(prefs["playerEthernetMaxVideoHeight"]?.toIntOrNull()?.takeIf { it > 0 })prefs["guideDensity"]?.takeIf { it.isNotBlank() }?.let { preferencesRepository.setGuideDensity(it) }prefs["guideChannelMode"]?.takeIf { it.isNotBlank() }?.let { preferencesRepository.setGuideChannelMode(it) }- prefs["guideDefaultCategoryId"]?.toLongOrNull()?.takeIf { it != 0L }?.let {- preferencesRepository.setGuideDefaultCategoryId(it)+ prefs["guideDefaultCategoryId"]?.toLongOrNull()?.takeUnless { skipProviderScopedReferences }?.let { categoryId ->+ if (categoryId == 0L) {+ preferencesRepository.clearGuideDefaultCategoryId()+ } else {+ preferencesRepository.setGuideDefaultCategoryId(categoryId)+ }}prefs["guideFavoritesOnly"]?.toBooleanStrictOrNull()?.let { preferencesRepository.setGuideFavoritesOnly(it) }- prefs["guideAnchorTime"]?.toLongOrNull()?.takeIf { it > 0L }?.let { preferencesRepository.setGuideAnchorTime(it) }- prefs["promotedLiveGroupIds"]?.let { token ->+ prefs["guideAnchorTime"]?.toLongOrNull()?.let { anchorTime ->+ if (anchorTime <= 0L) {+ preferencesRepository.clearGuideAnchorTime()+ } else {+ preferencesRepository.setGuideAnchorTime(anchorTime)+ }+ }+ prefs["promotedLiveGroupIds"]?.takeUnless { skipProviderScopedReferences }?.let { token ->preferencesRepository.setPromotedLiveGroupIds(token.split(",").mapNotNull { it.toLongOrNull() }.toSet())}// D13 — restore hidden channels per provider- prefs.entries+ prefs.entries.takeUnless { skipProviderScopedReferences }.orEmpty().filter { it.key.startsWith("hiddenChannels_") }.forEach { (key, value) ->val providerId = key.removePrefix("hiddenChannels_").toLongOrNull() ?: return@forEach@@ -677,7 +1506,7 @@ class BackupManagerImpl @Inject constructor(preferencesRepository.setHiddenChannelIds(providerId, ids)}// D13 — restore hidden categories per provider per content type- prefs.entries+ prefs.entries.takeUnless { skipProviderScopedReferences }.orEmpty().filter { it.key.startsWith("hiddenCategories_") }.forEach { (key, value) ->val rest = key.removePrefix("hiddenCategories_").split("_")@@ -692,7 +1521,8 @@ class BackupManagerImpl @Inject constructor(private suspend fun restoreRoomBackedSections(backupData: BackupData,plan: BackupImportPlan,- initialStoredProviders: List<ProviderEntity>+ initialStoredProviders: List<ProviderEntity>,+ onRoomCommitted: suspend () -> Unit = {}): RoomRestoreResult {if (!plan.importProviders && !plan.importSavedLibrary && !plan.importPlaybackHistory) {return RoomRestoreResult(@@ -767,6 +1597,7 @@ class BackupManagerImpl @Inject constructor(} else {skippedSections += "Playback History"}+ onRoomCommitted()}return RoomRestoreResult(@@ -925,12 +1756,35 @@ class BackupManagerImpl @Inject constructor(val skippedSections: List<String>)- private data class RecordingConflictKey(- val providerId: Long,- val startMs: Long,- val channelId: Long,- val streamUrl: String- )+private data class RecordingChannelConflictKey(+ val providerId: Long,+ val startMs: Long,+ val channelId: Long+)++private data class RecordingUrlConflictKey(+ val providerId: Long,+ val startMs: Long,+ val streamUrl: String+)++internal fun countScheduledRecordingConflicts(+ incoming: List<ScheduledRecordingBackup>,+ providersByIdentity: Map<Triple<String, String, String>, ProviderEntity>,+ existing: List<com.streamvault.domain.model.RecordingItem>+): Int {+ val channelKeys = existing.mapTo(hashSetOf()) {+ RecordingChannelConflictKey(it.providerId, it.scheduledStartMs, it.channelId)+ }+ val urlKeys = existing.mapTo(hashSetOf()) {+ RecordingUrlConflictKey(it.providerId, it.scheduledStartMs, it.streamUrl)+ }+ return incoming.count { recording ->+ val provider = providersByIdentity[recording.backupIdentity()] ?: return@count false+ RecordingChannelConflictKey(provider.id, recording.scheduledStartMs, recording.channelId) in channelKeys ||+ RecordingUrlConflictKey(provider.id, recording.scheduledStartMs, recording.streamUrl) in urlKeys+ }+}private class BoundedInputStream(input: java.io.InputStream, private val maxBytes: Long) : FilterInputStream(input) {private var bytesRead = 0L@@ -942,12 +1796,92 @@ class BackupManagerImpl @Inject constructor(private fun consume(count: Long) {bytesRead += count- if (bytesRead > maxBytes) throw IOException("Backup exceeds the ${maxBytes / (1024 * 1024)} MiB import limit")+ if (bytesRead > maxBytes) {+ throw BackupAdmissionException(+ BackupAdmissionReason.BYTE_LIMIT,+ "Backup exceeds the ${maxBytes / (1024 * 1024)} MiB import limit"+ )+ }+ }+ }++ /**+ * Rejects hostile JSON structure while characters are still being consumed by Gson.+ * This keeps deeply nested or overlong values from becoming a large object graph first.+ */+ private class AdmissionCheckingReader(+ reader: java.io.Reader,+ private val maxDepth: Int,+ private val maxStringChars: Int+ ) : FilterReader(reader) {+ private var depth = 0+ private var inString = false+ private var escaped = false+ private var stringChars = 0++ override fun read(): Int = super.read().also { value ->+ if (value >= 0) inspect(value.toChar())+ }++ override fun read(buffer: CharArray, offset: Int, length: Int): Int =+ super.read(buffer, offset, length).also { count ->+ if (count > 0) {+ for (index in offset until offset + count) inspect(buffer[index])+ }+ }++ private fun inspect(char: Char) {+ if (inString) {+ when {+ escaped -> {+ escaped = false+ countStringChar()+ }+ char == '\\' -> {+ escaped = true+ countStringChar()+ }+ char == '"' -> {+ inString = false+ stringChars = 0+ }+ else -> countStringChar()+ }+ return+ }++ when (char) {+ '"' -> {+ inString = true+ stringChars = 0+ }+ '{', '[' -> {+ depth += 1+ if (depth > maxDepth) {+ throw BackupAdmissionException(+ BackupAdmissionReason.DEPTH_LIMIT,+ "Backup JSON exceeds nesting limit $maxDepth"+ )+ }+ }+ '}', ']' -> depth -= 1+ }+ }++ private fun countStringChar() {+ stringChars += 1+ if (stringChars > maxStringChars) {+ throw BackupAdmissionException(+ BackupAdmissionReason.FIELD_LIMIT,+ "Backup contains a string longer than $maxStringChars characters"+ )+ }}}private companion object {const val MAX_BACKUP_BYTES = 16L * 1024 * 1024+ const val MAX_JSON_DEPTH = 64const val MAX_PREFERENCES = 5_000const val MAX_PROVIDERS = 1_000const val MAX_SECTION_ITEMS = 100_000@@ -955,9 +1889,85 @@ class BackupManagerImpl @Inject constructor(}}+internal enum class BackupAdmissionReason {+ BYTE_LIMIT,+ DEPTH_LIMIT,+ FIELD_LIMIT,+ SECTION_LIMIT,+ DUPLICATE_FIELD,+ UNSUPPORTED_VERSION,+ MALFORMED+}++internal class BackupAdmissionException(+ val reason: BackupAdmissionReason,+ message: String+) : IOException(message)+private fun ProviderEntity.backupIdentity(): Triple<String, String, String> =Triple(serverUrl, username, stalkerMacAddress)+private fun ProviderEntity.toBackupProviderReference() = BackupProviderReference(+ serverUrl = serverUrl,+ username = username,+ stalkerMacAddress = stalkerMacAddress.takeIf { it.isNotBlank() }+)++private fun Iterable<ProviderEntity>.findUnambiguousPortableProvider(+ reference: BackupProviderReference+): ProviderEntity? {+ val normalizedMac = reference.stalkerMacAddress.normalizedIdentity()+ return filter { provider ->+ provider.serverUrl == reference.serverUrl &&+ provider.username == reference.username &&+ provider.stalkerMacAddress.normalizedIdentity() == normalizedMac+ }.singleOrNull()+}++private fun List<com.streamvault.domain.model.Category>.resolvePortableCategory(+ reference: PortableCategoryReference+): com.streamvault.domain.model.Category? {+ val candidates = filter { it.type == reference.type }+ val normalizedName = reference.name.normalizedIdentity()+ val exactMatches = candidates.filter {+ it.id == reference.remoteCategoryId &&+ it.name.normalizedIdentity() == normalizedName+ }+ exactMatches.singleOrNull()?.let { return it }+ return candidates.filter { it.name.normalizedIdentity() == normalizedName }.singleOrNull()+}++private fun List<com.streamvault.data.local.entity.ChannelEntity>.resolvePortableChannel(+ reference: PortableChannelReference+): com.streamvault.data.local.entity.ChannelEntity? {+ val normalizedName = reference.name.normalizedIdentity()+ val normalizedUrl = reference.streamUrl.trim()+ val exactMatches = filter {+ it.streamId == reference.streamId &&+ it.name.normalizedIdentity() == normalizedName &&+ it.streamUrl.trim() == normalizedUrl+ }+ exactMatches.singleOrNull()?.let { return it }+ return filter {+ it.name.normalizedIdentity() == normalizedName &&+ it.streamUrl.trim() == normalizedUrl+ }.singleOrNull()+}++private fun BackupProviderReference.unresolvedLabel(kind: String): String =+ "$kind ${serverUrl} (${username.ifBlank { "anonymous" }})"++private fun PortableCategoryReference.unresolvedLabel(kind: String): String =+ "$kind ${name} [${type.name}] at ${provider.serverUrl}"++private fun PortableVirtualGroupReference.unresolvedLabel(kind: String): String =+ "$kind ${name} [${contentType.name}] at ${provider.serverUrl}"++private fun PortableChannelReference.unresolvedLabel(kind: String): String =+ "$kind ${name} (stream $streamId) at ${provider.serverUrl}"++private fun String?.normalizedIdentity(): String = orEmpty().trim().lowercase()+private fun com.streamvault.domain.model.Provider.backupIdentity(): Triple<String, String, String> =Triple(serverUrl, username, stalkerMacAddress)@@ -1169,9 +2179,29 @@ private fun Iterable<ProviderEntity>.findMatchingProvider(}private const val SHA256_PREFIX = "sha256:"-private const val CURRENT_BACKUP_VERSION = 8+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_FAILED_BEFORE_COMMIT = "FAILED_BEFORE_COMMIT"+private const val RESTORE_SNAPSHOT_PRESET_1 = "__restore_snapshot_preset_1"+private const val RESTORE_SNAPSHOT_PRESET_2 = "__restore_snapshot_preset_2"+private const val RESTORE_SNAPSHOT_PRESET_3 = "__restore_snapshot_preset_3"+private const val CURRENT_BACKUP_VERSION = 9private const val FILE_URI_SCHEME = "file"+private val PORTABLE_VIRTUAL_CATEGORY_IDS = setOf(-998L, -999L)private val MAP_STRING_STRING_TYPE: Type = object : TypeToken<Map<String, String>>() {}.type+private val PROVIDER_TYPE: Type = com.streamvault.domain.model.Provider::class.java+private val FAVORITE_TYPE: Type = com.streamvault.domain.model.Favorite::class.java+private val VIRTUAL_GROUP_TYPE: Type = com.streamvault.domain.model.VirtualGroup::class.java+private val PLAYBACK_HISTORY_TYPE: Type = com.streamvault.domain.model.PlaybackHistory::class.java+private val PROTECTED_CATEGORY_TYPE: Type = ProtectedCategoryBackup::class.java+private val SCHEDULED_RECORDING_TYPE: Type = ScheduledRecordingBackup::class.java+private val BACKUP_PROVIDER_REFERENCE_TYPE: Type = BackupProviderReference::class.java+private val PORTABLE_CATEGORY_REFERENCE_TYPE: Type = PortableCategoryReference::class.java+private val PORTABLE_GROUP_REFERENCE_TYPE: Type = PortableVirtualGroupReference::class.java+private val PORTABLE_CHANNEL_REFERENCE_TYPE: Type = PortableChannelReference::class.java+private val LONG_TYPE: Type = java.lang.Long::class.java+private val STRING_TYPE: Type = String::class.javaprivate val PROVIDER_LIST_TYPE: Type = object : TypeToken<List<com.streamvault.domain.model.Provider>>() {}.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>>() {}.typediff --git a/data/src/main/java/com/streamvault/data/manager/DownloadManagerImpl.kt b/data/src/main/java/com/streamvault/data/manager/DownloadManagerImpl.ktindex f2e15153..59e7d45c 100644--- a/data/src/main/java/com/streamvault/data/manager/DownloadManagerImpl.kt+++ b/data/src/main/java/com/streamvault/data/manager/DownloadManagerImpl.kt@@ -35,10 +35,12 @@ import java.net.ProtocolExceptionimport java.net.SocketExceptionimport java.net.SocketTimeoutExceptionimport java.util.concurrent.ConcurrentHashMap+import java.util.UUIDimport javax.inject.Injectimport javax.inject.Singletonimport kotlin.coroutines.coroutineContextimport kotlinx.coroutines.CancellationException+import kotlinx.coroutines.CoroutineStartimport kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.Job@@ -70,7 +72,10 @@ class DownloadManagerImpl @Inject constructor(private val activeCalls = ConcurrentHashMap<String, okhttp3.Call>()private val playbackPausedIds = ConcurrentHashMap.newKeySet<String>()private val schedulerMutex = Mutex()+ private val recoveryMutex = Mutex()private val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager+ private val ownerId = UUID.randomUUID().toString()+ @Volatile private var recoveryComplete = false@Volatile private var playbackActive = falseinit {@@ -139,7 +144,9 @@ class DownloadManagerImpl @Inject constructor(totalBytes = null,supportsResume = false,retryCount = 0,- failureReason = null+ failureReason = null,+ ownerId = null,+ heartbeatAt = null))}@@ -156,7 +163,13 @@ class DownloadManagerImpl @Inject constructor(activeCalls.remove(id)?.cancel()activeJobs.remove(id)?.cancelAndJoin()downloadDao.getByIdOnce(id)?.let { entity ->- downloadDao.update(entity.copy(status = DownloadStatus.CANCELLED))+ downloadDao.update(+ entity.copy(+ status = DownloadStatus.CANCELLED,+ ownerId = null,+ heartbeatAt = null+ )+ )}}.fold(onSuccess = { Result.success(Unit) },@@ -207,6 +220,7 @@ class DownloadManagerImpl @Inject constructor(}private suspend fun scheduleExisting(id: String, keepPaused: Boolean = false) {+ ensureInterruptedDownloadsRecovered()schedulerMutex.withLock {if (activeJobs.containsKey(id)) returnval entity = downloadDao.getByIdOnce(id) ?: return@@ -221,13 +235,20 @@ class DownloadManagerImpl @Inject constructor(}}- private fun startDownloadJob(entity: DownloadEntity) {- activeJobs[entity.id] = applicationScope.launch(Dispatchers.IO) {- captureDownload(entity)+ private suspend fun startDownloadJob(entity: DownloadEntity) {+ if (downloadDao.claimForDownload(entity.id, ownerId, System.currentTimeMillis()) != 1) return+ val claimed = downloadDao.getByIdOnce(entity.id)+ ?.takeIf { it.ownerId == ownerId && it.status == DownloadStatus.DOWNLOADING }+ ?: return+ val job = applicationScope.launch(start = CoroutineStart.LAZY) {+ captureDownload(claimed)}+ activeJobs[entity.id] = job+ job.start()}private suspend fun startNextQueued() {+ ensureInterruptedDownloadsRecovered()schedulerMutex.withLock {if (playbackActive || activeJobs.isNotEmpty()) returnval next = downloadDao.getQueuedOnce()@@ -242,14 +263,7 @@ class DownloadManagerImpl @Inject constructor(}override suspend fun recoverInterruptedDownloads(): Result<Int> = runSuspendCatching {- val recovered = schedulerMutex.withLock {- // This method runs only at process startup, before this manager owns any job.- // Reconnect callbacks deliberately do not call it, so live work is never reclaimed.- check(activeJobs.isEmpty()) { "Cannot recover downloads while this process owns active jobs" }- downloadDao.recoverOrphanedDownloading(- "Interrupted after app process stopped; queued to resume"- )- }+ val recovered = ensureInterruptedDownloadsRecovered()startNextQueued()recovered}.fold(@@ -257,10 +271,68 @@ class DownloadManagerImpl @Inject constructor(onFailure = { Result.error("Failed to recover interrupted downloads", it) })- /**- * A process death destroys active jobs and HTTP calls. Persisted DOWNLOADING rows therefore- * have no owner on the next manager instance and must be made schedulable again.- */+ private suspend fun ensureInterruptedDownloadsRecovered(): Int = recoveryMutex.withLock {+ if (recoveryComplete) return@withLock 0+ check(activeJobs.isEmpty()) { "Cannot recover downloads while this process owns active jobs" }+ val interrupted = downloadDao.getOrphanedDownloading(ownerId)+ interrupted.forEach { entity ->+ val targetLength = outputLength(entity)+ when (+ planInterruptedDownload(+ bytesWritten = entity.bytesWritten,+ totalBytes = entity.totalBytes,+ supportsResume = entity.supportsResume,+ targetLength = targetLength+ )+ ) {+ InterruptedDownloadPlan.COMPLETE -> {+ val completedBytes = requireNotNull(targetLength)+ downloadDao.update(+ entity.copy(+ status = DownloadStatus.COMPLETED,+ bytesWritten = completedBytes,+ totalBytes = entity.totalBytes ?: completedBytes,+ retryCount = 0,+ completedAt = System.currentTimeMillis(),+ failureReason = null,+ ownerId = null,+ heartbeatAt = null+ )+ )+ }+ InterruptedDownloadPlan.RESUME -> {+ downloadDao.update(+ entity.copy(+ status = DownloadStatus.PENDING,+ completedAt = null,+ failureReason = INTERRUPTED_RESUME_REASON,+ ownerId = null,+ heartbeatAt = null+ )+ )+ }+ InterruptedDownloadPlan.RESTART -> {+ deleteOutput(entity)+ downloadDao.update(+ entity.copy(+ outputUri = null,+ outputDisplayPath = null,+ status = DownloadStatus.PENDING,+ bytesWritten = 0L,+ totalBytes = null,+ supportsResume = false,+ completedAt = null,+ failureReason = INTERRUPTED_RESTART_REASON,+ ownerId = null,+ heartbeatAt = null+ )+ )+ }+ }+ }+ recoveryComplete = true+ interrupted.size+ }private suspend fun pauseActiveDownloadsForPlayback() {activeJobs.entries.toList().forEach { (id, job) ->@@ -286,47 +358,79 @@ class DownloadManagerImpl @Inject constructor()private suspend fun captureDownload(initial: DownloadEntity) {- var current = downloadDao.getByIdOnce(initial.id) ?: initial- current = current.copy(status = DownloadStatus.DOWNLOADING, failureReason = null)- downloadDao.update(current)+ var current = downloadDao.getByIdOnce(initial.id)+ ?.takeIf { it.ownerId == ownerId && it.ownerEpoch == initial.ownerEpoch }+ ?: returntry {val resumeFrom = current.bytesWritten.takeIf {- current.supportsResume && it > 0L && hasAppendTarget(current)+ current.supportsResume && it > 0L && outputLength(current) == it} ?: 0L+ if (current.bytesWritten > 0L && resumeFrom == 0L) {+ deleteOutput(current)+ current = current.copy(+ outputUri = null,+ outputDisplayPath = null,+ bytesWritten = 0L,+ totalBytes = null,+ supportsResume = false,+ heartbeatAt = System.currentTimeMillis()+ )+ downloadDao.update(current)+ }val resolvedStream = resolveFreshDownloadStream(current)val requestUrl = resolvedStream?.url?.takeIf { it.isNotBlank() } ?: current.streamUrlif (requestUrl != current.streamUrl) {current = current.copy(streamUrl = requestUrl)downloadDao.update(current)}- val requestBuilder = Request.Builder().url(requestUrl).get()- resolvedStream?.headers.orEmpty().forEach { (name, value) ->- requestBuilder.header(name, value)- }- resolvedStream?.userAgent?.takeIf { it.isNotBlank() }?.let { userAgent ->- requestBuilder.header("User-Agent", userAgent)- }- if (resumeFrom > 0L) requestBuilder.header("Range", "bytes=$resumeFrom-")- val call = okHttpClient.newCall(requestBuilder.build())+ val request = buildDownloadHttpRequest(+ url = requestUrl,+ headers = resolvedStream?.headers.orEmpty(),+ userAgent = resolvedStream?.userAgent,+ resumeFrom = resumeFrom+ )+ val call = okHttpClient.newCall(request)activeCalls[initial.id] = callcall.useCancellableResponse { response ->- if (!response.isSuccessful) throw HttpDownloadException(response.code)val body = response.body ?: error("Empty response body")- val rangeAccepted = resumeFrom > 0L && response.code == HttpURLConnection.HTTP_PARTIAL- val restartFromZero = resumeFrom > 0L && response.code == HttpURLConnection.HTTP_OK- if (restartFromZero) {+ val resumeDecision = resolveResumeResponse(+ resumeFrom = resumeFrom,+ responseCode = response.code,+ contentLength = body.contentLength().takeIf { it >= 0L },+ acceptRanges = response.header("Accept-Ranges"),+ contentRange = response.header("Content-Range")+ )+ if (resumeDecision == DownloadResumeResponse.RESTART) {+ throw RestartFromZeroException()+ }+ if (resumeDecision == DownloadResumeResponse.COMPLETE) {+ downloadDao.update(+ current.copy(+ status = DownloadStatus.COMPLETED,+ bytesWritten = resumeFrom,+ totalBytes = resumeFrom,+ retryCount = 0,+ completedAt = System.currentTimeMillis(),+ failureReason = null,+ ownerId = null,+ heartbeatAt = null+ )+ )+ return@useCancellableResponse+ }+ if (resumeDecision == DownloadResumeResponse.FAIL) {+ throw ProtocolException("Invalid partial download response")+ }+ if (!response.isSuccessful) throw HttpDownloadException(response.code)+ val transfer = resumeDecision as DownloadResumeResponse.TRANSFER+ if (!transfer.append && resumeFrom > 0L) {deleteOutput(current)current = current.copy(bytesWritten = 0L, outputUri = null, outputDisplayPath = null, supportsResume = false)}- val append = rangeAccepted- val contentLength = body.contentLength().takeIf { it > 0L }- val totalBytes = when {- append && contentLength != null -> resumeFrom + contentLength- else -> contentLength- }- val supportsResume = response.header("Accept-Ranges")- ?.contains("bytes", ignoreCase = true) == true || rangeAccepted+ val append = transfer.append+ val totalBytes = transfer.totalBytes+ val supportsResume = transfer.supportsResumeval target = runSuspendCatching { createOutputTarget(current, response.header("Content-Type"), append) }.getOrElse { error ->if (!append) throw error@@ -340,7 +444,8 @@ class DownloadManagerImpl @Inject constructor(bytesWritten = bytesWritten,totalBytes = totalBytes,supportsResume = supportsResume,- status = DownloadStatus.DOWNLOADING+ status = DownloadStatus.DOWNLOADING,+ heartbeatAt = System.currentTimeMillis())downloadDao.update(current)@@ -362,7 +467,8 @@ class DownloadManagerImpl @Inject constructor(bytesWritten = bytesWritten,totalBytes = totalBytes,supportsResume = supportsResume,- status = DownloadStatus.DOWNLOADING+ status = DownloadStatus.DOWNLOADING,+ heartbeatAt = System.currentTimeMillis())downloadDao.update(current)lastProgressUpdate = bytesWritten@@ -381,7 +487,9 @@ class DownloadManagerImpl @Inject constructor(supportsResume = supportsResume,retryCount = 0,completedAt = System.currentTimeMillis(),- failureReason = null+ failureReason = null,+ ownerId = null,+ heartbeatAt = null))}@@ -392,7 +500,13 @@ class DownloadManagerImpl @Inject constructor(} else if (cancelled is ForegroundServiceTimeoutCancellation) {pauseForForegroundServiceTimeout(current)} else {- downloadDao.update(entity.copy(status = DownloadStatus.CANCELLED))+ downloadDao.update(+ entity.copy(+ status = DownloadStatus.CANCELLED,+ ownerId = null,+ heartbeatAt = null+ )+ )}}throw cancelled@@ -457,7 +571,9 @@ class DownloadManagerImpl @Inject constructor(supportsResume = false,retryCount = retryCount,completedAt = null,- failureReason = reason+ failureReason = reason,+ ownerId = null,+ heartbeatAt = null))}@@ -467,14 +583,25 @@ class DownloadManagerImpl @Inject constructor(entity.copy(status = DownloadStatus.PAUSED,completedAt = null,- failureReason = FOREGROUND_SERVICE_TIMEOUT_REASON+ failureReason = FOREGROUND_SERVICE_TIMEOUT_REASON,+ ownerId = null,+ heartbeatAt = null))}- private fun hasAppendTarget(entity: DownloadEntity): Boolean {- val path = entity.outputDisplayPath- return !entity.outputUri.isNullOrBlank() || (!path.isNullOrBlank() && File(path).exists())+ private fun outputLength(entity: DownloadEntity): Long? {+ entity.outputDisplayPath+ ?.takeIf { it.isNotBlank() }+ ?.let(::File)+ ?.takeIf { it.isAbsolute && it.exists() }+ ?.let { return it.length() }+ val outputUri = entity.outputUri?.takeIf { it.isNotBlank() } ?: return null+ return runCatching {+ DocumentFile.fromSingleUri(context, Uri.parse(outputUri))+ ?.takeIf { it.exists() && it.canWrite() }+ ?.length()+ }.getOrNull()}private fun isTransient(error: Throwable): Boolean {@@ -646,16 +773,151 @@ class DownloadManagerImpl @Inject constructor(const val DEFAULT_BUFFER_SIZE = 64 * 1024const val PROGRESS_UPDATE_BYTES = 512 * 1024const val MAX_RETRIES = 5+ const val INTERRUPTED_RESUME_REASON =+ "Interrupted after app process stopped; validated output queued to resume."+ const val INTERRUPTED_RESTART_REASON =+ "Interrupted output could not be validated; queued to restart safely."const val FOREGROUND_SERVICE_TIMEOUT_REASON ="Download paused because Android exhausted the foreground-service time allowance."}private class HttpDownloadException(val code: Int) : Exception("HTTP $code")- private class RestartFromZeroException(cause: Throwable) : Exception(cause)+ private class RestartFromZeroException(cause: Throwable? = null) : Exception(cause)private class PlaybackStartedCancellation : CancellationException("Playback started")private class ForegroundServiceTimeoutCancellation :CancellationException("Android exhausted the foreground-service time allowance")}++internal enum class InterruptedDownloadPlan {+ COMPLETE,+ RESUME,+ RESTART+}++internal fun planInterruptedDownload(+ bytesWritten: Long,+ totalBytes: Long?,+ supportsResume: Boolean,+ targetLength: Long?+): InterruptedDownloadPlan {+ if (targetLength != null && totalBytes != null && totalBytes > 0L && targetLength == totalBytes) {+ return InterruptedDownloadPlan.COMPLETE+ }+ if (supportsResume && bytesWritten > 0L && targetLength == bytesWritten) {+ return InterruptedDownloadPlan.RESUME+ }+ return InterruptedDownloadPlan.RESTART+}++internal sealed interface DownloadResumeResponse {+ data class TRANSFER(+ val append: Boolean,+ val totalBytes: Long?,+ val supportsResume: Boolean+ ) : DownloadResumeResponse++ data object COMPLETE : DownloadResumeResponse+ data object RESTART : DownloadResumeResponse+ data object FAIL : DownloadResumeResponse+}++internal fun resolveResumeResponse(+ resumeFrom: Long,+ responseCode: Int,+ contentLength: Long?,+ acceptRanges: String?,+ contentRange: String?+): DownloadResumeResponse {+ val parsedRange = parseContentRange(contentRange)+ if (resumeFrom > 0L) {+ if (responseCode == 416) {+ return if (parsedRange?.total == resumeFrom) {+ DownloadResumeResponse.COMPLETE+ } else {+ DownloadResumeResponse.RESTART+ }+ }+ if (responseCode == HttpURLConnection.HTTP_PARTIAL) {+ if (parsedRange?.start != resumeFrom) return DownloadResumeResponse.RESTART+ return DownloadResumeResponse.TRANSFER(+ append = true,+ totalBytes = parsedRange.total+ ?: contentLength?.takeIf { it >= 0L }?.let { resumeFrom + it },+ supportsResume = true+ )+ }+ if (responseCode == HttpURLConnection.HTTP_OK) {+ return DownloadResumeResponse.TRANSFER(+ append = false,+ totalBytes = contentLength?.takeIf { it >= 0L },+ supportsResume = acceptRanges.hasByteRangeSupport()+ )+ }+ return if (responseCode in 200..299) {+ DownloadResumeResponse.RESTART+ } else {+ DownloadResumeResponse.TRANSFER(+ append = false,+ totalBytes = contentLength?.takeIf { it >= 0L },+ supportsResume = false+ )+ }+ }++ if (responseCode == HttpURLConnection.HTTP_PARTIAL && parsedRange?.start != 0L) {+ return DownloadResumeResponse.FAIL+ }+ return DownloadResumeResponse.TRANSFER(+ append = false,+ totalBytes = parsedRange?.total ?: contentLength?.takeIf { it >= 0L },+ supportsResume = acceptRanges.hasByteRangeSupport() ||+ responseCode == HttpURLConnection.HTTP_PARTIAL+ )+}++internal fun buildDownloadHttpRequest(+ url: String,+ headers: Map<String, String>,+ userAgent: String?,+ resumeFrom: Long+): Request = Request.Builder()+ .url(url)+ .get()+ .apply {+ headers.forEach { (name, value) -> header(name, value) }+ userAgent?.takeIf { it.isNotBlank() }?.let { header("User-Agent", it) }+ if (resumeFrom > 0L) header("Range", "bytes=$resumeFrom-")+ }+ .build()++private data class ParsedContentRange(+ val start: Long?,+ val total: Long?+)++private fun parseContentRange(header: String?): ParsedContentRange? {+ val value = header?.trim() ?: return null+ Regex("""bytes\s+(\d+)-\d+/(\d+|\*)""", RegexOption.IGNORE_CASE)+ .matchEntire(value)+ ?.let { match ->+ return ParsedContentRange(+ start = match.groupValues[1].toLongOrNull(),+ total = match.groupValues[2].takeUnless { it == "*" }?.toLongOrNull()+ )+ }+ Regex("""bytes\s+\*/(\d+)""", RegexOption.IGNORE_CASE)+ .matchEntire(value)+ ?.let { match ->+ return ParsedContentRange(+ start = null,+ total = match.groupValues[1].toLongOrNull()+ )+ }+ return null+}++private fun String?.hasByteRangeSupport(): Boolean =+ this?.contains("bytes", ignoreCase = true) == truediff --git a/data/src/main/java/com/streamvault/data/manager/ProgramReminderManagerImpl.kt b/data/src/main/java/com/streamvault/data/manager/ProgramReminderManagerImpl.ktindex 25fcbe65..45c47d93 100644--- a/data/src/main/java/com/streamvault/data/manager/ProgramReminderManagerImpl.kt+++ b/data/src/main/java/com/streamvault/data/manager/ProgramReminderManagerImpl.kt@@ -4,17 +4,24 @@ import com.streamvault.data.local.dao.ProgramReminderDaoimport com.streamvault.data.local.entity.ProgramReminderEntityimport com.streamvault.data.manager.reminder.ProgramReminderAlarmSchedulerimport com.streamvault.data.manager.reminder.ProgramReminderNotifier+import com.streamvault.data.manager.reminder.ReminderNotificationResultimport com.streamvault.domain.manager.ProgramReminderManagerimport com.streamvault.domain.model.Programimport com.streamvault.domain.model.ProgramReminder+import com.streamvault.domain.model.ProgramReminderDeliveryStateimport com.streamvault.domain.model.Result+import java.util.UUIDimport kotlinx.coroutines.delay+import kotlinx.coroutines.CancellationExceptionimport kotlinx.coroutines.flow.Flowimport kotlinx.coroutines.flow.combineimport kotlinx.coroutines.flow.flowimport javax.inject.Injectimport javax.inject.Singletonimport kotlinx.coroutines.flow.map+import kotlinx.coroutines.flow.distinctUntilChanged+import kotlinx.coroutines.sync.Mutex+import kotlinx.coroutines.sync.withLockprivate const val UPCOMING_REMINDER_REFRESH_MS = 15_000L@@ -26,6 +33,7 @@ class ProgramReminderManagerImpl private constructor(private val nowProvider: () -> Long,private val upcomingTimeFlow: Flow<Long>) : ProgramReminderManager {+ private val mutationMutex = Mutex()@Injectconstructor(@@ -42,6 +50,8 @@ class ProgramReminderManagerImpl private constructor(internal companion object {const val REMINDER_STALE_GRACE_MS = 2 * 60_000L+ const val STALE_REMINDER_REASON =+ "The program started before its reminder could be delivered."fun forTesting(programReminderDao: ProgramReminderDao,@@ -63,10 +73,23 @@ class ProgramReminderManagerImpl private constructor(.combine(upcomingTimeFlow) { reminders, now ->reminders.asSequence()- .filter { !it.isDismissed && it.programStartTime >= now }+ .filter {+ !it.isDismissed &&+ (+ it.programStartTime >= now ||+ (+ it.deliveryState in setOf(+ ProgramReminderDeliveryState.BLOCKED,+ ProgramReminderDeliveryState.FAILED+ ) &&+ it.programStartTime >= now - REMINDER_STALE_GRACE_MS+ )+ )+ }.map { it.asDomain() }.toList()}+ .distinctUntilChanged()override suspend fun isReminderScheduled(providerId: Long,@@ -84,16 +107,16 @@ class ProgramReminderManagerImpl private constructor(channelName: String,program: Program,leadTimeMinutes: Int- ): Result<Unit> {- if (providerId <= 0L) return Result.error("Program reminders need a synced provider.")- if (program.startTime <= System.currentTimeMillis()) {- return Result.error("This program has already started.")+ ): Result<Unit> = mutationMutex.withLock {+ if (providerId <= 0L) return@withLock Result.error("Program reminders need a synced provider.")+ if (program.startTime <= nowProvider()) {+ return@withLock Result.error("This program has already started.")}if (!alarmScheduler.canScheduleExactAlarms()) {- return Result.error(ProgramReminderAlarmScheduler.EXACT_ALARM_PERMISSION_MESSAGE)+ return@withLock Result.error(ProgramReminderAlarmScheduler.EXACT_ALARM_PERMISSION_MESSAGE)}- val now = System.currentTimeMillis()+ val now = nowProvider()val remindAt = (program.startTime - leadTimeMinutes * 60_000L).coerceAtLeast(now + 1_000L)val existing = programReminderDao.getByProgram(providerId, channelId, program.title, program.startTime)val reminder = ProgramReminderEntity(@@ -107,25 +130,74 @@ class ProgramReminderManagerImpl private constructor(leadTimeMinutes = leadTimeMinutes,isDismissed = false,notifiedAt = null,+ exactAlarmArmed = existing != null,createdAt = existing?.createdAt ?: now)- val reminderId = existing?.id ?: programReminderDao.insert(reminder)- return when (val result = alarmScheduler.schedule(reminderId, remindAt)) {+ val reminderId = existing?.id ?: try {+ programReminderDao.insert(reminder)+ } catch (cancelled: CancellationException) {+ throw cancelled+ } catch (error: Exception) {+ return@withLock Result.error("Could not save program reminder: ${error.message}", error)+ }+ return@withLock when (val result = alarmScheduler.schedule(reminderId, remindAt)) {is Result.Success -> {- if (existing != null) {- programReminderDao.update(reminder)+ if (existing == null) {+ try {+ programReminderDao.setExactAlarmArmed(reminderId, true)+ Result.success(Unit)+ } catch (cancelled: CancellationException) {+ throw cancelled+ } catch (error: Exception) {+ Result.error(+ "Reminder alarm is scheduled, but its armed state could not be saved; startup reconciliation will repair it.",+ error+ )+ }+ } else {+ commitReminderReplacement(existing, reminder)}- Result.success(Unit)}is Result.Error -> {if (existing == null) {- programReminderDao.deleteById(reminderId)+ try {+ programReminderDao.deleteById(reminderId)+ } catch (cancelled: CancellationException) {+ throw cancelled+ } catch (deleteError: Exception) {+ return@withLock Result.error(+ "${result.message}; the unarmed reminder row could not be removed and will be reconciled on startup.",+ deleteError+ )+ }+ Result.error(result.message, result.exception)+ } else {+ restorePriorReminder(+ existing = existing,+ primaryMessage = result.message,+ primaryError = result.exception+ )+ }+ }+ Result.Loading -> {+ if (existing == null) {+ try {+ programReminderDao.deleteById(reminderId)+ } catch (cancelled: CancellationException) {+ throw cancelled+ } catch (_: Exception) {+ // The inserted row is explicitly unarmed and startup reconciliation+ // can safely retry or remove it.+ }+ Result.error("Unexpected reminder scheduling state")} else {- alarmScheduler.schedule(existing.id, existing.remindAt)+ restorePriorReminder(+ existing = existing,+ primaryMessage = "Unexpected reminder scheduling state",+ primaryError = null+ )}- Result.error(result.message, result.exception)}- Result.Loading -> Result.error("Unexpected reminder scheduling state")}}@@ -134,43 +206,219 @@ class ProgramReminderManagerImpl private constructor(channelId: String,programTitle: String,programStartTime: Long- ): Result<Unit> {+ ): Result<Unit> = mutationMutex.withLock {val existing = programReminderDao.getByProgram(providerId, channelId, programTitle, programStartTime)- ?: return Result.success(Unit)- programReminderDao.deleteById(existing.id)- alarmScheduler.cancel(existing.id)- return Result.success(Unit)+ ?: return@withLock Result.success(Unit)+ try {+ alarmScheduler.cancel(existing.id)+ } catch (cancelled: CancellationException) {+ throw cancelled+ } catch (error: Exception) {+ return@withLock Result.error("Could not cancel reminder alarm; the reminder was kept.", error)+ }+ return@withLock try {+ programReminderDao.deleteById(existing.id)+ Result.success(Unit)+ } catch (cancelled: CancellationException) {+ throw cancelled+ } catch (deleteError: Exception) {+ val persistedRead = try {+ programReminderDao.getById(existing.id)+ } catch (cancelled: CancellationException) {+ throw cancelled+ } catch (_: Exception) {+ setExactAlarmArmedBestEffort(existing.id, false)+ return@withLock Result.error(+ "Reminder cancellation could not be verified; startup repair is pending.",+ deleteError+ )+ }+ if (persistedRead == null) {+ Result.success(Unit)+ } else {+ restorePriorReminder(+ existing = persistedRead,+ primaryMessage = "Could not remove reminder after cancelling its alarm",+ primaryError = deleteError+ )+ }+ }}- override suspend fun restoreScheduledReminders() {- val now = System.currentTimeMillis()- if (!alarmScheduler.canScheduleExactAlarms()) {- programReminderDao.getPendingActive(now).forEach { reminder ->- programReminderDao.setExactAlarmArmed(reminder.id, false)+ override suspend fun restoreScheduledReminders() = mutationMutex.withLock {+ val now = nowProvider()+ val reminders = programReminderDao.getPendingActive(now - REMINDER_STALE_GRACE_MS)+ val canScheduleExactAlarms = alarmScheduler.canScheduleExactAlarms()+ reminders.forEach { reminder ->+ val deliveryIsDue = reminder.remindAt <= now ||+ reminder.deliveryState != ProgramReminderDeliveryState.PENDING+ if (deliveryIsDue) {+ deliverReminderLocked(reminder.id)+ } else if (!canScheduleExactAlarms) {+ setExactAlarmArmedBestEffort(reminder.id, false)+ } else {+ when (val result = alarmScheduler.schedule(reminder.id, reminder.remindAt.coerceAtLeast(now + 1_000L))) {+ is Result.Error -> {+ setExactAlarmArmedBestEffort(reminder.id, false)+ android.util.Log.w("ProgramReminderManager", "Unable to restore reminder ${reminder.id}: ${result.message}")+ }+ is Result.Success -> setExactAlarmArmedBestEffort(reminder.id, true)+ Result.Loading -> setExactAlarmArmedBestEffort(reminder.id, false)+ }}- return}- programReminderDao.getPendingActive(now).forEach { reminder ->- when (val result = alarmScheduler.schedule(reminder.id, reminder.remindAt.coerceAtLeast(now + 1_000L))) {- is Result.Error -> {- programReminderDao.setExactAlarmArmed(reminder.id, false)- android.util.Log.w("ProgramReminderManager", "Unable to restore reminder ${reminder.id}: ${result.message}")+ }++ private suspend fun commitReminderReplacement(+ existing: ProgramReminderEntity,+ replacement: ProgramReminderEntity+ ): Result<Unit> = try {+ programReminderDao.update(replacement.copy(exactAlarmArmed = true))+ Result.success(Unit)+ } catch (cancelled: CancellationException) {+ throw cancelled+ } catch (updateError: Exception) {+ val persisted = try {+ programReminderDao.getById(existing.id)+ } catch (cancelled: CancellationException) {+ throw cancelled+ } catch (_: Exception) {+ null+ }+ if (persisted == replacement.copy(exactAlarmArmed = true)) {+ Result.success(Unit)+ } else {+ restorePriorReminder(+ existing = existing,+ primaryMessage = "Replacement alarm was scheduled but the reminder update was not committed",+ primaryError = updateError+ )+ }+ }++ private suspend fun restorePriorReminder(+ existing: ProgramReminderEntity,+ primaryMessage: String,+ primaryError: Throwable?+ ): Result<Unit> {+ return when (val rollback = alarmScheduler.schedule(existing.id, existing.remindAt)) {+ is Result.Success -> {+ try {+ programReminderDao.setExactAlarmArmed(existing.id, true)+ } catch (cancelled: CancellationException) {+ throw cancelled+ } catch (stateError: Exception) {+ return Result.error(+ "$primaryMessage; the prior alarm was restored but its armed state could not be saved.",+ stateError+ )+ }+ Result.error("$primaryMessage; the prior reminder was restored.", primaryError)+ }+ is Result.Error -> {+ try {+ programReminderDao.setExactAlarmArmed(existing.id, false)+ } catch (cancelled: CancellationException) {+ throw cancelled+ } catch (_: Exception) {+ // The persisted reminder still provides the source of truth for startup repair.}- else -> programReminderDao.setExactAlarmArmed(reminder.id, true)+ Result.error(+ "$primaryMessage; the prior alarm could not be restored and startup repair is pending: ${rollback.message}",+ rollback.exception ?: primaryError+ )+ }+ Result.Loading -> {+ setExactAlarmArmedBestEffort(existing.id, false)+ Result.error(+ "$primaryMessage; prior-alarm restoration did not complete and startup repair is pending.",+ primaryError+ )}}}- suspend fun deliverReminder(reminderId: Long) {- val reminder = programReminderDao.getById(reminderId) ?: return+ private suspend fun setExactAlarmArmedBestEffort(id: Long, armed: Boolean) {+ try {+ programReminderDao.setExactAlarmArmed(id, armed)+ } catch (cancelled: CancellationException) {+ throw cancelled+ } catch (_: Exception) {+ // The row remains the source of truth and the next startup/permission+ // reconciliation will retry this diagnostic state write.+ }+ }++ suspend fun deliverReminder(reminderId: Long) = mutationMutex.withLock {+ deliverReminderLocked(reminderId)+ }++ private suspend fun deliverReminderLocked(reminderId: Long) {+ var reminder = programReminderDao.getById(reminderId) ?: returnif (reminder.isDismissed || reminder.notifiedAt != null) return- val now = System.currentTimeMillis()+ val now = nowProvider()if (now - reminder.programStartTime > REMINDER_STALE_GRACE_MS) {- programReminderDao.update(reminder.copy(isDismissed = true))+ programReminderDao.update(+ reminder.copy(+ isDismissed = true,+ exactAlarmArmed = false,+ deliveryState = ProgramReminderDeliveryState.DISMISSED,+ deliveryAttemptToken = null,+ deliveryFailureReason = STALE_REMINDER_REASON+ )+ )return}- if (notifier.showReminder(reminder) is Result.Success) {- programReminderDao.update(reminder.copy(notifiedAt = now))++ if (reminder.deliveryState == ProgramReminderDeliveryState.DELIVERING) {+ val interruptedToken = reminder.deliveryAttemptToken+ if (interruptedToken != null && notifier.isReminderVisible(reminder.id)) {+ programReminderDao.markDelivered(reminder.id, interruptedToken, now)+ return+ }+ if (interruptedToken != null) {+ programReminderDao.resetInterruptedDelivery(reminder.id, interruptedToken)+ } else {+ programReminderDao.update(+ reminder.copy(+ deliveryState = ProgramReminderDeliveryState.PENDING,+ deliveryAttemptToken = null+ )+ )+ }+ reminder = programReminderDao.getById(reminderId) ?: return+ if (reminder.isDismissed || reminder.notifiedAt != null) return+ }++ val attemptToken = UUID.randomUUID().toString()+ if (programReminderDao.claimDelivery(reminder.id, attemptToken, now) != 1) return+ val result = try {+ notifier.showReminder(reminder)+ } catch (cancelled: CancellationException) {+ throw cancelled+ } catch (error: Exception) {+ ReminderNotificationResult.Failed("Unable to show program reminder.", error)+ }+ when (result) {+ ReminderNotificationResult.Accepted -> {+ programReminderDao.markDelivered(reminder.id, attemptToken, now)+ }+ is ReminderNotificationResult.Blocked -> {+ programReminderDao.markDeliveryIssue(+ reminder.id,+ attemptToken,+ ProgramReminderDeliveryState.BLOCKED,+ result.reason+ )+ }+ is ReminderNotificationResult.Failed -> {+ programReminderDao.markDeliveryIssue(+ reminder.id,+ attemptToken,+ ProgramReminderDeliveryState.FAILED,+ result.reason+ )+ }}}@@ -186,8 +434,13 @@ class ProgramReminderManagerImpl private constructor(isDismissed = isDismissed,notifiedAt = notifiedAt,exactAlarmArmed = exactAlarmArmed,+ deliveryState = deliveryState,+ deliveryAttemptedAt = deliveryAttemptedAt,+ deliveryAttemptCount = deliveryAttemptCount,+ deliveryFailureReason = deliveryFailureReason,createdAt = createdAt)+}private fun upcomingReminderTimeFlow(refreshMs: Long = UPCOMING_REMINDER_REFRESH_MS): Flow<Long> = flow {diff --git a/data/src/main/java/com/streamvault/data/manager/RecordingManagerImpl.kt b/data/src/main/java/com/streamvault/data/manager/RecordingManagerImpl.ktindex 3e0c257d..57310880 100644--- a/data/src/main/java/com/streamvault/data/manager/RecordingManagerImpl.kt+++ b/data/src/main/java/com/streamvault/data/manager/RecordingManagerImpl.kt@@ -1,6 +1,7 @@package com.streamvault.data.managerimport android.content.Context+import android.database.sqlite.SQLiteExceptionimport android.net.ConnectivityManagerimport android.net.NetworkCapabilitiesimport android.util.Log@@ -40,6 +41,9 @@ import com.streamvault.domain.manager.RecordingManagerimport com.streamvault.domain.model.RecordingFailureCategoryimport com.streamvault.domain.model.RecordingItemimport com.streamvault.domain.model.RecordingRecurrence+import com.streamvault.domain.model.RecordingReconciliationResult+import com.streamvault.domain.model.RecordingReconciliationRowFailure+import com.streamvault.domain.model.RecordingReconciliationSummaryimport com.streamvault.domain.model.RecordingRequestimport com.streamvault.domain.model.RecordingSourceTypeimport com.streamvault.domain.model.RecordingStatus@@ -49,6 +53,7 @@ import com.streamvault.domain.model.Resultimport dagger.hilt.android.qualifiers.ApplicationContextimport java.io.Fileimport java.io.FileInputStream+import java.io.IOExceptionimport java.time.Durationimport java.time.Instantimport java.time.ZoneId@@ -73,6 +78,16 @@ import kotlinx.coroutines.withContextprivate const val TAG = "RecordingManager"private const val MIN_FREE_SPACE_BYTES = 512L * 1024L * 1024L // 512 MB++internal fun isTransientRecordingReconciliationFailure(error: Throwable): Boolean = when (error) {+ is IOException -> true+ is SQLiteException -> {+ val message = error.message.orEmpty()+ message.contains("locked", ignoreCase = true) ||+ message.contains("busy", ignoreCase = true)+ }+ else -> false+}private const val FAILURE_NOTIFICATION_CHANNEL_ID = "streamvault_recording_failure"private const val FAILURE_NOTIFICATION_ID_BASE = 5000private const val FOREGROUND_SERVICE_TIMEOUT_REASON =@@ -493,35 +508,127 @@ class RecordingManagerImpl @Inject constructor()}- override suspend fun reconcileRecordingState(): Result<Unit> = withContext(Dispatchers.IO) {- runCatching<Unit> {+ override suspend fun reconcileRecordingState(): RecordingReconciliationResult =+ withContext(Dispatchers.IO) {+ val rowFailures = mutableListOf<RecordingReconciliationRowFailure>()+ var rowsInspected = 0+ var rowsRepaired = 0+ try {ensureStorageState()pruneExpiredRecordings()val scheduledRuns = recordingRunDao.getAlarmManagedScheduledRuns().filter { it.scheduleEnabled && it.status == RecordingStatus.SCHEDULED }- if (!alarmScheduler.canScheduleExactAlarms()) {- scheduledRuns.forEach { run -> recordingRunDao.setExactAlarmArmed(run.id, false) }- } else scheduledRuns.forEach { run ->- if (run.scheduledEndMs <= System.currentTimeMillis()) {- markRunFailed(run.id, "Recording window expired before capture started.", RecordingFailureCategory.UNKNOWN)- } else {- when (val result = alarmScheduler.scheduleStart(run.id, run.scheduledStartMs)) {- is Result.Error -> markRunFailed(run.id, result.message, RecordingFailureCategory.UNKNOWN)- else -> recordingRunDao.setExactAlarmArmed(run.id, true)+ val canScheduleExactAlarms = alarmScheduler.canScheduleExactAlarms()+ scheduledRuns.forEach { run ->+ rowsInspected+++ try {+ when {+ !canScheduleExactAlarms -> {+ recordingRunDao.setExactAlarmArmed(run.id, false)+ rowsRepaired+++ }+ run.scheduledEndMs <= System.currentTimeMillis() -> {+ quarantineReconciliationRow(+ run,+ "Recording window expired before capture started."+ )+ rowsRepaired+++ }+ else -> when (val result = alarmScheduler.scheduleStart(run.id, run.scheduledStartMs)) {+ is Result.Success -> {+ recordingRunDao.setExactAlarmArmed(run.id, true)+ rowsRepaired+++ }+ is Result.Error -> {+ result.exception+ ?.takeIf(::isTransientRecordingReconciliationFailure)+ ?.let { throw it }+ val reason = result.message.ifBlank {+ "Recording alarm could not be restored."+ }+ quarantineReconciliationRow(run, reason)+ rowFailures += RecordingReconciliationRowFailure(run.id, reason)+ rowsRepaired+++ }+ Result.Loading -> {+ val reason = "Recording alarm restore returned a non-terminal result."+ quarantineReconciliationRow(run, reason)+ rowFailures += RecordingReconciliationRowFailure(run.id, reason)+ rowsRepaired+++ }}}+ } catch (cancelled: CancellationException) {+ throw cancelled+ } catch (error: Throwable) {+ if (isTransientRecordingReconciliationFailure(error)) throw error+ val reason = error.message?.takeIf(String::isNotBlank)+ ?: "Recording row could not be reconciled."+ quarantineReconciliationRow(run, reason)+ rowFailures += RecordingReconciliationRowFailure(run.id, reason)+ rowsRepaired+++ }}recordingRunDao.getRecordingRuns().forEach { run ->- if (run.scheduledEndMs <= System.currentTimeMillis()) {- stopRecording(run.id)- } else if (!isActiveJob(run.id)) {- markInterruptedRun(run)+ rowsInspected+++ try {+ if (run.scheduledEndMs <= System.currentTimeMillis()) {+ when (val result = stopRecording(run.id)) {+ is Result.Success -> rowsRepaired+++ is Result.Error -> {+ result.exception+ ?.takeIf(::isTransientRecordingReconciliationFailure)+ ?.let { throw it }+ val reason = result.message.ifBlank {+ "Expired recording could not be stopped."+ }+ quarantineReconciliationRow(run, reason)+ rowFailures += RecordingReconciliationRowFailure(run.id, reason)+ rowsRepaired+++ }+ Result.Loading -> {+ val reason = "Recording stop returned a non-terminal result."+ quarantineReconciliationRow(run, reason)+ rowFailures += RecordingReconciliationRowFailure(run.id, reason)+ rowsRepaired+++ }+ }+ } else if (!isActiveJob(run.id)) {+ markInterruptedRun(run)+ rowsRepaired+++ }+ } catch (cancelled: CancellationException) {+ throw cancelled+ } catch (error: Throwable) {+ if (isTransientRecordingReconciliationFailure(error)) throw error+ val reason = error.message?.takeIf(String::isNotBlank)+ ?: "Recording row could not be reconciled."+ quarantineReconciliationRow(run, reason)+ rowFailures += RecordingReconciliationRowFailure(run.id, reason)+ rowsRepaired++}}- }.fold(- onSuccess = { Result.success(Unit) },- onFailure = { error -> Result.error(error.message ?: "Failed to reconcile recording state", error) }- )+ val summary = RecordingReconciliationSummary(+ rowsInspected = rowsInspected,+ rowsRepaired = rowsRepaired,+ rowsQuarantined = rowFailures.size+ )+ if (rowFailures.isEmpty()) {+ RecordingReconciliationResult.Complete(summary)+ } else {+ RecordingReconciliationResult.Partial(summary, rowFailures)+ }+ } catch (cancelled: CancellationException) {+ throw cancelled+ } catch (error: Throwable) {+ val message = error.message?.takeIf(String::isNotBlank)+ ?: "Failed to reconcile recording state."+ if (isTransientRecordingReconciliationFailure(error)) {+ RecordingReconciliationResult.TransientFailure(message)+ } else {+ RecordingReconciliationResult.PermanentFailure(message)+ }+ }}override suspend fun promoteScheduledRecording(recordingId: String): Result<Unit> = withContext(Dispatchers.IO) {@@ -845,6 +952,14 @@ class RecordingManagerImpl @Inject constructor()}+ private suspend fun quarantineReconciliationRow(run: RecordingRunEntity, reason: String) {+ markRunFailed(+ recordingId = run.id,+ reason = "Recording reconciliation quarantined this row: $reason",+ category = RecordingFailureCategory.UNKNOWN+ )+ }+private suspend fun persistManualRun(request: RecordingRequest,source: ResolvedRecordingSource,diff --git a/data/src/main/java/com/streamvault/data/manager/recording/RecordingReconcileWorker.kt b/data/src/main/java/com/streamvault/data/manager/recording/RecordingReconcileWorker.ktindex f36dffc3..d7f8530e 100644--- a/data/src/main/java/com/streamvault/data/manager/recording/RecordingReconcileWorker.kt+++ b/data/src/main/java/com/streamvault/data/manager/recording/RecordingReconcileWorker.kt@@ -9,6 +9,8 @@ import androidx.work.OneTimeWorkRequestBuilderimport androidx.work.PeriodicWorkRequestBuilderimport androidx.work.WorkManagerimport androidx.work.WorkerParameters+import androidx.work.workDataOf+import com.streamvault.domain.model.RecordingReconciliationResultimport dagger.hilt.EntryPointimport dagger.hilt.InstallInimport dagger.hilt.android.EntryPointAccessors@@ -31,13 +33,19 @@ class RecordingReconcileWorker(applicationContext,RecordingWorkerEntryPoint::class.java).recordingManager()- return reconciliationWorkResult(manager.reconcileRecordingState(), runAttemptCount)+ val reconciliation = manager.reconcileRecordingState()+ setProgress(reconciliationDiagnosticData(reconciliation, runAttemptCount))+ return reconciliationWorkResult(+ result = reconciliation,+ runAttemptCount = runAttemptCount,+ isOneShot = inputData.getBoolean(KEY_ONE_SHOT, false)+ )}companion object {private const val PERIODIC_WORK_NAME = "RecordingReconcileWorker"private const val ONE_SHOT_WORK_NAME = "RecordingReconcileWorkerOneShot"- private const val MAX_ONE_SHOT_ATTEMPTS = 3+ private const val KEY_ONE_SHOT = "one_shot"fun enqueuePeriodic(context: Context) {val request = PeriodicWorkRequestBuilder<RecordingReconcileWorker>(6, TimeUnit.HOURS)@@ -51,25 +59,89 @@ class RecordingReconcileWorker(fun enqueueOneShot(context: Context) {val request = OneTimeWorkRequestBuilder<RecordingReconcileWorker>()- .setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 30, TimeUnit.SECONDS)+ .setInputData(workDataOf(KEY_ONE_SHOT to true))+ .setBackoffCriteria(+ BackoffPolicy.EXPONENTIAL,+ RECORDING_RECONCILE_BACKOFF_MILLIS,+ TimeUnit.MILLISECONDS+ ).build()WorkManager.getInstance(context).enqueueUniqueWork(ONE_SHOT_WORK_NAME,- ExistingWorkPolicy.REPLACE,+ recordingReconcileOneShotExistingWorkPolicy(),request)}}}+internal const val RECORDING_RECONCILE_MAX_ONE_SHOT_ATTEMPTS = 3+internal const val RECORDING_RECONCILE_BACKOFF_MILLIS = 30_000L+internal const val RECONCILIATION_DIAGNOSTIC_OUTCOME = "outcome"+internal const val RECONCILIATION_DIAGNOSTIC_ATTEMPT = "attempt"+internal const val RECONCILIATION_DIAGNOSTIC_INSPECTED = "rows_inspected"+internal const val RECONCILIATION_DIAGNOSTIC_REPAIRED = "rows_repaired"+internal const val RECONCILIATION_DIAGNOSTIC_QUARANTINED = "rows_quarantined"+internal const val RECONCILIATION_DIAGNOSTIC_MESSAGE = "message"++internal fun recordingReconcileOneShotExistingWorkPolicy(): ExistingWorkPolicy =+ ExistingWorkPolicy.KEEP+internal fun reconciliationWorkResult(- result: com.streamvault.domain.model.Result<Unit>,+ result: RecordingReconciliationResult,runAttemptCount: Int,+ isOneShot: Boolean,): androidx.work.ListenableWorker.Result = when (result) {- is com.streamvault.domain.model.Result.Success -> androidx.work.ListenableWorker.Result.success()- is com.streamvault.domain.model.Result.Error -> {- if (runAttemptCount >= 2) androidx.work.ListenableWorker.Result.failure()- else androidx.work.ListenableWorker.Result.retry()+ is RecordingReconciliationResult.Complete,+ is RecordingReconciliationResult.Partial ->+ androidx.work.ListenableWorker.Result.success(+ reconciliationDiagnosticData(result, runAttemptCount)+ )+ is RecordingReconciliationResult.PermanentFailure ->+ androidx.work.ListenableWorker.Result.failure(+ reconciliationDiagnosticData(result, runAttemptCount)+ )+ is RecordingReconciliationResult.TransientFailure -> {+ val attemptCeilingReached = isOneShot &&+ runAttemptCount >= RECORDING_RECONCILE_MAX_ONE_SHOT_ATTEMPTS - 1+ if (attemptCeilingReached) {+ androidx.work.ListenableWorker.Result.failure(+ reconciliationDiagnosticData(result, runAttemptCount)+ )+ } else {+ androidx.work.ListenableWorker.Result.retry()+ }+ }+}++internal fun reconciliationDiagnosticData(+ result: RecordingReconciliationResult,+ runAttemptCount: Int+): androidx.work.Data {+ val outcome = when (result) {+ is RecordingReconciliationResult.Complete -> "complete"+ is RecordingReconciliationResult.Partial -> "partial"+ is RecordingReconciliationResult.TransientFailure -> "transient_failure"+ is RecordingReconciliationResult.PermanentFailure -> "permanent_failure"+ }+ val summary = when (result) {+ is RecordingReconciliationResult.Complete -> result.summary+ is RecordingReconciliationResult.Partial -> result.summary+ else -> null+ }+ val message = when (result) {+ is RecordingReconciliationResult.TransientFailure -> result.message+ is RecordingReconciliationResult.PermanentFailure -> result.message+ is RecordingReconciliationResult.Partial ->+ result.rowFailures.firstOrNull()?.reason.orEmpty()+ is RecordingReconciliationResult.Complete -> ""}- com.streamvault.domain.model.Result.Loading -> androidx.work.ListenableWorker.Result.failure()+ return workDataOf(+ RECONCILIATION_DIAGNOSTIC_OUTCOME to outcome,+ RECONCILIATION_DIAGNOSTIC_ATTEMPT to runAttemptCount,+ RECONCILIATION_DIAGNOSTIC_INSPECTED to (summary?.rowsInspected ?: 0),+ RECONCILIATION_DIAGNOSTIC_REPAIRED to (summary?.rowsRepaired ?: 0),+ RECONCILIATION_DIAGNOSTIC_QUARANTINED to (summary?.rowsQuarantined ?: 0),+ RECONCILIATION_DIAGNOSTIC_MESSAGE to message.take(1_024)+ )}diff --git a/data/src/main/java/com/streamvault/data/manager/reminder/ProgramReminderNotifier.kt b/data/src/main/java/com/streamvault/data/manager/reminder/ProgramReminderNotifier.ktindex a81ea62e..bbb44554 100644--- a/data/src/main/java/com/streamvault/data/manager/reminder/ProgramReminderNotifier.kt+++ b/data/src/main/java/com/streamvault/data/manager/reminder/ProgramReminderNotifier.kt@@ -8,45 +8,64 @@ import android.os.Buildimport androidx.core.app.NotificationCompatimport androidx.core.app.NotificationManagerCompatimport com.streamvault.data.local.entity.ProgramReminderEntity-import com.streamvault.domain.model.Resultimport dagger.hilt.android.qualifiers.ApplicationContextimport javax.inject.Injectimport javax.inject.Singleton+internal sealed interface ReminderNotificationResult {+ data object Accepted : ReminderNotificationResult+ data class Blocked(val reason: String) : ReminderNotificationResult+ data class Failed(val reason: String, val cause: Throwable? = null) : ReminderNotificationResult+}+@Singletonclass ProgramReminderNotifier @Inject constructor(@ApplicationContext private val context: Context) {- fun showReminder(reminder: ProgramReminderEntity): Result<Unit> {- val notificationManager = NotificationManagerCompat.from(context)- if (!notificationManager.areNotificationsEnabled()) {- return Result.error("Notifications are disabled for program reminders.")- }- createChannelIfNeeded()- val now = System.currentTimeMillis()- val minutesUntilStart = ((reminder.programStartTime - now) / 60000L).coerceAtLeast(0L)- val contentText = if (minutesUntilStart <= 0L) {- "${reminder.channelName} is starting now."- } else {- "${reminder.channelName} starts in ${minutesUntilStart} min."- }- val notification = NotificationCompat.Builder(context, CHANNEL_ID)- .setSmallIcon(android.R.drawable.ic_dialog_info)- .setContentTitle("Starting soon: ${reminder.programTitle}")- .setContentText(contentText)- .setStyle(NotificationCompat.BigTextStyle().bigText(contentText))- .setPriority(NotificationCompat.PRIORITY_DEFAULT)- .setCategory(NotificationCompat.CATEGORY_REMINDER)- .setAutoCancel(true)- .setContentIntent(buildLaunchPendingIntent())- .build()- return runCatching {+ internal fun showReminder(reminder: ProgramReminderEntity): ReminderNotificationResult {+ return try {+ val notificationManager = NotificationManagerCompat.from(context)+ createChannelIfNeeded()+ val channelImportance = reminderChannelImportance()+ reminderNotificationBlockedReason(+ notificationsEnabled = notificationManager.areNotificationsEnabled(),+ channelImportance = channelImportance+ )?.let { reason ->+ return ReminderNotificationResult.Blocked(reason)+ }+ val now = System.currentTimeMillis()+ val minutesUntilStart = ((reminder.programStartTime - now) / 60000L).coerceAtLeast(0L)+ val contentText = if (minutesUntilStart <= 0L) {+ "${reminder.channelName} is starting now."+ } else {+ "${reminder.channelName} starts in ${minutesUntilStart} min."+ }+ val notification = NotificationCompat.Builder(context, CHANNEL_ID)+ .setSmallIcon(android.R.drawable.ic_dialog_info)+ .setContentTitle("Starting soon: ${reminder.programTitle}")+ .setContentText(contentText)+ .setStyle(NotificationCompat.BigTextStyle().bigText(contentText))+ .setPriority(NotificationCompat.PRIORITY_DEFAULT)+ .setCategory(NotificationCompat.CATEGORY_REMINDER)+ .setAutoCancel(true)+ .setContentIntent(buildLaunchPendingIntent())+ .build()notificationManager.notify(reminderNotificationTag(reminder.id), 0, notification)- Result.success(Unit)- }.getOrElse { error -> Result.error("Unable to show program reminder.", error) }+ ReminderNotificationResult.Accepted+ } catch (error: Exception) {+ ReminderNotificationResult.Failed("Unable to show program reminder.", error)+ }}+ internal fun isReminderVisible(reminderId: Long): Boolean = runCatching {+ val manager = context.getSystemService(NotificationManager::class.java)+ ?: return@runCatching false+ manager.activeNotifications.any { notification ->+ notification.tag == reminderNotificationTag(reminderId)+ }+ }.getOrDefault(false)+private fun reminderNotificationTag(reminderId: Long): String = "program-reminder:$reminderId"private fun buildLaunchPendingIntent(): PendingIntent? {@@ -73,7 +92,27 @@ class ProgramReminderNotifier @Inject constructor(manager.createNotificationChannel(channel)}+ private fun reminderChannelImportance(): Int? {+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return null+ val manager = context.getSystemService(NotificationManager::class.java) ?: return null+ return manager.getNotificationChannel(CHANNEL_ID)?.importance+ }+companion object {- private const val CHANNEL_ID = "program-reminders"+ internal const val CHANNEL_ID = "program-reminders"+ internal const val NOTIFICATIONS_DISABLED_REASON =+ "Notifications are disabled for program reminders."+ internal const val CHANNEL_DISABLED_REASON =+ "The Program reminders notification channel is disabled."}}++internal fun reminderNotificationBlockedReason(+ notificationsEnabled: Boolean,+ channelImportance: Int?+): String? = when {+ !notificationsEnabled -> ProgramReminderNotifier.NOTIFICATIONS_DISABLED_REASON+ channelImportance == NotificationManager.IMPORTANCE_NONE ->+ ProgramReminderNotifier.CHANNEL_DISABLED_REASON+ else -> null+}diff --git a/data/src/main/java/com/streamvault/data/preferences/PreferencesRepository.kt b/data/src/main/java/com/streamvault/data/preferences/PreferencesRepository.ktindex 37088761..036dda7a 100644--- a/data/src/main/java/com/streamvault/data/preferences/PreferencesRepository.kt+++ b/data/src/main/java/com/streamvault/data/preferences/PreferencesRepository.kt@@ -7,13 +7,16 @@ import android.util.Logimport androidx.security.crypto.EncryptedSharedPreferencesimport androidx.security.crypto.MasterKeyimport androidx.datastore.core.DataStore+import androidx.datastore.core.handlers.ReplaceFileCorruptionHandlerimport androidx.datastore.preferences.core.Preferencesimport androidx.datastore.preferences.core.booleanPreferencesKey+import androidx.datastore.preferences.core.PreferenceDataStoreFactoryimport androidx.datastore.preferences.core.edit+import androidx.datastore.preferences.core.emptyPreferencesimport androidx.datastore.preferences.core.intPreferencesKeyimport androidx.datastore.preferences.core.longPreferencesKeyimport androidx.datastore.preferences.core.stringPreferencesKey-import androidx.datastore.preferences.preferencesDataStore+import androidx.datastore.preferences.preferencesDataStoreFileimport com.streamvault.data.local.dao.ChannelPreferenceDaoimport com.streamvault.data.local.dao.SearchHistoryDaoimport com.streamvault.domain.model.GroupedChannelLabelMode@@ -58,9 +61,64 @@ import kotlinx.coroutines.flow.mapimport javax.inject.Injectimport javax.inject.Singletonimport dagger.hilt.android.qualifiers.ApplicationContext+import java.io.File+import java.util.concurrent.atomic.AtomicLong++private const val PREFERENCES_DATASTORE_NAME = "user_preferences"@Singleton-private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "user_preferences")+class PreferencesCorruptionRecovery @Inject constructor(+ @ApplicationContext private val context: Context+) {+ private companion object {+ const val MAX_SNAPSHOT_BYTES = 4L * 1024L * 1024L+ const val MAX_SNAPSHOTS = 3+ }++ private val lastRecoveryAt = AtomicLong(0L)++ fun recover(+ cause: Throwable,+ dataStoreName: String = PREFERENCES_DATASTORE_NAME+ ): Preferences {+ val recoveredAt = System.currentTimeMillis()+ lastRecoveryAt.set(recoveredAt)+ val directory = File(context.filesDir, "preference-recovery").apply { mkdirs() }+ runCatching {+ val source = context.preferencesDataStoreFile(dataStoreName)+ if (!source.isFile) return@runCatching+ val snapshot = File(directory, "$dataStoreName.corrupt-$recoveredAt")+ source.inputStream().use { input ->+ snapshot.outputStream().use { output ->+ val buffer = ByteArray(DEFAULT_BUFFER_SIZE)+ var remaining = MAX_SNAPSHOT_BYTES+ while (remaining > 0L) {+ val read = input.read(buffer, 0, minOf(buffer.size.toLong(), remaining).toInt())+ if (read < 0) break+ output.write(buffer, 0, read)+ remaining -= read+ }+ }+ }+ directory.listFiles { _, name ->+ name.startsWith("$dataStoreName.corrupt-")+ }?.sortedByDescending(File::lastModified)+ ?.drop(MAX_SNAPSHOTS)+ ?.forEach(File::delete)+ }+ runCatching {+ File(directory, "$dataStoreName.recovery").writeText(+ "timestamp=$recoveredAt\n" ++ "type=${cause::class.java.name}\n" ++ "message=${cause.message.orEmpty().take(512)}\n"+ )+ }+ Log.e("PreferencesRecovery", "Preferences DataStore was corrupt; defaults restored", cause)+ return emptyPreferences()+ }++ fun lastRecoveryTimestamp(): Long = lastRecoveryAt.get()+}private fun sanitizePlaybackTimerMinutes(minutes: Int): Int = when (minutes) {0, 15, 30, 45, 60, 90, 120 -> minutes@@ -90,8 +148,20 @@ internal fun parseTimeshiftBackendPreference(saved: String?): TimeshiftBackendPrclass PreferencesRepository @Inject constructor(@ApplicationContext private val context: Context,private val channelPreferenceDao: ChannelPreferenceDao,- private val searchHistoryDao: SearchHistoryDao+ private val searchHistoryDao: SearchHistoryDao,+ private val corruptionRecovery: PreferencesCorruptionRecovery) : ParentalControlSessionStore, ParentalPinVerifier {+ private val preferencesDataStore: DataStore<Preferences> by lazy {+ PreferenceDataStoreFactory.create(+ corruptionHandler = ReplaceFileCorruptionHandler { cause ->+ corruptionRecovery.recover(cause)+ },+ produceFile = { context.preferencesDataStoreFile(PREFERENCES_DATASTORE_NAME) }+ )+ }++ private val Context.dataStore: DataStore<Preferences>+ get() = preferencesDataStorecompanion object {private const val AUDIO_VIDEO_OFFSET_MIN_MS = -2_000private const val AUDIO_VIDEO_OFFSET_MAX_MS = 2_000@@ -210,7 +280,9 @@ class PreferencesRepository @Inject constructor(val DOWNLOAD_TREE_URI = stringPreferencesKey("download_tree_uri")val MAX_CONCURRENT_STREAMS = intPreferencesKey("max_concurrent_streams")val LAST_APP_UPDATE_CHECK_TIMESTAMP = longPreferencesKey("last_app_update_check_timestamp")+ val LAST_APP_UPDATE_ATTEMPT_TIMESTAMP = longPreferencesKey("last_app_update_attempt_timestamp")val LAST_APP_UPDATE_FAILURE_TIMESTAMP = longPreferencesKey("last_app_update_failure_timestamp")+ val LAST_APP_UPDATE_OUTCOME = stringPreferencesKey("last_app_update_outcome")val APP_UPDATE_DOWNLOAD_ID = longPreferencesKey("app_update_download_id")val APP_UPDATE_DOWNLOAD_VERSION_NAME = stringPreferencesKey("app_update_download_version_name")val APP_UPDATE_DOWNLOADED_VERSION_NAME = stringPreferencesKey("app_update_downloaded_version_name")@@ -617,10 +689,18 @@ class PreferencesRepository @Inject constructor(preferences[PreferencesKeys.LAST_APP_UPDATE_CHECK_TIMESTAMP]?.takeIf { it > 0L }}+ val lastAppUpdateAttemptTimestamp: Flow<Long?> = context.dataStore.data.map { preferences ->+ preferences[PreferencesKeys.LAST_APP_UPDATE_ATTEMPT_TIMESTAMP]?.takeIf { it > 0L }+ }+val lastAppUpdateFailureTimestamp: Flow<Long?> = context.dataStore.data.map { preferences ->preferences[PreferencesKeys.LAST_APP_UPDATE_FAILURE_TIMESTAMP]?.takeIf { it > 0L }}+ val lastAppUpdateOutcome: Flow<String?> = context.dataStore.data.map { preferences ->+ preferences[PreferencesKeys.LAST_APP_UPDATE_OUTCOME]?.takeIf { it.isNotBlank() }+ }+val appUpdateDownloadId: Flow<Long?> = context.dataStore.data.map { preferences ->preferences[PreferencesKeys.APP_UPDATE_DOWNLOAD_ID]?.takeIf { it > 0L }}@@ -795,6 +875,26 @@ class PreferencesRepository @Inject constructor(}}+ suspend fun setLastAppUpdateAttemptTimestamp(timestampMs: Long?) {+ context.dataStore.edit { preferences ->+ if (timestampMs == null || timestampMs <= 0L) {+ preferences.remove(PreferencesKeys.LAST_APP_UPDATE_ATTEMPT_TIMESTAMP)+ } else {+ preferences[PreferencesKeys.LAST_APP_UPDATE_ATTEMPT_TIMESTAMP] = timestampMs+ }+ }+ }++ suspend fun setLastAppUpdateOutcome(outcome: String?) {+ context.dataStore.edit { preferences ->+ if (outcome.isNullOrBlank()) {+ preferences.remove(PreferencesKeys.LAST_APP_UPDATE_OUTCOME)+ } else {+ preferences[PreferencesKeys.LAST_APP_UPDATE_OUTCOME] = outcome.take(256)+ }+ }+ }+suspend fun setAppUpdateDownloadId(downloadId: Long?) {context.dataStore.edit { preferences ->if (downloadId == null || downloadId <= 0L) {@@ -1705,6 +1805,12 @@ class PreferencesRepository @Inject constructor(}}+ suspend fun clearGuideDefaultCategoryId() {+ context.dataStore.edit { preferences ->+ preferences.remove(PreferencesKeys.GUIDE_DEFAULT_CATEGORY_ID)+ }+ }+val guideFavoritesOnly: Flow<Boolean> = context.dataStore.data.map { preferences ->(preferences[PreferencesKeys.GUIDE_FAVORITES_ONLY] ?: 0) == 1}@@ -1735,6 +1841,12 @@ class PreferencesRepository @Inject constructor(}}+ suspend fun clearGuideAnchorTime() {+ context.dataStore.edit { preferences ->+ preferences.remove(PreferencesKeys.GUIDE_ANCHOR_TIME)+ }+ }+private fun decodeEpgTimeShifts(raw: String?): Map<Long, Int> {if (raw.isNullOrBlank()) return emptyMap()return raw.split(",").mapNotNull { token ->diff --git a/data/src/main/java/com/streamvault/data/repository/EpgSourceRepositoryImpl.kt b/data/src/main/java/com/streamvault/data/repository/EpgSourceRepositoryImpl.ktindex 6083a1fc..278de2ef 100644--- a/data/src/main/java/com/streamvault/data/repository/EpgSourceRepositoryImpl.kt+++ b/data/src/main/java/com/streamvault/data/repository/EpgSourceRepositoryImpl.kt@@ -38,6 +38,7 @@ import com.streamvault.domain.model.Programimport com.streamvault.domain.model.ProviderEpgSourceAssignmentimport com.streamvault.domain.model.Resultimport com.streamvault.domain.repository.EpgSourceRepository+import com.streamvault.domain.util.PersistedTimestampPolicyimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.CancellationExceptionimport kotlinx.coroutines.flow.Flow@@ -76,6 +77,16 @@ internal fun limitEpgInput(}}+internal fun shouldRateLimitEpgRefresh(+ lastSuccessfulRefreshAt: Long,+ now: Long,+ minimumIntervalMillis: Long+): Boolean = PersistedTimestampPolicy.isFresh(+ lastSuccessfulRefreshAt,+ now,+ minimumIntervalMillis+)+@Singletonclass EpgSourceRepositoryImpl @Inject constructor(@ApplicationContext private val context: Context,@@ -245,7 +256,7 @@ class EpgSourceRepositoryImpl @Inject constructor(val now = System.currentTimeMillis()// Rate-limit: skip if last successful refresh was less than 5 minutes ago- if (source.lastRefreshAt > 0 && now - source.lastRefreshAt < MIN_REFRESH_INTERVAL_MS) {+ if (shouldRateLimitEpgRefresh(source.lastRefreshAt, now, MIN_REFRESH_INTERVAL_MS)) {Log.d(TAG, "Skipping refresh for source $sourceId: last refresh was ${(now - source.lastRefreshAt) / 1000}s ago")return@withLock Result.success(Unit)}diff --git a/data/src/main/java/com/streamvault/data/repository/ProviderDeletionCleanupWorker.kt b/data/src/main/java/com/streamvault/data/repository/ProviderDeletionCleanupWorker.ktindex 78115905..997f4954 100644--- a/data/src/main/java/com/streamvault/data/repository/ProviderDeletionCleanupWorker.kt+++ b/data/src/main/java/com/streamvault/data/repository/ProviderDeletionCleanupWorker.kt@@ -15,6 +15,8 @@ import dagger.hilt.InstallInimport dagger.hilt.android.EntryPointAccessorsimport dagger.hilt.components.SingletonComponentimport kotlinx.coroutines.CancellationException+import javax.inject.Inject+import dagger.hilt.android.qualifiers.ApplicationContextclass ProviderDeletionCleanupWorker(appContext: Context, params: WorkerParameters) : CoroutineWorker(appContext, params) {@EntryPoint @InstallIn(SingletonComponent::class)@@ -27,23 +29,17 @@ class ProviderDeletionCleanupWorker(appContext: Context, params: WorkerParameteroverride suspend fun doWork(): Result {val entry = EntryPointAccessors.fromApplication(applicationContext, Entry::class.java)- val dao = entry.providerDeletionCleanupDao()- var failed = false- dao.getAll().forEach { item ->- try {- when (item.action) {- RECORDING_ALARM -> entry.recordingAlarmScheduler().cancel(item.targetId)- REMINDER_ALARM -> entry.programReminderAlarmScheduler().cancel(item.targetId.toLong())- SYNC_RUNTIME -> entry.syncManager().onProviderDeleted(item.providerId)- }- dao.delete(item.id)- } catch (t: Throwable) {- if (t is CancellationException) throw t- dao.recordFailure(item.id, t.message ?: t.javaClass.simpleName)- failed = true- }+ return when (+ drainProviderDeletionCleanup(+ dao = entry.providerDeletionCleanupDao(),+ cancelRecordingAlarm = entry.recordingAlarmScheduler()::cancel,+ cancelReminderAlarm = entry.programReminderAlarmScheduler()::cancel,+ cleanupSyncRuntime = entry.syncManager()::onProviderDeleted+ )+ ) {+ ProviderDeletionDrainOutcome.COMPLETE -> Result.success()+ ProviderDeletionDrainOutcome.RETRY -> Result.retry()}- return if (failed) Result.retry() else Result.success()}companion object {@@ -52,7 +48,69 @@ class ProviderDeletionCleanupWorker(appContext: Context, params: WorkerParameterconst val SYNC_RUNTIME = "SYNC_RUNTIME"private const val WORK_NAME = "ProviderDeletionCleanup"fun enqueue(context: Context) = WorkManager.getInstance(context).enqueueUniqueWork(- WORK_NAME, ExistingWorkPolicy.KEEP, OneTimeWorkRequestBuilder<ProviderDeletionCleanupWorker>().build()+ WORK_NAME,+ PROVIDER_DELETION_EXISTING_WORK_POLICY,+ OneTimeWorkRequestBuilder<ProviderDeletionCleanupWorker>().build())}}++class ProviderDeletionCleanupEnqueuer @Inject constructor(+ @param:ApplicationContext private val context: Context+) {+ fun enqueue() {+ ProviderDeletionCleanupWorker.enqueue(context)+ }+}++internal enum class ProviderDeletionDrainOutcome {+ COMPLETE,+ RETRY+}++internal suspend fun drainProviderDeletionCleanup(+ dao: ProviderDeletionCleanupDao,+ cancelRecordingAlarm: (String) -> Unit,+ cancelReminderAlarm: (Long) -> Unit,+ cleanupSyncRuntime: suspend (Long) -> Unit+): ProviderDeletionDrainOutcome {+ while (true) {+ val items = try {+ dao.getBatch(CLEANUP_BATCH_SIZE)+ } catch (cancelled: CancellationException) {+ throw cancelled+ } catch (_: Throwable) {+ return ProviderDeletionDrainOutcome.RETRY+ }+ if (items.isEmpty()) return ProviderDeletionDrainOutcome.COMPLETE++ var failed = false+ items.forEach { item ->+ try {+ when (item.action) {+ ProviderDeletionCleanupWorker.RECORDING_ALARM -> cancelRecordingAlarm(item.targetId)+ ProviderDeletionCleanupWorker.REMINDER_ALARM -> cancelReminderAlarm(item.targetId.toLong())+ ProviderDeletionCleanupWorker.SYNC_RUNTIME -> cleanupSyncRuntime(item.providerId)+ else -> error("Unknown provider cleanup action '${item.action}'")+ }+ dao.delete(item.id)+ } catch (cancelled: CancellationException) {+ throw cancelled+ } catch (error: Throwable) {+ failed = true+ try {+ dao.recordFailure(item.id, error.message ?: error.javaClass.simpleName)+ } catch (cancelled: CancellationException) {+ throw cancelled+ } catch (_: Throwable) {+ // The tombstone remains durable. Returning retry is more important than+ // successfully recording diagnostics for this attempt.+ }+ }+ }+ if (failed) return ProviderDeletionDrainOutcome.RETRY+ }+}++private const val CLEANUP_BATCH_SIZE = 100+internal val PROVIDER_DELETION_EXISTING_WORK_POLICY = ExistingWorkPolicy.APPEND_OR_REPLACEdiff --git a/data/src/main/java/com/streamvault/data/repository/ProviderRepositoryImpl.kt b/data/src/main/java/com/streamvault/data/repository/ProviderRepositoryImpl.ktindex c4a0fcf7..c0167d53 100644--- a/data/src/main/java/com/streamvault/data/repository/ProviderRepositoryImpl.kt+++ b/data/src/main/java/com/streamvault/data/repository/ProviderRepositoryImpl.kt@@ -1,8 +1,12 @@package com.streamvault.data.repositoryimport android.content.Context+import com.google.gson.Gsonimport com.streamvault.data.local.dao.ProviderDeletionCleanupDao+import com.streamvault.data.local.dao.ProviderConfigRevisionDaoimport com.streamvault.data.local.entity.ProviderDeletionCleanupEntity+import com.streamvault.data.local.entity.ProviderConfigRevisionEntity+import com.streamvault.data.local.entity.ProviderConfigRevisionStateimport com.streamvault.data.local.DatabaseTransactionRunnerimport com.streamvault.data.local.dao.*import com.streamvault.data.local.entity.ProviderEntity@@ -20,13 +24,21 @@ import com.streamvault.data.remote.xtream.XtreamProviderimport com.streamvault.data.security.CredentialCryptoimport com.streamvault.data.security.CredentialDecryptionExceptionimport com.streamvault.data.sync.SyncManager+import com.streamvault.data.sync.ProviderSyncWorker+import com.streamvault.data.sync.ProviderWorkflowDisposition+import com.streamvault.data.sync.ProviderWorkflowOutcome+import com.streamvault.data.sync.ProviderWorkflowRunner+import com.streamvault.data.sync.ProviderWorkflowCommitFenceimport com.streamvault.data.sync.hasUsableLiveCatalogForActivation+import com.streamvault.data.local.entity.ProviderWorkflowPhase+import com.streamvault.data.local.entity.ProviderWorkflowReasonimport com.streamvault.data.util.ProviderInputSanitizerimport com.streamvault.data.util.UrlSecurityPolicyimport com.streamvault.domain.manager.ProviderCredentialsimport com.streamvault.domain.model.*import com.streamvault.domain.provider.IptvProviderimport com.streamvault.domain.repository.LiveStreamProgramRequest+import com.streamvault.domain.repository.ProviderDeleteOutcomeimport com.streamvault.domain.repository.ProviderDeleteProgressimport com.streamvault.domain.repository.ProviderRepositoryimport com.streamvault.domain.repository.SyncMetadataRepository@@ -35,6 +47,7 @@ import kotlinx.coroutines.awaitAllimport kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.CancellationExceptionimport kotlinx.coroutines.coroutineScopeimport kotlinx.coroutines.delayimport kotlinx.coroutines.flow.Flow@@ -67,7 +80,12 @@ class ProviderRepositoryImpl @Inject constructor(private val programReminderAlarmScheduler: ProgramReminderAlarmScheduler,private val jellyfinProvider: JellyfinProvider,private val providerDeletionCleanupDao: ProviderDeletionCleanupDao,- @ApplicationContext private val appContext: Context+ private val providerDeletionCleanupEnqueuer: ProviderDeletionCleanupEnqueuer,+ private val providerConfigRevisionDao: ProviderConfigRevisionDao,+ private val gson: Gson,+ private val providerWorkflowRunner: ProviderWorkflowRunner,+ private val providerWorkflowCommitFence: ProviderWorkflowCommitFence,+ @param:ApplicationContext private val appContext: Context) : ProviderRepository {private companion object {const val XTREAM_GUIDE_BATCH_CONCURRENCY = 4@@ -77,11 +95,24 @@ class ProviderRepositoryImpl @Inject constructor(const val ALARM_STEP_WEIGHT = 5const val PROVIDER_ROW_STEP_WEIGHT = 200const val FINALIZE_STEP_WEIGHT = 200+ const val MANUAL_REFRESH_PRIORITY = 50val logger: Logger = Logger.getLogger(ProviderRepositoryImpl::class.java.name)}private val repositoryScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)+ private data class PendingProviderEdit(+ val revision: Long,+ val candidate: Provider,+ val secureCandidate: ProviderEntity+ )++ private data class InitialOnboardingTarget(+ val providerData: Provider,+ val providerForSync: Provider,+ val pendingEdit: PendingProviderEdit? = null+ )+override fun getProviders(): Flow<List<Provider>> =providerDao.getAll().map { entities -> entities.map { it.toPublicDomain() } }@@ -137,9 +168,9 @@ class ProviderRepositoryImpl @Inject constructor(override suspend fun deleteProvider(id: Long,onProgress: ((ProviderDeleteProgress) -> Unit)?- ): Result<Unit> = try {- val recordingRunIds = recordingRunDao.getIdsByProvider(id)- val reminderIds = programReminderDao.getIdsByProvider(id)+ ): Result<ProviderDeleteOutcome> = try {+ val estimatedRecordingRunIds = recordingRunDao.getIdsByProvider(id)+ val estimatedReminderIds = programReminderDao.getIdsByProvider(id)// Weight progress by the real row counts of the large child tables so the bar// advances proportionally to the work being done instead of in two big jumps.@@ -149,11 +180,12 @@ class ProviderRepositoryImpl @Inject constructor(val seriesCount = seriesDao.countByProvider(id)val totalWeight = (- programCount + channelCount + movieCount + seriesCount +- (recordingRunIds.size + reminderIds.size) * ALARM_STEP_WEIGHT ++ programCount + channelCount + movieCount + seriesCount ++ (estimatedRecordingRunIds.size + estimatedReminderIds.size) * ALARM_STEP_WEIGHT +PROVIDER_ROW_STEP_WEIGHT + FINALIZE_STEP_WEIGHT).coerceAtLeast(1)var completedWeight = 0+ var pendingCleanupActions = 0fun reportProgress(message: String) {onProgress?.invoke(@@ -166,6 +198,11 @@ class ProviderRepositoryImpl @Inject constructor(reportProgress("Preparing to remove provider...")transactionRunner.inTransaction {+ // Re-read alarm identities under the same Room transaction that removes+ // their rows. This closes the window where a newly committed alarm could+ // be cascade-deleted without receiving a durable cancellation tombstone.+ val recordingRunIds = recordingRunDao.getIdsByProvider(id)+ val reminderIds = programReminderDao.getIdsByProvider(id)providerDeletionCleanupDao.insertAll(recordingRunIds.map { ProviderDeletionCleanupEntity(id = 0, providerId = id, action = ProviderDeletionCleanupWorker.RECORDING_ALARM, targetId = it) } +reminderIds.map { ProviderDeletionCleanupEntity(id = 0, providerId = id, action = ProviderDeletionCleanupWorker.REMINDER_ALARM, targetId = it.toString()) } +@@ -191,14 +228,34 @@ class ProviderRepositoryImpl @Inject constructor(reportProgress("Removing provider record...")providerDao.delete(id)completedWeight += PROVIDER_ROW_STEP_WEIGHT+ pendingCleanupActions = providerDeletionCleanupDao.countByProvider(id)}reportProgress("Provider library removed.")reportProgress("Finalizing provider cleanup...")- runCatching { ProviderDeletionCleanupWorker.enqueue(appContext) }- .onFailure { logger.warning("Provider cleanup was queued but WorkManager enqueue failed: ${it.message}") }+ val reconciliationRequested = runCatching {+ providerDeletionCleanupEnqueuer.enqueue()+ true+ }.getOrElse {+ logger.warning("Provider cleanup is pending but WorkManager enqueue failed: ${it.message}")+ false+ }completedWeight = totalWeight- reportProgress("Provider deleted; final cleanup continues.")- Result.success(Unit)+ reportProgress(+ if (reconciliationRequested) {+ "Provider library deleted; final cleanup continues."+ } else {+ "Provider library deleted; cleanup is pending and will retry on startup."+ }+ )+ Result.success(+ ProviderDeleteOutcome(+ providerId = id,+ pendingCleanupActions = pendingCleanupActions,+ reconciliationRequested = reconciliationRequested+ )+ )+ } catch (cancelled: CancellationException) {+ throw cancelled} catch (e: Exception) {Result.error("Failed to delete provider: ${e.message}", e)}@@ -273,7 +330,7 @@ class ProviderRepositoryImpl @Inject constructor()return when (val authResult = provider.authenticate()) {is Result.Success -> {- val providerData = if (existingProvider != null) {+ val onboardingTarget = if (existingProvider != null) {onProgress?.invoke("Updating existing provider...")val updated = authResult.data.copy(id = existingProvider.id,@@ -293,8 +350,11 @@ class ProviderRepositoryImpl @Inject constructor(lastSyncedAt = 0,createdAt = existingProvider.createdAt)- providerDao.update(updated.toSecureEntity())- updated.copy(password = "")+ InitialOnboardingTarget(+ providerData = updated.copy(password = ""),+ providerForSync = updated,+ pendingEdit = stageProviderEdit(updated)+ )} else {val newData = authResult.data.copy(name = normalizedName.ifBlank { authResult.data.name },@@ -309,18 +369,21 @@ class ProviderRepositoryImpl @Inject constructor(status = ProviderStatus.PARTIAL)val newId = providerDao.insert(newData.toSecureEntity())- newData.copy(id = newId).copy(password = "")+ InitialOnboardingTarget(+ providerData = newData.copy(id = newId, password = ""),+ providerForSync = newData.copy(id = newId)+ )}handleInitialOnboardingSync(- providerData = providerData,- syncResult = syncManager.sync(- providerData.id,- force = false,- onProgress = onProgress,+ providerData = onboardingTarget.providerData,+ syncResult = syncInitialOnboarding(+ onboardingTarget,+ onProgress,trackInitialLiveOnboarding = true),- syncFailurePrefix = "Provider login succeeded, but initial sync failed. The provider was saved and can be retried from Settings"+ syncFailurePrefix = "Provider login succeeded, but initial sync failed. The provider was saved and can be retried from Settings",+ pendingEdit = onboardingTarget.pendingEdit)}is Result.Error -> Result.error(authResult.message, authResult.exception)@@ -368,7 +431,7 @@ class ProviderRepositoryImpl @Inject constructor(providerDao.getByUrlAndUser(normalizedUrl, "")}- val providerData = if (existingProvider != null) {+ val onboardingTarget = if (existingProvider != null) {val updated = existingProvider.copy(name = if (normalizedName.isNotBlank()) normalizedName else existingProvider.name,serverUrl = normalizedUrl,@@ -383,8 +446,11 @@ class ProviderRepositoryImpl @Inject constructor(status = ProviderStatus.PARTIAL,lastSyncedAt = 0)- providerDao.update(updated)- updated.toPublicDomain()+ InitialOnboardingTarget(+ providerData = updated.toPublicDomain(),+ providerForSync = updated.toDomain(),+ pendingEdit = stageProviderEdit(updated.toDomain())+ )} else {val provider = Provider(name = providerName,@@ -401,13 +467,17 @@ class ProviderRepositoryImpl @Inject constructor(status = ProviderStatus.PARTIAL)val newId = providerDao.insert(provider.toSecureEntity())- provider.copy(id = newId).copy(password = "")+ InitialOnboardingTarget(+ providerData = provider.copy(id = newId, password = ""),+ providerForSync = provider.copy(id = newId)+ )}handleInitialOnboardingSync(- providerData = providerData,- syncResult = syncManager.sync(providerData.id, force = false, onProgress = onProgress),- syncFailurePrefix = "Playlist saved, but initial sync failed. The provider was saved and can be retried from Settings"+ providerData = onboardingTarget.providerData,+ syncResult = syncInitialOnboarding(onboardingTarget, onProgress),+ syncFailurePrefix = "Playlist saved, but initial sync failed. The provider was saved and can be retried from Settings",+ pendingEdit = onboardingTarget.pendingEdit)} catch (e: Exception) {Result.error("Failed to add M3U provider: ${e.message}", e)@@ -454,25 +524,34 @@ class ProviderRepositoryImpl @Inject constructor(catch (e: CredentialDecryptionException) { return Result.error(e.message ?: CredentialDecryptionException.MESSAGE, e) }else -> return Result.error("Please enter Jellyfin password")}- val providerData = if (existingProvider != null) {+ val onboardingTarget = if (existingProvider != null) {val updated = existingProvider.copy(name = providerName.ifBlank { existingProvider.name }, type = ProviderType.JELLYFIN,serverUrl = normalizedServerUrl, username = normalizedUsername, password = authResult,m3uUrl = "", epgUrl = "", httpUserAgent = "", httpHeaders = "",isActive = false, status = ProviderStatus.PARTIAL, lastSyncedAt = 0)- providerDao.update(updated.toSecureEntity())- updated.copy(password = "")+ InitialOnboardingTarget(+ providerData = updated.copy(password = ""),+ providerForSync = updated,+ pendingEdit = stageProviderEdit(updated)+ )} else {val provider = Provider(name = providerName, type = ProviderType.JELLYFIN,serverUrl = normalizedServerUrl, username = normalizedUsername, password = authResult,isActive = false, status = ProviderStatus.PARTIAL)val newId = providerDao.insert(provider.toSecureEntity())- provider.copy(id = newId).copy(password = "")+ InitialOnboardingTarget(+ providerData = provider.copy(id = newId, password = ""),+ providerForSync = provider.copy(id = newId)+ )}- handleInitialOnboardingSync(providerData = providerData,- syncResult = syncManager.sync(providerData.id, force = false, onProgress = onProgress),- syncFailurePrefix = "Jellyfin provider saved, but initial sync failed. The provider was saved and can be retried from Settings")+ handleInitialOnboardingSync(+ providerData = onboardingTarget.providerData,+ syncResult = syncInitialOnboarding(onboardingTarget, onProgress),+ syncFailurePrefix = "Jellyfin provider saved, but initial sync failed. The provider was saved and can be retried from Settings",+ pendingEdit = onboardingTarget.pendingEdit+ )} catch (e: Exception) {Result.error("Failed to add Jellyfin provider: ${e.message}", e)}@@ -499,12 +578,15 @@ class ProviderRepositoryImpl @Inject constructor(is Result.Error -> return Result.error(quickConnectResult.message, quickConnectResult.exception)is Result.Loading -> return Result.error("Unexpected loading state")}- val providerData = saveJellyfinProvider(providerName = providerName,+ val onboardingTarget = saveJellyfinProvider(providerName = providerName,serverUrl = normalizedServerUrl, username = quickConnect.userName.ifBlank { providerName },password = quickConnect.accessToken, existingProvider = existingProvider)- handleInitialOnboardingSync(providerData = providerData,- syncResult = syncManager.sync(providerData.id, force = false, onProgress = onProgress),- syncFailurePrefix = "Jellyfin provider saved, but initial sync failed. The provider was saved and can be retried from Settings")+ handleInitialOnboardingSync(+ providerData = onboardingTarget.providerData,+ syncResult = syncInitialOnboarding(onboardingTarget, onProgress),+ syncFailurePrefix = "Jellyfin provider saved, but initial sync failed. The provider was saved and can be retried from Settings",+ pendingEdit = onboardingTarget.pendingEdit+ )} catch (e: Exception) {Result.error("Failed to add Jellyfin provider: ${e.message}", e)}@@ -512,7 +594,7 @@ class ProviderRepositoryImpl @Inject constructor(private suspend fun saveJellyfinProvider(providerName: String, serverUrl: String, username: String, password: String, existingProvider: Provider?- ): Provider {+ ): InitialOnboardingTarget {return if (existingProvider != null) {val updated = existingProvider.copy(name = providerName.ifBlank { existingProvider.name }, type = ProviderType.JELLYFIN,@@ -520,14 +602,20 @@ class ProviderRepositoryImpl @Inject constructor(m3uUrl = "", epgUrl = "", httpUserAgent = "", httpHeaders = "",isActive = false, status = ProviderStatus.PARTIAL, lastSyncedAt = 0)- providerDao.update(updated.toSecureEntity())- updated.copy(password = "")+ InitialOnboardingTarget(+ providerData = updated.copy(password = ""),+ providerForSync = updated,+ pendingEdit = stageProviderEdit(updated)+ )} else {val provider = Provider(name = providerName, type = ProviderType.JELLYFIN,serverUrl = serverUrl, username = username, password = password,isActive = false, status = ProviderStatus.PARTIAL)val newId = providerDao.insert(provider.toSecureEntity())- provider.copy(id = newId).copy(password = "")+ InitialOnboardingTarget(+ providerData = provider.copy(id = newId, password = ""),+ providerForSync = provider.copy(id = newId)+ )}}@@ -622,7 +710,7 @@ class ProviderRepositoryImpl @Inject constructor(return when (val authResult = provider.authenticate()) {is Result.Success -> {- val providerData = if (existingProvider != null) {+ val onboardingTarget = if (existingProvider != null) {onProgress?.invoke("Updating existing provider...")val updated = authResult.data.copy(id = existingProvider.id,@@ -652,8 +740,11 @@ class ProviderRepositoryImpl @Inject constructor(lastSyncedAt = 0L,createdAt = existingProvider.createdAt)- providerDao.update(updated.toSecureEntity())- updated.copy(password = "")+ InitialOnboardingTarget(+ providerData = updated.copy(password = ""),+ providerForSync = updated,+ pendingEdit = stageProviderEdit(updated)+ )} else {val newData = authResult.data.copy(name = normalizedName.ifBlank { authResult.data.name },@@ -680,13 +771,17 @@ class ProviderRepositoryImpl @Inject constructor(status = ProviderStatus.PARTIAL)val newId = providerDao.insert(newData.toSecureEntity())- newData.copy(id = newId).copy(password = "")+ InitialOnboardingTarget(+ providerData = newData.copy(id = newId, password = ""),+ providerForSync = newData.copy(id = newId)+ )}handleInitialOnboardingSync(- providerData = providerData,- syncResult = syncManager.sync(providerData.id, force = false, onProgress = onProgress),- syncFailurePrefix = "Provider login succeeded, but initial sync failed. The provider was saved and can be retried from Settings"+ providerData = onboardingTarget.providerData,+ syncResult = syncInitialOnboarding(onboardingTarget, onProgress),+ syncFailurePrefix = "Provider login succeeded, but initial sync failed. The provider was saved and can be retried from Settings",+ pendingEdit = onboardingTarget.pendingEdit)}is Result.Error -> Result.error(authResult.message, authResult.exception)@@ -694,12 +789,126 @@ class ProviderRepositoryImpl @Inject constructor(}}+ /**+ * Records an edit without touching the committed provider row. The password is encrypted+ * before serialization, so recovery state never introduces a new plaintext credential copy.+ */+ private suspend fun stageProviderEdit(candidate: Provider): PendingProviderEdit {+ require(candidate.id != 0L) { "A provider edit requires an existing provider ID." }+ val secureCandidate = candidate.toSecureEntity()+ val now = System.currentTimeMillis()+ val revision = transactionRunner.inTransaction {+ val nextRevision = providerConfigRevisionDao.latestRevision(candidate.id) + 1L+ providerConfigRevisionDao.supersedeOlder(candidate.id, nextRevision, now)+ providerConfigRevisionDao.upsert(+ ProviderConfigRevisionEntity(+ providerId = candidate.id,+ revision = nextRevision,+ configJson = gson.toJson(secureCandidate),+ state = ProviderConfigRevisionState.PENDING,+ createdAt = now,+ updatedAt = now+ )+ )+ check(providerConfigRevisionDao.claimForSync(candidate.id, nextRevision, now) == 1) {+ "Pending provider edit could not be claimed for synchronization."+ }+ nextRevision+ }+ return PendingProviderEdit(revision, candidate, secureCandidate).also { pendingEdit ->+ // If the process dies during the foreground sync, WorkManager retains this delayed+ // hand-off and resumes the staged candidate rather than the committed configuration.+ scheduleProviderEditRecovery(pendingEdit, immediate = false)+ }+ }++ /** Runs a candidate configuration without exposing it through the committed provider row. */+ private suspend fun syncInitialOnboarding(+ target: InitialOnboardingTarget,+ onProgress: ((String) -> Unit)?,+ trackInitialLiveOnboarding: Boolean = false+ ): Result<Unit> {+ return try {+ val pendingEdit = target.pendingEdit+ if (pendingEdit == null) {+ syncManager.sync(+ providerId = target.providerData.id,+ force = false,+ onProgress = onProgress,+ trackInitialLiveOnboarding = trackInitialLiveOnboarding+ )+ } else {+ syncManager.syncWithProviderOverride(+ providerId = target.providerData.id,+ force = false,+ onProgress = onProgress,+ trackInitialLiveOnboarding = trackInitialLiveOnboarding,+ providerOverride = pendingEdit.candidate,+ afterCatalogApply = { promoteProviderEdit(pendingEdit) }+ )+ }+ } catch (error: kotlinx.coroutines.CancellationException) {+ target.pendingEdit?.let { pendingEdit ->+ providerConfigRevisionDao.releaseForRetry(+ pendingEdit.candidate.id,+ pendingEdit.revision,+ System.currentTimeMillis()+ )+ }+ throw error+ }+ }++ /**+ * Called while the catalog transaction is open. A stale revision is+ * rejected before it can replace the provider row, making a late sync completion harmless.+ */+ private suspend fun promoteProviderEdit(pendingEdit: PendingProviderEdit) {+ val now = System.currentTimeMillis()+ check(+ providerConfigRevisionDao.markCommitted(+ pendingEdit.candidate.id,+ pendingEdit.revision,+ now+ ) == 1+ ) { "Provider edit ${pendingEdit.revision} was superseded before catalog commit." }+ providerDao.update(+ pendingEdit.secureCandidate.copy(+ isActive = true,+ status = ProviderStatus.PARTIAL,+ lastSyncedAt = now+ )+ )+ }+private suspend fun handleInitialOnboardingSync(providerData: Provider,syncResult: Result<Unit>,- syncFailurePrefix: String- ): Result<Provider> = when (syncResult) {+ syncFailurePrefix: String,+ pendingEdit: PendingProviderEdit? = null+ ): Result<Provider> {+ return when (syncResult) {is Result.Success -> {+ if (+ pendingEdit != null &&+ providerConfigRevisionDao.getState(providerData.id, pendingEdit.revision) != ProviderConfigRevisionState.COMMITTED+ ) {+ providerConfigRevisionDao.markFailed(+ providerData.id,+ pendingEdit.revision,+ "Initial sync completed without committing catalog content.",+ System.currentTimeMillis()+ )+ scheduleProviderEditRecovery(pendingEdit)+ val message = "$syncFailurePrefix: Sync did not finish with any committed content."+ return Result.error(+ message,+ ProviderSavedWithSyncErrorException(+ provider = providerData.copy(status = ProviderStatus.PARTIAL, isActive = false),+ message = message+ )+ )+ }val finalStatus = if (syncManager.currentSyncState(providerData.id) is SyncState.Partial) {ProviderStatus.PARTIAL} else {@@ -739,19 +948,61 @@ class ProviderRepositoryImpl @Inject constructor(}}is Result.Error -> {- updateProviderSyncStatus(providerData.id, ProviderStatus.PARTIAL, isActive = false)+ if (pendingEdit != null) {+ val state = providerConfigRevisionDao.getState(providerData.id, pendingEdit.revision)+ if (state != ProviderConfigRevisionState.COMMITTED) {+ providerConfigRevisionDao.markFailed(+ providerData.id,+ pendingEdit.revision,+ syncResult.message,+ System.currentTimeMillis()+ )+ scheduleProviderEditRecovery(pendingEdit)+ val message = "$syncFailurePrefix: ${syncResult.message}"+ return Result.error(+ message,+ ProviderSavedWithSyncErrorException(+ provider = providerData.copy(status = ProviderStatus.PARTIAL, isActive = false),+ message = message,+ cause = syncResult.exception+ )+ )+ }+ }+ updateProviderSyncStatus(+ providerData.id,+ ProviderStatus.PARTIAL,+ isActive = pendingEdit != null+ )syncManager.scheduleProviderSyncResume(providerData.id)val message = "$syncFailurePrefix: ${syncResult.message}"Result.error(message,ProviderSavedWithSyncErrorException(- provider = providerData.copy(status = ProviderStatus.PARTIAL, isActive = false),+ provider = providerData.copy(status = ProviderStatus.PARTIAL, isActive = pendingEdit != null),message = message,cause = syncResult.exception))}is Result.Loading -> Result.error("Unexpected loading state")+ }+ }++ private fun scheduleProviderEditRecovery(+ pendingEdit: PendingProviderEdit,+ immediate: Boolean = true+ ) {+ runCatching {+ ProviderSyncWorker.enqueueProviderConfigRevision(+ appContext,+ pendingEdit.candidate.id,+ pendingEdit.revision,+ immediate = immediate+ )+ }.onFailure { error ->+ logger.warning("Failed to schedule pending provider edit recovery: ${error.message}")+ }}/**@@ -764,50 +1015,110 @@ class ProviderRepositoryImpl @Inject constructor(epgSyncModeOverride: ProviderEpgSyncMode?,onProgress: ((String) -> Unit)?): Result<Unit> {- return when (- val syncResult = syncManager.sync(+ var syncResult: Result<Unit>? = null+ val disposition = providerWorkflowRunner.execute(+ providerId = providerId,+ phase = ProviderWorkflowPhase.PRIMARY_CATALOG,+ reason = ProviderWorkflowReason.MANUAL,+ force = force,+ supersede = force,+ priority = MANUAL_REFRESH_PRIORITY+ ) {+ val result = syncManager.sync(providerId,force = force,movieFastSyncOverride = movieFastSyncOverride,epgSyncModeOverride = epgSyncModeOverride,onProgress = onProgress)- ) {- is Result.Success -> {- val finalStatus = if (syncManager.currentSyncState(providerId) is SyncState.Partial) {- ProviderStatus.PARTIAL- } else {- ProviderStatus.ACTIVE+ syncResult = result+ when (result) {+ is Result.Success -> {+ finalizeSuccessfulManualSync(providerId)+ ProviderWorkflowOutcome.Success(+ partial = syncManager.currentSyncState(providerId) is SyncState.Partial+ )}- val provider = providerDao.getById(providerId)- if (provider != null && !hasUsableLiveCatalogForActivation(- providerId,- provider.type,- channelDao,- categoryDao,- syncMetadataRepository- )) {- updateProviderSyncStatus(- providerId,- ProviderStatus.PARTIAL,- lastSyncedAt = System.currentTimeMillis(),- isActive = false+ is Result.Error -> {+ transactionRunner.inTransaction {+ providerWorkflowCommitFence.assertCanCommit(providerId)+ updateProviderSyncStatus(providerId, ProviderStatus.ERROR)+ }+ ProviderWorkflowOutcome.Failure(+ code = "MANUAL_PROVIDER_SYNC",+ message = result.message,+ cause = result.exception)- syncManager.scheduleProviderSyncResume(providerId)- } else {- updateProviderSyncStatus(providerId, finalStatus, System.currentTimeMillis())- maybeScheduleBackgroundEpgSync(providerId)}- syncResult- }- is Result.Error -> {- updateProviderSyncStatus(providerId, ProviderStatus.ERROR)- syncResult+ is Result.Loading -> ProviderWorkflowOutcome.Failure(+ code = "MANUAL_PROVIDER_SYNC_LOADING",+ message = "Provider refresh did not reach a terminal state.",+ retryable = true+ )}+ }++ if (disposition == ProviderWorkflowDisposition.BUSY) {+ return Result.error("Provider refresh is already in progress.")+ }+ if (disposition == ProviderWorkflowDisposition.SUPERSEDED) {+ return Result.error("Provider refresh was superseded by a newer request.")+ }+ val terminalResult = syncResult ?: return when (disposition) {+ ProviderWorkflowDisposition.RETRY ->+ Result.error("Provider refresh was interrupted and will need to be retried.")+ ProviderWorkflowDisposition.FAILED ->+ Result.error("Provider refresh failed before synchronization started.")+ else -> Result.error("Provider refresh did not produce a result.")+ }++ return when (terminalResult) {+ is Result.Success -> terminalResult+ is Result.Error -> terminalResultis Result.Loading -> Result.error("Unexpected loading state")}}+ private suspend fun finalizeSuccessfulManualSync(providerId: Long) {+ var shouldResume = false+ var shouldScheduleEpg = false+ transactionRunner.inTransaction {+ providerWorkflowCommitFence.assertCanCommit(providerId)+ val finalStatus = if (syncManager.currentSyncState(providerId) is SyncState.Partial) {+ ProviderStatus.PARTIAL+ } else {+ ProviderStatus.ACTIVE+ }+ val provider = providerDao.getById(providerId)+ if (+ provider != null &&+ !hasUsableLiveCatalogForActivation(+ providerId,+ provider.type,+ channelDao,+ categoryDao,+ syncMetadataRepository+ )+ ) {+ updateProviderSyncStatus(+ providerId,+ ProviderStatus.PARTIAL,+ lastSyncedAt = System.currentTimeMillis(),+ isActive = false+ )+ shouldResume = true+ } else {+ updateProviderSyncStatus(providerId, finalStatus, System.currentTimeMillis())+ shouldScheduleEpg = true+ }+ }+ if (shouldResume) {+ syncManager.scheduleProviderSyncResume(providerId)+ } else if (shouldScheduleEpg) {+ maybeScheduleBackgroundEpgSync(providerId)+ }+ }+override suspend fun getProgramsForLiveStream(providerId: Long,streamId: Long,diff --git a/data/src/main/java/com/streamvault/data/sync/BackgroundEpgSyncWorker.kt b/data/src/main/java/com/streamvault/data/sync/BackgroundEpgSyncWorker.ktindex 5bb20b11..e4af904b 100644--- a/data/src/main/java/com/streamvault/data/sync/BackgroundEpgSyncWorker.kt+++ b/data/src/main/java/com/streamvault/data/sync/BackgroundEpgSyncWorker.kt@@ -7,12 +7,13 @@ import androidx.work.BackoffPolicyimport androidx.work.Constraintsimport androidx.work.CoroutineWorkerimport androidx.work.Data-import androidx.work.ExistingWorkPolicyimport androidx.work.NetworkTypeimport androidx.work.OneTimeWorkRequestBuilderimport androidx.work.WorkManagerimport androidx.work.WorkRequestimport androidx.work.WorkerParameters+import com.streamvault.data.local.entity.ProviderWorkflowPhase+import com.streamvault.data.local.entity.ProviderWorkflowReasonimport dagger.hilt.EntryPointimport dagger.hilt.InstallInimport dagger.hilt.android.EntryPointAccessors@@ -28,6 +29,7 @@ class BackgroundEpgSyncWorker(@InstallIn(SingletonComponent::class)interface BackgroundEpgSyncWorkerEntryPoint {fun syncManager(): SyncManager+ fun providerWorkflowRunner(): ProviderWorkflowRunner}override suspend fun doWork(): Result {@@ -52,31 +54,57 @@ class BackgroundEpgSyncWorker(applicationContext,BackgroundEpgSyncWorkerEntryPoint::class.java)- when (val result = entryPoint.syncManager().syncEpg(providerId, force = force)) {- is com.streamvault.domain.model.Result.Success -> {- // A successful EPG sync may still have transient partial failures- // (e.g. network hiccup on one provider section). Check the published- // sync state and retry if it signals a retryable EPG failure so- // WorkManager backoff can heal it without manual intervention.- val syncState = entryPoint.syncManager().currentSyncState(providerId)- if (syncState is com.streamvault.domain.model.SyncState.Partial &&- syncState.hasRetryableEpgFailure) {- Log.i(TAG, "Scheduling retry for provider $providerId: EPG completed with retryable failure")- Result.retry()- } else {- Result.success()+ when (+ entryPoint.providerWorkflowRunner().execute(+ providerId = providerId,+ phase = ProviderWorkflowPhase.EPG,+ reason = ProviderWorkflowReason.PERIODIC,+ force = force+ ) {+ when (val result = entryPoint.syncManager().syncEpg(providerId, force = force)) {+ is com.streamvault.domain.model.Result.Success -> {+ // A successful EPG sync may still have transient partial failures.+ val syncState = entryPoint.syncManager().currentSyncState(providerId)+ if (syncState is com.streamvault.domain.model.SyncState.Partial &&+ syncState.hasRetryableEpgFailure+ ) {+ Log.i(TAG, "Scheduling retry for provider $providerId: EPG completed with retryable failure")+ ProviderWorkflowOutcome.Failure(+ code = "EPG_PARTIAL_RETRYABLE",+ message = "EPG completed with a retryable partial failure.",+ retryable = true+ )+ } else {+ ProviderWorkflowOutcome.Success(+ partial = syncState is com.streamvault.domain.model.SyncState.Partial+ )+ }+ }+ is com.streamvault.domain.model.Result.Error -> {+ if (result.message.contains("not found", ignoreCase = true)) {+ ProviderWorkflowOutcome.Success()+ } else {+ ProviderWorkflowOutcome.Failure(+ code = "EPG_SYNC",+ message = result.message,+ cause = result.exception+ )+ }+ }+ com.streamvault.domain.model.Result.Loading ->+ ProviderWorkflowOutcome.Failure(+ code = "EPG_LOADING",+ message = "EPG operation did not reach a terminal state.",+ retryable = true+ )}}- is com.streamvault.domain.model.Result.Error -> {- if (result.message.contains("not found", ignoreCase = true)) {- Result.success()- } else if (shouldRetry(result.exception)) {- Result.retry()- } else {- Result.failure()- }- }- com.streamvault.domain.model.Result.Loading -> Result.retry()+ ) {+ ProviderWorkflowDisposition.SUCCEEDED,+ ProviderWorkflowDisposition.SUPERSEDED -> Result.success()+ ProviderWorkflowDisposition.RETRY,+ ProviderWorkflowDisposition.BUSY -> Result.retry()+ ProviderWorkflowDisposition.FAILED -> Result.failure()}} catch (cancelled: kotlinx.coroutines.CancellationException) {throw cancelled@@ -87,12 +115,7 @@ class BackgroundEpgSyncWorker(}private fun shouldRetry(error: Throwable?): Boolean {- return when (error) {- is java.io.IOException -> true- is SQLiteException -> error.message.orEmpty().contains("locked", ignoreCase = true) ||- error.message.orEmpty().contains("busy", ignoreCase = true)- else -> false- }+ return ProviderWorkFailureClassifier.isRetryable(error)}companion object {@@ -100,7 +123,6 @@ class BackgroundEpgSyncWorker(private const val KEY_PROVIDER_ID = "provider_id"private const val KEY_FORCE_REFRESH = "force_refresh"private const val INVALID_PROVIDER_ID = -1L- private const val UNIQUE_WORK_PREFIX = "background-epg-sync-"/*** Default delay before the first background EPG sync runs after enqueue. This* replaces the in-process [kotlinx.coroutines.delay] previously used by the@@ -137,10 +159,8 @@ class BackgroundEpgSyncWorker(.build()WorkManager.getInstance(context).enqueueUniqueWork(- uniqueWorkName(providerId),- // Force-refresh requests must displace any queued stale work so the new- // parameters (force=true) actually run; KEEP would silently drop them.- if (force) ExistingWorkPolicy.REPLACE else ExistingWorkPolicy.KEEP,+ providerWorkUniqueName(providerId),+ providerWorkExistingPolicy(supersede = false),request)}@@ -148,12 +168,11 @@ class BackgroundEpgSyncWorker(fun cancel(context: Context, providerId: Long) {if (providerId <= 0L) returnrunCatching {- WorkManager.getInstance(context).cancelUniqueWork(uniqueWorkName(providerId))+ WorkManager.getInstance(context).cancelUniqueWork(providerWorkUniqueName(providerId))}.onFailure { error ->Log.w(TAG, "Skipping background EPG cancellation for provider $providerId", error)}}- private fun uniqueWorkName(providerId: Long): String = "$UNIQUE_WORK_PREFIX$providerId"}}diff --git a/data/src/main/java/com/streamvault/data/sync/ContentCachePolicy.kt b/data/src/main/java/com/streamvault/data/sync/ContentCachePolicy.ktindex 0c9ed689..c1eed865 100644--- a/data/src/main/java/com/streamvault/data/sync/ContentCachePolicy.kt+++ b/data/src/main/java/com/streamvault/data/sync/ContentCachePolicy.kt@@ -1,13 +1,12 @@package com.streamvault.data.sync+import com.streamvault.domain.util.PersistedTimestampPolicy+object ContentCachePolicy {const val CATALOG_TTL_MILLIS = 24L * 60 * 60 * 1000Lconst val SERIES_CATEGORY_TTL_MILLIS = 6L * 60 * 60 * 1000Lconst val EPG_TTL_MILLIS = 6L * 60 * 60 * 1000L- fun shouldRefresh(lastSyncAt: Long, ttlMillis: Long, now: Long = System.currentTimeMillis()): Boolean {- if (lastSyncAt <= 0L) return true- val elapsed = now - lastSyncAt- return elapsed < 0L || elapsed >= ttlMillis- }+ fun shouldRefresh(lastSyncAt: Long, ttlMillis: Long, now: Long = System.currentTimeMillis()): Boolean =+ !PersistedTimestampPolicy.isFresh(lastSyncAt, now, ttlMillis)}diff --git a/data/src/main/java/com/streamvault/data/sync/ProviderSyncStateReaderImpl.kt b/data/src/main/java/com/streamvault/data/sync/ProviderSyncStateReaderImpl.ktindex 2b3e4371..a4e7bb84 100644--- a/data/src/main/java/com/streamvault/data/sync/ProviderSyncStateReaderImpl.kt+++ b/data/src/main/java/com/streamvault/data/sync/ProviderSyncStateReaderImpl.kt@@ -1,25 +1,45 @@package com.streamvault.data.syncimport com.streamvault.data.local.dao.XtreamIndexJobDao+import com.streamvault.data.local.dao.ProviderWorkflowDao+import com.streamvault.data.local.entity.ProviderWorkflowPhase+import com.streamvault.data.local.entity.ProviderWorkflowStateimport com.streamvault.domain.manager.ProviderSyncStateReaderimport com.streamvault.domain.model.SyncStateimport javax.inject.Injectimport javax.inject.Singletonimport kotlinx.coroutines.flow.Flowimport kotlinx.coroutines.flow.map+import kotlinx.coroutines.flow.combine@Singletonclass ProviderSyncStateReaderImpl @Inject constructor(private val syncManager: SyncManager,- private val xtreamIndexJobDao: XtreamIndexJobDao+ private val xtreamIndexJobDao: XtreamIndexJobDao,+ private val providerWorkflowDao: ProviderWorkflowDao) : ProviderSyncStateReader {override fun currentSyncState(providerId: Long): SyncState = syncManager.currentSyncState(providerId)override fun observeBackgroundIndexingActive(providerId: Long): Flow<Boolean> =- xtreamIndexJobDao.observeForProvider(providerId).map { jobs ->- jobs.any { job ->+ combine(+ xtreamIndexJobDao.observeForProvider(providerId),+ providerWorkflowDao.observeWorkflow(providerId),+ providerWorkflowDao.observeActivePhases(providerId)+ ) { jobs, workflow, activePhases ->+ val legacyIndexActive = jobs.any { job ->job.section in setOf("MOVIE", "SERIES") &&job.state in setOf("QUEUED", "RUNNING", "PARTIAL", "STALE", "FAILED_RETRYABLE")}+ val workflowIndexActive = workflow?.let {+ it.state in setOf(ProviderWorkflowState.PENDING, ProviderWorkflowState.RUNNING) &&+ activePhases.any { phase ->+ phase in setOf(+ ProviderWorkflowPhase.CONTENT_INDEX,+ ProviderWorkflowPhase.MOVIE_INDEX,+ ProviderWorkflowPhase.SERIES_INDEX+ )+ }+ } == true+ legacyIndexActive || workflowIndexActive}}diff --git a/data/src/main/java/com/streamvault/data/sync/ProviderSyncWorker.kt b/data/src/main/java/com/streamvault/data/sync/ProviderSyncWorker.ktindex 02531af0..04bd4501 100644--- a/data/src/main/java/com/streamvault/data/sync/ProviderSyncWorker.kt+++ b/data/src/main/java/com/streamvault/data/sync/ProviderSyncWorker.kt@@ -15,17 +15,28 @@ import androidx.work.WorkManagerimport androidx.work.WorkRequestimport androidx.work.WorkerParametersimport androidx.work.workDataOf+import com.google.gson.Gsonimport com.streamvault.data.local.dao.ProviderDao+import com.streamvault.data.local.dao.ProviderConfigRevisionDaoimport com.streamvault.data.local.dao.ChannelDaoimport com.streamvault.data.local.dao.CategoryDaoimport com.streamvault.data.local.dao.XtreamIndexJobDaoimport com.streamvault.data.local.dao.XtreamLiveOnboardingDao+import com.streamvault.data.local.DatabaseTransactionRunner+import com.streamvault.data.local.entity.ProviderConfigRevisionState+import com.streamvault.data.local.entity.ProviderEntity+import com.streamvault.data.local.entity.ProviderWorkflowPhase+import com.streamvault.data.local.entity.ProviderWorkflowReason+import com.streamvault.data.local.entity.XtreamIndexJobEntity+import com.streamvault.data.mapper.toDomain+import com.streamvault.data.security.CredentialCryptoimport com.streamvault.domain.model.ProviderStatusimport com.streamvault.domain.model.ContentTypeimport com.streamvault.domain.model.ProviderEpgSyncModeimport com.streamvault.domain.model.ProviderTypeimport com.streamvault.domain.model.SyncStateimport com.streamvault.domain.repository.SyncMetadataRepository+import com.streamvault.domain.util.PersistedTimestampPolicyimport dagger.hilt.EntryPointimport dagger.hilt.InstallInimport dagger.hilt.android.EntryPointAccessors@@ -86,7 +97,21 @@ internal fun isFreshRunningIndexJob(updatedAt: Long,now: Long,staleAfterMillis: Long-): Boolean = updatedAt <= now && now - updatedAt < staleAfterMillis+): Boolean = PersistedTimestampPolicy.isFresh(updatedAt, now, staleAfterMillis)++internal fun shouldRunPersistedIndexJob(+ job: XtreamIndexJobEntity?,+ now: Long,+ staleRunningAfterMillis: Long,+ successTtlMillis: Long+): Boolean {+ if (job == null) return true+ if (job.state in setOf("QUEUED", "PARTIAL", "STALE", "FAILED_RETRYABLE")) return true+ if (job.state == "RUNNING") {+ return !isFreshRunningIndexJob(job.updatedAt, now, staleRunningAfterMillis)+ }+ return ContentCachePolicy.shouldRefresh(job.lastSuccessAt, successTtlMillis, now)+}internal suspend fun shouldTrackInitialLiveOnboarding(provider: com.streamvault.data.local.entity.ProviderEntity,@@ -107,8 +132,14 @@ class ProviderSyncWorker(fun categoryDao(): CategoryDaofun syncManager(): SyncManagerfun syncMetadataRepository(): SyncMetadataRepository+ fun providerConfigRevisionDao(): ProviderConfigRevisionDao+ fun credentialCrypto(): CredentialCrypto+ fun gson(): Gsonfun xtreamIndexJobDao(): XtreamIndexJobDaofun xtreamLiveOnboardingDao(): XtreamLiveOnboardingDao+ fun providerWorkflowRunner(): ProviderWorkflowRunner+ fun providerWorkflowCommitFence(): ProviderWorkflowCommitFence+ fun databaseTransactionRunner(): DatabaseTransactionRunner}override suspend fun doWork(): Result {@@ -118,49 +149,113 @@ class ProviderSyncWorker(ProviderSyncWorkerEntryPoint::class.java)val requestedProviderId = inputData.getLong(KEY_PROVIDER_ID, INVALID_PROVIDER_ID)+ val requestedRevision = inputData.getLong(KEY_PROVIDER_CONFIG_REVISION, INVALID_REVISION)+ if (requestedRevision != INVALID_REVISION) {+ return runConfigRevisionWorkflow(+ entryPoint,+ requestedProviderId,+ requestedRevision+ ).toWorkResult()+ }++ var sawRetryableFailure = false+ val recoveryNow = System.currentTimeMillis()+ val staleSyncingBefore = recoveryNow - STALE_CONFIG_SYNC_MILLIS+ val revisionDao = entryPoint.providerConfigRevisionDao()+ // Never run the committed configuration while a newer edit is being recovered.+ // That would turn a recovery attempt into an implicit fallback to the old settings.+ val providerIdsWithPendingEdits = revisionDao.getRecoverable()+ .mapTo(mutableSetOf()) { it.providerId }+ revisionDao+ .getRecoveryCandidates(recoveryNow, staleSyncingBefore)+ .forEach { revision ->+ when (+ runConfigRevisionWorkflow(+ entryPoint,+ revision.providerId,+ revision.revision+ )+ ) {+ ProviderWorkflowDisposition.RETRY,+ ProviderWorkflowDisposition.BUSY -> sawRetryableFailure = true+ else -> Unit+ }+ }+val providers = if (requestedProviderId != INVALID_PROVIDER_ID) {entryPoint.providerDao().getById(requestedProviderId)?.let(::listOf).orEmpty()} else {entryPoint.providerDao().getAllSync()}if (providers.isEmpty()) {- return Result.success()+ return if (sawRetryableFailure) Result.retry() else Result.success()}- var sawRetryableFailure = false- providers.forEach { provider ->- val trackInitialLiveOnboarding = shouldTrackInitialLiveOnboarding(- provider = provider,- onboardingDao = entryPoint.xtreamLiveOnboardingDao()- )- val result = if (requestedProviderId == provider.id) {- entryPoint.syncManager().sync(- provider.id,- force = false,- trackInitialLiveOnboarding = trackInitialLiveOnboarding+ var sawPermanentFailure = false+ providers.filterNot { it.id in providerIdsWithPendingEdits }.forEach { provider ->+ val disposition = entryPoint.providerWorkflowRunner().execute(+ providerId = provider.id,+ phase = ProviderWorkflowPhase.PRIMARY_CATALOG,+ reason = if (requestedProviderId == provider.id) {+ ProviderWorkflowReason.RECOVERY+ } else {+ ProviderWorkflowReason.PERIODIC+ }+ ) {+ val trackInitialLiveOnboarding = shouldTrackInitialLiveOnboarding(+ provider = provider,+ onboardingDao = entryPoint.xtreamLiveOnboardingDao())- } else if (provider.type == ProviderType.XTREAM_CODES) {- syncXtreamProviderIfStale(entryPoint, provider)- } else if (provider.type == ProviderType.STALKER_PORTAL) {- syncStalkerProviderIfStale(entryPoint, provider)- } else {- entryPoint.syncManager().sync(provider.id, force = false)- }- if (requestedProviderId == provider.id) {- reconcileTargetedProviderStatus(entryPoint, provider, result)- }- when (result) {- is com.streamvault.domain.model.Result.Error -> {- Log.w(TAG, "Provider sync worker failed for provider ${provider.id}: ${result.message}")- if (shouldRetry(result.exception)) {- sawRetryableFailure = true+ val result = if (requestedProviderId == provider.id) {+ entryPoint.syncManager().sync(+ provider.id,+ force = false,+ trackInitialLiveOnboarding = trackInitialLiveOnboarding+ )+ } else if (provider.type == ProviderType.XTREAM_CODES) {+ syncXtreamProviderIfStale(entryPoint, provider)+ } else if (provider.type == ProviderType.STALKER_PORTAL) {+ syncStalkerProviderIfStale(entryPoint, provider)+ } else {+ entryPoint.syncManager().sync(provider.id, force = false)+ }+ if (requestedProviderId == provider.id) {+ reconcileTargetedProviderStatusFenced(entryPoint, provider, result)+ }+ when (result) {+ is com.streamvault.domain.model.Result.Success ->+ ProviderWorkflowOutcome.Success(+ partial = entryPoint.syncManager().currentSyncState(provider.id) is SyncState.Partial+ )+ is com.streamvault.domain.model.Result.Error -> {+ Log.w(TAG, "Provider sync worker failed for provider ${provider.id}: ${result.message}")+ ProviderWorkflowOutcome.Failure(+ code = "PROVIDER_SYNC",+ message = result.message,+ cause = result.exception+ )}+ com.streamvault.domain.model.Result.Loading ->+ ProviderWorkflowOutcome.Failure(+ code = "PROVIDER_SYNC_LOADING",+ message = "Provider sync did not reach a terminal state.",+ retryable = true+ )}+ }+ when (disposition) {+ ProviderWorkflowDisposition.RETRY,+ ProviderWorkflowDisposition.BUSY -> sawRetryableFailure = true+ ProviderWorkflowDisposition.FAILED -> sawPermanentFailure = trueelse -> Unit}}- if (sawRetryableFailure) Result.retry() else Result.success()+ when {+ sawRetryableFailure -> Result.retry()+ sawPermanentFailure -> Result.failure()+ else -> Result.success()+ }} catch (cancelled: kotlinx.coroutines.CancellationException) {throw cancelled} catch (e: Exception) {@@ -170,11 +265,180 @@ class ProviderSyncWorker(}private fun shouldRetry(error: Throwable?): Boolean {- return when (error) {- is java.io.IOException -> true- is SQLiteException -> error.message.orEmpty().contains("locked", ignoreCase = true) ||- error.message.orEmpty().contains("busy", ignoreCase = true)- else -> false+ return ProviderWorkFailureClassifier.isRetryable(error)+ }++ private fun ProviderWorkflowDisposition.toWorkResult(): Result = when (this) {+ ProviderWorkflowDisposition.SUCCEEDED,+ ProviderWorkflowDisposition.SUPERSEDED -> Result.success()+ ProviderWorkflowDisposition.RETRY,+ ProviderWorkflowDisposition.BUSY -> Result.retry()+ ProviderWorkflowDisposition.FAILED -> Result.failure()+ }++ private suspend fun runConfigRevisionWorkflow(+ entryPoint: ProviderSyncWorkerEntryPoint,+ providerId: Long,+ revisionNumber: Long+ ): ProviderWorkflowDisposition {+ if (providerId == INVALID_PROVIDER_ID) {+ return ProviderWorkflowDisposition.FAILED+ }+ return entryPoint.providerWorkflowRunner().execute(+ providerId = providerId,+ phase = ProviderWorkflowPhase.PREPARE,+ reason = ProviderWorkflowReason.CONFIG_CHANGE,+ force = true,+ supersede = true,+ priority = CONFIG_CHANGE_PRIORITY+ ) {+ when (recoverProviderConfigRevision(entryPoint, providerId, revisionNumber)) {+ RevisionRecoveryOutcome.SUCCESS -> ProviderWorkflowOutcome.Success()+ RevisionRecoveryOutcome.RETRY -> ProviderWorkflowOutcome.Failure(+ code = "CONFIG_REVISION_RETRY",+ message = "Provider configuration recovery needs retry.",+ retryable = true+ )+ RevisionRecoveryOutcome.FAILURE -> ProviderWorkflowOutcome.Failure(+ code = "CONFIG_REVISION_FAILED",+ message = "Provider configuration recovery failed.",+ retryable = false+ )+ }+ }+ }++ private suspend fun reconcileTargetedProviderStatusFenced(+ entryPoint: ProviderSyncWorkerEntryPoint,+ provider: ProviderEntity,+ result: com.streamvault.domain.model.Result<Unit>+ ) {+ entryPoint.databaseTransactionRunner().inTransaction {+ entryPoint.providerWorkflowCommitFence().assertCanCommit(provider.id)+ reconcileTargetedProviderStatus(entryPoint, provider, result)+ }+ }++ /**+ * Restarts only the durable candidate configuration. It never feeds the committed provider+ * row back into the sync pipeline, so a process restart cannot silently discard an edit.+ */+ private suspend fun recoverProviderConfigRevision(+ entryPoint: ProviderSyncWorkerEntryPoint,+ providerId: Long,+ revisionNumber: Long+ ): RevisionRecoveryOutcome {+ if (providerId == INVALID_PROVIDER_ID) return RevisionRecoveryOutcome.SUCCESS+ val revisionDao = entryPoint.providerConfigRevisionDao()+ val revision = revisionDao.get(providerId, revisionNumber) ?: return RevisionRecoveryOutcome.SUCCESS+ if (revision.state == ProviderConfigRevisionState.COMMITTED ||+ revision.state == ProviderConfigRevisionState.SUPERSEDED+ ) {+ return RevisionRecoveryOutcome.SUCCESS+ }++ val now = System.currentTimeMillis()+ if (revision.state == ProviderConfigRevisionState.SYNCING) {+ revisionDao.releaseForRetry(providerId, revisionNumber, now)+ }+ if (revisionDao.claimForSync(providerId, revisionNumber, now) != 1) {+ return RevisionRecoveryOutcome.SUCCESS+ }++ val secureCandidate = try {+ entryPoint.gson().fromJson(revision.configJson, ProviderEntity::class.java)+ ?: throw IllegalStateException("Saved provider edit was empty.")+ } catch (error: Exception) {+ revisionDao.markFailed(providerId, revisionNumber, "Saved provider edit is invalid.", now)+ return RevisionRecoveryOutcome.FAILURE+ }+ if (secureCandidate.id != providerId) {+ revisionDao.markFailed(providerId, revisionNumber, "Saved provider edit did not match its provider.", now)+ return RevisionRecoveryOutcome.FAILURE+ }++ val candidate = try {+ secureCandidate+ .copy(password = entryPoint.credentialCrypto().decryptIfNeeded(secureCandidate.password))+ .toDomain()+ } catch (error: Exception) {+ revisionDao.markFailed(providerId, revisionNumber, "Saved provider credentials could not be restored.", now)+ return RevisionRecoveryOutcome.FAILURE+ }++ val result = entryPoint.syncManager().syncWithProviderOverride(+ providerId = providerId,+ force = false,+ providerOverride = candidate,+ afterCatalogApply = {+ val committedAt = System.currentTimeMillis()+ check(revisionDao.markCommitted(providerId, revisionNumber, committedAt) == 1) {+ "Provider edit was superseded before recovery could commit it."+ }+ entryPoint.providerDao().update(+ secureCandidate.copy(+ isActive = true,+ status = ProviderStatus.PARTIAL,+ lastSyncedAt = committedAt+ )+ )+ }+ )+ val finalState = revisionDao.getState(providerId, revisionNumber)+ return when (result) {+ is com.streamvault.domain.model.Result.Success -> {+ if (finalState != ProviderConfigRevisionState.COMMITTED) {+ revisionDao.markFailed(+ providerId,+ revisionNumber,+ "Recovery sync completed without committing catalog content.",+ System.currentTimeMillis()+ )+ RevisionRecoveryOutcome.FAILURE+ } else {+ entryPoint.providerDao().getById(providerId)?.let { committedProvider ->+ reconcileTargetedProviderStatusFenced(entryPoint, committedProvider, result)+ }+ RevisionRecoveryOutcome.SUCCESS+ }+ }+ is com.streamvault.domain.model.Result.Error -> {+ if (finalState == ProviderConfigRevisionState.COMMITTED) {+ entryPoint.providerDao().getById(providerId)?.let { committedProvider ->+ entryPoint.databaseTransactionRunner().inTransaction {+ entryPoint.providerWorkflowCommitFence().assertCanCommit(providerId)+ entryPoint.providerDao().update(+ committedProvider.copy(isActive = true, status = ProviderStatus.PARTIAL)+ )+ }+ }+ } else {+ revisionDao.markFailed(+ providerId,+ revisionNumber,+ result.message,+ System.currentTimeMillis()+ )+ }+ if (shouldRetry(result.exception)) {+ RevisionRecoveryOutcome.RETRY+ } else {+ RevisionRecoveryOutcome.FAILURE+ }+ }+ is com.streamvault.domain.model.Result.Loading -> RevisionRecoveryOutcome.RETRY+ }+ }++ private enum class RevisionRecoveryOutcome {+ SUCCESS,+ RETRY,+ FAILURE;++ fun toWorkResult(): Result = when (this) {+ SUCCESS -> Result.success()+ RETRY -> Result.retry()+ FAILURE -> Result.failure()}}@@ -183,9 +447,13 @@ class ProviderSyncWorker(private const val STALE_RUNNING_JOB_MILLIS = 15 * 60 * 1000Lprivate const val UNIQUE_WORK_NAME = "provider-sync-worker"private const val UNIQUE_LAUNCH_STALE_WORK_NAME = "provider-sync-launch-stale-check"- private const val UNIQUE_PROVIDER_WORK_PREFIX = "provider-sync-provider-"private const val KEY_PROVIDER_ID = "provider_id"+ private const val KEY_PROVIDER_CONFIG_REVISION = "provider_config_revision"private const val INVALID_PROVIDER_ID = -1L+ private const val INVALID_REVISION = -1L+ private const val STALE_CONFIG_SYNC_MILLIS = 60_000L+ private const val CONFIG_REVISION_RECOVERY_GRACE_MILLIS = 5 * 60 * 1000L+ private const val CONFIG_CHANGE_PRIORITY = 100fun enqueuePeriodic(context: Context) {val request = PeriodicWorkRequestBuilder<ProviderSyncWorker>(6, TimeUnit.HOURS)@@ -249,8 +517,45 @@ class ProviderSyncWorker(.build()WorkManager.getInstance(context).enqueueUniqueWork(- UNIQUE_PROVIDER_WORK_PREFIX + providerId,- ExistingWorkPolicy.REPLACE,+ providerWorkUniqueName(providerId),+ providerWorkExistingPolicy(supersede = false),+ request+ )+ }++ fun enqueueProviderConfigRevision(+ context: Context,+ providerId: Long,+ revision: Long,+ immediate: Boolean = true+ ) {+ val request = OneTimeWorkRequestBuilder<ProviderSyncWorker>()+ .setInputData(+ workDataOf(+ KEY_PROVIDER_ID to providerId,+ KEY_PROVIDER_CONFIG_REVISION to revision+ )+ )+ .setConstraints(+ Constraints.Builder()+ .setRequiredNetworkType(NetworkType.CONNECTED)+ .setRequiresBatteryNotLow(true)+ .build()+ )+ .setInitialDelay(+ if (immediate) 0 else CONFIG_REVISION_RECOVERY_GRACE_MILLIS,+ TimeUnit.MILLISECONDS+ )+ .setBackoffCriteria(+ BackoffPolicy.EXPONENTIAL,+ WorkRequest.MIN_BACKOFF_MILLIS,+ TimeUnit.MILLISECONDS+ )+ .build()++ WorkManager.getInstance(context).enqueueUniqueWork(+ providerWorkUniqueName(providerId),+ providerWorkExistingPolicy(supersede = true),request)}@@ -318,10 +623,12 @@ class ProviderSyncWorker(section: ContentType,now: Long): Boolean {- val job = entryPoint.xtreamIndexJobDao().get(providerId, section.name) ?: return true- if (job.state in setOf("QUEUED", "PARTIAL", "STALE", "FAILED_RETRYABLE")) return true- if (job.state == "RUNNING" && isFreshRunningIndexJob(job.updatedAt, now, STALE_RUNNING_JOB_MILLIS)) return false- return ContentCachePolicy.shouldRefresh(job.lastSuccessAt, ContentCachePolicy.CATALOG_TTL_MILLIS, now)+ return shouldRunPersistedIndexJob(+ job = entryPoint.xtreamIndexJobDao().get(providerId, section.name),+ now = now,+ staleRunningAfterMillis = STALE_RUNNING_JOB_MILLIS,+ successTtlMillis = ContentCachePolicy.CATALOG_TTL_MILLIS+ )}private suspend fun syncStalkerProviderIfStale(diff --git a/data/src/main/java/com/streamvault/data/sync/ProviderWorkLockRegistry.kt b/data/src/main/java/com/streamvault/data/sync/ProviderWorkLockRegistry.ktnew file mode 100644index 00000000..3b1ccd55--- /dev/null+++ b/data/src/main/java/com/streamvault/data/sync/ProviderWorkLockRegistry.kt@@ -0,0 +1,42 @@+package com.streamvault.data.sync++import java.util.concurrent.ConcurrentHashMap+import java.util.concurrent.atomic.AtomicInteger+import kotlinx.coroutines.sync.Mutex+import kotlinx.coroutines.sync.withLock++/**+ * Provides one in-process execution lane per provider, regardless of whether work originated+ * from foreground refresh, catalog indexing, EPG, or a WorkManager recovery entry point.+ */+internal class ProviderWorkLockRegistry {+ private val admissionMutex = Mutex()+ private val providerMutexes = ConcurrentHashMap<Long, Mutex>()+ private val admittedCount = AtomicInteger(0)++ fun isAnyWorkActiveOrWaiting(): Boolean = admittedCount.get() > 0++ suspend fun <T> withProviderLock(providerId: Long, block: suspend () -> T): T {+ require(providerId > 0L) { "Provider work requires a positive provider ID." }+ val providerMutex = admissionMutex.withLock {+ admittedCount.incrementAndGet()+ providerMutexes.computeIfAbsent(providerId) { Mutex() }+ }+ return try {+ providerMutex.withLock { block() }+ } finally {+ admissionMutex.withLock {+ admittedCount.decrementAndGet()+ }+ }+ }++ suspend fun runWhenNoWorkActive(block: suspend () -> Boolean): Boolean =+ admissionMutex.withLock {+ if (admittedCount.get() > 0) {+ false+ } else {+ block()+ }+ }+}diff --git a/data/src/main/java/com/streamvault/data/sync/ProviderWorkScheduling.kt b/data/src/main/java/com/streamvault/data/sync/ProviderWorkScheduling.ktnew file mode 100644index 00000000..24752987--- /dev/null+++ b/data/src/main/java/com/streamvault/data/sync/ProviderWorkScheduling.kt@@ -0,0 +1,17 @@+package com.streamvault.data.sync++import androidx.work.ExistingWorkPolicy++private const val PROVIDER_WORK_UNIQUE_PREFIX = "provider-workflow-"++internal fun providerWorkUniqueName(providerId: Long): String {+ require(providerId > 0L) { "Provider work requires a positive provider ID." }+ return PROVIDER_WORK_UNIQUE_PREFIX + providerId+}++internal fun providerWorkExistingPolicy(supersede: Boolean): ExistingWorkPolicy =+ if (supersede) {+ ExistingWorkPolicy.REPLACE+ } else {+ ExistingWorkPolicy.APPEND_OR_REPLACE+ }diff --git a/data/src/main/java/com/streamvault/data/sync/ProviderWorkflowCommitFence.kt b/data/src/main/java/com/streamvault/data/sync/ProviderWorkflowCommitFence.ktnew file mode 100644index 00000000..21210c69--- /dev/null+++ b/data/src/main/java/com/streamvault/data/sync/ProviderWorkflowCommitFence.kt@@ -0,0 +1,52 @@+package com.streamvault.data.sync++import com.streamvault.data.local.dao.ProviderWorkflowDao+import com.streamvault.data.local.dao.ProviderWorkflowLease+import javax.inject.Inject+import javax.inject.Singleton+import kotlin.coroutines.AbstractCoroutineContextElement+import kotlin.coroutines.CoroutineContext+import kotlin.coroutines.coroutineContext++/**+ * Lease propagated through the sync coroutine so catalog commits can prove they still belong to+ * the generation that fetched and staged the data.+ */+class ProviderWorkflowExecutionContext(+ val lease: ProviderWorkflowLease+) : AbstractCoroutineContextElement(Key) {+ companion object Key : CoroutineContext.Key<ProviderWorkflowExecutionContext>+}++class ProviderWorkflowSupersededException(+ providerId: Long,+ generation: Long+) : IllegalStateException(+ "Provider $providerId workflow generation $generation was superseded before catalog commit."+)++/**+ * Checks workflow ownership from inside the same Room transaction that applies staged catalog+ * rows. If supersession commits first, this check rejects the old apply. If this transaction+ * begins first, Room serialization makes supersession wait until its coherent commit completes.+ */+@Singleton+class ProviderWorkflowCommitFence @Inject constructor(+ private val workflowDao: ProviderWorkflowDao? = null+) {+ suspend fun assertCanCommit(providerId: Long) {+ val execution = coroutineContext[ProviderWorkflowExecutionContext] ?: return+ val lease = execution.lease+ if (+ lease.providerId != providerId ||+ workflowDao?.isCurrentOwner(+ providerId = providerId,+ generation = lease.generation,+ phase = lease.phase,+ token = lease.token+ ) != 1+ ) {+ throw ProviderWorkflowSupersededException(providerId, lease.generation)+ }+ }+}diff --git a/data/src/main/java/com/streamvault/data/sync/ProviderWorkflowRunner.kt b/data/src/main/java/com/streamvault/data/sync/ProviderWorkflowRunner.ktnew file mode 100644index 00000000..8f585fbd--- /dev/null+++ b/data/src/main/java/com/streamvault/data/sync/ProviderWorkflowRunner.kt@@ -0,0 +1,194 @@+package com.streamvault.data.sync++import android.database.sqlite.SQLiteException+import com.streamvault.data.local.dao.ProviderWorkflowDao+import com.streamvault.data.local.dao.ProviderWorkflowLease+import com.streamvault.data.local.entity.ProviderWorkflowPhase+import com.streamvault.data.local.entity.ProviderWorkflowReason+import java.io.IOException+import java.util.UUID+import javax.inject.Inject+import javax.inject.Singleton+import kotlinx.coroutines.CancellationException+import kotlinx.coroutines.NonCancellable+import kotlinx.coroutines.cancelAndJoin+import kotlinx.coroutines.coroutineScope+import kotlinx.coroutines.delay+import kotlinx.coroutines.launch+import kotlinx.coroutines.withContext++sealed interface ProviderWorkflowOutcome {+ data class Success(+ val checkpoint: String? = null,+ val partial: Boolean = false+ ) : ProviderWorkflowOutcome++ data class Failure(+ val code: String,+ val message: String?,+ val cause: Throwable? = null,+ val retryable: Boolean = ProviderWorkFailureClassifier.isRetryable(cause)+ ) : ProviderWorkflowOutcome+}++enum class ProviderWorkflowDisposition {+ SUCCEEDED,+ RETRY,+ FAILED,+ BUSY,+ SUPERSEDED+}++object ProviderWorkFailureClassifier {+ fun isRetryable(error: Throwable?): Boolean = when (error) {+ is IOException -> true+ is SQLiteException -> error.message.orEmpty().contains("locked", ignoreCase = true) ||+ error.message.orEmpty().contains("busy", ignoreCase = true)+ else -> false+ }+}++/**+ * Executes one provider phase while maintaining its persisted lease.+ *+ * The Room generation/token checks are the authority. WorkManager uniqueness and the in-process+ * mutex remain useful admission controls, but neither is relied on to prove ownership.+ */+@Singleton+class ProviderWorkflowRunner @Inject constructor(+ private val workflowDao: ProviderWorkflowDao+) {+ suspend fun execute(+ providerId: Long,+ phase: ProviderWorkflowPhase,+ reason: ProviderWorkflowReason,+ force: Boolean = false,+ supersede: Boolean = false,+ priority: Int = 0,+ block: suspend () -> ProviderWorkflowOutcome+ ): ProviderWorkflowDisposition {+ val requestedAt = System.currentTimeMillis()+ val ticket = workflowDao.request(+ providerId = providerId,+ phase = phase,+ reason = reason,+ now = requestedAt,+ supersede = supersede,+ priority = priority,+ force = force+ )+ val lease = workflowDao.claim(+ ticket = ticket,+ token = UUID.randomUUID().toString(),+ now = requestedAt,+ leaseDurationMs = LEASE_DURATION_MILLIS,+ staleHeartbeatBefore = requestedAt - STALE_HEARTBEAT_MILLIS+ ) ?: return ProviderWorkflowDisposition.BUSY++ return try {+ val outcome = withContext(ProviderWorkflowExecutionContext(lease)) {+ runWithHeartbeat(lease, block)+ }+ publishOutcome(lease, outcome)+ } catch (lost: ProviderWorkflowLeaseLostException) {+ ProviderWorkflowDisposition.SUPERSEDED+ } catch (cancelled: CancellationException) {+ withContext(NonCancellable) {+ workflowDao.fail(+ lease = lease,+ now = System.currentTimeMillis(),+ errorCode = "CANCELLED",+ errorMessage = "Worker cancelled before the phase completed.",+ retryable = true+ )+ }+ throw cancelled+ } catch (error: Exception) {+ publishOutcome(+ lease,+ ProviderWorkflowOutcome.Failure(+ code = error::class.java.simpleName.ifBlank { "UNEXPECTED" },+ message = error.message,+ cause = error+ )+ )+ }+ }++ private suspend fun runWithHeartbeat(+ lease: ProviderWorkflowLease,+ block: suspend () -> ProviderWorkflowOutcome+ ): ProviderWorkflowOutcome = coroutineScope {+ val heartbeat = launch {+ while (true) {+ delay(HEARTBEAT_INTERVAL_MILLIS)+ val now = System.currentTimeMillis()+ if (+ workflowDao.renewLease(+ providerId = lease.providerId,+ generation = lease.generation,+ phase = lease.phase,+ token = lease.token,+ now = now,+ expiresAt = now + LEASE_DURATION_MILLIS+ ) != 1+ ) {+ throw ProviderWorkflowLeaseLostException()+ }+ }+ }+ try {+ block()+ } finally {+ heartbeat.cancelAndJoin()+ }+ }++ private suspend fun publishOutcome(+ lease: ProviderWorkflowLease,+ outcome: ProviderWorkflowOutcome+ ): ProviderWorkflowDisposition {+ val now = System.currentTimeMillis()+ return when (outcome) {+ is ProviderWorkflowOutcome.Success -> {+ if (+ workflowDao.complete(+ lease = lease,+ now = now,+ checkpoint = outcome.checkpoint,+ partial = outcome.partial+ )+ ) {+ ProviderWorkflowDisposition.SUCCEEDED+ } else {+ ProviderWorkflowDisposition.SUPERSEDED+ }+ }++ is ProviderWorkflowOutcome.Failure -> {+ val published = workflowDao.fail(+ lease = lease,+ now = now,+ errorCode = outcome.code,+ errorMessage = outcome.message,+ retryable = outcome.retryable+ )+ when {+ !published -> ProviderWorkflowDisposition.SUPERSEDED+ outcome.retryable -> ProviderWorkflowDisposition.RETRY+ else -> ProviderWorkflowDisposition.FAILED+ }+ }+ }+ }++ private class ProviderWorkflowLeaseLostException : IllegalStateException(+ "Provider workflow lease was superseded or reclaimed."+ )++ private companion object {+ const val HEARTBEAT_INTERVAL_MILLIS = 30_000L+ const val LEASE_DURATION_MILLIS = 2 * 60_000L+ const val STALE_HEARTBEAT_MILLIS = 2 * 60_000L+ }+}diff --git a/data/src/main/java/com/streamvault/data/sync/StalkerIndexWorker.kt b/data/src/main/java/com/streamvault/data/sync/StalkerIndexWorker.ktindex 2d049be3..4ac4b459 100644--- a/data/src/main/java/com/streamvault/data/sync/StalkerIndexWorker.kt+++ b/data/src/main/java/com/streamvault/data/sync/StalkerIndexWorker.kt@@ -7,13 +7,14 @@ import androidx.work.BackoffPolicyimport androidx.work.Constraintsimport androidx.work.CoroutineWorkerimport androidx.work.Data-import androidx.work.ExistingWorkPolicyimport androidx.work.NetworkTypeimport androidx.work.OneTimeWorkRequestBuilderimport androidx.work.WorkManagerimport androidx.work.WorkRequestimport androidx.work.WorkerParametersimport com.streamvault.data.local.dao.ProviderDao+import com.streamvault.data.local.entity.ProviderWorkflowPhase+import com.streamvault.data.local.entity.ProviderWorkflowReasonimport com.streamvault.domain.model.ContentTypeimport com.streamvault.domain.model.ProviderTypeimport dagger.hilt.EntryPoint@@ -33,6 +34,7 @@ class StalkerIndexWorker(interface StalkerIndexWorkerEntryPoint {fun providerDao(): ProviderDaofun syncManager(): SyncManager+ fun providerWorkflowRunner(): ProviderWorkflowRunner}override suspend fun doWork(): Result {@@ -58,26 +60,53 @@ class StalkerIndexWorker(}var sawRetryableFailure = false+ var sawPermanentFailure = falseproviders.filter { provider -> provider.type == ProviderType.STALKER_PORTAL }.forEach { provider ->- when (val result = entryPoint.syncManager().processQueuedStalkerIndexJobs(+ val disposition = entryPoint.providerWorkflowRunner().execute(providerId = provider.id,- section = requestedSection,- force = force,- maxCategoriesPerSection = CATEGORY_SLICE_SIZE- )) {- is com.streamvault.domain.model.Result.Error -> {- Log.w(TAG, "Stalker index worker failed for provider ${provider.id}: ${result.message}")- if (shouldRetry(result.exception)) {- sawRetryableFailure = true+ phase = requestedSection.toWorkflowPhase(),+ reason = ProviderWorkflowReason.PERIODIC,+ force = force+ ) {+ when (val result = entryPoint.syncManager().processQueuedStalkerIndexJobs(+ providerId = provider.id,+ section = requestedSection,+ force = force,+ maxCategoriesPerSection = CATEGORY_SLICE_SIZE+ )) {+ is com.streamvault.domain.model.Result.Error -> {+ Log.w(TAG, "Stalker index worker failed for provider ${provider.id}: ${result.message}")+ ProviderWorkflowOutcome.Failure(+ code = "STALKER_INDEX",+ message = result.message,+ cause = result.exception+ )}+ is com.streamvault.domain.model.Result.Success ->+ ProviderWorkflowOutcome.Success()+ com.streamvault.domain.model.Result.Loading ->+ ProviderWorkflowOutcome.Failure(+ code = "STALKER_INDEX_LOADING",+ message = "Index operation did not reach a terminal state.",+ retryable = true+ )}+ }+ when (disposition) {+ ProviderWorkflowDisposition.RETRY,+ ProviderWorkflowDisposition.BUSY -> sawRetryableFailure = true+ ProviderWorkflowDisposition.FAILED -> sawPermanentFailure = trueelse -> Unit}}- if (sawRetryableFailure) Result.retry() else Result.success()+ when {+ sawRetryableFailure -> Result.retry()+ sawPermanentFailure -> Result.failure()+ else -> Result.success()+ }} catch (cancelled: kotlinx.coroutines.CancellationException) {throw cancelled} catch (error: Exception) {@@ -87,12 +116,7 @@ class StalkerIndexWorker(}private fun shouldRetry(error: Throwable?): Boolean {- return when (error) {- is IOException -> true- is SQLiteException -> error.message.orEmpty().contains("locked", ignoreCase = true) ||- error.message.orEmpty().contains("busy", ignoreCase = true)- else -> false- }+ return ProviderWorkFailureClassifier.isRetryable(error)}companion object {@@ -102,7 +126,6 @@ class StalkerIndexWorker(private const val KEY_FORCE = "force"private const val INVALID_PROVIDER_ID = -1Lprivate const val CATEGORY_SLICE_SIZE = 32- private const val UNIQUE_WORK_PREFIX = "stalker-index-worker-"fun enqueue(context: Context,@@ -132,8 +155,8 @@ class StalkerIndexWorker(.build()WorkManager.getInstance(context).enqueueUniqueWork(- uniqueWorkName(providerId, section),- if (force) ExistingWorkPolicy.REPLACE else ExistingWorkPolicy.APPEND_OR_REPLACE,+ providerWorkUniqueName(providerId),+ providerWorkExistingPolicy(supersede = false),request)}@@ -143,10 +166,14 @@ class StalkerIndexWorker(.setRequiresBatteryNotLow(true).build()- private fun uniqueWorkName(providerId: Long, section: String?): String =- "$UNIQUE_WORK_PREFIX$providerId-${section.orEmpty()}"-private fun String.toContentTypeOrNull(): ContentType? =runCatching { ContentType.valueOf(this) }.getOrNull()++ private fun ContentType?.toWorkflowPhase(): ProviderWorkflowPhase = when (this) {+ ContentType.MOVIE -> ProviderWorkflowPhase.MOVIE_INDEX+ ContentType.SERIES,+ ContentType.SERIES_EPISODE -> ProviderWorkflowPhase.SERIES_INDEX+ else -> ProviderWorkflowPhase.CONTENT_INDEX+ }}}diff --git a/data/src/main/java/com/streamvault/data/sync/SyncCatalogStore.kt b/data/src/main/java/com/streamvault/data/sync/SyncCatalogStore.ktindex 62b08287..50c482cc 100644--- a/data/src/main/java/com/streamvault/data/sync/SyncCatalogStore.kt+++ b/data/src/main/java/com/streamvault/data/sync/SyncCatalogStore.kt@@ -33,6 +33,7 @@ internal class SyncCatalogStore(private val catalogSyncDao: CatalogSyncDao,private val tmdbIdentityDao: TmdbIdentityDao,private val transactionRunner: DatabaseTransactionRunner,+ private val workflowCommitFence: ProviderWorkflowCommitFence = ProviderWorkflowCommitFence(),private val sizeLimits: CatalogSizeLimits = CatalogSizeLimits()) {companion object {@@ -72,7 +73,12 @@ internal class SyncCatalogStore(}}- suspend fun replaceLiveCatalog(providerId: Long, categories: List<CategoryEntity>?, channels: List<ChannelEntity>): Int {+ suspend fun replaceLiveCatalog(+ providerId: Long,+ categories: List<CategoryEntity>?,+ channels: List<ChannelEntity>,+ afterCatalogApply: suspend () -> Unit = {}+ ): Int {val sessionId = newSessionId()val stagedChannels = buildChannelStages(providerId, sessionId, channels)val limitedChannels = limitChannels(providerId, stagedChannels)@@ -84,7 +90,7 @@ internal class SyncCatalogStore(clearProviderStaging(providerId)categories?.let { stageCategories(providerId, sessionId, it) }insertStageRows(limitedChannels, catalogSyncDao::insertChannelStages)- transactionRunner.inTransaction {+ providerTransaction(providerId) {categories?.let { applyCategories(providerId, sessionId, "LIVE", pruneStale = !overflowed) }if (overflowed) {upsertChannels(providerId, sessionId)@@ -92,6 +98,7 @@ internal class SyncCatalogStore(applyChannels(providerId, sessionId)}catalogSyncDao.rebuildChannelFts()+ afterCatalogApply()}return limitedChannels.size} finally {@@ -105,7 +112,7 @@ internal class SyncCatalogStore(clearProviderStaging(providerId)categories?.let { stageCategories(providerId, sessionId, it) }val stagingResult = stageMovieSequence(providerId, sessionId, movies)- transactionRunner.inTransaction {+ providerTransaction(providerId) {categories?.let { applyCategories(providerId, sessionId, "MOVIE", pruneStale = !stagingResult.overflowed) }if (stagingResult.overflowed) {upsertMovies(providerId, sessionId)@@ -127,7 +134,7 @@ internal class SyncCatalogStore(clearProviderStaging(providerId)categories?.let { stageCategories(providerId, sessionId, it) }val stagingResult = stageSeriesSequence(providerId, sessionId, series)- transactionRunner.inTransaction {+ providerTransaction(providerId) {categories?.let { applyCategories(providerId, sessionId, "SERIES", pruneStale = !stagingResult.overflowed) }if (stagingResult.overflowed) {upsertSeries(providerId, sessionId)@@ -142,26 +149,38 @@ internal class SyncCatalogStore(}}- suspend fun applyStagedLiveCatalog(providerId: Long, sessionId: Long, categories: List<CategoryEntity>?) {+ suspend fun applyStagedLiveCatalog(+ providerId: Long,+ sessionId: Long,+ categories: List<CategoryEntity>?,+ afterCatalogApply: suspend () -> Unit = {}+ ) {try {- transactionRunner.inTransaction {+ providerTransaction(providerId) {categories?.let { stageCategories(providerId, sessionId, it) }categories?.let { applyCategories(providerId, sessionId, "LIVE") }applyChannels(providerId, sessionId)catalogSyncDao.rebuildChannelFts()+ afterCatalogApply()}} finally {clearSession(providerId, sessionId)}}- suspend fun applyStagedMovieCatalog(providerId: Long, sessionId: Long, categories: List<CategoryEntity>?) {+ suspend fun applyStagedMovieCatalog(+ providerId: Long,+ sessionId: Long,+ categories: List<CategoryEntity>?,+ afterCatalogApply: suspend () -> Unit = {}+ ) {try {- transactionRunner.inTransaction {+ providerTransaction(providerId) {categories?.let { stageCategories(providerId, sessionId, it) }categories?.let { applyCategories(providerId, sessionId, "MOVIE") }applyMovies(providerId, sessionId)catalogSyncDao.rebuildMovieFts()+ afterCatalogApply()}movieDao.restoreWatchProgress(providerId)} finally {@@ -169,13 +188,19 @@ internal class SyncCatalogStore(}}- suspend fun applyStagedSeriesCatalog(providerId: Long, sessionId: Long, categories: List<CategoryEntity>?) {+ suspend fun applyStagedSeriesCatalog(+ providerId: Long,+ sessionId: Long,+ categories: List<CategoryEntity>?,+ afterCatalogApply: suspend () -> Unit = {}+ ) {try {- transactionRunner.inTransaction {+ providerTransaction(providerId) {categories?.let { stageCategories(providerId, sessionId, it) }categories?.let { applyCategories(providerId, sessionId, "SERIES") }applySeries(providerId, sessionId)catalogSyncDao.rebuildSeriesFts()+ afterCatalogApply()}} finally {clearSession(providerId, sessionId)@@ -189,13 +214,19 @@ internal class SyncCatalogStore(* Use when the staged session represents a partial (subset) of categories/channels —* absent rows must NOT be treated as deletions.*/- suspend fun applyStagedLiveCatalogUpsertOnly(providerId: Long, sessionId: Long, categories: List<CategoryEntity>?) {+ suspend fun applyStagedLiveCatalogUpsertOnly(+ providerId: Long,+ sessionId: Long,+ categories: List<CategoryEntity>?,+ afterCatalogApply: suspend () -> Unit = {}+ ) {try {- transactionRunner.inTransaction {+ providerTransaction(providerId) {categories?.let { stageCategories(providerId, sessionId, it) }categories?.let { applyCategories(providerId, sessionId, "LIVE", pruneStale = false) }upsertChannels(providerId, sessionId)catalogSyncDao.rebuildChannelFts()+ afterCatalogApply()}} finally {clearSession(providerId, sessionId)@@ -208,7 +239,7 @@ internal class SyncCatalogStore(*/suspend fun applyStagedMovieCatalogUpsertOnly(providerId: Long, sessionId: Long, categories: List<CategoryEntity>?) {try {- transactionRunner.inTransaction {+ providerTransaction(providerId) {categories?.let { stageCategories(providerId, sessionId, it) }categories?.let { applyCategories(providerId, sessionId, "MOVIE", pruneStale = false) }upsertMovies(providerId, sessionId)@@ -226,7 +257,7 @@ internal class SyncCatalogStore(*/suspend fun applyStagedSeriesCatalogUpsertOnly(providerId: Long, sessionId: Long, categories: List<CategoryEntity>?) {try {- transactionRunner.inTransaction {+ providerTransaction(providerId) {categories?.let { stageCategories(providerId, sessionId, it) }categories?.let { applyCategories(providerId, sessionId, "SERIES", pruneStale = false) }upsertSeries(providerId, sessionId)@@ -241,17 +272,23 @@ internal class SyncCatalogStore(* Non-staged live-catalog upsert: stages the given channels, then updates and inserts* without deleting stale rows. Used for partial Xtream category results.*/- suspend fun upsertLiveCatalog(providerId: Long, categories: List<CategoryEntity>?, channels: List<ChannelEntity>): Int {+ suspend fun upsertLiveCatalog(+ providerId: Long,+ categories: List<CategoryEntity>?,+ channels: List<ChannelEntity>,+ afterCatalogApply: suspend () -> Unit = {}+ ): Int {val sessionId = newSessionId()val stagedChannels = buildChannelStages(providerId, sessionId, channels)try {clearProviderStaging(providerId)categories?.let { stageCategories(providerId, sessionId, it) }insertStageRows(stagedChannels, catalogSyncDao::insertChannelStages)- transactionRunner.inTransaction {+ providerTransaction(providerId) {categories?.let { applyCategories(providerId, sessionId, "LIVE", pruneStale = false) }upsertChannels(providerId, sessionId)catalogSyncDao.rebuildChannelFts()+ afterCatalogApply()}return stagedChannels.size} finally {@@ -269,7 +306,7 @@ internal class SyncCatalogStore(clearProviderStaging(providerId)categories?.let { stageCategories(providerId, sessionId, it) }val stagingResult = stageMovieSequence(providerId, sessionId, movies)- transactionRunner.inTransaction {+ providerTransaction(providerId) {categories?.let { applyCategories(providerId, sessionId, "MOVIE", pruneStale = false) }upsertMovies(providerId, sessionId)catalogSyncDao.rebuildMovieFts()@@ -291,7 +328,7 @@ internal class SyncCatalogStore(clearProviderStaging(providerId)categories?.let { stageCategories(providerId, sessionId, it) }val stagingResult = stageSeriesSequence(providerId, sessionId, series)- transactionRunner.inTransaction {+ providerTransaction(providerId) {categories?.let { applyCategories(providerId, sessionId, "SERIES", pruneStale = false) }upsertSeries(providerId, sessionId)catalogSyncDao.rebuildSeriesFts()@@ -307,7 +344,7 @@ internal class SyncCatalogStore(try {clearProviderStaging(providerId)stageCategories(providerId, sessionId, categories)- transactionRunner.inTransaction {+ providerTransaction(providerId) {applyCategories(providerId, sessionId, type, pruneStale = false)}} finally {@@ -320,7 +357,7 @@ internal class SyncCatalogStore(try {clearProviderStaging(providerId)stageCategories(providerId, sessionId, categories)- transactionRunner.inTransaction {+ providerTransaction(providerId) {applyCategories(providerId, sessionId, type)}} finally {@@ -376,9 +413,10 @@ internal class SyncCatalogStore(liveCategories: List<CategoryEntity>?,movieCategories: List<CategoryEntity>?,includeLive: Boolean,- includeMovies: Boolean+ includeMovies: Boolean,+ afterCatalogApply: suspend () -> Unit = {}) {- transactionRunner.inTransaction {+ providerTransaction(providerId) {if (includeLive) {stageCategories(providerId, sessionId, liveCategories.orEmpty())applyCategories(providerId, sessionId, "LIVE")@@ -391,6 +429,9 @@ internal class SyncCatalogStore(applyMovies(providerId, sessionId)catalogSyncDao.rebuildMovieFts()}+ if (includeLive || includeMovies) {+ afterCatalogApply()+ }}if (includeMovies) {movieDao.restoreWatchProgress(providerId)@@ -401,6 +442,14 @@ internal class SyncCatalogStore(clearSession(providerId, sessionId)}+ private suspend fun <T> providerTransaction(+ providerId: Long,+ block: suspend () -> T+ ): T = transactionRunner.inTransaction {+ workflowCommitFence.assertCanCommit(providerId)+ block()+ }+private fun requireStageCapacity(currentCount: Int, incomingCount: Int, maximum: Int, label: String) {if (incomingCount > maximum - currentCount) {throw CatalogAdmissionExceeded("Staged $label limit exceeded")diff --git a/data/src/main/java/com/streamvault/data/sync/SyncManager.kt b/data/src/main/java/com/streamvault/data/sync/SyncManager.ktindex 00643644..7ee83027 100644--- a/data/src/main/java/com/streamvault/data/sync/SyncManager.kt+++ b/data/src/main/java/com/streamvault/data/sync/SyncManager.kt@@ -160,6 +160,22 @@ private data class XtreamLiveCommitResult(val warnings: List<String>)+/** Ensures a pending provider edit is promoted by only the first durable catalog commit. */+private class CatalogCommitGate(+ private val afterCatalogApply: suspend () -> Unit+) {+ private var applied = false++ val hasApplied: Boolean+ get() = applied++ suspend fun apply() {+ if (applied) return+ afterCatalogApply()+ applied = true+ }+}+enum class SyncRepairSection {LIVE,EPG,@@ -195,7 +211,8 @@ class SyncManager @Inject constructor(private val syncMetadataRepository: SyncMetadataRepository,private val transactionRunner: DatabaseTransactionRunner,private val preferencesRepository: com.streamvault.data.preferences.PreferencesRepository,- private val syncProgressBus: SyncProgressBus+ private val syncProgressBus: SyncProgressBus,+ private val providerWorkflowCommitFence: ProviderWorkflowCommitFence) {private val syncStateTracker = SyncStateTracker()private val syncErrorSanitizer = SyncErrorSanitizer()@@ -207,7 +224,8 @@ class SyncManager @Inject constructor(categoryDao = categoryDao,catalogSyncDao = catalogSyncDao,tmdbIdentityDao = tmdbIdentityDao,- transactionRunner = transactionRunner+ transactionRunner = transactionRunner,+ workflowCommitFence = providerWorkflowCommitFence)private val m3uImporter = SyncManagerM3uImporter(m3uParser = m3uParser,@@ -228,12 +246,9 @@ class SyncManager @Inject constructor()val syncState: StateFlow<SyncState> = syncStateTracker.aggregateStateval syncStatesByProvider: StateFlow<Map<Long, SyncState>> = syncStateTracker.statesByProvider- private val providerSyncMutexes = ConcurrentHashMap<Long, Mutex>()- private val providerStalkerSummaryMutexes = ConcurrentHashMap<Long, Mutex>()- private val providerStalkerIndexSectionMutexes = ConcurrentHashMap<String, Mutex>()+ private val providerWorkLocks = ProviderWorkLockRegistry()private val providerStalkerFetchSemaphores = ConcurrentHashMap<Long, Semaphore>()- private val providerEpgMutexes = ConcurrentHashMap<Long, Mutex>()- private val syncAdmissionMutex = Mutex()+ private val stalkerFetchAdmissionMutex = Mutex()private val xtreamCatalogHttpService: OkHttpXtreamApiService by lazy {OkHttpXtreamApiService(client = okHttpClient,@@ -288,112 +303,32 @@ class SyncManager @Inject constructor(syncStateTracker.current(providerId)/** Returns true if any provider sync mutex is currently held (used by DatabaseMaintenanceManager). */- fun isAnySyncActive(): Boolean = isAnySyncMutexLocked()-- private fun isAnySyncMutexLocked(): Boolean =- providerSyncMutexes.values.any { it.isLocked } ||- providerEpgMutexes.values.any { it.isLocked }-- private suspend fun <T> withProviderLock(providerId: Long, block: suspend () -> T): T {- val mutex = syncAdmissionMutex.withLock {- providerSyncMutexes.computeIfAbsent(providerId) { Mutex() }.also { providerMutex ->- providerMutex.lock()- }- }- try {- return block()- } finally {- mutex.unlock()- }- }+ fun isAnySyncActive(): Boolean = providerWorkLocks.isAnyWorkActiveOrWaiting()- private suspend fun <T> withProviderEpgLock(providerId: Long, block: suspend () -> T): T {- val mutex = syncAdmissionMutex.withLock {- providerEpgMutexes.computeIfAbsent(providerId) { Mutex() }.also { providerMutex ->- providerMutex.lock()- }- }- try {- return block()- } finally {- mutex.unlock()- }- }-- private suspend fun <T> withStalkerIndexSectionLock(- providerId: Long,- section: ContentType,- block: suspend () -> T- ): T {- val lockKey = "$providerId:${section.name}"- val mutex = syncAdmissionMutex.withLock {- providerStalkerIndexSectionMutexes.computeIfAbsent(lockKey) { Mutex() }.also { sectionMutex ->- sectionMutex.lock()- }- }- try {- return block()- } finally {- mutex.unlock()- }- }-- private suspend fun <T> withStalkerSummaryProviderLock(providerId: Long, block: suspend () -> T): T {- val mutex = syncAdmissionMutex.withLock {- providerStalkerSummaryMutexes.computeIfAbsent(providerId) { Mutex() }.also { providerMutex ->- providerMutex.lock()- }- }- try {- return block()- } finally {- mutex.unlock()- }- }-- private suspend fun <T> withStalkerSummaryLock(- providerId: Long,- section: ContentType?,- providerMaxConnections: Int,- block: suspend () -> T- ): T = when (section) {- ContentType.MOVIE,- ContentType.SERIES -> withStalkerSummaryProviderLock(providerId, block)- else -> withProviderLock(providerId, block)- }+ private suspend fun <T> withProviderLock(providerId: Long, block: suspend () -> T): T =+ providerWorkLocks.withProviderLock(providerId, block)private suspend fun <T> withStalkerFetchPermit(provider: Provider, block: suspend () -> T): T {val permitCount = minOf(provider.maxConnections.coerceAtLeast(1),STALKER_MAX_PARALLEL_CATEGORY_FETCHES).coerceAtLeast(1)- val semaphore = syncAdmissionMutex.withLock {+ val semaphore = stalkerFetchAdmissionMutex.withLock {providerStalkerFetchSemaphores.computeIfAbsent(provider.id) { Semaphore(permitCount) }}return semaphore.withPermit { block() }}suspend fun runWhenNoSyncActive(block: suspend () -> Boolean): Boolean =- syncAdmissionMutex.withLock {- if (isAnySyncMutexLocked()) {- false- } else {- block()- }- }+ providerWorkLocks.runWhenNoWorkActive(block)suspend fun onProviderDeleted(providerId: Long) {BackgroundEpgSyncWorker.cancel(applicationContext, providerId)withProviderLock(providerId) {- withProviderEpgLock(providerId) {- syncStateTracker.reset(providerId)- xtreamAdaptiveSyncPolicy.forgetProvider(providerId)- syncCatalogStore.clearProviderStaging(providerId)- epgRepository.onProviderDeleted(providerId)- providerSyncMutexes.remove(providerId)- providerStalkerSummaryMutexes.remove(providerId)- providerEpgMutexes.remove(providerId)- }+ syncStateTracker.reset(providerId)+ xtreamAdaptiveSyncPolicy.forgetProvider(providerId)+ syncCatalogStore.clearProviderStaging(providerId)+ epgRepository.onProviderDeleted(providerId)}}@@ -520,16 +455,10 @@ class SyncManager @Inject constructor(val providerEntity = providerDao.getById(providerId)?: return com.streamvault.domain.model.Result.error("Provider $providerId not found")- return if (providerEntity.type == ProviderType.STALKER_PORTAL) {- withProviderEpgLock(providerId) {- syncEpgLocked(providerEntity, force, onProgress)- }- } else {- withProviderLock(providerId) {- val freshProviderEntity = providerDao.getById(providerId)- ?: return@withProviderLock com.streamvault.domain.model.Result.error("Provider $providerId not found")- syncEpgLocked(freshProviderEntity, force, onProgress)- }+ return withProviderLock(providerId) {+ val freshProviderEntity = providerDao.getById(providerId)+ ?: return@withProviderLock com.streamvault.domain.model.Result.error("Provider $providerId not found")+ syncEpgLocked(freshProviderEntity, force, onProgress)}}@@ -664,21 +593,47 @@ class SyncManager @Inject constructor(epgSyncModeOverride: ProviderEpgSyncMode? = null,onProgress: ((String) -> Unit)? = null,trackInitialLiveOnboarding: Boolean = false+ ): com.streamvault.domain.model.Result<Unit> = syncWithProviderOverride(+ providerId = providerId,+ force = force,+ movieFastSyncOverride = movieFastSyncOverride,+ epgSyncModeOverride = epgSyncModeOverride,+ onProgress = onProgress,+ trackInitialLiveOnboarding = trackInitialLiveOnboarding+ )++ /**+ * Runs a not-yet-committed configuration. The callback is invoked within the first catalog+ * transaction that publishes data, so callers can atomically promote the configuration.+ */+ suspend fun syncWithProviderOverride(+ providerId: Long,+ force: Boolean = false,+ movieFastSyncOverride: Boolean? = null,+ epgSyncModeOverride: ProviderEpgSyncMode? = null,+ onProgress: ((String) -> Unit)? = null,+ trackInitialLiveOnboarding: Boolean = false,+ providerOverride: Provider? = null,+ afterCatalogApply: (suspend () -> Unit)? = null): com.streamvault.domain.model.Result<Unit> = withProviderLock(providerId) lock@{var progressSession: SyncProgressSession? = nulltry {val providerEntity = providerDao.getById(providerId)?: return@lock com.streamvault.domain.model.Result.error("Provider $providerId not found")- val provider = providerEntity+ require(providerOverride == null || providerOverride.id == providerId) {+ "Provider override must match the requested provider ID."+ }+ val provider = (providerOverride ?: providerEntity.copy(password = credentialCrypto.decryptIfNeeded(providerEntity.password))- .toDomain()+ .toDomain()).let { resolvedProvider ->resolvedProvider.copy(xtreamFastSyncEnabled = movieFastSyncOverride ?: resolvedProvider.xtreamFastSyncEnabled,epgSyncMode = epgSyncModeOverride ?: resolvedProvider.epgSyncMode)}+ val catalogCommitGate = CatalogCommitGate(afterCatalogApply ?: {})progressSession = beginProgressSession(providerId)publishSyncState(providerId, SyncState.Syncing("Starting..."))@@ -694,18 +649,26 @@ class SyncManager @Inject constructor(XtreamLiveSyncReason.INITIAL_ONBOARDING} else {XtreamLiveSyncReason.FOREGROUND- }+ },+ afterCatalogApply = catalogCommitGate::apply)- ProviderType.M3U -> syncM3u(provider, force, onProgress)- ProviderType.STALKER_PORTAL -> syncStalker(provider, force, onProgress)- ProviderType.JELLYFIN -> syncJellyfin(provider, force, onProgress)+ ProviderType.M3U -> syncM3u(provider, force, onProgress, catalogCommitGate::apply)+ ProviderType.STALKER_PORTAL -> syncStalker(provider, force, onProgress, catalogCommitGate::apply)+ ProviderType.JELLYFIN -> syncJellyfin(provider, force, onProgress, catalogCommitGate::apply)}}- providerDao.updateSyncTime(providerId, System.currentTimeMillis())- updateSyncStatusMetadata(- providerId = providerId,- status = if (outcome.partial) "PARTIAL" else "SUCCESS"- )+ transactionRunner.inTransaction {+ providerWorkflowCommitFence.assertCanCommit(providerId)+ // A candidate configuration which produced no catalog is not committed. Do+ // not make the previous provider look freshly synced in that case.+ if (providerOverride == null || catalogCommitGate.hasApplied) {+ providerDao.updateSyncTime(providerId, System.currentTimeMillis())+ }+ updateSyncStatusMetadata(+ providerId = providerId,+ status = if (outcome.partial) "PARTIAL" else "SUCCESS"+ )+ }publishSyncState(providerId, if (outcome.partial) {SyncState.Partial("Sync completed with warnings", outcome.warnings)} else {@@ -909,7 +872,8 @@ class SyncManager @Inject constructor(force: Boolean,onProgress: ((String) -> Unit)?,trackInitialLiveOnboarding: Boolean = false,- syncReason: XtreamLiveSyncReason = XtreamLiveSyncReason.FOREGROUND+ syncReason: XtreamLiveSyncReason = XtreamLiveSyncReason.FOREGROUND,+ afterCatalogApply: suspend () -> Unit = {}): SyncOutcome {val warnings = mutableListOf<String>()UrlSecurityPolicy.validateXtreamServerUrl(provider.serverUrl)?.let { message ->@@ -946,7 +910,8 @@ class SyncManager @Inject constructor(val recoveredLiveCommit = if (trackInitialLiveOnboarding) {recoverXtreamLiveOnboardingSession(provider = provider,- hiddenLiveCategoryIds = hiddenLiveCategoryIds+ hiddenLiveCategoryIds = hiddenLiveCategoryIds,+ afterCatalogApply = afterCatalogApply)} else {null@@ -1046,7 +1011,8 @@ class SyncManager @Inject constructor(providerId = provider.id,liveSyncResult = liveSyncResult,hiddenLiveCategoryIds = hiddenLiveCategoryIds,- onProgress = onProgress+ onProgress = onProgress,+ afterCatalogApply = afterCatalogApply).also { commitResult ->warnings += commitResult.warnings}.acceptedCount@@ -1071,7 +1037,8 @@ class SyncManager @Inject constructor(liveSyncResult = liveSyncResult,hiddenLiveCategoryIds = hiddenLiveCategoryIds,onProgress = onProgress,- partialCompletionWarning = "Live TV sync completed partially."+ partialCompletionWarning = "Live TV sync completed partially.",+ afterCatalogApply = afterCatalogApply).also { commitResult ->warnings += commitResult.warnings}.acceptedCount@@ -1342,7 +1309,8 @@ class SyncManager @Inject constructor(private suspend fun recoverXtreamLiveOnboardingSession(provider: Provider,- hiddenLiveCategoryIds: Set<Long>+ hiddenLiveCategoryIds: Set<Long>,+ afterCatalogApply: suspend () -> Unit = {}): XtreamLiveCommitResult? {val state = xtreamLiveOnboardingDao.getIncompleteByProvider(provider.id) ?: return nullval sessionId = state.stagedSessionId ?: return null@@ -1395,7 +1363,8 @@ class SyncManager @Inject constructor(syncCatalogStore.applyStagedLiveCatalog(providerId = provider.id,sessionId = sessionId,- categories = commitState.categories.takeIf { it.isNotEmpty() }+ categories = commitState.categories.takeIf { it.isNotEmpty() },+ afterCatalogApply = afterCatalogApply)return XtreamLiveCommitResult(acceptedCount = stagedState.channelCount,@@ -1547,8 +1516,7 @@ class SyncManager @Inject constructor(maxCategoriesPerSection: Int? = null,onProgress: ((String) -> Unit)? = null): com.streamvault.domain.model.Result<Unit> {- val providerMaxConnections = providerDao.getById(providerId)?.maxConnections ?: Int.MAX_VALUE- return withStalkerSummaryLock(providerId, section, providerMaxConnections) lock@{+ return withProviderLock(providerId) lock@{val playbackDelayMillis = StalkerTrafficCoordinator.deferCatalogFetchMillis(providerId)if (playbackDelayMillis > 0L) {Log.i(TAG, "Deferring Stalker catalog work for provider $providerId because playback is active.")@@ -3746,21 +3714,27 @@ class SyncManager @Inject constructor(private suspend fun syncM3u(provider: Provider,force: Boolean,- onProgress: ((String) -> Unit)?+ onProgress: ((String) -> Unit)?,+ afterCatalogApply: suspend () -> Unit = {}): SyncOutcome {val warnings = mutableListOf<String>()var metadata = syncMetadataRepository.getMetadata(provider.id) ?: SyncMetadata(provider.id)val now = System.currentTimeMillis()if (force || ContentCachePolicy.shouldRefresh(metadata.lastLiveSuccess, ContentCachePolicy.CATALOG_TTL_MILLIS, now)) {- val stats = withContext(Dispatchers.IO) { m3uImporter.importPlaylist(provider, onProgress) }+ val stats = withContext(Dispatchers.IO) {+ m3uImporter.importPlaylist(provider, onProgress, afterCatalogApply = afterCatalogApply)+ }if (stats.liveCount == 0 && stats.movieCount == 0) {throw IllegalStateException("Playlist is empty or contains no supported entries")}warnings += stats.warningsval playlistEpgUrl = stats.header.tvgUrlif (provider.epgUrl.isBlank() && !playlistEpgUrl.isNullOrBlank()) {- providerDao.updateEpgUrl(provider.id, playlistEpgUrl)+ transactionRunner.inTransaction {+ providerWorkflowCommitFence.assertCanCommit(provider.id)+ providerDao.updateEpgUrl(provider.id, playlistEpgUrl)+ }val existingSourcesByUrl = epgSourceRepository.getAllSources().first().associateBy { it.url }val assignedSourceIds = epgSourceRepository.getAssignmentsForProvider(provider.id).first()@@ -3887,7 +3861,8 @@ class SyncManager @Inject constructor(private suspend fun syncStalker(provider: Provider,force: Boolean,- onProgress: ((String) -> Unit)?+ onProgress: ((String) -> Unit)?,+ afterCatalogApply: suspend () -> Unit = {}): SyncOutcome {val warnings = mutableListOf<String>()UrlSecurityPolicy.validateStalkerPortalUrl(provider.serverUrl)?.let { message ->@@ -3917,7 +3892,13 @@ class SyncManager @Inject constructor()progress(provider.id, onProgress, "Downloading Live TV...")val hiddenLiveCategoryIds = preferencesRepository.getHiddenCategoryIds(provider.id, ContentType.LIVE).first()- val liveCatalogResult = syncStalkerLiveCatalogStaged(api, provider, hiddenLiveCategoryIds, onProgress)+ val liveCatalogResult = syncStalkerLiveCatalogStaged(+ api,+ provider,+ hiddenLiveCategoryIds,+ onProgress,+ afterCatalogApply+ )val liveCategoryCount = categoryDao.getByProviderAndTypeSync(provider.id, ContentType.LIVE.name).sizeval liveFinishedAt = System.currentTimeMillis()metadata = metadata.copy(@@ -4117,7 +4098,8 @@ class SyncManager @Inject constructor(private suspend fun syncJellyfin(provider: Provider,force: Boolean,- onProgress: ((String) -> Unit)?+ onProgress: ((String) -> Unit)?,+ afterCatalogApply: suspend () -> Unit = {}): SyncOutcome {val warnings = mutableListOf<String>()try {@@ -4169,12 +4151,28 @@ class SyncManager @Inject constructor(}progress(provider.id, onProgress, "Importing Jellyfin library...")- syncCatalogStore.applyStagedMovieCatalog(provider.id, movieSession, listOf(- com.streamvault.data.local.entity.CategoryEntity(providerId = provider.id, categoryId = 1L, name = "Movies", type = com.streamvault.domain.model.ContentType.MOVIE)- ))- syncCatalogStore.applyStagedSeriesCatalog(provider.id, seriesSession, listOf(- com.streamvault.data.local.entity.CategoryEntity(providerId = provider.id, categoryId = 2L, name = "Series", type = com.streamvault.domain.model.ContentType.SERIES)- ))+ syncCatalogStore.applyStagedMovieCatalog(+ provider.id,+ movieSession,+ listOf(com.streamvault.data.local.entity.CategoryEntity(+ providerId = provider.id,+ categoryId = 1L,+ name = "Movies",+ type = com.streamvault.domain.model.ContentType.MOVIE+ )),+ afterCatalogApply+ )+ syncCatalogStore.applyStagedSeriesCatalog(+ provider.id,+ seriesSession,+ listOf(com.streamvault.data.local.entity.CategoryEntity(+ providerId = provider.id,+ categoryId = 2L,+ name = "Series",+ type = com.streamvault.domain.model.ContentType.SERIES+ )),+ afterCatalogApply+ )return SyncOutcome(warnings = warnings)} catch (error: Exception) {syncCatalogStore.clearProviderStaging(provider.id)@@ -5235,7 +5233,8 @@ class SyncManager @Inject constructor(liveSyncResult: CatalogSyncPayload<Channel>,hiddenLiveCategoryIds: Set<Long>,onProgress: ((String) -> Unit)? = null,- partialCompletionWarning: String? = null+ partialCompletionWarning: String? = null,+ afterCatalogApply: suspend () -> Unit = {}): XtreamLiveCommitResult {progress(providerId, onProgress, "Saving Live TV channels...")val warnings = buildList {@@ -5257,7 +5256,8 @@ class SyncManager @Inject constructor(syncCatalogStore.applyStagedLiveCatalog(providerId = providerId,sessionId = sessionId,- categories = mergedCategories+ categories = mergedCategories,+ afterCatalogApply = afterCatalogApply)liveSyncResult.stagedAcceptedCount} ?: run {@@ -5270,7 +5270,8 @@ class SyncManager @Inject constructor(syncCatalogStore.replaceLiveCatalog(providerId = providerId,categories = liveCatalog.categories,- channels = liveCatalog.channels+ channels = liveCatalog.channels,+ afterCatalogApply = afterCatalogApply)}}@@ -5287,7 +5288,8 @@ class SyncManager @Inject constructor(syncCatalogStore.applyStagedLiveCatalogUpsertOnly(providerId = providerId,sessionId = sessionId,- categories = mergedCategories+ categories = mergedCategories,+ afterCatalogApply = afterCatalogApply)liveSyncResult.stagedAcceptedCount} ?: run {@@ -5300,7 +5302,8 @@ class SyncManager @Inject constructor(syncCatalogStore.upsertLiveCatalog(providerId = providerId,categories = liveCatalog.categories,- channels = liveCatalog.channels+ channels = liveCatalog.channels,+ afterCatalogApply = afterCatalogApply)}}@@ -5607,7 +5610,8 @@ class SyncManager @Inject constructor(api: StalkerProvider,provider: Provider,hiddenLiveCategoryIds: Set<Long>,- onProgress: ((String) -> Unit)?+ onProgress: ((String) -> Unit)?,+ afterCatalogApply: suspend () -> Unit = {}): StagedStalkerLiveCatalogResult {val warnings = mutableListOf<String>()var categoriesErrorMessage: String? = null@@ -5679,7 +5683,12 @@ class SyncManager @Inject constructor(warnings = (warnings + "Live TV provider exposed no live channels; continuing with VOD and series only.").distinct())}- syncCatalogStore.applyStagedLiveCatalog(provider.id, sessionId, categories)+ syncCatalogStore.applyStagedLiveCatalog(+ provider.id,+ sessionId,+ categories,+ afterCatalogApply+ )return StagedStalkerLiveCatalogResult(acceptedCount, warnings)}diff --git a/data/src/main/java/com/streamvault/data/sync/SyncManagerM3uImporter.kt b/data/src/main/java/com/streamvault/data/sync/SyncManagerM3uImporter.ktindex 75aecfaf..44dd91e7 100644--- a/data/src/main/java/com/streamvault/data/sync/SyncManagerM3uImporter.kt+++ b/data/src/main/java/com/streamvault/data/sync/SyncManagerM3uImporter.kt@@ -41,7 +41,8 @@ internal class SyncManagerM3uImporter(onProgress: ((String) -> Unit)?,includeLive: Boolean = true,includeMovies: Boolean = true,- batchSize: Int = 1000+ batchSize: Int = 1000,+ afterCatalogApply: suspend () -> Unit = {}): M3uImportStats {UrlSecurityPolicy.validatePlaylistSourceUrl(provider.m3uUrl.ifBlank { provider.serverUrl })?.let { message ->throw IllegalStateException(message)@@ -243,7 +244,8 @@ internal class SyncManagerM3uImporter(liveCategories = if (effectiveLive) liveCategories.entities() else null,movieCategories = if (effectiveMovies) movieCategories.entities() else null,includeLive = effectiveLive,- includeMovies = effectiveMovies+ includeMovies = effectiveMovies,+ afterCatalogApply = afterCatalogApply)} finally {syncCatalogStore.discardStagedImport(provider.id, sessionId)diff --git a/data/src/main/java/com/streamvault/data/sync/XtreamIndexWorker.kt b/data/src/main/java/com/streamvault/data/sync/XtreamIndexWorker.ktindex 9d49732e..ce244f4d 100644--- a/data/src/main/java/com/streamvault/data/sync/XtreamIndexWorker.kt+++ b/data/src/main/java/com/streamvault/data/sync/XtreamIndexWorker.kt@@ -16,6 +16,8 @@ import androidx.work.WorkManagerimport androidx.work.WorkRequestimport androidx.work.WorkerParametersimport com.streamvault.data.local.dao.ProviderDao+import com.streamvault.data.local.entity.ProviderWorkflowPhase+import com.streamvault.data.local.entity.ProviderWorkflowReasonimport com.streamvault.domain.model.ContentTypeimport com.streamvault.domain.model.ProviderTypeimport dagger.hilt.EntryPoint@@ -35,6 +37,7 @@ class XtreamIndexWorker(interface XtreamIndexWorkerEntryPoint {fun providerDao(): ProviderDaofun syncManager(): SyncManager+ fun providerWorkflowRunner(): ProviderWorkflowRunner}override suspend fun doWork(): Result {@@ -60,26 +63,53 @@ class XtreamIndexWorker(}var sawRetryableFailure = false+ var sawPermanentFailure = falseproviders.filter { provider -> provider.type == ProviderType.XTREAM_CODES }.forEach { provider ->- when (val result = entryPoint.syncManager().processQueuedXtreamIndexJobs(+ val disposition = entryPoint.providerWorkflowRunner().execute(providerId = provider.id,- section = requestedSection,- force = force,- maxCategoriesPerSection = CATEGORY_SLICE_SIZE- )) {- is com.streamvault.domain.model.Result.Error -> {- Log.w(TAG, "Xtream index worker failed for provider ${provider.id}: ${result.message}")- if (shouldRetry(result.exception)) {- sawRetryableFailure = true+ phase = requestedSection.toWorkflowPhase(),+ reason = ProviderWorkflowReason.PERIODIC,+ force = force+ ) {+ when (val result = entryPoint.syncManager().processQueuedXtreamIndexJobs(+ providerId = provider.id,+ section = requestedSection,+ force = force,+ maxCategoriesPerSection = CATEGORY_SLICE_SIZE+ )) {+ is com.streamvault.domain.model.Result.Error -> {+ Log.w(TAG, "Xtream index worker failed for provider ${provider.id}: ${result.message}")+ ProviderWorkflowOutcome.Failure(+ code = "XTREAM_INDEX",+ message = result.message,+ cause = result.exception+ )}+ is com.streamvault.domain.model.Result.Success ->+ ProviderWorkflowOutcome.Success()+ com.streamvault.domain.model.Result.Loading ->+ ProviderWorkflowOutcome.Failure(+ code = "XTREAM_INDEX_LOADING",+ message = "Index operation did not reach a terminal state.",+ retryable = true+ )}+ }+ when (disposition) {+ ProviderWorkflowDisposition.RETRY,+ ProviderWorkflowDisposition.BUSY -> sawRetryableFailure = true+ ProviderWorkflowDisposition.FAILED -> sawPermanentFailure = trueelse -> Unit}}- if (sawRetryableFailure) Result.retry() else Result.success()+ when {+ sawRetryableFailure -> Result.retry()+ sawPermanentFailure -> Result.failure()+ else -> Result.success()+ }} catch (cancelled: kotlinx.coroutines.CancellationException) {throw cancelled} catch (error: Exception) {@@ -89,12 +119,7 @@ class XtreamIndexWorker(}private fun shouldRetry(error: Throwable?): Boolean {- return when (error) {- is IOException -> true- is SQLiteException -> error.message.orEmpty().contains("locked", ignoreCase = true) ||- error.message.orEmpty().contains("busy", ignoreCase = true)- else -> false- }+ return ProviderWorkFailureClassifier.isRetryable(error)}companion object {@@ -104,7 +129,7 @@ class XtreamIndexWorker(private const val KEY_FORCE = "force"private const val INVALID_PROVIDER_ID = -1Lprivate const val CATEGORY_SLICE_SIZE = 2- private const val UNIQUE_WORK_PREFIX = "xtream-index-worker-"+ private const val UNIQUE_LAUNCH_WORK_NAME = "xtream-index-launch-stale-check"private const val UNIQUE_PERIODIC_WORK_NAME = "xtream-index-periodic-worker"fun enqueue(@@ -135,8 +160,8 @@ class XtreamIndexWorker(.build()WorkManager.getInstance(context).enqueueUniqueWork(- uniqueWorkName(providerId, section),- if (force) ExistingWorkPolicy.REPLACE else ExistingWorkPolicy.APPEND_OR_REPLACE,+ providerWorkUniqueName(providerId),+ providerWorkExistingPolicy(supersede = false),request)}@@ -153,7 +178,7 @@ class XtreamIndexWorker(.build()WorkManager.getInstance(context).enqueueUniqueWork(- "$UNIQUE_WORK_PREFIX-launch-stale-check",+ UNIQUE_LAUNCH_WORK_NAME,ExistingWorkPolicy.KEEP,request)@@ -181,10 +206,14 @@ class XtreamIndexWorker(.setRequiresBatteryNotLow(true).build()- private fun uniqueWorkName(providerId: Long, section: String?): String =- "$UNIQUE_WORK_PREFIX$providerId-${section.orEmpty()}"-private fun String.toContentTypeOrNull(): ContentType? =runCatching { ContentType.valueOf(this) }.getOrNull()++ private fun ContentType?.toWorkflowPhase(): ProviderWorkflowPhase = when (this) {+ ContentType.MOVIE -> ProviderWorkflowPhase.MOVIE_INDEX+ ContentType.SERIES,+ ContentType.SERIES_EPISODE -> ProviderWorkflowPhase.SERIES_INDEX+ else -> ProviderWorkflowPhase.CONTENT_INDEX+ }}}diff --git a/data/src/test/java/com/streamvault/data/local/DownloadDaoOwnershipTest.kt b/data/src/test/java/com/streamvault/data/local/DownloadDaoOwnershipTest.ktnew file mode 100644index 00000000..669dc063--- /dev/null+++ b/data/src/test/java/com/streamvault/data/local/DownloadDaoOwnershipTest.kt@@ -0,0 +1,76 @@+package com.streamvault.data.local++import androidx.room.Room+import com.google.common.truth.Truth.assertThat+import com.streamvault.data.local.entity.DownloadEntity+import com.streamvault.domain.model.DownloadContentType+import com.streamvault.domain.model.DownloadStatus+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.async+import kotlinx.coroutines.awaitAll+import kotlinx.coroutines.test.runTest+import kotlinx.coroutines.withContext+import org.junit.After+import org.junit.Before+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.RuntimeEnvironment++@RunWith(RobolectricTestRunner::class)+class DownloadDaoOwnershipTest {++ private lateinit var database: StreamVaultDatabase++ @Before+ fun setUp() {+ database = Room.inMemoryDatabaseBuilder(+ RuntimeEnvironment.getApplication(),+ StreamVaultDatabase::class.java+ ).allowMainThreadQueries().build()+ }++ @After+ fun tearDown() {+ database.close()+ }++ @Test+ fun `concurrent schedulers grant exactly one durable owner`() = runTest {+ val dao = database.downloadDao()+ dao.insert(download())++ val claims = withContext(Dispatchers.Default) {+ listOf("owner-a", "owner-b").map { owner ->+ async { dao.claimForDownload("download-1", owner, 1234L) }+ }.awaitAll()+ }++ assertThat(claims.sum()).isEqualTo(1)+ val claimed = dao.getByIdOnce("download-1")!!+ assertThat(claimed.status).isEqualTo(DownloadStatus.DOWNLOADING)+ assertThat(claimed.ownerId).isAnyOf("owner-a", "owner-b")+ assertThat(claimed.ownerEpoch).isEqualTo(1L)+ assertThat(claimed.heartbeatAt).isEqualTo(1234L)+ }++ @Test+ fun `restart sees prior process owner as orphan but not current owner`() = runTest {+ val dao = database.downloadDao()+ dao.insert(download())+ assertThat(dao.claimForDownload("download-1", "old-process", 1234L)).isEqualTo(1)++ assertThat(dao.getOrphanedDownloading("new-process").map { it.id })+ .containsExactly("download-1")+ assertThat(dao.getOrphanedDownloading("old-process")).isEmpty()+ }++ private fun download() = DownloadEntity(+ id = "download-1",+ providerId = 1L,+ contentType = DownloadContentType.MOVIE,+ contentId = 2L,+ contentName = "Movie",+ streamUrl = "https://example.com/movie.mp4"+ )+}diff --git a/data/src/test/java/com/streamvault/data/local/ProgramReminderDeliveryDaoTest.kt b/data/src/test/java/com/streamvault/data/local/ProgramReminderDeliveryDaoTest.ktnew file mode 100644index 00000000..de9b59a8--- /dev/null+++ b/data/src/test/java/com/streamvault/data/local/ProgramReminderDeliveryDaoTest.kt@@ -0,0 +1,87 @@+package com.streamvault.data.local++import androidx.room.Room+import com.google.common.truth.Truth.assertThat+import com.streamvault.data.local.entity.ProgramReminderEntity+import com.streamvault.domain.model.ProgramReminderDeliveryState+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.async+import kotlinx.coroutines.awaitAll+import kotlinx.coroutines.test.runTest+import kotlinx.coroutines.withContext+import org.junit.After+import org.junit.Before+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.RuntimeEnvironment++@RunWith(RobolectricTestRunner::class)+class ProgramReminderDeliveryDaoTest {++ private lateinit var database: StreamVaultDatabase++ @Before+ fun setUp() {+ database = Room.inMemoryDatabaseBuilder(+ RuntimeEnvironment.getApplication(),+ StreamVaultDatabase::class.java+ ).allowMainThreadQueries().build()+ database.openHelper.writableDatabase.execSQL("PRAGMA foreign_keys = OFF")+ }++ @After+ fun tearDown() {+ database.close()+ }++ @Test+ fun `concurrent alarm deliveries grant exactly one attempt token`() = runTest {+ val dao = database.programReminderDao()+ dao.insert(+ ProgramReminderEntity(+ id = 42L,+ providerId = 7L,+ channelId = "bbc1",+ channelName = "BBC One",+ programTitle = "World News",+ programStartTime = 10_000L,+ remindAt = 5_000L+ )+ )++ val claims = withContext(Dispatchers.Default) {+ listOf("attempt-a", "attempt-b").map { token ->+ async { dao.claimDelivery(42L, token, 5_000L) }+ }.awaitAll()+ }++ assertThat(claims.sum()).isEqualTo(1)+ val claimed = dao.getById(42L)!!+ assertThat(claimed.deliveryState).isEqualTo(ProgramReminderDeliveryState.DELIVERING)+ assertThat(claimed.deliveryAttemptToken).isAnyOf("attempt-a", "attempt-b")+ assertThat(claimed.deliveryAttemptCount).isEqualTo(1)+ assertThat(claimed.exactAlarmArmed).isFalse()+ }++ @Test+ fun `stale completion token cannot overwrite a newer delivery attempt`() = runTest {+ val dao = database.programReminderDao()+ dao.insert(+ ProgramReminderEntity(+ id = 42L,+ providerId = 7L,+ channelId = "bbc1",+ channelName = "BBC One",+ programTitle = "World News",+ programStartTime = 10_000L,+ remindAt = 5_000L+ )+ )+ assertThat(dao.claimDelivery(42L, "current-attempt", 5_000L)).isEqualTo(1)++ assertThat(dao.markDelivered(42L, "stale-attempt", 5_100L)).isEqualTo(0)+ assertThat(dao.getById(42L)!!.deliveryState)+ .isEqualTo(ProgramReminderDeliveryState.DELIVERING)+ }+}diff --git a/data/src/test/java/com/streamvault/data/local/ProviderConfigRevisionClockRecoveryTest.kt b/data/src/test/java/com/streamvault/data/local/ProviderConfigRevisionClockRecoveryTest.ktnew file mode 100644index 00000000..8b0d215b--- /dev/null+++ b/data/src/test/java/com/streamvault/data/local/ProviderConfigRevisionClockRecoveryTest.kt@@ -0,0 +1,73 @@+package com.streamvault.data.local++import androidx.room.Room+import com.google.common.truth.Truth.assertThat+import com.streamvault.data.local.entity.ProviderConfigRevisionEntity+import com.streamvault.data.local.entity.ProviderConfigRevisionState+import com.streamvault.data.local.entity.ProviderEntity+import com.streamvault.domain.model.ProviderType+import kotlinx.coroutines.test.runTest+import org.junit.After+import org.junit.Before+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.RuntimeEnvironment++@RunWith(RobolectricTestRunner::class)+class ProviderConfigRevisionClockRecoveryTest {++ private lateinit var database: StreamVaultDatabase++ @Before+ fun setUp() {+ database = Room.inMemoryDatabaseBuilder(+ RuntimeEnvironment.getApplication(),+ StreamVaultDatabase::class.java+ ).allowMainThreadQueries().build()+ }++ @After+ fun tearDown() {+ database.close()+ }++ @Test+ fun `process restart recovers future stale and invalid syncing revisions but not live owner`() = runTest {+ val providerDao = database.providerDao()+ val revisionDao = database.providerConfigRevisionDao()+ val now = 10_000L+ val staleBefore = 9_000L++ listOf(+ 1L to 10_001L,+ 2L to staleBefore,+ 3L to 0L,+ 4L to 9_999L+ ).forEach { (providerId, updatedAt) ->+ providerDao.insert(+ ProviderEntity(+ id = providerId,+ name = "Provider $providerId",+ type = ProviderType.M3U,+ serverUrl = "https://example.com/$providerId"+ )+ )+ revisionDao.upsert(+ ProviderConfigRevisionEntity(+ providerId = providerId,+ revision = 1L,+ configJson = "{}",+ state = ProviderConfigRevisionState.SYNCING,+ createdAt = 1L,+ updatedAt = updatedAt+ )+ )+ }++ val candidates = revisionDao.getRecoveryCandidates(now, staleBefore)++ assertThat(candidates.map { it.providerId }).containsExactly(1L, 2L, 3L)+ assertThat(candidates.map { it.providerId }).doesNotContain(4L)+ }+}diff --git a/data/src/test/java/com/streamvault/data/local/ProviderWorkflowDaoTest.kt b/data/src/test/java/com/streamvault/data/local/ProviderWorkflowDaoTest.ktnew file mode 100644index 00000000..39685bbc--- /dev/null+++ b/data/src/test/java/com/streamvault/data/local/ProviderWorkflowDaoTest.kt@@ -0,0 +1,320 @@+package com.streamvault.data.local++import androidx.room.Room+import com.google.common.truth.Truth.assertThat+import com.streamvault.data.local.dao.ProviderWorkflowTicket+import com.streamvault.data.local.entity.ProviderEntity+import com.streamvault.data.local.entity.ProviderWorkflowPhase+import com.streamvault.data.local.entity.ProviderWorkflowPhaseState+import com.streamvault.data.local.entity.ProviderWorkflowReason+import com.streamvault.data.local.entity.ProviderWorkflowState+import com.streamvault.domain.model.ProviderType+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.async+import kotlinx.coroutines.awaitAll+import kotlinx.coroutines.test.runTest+import kotlinx.coroutines.withContext+import org.junit.After+import org.junit.Before+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.RuntimeEnvironment++@RunWith(RobolectricTestRunner::class)+class ProviderWorkflowDaoTest {+ private lateinit var database: StreamVaultDatabase++ @Before+ fun setUp() {+ database = Room.inMemoryDatabaseBuilder(+ RuntimeEnvironment.getApplication(),+ StreamVaultDatabase::class.java+ ).allowMainThreadQueries().build()+ }++ @After+ fun tearDown() {+ database.close()+ }++ @Test+ fun `concurrent schedulers grant exactly one workflow lease`() = runTest {+ insertProvider()+ val dao = database.providerWorkflowDao()+ val ticket = dao.request(+ providerId = PROVIDER_ID,+ phase = ProviderWorkflowPhase.PRIMARY_CATALOG,+ reason = ProviderWorkflowReason.PERIODIC,+ now = 100L+ )++ val claims = withContext(Dispatchers.Default) {+ listOf("owner-a", "owner-b").map { token ->+ async {+ dao.claim(+ ticket = ticket,+ token = token,+ now = 101L,+ leaseDurationMs = 1_000L,+ staleHeartbeatBefore = 0L+ )+ }+ }.awaitAll()+ }++ assertThat(claims.count { it != null }).isEqualTo(1)+ val workflow = dao.getWorkflow(PROVIDER_ID)!!+ assertThat(workflow.state).isEqualTo(ProviderWorkflowState.RUNNING)+ assertThat(workflow.leaseToken).isAnyOf("owner-a", "owner-b")+ assertThat(workflow.generation).isEqualTo(1L)+ }++ @Test+ fun `superseding request fences the old owner and records a new generation`() = runTest {+ insertProvider()+ val dao = database.providerWorkflowDao()+ val oldTicket = dao.request(+ providerId = PROVIDER_ID,+ phase = ProviderWorkflowPhase.PRIMARY_CATALOG,+ reason = ProviderWorkflowReason.PERIODIC,+ now = 100L+ )+ val oldLease = checkNotNull(+ dao.claim(oldTicket, "old-owner", 101L, 1_000L, staleHeartbeatBefore = 0L)+ )++ val newTicket = dao.request(+ providerId = PROVIDER_ID,+ phase = ProviderWorkflowPhase.PREPARE,+ reason = ProviderWorkflowReason.CONFIG_CHANGE,+ now = 200L,+ supersede = true,+ priority = 100,+ force = true+ )++ assertThat(newTicket.generation).isEqualTo(oldTicket.generation + 1L)+ assertThat(+ dao.renewLease(+ providerId = oldLease.providerId,+ generation = oldLease.generation,+ phase = oldLease.phase,+ token = oldLease.token,+ now = 201L,+ expiresAt = 1_201L+ )+ ).isEqualTo(0)+ assertThat(dao.complete(oldLease, now = 202L)).isFalse()+ assertThat(dao.getPhases(PROVIDER_ID, oldTicket.generation).single().state)+ .isEqualTo(ProviderWorkflowPhaseState.SUPERSEDED)++ val workflow = dao.getWorkflow(PROVIDER_ID)!!+ assertThat(workflow.generation).isEqualTo(newTicket.generation)+ assertThat(workflow.reason).isEqualTo(ProviderWorkflowReason.CONFIG_CHANGE)+ assertThat(workflow.priority).isEqualTo(100)+ assertThat(workflow.force).isTrue()+ assertThat(workflow.leaseToken).isNull()+ }++ @Test+ fun `ordinary requests join the current generation and serialize added phases`() = runTest {+ insertProvider()+ val dao = database.providerWorkflowDao()+ val catalog = dao.request(+ PROVIDER_ID,+ ProviderWorkflowPhase.PRIMARY_CATALOG,+ ProviderWorkflowReason.STARTUP,+ now = 100L+ )+ val epg = dao.request(+ PROVIDER_ID,+ ProviderWorkflowPhase.EPG,+ ProviderWorkflowReason.MANUAL,+ now = 101L,+ priority = 50+ )++ assertThat(epg.generation).isEqualTo(catalog.generation)+ assertThat(dao.getPhases(PROVIDER_ID, catalog.generation).map { it.phase })+ .containsExactly(ProviderWorkflowPhase.PRIMARY_CATALOG, ProviderWorkflowPhase.EPG)++ val catalogLease = checkNotNull(+ dao.claim(catalog, "catalog", 102L, 1_000L, staleHeartbeatBefore = 0L)+ )+ assertThat(dao.claim(epg, "epg-early", 103L, 1_000L, staleHeartbeatBefore = 0L))+ .isNull()+ assertThat(dao.complete(catalogLease, now = 104L)).isTrue()+ assertThat(dao.getWorkflow(PROVIDER_ID)!!.state).isEqualTo(ProviderWorkflowState.PENDING)++ val epgLease = checkNotNull(+ dao.claim(epg, "epg", 105L, 1_000L, staleHeartbeatBefore = 0L)+ )+ assertThat(dao.complete(epgLease, now = 106L)).isTrue()+ assertThat(dao.getWorkflow(PROVIDER_ID)!!.state).isEqualTo(ProviderWorkflowState.SUCCEEDED)+ }++ @Test+ fun `recovery candidates include expired stale invalid and future heartbeats`() = runTest {+ val dao = database.providerWorkflowDao()+ val now = 10_000L+ val staleBefore = 9_000L+ val heartbeatByProvider = mapOf(+ 1L to 10_000L,+ 2L to staleBefore,+ 3L to 0L,+ 4L to 10_001L+ )++ heartbeatByProvider.forEach { (providerId, heartbeat) ->+ insertProvider(providerId)+ val ticket = dao.request(+ providerId,+ ProviderWorkflowPhase.PRIMARY_CATALOG,+ ProviderWorkflowReason.PERIODIC,+ now = heartbeat+ )+ checkNotNull(+ dao.claim(+ ticket,+ "owner-$providerId",+ heartbeat,+ leaseDurationMs = if (providerId == 3L) 1L else 10_000L,+ staleHeartbeatBefore = Long.MIN_VALUE+ )+ )+ }++ val candidates = dao.getRecoveryCandidates(now, staleBefore)++ assertThat(candidates.map { it.providerId }).containsExactly(2L, 3L, 4L)+ assertThat(candidates.map { it.providerId }).doesNotContain(1L)+ }++ @Test+ fun `retryable failure releases ownership and can be claimed again`() = runTest {+ insertProvider()+ val dao = database.providerWorkflowDao()+ val ticket: ProviderWorkflowTicket = dao.request(+ PROVIDER_ID,+ ProviderWorkflowPhase.MOVIE_INDEX,+ ProviderWorkflowReason.REPAIR,+ now = 100L+ )+ val firstLease = checkNotNull(+ dao.claim(ticket, "first", 101L, 1_000L, staleHeartbeatBefore = 0L)+ )++ assertThat(+ dao.fail(+ lease = firstLease,+ now = 102L,+ errorCode = "NETWORK",+ errorMessage = "temporary",+ retryable = true,+ checkpoint = "page=4"+ )+ ).isTrue()++ val retriedLease = dao.claim(ticket, "second", 103L, 1_000L, staleHeartbeatBefore = 0L)+ assertThat(retriedLease).isNotNull()+ assertThat(dao.getPhases(PROVIDER_ID, ticket.generation).single().attemptCount)+ .isEqualTo(2)+ }++ @Test+ fun `restarted request reclaims stale phase but does not disturb live owner`() = runTest {+ insertProvider()+ val dao = database.providerWorkflowDao()+ val original = dao.request(+ PROVIDER_ID,+ ProviderWorkflowPhase.EPG,+ ProviderWorkflowReason.PERIODIC,+ now = 100L+ )+ checkNotNull(+ dao.claim(original, "old-process", 101L, 100L, staleHeartbeatBefore = 0L)+ )++ val liveJoin = dao.request(+ PROVIDER_ID,+ ProviderWorkflowPhase.EPG,+ ProviderWorkflowReason.RECOVERY,+ now = 150L,+ staleHeartbeatBefore = 0L+ )+ assertThat(dao.claim(liveJoin, "too-early", 150L, 100L, staleHeartbeatBefore = 0L))+ .isNull()+ assertThat(dao.getPhases(PROVIDER_ID, original.generation).single().state)+ .isEqualTo(ProviderWorkflowPhaseState.RUNNING)++ val restarted = dao.request(+ PROVIDER_ID,+ ProviderWorkflowPhase.EPG,+ ProviderWorkflowReason.RECOVERY,+ now = 202L,+ staleHeartbeatBefore = 150L+ )+ val recoveredLease = dao.claim(+ restarted,+ "new-process",+ now = 202L,+ leaseDurationMs = 100L,+ staleHeartbeatBefore = 150L+ )++ assertThat(recoveredLease).isNotNull()+ assertThat(dao.getPhases(PROVIDER_ID, original.generation).single().attemptCount)+ .isEqualTo(2)+ }++ @Test+ fun `lower priority manual request cannot supersede configuration workflow`() = runTest {+ insertProvider()+ val dao = database.providerWorkflowDao()+ val config = dao.request(+ providerId = PROVIDER_ID,+ phase = ProviderWorkflowPhase.PREPARE,+ reason = ProviderWorkflowReason.CONFIG_CHANGE,+ now = 100L,+ supersede = true,+ priority = 100,+ force = true+ )++ val manual = dao.request(+ providerId = PROVIDER_ID,+ phase = ProviderWorkflowPhase.PRIMARY_CATALOG,+ reason = ProviderWorkflowReason.MANUAL,+ now = 101L,+ supersede = true,+ priority = 50,+ force = true+ )++ assertThat(manual.admitted).isFalse()+ assertThat(manual.generation).isEqualTo(config.generation)+ assertThat(dao.claim(manual, "manual", 102L, 1_000L, staleHeartbeatBefore = 0L))+ .isNull()+ val workflow = dao.getWorkflow(PROVIDER_ID)!!+ assertThat(workflow.reason).isEqualTo(ProviderWorkflowReason.CONFIG_CHANGE)+ assertThat(workflow.priority).isEqualTo(100)+ assertThat(dao.getPhases(PROVIDER_ID, config.generation).map { it.phase })+ .containsExactly(ProviderWorkflowPhase.PREPARE)+ }++ private suspend fun insertProvider(providerId: Long = PROVIDER_ID) {+ database.providerDao().insert(+ ProviderEntity(+ id = providerId,+ name = "Provider $providerId",+ type = ProviderType.M3U,+ serverUrl = "https://example.com/$providerId"+ )+ )+ }++ private companion object {+ const val PROVIDER_ID = 1L+ }+}diff --git a/data/src/test/java/com/streamvault/data/manager/BackupManagerImplTest.kt b/data/src/test/java/com/streamvault/data/manager/BackupManagerImplTest.ktindex b32c0b3a..5a7de840 100644--- a/data/src/test/java/com/streamvault/data/manager/BackupManagerImplTest.kt+++ b/data/src/test/java/com/streamvault/data/manager/BackupManagerImplTest.kt@@ -11,21 +11,33 @@ import com.streamvault.data.local.dao.FavoriteDaoimport com.streamvault.data.local.dao.MovieDaoimport com.streamvault.data.local.dao.PlaybackHistoryDaoimport com.streamvault.data.local.dao.ProviderDao+import com.streamvault.data.local.dao.BackupRestoreCheckpointDao+import com.streamvault.data.local.dao.ChannelDaoimport com.streamvault.data.local.dao.RecordingScheduleDaoimport com.streamvault.data.local.dao.VirtualGroupDaoimport com.streamvault.data.local.entity.ProviderEntity+import com.streamvault.data.local.entity.BackupRestoreCheckpointEntity+import com.streamvault.data.local.entity.ChannelEntityimport com.streamvault.data.local.entity.RecordingScheduleEntity+import com.streamvault.data.local.entity.VirtualGroupEntityimport com.streamvault.data.preferences.PreferencesRepositoryimport com.streamvault.data.security.CredentialCryptoimport com.streamvault.domain.manager.BackupDataimport com.streamvault.domain.manager.BackupConflictStrategyimport com.streamvault.domain.manager.BackupImportPlan+import com.streamvault.domain.manager.BackupRestoreOutcome+import com.streamvault.domain.manager.BackupProviderReference+import com.streamvault.domain.manager.PortableCategoryReference+import com.streamvault.domain.manager.PortableChannelReference+import com.streamvault.domain.manager.PortableProviderPreferencesBackup+import com.streamvault.domain.manager.PortableVirtualGroupReferenceimport com.streamvault.domain.manager.RecordingManagerimport com.streamvault.domain.manager.RecordingScheduleImportDispositionimport com.streamvault.domain.manager.ScheduledRecordingBackupimport com.streamvault.domain.model.AppHomeDashboardShelfimport com.streamvault.domain.model.AppTopLevelDestinationimport com.streamvault.domain.model.ContentType+import com.streamvault.domain.model.Categoryimport com.streamvault.domain.model.DecoderModeimport com.streamvault.domain.model.Favoriteimport com.streamvault.domain.model.PlaybackHistory@@ -37,11 +49,21 @@ import com.streamvault.domain.model.RecordingStatusimport com.streamvault.domain.model.Resultimport com.streamvault.domain.repository.CategoryRepositoryimport java.io.ByteArrayInputStream+import java.io.File+import java.io.FileOutputStream+import java.io.InputStream+import kotlinx.coroutines.CancellationException+import kotlinx.coroutines.flow.flowOfimport kotlinx.coroutines.runBlocking+import kotlin.system.measureTimeMillis+import org.junit.Assert.assertThrowsimport org.junit.Testimport org.mockito.kotlin.any+import org.mockito.kotlin.anyOrNullimport org.mockito.kotlin.argThatimport org.mockito.kotlin.doAnswer+import org.mockito.kotlin.doThrow+import org.mockito.kotlin.eqimport org.mockito.kotlin.mockimport org.mockito.kotlin.neverimport org.mockito.kotlin.verify@@ -49,6 +71,195 @@ import org.mockito.kotlin.wheneverclass BackupManagerImplTest {+ @Test+ fun `inspectBackup rejects oversized non seekable input with typed byte limit`() = runBlocking {+ val context: Context = mock()+ val contentResolver: ContentResolver = mock()+ val uri = Uri.parse("content://oversized-stream")+ whenever(context.contentResolver).thenReturn(contentResolver)+ whenever(contentResolver.openInputStream(uri)).thenReturn(+ PrefixThenPaddingInputStream(+ prefix = """{"version":9,"preferences":{"key":"value"}}""".toByteArray(),+ totalBytes = 16 * 1024 * 1024 + 1+ )+ )++ val result = backupManagerForValidation(context).inspectBackup("content://oversized-stream")++ val error = result as Result.Error+ assertThat(error.exception).isInstanceOf(BackupAdmissionException::class.java)+ assertThat((error.exception as BackupAdmissionException).reason)+ .isEqualTo(BackupAdmissionReason.BYTE_LIMIT)+ }++ @Test+ fun `importConfig rejects oversized seekable file before mutation`() = runBlocking {+ val file = File.createTempFile("streamvault-oversized-backup", ".json")+ try {+ FileOutputStream(file).buffered().use { output ->+ output.write("""{"version":9,"preferences":{"key":"value"}}""".toByteArray())+ val padding = ByteArray(64 * 1024) { ' '.code.toByte() }+ repeat(257) { output.write(padding) }+ }+ val preferencesRepository: PreferencesRepository = mock()++ val result = backupManagerForValidation(+ context = mock(),+ preferencesRepository = preferencesRepository+ ).importConfig(file.toURI().toString(), preferencesOnlyPlan())++ val error = result as Result.Error+ assertThat((error.exception as BackupAdmissionException).reason)+ .isEqualTo(BackupAdmissionReason.BYTE_LIMIT)+ verify(preferencesRepository, never()).setParentalControlLevel(any())+ } finally {+ file.delete()+ }+ }++ @Test+ fun `inspectBackup rejects deeply nested json while streaming`() = runBlocking {+ val nested = buildString {+ append("""{"version":9,"unknown":""")+ repeat(65) { append('[') }+ append('0')+ repeat(65) { append(']') }+ append('}')+ }++ val error = inspectAdmissionFailure("deep-json", nested)++ assertThat(error.reason).isEqualTo(BackupAdmissionReason.DEPTH_LIMIT)+ }++ @Test+ fun `inspectBackup rejects million entry section before materializing it`() = runBlocking {+ val json = buildString(2_100_000) {+ append("""{"version":9,"multiViewPresets":{"preset_1":[""")+ repeat(1_000_000) { index ->+ if (index > 0) append(',')+ append('0')+ }+ append("]}}")+ }++ val error = inspectAdmissionFailure("million-entry", json)++ assertThat(error.reason).isEqualTo(BackupAdmissionReason.SECTION_LIMIT)+ assertThat(error.message).contains("preset entries")+ }++ @Test+ fun `inspectBackup rejects overlong strings before object allocation`() = runBlocking {+ val json = """{"version":9,"preferences":{"key":"${"x".repeat(8_193)}"}}"""++ val error = inspectAdmissionFailure("long-string", json)++ assertThat(error.reason).isEqualTo(BackupAdmissionReason.FIELD_LIMIT)+ }++ @Test+ fun `inspectBackup reports malformed and truncated json as typed admission failures`() = runBlocking {+ listOf(+ """{"version":9,"preferences":""",+ """{"version":9,"preferences":{"key":]}"""+ ).forEachIndexed { index, json ->+ val error = inspectAdmissionFailure("malformed-$index", json)+ assertThat(error.reason).isEqualTo(BackupAdmissionReason.MALFORMED)+ }+ }++ @Test+ fun `inspectBackup rejects unsupported version before reading sections`() = runBlocking {+ val error = inspectAdmissionFailure(+ "unsupported-version",+ """{"version":10,"preferences":{"value":"${"x".repeat(8_193)}"}}"""+ )++ assertThat(error.reason).isEqualTo(BackupAdmissionReason.UNSUPPORTED_VERSION)+ }++ @Test+ fun `inspectBackup rejects a missing or displaced version header`() = runBlocking {+ listOf(+ "{}",+ """{"preferences":{},"version":9}"""+ ).forEachIndexed { index, json ->+ val error = inspectAdmissionFailure("missing-header-$index", json)+ assertThat(error.reason).isEqualTo(BackupAdmissionReason.MALFORMED)+ }+ }++ @Test+ fun `inspectBackup rejects duplicate top level fields`() = runBlocking {+ val error = inspectAdmissionFailure(+ "duplicate-field",+ """{"version":9,"preferences":{},"preferences":{}}"""+ )++ assertThat(error.reason).isEqualTo(BackupAdmissionReason.DUPLICATE_FIELD)+ }++ @Test+ fun `inspectBackup propagates cancellation during streaming read`() {+ val context: Context = mock()+ val contentResolver: ContentResolver = mock()+ whenever(context.contentResolver).thenReturn(contentResolver)+ whenever(contentResolver.openInputStream(Uri.parse("content://cancel-mid-read"))).thenReturn(+ CancellingInputStream("""{"version":9,"preferences":{""".toByteArray())+ )++ assertThrows(CancellationException::class.java) {+ runBlocking {+ backupManagerForValidation(context).inspectBackup("content://cancel-mid-read")+ }+ }+ }++ @Test+ fun `recording conflict benchmark remains linear for duplicate heavy sections`() {+ val provider = ProviderEntity(+ id = 7L,+ name = "Provider",+ type = ProviderType.M3U,+ serverUrl = "https://example.com",+ username = "user"+ )+ val incomingItem = ScheduledRecordingBackup(+ providerServerUrl = provider.serverUrl,+ providerUsername = provider.username,+ channelId = 100L,+ channelName = "News",+ streamUrl = "https://example.com/live",+ scheduledStartMs = 1_700_000_000_000L,+ scheduledEndMs = 1_700_000_060_000L+ )+ val existingItem = RecordingItem(+ id = "existing",+ providerId = provider.id,+ channelId = incomingItem.channelId,+ channelName = incomingItem.channelName,+ streamUrl = incomingItem.streamUrl,+ scheduledStartMs = incomingItem.scheduledStartMs,+ scheduledEndMs = incomingItem.scheduledEndMs,+ status = RecordingStatus.SCHEDULED+ )+ val incoming = List(20_000) { incomingItem }+ val existing = List(20_000) { existingItem }+ var conflicts = 0++ val elapsedMs = measureTimeMillis {+ conflicts = backupManagerForValidation(mock()).countScheduledRecordingConflicts(+ incoming = incoming,+ providersByIdentity = mapOf(provider.backupIdentityForTest() to provider),+ existing = existing+ )+ }++ assertThat(conflicts).isEqualTo(incoming.size)+ assertThat(elapsedMs).isLessThan(5_000L)+ }+@Testfun `inspectBackup rejects structurally empty json instead of previewing version zero`() = runBlocking {val context: Context = mock()@@ -63,7 +274,9 @@ class BackupManagerImplTest {val result = manager.inspectBackup("content://empty-backup")assertThat(result).isInstanceOf(Result.Error::class.java)- assertThat((result as Result.Error).message).contains("does not contain any importable data")+ assertThat((result as Result.Error).exception).isInstanceOf(BackupAdmissionException::class.java)+ assertThat((result.exception as BackupAdmissionException).reason)+ .isEqualTo(BackupAdmissionReason.MALFORMED)}@Test@@ -84,7 +297,9 @@ class BackupManagerImplTest {val result = manager.importConfig("content://empty-backup-import")assertThat(result).isInstanceOf(Result.Error::class.java)- assertThat((result as Result.Error).message).contains("does not contain any importable data")+ assertThat((result as Result.Error).exception).isInstanceOf(BackupAdmissionException::class.java)+ assertThat((result.exception as BackupAdmissionException).reason)+ .isEqualTo(BackupAdmissionReason.MALFORMED)verify(preferencesRepository, never()).setParentalControlLevel(any())}@@ -153,7 +368,8 @@ class BackupManagerImplTest {recordingScheduleDao = mock<RecordingScheduleDao>(),recordingManager = mock<RecordingManager>(),transactionRunner = transactionRunner,- gson = gson+ gson = gson,+ channelDao = mock())val result = manager.importConfig(@@ -277,7 +493,8 @@ class BackupManagerImplTest {recordingScheduleDao = mock<RecordingScheduleDao>(),recordingManager = mock<RecordingManager>(),transactionRunner = transactionRunner,- gson = gson+ gson = gson,+ channelDao = mock())val result = manager.importConfig(@@ -363,7 +580,8 @@ class BackupManagerImplTest {transactionRunner = object : DatabaseTransactionRunner {override suspend fun <T> inTransaction(block: suspend () -> T): T = block()},- gson = gson+ gson = gson,+ channelDao = mock())val result = manager.importConfig(@@ -379,10 +597,606 @@ class BackupManagerImplTest {))- assertThat(result).isInstanceOf(Result.Error::class.java)+ assertThat(result).isInstanceOf(Result.Success::class.java)+ assertThat((result as Result.Success).data.outcome)+ .isEqualTo(BackupRestoreOutcome.FAILED_BEFORE_COMMIT)verify(preferencesRepository, never()).setParentalControlLevel(any())}+ @Test+ fun `importConfig reports a preference write failure as partial after room commit`() = runBlocking {+ val context: Context = mock()+ val contentResolver: ContentResolver = mock()+ val preferencesRepository: PreferencesRepository = mock()+ val providerDao: ProviderDao = mock()+ whenever(context.contentResolver).thenReturn(contentResolver)+ whenever(providerDao.getAllSync()).thenReturn(emptyList())+ whenever(contentResolver.openInputStream(Uri.parse("content://backup-preference-partial"))).thenReturn(+ ByteArrayInputStream(Gson().toJson(BackupData(preferences = mapOf("parentalControlLevel" to "4"))).toByteArray())+ )+ doThrow(IllegalStateException("DataStore unavailable"))+ .whenever(preferencesRepository).setParentalControlLevel(4)++ val result = backupManagerForValidation(+ context = context,+ preferencesRepository = preferencesRepository,+ providerDao = providerDao+ ).importConfig(+ uriString = "content://backup-preference-partial",+ plan = BackupImportPlan(+ importPreferences = true,+ importProviders = false,+ importSavedLibrary = false,+ importPlaybackHistory = false,+ importMultiViewPresets = false,+ importRecordingSchedules = false+ )+ )++ assertThat(result).isInstanceOf(Result.Success::class.java)+ val import = (result as Result.Success).data+ assertThat(import.outcome).isEqualTo(BackupRestoreOutcome.PARTIAL)+ assertThat(import.failedSections.single()).contains("Preferences: DataStore unavailable")+ }++ @Test+ fun `importConfig clears optional guide preferences when backup has no selected value`() = runBlocking {+ val context: Context = mock()+ val contentResolver: ContentResolver = mock()+ val preferencesRepository: PreferencesRepository = mock()+ val providerDao: ProviderDao = mock()+ whenever(context.contentResolver).thenReturn(contentResolver)+ whenever(providerDao.getAllSync()).thenReturn(emptyList())+ whenever(contentResolver.openInputStream(Uri.parse("content://backup-guide-defaults"))).thenReturn(+ ByteArrayInputStream(+ Gson().toJson(+ BackupData(+ preferences = mapOf(+ "guideDefaultCategoryId" to "0",+ "guideAnchorTime" to "0"+ )+ )+ ).toByteArray()+ )+ )++ val result = backupManagerForValidation(+ context = context,+ preferencesRepository = preferencesRepository,+ providerDao = providerDao+ ).importConfig(+ uriString = "content://backup-guide-defaults",+ plan = BackupImportPlan(+ importPreferences = true,+ importProviders = false,+ importSavedLibrary = false,+ importPlaybackHistory = false,+ importMultiViewPresets = false,+ importRecordingSchedules = false+ )+ )++ assertThat(result).isInstanceOf(Result.Success::class.java)+ verify(preferencesRepository).clearGuideDefaultCategoryId()+ verify(preferencesRepository).clearGuideAnchorTime()+ Unit+ }++ @Test+ fun `importConfig propagates cancellation without reporting a false outcome`() = runBlocking {+ val context: Context = mock()+ val contentResolver: ContentResolver = mock()+ whenever(context.contentResolver).thenReturn(contentResolver)+ doThrow(CancellationException("cancelled"))+ .whenever(contentResolver).openInputStream(Uri.parse("content://backup-cancelled"))+ val manager = backupManagerForValidation(context = context)++ assertThrows(CancellationException::class.java) {+ runBlocking { manager.importConfig("content://backup-cancelled") }+ }+ Unit+ }++ @Test+ fun `importConfig reports unresolved portable provider preferences without applying raw ids`() = runBlocking {+ val context: Context = mock()+ val contentResolver: ContentResolver = mock()+ val providerDao: ProviderDao = mock()+ val preferencesRepository: PreferencesRepository = mock()+ whenever(context.contentResolver).thenReturn(contentResolver)+ whenever(providerDao.getAllSync()).thenReturn(emptyList())+ whenever(contentResolver.openInputStream(Uri.parse("content://portable-unresolved"))).thenReturn(+ ByteArrayInputStream(+ Gson().toJson(+ BackupData(+ preferences = mapOf("hiddenChannels_2" to "99"),+ portableProviderPreferences = PortableProviderPreferencesBackup(+ providers = listOf(BackupProviderReference("https://missing", "user"))+ )+ )+ ).toByteArray()+ )+ )++ val result = backupManagerForValidation(+ context = context,+ preferencesRepository = preferencesRepository,+ providerDao = providerDao,+ channelDao = mock()+ ).importConfig(+ "content://portable-unresolved",+ BackupImportPlan(+ importPreferences = true,+ importProviders = false,+ importSavedLibrary = false,+ importPlaybackHistory = false,+ importMultiViewPresets = false,+ importRecordingSchedules = false+ )+ )++ val imported = (result as Result.Success).data+ assertThat(imported.outcome).isEqualTo(BackupRestoreOutcome.PARTIAL)+ assertThat(imported.unresolvedReferences).contains("Provider https://missing (user)")+ verify(preferencesRepository, never()).setHiddenChannelIds(2L, setOf(99L))+ Unit+ }++ @Test+ fun `portable export uses semantic identities instead of local provider category group and channel ids`() = runBlocking {+ val context: Context = mock()+ val preferencesRepository: PreferencesRepository = mock()+ val categoryRepository: CategoryRepository = mock()+ val virtualGroupDao: VirtualGroupDao = mock()+ val channelDao: ChannelDao = mock()+ val provider = ProviderEntity(+ id = 2L,+ name = "Source",+ type = ProviderType.XTREAM_CODES,+ serverUrl = "https://example.com",+ username = "user"+ )+ val category = Category(+ id = 50L,+ roomId = 500L,+ name = "News",+ type = ContentType.LIVE+ )+ whenever(preferencesRepository.lastActiveProviderId).thenReturn(flowOf(provider.id))+ whenever(preferencesRepository.guideDefaultCategoryId).thenReturn(flowOf(category.id))+ whenever(preferencesRepository.promotedLiveGroupIds).thenReturn(flowOf(setOf(60L)))+ whenever(preferencesRepository.getHiddenChannelIds(provider.id)).thenReturn(flowOf(setOf(40L)))+ whenever(preferencesRepository.getHiddenCategoryIds(eq(provider.id), any())).thenReturn(flowOf(emptySet()))+ whenever(preferencesRepository.getHiddenCategoryIds(provider.id, ContentType.LIVE))+ .thenReturn(flowOf(setOf(category.id)))+ whenever(categoryRepository.getCategories(provider.id)).thenReturn(flowOf(listOf(category)))+ whenever(virtualGroupDao.getById(60L)).thenReturn(+ VirtualGroupEntity(+ id = 60L,+ providerId = provider.id,+ name = "My News",+ contentType = ContentType.LIVE+ )+ )+ whenever(channelDao.getById(40L)).thenReturn(+ ChannelEntity(+ id = 40L,+ streamId = 400L,+ name = "World News",+ streamUrl = "https://example.com/live/400",+ providerId = provider.id+ )+ )++ val portable = backupManagerForValidation(+ context = context,+ preferencesRepository = preferencesRepository,+ categoryRepository = categoryRepository,+ virtualGroupDao = virtualGroupDao,+ channelDao = channelDao+ ).buildPortableProviderPreferences(listOf(provider))++ val providerReference = BackupProviderReference(provider.serverUrl, provider.username)+ assertThat(portable.providers).containsExactly(providerReference)+ assertThat(portable.activeProvider).isEqualTo(providerReference)+ assertThat(portable.guideDefaultCategory?.remoteCategoryId).isEqualTo(50L)+ assertThat(portable.guideDefaultCategory?.name).isEqualTo("News")+ assertThat(portable.promotedLiveGroups.single().name).isEqualTo("My News")+ assertThat(portable.hiddenChannels.single().streamId).isEqualTo(400L)+ assertThat(portable.hiddenChannels.single().name).isEqualTo("World News")+ assertThat(portable.hiddenCategories.single().remoteCategoryId).isEqualTo(50L)+ assertThat(portable.unresolvedReferences).isEmpty()+ }++ @Test+ fun `semantic json round trip resolves shifted target ids after room restore`() = runBlocking {+ val context: Context = mock()+ val contentResolver: ContentResolver = mock()+ val preferencesRepository: PreferencesRepository = mock()+ val providerDao: ProviderDao = mock()+ val categoryRepository: CategoryRepository = mock()+ val virtualGroupDao: VirtualGroupDao = mock()+ val channelDao: ChannelDao = mock()+ val providerReference = BackupProviderReference("https://example.com", "user")+ val targetProvider = ProviderEntity(+ id = 7L,+ name = "Target",+ type = ProviderType.XTREAM_CODES,+ serverUrl = providerReference.serverUrl,+ username = providerReference.username+ )+ val portable = PortableProviderPreferencesBackup(+ providers = listOf(providerReference),+ activeProvider = providerReference,+ guideDefaultCategory = PortableCategoryReference(+ provider = providerReference,+ name = "News",+ type = ContentType.LIVE,+ remoteCategoryId = 50L+ ),+ guideDefaultCategorySpecified = true,+ promotedLiveGroups = listOf(+ PortableVirtualGroupReference(providerReference, "My News", ContentType.LIVE)+ ),+ hiddenChannels = listOf(+ PortableChannelReference(+ provider = providerReference,+ streamId = 400L,+ name = "World News",+ streamUrl = "https://example.com/live/400"+ )+ ),+ hiddenCategories = listOf(+ PortableCategoryReference(providerReference, "News", ContentType.LIVE, 50L)+ )+ )+ whenever(context.contentResolver).thenReturn(contentResolver)+ whenever(providerDao.getAllSync()).thenReturn(listOf(targetProvider))+ whenever(categoryRepository.getCategories(targetProvider.id)).thenReturn(+ flowOf(listOf(Category(id = 150L, roomId = 1_500L, name = "News", type = ContentType.LIVE)))+ )+ whenever(virtualGroupDao.getByType(targetProvider.id, ContentType.LIVE.name)).thenReturn(+ flowOf(+ listOf(+ VirtualGroupEntity(+ id = 160L,+ providerId = targetProvider.id,+ name = "My News",+ contentType = ContentType.LIVE+ )+ )+ )+ )+ whenever(channelDao.getByProviderSync(targetProvider.id)).thenReturn(+ listOf(+ ChannelEntity(+ id = 140L,+ streamId = 400L,+ name = "World News",+ streamUrl = "https://example.com/live/400",+ providerId = targetProvider.id+ )+ )+ )+ whenever(contentResolver.openInputStream(Uri.parse("content://portable-shifted"))).thenReturn(+ ByteArrayInputStream(+ Gson().toJson(+ BackupData(+ version = 9,+ preferences = mapOf(+ "guideDefaultCategoryId" to "50",+ "promotedLiveGroupIds" to "60",+ "hiddenChannels_2" to "40",+ "hiddenCategories_2_LIVE" to "50"+ ),+ portableProviderPreferences = portable+ )+ ).toByteArray()+ )+ )++ val result = backupManagerForValidation(+ context = context,+ preferencesRepository = preferencesRepository,+ providerDao = providerDao,+ categoryRepository = categoryRepository,+ virtualGroupDao = virtualGroupDao,+ channelDao = channelDao+ ).importConfig("content://portable-shifted", preferencesOnlyPlan())++ val imported = (result as Result.Success).data+ assertThat(imported.outcome).isEqualTo(BackupRestoreOutcome.COMPLETE)+ assertThat(imported.unresolvedReferences).isEmpty()+ verify(preferencesRepository).setLastActiveProviderId(7L)+ verify(preferencesRepository).setGuideDefaultCategoryId(150L)+ verify(preferencesRepository).setPromotedLiveGroupIds(setOf(160L))+ verify(preferencesRepository).setHiddenChannelIds(7L, setOf(140L))+ verify(preferencesRepository).setHiddenCategoryIds(7L, ContentType.LIVE, setOf(150L))+ verify(preferencesRepository, never()).setHiddenChannelIds(2L, setOf(40L))+ }++ @Test+ fun `duplicate semantic group names remain unresolved and are not guessed`() = runBlocking {+ val context: Context = mock()+ val contentResolver: ContentResolver = mock()+ val preferencesRepository: PreferencesRepository = mock()+ val providerDao: ProviderDao = mock()+ val categoryRepository: CategoryRepository = mock()+ val virtualGroupDao: VirtualGroupDao = mock()+ val channelDao: ChannelDao = mock()+ val reference = BackupProviderReference("https://example.com", "user")+ val targetProvider = ProviderEntity(+ id = 7L,+ name = "Target",+ type = ProviderType.XTREAM_CODES,+ serverUrl = reference.serverUrl,+ username = reference.username+ )+ whenever(context.contentResolver).thenReturn(contentResolver)+ whenever(providerDao.getAllSync()).thenReturn(listOf(targetProvider))+ whenever(categoryRepository.getCategories(targetProvider.id)).thenReturn(flowOf(emptyList()))+ whenever(channelDao.getByProviderSync(targetProvider.id)).thenReturn(emptyList())+ whenever(virtualGroupDao.getByType(targetProvider.id, ContentType.LIVE.name)).thenReturn(+ flowOf(+ listOf(+ VirtualGroupEntity(10L, targetProvider.id, "News", contentType = ContentType.LIVE),+ VirtualGroupEntity(11L, targetProvider.id, "NEWS", contentType = ContentType.LIVE)+ )+ )+ )+ whenever(contentResolver.openInputStream(Uri.parse("content://portable-duplicate-group"))).thenReturn(+ ByteArrayInputStream(+ Gson().toJson(+ BackupData(+ portableProviderPreferences = PortableProviderPreferencesBackup(+ providers = listOf(reference),+ promotedLiveGroups = listOf(+ PortableVirtualGroupReference(reference, "News", ContentType.LIVE)+ )+ )+ )+ ).toByteArray()+ )+ )++ val result = backupManagerForValidation(+ context = context,+ preferencesRepository = preferencesRepository,+ providerDao = providerDao,+ categoryRepository = categoryRepository,+ virtualGroupDao = virtualGroupDao,+ channelDao = channelDao+ ).importConfig("content://portable-duplicate-group", preferencesOnlyPlan())++ val imported = (result as Result.Success).data+ assertThat(imported.outcome).isEqualTo(BackupRestoreOutcome.PARTIAL)+ assertThat(imported.unresolvedReferences)+ .contains("Group News [LIVE] at https://example.com")+ verify(preferencesRepository).setPromotedLiveGroupIds(emptySet())+ }++ @Test+ fun `legacy v8 provider scoped ids remain restorable`() = runBlocking {+ val context: Context = mock()+ val contentResolver: ContentResolver = mock()+ val preferencesRepository: PreferencesRepository = mock()+ val providerDao: ProviderDao = mock()+ whenever(context.contentResolver).thenReturn(contentResolver)+ whenever(providerDao.getAllSync()).thenReturn(emptyList())+ whenever(contentResolver.openInputStream(Uri.parse("content://legacy-v8"))).thenReturn(+ ByteArrayInputStream(+ Gson().toJson(+ BackupData(+ version = 8,+ preferences = mapOf(+ "guideDefaultCategoryId" to "50",+ "promotedLiveGroupIds" to "60",+ "hiddenChannels_2" to "40",+ "hiddenCategories_2_LIVE" to "50"+ )+ )+ ).toByteArray()+ )+ )++ val result = backupManagerForValidation(+ context = context,+ preferencesRepository = preferencesRepository,+ providerDao = providerDao+ ).importConfig("content://legacy-v8", preferencesOnlyPlan())++ assertThat((result as Result.Success).data.outcome).isEqualTo(BackupRestoreOutcome.COMPLETE)+ verify(preferencesRepository).setGuideDefaultCategoryId(50L)+ verify(preferencesRepository).setPromotedLiveGroupIds(setOf(60L))+ verify(preferencesRepository).setHiddenChannelIds(2L, setOf(40L))+ verify(preferencesRepository).setHiddenCategoryIds(2L, ContentType.LIVE, setOf(50L))+ }++ @Test+ fun `portable preferences map to the target provider for keep and replace conflicts`() = runBlocking {+ BackupConflictStrategy.entries.forEach { conflictStrategy ->+ val context: Context = mock()+ val contentResolver: ContentResolver = mock()+ val preferencesRepository: PreferencesRepository = mock()+ val providerDao: ProviderDao = mock()+ val categoryRepository: CategoryRepository = mock()+ val virtualGroupDao: VirtualGroupDao = mock()+ val channelDao: ChannelDao = mock()+ val credentialCrypto: CredentialCrypto = mock()+ val sourceProvider = Provider(+ id = 2L,+ name = "Source",+ type = ProviderType.XTREAM_CODES,+ serverUrl = "https://example.com",+ username = "user"+ )+ val targetProvider = ProviderEntity(+ id = 7L,+ name = "Target",+ type = ProviderType.XTREAM_CODES,+ serverUrl = sourceProvider.serverUrl,+ username = sourceProvider.username+ )+ val reference = BackupProviderReference(sourceProvider.serverUrl, sourceProvider.username)+ val uriString = "content://portable-conflict-${conflictStrategy.name}"+ var insertCalls = 0+ whenever(context.contentResolver).thenReturn(contentResolver)+ whenever(providerDao.getAllSync()).thenReturn(listOf(targetProvider))+ doAnswer {+ insertCalls += 1+ targetProvider.id+ }.whenever(providerDao).insert(any())+ whenever(credentialCrypto.encryptIfNeeded(any())).thenReturn("")+ whenever(categoryRepository.getCategories(targetProvider.id)).thenReturn(flowOf(emptyList()))+ whenever(channelDao.getByProviderSync(targetProvider.id)).thenReturn(emptyList())+ whenever(contentResolver.openInputStream(Uri.parse(uriString))).thenReturn(+ ByteArrayInputStream(+ Gson().toJson(+ BackupData(+ providers = listOf(sourceProvider),+ portableProviderPreferences = PortableProviderPreferencesBackup(+ providers = listOf(reference)+ )+ )+ ).toByteArray()+ )+ )++ val result = backupManagerForValidation(+ context = context,+ preferencesRepository = preferencesRepository,+ providerDao = providerDao,+ categoryRepository = categoryRepository,+ virtualGroupDao = virtualGroupDao,+ channelDao = channelDao,+ credentialCrypto = credentialCrypto+ ).importConfig(+ uriString,+ preferencesOnlyPlan().copy(+ importProviders = true,+ conflictStrategy = conflictStrategy+ )+ )++ assertThat((result as Result.Success).data.outcome)+ .isEqualTo(BackupRestoreOutcome.COMPLETE)+ verify(preferencesRepository).setHiddenChannelIds(targetProvider.id, emptySet())+ assertThat(insertCalls).isEqualTo(+ if (conflictStrategy == BackupConflictStrategy.KEEP_EXISTING) 0 else 1+ )+ }+ }++ @Test+ fun `importConfig checkpoints room completion in the same durable restore`() = runBlocking {+ val context: Context = mock()+ val contentResolver: ContentResolver = mock()+ val providerDao: ProviderDao = mock()+ val checkpointDao: BackupRestoreCheckpointDao = mock()+ val gson = Gson()+ var checkpoint: BackupRestoreCheckpointEntity? = null+ whenever(context.contentResolver).thenReturn(contentResolver)+ whenever(providerDao.getAllSync()).thenReturn(emptyList())+ whenever(contentResolver.openInputStream(Uri.parse("content://backup-checkpoint"))).thenReturn(+ ByteArrayInputStream(+ gson.toJson(+ BackupData(+ providers = listOf(+ Provider(+ id = 9L,+ name = "backup provider",+ type = ProviderType.M3U,+ serverUrl = "https://example.com"+ )+ )+ )+ ).toByteArray()+ )+ )+ whenever(checkpointDao.get(any())).thenAnswer { checkpoint }+ doAnswer { invocation ->+ checkpoint = invocation.getArgument(0)+ 1L+ }.whenever(checkpointDao).insertIfAbsent(any())+ doAnswer { invocation ->+ checkpoint = checkpoint!!.copy(+ roomComplete = invocation.getArgument(1),+ preferencesComplete = invocation.getArgument(2),+ presetsComplete = invocation.getArgument(3),+ schedulesComplete = invocation.getArgument(4),+ state = invocation.getArgument(5),+ lastError = invocation.getArgument(6),+ updatedAt = invocation.getArgument(7)+ )+ 1+ }.whenever(checkpointDao).update(any(), any(), any(), any(), any(), any(), anyOrNull(), any())++ val result = backupManagerForValidation(+ context = context,+ providerDao = providerDao,+ checkpointDao = checkpointDao+ ).importConfig(+ uriString = "content://backup-checkpoint",+ plan = BackupImportPlan(+ importPreferences = false,+ importProviders = false,+ importSavedLibrary = true,+ importPlaybackHistory = false,+ importMultiViewPresets = false,+ importRecordingSchedules = false+ )+ )++ assertThat(result).isInstanceOf(Result.Success::class.java)+ assertThat(checkpoint!!.roomComplete).isTrue()+ assertThat(checkpoint!!.state).isEqualTo("COMPLETE")+ }++ @Test+ fun `importConfig retry is a no-op after the same restore checkpoint completed`() = runBlocking {+ val context: Context = mock()+ val contentResolver: ContentResolver = mock()+ val providerDao: ProviderDao = mock()+ val checkpointDao: BackupRestoreCheckpointDao = mock()+ whenever(context.contentResolver).thenReturn(contentResolver)+ whenever(contentResolver.openInputStream(Uri.parse("content://backup-complete-retry"))).thenReturn(+ ByteArrayInputStream(+ Gson().toJson(+ BackupData(+ providers = listOf(+ Provider(+ id = 3L,+ name = "provider",+ type = ProviderType.M3U,+ serverUrl = "https://example.com"+ )+ )+ )+ ).toByteArray()+ )+ )+ whenever(checkpointDao.get(any())).thenReturn(+ BackupRestoreCheckpointEntity(+ restoreKey = "existing",+ roomComplete = true,+ state = "COMPLETE",+ createdAt = 1L,+ updatedAt = 1L+ )+ )++ val result = backupManagerForValidation(+ context = context,+ providerDao = providerDao,+ checkpointDao = checkpointDao+ ).importConfig("content://backup-complete-retry")++ assertThat(result).isInstanceOf(Result.Success::class.java)+ assertThat((result as Result.Success).data.outcome).isEqualTo(BackupRestoreOutcome.COMPLETE)+ verify(providerDao, never()).getAllSync()+ Unit+ }+@Testfun `importConfig restores audio video sync enabled preference`() = runBlocking {val context: Context = mock()@@ -419,7 +1233,8 @@ class BackupManagerImplTest {transactionRunner = object : DatabaseTransactionRunner {override suspend fun <T> inTransaction(block: suspend () -> T): T = block()},- gson = gson+ gson = gson,+ channelDao = mock())val result = manager.importConfig(@@ -563,7 +1378,8 @@ class BackupManagerImplTest {transactionRunner = object : DatabaseTransactionRunner {override suspend fun <T> inTransaction(block: suspend () -> T): T = block()},- gson = gson+ gson = gson,+ channelDao = mock())val result = manager.importConfig(@@ -623,7 +1439,8 @@ class BackupManagerImplTest {transactionRunner = object : DatabaseTransactionRunner {override suspend fun <T> inTransaction(block: suspend () -> T): T = block()},- gson = gson+ gson = gson,+ channelDao = mock())val result = manager.importConfig(@@ -934,6 +1751,60 @@ class BackupManagerImplTest {}}+ @Test+ fun `importScheduledRecordingBackups keeps old schedule when replacement cancellation fails`() = runBlocking {+ val recordingManager: RecordingManager = mock()+ val provider = ProviderEntity(+ id = 7L,+ name = "Provider",+ type = ProviderType.M3U,+ serverUrl = "https://example.com",+ username = "user"+ )+ val existingSchedule = RecordingItem(+ id = "existing-1",+ providerId = 7L,+ channelId = 100L,+ channelName = "BBC One",+ streamUrl = "https://example.com/live.ts",+ scheduledStartMs = 1_700_000_000_000L,+ scheduledEndMs = 1_700_000_540_000L,+ status = RecordingStatus.SCHEDULED+ )+ val imported = ScheduledRecordingBackup(+ providerServerUrl = provider.serverUrl,+ providerUsername = provider.username,+ channelId = 100L,+ channelName = "BBC One",+ streamUrl = "https://example.com/live.ts",+ scheduledStartMs = existingSchedule.scheduledStartMs,+ scheduledEndMs = existingSchedule.scheduledEndMs+ )+ val replacement = existingSchedule.copy(id = "replacement-1")+ whenever(recordingManager.scheduleRecording(any())).thenReturn(Result.success(replacement))+ whenever(recordingManager.cancelRecording(existingSchedule.id)).thenReturn(+ Result.error("old alarm cancellation failed")+ )+ whenever(recordingManager.cancelRecording(replacement.id)).thenReturn(Result.success(Unit))++ val schedules = mutableListOf(existingSchedule)+ val summary = importScheduledRecordingBackups(+ recordings = listOf(imported),+ storedProviders = listOf(provider),+ existingSchedules = schedules,+ conflictStrategy = BackupConflictStrategy.REPLACE_EXISTING,+ recordingManager = recordingManager,+ nowMs = 1_699_999_000_000L+ )++ assertThat(summary.importedCount).isEqualTo(0)+ assertThat(summary.failedCount).isEqualTo(1)+ assertThat(summary.outcomes.single().reason).contains("Could not replace existing schedule")+ assertThat(schedules).containsExactly(existingSchedule)+ verify(recordingManager).cancelRecording(replacement.id)+ Unit+ }+private class RecordingTransactionRunner : DatabaseTransactionRunner {var calls: Int = 0private var depth: Int = 0@@ -952,26 +1823,83 @@ class BackupManagerImplTest {}}+ private suspend fun inspectAdmissionFailure(name: String, json: String): BackupAdmissionException {+ val context: Context = mock()+ val contentResolver: ContentResolver = mock()+ whenever(context.contentResolver).thenReturn(contentResolver)+ whenever(contentResolver.openInputStream(Uri.parse("content://$name"))).thenReturn(+ ByteArrayInputStream(json.toByteArray())+ )+ val result = backupManagerForValidation(context).inspectBackup("content://$name")+ val error = result as Result.Error+ assertThat(error.exception).isInstanceOf(BackupAdmissionException::class.java)+ return error.exception as BackupAdmissionException+ }++ private class PrefixThenPaddingInputStream(+ private val prefix: ByteArray,+ private val totalBytes: Int+ ) : InputStream() {+ private var position = 0++ override fun read(): Int {+ if (position >= totalBytes) return -1+ val value = if (position < prefix.size) prefix[position].toInt() and 0xff else ' '.code+ position += 1+ return value+ }+ }++ private class CancellingInputStream(+ private val prefix: ByteArray+ ) : InputStream() {+ private var position = 0++ override fun read(): Int {+ if (position >= prefix.size) throw CancellationException("cancelled during read")+ return prefix[position++].toInt() and 0xff+ }+ }++ private fun ProviderEntity.backupIdentityForTest(): Triple<String, String, String> =+ Triple(serverUrl, username, stalkerMacAddress)+private fun backupManagerForValidation(context: Context,preferencesRepository: PreferencesRepository = mock(),providerDao: ProviderDao = mock(),+ checkpointDao: BackupRestoreCheckpointDao? = null,+ channelDao: ChannelDao = mock(),+ categoryRepository: CategoryRepository = mock(),+ virtualGroupDao: VirtualGroupDao = mock(),+ credentialCrypto: CredentialCrypto = mock(),): BackupManagerImpl = BackupManagerImpl(context = context,preferencesRepository = preferencesRepository,- credentialCrypto = mock<CredentialCrypto>(),+ credentialCrypto = credentialCrypto,providerDao = providerDao,favoriteDao = mock<FavoriteDao>(),- virtualGroupDao = mock<VirtualGroupDao>(),+ virtualGroupDao = virtualGroupDao,playbackHistoryDao = mock<PlaybackHistoryDao>(),movieDao = mock<MovieDao>(),episodeDao = mock<EpisodeDao>(),- categoryRepository = mock<CategoryRepository>(),+ categoryRepository = categoryRepository,recordingScheduleDao = mock<RecordingScheduleDao>(),recordingManager = mock<RecordingManager>(),transactionRunner = object : DatabaseTransactionRunner {override suspend fun <T> inTransaction(block: suspend () -> T): T = block()},- gson = Gson()+ gson = Gson(),+ backupRestoreCheckpointDao = checkpointDao,+ channelDao = channelDao+ )++ private fun preferencesOnlyPlan() = BackupImportPlan(+ importPreferences = true,+ importProviders = false,+ importSavedLibrary = false,+ importPlaybackHistory = false,+ importMultiViewPresets = false,+ importRecordingSchedules = false)}diff --git a/data/src/test/java/com/streamvault/data/manager/DownloadRecoveryStateMachineTest.kt b/data/src/test/java/com/streamvault/data/manager/DownloadRecoveryStateMachineTest.ktnew file mode 100644index 00000000..be96e948--- /dev/null+++ b/data/src/test/java/com/streamvault/data/manager/DownloadRecoveryStateMachineTest.kt@@ -0,0 +1,195 @@+package com.streamvault.data.manager++import com.google.common.truth.Truth.assertThat+import org.junit.Test++class DownloadRecoveryStateMachineTest {++ @Test+ fun `process death after row transition restarts without trusting missing output`() {+ assertThat(+ planInterruptedDownload(+ bytesWritten = 0L,+ totalBytes = null,+ supportsResume = false,+ targetLength = null+ )+ ).isEqualTo(InterruptedDownloadPlan.RESTART)+ }++ @Test+ fun `process death after target creation restarts zero byte output`() {+ assertThat(+ planInterruptedDownload(+ bytesWritten = 0L,+ totalBytes = 1_000L,+ supportsResume = true,+ targetLength = 0L+ )+ ).isEqualTo(InterruptedDownloadPlan.RESTART)+ }++ @Test+ fun `exact progress checkpoint resumes validated output`() {+ assertThat(+ planInterruptedDownload(+ bytesWritten = 512L,+ totalBytes = 1_000L,+ supportsResume = true,+ targetLength = 512L+ )+ ).isEqualTo(InterruptedDownloadPlan.RESUME)+ }++ @Test+ fun `bytes beyond last checkpoint restart instead of duplicating appended data`() {+ assertThat(+ planInterruptedDownload(+ bytesWritten = 512L,+ totalBytes = 1_000L,+ supportsResume = true,+ targetLength = 700L+ )+ ).isEqualTo(InterruptedDownloadPlan.RESTART)+ }++ @Test+ fun `final bytes persisted before completion update recover as complete`() {+ assertThat(+ planInterruptedDownload(+ bytesWritten = 512L,+ totalBytes = 1_000L,+ supportsResume = true,+ targetLength = 1_000L+ )+ ).isEqualTo(InterruptedDownloadPlan.COMPLETE)+ }++ @Test+ fun `revoked SAF target restarts without attempting append`() {+ assertThat(+ planInterruptedDownload(+ bytesWritten = 512L,+ totalBytes = 1_000L,+ supportsResume = true,+ targetLength = null+ )+ ).isEqualTo(InterruptedDownloadPlan.RESTART)+ }++ @Test+ fun `valid 206 appends from requested byte and trusts content range total`() {+ assertThat(+ resolveResumeResponse(+ resumeFrom = 512L,+ responseCode = 206,+ contentLength = 488L,+ acceptRanges = null,+ contentRange = "bytes 512-999/1000"+ )+ ).isEqualTo(+ DownloadResumeResponse.TRANSFER(+ append = true,+ totalBytes = 1_000L,+ supportsResume = true+ )+ )+ }++ @Test+ fun `resumed request carries exact range and refreshed stream headers`() {+ val request = buildDownloadHttpRequest(+ url = "https://example.com/movie.mp4",+ headers = mapOf("Authorization" to "Bearer refreshed"),+ userAgent = "StreamVault Test",+ resumeFrom = 512L+ )++ assertThat(request.header("Range")).isEqualTo("bytes=512-")+ assertThat(request.header("Authorization")).isEqualTo("Bearer refreshed")+ assertThat(request.header("User-Agent")).isEqualTo("StreamVault Test")+ }++ @Test+ fun `fresh request omits range header`() {+ val request = buildDownloadHttpRequest(+ url = "https://example.com/movie.mp4",+ headers = emptyMap(),+ userAgent = null,+ resumeFrom = 0L+ )++ assertThat(request.header("Range")).isNull()+ }++ @Test+ fun `misaligned 206 restarts instead of corrupting output`() {+ assertThat(+ resolveResumeResponse(+ resumeFrom = 512L,+ responseCode = 206,+ contentLength = 600L,+ acceptRanges = "bytes",+ contentRange = "bytes 400-999/1000"+ )+ ).isEqualTo(DownloadResumeResponse.RESTART)+ }++ @Test+ fun `malformed 206 on fresh request fails instead of restart looping`() {+ assertThat(+ resolveResumeResponse(+ resumeFrom = 0L,+ responseCode = 206,+ contentLength = 600L,+ acceptRanges = "bytes",+ contentRange = null+ )+ ).isEqualTo(DownloadResumeResponse.FAIL)+ }++ @Test+ fun `200 response to range request restarts transfer from zero`() {+ assertThat(+ resolveResumeResponse(+ resumeFrom = 512L,+ responseCode = 200,+ contentLength = 1_000L,+ acceptRanges = "bytes",+ contentRange = null+ )+ ).isEqualTo(+ DownloadResumeResponse.TRANSFER(+ append = false,+ totalBytes = 1_000L,+ supportsResume = true+ )+ )+ }++ @Test+ fun `416 at exact remote length completes existing output`() {+ assertThat(+ resolveResumeResponse(+ resumeFrom = 1_000L,+ responseCode = 416,+ contentLength = 0L,+ acceptRanges = "bytes",+ contentRange = "bytes */1000"+ )+ ).isEqualTo(DownloadResumeResponse.COMPLETE)+ }++ @Test+ fun `416 with different remote length restarts safely`() {+ assertThat(+ resolveResumeResponse(+ resumeFrom = 512L,+ responseCode = 416,+ contentLength = 0L,+ acceptRanges = "bytes",+ contentRange = "bytes */1000"+ )+ ).isEqualTo(DownloadResumeResponse.RESTART)+ }+}diff --git a/data/src/test/java/com/streamvault/data/manager/ProgramReminderManagerImplTest.kt b/data/src/test/java/com/streamvault/data/manager/ProgramReminderManagerImplTest.ktindex 66d66bb6..dcd34451 100644--- a/data/src/test/java/com/streamvault/data/manager/ProgramReminderManagerImplTest.kt+++ b/data/src/test/java/com/streamvault/data/manager/ProgramReminderManagerImplTest.kt@@ -5,16 +5,22 @@ import com.streamvault.data.local.dao.ProgramReminderDaoimport com.streamvault.data.local.entity.ProgramReminderEntityimport com.streamvault.data.manager.reminder.ProgramReminderAlarmSchedulerimport com.streamvault.data.manager.reminder.ProgramReminderNotifier+import com.streamvault.data.manager.reminder.ReminderNotificationResultimport com.streamvault.domain.model.Programimport com.streamvault.domain.model.ProgramReminder+import com.streamvault.domain.model.ProgramReminderDeliveryStateimport com.streamvault.domain.model.Result+import kotlinx.coroutines.CancellationExceptionimport kotlinx.coroutines.flow.Flowimport kotlinx.coroutines.flow.MutableStateFlowimport kotlinx.coroutines.flow.first+import kotlinx.coroutines.runBlockingimport kotlinx.coroutines.test.runTestimport org.junit.Testimport org.mockito.kotlin.argumentCaptor+import org.mockito.kotlin.doThrowimport org.mockito.kotlin.eq+import org.mockito.kotlin.inOrderimport org.mockito.kotlin.mockimport org.mockito.kotlin.neverimport org.mockito.kotlin.verify@@ -35,7 +41,23 @@ class ProgramReminderManagerImplTest {init {whenever(alarmScheduler.canScheduleExactAlarms()).thenReturn(true)whenever(alarmScheduler.schedule(org.mockito.kotlin.any(), org.mockito.kotlin.any())).thenReturn(Result.success(Unit))- whenever(notifier.showReminder(org.mockito.kotlin.any())).thenReturn(Result.success(Unit))+ whenever(notifier.showReminder(org.mockito.kotlin.any())).thenReturn(ReminderNotificationResult.Accepted)+ runBlocking {+ whenever(dao.claimDelivery(org.mockito.kotlin.any(), org.mockito.kotlin.any(), org.mockito.kotlin.any()))+ .thenReturn(1)+ whenever(dao.markDelivered(org.mockito.kotlin.any(), org.mockito.kotlin.any(), org.mockito.kotlin.any()))+ .thenReturn(1)+ whenever(+ dao.markDeliveryIssue(+ org.mockito.kotlin.any(),+ org.mockito.kotlin.any(),+ org.mockito.kotlin.any(),+ org.mockito.kotlin.any()+ )+ ).thenReturn(1)+ whenever(dao.resetInterruptedDelivery(org.mockito.kotlin.any(), org.mockito.kotlin.any()))+ .thenReturn(1)+ }}@Test@@ -59,8 +81,11 @@ class ProgramReminderManagerImplTest {)assertThat(result).isInstanceOf(com.streamvault.domain.model.Result.Success::class.java)- verify(dao).insert(org.mockito.kotlin.any())+ val inserted = argumentCaptor<ProgramReminderEntity>()+ verify(dao).insert(inserted.capture())+ assertThat(inserted.firstValue.exactAlarmArmed).isFalse()verify(alarmScheduler).schedule(eq(42L), org.mockito.kotlin.any())+ verify(dao).setExactAlarmArmed(42L, true)}@Test@@ -87,6 +112,28 @@ class ProgramReminderManagerImplTest {verify(alarmScheduler, never()).schedule(org.mockito.kotlin.any(), org.mockito.kotlin.any())}+ @Test+ fun `permission loss during new reminder scheduling removes unarmed row`() = runTest {+ val now = System.currentTimeMillis()+ val program = Program(+ channelId = "bbc1",+ title = "World News",+ startTime = now + 30 * 60_000L,+ endTime = now + 60 * 60_000L,+ providerId = 7L+ )+ whenever(dao.getByProgram(7L, "bbc1", "World News", program.startTime)).thenReturn(null)+ whenever(dao.insert(org.mockito.kotlin.any())).thenReturn(42L)+ whenever(alarmScheduler.schedule(eq(42L), org.mockito.kotlin.any()))+ .thenReturn(Result.error("permission revoked"))++ val result = manager.scheduleReminder(7L, "bbc1", "BBC One", program, 5)++ assertThat(result).isInstanceOf(Result.Error::class.java)+ verify(dao).deleteById(42L)+ verify(dao, never()).setExactAlarmArmed(42L, true)+ }+@Testfun `scheduleReminder keeps existing reminder when replacement alarm fails`() = runTest {val now = System.currentTimeMillis()@@ -121,6 +168,87 @@ class ProgramReminderManagerImplTest {assertThat(result).isInstanceOf(Result.Error::class.java)verify(dao, never()).update(org.mockito.kotlin.any())verify(alarmScheduler).schedule(42L, existing.remindAt)+ verify(dao).setExactAlarmArmed(42L, false)+ assertThat((result as Result.Error).message).contains("startup repair is pending")+ }++ @Test+ fun `replacement database failure restores prior alarm and keeps prior row`() = runTest {+ val now = System.currentTimeMillis()+ val program = Program(+ channelId = "bbc1",+ title = "World News",+ startTime = now + 30 * 60_000L,+ endTime = now + 60 * 60_000L,+ providerId = 7L+ )+ val existing = ProgramReminderEntity(+ id = 42L,+ providerId = 7L,+ channelId = "bbc1",+ channelName = "BBC One",+ programTitle = program.title,+ programStartTime = program.startTime,+ remindAt = now + 10 * 60_000L,+ leadTimeMinutes = 20+ )+ whenever(dao.getByProgram(7L, "bbc1", "World News", program.startTime)).thenReturn(existing)+ whenever(dao.getById(42L)).thenReturn(existing)+ doThrow(IllegalStateException("disk full")).whenever(dao)+ .update(org.mockito.kotlin.any())++ val result = manager.scheduleReminder(+ providerId = 7L,+ channelId = "bbc1",+ channelName = "BBC One",+ program = program,+ leadTimeMinutes = 5+ )++ assertThat(result).isInstanceOf(Result.Error::class.java)+ val scheduledTimes = argumentCaptor<Long>()+ verify(alarmScheduler, org.mockito.kotlin.times(2)).schedule(eq(42L), scheduledTimes.capture())+ assertThat(scheduledTimes.allValues.last()).isEqualTo(existing.remindAt)+ verify(dao).setExactAlarmArmed(42L, true)+ }++ @Test+ fun `replacement database and rollback failures persist unarmed repair state`() = runTest {+ val now = System.currentTimeMillis()+ val program = Program(+ channelId = "bbc1",+ title = "World News",+ startTime = now + 30 * 60_000L,+ endTime = now + 60 * 60_000L,+ providerId = 7L+ )+ val existing = ProgramReminderEntity(+ id = 42L,+ providerId = 7L,+ channelId = "bbc1",+ channelName = "BBC One",+ programTitle = program.title,+ programStartTime = program.startTime,+ remindAt = now + 10 * 60_000L,+ leadTimeMinutes = 20+ )+ whenever(dao.getByProgram(7L, "bbc1", "World News", program.startTime)).thenReturn(existing)+ whenever(dao.getById(42L)).thenReturn(existing)+ doThrow(IllegalStateException("disk full")).whenever(dao)+ .update(org.mockito.kotlin.any())+ whenever(alarmScheduler.schedule(42L, existing.remindAt)).thenReturn(Result.error("permission revoked"))++ val result = manager.scheduleReminder(+ providerId = 7L,+ channelId = "bbc1",+ channelName = "BBC One",+ program = program,+ leadTimeMinutes = 5+ )++ assertThat(result).isInstanceOf(Result.Error::class.java)+ assertThat((result as Result.Error).message).contains("startup repair is pending")+ verify(dao).setExactAlarmArmed(42L, false)}@Test@@ -148,7 +276,96 @@ class ProgramReminderManagerImplTest {}@Test- fun `restoreScheduledReminders coerces overdue reminder alarms into the future`() = runTest {+ fun `cancelReminder keeps row when alarm cancellation fails`() = runTest {+ val reminder = ProgramReminderEntity(+ id = 42L,+ providerId = 7L,+ channelId = "bbc1",+ channelName = "BBC One",+ programTitle = "World News",+ programStartTime = 1_000L,+ remindAt = 900L+ )+ whenever(dao.getByProgram(7L, "bbc1", "World News", 1_000L)).thenReturn(reminder)+ doThrow(IllegalStateException("alarm service unavailable")).whenever(alarmScheduler).cancel(42L)++ val result = manager.cancelReminder(7L, "bbc1", "World News", 1_000L)++ assertThat(result).isInstanceOf(Result.Error::class.java)+ verify(dao, never()).deleteById(42L)+ }++ @Test+ fun `cancelReminder restores prior alarm when row deletion fails`() = runTest {+ val reminder = ProgramReminderEntity(+ id = 42L,+ providerId = 7L,+ channelId = "bbc1",+ channelName = "BBC One",+ programTitle = "World News",+ programStartTime = 1_000L,+ remindAt = 900L+ )+ whenever(dao.getByProgram(7L, "bbc1", "World News", 1_000L)).thenReturn(reminder)+ whenever(dao.getById(42L)).thenReturn(reminder)+ doThrow(IllegalStateException("database unavailable")).whenever(dao).deleteById(42L)++ val result = manager.cancelReminder(7L, "bbc1", "World News", 1_000L)++ assertThat(result).isInstanceOf(Result.Error::class.java)+ val order = inOrder(alarmScheduler, dao)+ order.verify(alarmScheduler).cancel(42L)+ order.verify(dao).deleteById(42L)+ verify(alarmScheduler).schedule(42L, reminder.remindAt)+ verify(dao).setExactAlarmArmed(42L, true)+ }++ @Test+ fun `cancel rollback failure persists unarmed startup repair state`() = runTest {+ val reminder = ProgramReminderEntity(+ id = 42L,+ providerId = 7L,+ channelId = "bbc1",+ channelName = "BBC One",+ programTitle = "World News",+ programStartTime = 1_000L,+ remindAt = 900L+ )+ whenever(dao.getByProgram(7L, "bbc1", "World News", 1_000L)).thenReturn(reminder)+ whenever(dao.getById(42L)).thenReturn(reminder)+ doThrow(IllegalStateException("database unavailable")).whenever(dao).deleteById(42L)+ whenever(alarmScheduler.schedule(42L, reminder.remindAt)).thenReturn(Result.error("permission revoked"))++ val result = manager.cancelReminder(7L, "bbc1", "World News", 1_000L)++ assertThat(result).isInstanceOf(Result.Error::class.java)+ assertThat((result as Result.Error).message).contains("startup repair is pending")+ verify(dao).setExactAlarmArmed(42L, false)+ }++ @Test+ fun `cancel treats delete exception as success when row is already gone`() = runTest {+ val reminder = ProgramReminderEntity(+ id = 42L,+ providerId = 7L,+ channelId = "bbc1",+ channelName = "BBC One",+ programTitle = "World News",+ programStartTime = 1_000L,+ remindAt = 900L+ )+ whenever(dao.getByProgram(7L, "bbc1", "World News", 1_000L)).thenReturn(reminder)+ whenever(dao.getById(42L)).thenReturn(null)+ doThrow(IllegalStateException("completion acknowledgement lost")).whenever(dao).deleteById(42L)++ val result = manager.cancelReminder(7L, "bbc1", "World News", 1_000L)++ assertThat(result).isInstanceOf(Result.Success::class.java)+ verify(alarmScheduler, never()).schedule(42L, reminder.remindAt)+ }++ @Test+ fun `restoreScheduledReminders delivers overdue reminder immediately`() = runTest {val nowBeforeRestore = System.currentTimeMillis()val reminder = ProgramReminderEntity(id = 42L,@@ -160,13 +377,13 @@ class ProgramReminderManagerImplTest {remindAt = nowBeforeRestore - 60_000L)whenever(dao.getPendingActive(org.mockito.kotlin.any())).thenReturn(listOf(reminder))+ whenever(dao.getById(42L)).thenReturn(reminder)manager.restoreScheduledReminders()- val remindAtCaptor = argumentCaptor<Long>()- verify(alarmScheduler).schedule(eq(42L), remindAtCaptor.capture())- verify(dao).setExactAlarmArmed(42L, true)- assertThat(remindAtCaptor.firstValue).isAtLeast(nowBeforeRestore + 1_000L)+ verify(notifier).showReminder(reminder)+ verify(dao).markDelivered(eq(42L), org.mockito.kotlin.any(), org.mockito.kotlin.any())+ verify(alarmScheduler, never()).schedule(eq(42L), org.mockito.kotlin.any())}@Test@@ -219,6 +436,54 @@ class ProgramReminderManagerImplTest {verify(alarmScheduler).schedule(42L, second.remindAt)}+ @Test+ fun `startup repair restores persisted time after process death during replacement`() = runTest {+ val now = System.currentTimeMillis()+ val persistedPrior = ProgramReminderEntity(+ id = 42L,+ providerId = 7L,+ channelId = "bbc1",+ channelName = "BBC One",+ programTitle = "World News",+ programStartTime = now + 30 * 60_000L,+ remindAt = now + 10 * 60_000L,+ leadTimeMinutes = 20+ )+ val replacementTime = now + 25 * 60_000L+ whenever(dao.getPendingActive(org.mockito.kotlin.any())).thenReturn(listOf(persistedPrior))++ // The prior process scheduled the replacement and died before committing Room.+ alarmScheduler.schedule(42L, replacementTime)+ manager.restoreScheduledReminders()++ val times = argumentCaptor<Long>()+ verify(alarmScheduler, org.mockito.kotlin.times(2)).schedule(eq(42L), times.capture())+ assertThat(times.allValues).containsExactly(replacementTime, persistedPrior.remindAt).inOrder()+ verify(dao).setExactAlarmArmed(42L, true)+ }++ @Test+ fun `startup repair restores persisted alarm after process death during cancellation`() = runTest {+ val now = System.currentTimeMillis()+ val persistedReminder = ProgramReminderEntity(+ id = 42L,+ providerId = 7L,+ channelId = "bbc1",+ channelName = "BBC One",+ programTitle = "World News",+ programStartTime = now + 30 * 60_000L,+ remindAt = now + 10 * 60_000L+ )+ whenever(dao.getPendingActive(org.mockito.kotlin.any())).thenReturn(listOf(persistedReminder))++ // The prior process cancelled AlarmManager and died before deleting Room.+ alarmScheduler.cancel(42L)+ manager.restoreScheduledReminders()++ verify(alarmScheduler).schedule(42L, persistedReminder.remindAt)+ verify(dao).setExactAlarmArmed(42L, true)+ }+@Testfun `deliverReminder notifies once and marks reminder notified`() = runTest {val reminder = ProgramReminderEntity(@@ -235,13 +500,12 @@ class ProgramReminderManagerImplTest {manager.deliverReminder(42L)verify(notifier).showReminder(reminder)- val updatedCaptor = argumentCaptor<ProgramReminderEntity>()- verify(dao).update(updatedCaptor.capture())- assertThat(updatedCaptor.firstValue.notifiedAt).isNotNull()+ verify(dao).claimDelivery(eq(42L), org.mockito.kotlin.any(), org.mockito.kotlin.any())+ verify(dao).markDelivered(eq(42L), org.mockito.kotlin.any(), org.mockito.kotlin.any())}@Test- fun `deliverReminder keeps reminder pending when notification fails`() = runTest {+ fun `deliverReminder persists blocked reason when notification permission is revoked`() = runTest {val reminder = ProgramReminderEntity(id = 42L,providerId = 7L,@@ -252,11 +516,136 @@ class ProgramReminderManagerImplTest {remindAt = System.currentTimeMillis())whenever(dao.getById(42L)).thenReturn(reminder)- whenever(notifier.showReminder(reminder)).thenReturn(Result.error("disabled"))+ whenever(notifier.showReminder(reminder))+ .thenReturn(ReminderNotificationResult.Blocked("Notifications are disabled"))manager.deliverReminder(42L)- verify(dao, never()).update(org.mockito.kotlin.any())+ verify(dao).markDeliveryIssue(+ eq(42L),+ org.mockito.kotlin.any(),+ eq(ProgramReminderDeliveryState.BLOCKED),+ eq("Notifications are disabled")+ )+ }++ @Test+ fun `deliverReminder persists channel disabled as blocked`() = runTest {+ val reminder = deliveryReminder()+ whenever(dao.getById(42L)).thenReturn(reminder)+ whenever(notifier.showReminder(reminder))+ .thenReturn(ReminderNotificationResult.Blocked("Program reminders channel is disabled"))++ manager.deliverReminder(42L)++ verify(dao).markDeliveryIssue(+ eq(42L),+ org.mockito.kotlin.any(),+ eq(ProgramReminderDeliveryState.BLOCKED),+ eq("Program reminders channel is disabled")+ )+ }++ @Test+ fun `deliverReminder persists notifier exception as failed`() = runTest {+ val reminder = deliveryReminder()+ whenever(dao.getById(42L)).thenReturn(reminder)+ doThrow(IllegalStateException("notification service failed"))+ .whenever(notifier).showReminder(reminder)++ manager.deliverReminder(42L)++ verify(dao).markDeliveryIssue(+ eq(42L),+ org.mockito.kotlin.any(),+ eq(ProgramReminderDeliveryState.FAILED),+ eq("Unable to show program reminder.")+ )+ }++ @Test+ fun `process death after notify reconciles visible stable notification without reposting`() = runTest {+ val reminder = deliveryReminder().copy(+ deliveryState = ProgramReminderDeliveryState.DELIVERING,+ deliveryAttemptToken = "prior-attempt",+ deliveryAttemptedAt = System.currentTimeMillis() - 1_000L,+ deliveryAttemptCount = 1+ )+ whenever(dao.getById(42L)).thenReturn(reminder)+ whenever(notifier.isReminderVisible(42L)).thenReturn(true)++ manager.deliverReminder(42L)++ verify(dao).markDelivered(eq(42L), eq("prior-attempt"), org.mockito.kotlin.any())+ verify(notifier, never()).showReminder(org.mockito.kotlin.any())+ verify(dao, never()).claimDelivery(org.mockito.kotlin.any(), org.mockito.kotlin.any(), org.mockito.kotlin.any())+ }++ @Test+ fun `process death before notify retries interrupted claim once`() = runTest {+ val interrupted = deliveryReminder().copy(+ deliveryState = ProgramReminderDeliveryState.DELIVERING,+ deliveryAttemptToken = "prior-attempt",+ deliveryAttemptedAt = System.currentTimeMillis() - 1_000L,+ deliveryAttemptCount = 1+ )+ val pending = interrupted.copy(+ deliveryState = ProgramReminderDeliveryState.PENDING,+ deliveryAttemptToken = null+ )+ whenever(dao.getById(42L)).thenReturn(interrupted, pending)+ whenever(notifier.isReminderVisible(42L)).thenReturn(false)++ manager.deliverReminder(42L)++ verify(dao).resetInterruptedDelivery(42L, "prior-attempt")+ verify(dao).claimDelivery(eq(42L), org.mockito.kotlin.any(), org.mockito.kotlin.any())+ verify(notifier).showReminder(pending)+ verify(dao).markDelivered(eq(42L), org.mockito.kotlin.any(), org.mockito.kotlin.any())+ }++ @Test+ fun `already delivered reminder is deduplicated`() = runTest {+ val reminder = deliveryReminder().copy(+ notifiedAt = System.currentTimeMillis(),+ deliveryState = ProgramReminderDeliveryState.DELIVERED+ )+ whenever(dao.getById(42L)).thenReturn(reminder)++ manager.deliverReminder(42L)++ verify(notifier, never()).showReminder(org.mockito.kotlin.any())+ verify(dao, never()).claimDelivery(org.mockito.kotlin.any(), org.mockito.kotlin.any(), org.mockito.kotlin.any())+ }++ @Test+ fun `reboot recovery immediately retries a due reminder`() = runTest {+ val reminder = deliveryReminder().copy(remindAt = System.currentTimeMillis() - 1_000L)+ whenever(dao.getPendingActive(org.mockito.kotlin.any())).thenReturn(listOf(reminder))+ whenever(dao.getById(42L)).thenReturn(reminder)++ manager.restoreScheduledReminders()++ verify(notifier).showReminder(reminder)+ verify(alarmScheduler, never()).schedule(eq(42L), org.mockito.kotlin.any())+ }++ @Test+ fun `cancellation while claiming delivery propagates without notification`() = runTest {+ val reminder = deliveryReminder()+ whenever(dao.getById(42L)).thenReturn(reminder)+ doThrow(CancellationException("cancelled")).whenever(dao)+ .claimDelivery(eq(42L), org.mockito.kotlin.any(), org.mockito.kotlin.any())++ val thrown = try {+ manager.deliverReminder(42L)+ null+ } catch (error: Throwable) {+ error+ }++ assertThat(thrown).isInstanceOf(CancellationException::class.java)+ verify(notifier, never()).showReminder(org.mockito.kotlin.any())}@Test@@ -279,6 +668,8 @@ class ProgramReminderManagerImplTest {verify(dao).update(updatedCaptor.capture())assertThat(updatedCaptor.firstValue.isDismissed).isTrue()assertThat(updatedCaptor.firstValue.notifiedAt).isNull()+ assertThat(updatedCaptor.firstValue.deliveryState)+ .isEqualTo(ProgramReminderDeliveryState.DISMISSED)}@Test@@ -312,7 +703,8 @@ class ProgramReminderManagerImplTest {override suspend fun getById(id: Long): ProgramReminderEntity? = error("unused")- override suspend fun getPendingActive(now: Long): List<ProgramReminderEntity> = error("unused")+ override suspend fun getPendingActive(activeAfter: Long): List<ProgramReminderEntity> =+ error("unused")override suspend fun insert(reminder: ProgramReminderEntity): Long = error("unused")@@ -320,6 +712,22 @@ class ProgramReminderManagerImplTest {override suspend fun setExactAlarmArmed(id: Long, armed: Boolean) = error("unused")+ override suspend fun claimDelivery(id: Long, attemptToken: String, attemptedAt: Long): Int =+ error("unused")++ override suspend fun markDelivered(id: Long, attemptToken: String, notifiedAt: Long): Int =+ error("unused")++ override suspend fun markDeliveryIssue(+ id: Long,+ attemptToken: String,+ state: ProgramReminderDeliveryState,+ reason: String+ ): Int = error("unused")++ override suspend fun resetInterruptedDelivery(id: Long, attemptToken: String): Int =+ error("unused")+override suspend fun deleteByProgram(providerId: Long,channelId: String,@@ -347,4 +755,14 @@ class ProgramReminderManagerImplTest {val expired = timedManager.observeUpcomingReminders().first()assertThat(expired).isEmpty()}++ private fun deliveryReminder() = ProgramReminderEntity(+ id = 42L,+ providerId = 7L,+ channelId = "bbc1",+ channelName = "BBC One",+ programTitle = "World News",+ programStartTime = System.currentTimeMillis() + 5 * 60_000L,+ remindAt = System.currentTimeMillis()+ )}diff --git a/data/src/test/java/com/streamvault/data/manager/RecordingManagerImplTest.kt b/data/src/test/java/com/streamvault/data/manager/RecordingManagerImplTest.ktindex c34ac818..142e6c0b 100644--- a/data/src/test/java/com/streamvault/data/manager/RecordingManagerImplTest.kt+++ b/data/src/test/java/com/streamvault/data/manager/RecordingManagerImplTest.kt@@ -2,6 +2,7 @@ package com.streamvault.data.managerimport android.app.NotificationManagerimport android.content.ContentResolver+import android.database.sqlite.SQLiteExceptionimport android.content.Contextimport com.google.common.truth.Truth.assertThatimport com.google.gson.Gson@@ -23,13 +24,16 @@ import com.streamvault.data.preferences.PreferencesRepositoryimport com.streamvault.domain.model.ProviderTypeimport com.streamvault.domain.model.RecordingFailureCategoryimport com.streamvault.domain.model.RecordingRecurrence+import com.streamvault.domain.model.RecordingReconciliationResultimport com.streamvault.domain.model.RecordingRequestimport com.streamvault.domain.model.RecordingSourceTypeimport com.streamvault.domain.model.RecordingStatusimport com.streamvault.domain.model.Resultimport java.io.File+import java.io.IOExceptionimport java.util.UUIDimport kotlinx.coroutines.flow.flowOf+import kotlinx.coroutines.CancellationExceptionimport kotlinx.coroutines.runBlockingimport kotlinx.coroutines.withTimeoutimport org.junit.Test@@ -184,7 +188,7 @@ class RecordingManagerImplTest {val manager = createManager()val result = manager.reconcileRecordingState()- assertThat(result).isInstanceOf(com.streamvault.domain.model.Result.Success::class.java)+ assertThat(result).isInstanceOf(RecordingReconciliationResult.Complete::class.java)verify(recordingRunDao, atLeastOnce()).update(argThat {id == staleRun.id &&@@ -203,11 +207,66 @@ class RecordingManagerImplTest {val result = createManager().reconcileRecordingState()- assertThat(result).isInstanceOf(Result.Success::class.java)- verify(recordingRunDao).setExactAlarmArmed(eq(scheduled.id), eq(false), any())+ assertThat(result).isInstanceOf(RecordingReconciliationResult.Complete::class.java)+ verify(recordingRunDao, atLeastOnce()).setExactAlarmArmed(eq(scheduled.id), eq(false), any())verify(alarmScheduler, never()).scheduleStart(any(), any())}+ @Test+ fun `reconcileRecordingState quarantines malformed row and reports partial outcome`(): Unit = runBlocking {+ val malformed = scheduledRun(id = "malformed-row")+ whenever(recordingRunDao.getAlarmManagedScheduledRuns()).thenReturn(listOf(malformed))+ whenever(recordingRunDao.getById(malformed.id)).thenReturn(malformed)+ whenever(alarmScheduler.scheduleStart(malformed.id, malformed.scheduledStartMs)).thenReturn(+ Result.error("Malformed legacy schedule", IllegalArgumentException("bad timestamp"))+ )++ val result = createManager().reconcileRecordingState()++ assertThat(result).isInstanceOf(RecordingReconciliationResult.Partial::class.java)+ val partial = result as RecordingReconciliationResult.Partial+ assertThat(partial.summary.rowsInspected).isEqualTo(1)+ assertThat(partial.summary.rowsQuarantined).isEqualTo(1)+ assertThat(partial.rowFailures.single().recordingId).isEqualTo(malformed.id)+ verify(recordingRunDao, atLeastOnce()).update(+ argThat {+ id == malformed.id &&+ status == RecordingStatus.FAILED &&+ failureReason?.contains("Malformed legacy schedule") == true+ }+ )+ }++ @Test+ fun `reconciliation failure classification separates transient infrastructure from permanent data`() {+ val lockedDatabase: SQLiteException = mock()+ val constraintFailure: SQLiteException = mock()+ whenever(lockedDatabase.message).thenReturn("database is locked")+ whenever(constraintFailure.message).thenReturn("constraint failed")++ assertThat(isTransientRecordingReconciliationFailure(IOException("offline"))).isTrue()+ assertThat(isTransientRecordingReconciliationFailure(lockedDatabase)).isTrue()+ assertThat(isTransientRecordingReconciliationFailure(constraintFailure)).isFalse()+ assertThat(isTransientRecordingReconciliationFailure(IllegalArgumentException("bad row"))).isFalse()+ }++ @Test+ fun `reconcileRecordingState propagates cancellation without terminal classification`() = runBlocking {+ val manager = createManager()+ whenever(recordingRunDao.getAlarmManagedScheduledRuns())+ .thenThrow(CancellationException("test cancellation"))++ var cancellation: CancellationException? = null+ try {+ manager.reconcileRecordingState()+ } catch (caught: CancellationException) {+ cancellation = caught+ }++ assertThat(cancellation).isNotNull()+ assertThat(cancellation?.message).isEqualTo("test cancellation")+ }+@Testfun `foreground service timeout joins capture and persists a terminal reason`() = runBlocking {val activeRun = scheduledRun(id = "quota-timeout", status = RecordingStatus.RECORDING)diff --git a/data/src/test/java/com/streamvault/data/manager/recording/RecordingReconcileWorkerTest.kt b/data/src/test/java/com/streamvault/data/manager/recording/RecordingReconcileWorkerTest.ktindex f7584ff3..a14f71c7 100644--- a/data/src/test/java/com/streamvault/data/manager/recording/RecordingReconcileWorkerTest.kt+++ b/data/src/test/java/com/streamvault/data/manager/recording/RecordingReconcileWorkerTest.kt@@ -1,15 +1,100 @@package com.streamvault.data.manager.recording+import androidx.work.ExistingWorkPolicyimport androidx.work.ListenableWorkerimport com.google.common.truth.Truth.assertThat-import com.streamvault.domain.model.Result+import com.streamvault.domain.model.RecordingReconciliationResult+import com.streamvault.domain.model.RecordingReconciliationRowFailure+import com.streamvault.domain.model.RecordingReconciliationSummaryimport org.junit.Testclass RecordingReconcileWorkerTest {++ @Test+ fun `transient failure retries and a later success completes`() {+ val transient = RecordingReconciliationResult.TransientFailure("database busy")+ val complete = RecordingReconciliationResult.Complete(+ RecordingReconciliationSummary(rowsInspected = 2, rowsRepaired = 1)+ )++ assertThat(reconciliationWorkResult(transient, 0, isOneShot = true))+ .isEqualTo(ListenableWorker.Result.retry())+ assertThat(reconciliationWorkResult(complete, 1, isOneShot = true))+ .isEqualTo(+ ListenableWorker.Result.success(reconciliationDiagnosticData(complete, 1))+ )+ }++ @Test+ fun `permanent failure stops immediately and partial row failure is committed`() {+ val permanent = RecordingReconciliationResult.PermanentFailure("malformed configuration")+ val partial = RecordingReconciliationResult.Partial(+ summary = RecordingReconciliationSummary(+ rowsInspected = 3,+ rowsRepaired = 2,+ rowsQuarantined = 1+ ),+ rowFailures = listOf(+ RecordingReconciliationRowFailure("bad-row", "invalid schedule")+ )+ )++ assertThat(reconciliationWorkResult(permanent, 0, isOneShot = true))+ .isEqualTo(+ ListenableWorker.Result.failure(reconciliationDiagnosticData(permanent, 0))+ )+ assertThat(reconciliationWorkResult(partial, 0, isOneShot = true))+ .isEqualTo(+ ListenableWorker.Result.success(reconciliationDiagnosticData(partial, 0))+ )+ }++ @Test+ fun `one shot transient retry has exponential backoff and a three attempt ceiling`() {+ val transient = RecordingReconciliationResult.TransientFailure("locked")++ assertThat(RECORDING_RECONCILE_BACKOFF_MILLIS).isEqualTo(30_000L)+ assertThat(RECORDING_RECONCILE_MAX_ONE_SHOT_ATTEMPTS).isEqualTo(3)+ assertThat(reconciliationWorkResult(transient, 0, isOneShot = true))+ .isEqualTo(ListenableWorker.Result.retry())+ assertThat(reconciliationWorkResult(transient, 1, isOneShot = true))+ .isEqualTo(ListenableWorker.Result.retry())+ assertThat(reconciliationWorkResult(transient, 2, isOneShot = true))+ .isEqualTo(+ ListenableWorker.Result.failure(reconciliationDiagnosticData(transient, 2))+ )+ }++ @Test+ fun `periodic transient failure is not consumed by one shot ceiling`() {+ val transient = RecordingReconciliationResult.TransientFailure("temporarily unavailable")++ assertThat(reconciliationWorkResult(transient, 9, isOneShot = false))+ .isEqualTo(ListenableWorker.Result.retry())+ }+@Test- fun `permanent reconciliation failures stop after bounded retries`() {- assertThat(reconciliationWorkResult(Result.error("bad row"), 0)).isEqualTo(ListenableWorker.Result.retry())- assertThat(reconciliationWorkResult(Result.error("bad row"), 2)).isEqualTo(ListenableWorker.Result.failure())- assertThat(reconciliationWorkResult(Result.Loading, 0)).isEqualTo(ListenableWorker.Result.failure())+ fun `startup enqueue keeps unfinished one shot instead of resetting attempt history`() {+ assertThat(recordingReconcileOneShotExistingWorkPolicy())+ .isEqualTo(ExistingWorkPolicy.KEEP)+ }++ @Test+ fun `diagnostic metadata reports outcome counts attempt and bounded reason`() {+ val partial = RecordingReconciliationResult.Partial(+ summary = RecordingReconciliationSummary(4, 3, 1),+ rowFailures = listOf(+ RecordingReconciliationRowFailure("row-7", "bad row")+ )+ )++ val diagnostics = reconciliationDiagnosticData(partial, 2)++ assertThat(diagnostics.getString(RECONCILIATION_DIAGNOSTIC_OUTCOME)).isEqualTo("partial")+ assertThat(diagnostics.getInt(RECONCILIATION_DIAGNOSTIC_ATTEMPT, -1)).isEqualTo(2)+ assertThat(diagnostics.getInt(RECONCILIATION_DIAGNOSTIC_INSPECTED, -1)).isEqualTo(4)+ assertThat(diagnostics.getInt(RECONCILIATION_DIAGNOSTIC_REPAIRED, -1)).isEqualTo(3)+ assertThat(diagnostics.getInt(RECONCILIATION_DIAGNOSTIC_QUARANTINED, -1)).isEqualTo(1)+ assertThat(diagnostics.getString(RECONCILIATION_DIAGNOSTIC_MESSAGE)).isEqualTo("bad row")}}diff --git a/data/src/test/java/com/streamvault/data/manager/reminder/ProgramReminderNotifierPolicyTest.kt b/data/src/test/java/com/streamvault/data/manager/reminder/ProgramReminderNotifierPolicyTest.ktnew file mode 100644index 00000000..0102bd15--- /dev/null+++ b/data/src/test/java/com/streamvault/data/manager/reminder/ProgramReminderNotifierPolicyTest.kt@@ -0,0 +1,38 @@+package com.streamvault.data.manager.reminder++import android.app.NotificationManager+import com.google.common.truth.Truth.assertThat+import org.junit.Test++class ProgramReminderNotifierPolicyTest {++ @Test+ fun `runtime notification denial is blocked`() {+ assertThat(+ reminderNotificationBlockedReason(+ notificationsEnabled = false,+ channelImportance = NotificationManager.IMPORTANCE_DEFAULT+ )+ ).isEqualTo(ProgramReminderNotifier.NOTIFICATIONS_DISABLED_REASON)+ }++ @Test+ fun `disabled reminder channel is blocked`() {+ assertThat(+ reminderNotificationBlockedReason(+ notificationsEnabled = true,+ channelImportance = NotificationManager.IMPORTANCE_NONE+ )+ ).isEqualTo(ProgramReminderNotifier.CHANNEL_DISABLED_REASON)+ }++ @Test+ fun `enabled app and channel allow delivery`() {+ assertThat(+ reminderNotificationBlockedReason(+ notificationsEnabled = true,+ channelImportance = NotificationManager.IMPORTANCE_DEFAULT+ )+ ).isNull()+ }+}diff --git a/data/src/test/java/com/streamvault/data/preferences/PreferencesCorruptionRecoveryTest.kt b/data/src/test/java/com/streamvault/data/preferences/PreferencesCorruptionRecoveryTest.ktnew file mode 100644index 00000000..dec64a1b--- /dev/null+++ b/data/src/test/java/com/streamvault/data/preferences/PreferencesCorruptionRecoveryTest.kt@@ -0,0 +1,54 @@+package com.streamvault.data.preferences++import android.content.Context+import androidx.datastore.core.CorruptionException+import androidx.datastore.preferences.core.emptyPreferences+import androidx.datastore.preferences.preferencesDataStoreFile+import com.google.common.truth.Truth.assertThat+import org.junit.After+import org.junit.Before+import org.junit.Test+import org.robolectric.RobolectricTestRunner+import org.junit.runner.RunWith+import org.robolectric.RuntimeEnvironment+import java.io.File++@RunWith(RobolectricTestRunner::class)+class PreferencesCorruptionRecoveryTest {+ private lateinit var context: Context++ @Before+ fun setUp() {+ context = RuntimeEnvironment.getApplication()+ recoveryDirectory().deleteRecursively()+ context.preferencesDataStoreFile(DATASTORE_NAME).delete()+ }++ @After+ fun tearDown() {+ recoveryDirectory().deleteRecursively()+ context.preferencesDataStoreFile(DATASTORE_NAME).delete()+ }++ @Test+ fun `corruption handler returns defaults and retains diagnostic snapshot`() {+ val source = context.preferencesDataStoreFile(DATASTORE_NAME).apply {+ parentFile?.mkdirs()+ writeText("not-a-preferences-protobuf")+ }+ val recovery = PreferencesCorruptionRecovery(context)+ assertThat(recovery.recover(CorruptionException("checksum"), DATASTORE_NAME).asMap())+ .isEqualTo(emptyPreferences().asMap())+ assertThat(recovery.lastRecoveryTimestamp()).isGreaterThan(0L)+ assertThat(recoveryDirectory().resolve("$DATASTORE_NAME.recovery").isFile).isTrue()+ assertThat(recoveryDirectory().listFiles { file, name ->+ name.startsWith("$DATASTORE_NAME.corrupt-")+ }).hasLength(1)+ }++ private fun recoveryDirectory(): File = File(context.filesDir, "preference-recovery")++ companion object {+ private const val DATASTORE_NAME = "user_preferences_corruption_test"+ }+}diff --git a/data/src/test/java/com/streamvault/data/repository/EpgRefreshClockPolicyTest.kt b/data/src/test/java/com/streamvault/data/repository/EpgRefreshClockPolicyTest.ktnew file mode 100644index 00000000..ff98f62b--- /dev/null+++ b/data/src/test/java/com/streamvault/data/repository/EpgRefreshClockPolicyTest.kt@@ -0,0 +1,29 @@+package com.streamvault.data.repository++import com.google.common.truth.Truth.assertThat+import org.junit.Test++class EpgRefreshClockPolicyTest {++ @Test+ fun `future persisted refresh does not rate limit after backward clock jump`() {+ assertThat(+ shouldRateLimitEpgRefresh(+ lastSuccessfulRefreshAt = 10_001L,+ now = 10_000L,+ minimumIntervalMillis = 300_000L+ )+ ).isFalse()+ }++ @Test+ fun `recent persisted refresh still rate limits duplicate owner`() {+ assertThat(+ shouldRateLimitEpgRefresh(+ lastSuccessfulRefreshAt = 10_000L,+ now = 10_001L,+ minimumIntervalMillis = 300_000L+ )+ ).isTrue()+ }+}diff --git a/data/src/test/java/com/streamvault/data/repository/ProviderDeletionCleanupWorkerTest.kt b/data/src/test/java/com/streamvault/data/repository/ProviderDeletionCleanupWorkerTest.ktnew file mode 100644index 00000000..571032a6--- /dev/null+++ b/data/src/test/java/com/streamvault/data/repository/ProviderDeletionCleanupWorkerTest.kt@@ -0,0 +1,245 @@+package com.streamvault.data.repository++import androidx.work.ExistingWorkPolicy+import com.google.common.truth.Truth.assertThat+import com.streamvault.data.local.dao.ProviderDeletionCleanupDao+import com.streamvault.data.local.entity.ProviderDeletionCleanupEntity+import kotlinx.coroutines.CancellationException+import kotlinx.coroutines.test.runTest+import org.junit.Test+import org.junit.Assert.assertThrows++class ProviderDeletionCleanupWorkerTest {++ @Test+ fun `drain completes recording reminder and sync tombstones`() = runTest {+ val dao = FakeCleanupDao(+ listOf(+ cleanup(1, ProviderDeletionCleanupWorker.RECORDING_ALARM, "run-1"),+ cleanup(2, ProviderDeletionCleanupWorker.REMINDER_ALARM, "42"),+ cleanup(3, ProviderDeletionCleanupWorker.SYNC_RUNTIME)+ )+ )+ val actions = mutableListOf<String>()++ val outcome = drainProviderDeletionCleanup(+ dao = dao,+ cancelRecordingAlarm = { actions += "recording:$it" },+ cancelReminderAlarm = { actions += "reminder:$it" },+ cleanupSyncRuntime = { actions += "sync:$it" }+ )++ assertThat(outcome).isEqualTo(ProviderDeletionDrainOutcome.COMPLETE)+ assertThat(actions).containsExactly("recording:run-1", "reminder:42", "sync:7").inOrder()+ assertThat(dao.items).isEmpty()+ }++ @Test+ fun `each external cleanup failure retains its tombstone and requests retry`() = runTest {+ listOf(+ ProviderDeletionCleanupWorker.RECORDING_ALARM,+ ProviderDeletionCleanupWorker.REMINDER_ALARM,+ ProviderDeletionCleanupWorker.SYNC_RUNTIME+ ).forEachIndexed { index, failingAction ->+ val dao = FakeCleanupDao(listOf(cleanup(index + 1L, failingAction, targetFor(failingAction))))++ val outcome = drainProviderDeletionCleanup(+ dao = dao,+ cancelRecordingAlarm = {+ if (failingAction == ProviderDeletionCleanupWorker.RECORDING_ALARM) error("recording failed")+ },+ cancelReminderAlarm = {+ if (failingAction == ProviderDeletionCleanupWorker.REMINDER_ALARM) error("reminder failed")+ },+ cleanupSyncRuntime = {+ if (failingAction == ProviderDeletionCleanupWorker.SYNC_RUNTIME) error("sync failed")+ }+ )++ assertThat(outcome).isEqualTo(ProviderDeletionDrainOutcome.RETRY)+ assertThat(dao.items).hasSize(1)+ assertThat(dao.failureAttempts).containsExactly(index + 1L)+ }+ }++ @Test+ fun `process restart after each side effect replays idempotently and completes tombstone`() = runTest {+ listOf(+ ProviderDeletionCleanupWorker.RECORDING_ALARM,+ ProviderDeletionCleanupWorker.REMINDER_ALARM,+ ProviderDeletionCleanupWorker.SYNC_RUNTIME+ ).forEachIndexed { index, action ->+ val dao = FakeCleanupDao(+ listOf(cleanup(index + 1L, action, targetFor(action)))+ ).apply {+ failNextDelete = true+ }+ var sideEffects = 0++ fun recording(recordingId: String) {+ recordingId.length+ sideEffects += 1+ }+ fun reminder(reminderId: Long) {+ reminderId.toString()+ sideEffects += 1+ }+ suspend fun sync(providerId: Long) {+ providerId.toString()+ sideEffects += 1+ }++ val first = drainProviderDeletionCleanup(dao, ::recording, ::reminder, ::sync)+ val afterRestart = drainProviderDeletionCleanup(dao, ::recording, ::reminder, ::sync)++ assertThat(first).isEqualTo(ProviderDeletionDrainOutcome.RETRY)+ assertThat(afterRestart).isEqualTo(ProviderDeletionDrainOutcome.COMPLETE)+ assertThat(sideEffects).isEqualTo(2)+ assertThat(dao.items).isEmpty()+ }+ }++ @Test+ fun `database read and diagnostic write failures request retry`() = runTest {+ val readFailureDao = FakeCleanupDao(emptyList()).apply { failNextRead = true }+ assertThat(drain(readFailureDao)).isEqualTo(ProviderDeletionDrainOutcome.RETRY)++ val diagnosticFailureDao = FakeCleanupDao(+ listOf(cleanup(1, ProviderDeletionCleanupWorker.RECORDING_ALARM, "run-1"))+ ).apply {+ failRecordFailure = true+ }+ val outcome = drainProviderDeletionCleanup(+ diagnosticFailureDao,+ cancelRecordingAlarm = { error("alarm failure") },+ cancelReminderAlarm = {},+ cleanupSyncRuntime = {}+ )++ assertThat(outcome).isEqualTo(ProviderDeletionDrainOutcome.RETRY)+ assertThat(diagnosticFailureDao.items).hasSize(1)+ }++ @Test+ fun `drain sees tombstones added after its first batch`() = runTest {+ val second = cleanup(2, ProviderDeletionCleanupWorker.REMINDER_ALARM, "42")+ val dao = FakeCleanupDao(+ listOf(cleanup(1, ProviderDeletionCleanupWorker.RECORDING_ALARM, "run-1"))+ ).apply {+ itemToAddAfterFirstDelete = second+ }+ val actions = mutableListOf<String>()++ val outcome = drainProviderDeletionCleanup(+ dao,+ cancelRecordingAlarm = { actions += "recording" },+ cancelReminderAlarm = { actions += "reminder" },+ cleanupSyncRuntime = {}+ )++ assertThat(outcome).isEqualTo(ProviderDeletionDrainOutcome.COMPLETE)+ assertThat(actions).containsExactly("recording", "reminder").inOrder()+ assertThat(dao.items).isEmpty()+ }++ @Test+ fun `repeated drain after completion is a no op`() = runTest {+ val dao = FakeCleanupDao(+ listOf(cleanup(1, ProviderDeletionCleanupWorker.SYNC_RUNTIME))+ )+ var calls = 0++ assertThat(+ drainProviderDeletionCleanup(dao, {}, {}, { calls += 1 })+ ).isEqualTo(ProviderDeletionDrainOutcome.COMPLETE)+ assertThat(+ drainProviderDeletionCleanup(dao, {}, {}, { calls += 1 })+ ).isEqualTo(ProviderDeletionDrainOutcome.COMPLETE)++ assertThat(calls).isEqualTo(1)+ }++ @Test+ fun `cancellation is propagated without consuming tombstone`() {+ val dao = FakeCleanupDao(+ listOf(cleanup(1, ProviderDeletionCleanupWorker.SYNC_RUNTIME))+ )++ assertThrows(CancellationException::class.java) {+ runTest {+ drainProviderDeletionCleanup(+ dao,+ cancelRecordingAlarm = {},+ cancelReminderAlarm = {},+ cleanupSyncRuntime = { throw CancellationException("stopped") }+ )+ }+ }+ assertThat(dao.items).hasSize(1)+ }++ @Test+ fun `new deletion appends reconciliation behind running work`() {+ assertThat(PROVIDER_DELETION_EXISTING_WORK_POLICY)+ .isEqualTo(ExistingWorkPolicy.APPEND_OR_REPLACE)+ }++ private suspend fun drain(dao: ProviderDeletionCleanupDao) =+ drainProviderDeletionCleanup(dao, {}, {}, {})++ private fun cleanup(id: Long, action: String, targetId: String = "") =+ ProviderDeletionCleanupEntity(+ id = id,+ providerId = 7,+ action = action,+ targetId = targetId+ )++ private fun targetFor(action: String): String = when (action) {+ ProviderDeletionCleanupWorker.RECORDING_ALARM -> "run-1"+ ProviderDeletionCleanupWorker.REMINDER_ALARM -> "42"+ else -> ""+ }++ private class FakeCleanupDao(initial: List<ProviderDeletionCleanupEntity>) :+ ProviderDeletionCleanupDao {+ val items = initial.toMutableList()+ val failureAttempts = mutableListOf<Long>()+ var failNextRead = false+ var failNextDelete = false+ var failRecordFailure = false+ var itemToAddAfterFirstDelete: ProviderDeletionCleanupEntity? = null++ override suspend fun insertAll(items: List<ProviderDeletionCleanupEntity>) {+ this.items += items+ }++ override suspend fun getBatch(limit: Int): List<ProviderDeletionCleanupEntity> {+ if (failNextRead) {+ failNextRead = false+ error("database unavailable")+ }+ return items.take(limit)+ }++ override suspend fun countByProvider(providerId: Long): Int =+ items.count { it.providerId == providerId }++ override suspend fun delete(id: Long) {+ if (failNextDelete) {+ failNextDelete = false+ error("process stopped before tombstone commit")+ }+ items.removeAll { it.id == id }+ itemToAddAfterFirstDelete?.let {+ items += it+ itemToAddAfterFirstDelete = null+ }+ }++ override suspend fun recordFailure(id: Long, error: String) {+ if (failRecordFailure) throw IllegalStateException("diagnostic write failed")+ failureAttempts += id+ }+ }+}diff --git a/data/src/test/java/com/streamvault/data/repository/ProviderRepositoryImplTest.kt b/data/src/test/java/com/streamvault/data/repository/ProviderRepositoryImplTest.ktindex 75f4f8a9..2e9ff687 100644--- a/data/src/test/java/com/streamvault/data/repository/ProviderRepositoryImplTest.kt+++ b/data/src/test/java/com/streamvault/data/repository/ProviderRepositoryImplTest.kt@@ -1,6 +1,7 @@package com.streamvault.data.repositoryimport android.content.Context+import com.google.gson.Gsonimport com.google.common.truth.Truth.assertThatimport com.streamvault.data.local.DatabaseTransactionRunnerimport com.streamvault.data.local.dao.CategoryDao@@ -9,11 +10,15 @@ import com.streamvault.data.local.dao.MovieDaoimport com.streamvault.data.local.dao.ProgramDaoimport com.streamvault.data.local.dao.ProgramReminderDaoimport com.streamvault.data.local.dao.ProviderDao+import com.streamvault.data.local.dao.ProviderConfigRevisionDaoimport com.streamvault.data.local.dao.RecordingRunDaoimport com.streamvault.data.local.dao.SeriesDaoimport com.streamvault.data.local.dao.ProviderDeletionCleanupDaoimport com.streamvault.data.local.entity.ProviderEntity+import com.streamvault.data.local.entity.ProviderConfigRevisionStateimport com.streamvault.data.local.entity.CategoryEntity+import com.streamvault.data.local.entity.ProviderWorkflowPhase+import com.streamvault.data.local.entity.ProviderWorkflowReasonimport com.streamvault.data.manager.recording.RecordingAlarmSchedulerimport com.streamvault.data.manager.reminder.ProgramReminderAlarmSchedulerimport com.streamvault.data.preferences.PreferencesRepository@@ -25,6 +30,10 @@ import com.streamvault.data.remote.dto.XtreamServerInfoimport com.streamvault.data.remote.dto.XtreamUserInfoimport com.streamvault.data.security.CredentialCryptoimport com.streamvault.data.sync.SyncManager+import com.streamvault.data.sync.ProviderWorkflowDisposition+import com.streamvault.data.sync.ProviderWorkflowOutcome+import com.streamvault.data.sync.ProviderWorkflowRunner+import com.streamvault.data.sync.ProviderWorkflowCommitFenceimport com.streamvault.domain.model.ProviderEpgSyncModeimport com.streamvault.domain.model.ProviderSavedWithSyncErrorExceptionimport com.streamvault.domain.model.Result@@ -45,6 +54,7 @@ import org.mockito.kotlin.eqimport org.mockito.kotlin.inOrderimport org.mockito.kotlin.mockimport org.mockito.kotlin.never+import org.mockito.kotlin.timesimport org.mockito.kotlin.argumentCaptorimport org.mockito.kotlin.verifyimport org.mockito.kotlin.whenever@@ -70,6 +80,10 @@ class ProviderRepositoryImplTest {private val programReminderAlarmScheduler: ProgramReminderAlarmScheduler = mock()private val jellyfinProvider: JellyfinProvider = mock()private val providerDeletionCleanupDao: ProviderDeletionCleanupDao = mock()+ private val providerDeletionCleanupEnqueuer: ProviderDeletionCleanupEnqueuer = mock()+ private val providerConfigRevisionDao: ProviderConfigRevisionDao = mock()+ private val providerWorkflowRunner: ProviderWorkflowRunner = mock()+ private val gson = Gson()private val appContext: Context = mock()private val transactionRunner = object : DatabaseTransactionRunner {override suspend fun <T> inTransaction(block: suspend () -> T): T = block()@@ -97,6 +111,11 @@ class ProviderRepositoryImplTest {programReminderAlarmScheduler = programReminderAlarmScheduler,jellyfinProvider = jellyfinProvider,providerDeletionCleanupDao = providerDeletionCleanupDao,+ providerDeletionCleanupEnqueuer = providerDeletionCleanupEnqueuer,+ providerConfigRevisionDao = providerConfigRevisionDao,+ gson = gson,+ providerWorkflowRunner = providerWorkflowRunner,+ providerWorkflowCommitFence = ProviderWorkflowCommitFence(),appContext = appContext)@@ -105,11 +124,47 @@ class ProviderRepositoryImplTest {init {whenever(preferencesRepository.xtreamBase64TextCompatibility).thenReturn(flowOf(false))runBlocking {+ whenever(credentialCrypto.encryptIfNeeded(any())).thenAnswer { invocation ->+ invocation.getArgument<String>(0)+ }+ whenever(providerConfigRevisionDao.latestRevision(any())).thenReturn(0L)+ whenever(providerConfigRevisionDao.claimForSync(any(), any(), any())).thenReturn(1)+ whenever(providerConfigRevisionDao.getState(any(), any()))+ .thenReturn(ProviderConfigRevisionState.COMMITTED)+ whenever(+ providerWorkflowRunner.execute(+ any(),+ any(),+ any(),+ any(),+ any(),+ any(),+ any()+ )+ ).thenAnswer { invocation ->+ val block = invocation.getArgument<suspend () -> ProviderWorkflowOutcome>(6)+ when (val outcome = runBlocking { block() }) {+ is ProviderWorkflowOutcome.Success -> ProviderWorkflowDisposition.SUCCEEDED+ is ProviderWorkflowOutcome.Failure -> {+ if (outcome.retryable) {+ ProviderWorkflowDisposition.RETRY+ } else {+ ProviderWorkflowDisposition.FAILED+ }+ }+ }+ }+ whenever(+ syncManager.syncWithProviderOverride(+ any(), any(), anyOrNull(), anyOrNull(), anyOrNull(), any(), anyOrNull(), anyOrNull()+ )+ ).thenReturn(Result.success(Unit))whenever(categoryDao.getByProviderAndTypeSync(any(), any())).thenReturn(emptyList())whenever(programDao.countByProvider(any())).thenReturn(0)whenever(channelDao.countByProvider(any())).thenReturn(0)whenever(movieDao.countByProvider(any())).thenReturn(0)whenever(seriesDao.countByProvider(any())).thenReturn(0)+ whenever(providerDeletionCleanupDao.countByProvider(any())).thenReturn(1)}}@@ -125,8 +180,51 @@ class ProviderRepositoryImplTest {inOrder.verify(programDao).deleteByProvider(7L)inOrder.verify(providerDao).delete(7L)verify(providerDeletionCleanupDao).insertAll(any())- verify(recordingRunDao).getIdsByProvider(7L)- verify(programReminderDao).getIdsByProvider(7L)+ verify(recordingRunDao, times(2)).getIdsByProvider(7L)+ verify(programReminderDao, times(2)).getIdsByProvider(7L)+ }++ @Test+ fun `deleteProvider captures alarm identities inside deletion transaction`() = runTest {+ var insideTransaction = false+ val transactionalRunner = object : DatabaseTransactionRunner {+ override suspend fun <T> inTransaction(block: suspend () -> T): T {+ insideTransaction = true+ return try {+ block()+ } finally {+ insideTransaction = false+ }+ }+ }+ whenever(recordingRunDao.getIdsByProvider(7L)).thenAnswer {+ if (insideTransaction) listOf("run-committed-before-delete") else emptyList()+ }+ whenever(programReminderDao.getIdsByProvider(7L)).thenAnswer {+ if (insideTransaction) listOf(41L) else emptyList()+ }+ val tombstones = argumentCaptor<List<com.streamvault.data.local.entity.ProviderDeletionCleanupEntity>>()++ val result = createRepository(transactionRunner = transactionalRunner).deleteProvider(7L)++ assertThat(result.isSuccess).isTrue()+ verify(providerDeletionCleanupDao).insertAll(tombstones.capture())+ assertThat(tombstones.firstValue.map { it.targetId })+ .containsAtLeast("run-committed-before-delete", "41")+ }++ @Test+ fun `deleteProvider rolls back provider deletion when tombstone insertion fails`() = runTest {+ whenever(recordingRunDao.getIdsByProvider(7L)).thenReturn(listOf("run-1"))+ whenever(programReminderDao.getIdsByProvider(7L)).thenReturn(emptyList())+ doAnswer { throw IllegalStateException("disk full") }+ .whenever(providerDeletionCleanupDao).insertAll(any())++ val result = repository.deleteProvider(7L)++ assertThat(result).isInstanceOf(Result.Error::class.java)+ verify(providerDao, never()).delete(7L)+ verify(providerDeletionCleanupEnqueuer, never()).enqueue()}@Test@@ -171,15 +269,20 @@ class ProviderRepositoryImplTest {}@Test- fun `deleteProvider keeps success after post commit cleanup failure`() = runTest {+ fun `deleteProvider reports cleanup pending when reconciliation enqueue fails`() = runTest {whenever(recordingRunDao.getIdsByProvider(7L)).thenReturn(listOf("run-1"))whenever(programReminderDao.getIdsByProvider(7L)).thenReturn(listOf(11L))- doAnswer { throw IllegalStateException("sync cleanup failed") }- .whenever(syncManager).onProviderDeleted(7L)+ doAnswer { throw IllegalStateException("enqueue failed") }+ .whenever(providerDeletionCleanupEnqueuer).enqueue()+ whenever(providerDeletionCleanupDao.countByProvider(7L)).thenReturn(3)val result = repository.deleteProvider(7L)assertThat(result.isSuccess).isTrue()+ val outcome = (result as Result.Success).data+ assertThat(outcome.cleanupPending).isTrue()+ assertThat(outcome.pendingCleanupActions).isEqualTo(3)+ assertThat(outcome.reconciliationRequested).isFalse()verify(programDao).deleteByProvider(7L)verify(providerDao).delete(7L)verify(providerDeletionCleanupDao).insertAll(any())@@ -323,6 +426,52 @@ class ProviderRepositoryImplTest {assertThat(updatedProvider.firstValue.lastSyncedAt).isGreaterThan(0L)verify(syncManager).scheduleProviderSyncResume(9L)verify(providerDao, never()).setActive(9L)+ verify(providerWorkflowRunner).execute(+ eq(9L),+ eq(ProviderWorkflowPhase.PRIMARY_CATALOG),+ eq(ProviderWorkflowReason.MANUAL),+ eq(false),+ eq(false),+ eq(50),+ any()+ )+ }++ @Test+ fun `forced manual refresh explicitly requests workflow supersession`() = runTest {+ whenever(providerDao.getById(9L)).thenReturn(+ ProviderEntity(+ id = 9L,+ name = "M3U",+ type = ProviderType.M3U,+ serverUrl = "https://example.com/list.m3u",+ m3uUrl = "https://example.com/list.m3u",+ isActive = true,+ status = ProviderStatus.ACTIVE+ )+ )+ whenever(syncManager.sync(9L, true, null, null, null)).thenReturn(Result.success(Unit))+ whenever(syncManager.currentSyncState(9L)).thenReturn(SyncState.Success(123L))+ whenever(channelDao.getCount(9L)).thenReturn(flowOf(1))++ val result = repository.refreshProviderData(+ providerId = 9L,+ force = true,+ movieFastSyncOverride = null,+ epgSyncModeOverride = null,+ onProgress = null+ )++ assertThat(result.isSuccess).isTrue()+ verify(providerWorkflowRunner).execute(+ eq(9L),+ eq(ProviderWorkflowPhase.PRIMARY_CATALOG),+ eq(ProviderWorkflowReason.MANUAL),+ eq(true),+ eq(true),+ eq(50),+ any()+ )}@Test@@ -389,6 +538,47 @@ class ProviderRepositoryImplTest {assertThat(result.isSuccess).isTrue()}+ @Test+ fun `validateM3u failed edit preserves the committed provider row`() = runTest {+ val committedProvider = ProviderEntity(+ id = 5L,+ name = "Committed playlist",+ type = ProviderType.M3U,+ serverUrl = "https://example.com/committed.m3u",+ m3uUrl = "https://example.com/committed.m3u",+ isActive = true,+ status = ProviderStatus.ACTIVE,+ lastSyncedAt = 1234L+ )+ whenever(providerDao.getByUrlAndUser("https://example.com/replacement.m3u", "", ""))+ .thenReturn(null)+ whenever(providerDao.getById(5L)).thenReturn(committedProvider)+ whenever(providerConfigRevisionDao.getState(5L, 1L))+ .thenReturn(ProviderConfigRevisionState.SYNCING)+ whenever(+ syncManager.syncWithProviderOverride(+ eq(5L), eq(false), anyOrNull(), anyOrNull(), anyOrNull(), eq(false), anyOrNull(), anyOrNull()+ )+ ).thenReturn(Result.error("replacement endpoint unavailable"))++ val result = repository.validateM3u(+ url = "https://example.com/replacement.m3u",+ name = "Replacement playlist",+ epgSyncMode = ProviderEpgSyncMode.UPFRONT,+ m3uVodClassificationEnabled = false,+ onProgress = null,+ id = 5L+ )++ assertThat(result.isError).isTrue()+ verify(providerConfigRevisionDao).markFailed(+ eq(5L), eq(1L), any(), any()+ )+ verify(providerDao, never()).update(any())+ verify(providerDao, never()).setActive(5L)+ verify(syncManager, never()).scheduleProviderSyncResume(5L)+ }+@Testfun `setActiveProvider uses transactional activation api`() = runTest {whenever(providerDao.getById(9L)).thenReturn(diff --git a/data/src/test/java/com/streamvault/data/sync/ProviderSyncStateReaderImplTest.kt b/data/src/test/java/com/streamvault/data/sync/ProviderSyncStateReaderImplTest.ktnew file mode 100644index 00000000..4d71bdad--- /dev/null+++ b/data/src/test/java/com/streamvault/data/sync/ProviderSyncStateReaderImplTest.kt@@ -0,0 +1,70 @@+package com.streamvault.data.sync++import com.google.common.truth.Truth.assertThat+import com.streamvault.data.local.dao.ProviderWorkflowDao+import com.streamvault.data.local.dao.XtreamIndexJobDao+import com.streamvault.data.local.entity.ProviderWorkflowEntity+import com.streamvault.data.local.entity.ProviderWorkflowPhase+import com.streamvault.data.local.entity.ProviderWorkflowReason+import com.streamvault.data.local.entity.ProviderWorkflowState+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.flow.flowOf+import kotlinx.coroutines.test.runTest+import org.junit.Test+import org.mockito.kotlin.mock+import org.mockito.kotlin.whenever++class ProviderSyncStateReaderImplTest {+ private val syncManager: SyncManager = mock()+ private val xtreamIndexJobDao: XtreamIndexJobDao = mock()+ private val workflowDao: ProviderWorkflowDao = mock()++ @Test+ fun `durable queued index phase is visible without legacy job state`() = runTest {+ whenever(xtreamIndexJobDao.observeForProvider(PROVIDER_ID)).thenReturn(flowOf(emptyList()))+ whenever(workflowDao.observeWorkflow(PROVIDER_ID)).thenReturn(+ flowOf(+ ProviderWorkflowEntity(+ providerId = PROVIDER_ID,+ generation = 3L,+ state = ProviderWorkflowState.PENDING,+ reason = ProviderWorkflowReason.PERIODIC,+ createdAt = 100L,+ updatedAt = 100L+ )+ )+ )+ whenever(workflowDao.observeActivePhases(PROVIDER_ID)).thenReturn(+ flowOf(listOf(ProviderWorkflowPhase.MOVIE_INDEX))+ )+ val reader = ProviderSyncStateReaderImpl(syncManager, xtreamIndexJobDao, workflowDao)++ assertThat(reader.observeBackgroundIndexingActive(PROVIDER_ID).first()).isTrue()+ }++ @Test+ fun `terminal durable workflow does not report background indexing`() = runTest {+ whenever(xtreamIndexJobDao.observeForProvider(PROVIDER_ID)).thenReturn(flowOf(emptyList()))+ whenever(workflowDao.observeWorkflow(PROVIDER_ID)).thenReturn(+ flowOf(+ ProviderWorkflowEntity(+ providerId = PROVIDER_ID,+ generation = 3L,+ state = ProviderWorkflowState.SUCCEEDED,+ reason = ProviderWorkflowReason.PERIODIC,+ createdAt = 100L,+ updatedAt = 200L,+ completedAt = 200L+ )+ )+ )+ whenever(workflowDao.observeActivePhases(PROVIDER_ID)).thenReturn(flowOf(emptyList()))+ val reader = ProviderSyncStateReaderImpl(syncManager, xtreamIndexJobDao, workflowDao)++ assertThat(reader.observeBackgroundIndexingActive(PROVIDER_ID).first()).isFalse()+ }++ private companion object {+ const val PROVIDER_ID = 7L+ }+}diff --git a/data/src/test/java/com/streamvault/data/sync/ProviderSyncWorkerTest.kt b/data/src/test/java/com/streamvault/data/sync/ProviderSyncWorkerTest.ktindex a42ef4b9..d0ca79af 100644--- a/data/src/test/java/com/streamvault/data/sync/ProviderSyncWorkerTest.kt+++ b/data/src/test/java/com/streamvault/data/sync/ProviderSyncWorkerTest.kt@@ -7,6 +7,7 @@ import com.streamvault.data.local.dao.ProviderDaoimport com.streamvault.data.local.dao.XtreamLiveOnboardingDaoimport com.streamvault.data.local.entity.CategoryEntityimport com.streamvault.data.local.entity.ProviderEntity+import com.streamvault.data.local.entity.XtreamIndexJobEntityimport com.streamvault.data.local.entity.XtreamLiveOnboardingStateEntityimport com.streamvault.domain.model.ContentTypeimport com.streamvault.domain.model.ProviderStatus@@ -62,6 +63,100 @@ class ProviderSyncWorkerTest {).isTrue()}+ @Test+ fun `process death orphan is recoverable even when prior success is fresh`() {+ val persistedAfterProcessDeath = XtreamIndexJobEntity(+ providerId = 7L,+ section = ContentType.MOVIE.name,+ state = "RUNNING",+ lastSuccessAt = 9_999L,+ updatedAt = 1_000L+ )++ assertThat(+ shouldRunPersistedIndexJob(+ job = persistedAfterProcessDeath,+ now = 10_000L,+ staleRunningAfterMillis = 1_000L,+ successTtlMillis = 24 * 60 * 60 * 1_000L+ )+ ).isTrue()+ }++ @Test+ fun `backward clock jump makes persisted running owner recoverable`() {+ val running = XtreamIndexJobEntity(+ providerId = 7L,+ section = ContentType.SERIES.name,+ state = "RUNNING",+ updatedAt = 10_001L+ )++ assertThat(+ shouldRunPersistedIndexJob(running, 10_000L, 1_000L, 86_400_000L)+ ).isTrue()+ }++ @Test+ fun `forward clock jump makes persisted running owner recoverable`() {+ val running = XtreamIndexJobEntity(+ providerId = 7L,+ section = ContentType.SERIES.name,+ state = "RUNNING",+ updatedAt = 10_000L+ )++ assertThat(+ shouldRunPersistedIndexJob(running, 20_000L, 1_000L, 86_400_000L)+ ).isTrue()+ }++ @Test+ fun `running owner is stale at exact threshold`() {+ val running = XtreamIndexJobEntity(+ providerId = 7L,+ section = ContentType.MOVIE.name,+ state = "RUNNING",+ updatedAt = 10_000L+ )++ assertThat(+ shouldRunPersistedIndexJob(running, 11_000L, 1_000L, 86_400_000L)+ ).isTrue()+ }++ @Test+ fun `zero and negative running timestamps are recoverable`() {+ listOf(0L, -1L).forEach { invalidTimestamp ->+ val running = XtreamIndexJobEntity(+ providerId = 7L,+ section = ContentType.MOVIE.name,+ state = "RUNNING",+ updatedAt = invalidTimestamp+ )++ assertThat(+ shouldRunPersistedIndexJob(running, 10_000L, 1_000L, 86_400_000L)+ ).isTrue()+ }+ }++ @Test+ fun `fresh persisted running owner does not admit duplicate recovery`() {+ val running = XtreamIndexJobEntity(+ providerId = 7L,+ section = ContentType.MOVIE.name,+ state = "RUNNING",+ updatedAt = 10_000L+ )++ repeat(32) {+ assertThat(+ shouldRunPersistedIndexJob(running, 10_999L, 1_000L, 86_400_000L)+ ).isFalse()+ }+ }+@Testfun `xtream provider with incomplete onboarding state is tracked for initial live resume`() = runTest {val provider = ProviderEntity(diff --git a/data/src/test/java/com/streamvault/data/sync/ProviderWorkLockRegistryTest.kt b/data/src/test/java/com/streamvault/data/sync/ProviderWorkLockRegistryTest.ktnew file mode 100644index 00000000..18e4420e--- /dev/null+++ b/data/src/test/java/com/streamvault/data/sync/ProviderWorkLockRegistryTest.kt@@ -0,0 +1,96 @@+package com.streamvault.data.sync++import com.google.common.truth.Truth.assertThat+import kotlinx.coroutines.CompletableDeferred+import kotlinx.coroutines.ExperimentalCoroutinesApi+import kotlinx.coroutines.async+import kotlinx.coroutines.test.runCurrent+import kotlinx.coroutines.test.runTest+import org.junit.Test++@OptIn(ExperimentalCoroutinesApi::class)+class ProviderWorkLockRegistryTest {+ @Test+ fun `same provider phases are serialized`() = runTest {+ val registry = ProviderWorkLockRegistry()+ val firstEntered = CompletableDeferred<Unit>()+ val releaseFirst = CompletableDeferred<Unit>()+ val secondEntered = CompletableDeferred<Unit>()++ val first = async {+ registry.withProviderLock(7L) {+ firstEntered.complete(Unit)+ releaseFirst.await()+ }+ }+ firstEntered.await()++ val second = async {+ registry.withProviderLock(7L) {+ secondEntered.complete(Unit)+ }+ }+ runCurrent()++ assertThat(secondEntered.isCompleted).isFalse()+ assertThat(registry.isAnyWorkActiveOrWaiting()).isTrue()++ releaseFirst.complete(Unit)+ first.await()+ second.await()++ assertThat(secondEntered.isCompleted).isTrue()+ assertThat(registry.isAnyWorkActiveOrWaiting()).isFalse()+ }++ @Test+ fun `different providers retain independent execution lanes`() = runTest {+ val registry = ProviderWorkLockRegistry()+ val firstEntered = CompletableDeferred<Unit>()+ val releaseFirst = CompletableDeferred<Unit>()+ val secondEntered = CompletableDeferred<Unit>()++ val first = async {+ registry.withProviderLock(7L) {+ firstEntered.complete(Unit)+ releaseFirst.await()+ }+ }+ firstEntered.await()++ val second = async {+ registry.withProviderLock(8L) {+ secondEntered.complete(Unit)+ }+ }+ runCurrent()++ assertThat(secondEntered.isCompleted).isTrue()++ releaseFirst.complete(Unit)+ first.await()+ second.await()+ }++ @Test+ fun `maintenance admission rejects active or queued provider work`() = runTest {+ val registry = ProviderWorkLockRegistry()+ val firstEntered = CompletableDeferred<Unit>()+ val releaseFirst = CompletableDeferred<Unit>()++ val providerWork = async {+ registry.withProviderLock(7L) {+ firstEntered.complete(Unit)+ releaseFirst.await()+ }+ }+ firstEntered.await()++ assertThat(registry.runWhenNoWorkActive { true }).isFalse()++ releaseFirst.complete(Unit)+ providerWork.await()++ assertThat(registry.runWhenNoWorkActive { true }).isTrue()+ }+}diff --git a/data/src/test/java/com/streamvault/data/sync/ProviderWorkSchedulingTest.kt b/data/src/test/java/com/streamvault/data/sync/ProviderWorkSchedulingTest.ktnew file mode 100644index 00000000..3b06b44d--- /dev/null+++ b/data/src/test/java/com/streamvault/data/sync/ProviderWorkSchedulingTest.kt@@ -0,0 +1,36 @@+package com.streamvault.data.sync++import androidx.work.ExistingWorkPolicy+import com.google.common.truth.Truth.assertThat+import org.junit.Test++class ProviderWorkSchedulingTest {+ @Test+ fun `all provider phases resolve to one unique work identity`() {+ val identities = listOf(+ providerWorkUniqueName(7L),+ providerWorkUniqueName(7L),+ providerWorkUniqueName(7L),+ providerWorkUniqueName(7L)+ )++ assertThat(identities.distinct()).containsExactly("provider-workflow-7")+ }++ @Test+ fun `ordinary provider phases append without inheriting failed prerequisites`() {+ assertThat(providerWorkExistingPolicy(supersede = false))+ .isEqualTo(ExistingWorkPolicy.APPEND_OR_REPLACE)+ }++ @Test+ fun `configuration revision explicitly supersedes older provider work`() {+ assertThat(providerWorkExistingPolicy(supersede = true))+ .isEqualTo(ExistingWorkPolicy.REPLACE)+ }++ @Test(expected = IllegalArgumentException::class)+ fun `provider work identity rejects invalid provider id`() {+ providerWorkUniqueName(0L)+ }+}diff --git a/data/src/test/java/com/streamvault/data/sync/ProviderWorkflowCommitFenceTest.kt b/data/src/test/java/com/streamvault/data/sync/ProviderWorkflowCommitFenceTest.ktnew file mode 100644index 00000000..e9f29225--- /dev/null+++ b/data/src/test/java/com/streamvault/data/sync/ProviderWorkflowCommitFenceTest.kt@@ -0,0 +1,141 @@+package com.streamvault.data.sync++import androidx.room.Room+import com.google.common.truth.Truth.assertThat+import com.streamvault.data.local.RoomDatabaseTransactionRunner+import com.streamvault.data.local.StreamVaultDatabase+import com.streamvault.data.local.entity.ChannelEntity+import com.streamvault.data.local.entity.ProviderEntity+import com.streamvault.data.local.entity.ProviderWorkflowPhase+import com.streamvault.data.local.entity.ProviderWorkflowReason+import com.streamvault.domain.model.ProviderType+import kotlinx.coroutines.test.runTest+import kotlinx.coroutines.withContext+import org.junit.After+import org.junit.Before+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.RuntimeEnvironment++@RunWith(RobolectricTestRunner::class)+class ProviderWorkflowCommitFenceTest {+ private lateinit var database: StreamVaultDatabase++ @Before+ fun setUp() {+ database = Room.inMemoryDatabaseBuilder(+ RuntimeEnvironment.getApplication(),+ StreamVaultDatabase::class.java+ ).allowMainThreadQueries().build()+ }++ @After+ fun tearDown() {+ database.close()+ }++ @Test+ fun `superseded generation cannot apply staged catalog rows`() = runTest {+ insertProvider()+ database.channelDao().insertAll(listOf(channel(name = "Committed", streamUrl = "old")))+ val workflowDao = database.providerWorkflowDao()+ val ticket = workflowDao.request(+ PROVIDER_ID,+ ProviderWorkflowPhase.PRIMARY_CATALOG,+ ProviderWorkflowReason.PERIODIC,+ now = 100L+ )+ val staleLease = checkNotNull(+ workflowDao.claim(ticket, "old-owner", 101L, 1_000L, staleHeartbeatBefore = 0L)+ )+ workflowDao.request(+ PROVIDER_ID,+ ProviderWorkflowPhase.PREPARE,+ ProviderWorkflowReason.CONFIG_CHANGE,+ now = 200L,+ supersede = true,+ force = true+ )++ val error = runCatching {+ withContext(ProviderWorkflowExecutionContext(staleLease)) {+ store().replaceLiveCatalog(+ providerId = PROVIDER_ID,+ categories = null,+ channels = listOf(channel(name = "Stale replacement", streamUrl = "new"))+ )+ }+ }.exceptionOrNull()++ assertThat(error).isInstanceOf(ProviderWorkflowSupersededException::class.java)+ val retained = database.channelDao().getByProviderSync(PROVIDER_ID)+ assertThat(retained).hasSize(1)+ assertThat(retained.single().name).isEqualTo("Committed")+ assertThat(retained.single().streamUrl).isEqualTo("old")+ }++ @Test+ fun `current generation applies catalog inside fenced transaction`() = runTest {+ insertProvider()+ val workflowDao = database.providerWorkflowDao()+ val ticket = workflowDao.request(+ PROVIDER_ID,+ ProviderWorkflowPhase.PRIMARY_CATALOG,+ ProviderWorkflowReason.MANUAL,+ now = 100L+ )+ val lease = checkNotNull(+ workflowDao.claim(ticket, "manual-owner", 101L, 1_000L, staleHeartbeatBefore = 0L)+ )++ withContext(ProviderWorkflowExecutionContext(lease)) {+ store().replaceLiveCatalog(+ providerId = PROVIDER_ID,+ categories = null,+ channels = listOf(channel(name = "Fresh", streamUrl = "fresh"))+ )+ }++ assertThat(database.channelDao().getByProviderSync(PROVIDER_ID).single().name)+ .isEqualTo("Fresh")+ }++ private fun store() = SyncCatalogStore(+ channelDao = database.channelDao(),+ movieDao = database.movieDao(),+ seriesDao = database.seriesDao(),+ categoryDao = database.categoryDao(),+ catalogSyncDao = database.catalogSyncDao(),+ tmdbIdentityDao = database.tmdbIdentityDao(),+ transactionRunner = RoomDatabaseTransactionRunner(database),+ workflowCommitFence = ProviderWorkflowCommitFence(database.providerWorkflowDao())+ )++ private suspend fun insertProvider() {+ database.providerDao().insert(+ ProviderEntity(+ id = PROVIDER_ID,+ name = "Provider",+ type = ProviderType.M3U,+ serverUrl = "https://example.com"+ )+ )+ }++ private fun channel(+ name: String,+ streamUrl: String,+ id: Long = 0L+ ) = ChannelEntity(+ id = id,+ streamId = 10L,+ name = name,+ streamUrl = streamUrl,+ providerId = PROVIDER_ID+ )++ private companion object {+ const val PROVIDER_ID = 1L+ }+}diff --git a/data/src/test/java/com/streamvault/data/sync/ProviderWorkflowRunnerTest.kt b/data/src/test/java/com/streamvault/data/sync/ProviderWorkflowRunnerTest.ktnew file mode 100644index 00000000..0dfb0abc--- /dev/null+++ b/data/src/test/java/com/streamvault/data/sync/ProviderWorkflowRunnerTest.kt@@ -0,0 +1,165 @@+package com.streamvault.data.sync++import androidx.room.Room+import com.google.common.truth.Truth.assertThat+import com.streamvault.data.local.StreamVaultDatabase+import com.streamvault.data.local.entity.ProviderEntity+import com.streamvault.data.local.entity.ProviderWorkflowPhase+import com.streamvault.data.local.entity.ProviderWorkflowPhaseState+import com.streamvault.data.local.entity.ProviderWorkflowReason+import com.streamvault.data.local.entity.ProviderWorkflowState+import com.streamvault.domain.model.ProviderType+import java.io.IOException+import kotlinx.coroutines.CompletableDeferred+import kotlinx.coroutines.async+import kotlinx.coroutines.test.runTest+import org.junit.After+import org.junit.Before+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.RuntimeEnvironment++@RunWith(RobolectricTestRunner::class)+class ProviderWorkflowRunnerTest {+ private lateinit var database: StreamVaultDatabase+ private lateinit var runner: ProviderWorkflowRunner++ @Before+ fun setUp() {+ database = Room.inMemoryDatabaseBuilder(+ RuntimeEnvironment.getApplication(),+ StreamVaultDatabase::class.java+ ).allowMainThreadQueries().build()+ runner = ProviderWorkflowRunner(database.providerWorkflowDao())+ }++ @After+ fun tearDown() {+ database.close()+ }++ @Test+ fun `successful execution publishes the terminal phase and workflow`() = runTest {+ insertProvider()++ val disposition = runner.execute(+ providerId = PROVIDER_ID,+ phase = ProviderWorkflowPhase.EPG,+ reason = ProviderWorkflowReason.PERIODIC+ ) {+ ProviderWorkflowOutcome.Success(checkpoint = "window=complete")+ }++ assertThat(disposition).isEqualTo(ProviderWorkflowDisposition.SUCCEEDED)+ val workflow = database.providerWorkflowDao().getWorkflow(PROVIDER_ID)!!+ assertThat(workflow.state).isEqualTo(ProviderWorkflowState.SUCCEEDED)+ val phase = database.providerWorkflowDao()+ .getPhases(PROVIDER_ID, workflow.generation)+ .single()+ assertThat(phase.state).isEqualTo(ProviderWorkflowPhaseState.SUCCEEDED)+ assertThat(phase.checkpoint).isEqualTo("window=complete")+ }++ @Test+ fun `retryable execution publishes durable retry state`() = runTest {+ insertProvider()++ val disposition = runner.execute(+ providerId = PROVIDER_ID,+ phase = ProviderWorkflowPhase.CONTENT_INDEX,+ reason = ProviderWorkflowReason.PERIODIC+ ) {+ ProviderWorkflowOutcome.Failure(+ code = "NETWORK",+ message = "offline",+ cause = IOException("offline")+ )+ }++ assertThat(disposition).isEqualTo(ProviderWorkflowDisposition.RETRY)+ val workflow = database.providerWorkflowDao().getWorkflow(PROVIDER_ID)!!+ assertThat(workflow.state).isEqualTo(ProviderWorkflowState.PENDING)+ assertThat(workflow.lastErrorCode).isEqualTo("NETWORK")+ assertThat(+ database.providerWorkflowDao()+ .getPhases(PROVIDER_ID, workflow.generation)+ .single()+ .state+ ).isEqualTo(ProviderWorkflowPhaseState.FAILED_RETRYABLE)+ }++ @Test+ fun `supersession during execution prevents old completion publication`() = runTest {+ insertProvider()+ val dao = database.providerWorkflowDao()++ val disposition = runner.execute(+ providerId = PROVIDER_ID,+ phase = ProviderWorkflowPhase.PRIMARY_CATALOG,+ reason = ProviderWorkflowReason.PERIODIC+ ) {+ dao.request(+ providerId = PROVIDER_ID,+ phase = ProviderWorkflowPhase.PREPARE,+ reason = ProviderWorkflowReason.CONFIG_CHANGE,+ now = System.currentTimeMillis(),+ supersede = true,+ force = true+ )+ ProviderWorkflowOutcome.Success()+ }++ assertThat(disposition).isEqualTo(ProviderWorkflowDisposition.SUPERSEDED)+ val workflow = dao.getWorkflow(PROVIDER_ID)!!+ assertThat(workflow.generation).isEqualTo(2L)+ assertThat(workflow.state).isEqualTo(ProviderWorkflowState.PENDING)+ }++ @Test+ fun `overlapping execution is told to retry while current owner retains lease`() = runTest {+ insertProvider()+ val started = CompletableDeferred<Unit>()+ val release = CompletableDeferred<Unit>()+ val first = async {+ runner.execute(+ providerId = PROVIDER_ID,+ phase = ProviderWorkflowPhase.EPG,+ reason = ProviderWorkflowReason.PERIODIC+ ) {+ started.complete(Unit)+ release.await()+ ProviderWorkflowOutcome.Success()+ }+ }+ started.await()++ val overlapping = runner.execute(+ providerId = PROVIDER_ID,+ phase = ProviderWorkflowPhase.EPG,+ reason = ProviderWorkflowReason.MANUAL,+ priority = 50+ ) {+ ProviderWorkflowOutcome.Success()+ }++ assertThat(overlapping).isEqualTo(ProviderWorkflowDisposition.BUSY)+ release.complete(Unit)+ assertThat(first.await()).isEqualTo(ProviderWorkflowDisposition.SUCCEEDED)+ }++ private suspend fun insertProvider() {+ database.providerDao().insert(+ ProviderEntity(+ id = PROVIDER_ID,+ name = "Provider",+ type = ProviderType.M3U,+ serverUrl = "https://example.com"+ )+ )+ }++ private companion object {+ const val PROVIDER_ID = 1L+ }+}diff --git a/data/src/test/java/com/streamvault/data/sync/SyncManagerTest.kt b/data/src/test/java/com/streamvault/data/sync/SyncManagerTest.ktindex 7e913983..0ebee9d0 100644--- a/data/src/test/java/com/streamvault/data/sync/SyncManagerTest.kt+++ b/data/src/test/java/com/streamvault/data/sync/SyncManagerTest.kt@@ -370,7 +370,8 @@ class SyncManagerTest {syncMetadataRepository = syncMetadataRepo,transactionRunner = transactionRunner,preferencesRepository = preferencesRepo,- syncProgressBus = SyncProgressBus()+ syncProgressBus = SyncProgressBus(),+ providerWorkflowCommitFence = ProviderWorkflowCommitFence())// ── Initial state ───────────────────────────────────────────────diff --git a/docs/IPTV_CODE_REVIEW.md b/docs/IPTV_CODE_REVIEW.mdindex b9fd7241..b417f233 100644--- a/docs/IPTV_CODE_REVIEW.md+++ b/docs/IPTV_CODE_REVIEW.md@@ -169,7 +169,7 @@ App update checking starts from `StreamVaultApp` and stores cached release metad| ARCH-005 | Architectural concern | High | `PlayerViewModel` is a 25+ dependency feature orchestrator that crosses domain/data/player boundaries. | Architectural || ARCH-006 | Highly likely defect | High | Plugin discovery performs multiple blocking IPC calls and maps plugin providers into M3U records. | Local + architectural || ARCH-007 | Architectural concern | Medium | Database schema and the full migration history are concentrated in one multi-thousand-line class. | Architectural |-| ARCH-008 | Suspected risk | Medium | Startup launches several overlapping background pipelines with independent work identities and state stores. | Architectural |+| ARCH-008 | Implemented; device validation pending | Medium | Startup launches several overlapping background pipelines with independent work identities and state stores. | Architectural |## Detailed Phase 1 findings@@ -259,8 +259,9 @@ App update checking starts from `StreamVaultApp` and stores cached release metad### ARCH-008 — Background work is fragmented across independently scheduled pipelines-- **Classification:** Suspected risk requiring further verification+- **Classification:** Implemented; device integration validation pending- **Severity:** Medium+- **Implementation status (2026-07-30):** Implemented in code; device integration validation pending. The migration introduces one provider work identity, one in-process provider execution lane, a central startup-work registry, and a durable Room-backed workflow/phase coordinator with generation-fenced catalog and status commits. Configuration revisions explicitly supersede older work; ordinary sync, index, and EPG requests join the provider chain.- **Where:** `StreamVaultApp.onCreate:74-97`; `ProviderSyncWorker`; `XtreamIndexWorker`; `StalkerIndexWorker`; `BackgroundEpgSyncWorker`; `RecordingReconcileWorker`; scheduling methods inside `SyncManager`.- **Current behavior:** Every process start enqueues maintenance, provider stale-check, Xtream index stale-check, and recording reconciliation, while periodic equivalents also exist. Provider sync can queue provider-specific index and EPG workers. Each class has separate unique names, `KEEP`/`REPLACE`/`APPEND_OR_REPLACE` policy, retry classification, delays, and persisted job metadata. In-process provider mutexes serialize some `SyncManager` calls but do not by themselves define a durable cross-worker state machine.- **Why this is wrong/fragile:** WorkManager uniqueness prevents duplicates only within an identical unique name. Different worker types can target the same provider and network/database concurrently. Status is distributed across WorkManager, Room job tables, provider status, sync metadata, and in-memory `SyncStateTracker`, so cancellation/process death may leave contradictory state.@@ -269,6 +270,45 @@ App update checking starts from `StreamVaultApp` and stores cached release metad- **Fix scope:** Architectural.- **Required tests:** Simultaneous launch workers; manual refresh during each worker phase; process death and restart; stale WorkManager input after provider edit/delete; network loss and retry across phases; verify one authoritative user-visible status.+**Implementation evidence (2026-07-30, slice 1):**++- `StartupWorkRegistry` is now the sole durable-work registration entry point called by `StreamVaultApp`; data maintenance uses periodic `UPDATE` so changed constraints are applied without creating a second schedule.+- Provider resume, Xtream index, Stalker index, background EPG, and provider-configuration recovery now resolve to one `provider-workflow-{providerId}` unique chain. Ordinary phases use `APPEND_OR_REPLACE`; configuration recovery uses `REPLACE` as an explicit superseding operation.+- `ProviderWorkLockRegistry` replaces the separate full-sync, Stalker-summary, and Stalker-EPG mutex ownership paths. All `SyncManager` provider operations now share one per-provider execution lane while different providers can still execute concurrently.+- This slice closes same-process overlap and centralizes scheduling policy.++**Implementation evidence (2026-07-30, slice 2):**++- Room schema version 71 adds `provider_workflows`, the authoritative current generation/state/lease row for each provider, plus `provider_workflow_phases`, a per-generation phase ledger for prepare, catalog, index, EPG, and finalize work.+- `ProviderWorkflowDao.request` gives ordinary startup/periodic/manual work explicit join semantics and gives configuration changes explicit supersede semantics. Supersession atomically increments the generation, clears the prior lease, and marks unfinished older phases `SUPERSEDED`.+- Lease claim, renewal, completion, and failure all require provider ID, generation, phase, and an opaque lease token. A worker from an older generation therefore cannot renew or publish completion after a provider edit supersedes it.+- Lease expiry and heartbeat recovery handle expired, missing, stale, invalid, and future-clock state. Retryable failures preserve phase checkpoints and return the phase to the durable pending workflow.+- `ProviderWorkflowDaoTest` covers concurrent claim exclusion, join/phase serialization, generation fencing, retry, and restart candidate selection. `MIGRATION_70_71` and its `MigrationTestHelper` case validate both new tables, indices, and cascade ownership for upgraded installations.++**Implementation evidence (2026-07-30, slice 3):**++- `ProviderWorkflowRunner` is now the common execution boundary for full provider sync, configuration-revision recovery, Xtream indexing, Stalker indexing, and background EPG. It claims an opaque generation-bound lease before entering `SyncManager`, renews that lease during long calls, and publishes success, partial, retryable failure, or permanent failure through the phase ledger.+- `ProviderWorkFailureClassifier` consolidates the duplicated network/SQLite retry rule used by those workers. Worker result mapping now follows the durable disposition: busy or retryable work retries, permanent failure fails, and a superseded generation exits without overwriting the newer workflow result.+- A restarted request can atomically reclaim a `RUNNING` phase only when its lease is expired, missing, stale, or has a future-clock heartbeat. A live lease is left untouched. This closes the process-death loop for WorkManager's persisted retries without requiring an in-memory owner to release its mutex.+- `ProviderWorkflowRunnerTest` covers durable success and retry publication, overlapping-owner admission, and supersession during execution. `ProviderWorkflowDaoTest` additionally covers stale-process reclaim while proving that a live owner is not disturbed.++**Implementation evidence (2026-07-30, slice 4):**++- `ProviderRepositoryImpl.refreshProviderData` now executes through `ProviderWorkflowRunner`. A forced manual refresh explicitly supersedes background work at priority 50; a non-forced refresh joins the current generation and reports a busy workflow instead of starting a second sync.+- Workflow admission is priority-aware inside the Room transaction. Configuration changes (priority 100) cannot be displaced by manual refresh (50), and manual work cannot be displaced by periodic/startup work (0). Rejected lower-priority requests do not mutate the generation, reason, or phase ledger.+- `ProviderWorkflowExecutionContext` carries the claimed generation/token through the sync coroutine. Every `SyncCatalogStore` apply path now checks that token inside the same Room transaction that applies staged categories/channels/movies/series. Supersession and catalog commit are therefore serialized: whichever transaction commits first determines whether the old apply is accepted or rejected.+- `ProviderWorkflowCommitFenceTest` proves that a superseded generation cannot replace committed catalog rows and that the current owner can apply normally. Manual-refresh tests verify explicit join versus supersede arguments, and DAO tests cover configuration-over-manual priority inversion.+- `ProviderSyncStateReaderImpl` now combines durable active workflow phases with the legacy Xtream job table, so queued/running movie or series indexing remains observable after process recreation.+- Provider sync timestamps, sync metadata, discovered M3U EPG URLs, manual status reconciliation, and targeted-worker status reconciliation are now checked inside generation-owned transactions before publication. ARCH-008 remains open only for device-backed process-kill and manual-refresh-during-each-phase integration tests, plus final removal or demotion of redundant legacy status stores after UI compatibility is verified.++**Implementation evidence (2026-07-30, slice 5):**++- `ProviderWorkflowIntegrationTest` adds file-backed Room instrumentation coverage for the remaining coordinator boundaries. It closes and reopens the database to model process recreation, then proves that an expired durable phase lease can be reclaimed without relying on in-memory ownership.+- The integration matrix forces a manual refresh while each background phase owns the workflow (`PRIMARY_CATALOG`, `CONTENT_INDEX`, `MOVIE_INDEX`, `SERIES_INDEX`, `EPG`, and `FINALIZE`). In every case the old generation loses commit authority and the manual generation can claim the phase. A separate case proves that manual priority cannot supersede an active configuration migration.+- The data module now declares `AndroidJUnitRunner`; both the new integration suite and the 70-to-71 migration test compile and package successfully with `:data:assembleDebugAndroidTest`.+- A targeted `:data:connectedDebugAndroidTest` run was attempted on 2026-07-30, but ADB reported no attached device and Gradle stopped with `DeviceException: No connected devices!`. These cases are implemented but must still be executed on an Android device/emulator; this is why the finding remains **Implemented; device integration validation pending**.+- After device execution, the remaining architectural cleanup is to remove or explicitly demote redundant legacy status stores once UI compatibility has been verified.+## Phase 1 open questions1. Which historical app/database versions are actually in the supported upgrade window? Phase 4 migration coverage depends on this.@@ -322,10 +362,10 @@ Phase 2 should review these files/modules first, in this order:| PERF-001 | Playback snapshots synchronously rewrite a file every second on main | Resolved (2026-07-26) | High || PERF-002 | VOD progress triggers DB and Android TV rewrites every five seconds | Resolved (2026-07-26) | High || WORK-001 | Local database maintenance is incorrectly gated on connectivity | Resolved (2026-07-26) | Medium |-| WORK-002 | Recording reconciliation retries every error without classification/cap | Resolved (2026-07-26) | Medium |-| UPDATE-001 | Failed automatic update checks suppress another attempt for 24 hours | Resolved (2026-07-26) | Medium |+| WORK-002 | Recording reconciliation retries every error without classification/cap | Resolved (2026-07-29) | Medium |+| UPDATE-001 | Failed automatic update checks suppress another attempt for 24 hours | Resolved (2026-07-29) | Medium || MEMORY-001 | Process-lifetime maps grow with provider/category/host/media identities | Architectural concern | Medium |-| PERSIST-001 | The central preferences DataStore has no explicit corruption recovery | Suspected risk | Medium |+| PERSIST-001 | The central preferences DataStore has no explicit corruption recovery | Implemented; boundary verification pending (2026-07-30) | Medium || TEST-001 | The player suite asserts the opposite MPEG-TS extractor policy from production | Resolved (2026-07-26) | Medium |The urgent shared fixes are cancellation-safe HTTP, recording/timeshift lifecycle ownership, M3U admission limits, and removal of main-thread/per-five-second persistence churn. These can cause work after cancellation, contradictory terminal state, retained resources, storage exhaustion, and playback jank independently of provider protocol correctness.@@ -360,7 +400,7 @@ The urgent shared fixes are cancellation-safe HTTP, recording/timeshift lifecycl### SYNC-001 — M3U staging has no effective response or catalog-size bound-- **Classification:** Resolved (2026-07-26)+- **Classification:** Resolved (2026-07-29)- **Severity:** High- **Where:** `SyncManagerM3uImporter.kt:60-220,236-267,314-320`; `SyncCatalogStore.kt:331-379`; compare `NetworkTimeoutConfig` and `CatalogSizeLimits` used by non-staging paths.- **Current behavior:** The importer does not bound `Content-Length`, decompressed bytes/lines, entries, or categories. It retains unbounded live/movie identity sets and category accumulators. M3U uses `stageChannelBatch`/`stageMovieBatch` then `finalizeStagedImport`, bypassing catalog limits applied by other store methods.@@ -462,28 +502,31 @@ The urgent shared fixes are cancellation-safe HTTP, recording/timeshift lifecycl### WORK-002 — Recording reconciliation retries every error without classification or cap-- **Classification:** Confirmed defect+- **Classification:** Resolved (2026-07-29)- **Severity:** Medium-- **Where:** `RecordingReconcileWorker.kt:17-67`; `RecordingManagerImpl.reconcileRecordingState:279-444`.-- **Current behavior:** Every domain `Error` and even `Loading` maps to `Result.retry()`, without explicit backoff, attempt ceiling, or category. Startup replaces a one-shot while periodic work runs every six hours.+- **Where:** `RecordingReconcileWorker.kt`; `RecordingManagerImpl.reconcileRecordingState`; typed contract in `RecordingModels.kt` and `RecordingManager.kt`.+- **Original behavior:** Every domain `Error` and even `Loading` mapped to `Result.retry()`, without explicit backoff, attempt ceiling, or category. A preliminary correction added a three-attempt ceiling and exponential backoff, but still classified every error as transient, returned only `Result<Unit>`, swallowed cancellation through `runCatching`, emitted no diagnostic metadata, and used startup `REPLACE`, which reset the unfinished one-shot and its attempt history.- **Why this is wrong/fragile:** Permanent row/configuration failures retry indefinitely. Startup replacement can reset the history of a repeatedly failing one-shot and diagnostics cannot distinguish causes.- **Concrete failure scenario:** A malformed legacy recording row fails deterministically; each launch replaces/restarts work and WorkManager repeatedly scans state without quarantining it.- **Recommended correction:** Return typed transient/permanent/per-row outcomes, quarantine/report bad rows, cap one-shot attempts with exponential backoff, and make `Loading` impossible as a terminal return.- **Fix scope:** Worker plus result refinement.- **Required tests:** Transient then success, permanent/partial row failure, ceiling/backoff, cancellation, startup replacement, and diagnostic metadata.+- **Resolution:** Recording reconciliation now returns the closed `Complete`, `Partial`, `TransientFailure`, or `PermanentFailure` contract; `Loading` is not representable. Deterministic row failures are marked `FAILED` with a persisted quarantine reason and accumulated into a partial report without blocking healthy rows. I/O and locked/busy database failures remain retryable, other global failures terminate, and `CancellationException` is always rethrown without a status write. The one-shot uses 30-second exponential backoff, stops after three attempts, and startup/boot enqueue uses unique `KEEP` ownership so another launch cannot reset an unfinished attempt chain. Periodic transient work remains retryable independently. Success/failure output and retry progress carry bounded outcome, attempt, inspected, repaired, quarantined, and reason diagnostics.+- **Verification:** `RecordingReconcileWorkerTest` covers transient-then-success, permanent and partial outcomes, the one-shot ceiling/backoff, periodic independence, startup `KEEP`, and diagnostic fields. `RecordingManagerImplTest` covers row quarantine/persisted reason, transient/permanent classification, cancellation propagation, stale capture repair, and exact-alarm reconciliation. The focused 17-test data matrix and full domain test task passed, and `:app:assembleDebug` passed on 2026-07-29.### UPDATE-001 — Failed automatic update checks suppress another attempt for 24 hours-- **Classification:** Resolved (2026-07-26)+- **Classification:** Resolved (2026-07-29)- **Severity:** Medium-- **Where:** `StreamVaultApp.refreshCachedAppUpdateIfNeeded:105-132`; `GitHubReleaseChecker.kt:39-68`; `PreferencesRepository.kt:748-778`; similar ordering in `SettingsAppUpdateActions.kt:42-55`.-- **Current behavior:** Startup writes the last-check timestamp before fetching. Only success refreshes cache; error is ignored. The timestamp gates checks for 24 hours, treating transient failure as success.+- **Where:** `AppUpdateCheckWorker.kt`; `GitHubReleaseChecker.kt:39-68`; `PreferencesRepository.kt`; `SettingsAppUpdateActions.kt:42-55`.+- **Original behavior:** Startup wrote the last-check timestamp before fetching. Only success refreshed cache; error was ignored. The timestamp gated checks for 24 hours, treating transient failure as success.- **Why this is wrong/fragile:** Last attempt and last success require different retry semantics; update discovery depends on being online at one startup and stale cache has no observable reason.- **Concrete failure scenario:** The TV starts before Wi-Fi, records the attempt, fails, then stays online all day without another automatic check.- **Recommended correction:** Store separate attempt/success/outcome. Rate-limit success for 24 hours, use short bounded failure backoff, and preferably use network-constrained unique WorkManager work. Preserve valid cache on failure.- **Fix scope:** Local/shared startup-settings policy.- **Required tests:** Offline then reconnect, 429/500, malformed response, cached success then failure, restart, force check, and clock changes.-- **Resolution:** Successful checks retain the 24-hour cadence; failed checks persist separately and retry after a 15-minute bounded backoff without overwriting valid cached release data.+- **Resolution:** Successful checks retain the 24-hour cadence; attempts, outcomes, and failures are persisted separately; failed automatic checks run as unique network-constrained WorkManager work with exponential 15-minute backoff, including when connectivity returns after startup. Manual checks use the same markers, and failures never overwrite valid cached release data.+- **Verification:** `GitHubReleaseCheckerTest` covers HTTP 429/5xx and malformed successful responses; `SettingsAppUpdateActionsTest` proves failed refreshes preserve cached release data; `AppUpdateCheckPolicyTest` covers success cadence, failure backoff, and backward clock changes. The focused 8-test app matrix and `:app:compileDebugKotlin` passed on 2026-07-30.### MEMORY-001 — Process-lifetime maps grow with provider/category/host/media identities@@ -499,13 +542,15 @@ The urgent shared fixes are cancellation-safe HTTP, recording/timeshift lifecycl### PERSIST-001 — The central preferences DataStore has no explicit corruption recovery-- **Classification:** Suspected risk requiring runtime fixture+- **Classification:** Implemented; boundary verification pending (2026-07-30)- **Severity:** Medium- **Where:** `PreferencesRepository.kt:62-64` and its direct `.data.map/first` consumers; startup consumers in application/welcome/settings/player.-- **Current behavior:** `preferencesDataStore(name = "user_preferences")` has no `ReplaceFileCorruptionHandler`, and no central read-I/O fallback/diagnostic policy was found. This graph god node backs onboarding, provider/source choices, playback configuration, updates, plugin mappings, and feature flags.+- **Original behavior:** `preferencesDataStore(name = "user_preferences")` had no `ReplaceFileCorruptionHandler`, and no central read-I/O fallback/diagnostic policy was present. This graph god node backs onboarding, provider/source choices, playback configuration, updates, plugin mappings, and feature flags.- **Why this is wrong/fragile:** DataStore surfaces corruption/read failure unless recovery is configured. One damaged file can repeatedly fail unrelated startup flows. Blindly defaulting every error is also unsafe, so the policy must reconcile Room-backed state explicitly.- **Concrete failure scenario:** Storage/power damage corrupts preferences; eager collectors and `.first()` calls fail every process start even though the Room catalog remains usable.- **Recommended correction:** Add a documented corruption handler that preserves a diagnostic copy when possible and replaces known defaults; distinguish corruption from transient I/O; expose recoverable UI/telemetry; centralize policy.+- **Resolution:** `PreferencesRepository` now creates the preferences DataStore through a single `PreferenceDataStoreFactory` policy. `ReplaceFileCorruptionHandler` snapshots the damaged file when possible, writes a bounded recovery marker outside DataStore, logs the corruption for diagnostics, and returns `emptyPreferences()` so known repository defaults can restore service. Snapshots are capped at 4 MiB and three retained copies. Transient I/O exceptions and coroutine cancellation remain outside the corruption handler and are not converted into defaults.+- **Verification:** `PreferencesCorruptionRecoveryTest` proves corrupt input produces empty defaults, persists a recovery marker, and retains one diagnostic snapshot. `:data:testDebugUnitTest --tests com.streamvault.data.preferences.PreferencesCorruptionRecoveryTest` and `:data:compileDebugKotlin` passed on 2026-07-30. The broader runtime matrix below remains pending.- **Fix scope:** Shared persistence policy, possibly recovery UX.- **Required tests:** Corrupt checksum/file, transient unreadable file, one-time handler, Room/provider reconciliation, restart, backup/restore, and cancellation not treated as corruption.@@ -861,11 +906,11 @@ Phase 4 should trace feature flows end to end in this order:| ID | Finding | Classification | Severity ||---|---|---|---|-| SETUP-001 | Editing an active provider deactivates it before replacement sync succeeds | Confirmed defect | High |-| BACKUP-001 | Restore is non-atomic across Room, preferences, and recording alarms | Confirmed defect | High |-| BACKUP-002 | Provider-scoped restored preferences retain obsolete database IDs | Confirmed defect | High |-| DELETE-001 | Post-delete alarm/sync cleanup failures are never reconciled | Resolved (2026-07-26) | Medium |-| EPG-001 | Editing a reminder can persist a time whose alarm replacement failed | Confirmed defect | Medium |+| SETUP-001 | Editing an active provider deactivates it before replacement sync succeeds | Resolved (2026-07-29) | High |+| BACKUP-001 | Restore is non-atomic across Room, preferences, and recording alarms | Resolved (2026-07-29) | High |+| BACKUP-002 | Provider-scoped restored preferences retain obsolete database IDs | Resolved (2026-07-29) | High |+| DELETE-001 | Post-delete alarm/sync cleanup failures are never reconciled | Resolved (2026-07-29) | Medium |+| EPG-001 | Editing a reminder can persist a time whose alarm replacement failed | Resolved (2026-07-29) | Medium || PLAY-001 | Failed live-history persistence suppresses same-channel retry for the session | Confirmed defect | Medium || MIGRATION-001 | The current 61→62 migration and full supported chain are untested | Needs improvement (2026-07-26 audit) | Medium |@@ -873,8 +918,8 @@ The main feature risks are cross-store transitions: provider edits expose partia## Feature-flow observations-- **Setup/catalog/navigation:** Authentication/save converges in `ProviderRepositoryImpl`; activation follows initial sync. Xtream/Stalker require committed content while M3U/Jellyfin need not contain live channels. Catalog staging protects replacement rows, but provider state changes before commit (SETUP-001). Browsing, search, favorites, protection, and virtual groups are provider-scoped; backup breaks that identity model (BACKUP-002).-- **EPG/catch-up/zapping:** Source refresh/matching, cached lookup, catch-up construction, and launch have clear owners. Phase 3 covers source/parser faults. New-reminder alarm failure is compensated, but edit failure is not (EPG-001). Zap resolution uses request generations to reject stale work; live-history de-duplication is optimistic (PLAY-001).+- **Setup/catalog/navigation:** Authentication/save converges in `ProviderRepositoryImpl`; activation follows initial sync. Xtream/Stalker require committed content while M3U/Jellyfin need not contain live channels. Candidate revisions now retain the committed provider/catalog through replacement sync (SETUP-001). Browsing, search, favorites, protection, and virtual groups are provider-scoped; backup v9 now carries that identity model into portable preference restore (BACKUP-002).+- **EPG/catch-up/zapping:** Source refresh/matching, cached lookup, catch-up construction, and launch have clear owners. Phase 3 covers source/parser faults. Reminder creation, edit, cancellation, and startup repair now use compensating alarm/Room ordering (EPG-001). Zap resolution uses request generations to reject stale work; live-history de-duplication is optimistic (PLAY-001).- **Playback/download/cast/multiview:** Logical URLs become `StreamInfo`, followed by preparation, renewal, and recovery. Phase 2 lifecycle/timeshift/progress/cancellation findings remain controlling. Downloads correctly restart when a server ignores `Range` and returns `200`. Cast eligibility/media creation is centralized and tested for unsupported headers. Auxiliary multiview engines inherit LIFE-001/LIFE-002.- **Recording/backup/plugins/updates/migrations:** Scheduling validates storage, conflicts, connection limits, and exact alarms; alarm failure leaves an observable failed run. Capture inherits REC-001. Only provider/library/history restore is one Room transaction (BACKUP-001). Plugins retain PLUGIN-001–003 and updates UPDATE-001. Room 62 defines and production-registers every adjacent migration; the latest boundary lacks tests (MIGRATION-001).@@ -882,66 +927,72 @@ The main feature risks are cross-store transitions: provider edits expose partia### SETUP-001 — Editing an active provider deactivates it before replacement sync succeeds-- **Classification / severity:** Confirmed defect — High+- **Classification / severity:** Resolved (2026-07-29) — High- **Where:** `ProviderRepositoryImpl.kt:285-333` (Xtream), `381-420` (M3U), `467-485` (Jellyfin), `635-700` (Stalker), and `707-764` (shared completion).- **Current behavior:** Existing-provider paths write `isActive = false`, `status = PARTIAL`, and reset sync metadata before initial sync. Only success reactivates; error persists inactive state and schedules resume. The old committed catalog does not preserve selection.- **Why / scenario:** Replacement authentication and catalog promotion are separate commits. A transient failure after editing the active account's name or HTTP profile disables Home/Live TV despite a previously usable catalog.- **Recommended correction:** Keep the last active provider/catalog until a pending configuration revision and sync epoch commit atomically. At minimum restore prior active state on failure and delay timestamp reset.- **Fix scope:** Shared provider state-transition architecture.- **Required tests:** Active/inactive edit for every provider; sync failure, cancellation, process death, success, old-catalog availability, and stale-epoch isolation.+- **Resolution:** Provider edits now create a candidate configuration revision and keep the last committed provider/catalog active until the replacement sync epoch promotes successfully. Failed or cancelled replacements retain the prior configuration and active catalog; stale candidate epochs cannot promote. Focused repository and worker coverage exercises successful promotion, failure, cancellation, and retry isolation.### BACKUP-001 — Restore is non-atomic across Room, preferences, and recording alarms-- **Classification / severity:** Confirmed defect — High+- **Classification / severity:** Resolved (2026-07-29) — High- **Where:** `BackupManagerImpl.kt:344-434,693-778,995-1080`.- **Current behavior:** Provider/library/history commit in Room, followed by DataStore preferences, presets, and schedules/alarms. Later exceptions return generic failure without rollback. `REPLACE_EXISTING` cancels the old recording before the replacement is known to schedule.- **Why / scenario:** One result hides irreversible commits. Room and several preferences can change before a later write fails, yet UI reports total failure; failed schedule replacement can leave neither schedule.- **Recommended correction:** Use a durable sectioned restore with validated plan, checkpoints, and complete/partial/failed-before-commit outcomes. Snapshot/compensate preferences and restore the prior schedule if replacement promotion fails.- **Fix scope:** Cross-store restore protocol and result contract.- **Required tests:** Failure/cancellation/process death at every Room/DataStore/alarm boundary; idempotent retry; replacement compensation; exact section outcomes; no duplicates.+- **Resolution:** Backup restore now records durable section checkpoints and returns explicit `complete`, `partial`, or `failed-before-commit` outcomes. The Room checkpoint commits with the Room section; preference/preset changes use a pre-import snapshot for retry/compensation; failed recording replacement compensates the new alarm without removing the prior schedule. Replaying the same backup and plan is idempotent, and partial UI state retains the source/plan for retry. Focused manager and settings-action tests cover outcome reporting, cancellation, compensation, checkpoint replay, and retry state.### BACKUP-002 — Provider-scoped restored preferences retain obsolete database IDs-- **Classification / severity:** Confirmed defect — High+- **Classification / severity:** Resolved (2026-07-29) — High- **Where:** Export `BackupManagerImpl.kt:118-137`; restore `558-690`; Room mapping `714-810`.- **Current behavior:** `guideDefaultCategoryId`, `promotedLiveGroupIds`, `hiddenChannels_<providerId>`, and `hiddenCategories_<providerId>_<type>` contain source row IDs and are restored directly. Provider/group mappings never reach preferences; channel/category IDs can also change after resync.- **Why / scenario:** Auto-generated IDs are not portable. If source provider 2 maps to target 7, `hiddenChannels_2` affects no intended channel and can affect unrelated provider 2; group/category references similarly drift.- **Recommended correction:** Back up semantic provider/content/group identities, resolve them after Room import, then write target IDs; explicitly report unresolved references.- **Fix scope:** Backup schema/version and identity contract.- **Required tests:** Empty/populated targets with shifted IDs; keep/replace conflicts; changed catalog IDs; duplicate group names; unresolved references; semantic round trip.+- **Resolution:** Backup schema v9 exports semantic provider, active-provider, category, virtual-group, and channel references while retaining the legacy preference map for v8-and-older imports. Restore resolves providers and content only when the target match is unambiguous, supports changed category IDs through a unique semantic-name fallback, writes target provider/group/channel/category IDs, and reports both source-side stale references and target-side unresolved/duplicate matches as a truthful partial outcome without applying raw v9 IDs. Unresolved portable references remain retryable through the durable preference checkpoint. Focused coverage exercises semantic export/JSON round trip, shifted provider/Room/catalog IDs, empty and populated targets, keep/replace provider conflicts, duplicate group names, unresolved references, and explicit v8 compatibility.### DELETE-001 — Post-delete alarm and sync cleanup failures are never reconciled-- **Classification / severity:** Resolved (2026-07-26) — Medium+- **Classification / severity:** Resolved (2026-07-29) — Medium- **Where:** `ProviderRepositoryImpl.kt:131-213`; behavior is explicit in `ProviderRepositoryImplTest`.- **Current behavior:** Room deletion commits, then alarm cancellation and `syncManager.onProviderDeleted` use a catch-and-log helper. Success is returned without a retry marker.- **Why / scenario:** A transient external failure becomes permanent after its provider record is gone. Orphan alarms can fire against deleted rows and provider work/cache can survive.- **Recommended correction:** Persist a deletion tombstone, make cleanup idempotent, and enqueue unique reconciliation until all steps succeed; distinguish library-deleted from cleanup-pending diagnostics.- **Fix scope:** Deletion workflow and external cleanup hooks.- **Required tests:** Failure/process death after each step, reboot repair, repeated cleanup, concurrent alarm, and tombstone completion.-- **Resolution:** Provider deletion now inserts durable per-action cleanup records in the same Room transaction as the provider-row deletion. A unique WorkManager worker retries recording-alarm, reminder-alarm, and sync-runtime cleanup after process death or transient failure, deleting each record only on success; startup enqueues the same drain worker.+- **Resolution:** Provider deletion re-reads recording and reminder alarm identities inside the same Room transaction that inserts per-action tombstones and removes the provider, closing the concurrent-scheduling orphan-alarm window. The returned typed outcome truthfully reports that the library is deleted while cleanup remains pending, including the pending-action count and whether reconciliation was requested. Cleanup drains bounded batches until empty, retains tombstones on every external or database failure, propagates cancellation, and removes each tombstone only after its idempotent side effect succeeds. Unique work uses `APPEND_OR_REPLACE`, so a deletion committed while a drain is running cannot be lost; persisted work and the application-start enqueue repair pending tombstones after process restart or reboot.+- **Verification:** Focused repository and worker fixtures cover tombstone-write rollback, alarm identities committed immediately before the deletion transaction, enqueue failure, recording/reminder/sync failures, database read/diagnostic failures, process restart after each side effect but before tombstone deletion, tombstones added during a drain, repeated cleanup, cancellation, append-safe unique work, and final tombstone completion. Settings coverage verifies that cleanup-pending is surfaced distinctly from complete deletion. The focused tests and `:app:assembleDebug` passed on 2026-07-29.### EPG-001 — Editing a reminder can persist a time whose alarm replacement failed-- **Classification / severity:** Resolved (2026-07-26) — Medium+- **Classification / severity:** Resolved (2026-07-29) — Medium- **Where:** `ProgramReminderManagerImpl.kt:81-127`; tests omit existing-row scheduler failure.- **Current behavior:** Existing reminder rows update before alarm scheduling. Failure deletes only a new row, so an edit remains stored although the alarm was not replaced; cancellation also deletes first.- **Why / scenario:** Changing lead time from 10 to 30 minutes can show/store 30 while the old 10-minute alarm remains after scheduler failure.- **Recommended correction:** Keep the old entity, schedule replacement, then commit; compensate with the prior alarm when necessary and reconcile on startup.- **Fix scope:** Local reminder compensation protocol.- **Required tests:** Existing schedule/cancel/rollback failure, process death between boundaries, permission changes, startup repair.-- **Resolution:** Existing reminder rows now update only after their replacement alarm schedules successfully. A failed replacement restores the prior alarm and leaves the persisted reminder unchanged.+- **Resolution:** Reminder mutations are serialized. Existing rows remain the source of truth while a replacement alarm is scheduled, and Room commits the new time only after scheduling succeeds. A Room commit failure reschedules the prior alarm; failed compensation marks the persisted row unarmed so startup repair can retry truthfully. Cancellation now cancels AlarmManager before deleting Room, restores the prior alarm when deletion fails, and verifies ambiguous delete failures before deciding whether cancellation completed. New rows are persisted unarmed until scheduling succeeds. Every application process start now reconciles persisted reminders in addition to boot, package-replacement, and exact-alarm permission broadcasts.+- **Verification:** Focused fixtures cover existing replacement failure, Room failure after replacement scheduling, rollback success/failure, cancellation failure, Room failure after cancellation, ambiguous delete completion, permission loss between capability check and scheduling, unarmed new rows, process restart between replacement/cancel side effects and Room commit, startup repair, permission-unavailable repair, and continued reconciliation after one reminder fails. `ProgramReminderManagerImplTest` and `:app:assembleDebug` passed on 2026-07-29.### PLAY-001 — Failed live-history persistence suppresses same-channel retry for the session-- **Classification / severity:** Resolved (2026-07-26) — Medium+- **Classification / severity:** Resolved (2026-07-29) — Medium- **Where:** `PlayerZapActions.kt:298-321`; state `PlayerViewModel.kt:268`; candidate tests omit repository failure.- **Current behavior:** `lastRecordedLivePlaybackKey` is assigned before asynchronous `recordPlayback`. Failure is logged without clearing it; later same-channel events return early.- **Why / scenario:** A transient first insert failure prevents every later retry, so last-watched/recent state remains absent even after staying on or returning to the channel.- **Recommended correction:** Separate in-flight and last-successful keys; mark success only after `Result.Success`, clear on failure/cancellation, and serialize stale completions.- **Fix scope:** Local player/history coordination.- **Required tests:** Failure then success, A→B→A, cancellation, concurrent duplicates, stale completion.-- **Resolution:** Live-history de-duplication now distinguishes in-flight writes from the latest successful write. Failed or cancelled writes become retryable, concurrent duplicates remain suppressed, and stale completions cannot replace the active channel's successful key.+- **Resolution:** Live-history persistence now runs through a serialized coordinator with distinct latest-request, in-flight-attempt, and last-successful markers. Only `Result.Success` advances the successful marker; failure and cancellation clear the matching attempt in `finally`, including cancellation swallowed into a repository result. Uninterrupted same-channel duplicates are coalesced, while A→B→A creates a new A attempt so a failed first A cannot suppress the return. Obsolete queued writes are skipped before repository entry. If a stale write was already inside the repository when the channel changed, the latest-channel attempt runs after it, making the latest channel the final durable recent-history write rather than merely ignoring the stale marker completion.+- **Verification:** `PlayerZapActionsLivePlaybackTest` now drives the production coordinator across failure-then-success, successful de-duplication, A→B→A with the first A failing, concurrent duplicate events, cancellation followed by retry, a queued stale write, and a stale write already inside the repository followed by the latest-channel repair write. The focused test task and `:app:assembleDebug` passed on 2026-07-29.### MIGRATION-001 — The current 61→62 migration and full supported chain are untested@@ -994,12 +1045,12 @@ Phase 5 should stress these boundaries: process death/cancellation during commit|---|---|---|---|| PLATFORM-001 | Boot recovery starts a prohibited `dataSync` foreground service before enqueuing durable work | Needs improvement (2026-07-26 audit) | High || PLATFORM-002 | Recording and downloads share the six-hour `dataSync` quota without timeout handling | Needs improvement (2026-07-26 audit) | High |-| DOWNLOAD-001 | Process-killed downloads remain permanently `DOWNLOADING` | Resolved (2026-07-26) | High |+| DOWNLOAD-001 | Process-killed downloads remain permanently `DOWNLOADING` | Resolved (2026-07-29) | High || ALARM-001 | Exact-alarm permission revocation cancels schedules with no grant-time restoration | Needs improvement (2026-07-26 audit) | High |-| BACKUP-003 | Backup inspection/import has unbounded parsing and quadratic conflict scans | Confirmed defect | High |-| REMINDER-001 | Notification failure is swallowed and the reminder is marked delivered | Confirmed defect | Medium |-| CLOCK-001 | A future-dated `RUNNING` Xtream index job can suppress recovery indefinitely | Confirmed defect | Medium |-| TEST-002 | The download manager/service has no focused tests | Confirmed test gap | Medium |+| BACKUP-003 | Backup inspection/import has unbounded parsing and quadratic conflict scans | Resolved (2026-07-29) | High |+| REMINDER-001 | Notification failure is swallowed and the reminder is marked delivered | Resolved (2026-07-29) | Medium |+| CLOCK-001 | A future-dated `RUNNING` Xtream index job can suppress recovery indefinitely | Resolved (2026-07-29) | Medium |+| TEST-002 | The download manager/service lacks complete boundary coverage | Needs improvement (2026-07-29 audit) | Medium || COMPAT-001 | Legacy-route decoding calls an API-33 overload on API 25–32 | Needs improvement (2026-07-26 audit) | High |## Adversarial scenario matrix@@ -1009,13 +1060,13 @@ Phase 5 should stress these boundaries: process death/cancellation during commit| Process death during staged catalog import | Epoch/staging state is persisted and active catalog promotion is transactional | Good baseline; size/cancellation defects remain in Phase 2 || Rapid player prepare/zap | Request generations reject stale URL resolution/preload completion | Good baseline || Clock moves backward for cache TTL | `ContentCachePolicy` explicitly treats negative elapsed time as stale | Good baseline |-| Process death during download | Startup reclaims the ownerless row into the pending queue | Resolved (DOWNLOAD-001) |+| Process death during download | Startup reconciles the durable owner and validates the partial output before completion, resume, or safe restart | Resolved (DOWNLOAD-001) || Reboot with scheduled recording | Boot receiver starts a forbidden FGS before WorkManager enqueue | PLATFORM-001 || Exact-alarm permission revoked/re-granted | System cancels alarms; app has no grant receiver | ALARM-001 || Long/cumulative recording and download work | Both services consume one six-hour `dataSync` budget; neither handles timeout | PLATFORM-002 |-| Notification permission/channel changes after reminder creation | Notify error is discarded and delivery is still committed | REMINDER-001 |+| Notification permission/channel changes after reminder creation | Delivery is blocked truthfully, persisted with a reason, surfaced on resume, and retried without duplicate ownership | Resolved (REMINDER-001) || Huge/malformed backup | Full Gson object graph is allocated before validation; preview conflict checks are nested scans | BACKUP-003 |-| Wall clock is corrected behind a persisted running-job timestamp | Negative age is treated as “still running” in one Xtream gate | CLOCK-001 |+| Wall clock is corrected behind a persisted running-job timestamp | Future/invalid persisted event timestamps are stale; orphaned index/config work is recovered while a genuinely fresh owner is retained | Resolved (CLOCK-001) || Encoded legacy route on API 25–32 | Unconditionally calls an API-33 URL-decoder overload | COMPAT-001 || Recurring recording across DST | `ZonedDateTime.plusDays/plusWeeks` preserves local start time and fixed duration | Good baseline || Range server returns `200` to resume request | Partial output is discarded and restarted from zero | Good baseline |@@ -1046,14 +1097,15 @@ Phase 5 should stress these boundaries: process death/cancellation during commit### DOWNLOAD-001 — Process-killed downloads remain permanently DOWNLOADING-- **Classification / severity:** Resolved (2026-07-26) — High+- **Classification / severity:** Resolved (2026-07-29) — High- **Where:** `DownloadManagerImpl.kt:74-88,207-239,251-383`; `DownloadDao.kt:23-30`; `DownloadForegroundService.kt:50-100`.-- **Current behavior:** Capture persists `DOWNLOADING` before network/file work. Process death prevents catch/finally from changing it. Startup/connectivity scheduling selects only `PENDING`/`PAUSED`; `getActive()` observes but does not repair `DOWNLOADING`. Although a valid service start returns `START_STICKY`, a system restart supplies no download ID, causing the service to stop without reconciliation.+- **Original behavior:** Capture persisted `DOWNLOADING` before network/file work. Process death prevented catch/finally from changing it. Startup/connectivity scheduling selected only `PENDING`/`PAUSED`; `getActive()` observed but did not repair `DOWNLOADING`. Although a valid service start returned `START_STICKY`, a system restart supplied no download ID, causing the service to stop without reconciliation.- **Why / scenario:** Killing the process mid-download leaves a row and partial document that no queue path owns. Reopening Downloads or reconnecting does not resume/fail it; only manual resume restarts from zero.- **Recommended correction:** Persist an owner generation/heartbeat and reconcile orphan `DOWNLOADING` rows at application/service initialization. If the output grant and byte count remain valid, resume with `Range`; otherwise atomically mark paused/restartable. Use durable unique work or a service command journal rather than in-memory jobs as ownership proof.- **Fix scope:** Download state machine and durable execution ownership.- **Required tests:** Kill after row transition, target creation, progress checkpoint, final byte, and before completion update; sticky null intent; reboot; revoked SAF grant; server `206/200/416`; exactly one resumed owner.-- **Resolution:** A fresh `DownloadManagerImpl` now reclaims persisted `DOWNLOADING` rows before scheduling downloads, transitioning them to `PENDING` with an interruption reason so the existing queue/resume path owns them again.+- **Resolution:** Download rows now persist `owner_id`, monotonic `owner_epoch`, and `heartbeat_at` through migration 68-to-69. Every scheduling entry point serializes orphan reconciliation before queue admission, and a conditional DAO update grants exactly one process owner. Recovery validates the real target length: a fully written known-length target is completed, an exact resumable checkpoint is queued with `Range`, and missing, revoked, zero-length, or mismatched output is deleted and restarted safely. Resume handling validates `Content-Range`, appends only an aligned `206`, replaces output on `200`, recognizes an exact-length `416`, and rejects malformed fresh partial responses without a restart loop. A sticky service restart with no download ID now enters the same reconciliation path instead of stopping.+- **Verification:** `DownloadRecoveryStateMachineTest` covers interruption after row transition, target creation, an exact progress checkpoint, bytes beyond the checkpoint, final bytes before the completion commit, revoked SAF access, request headers, aligned/misaligned/malformed `206`, `200`, and exact/mismatched `416`. `DownloadDaoOwnershipTest` uses Room with concurrent schedulers to prove a single claim and verifies that a new process sees the prior owner as orphaned. `DownloadForegroundServicePolicyTest` covers null, blank, and explicit sticky commands. The focused data and app tests passed; the 68-to-69 Android migration test sources compiled; and `:app:assembleDebug` passed on 2026-07-29.### ALARM-001 — Exact-alarm permission revocation cancels schedules with no grant-time restoration@@ -1069,45 +1121,50 @@ Phase 5 should stress these boundaries: process death/cancellation during commit### BACKUP-003 — Backup inspection/import has unbounded parsing and quadratic conflict scans-- **Classification / severity:** Confirmed defect — High+- **Classification / severity:** Resolved (2026-07-29) — High- **Where:** `BackupManagerImpl.kt:232-340,344-359,513-518`; nested preview scans at `271-317`; no size/count/depth limits are defined.- **Current behavior:** Inspection and import deserialize the entire stream into `BackupData` with Gson before version, structure, or checksum validation. Preview then performs incoming-list `count` operations containing linear `any` scans over existing groups/favorites/history/recordings. `OutOfMemoryError` is not caught by the surrounding `catch (Exception)`.- **Why / scenario:** A mistakenly selected huge JSON file or an oversized legitimate backup can allocate an unbounded object graph, perform quadratic work, freeze/kill a TV process, and never return the intended corruption result. Checksum validation happens too late to protect admission.- **Recommended correction:** Enforce compressed/uncompressed byte, nesting, per-section count, and field-length limits while streaming. Validate header/version and compute checksum incrementally. Build hash-indexed conflict keys for O(n+m) preview and reject oversized sections with typed diagnostics.- **Fix scope:** Backup format reader/admission architecture.- **Required tests:** Oversized seekable/non-seekable URI, deep JSON, million-entry/duplicate-heavy sections, long strings, malformed/truncated input, cancellation, low-heap fixture, and linear-time conflict benchmark.+- **Resolution:** Inspection and import now share a bounded streaming reader that admits the version header first, limits the input to 16 MiB, rejects nesting beyond 64 levels, caps every materialized section, and rejects strings beyond 8,192 characters before Gson can allocate the corresponding object graph. Admission failures carry typed reasons, cancellation is propagated, trailing/duplicate/malformed input is rejected, and canonical SHA-256 verification is streamed through a digest output. Preview conflict detection uses hash-indexed keys, including recording channel/URL alternatives, for O(n+m) behavior.+- **Verification:** `BackupManagerImplTest` covers oversized seekable and non-seekable streams, early unsupported/missing headers, depth, million-entry section rejection, duplicate fields, long strings, malformed/truncated JSON, cancellation, and a 20,000-by-20,000 duplicate-heavy recording benchmark. `:data:lowHeapBackupAdmissionTest` runs the focused suite in a 128 MiB test JVM. Both focused tasks passed on 2026-07-29.### REMINDER-001 — Notification failure is swallowed and the reminder is marked delivered-- **Classification / severity:** Resolved (2026-07-26) — Medium+- **Classification / severity:** Resolved (2026-07-29) — Medium- **Where:** `ProgramReminderNotifier.kt:20-42`; `ProgramReminderManagerImpl.kt:153-163`; scheduling-time UI gate in `NotificationPermissionGate.kt:36-103`.-- **Current behavior:** `notify()` is wrapped in `runCatching` and returns no outcome. `deliverReminder()` unconditionally writes `notifiedAt` after the call. The UI checks permission when creating a reminder, but permission/channel state can change later.+- **Original behavior:** `notify()` was wrapped in `runCatching` and returned no outcome. `deliverReminder()` unconditionally wrote `notifiedAt` after the call. The UI checked permission when creating a reminder, but permission/channel state could change later.- **Why / scenario:** If notifications are revoked, the channel is disabled, or notify throws at delivery time, the user sees nothing while the row permanently records successful delivery and cannot be retried or diagnosed.- **Recommended correction:** Return a typed notification result, check runtime/channel state at delivery, and commit `notifiedAt` only after accepted delivery. Persist a blocked/failed reason and surface it when the app resumes; avoid blind repeated alerts.- **Fix scope:** Reminder delivery result/state model.- **Required tests:** Permission revoked after scheduling, channel disabled, notify exception, process death between notify and DB update, retry/deduplication, stale reminder, and reboot.-- **Resolution:** Notification delivery now returns a typed result and `notifiedAt` is written only after successful delivery. Disabled app notifications remain pending for a later retry.+- **Resolution:** Reminder delivery now uses typed `Accepted`, `Blocked`, and `Failed` outcomes and checks both app-level notification permission and the reminder channel's importance. Migration 69-to-70 persists delivery state, attempt token/time/count, and failure reason. A conditional DAO claim grants one delivery owner; terminal writes require the same attempt token, so concurrent or stale completions cannot overwrite a newer attempt. `notifiedAt` is committed only after `NotificationManager` accepts the stable-tag notification. If the process dies after posting but before that commit, startup checks the app's active notification and completes the interrupted attempt without reposting; if no notification exists, it retries safely with the same stable tag. Blocked/failed reminders are retried during startup, reboot, and guide foreground reconciliation, remain visible through the stale grace period, and surface their persisted reason in the guide. Stale reminders are dismissed without notifying.+- **Verification:** `ProgramReminderManagerImplTest` covers permission loss, channel blocking, notifier exceptions, cancellation, stale reminders, already-delivered deduplication, process death before and after posting, due-reminder retry, and reboot restoration. `ProgramReminderNotifierPolicyTest` verifies app and channel admission. `ProgramReminderDeliveryDaoTest` proves one concurrent attempt owner and rejects a stale completion token. `ProgramReminderIssueMessageTest` verifies persisted failures are surfaced, and the complete `EpgViewModelTest` suite remains green. Focused tests passed, migration 69-to-70 Android test sources compiled, and `:app:assembleDebug` passed on 2026-07-29.### CLOCK-001 — A future-dated running Xtream index job can suppress recovery indefinitely-- **Classification / severity:** Resolved (2026-07-26) — Medium-- **Where:** `ProviderSyncWorker.kt:307-316`; contrast `ContentCachePolicy.kt:8-13`, which correctly handles negative elapsed time.-- **Current behavior:** A `RUNNING` job is treated as fresh when `(now - updatedAt) < 15 minutes`. If `updatedAt` is in the future after manual/NTP clock correction, the negative age satisfies the condition until wall time catches up.+- **Classification / severity:** Resolved (2026-07-29) — Medium+- **Where:** `ProviderSyncWorker.kt`; `ContentCachePolicy.kt`; shared policy in `PersistedTimestampPolicy.kt`; related persisted-event gates in `ProviderConfigRevisionDao.kt`, `EpgSourceRepositoryImpl.kt`, `SettingsProviderActions.kt`, and `AppUpdateCheckPolicy.kt`.+- **Original behavior:** A `RUNNING` job was treated as fresh when `(now - updatedAt) < 15 minutes`. The earlier local correction rejected future timestamps, but then fell through to the previous successful-index TTL; an orphaned `RUNNING` job could therefore still be skipped when `lastSuccessAt` was recent. Durable `SYNCING` provider revisions and several persisted “last event” gates also used raw wall-clock comparisons that extended suppression after a rollback.- **Why / scenario:** A process dies with a running job, then the device clock moves backward by hours/days. Launch/periodic stale checks repeatedly skip the orphan job and its VOD/series index remains partial.- **Recommended correction:** Treat negative age as stale, matching `ContentCachePolicy`, or centralize persisted-age calculation with bounded clock-skew rules. Use monotonic time only for in-process durations and wall time plus explicit skew handling across restarts.- **Fix scope:** Local gate plus shared timestamp policy audit.- **Required tests:** Future timestamp, backward/forward jumps, process death, exact threshold, zero/invalid timestamps, and no duplicate live owner.-- **Resolution:** A running index job is fresh only when its timestamp is not in the future and is within the stale window. Future timestamps are now eligible for recovery.+- **Resolution:** `PersistedTimestampPolicy` now defines one wall-clock freshness rule: missing, non-positive, future, and threshold-expired timestamps are stale. `ContentCachePolicy` and the Xtream worker use it. A `RUNNING` index row now returns directly from the owner-freshness decision, so every stale/invalid orphan is recoverable regardless of an older `lastSuccessAt`; a genuinely fresh row remains the live owner and suppresses duplicate recovery. Provider-revision recovery admits future/invalid `SYNCING` rows after process death, while retaining a recent owner. The shared audit moved persisted EPG refresh, provider auto-sync, and app-update event backoff gates onto the same rule. Absolute schedule timestamps remain wall-clock semantics; in-process elapsed timing is not represented by this persisted policy.+- **Verification:** `PersistedTimestampPolicyTest`, `ProviderSyncWorkerTest`, `ContentCachePolicyTest`, `ProviderConfigRevisionClockRecoveryTest`, `EpgRefreshClockPolicyTest`, `SettingsProviderActionsTest`, and `AppUpdateCheckPolicyTest` cover future/backward and forward jumps, process-death rows with a recent prior success, exact threshold, zero/negative/missing values, Room recovery admission, and retention of a fresh owner. The focused 33-test matrix passed with zero failures, and `:app:assembleDebug` passed on 2026-07-29.-### TEST-002 — The download manager/service has no focused tests+### TEST-002 — The download manager/service lacks complete boundary coverage-- **Classification / severity:** Confirmed test gap — Medium-- **Where:** `DownloadManagerImpl.kt`, `DownloadForegroundService.kt`, `DownloadDao.kt`; no corresponding test class exists. Current download references in tests are UI mocks or update/speed-test code.-- **Current behavior:** The most failure-sensitive paths—process recovery, SAF output, range resume, cancellation, network retry, playback pause, service restart, and terminal finalization—have no executable regression coverage.+- **Classification / severity:** Needs improvement (2026-07-29 audit) — Medium+- **Where:** `DownloadManagerImpl.kt`, `DownloadForegroundService.kt`, `DownloadDao.kt`; focused recovery, ownership, and service-policy tests now exist, but the wider execution matrix remains incomplete.+- **Current behavior:** DOWNLOAD-001 now has executable state-machine, Room concurrency, and sticky-command regression coverage. Disk-full writes, cancellation at every I/O/commit boundary, retry/backoff ceilings, timeout execution, and concurrent enqueue/playback still lack end-to-end adapter or device coverage.- **Why / scenario:** DOWNLOAD-001 and platform timeout behavior can ship while broad builds and unrelated UI tests remain green.- **Recommended correction:** Extract a deterministic download state machine with injected clock/dispatcher/output/network adapters, add Room/MockWebServer unit tests, and add API 35/36 service/process-death instrumentation.- **Fix scope:** Testability refactor plus unit/instrumentation suite.- **Required tests:** All DOWNLOAD-001 cases, disk full, permission loss, 200/206/416, unknown length, cancellation at each boundary, retry ceiling/backoff, service null intent, timeout, and concurrent enqueue/playback.+- **2026-07-29 audit:** The DOWNLOAD-001 subset is covered and passing. The remaining failure and platform boundaries above are still required, so this broader finding is not resolved.### COMPAT-001 — Legacy-route decoding calls an API-33 overload on API 25–32diff --git a/domain/src/main/java/com/streamvault/domain/manager/BackupManager.kt b/domain/src/main/java/com/streamvault/domain/manager/BackupManager.ktindex bee3ddf4..d6aa0282 100644--- a/domain/src/main/java/com/streamvault/domain/manager/BackupManager.kt+++ b/domain/src/main/java/com/streamvault/domain/manager/BackupManager.kt@@ -8,7 +8,7 @@ import kotlinx.coroutines.flow.Flowimport com.streamvault.domain.model.Resultdata class BackupData(- val version: Int = 8,+ val version: Int = 9,val checksum: String? = null,val preferences: Map<String, String>? = null,val providers: List<Provider>? = null,@@ -17,7 +17,50 @@ data class BackupData(val playbackHistory: List<PlaybackHistory>? = null,val multiViewPresets: Map<String, List<Long>>? = null,val protectedCategories: List<ProtectedCategoryBackup>? = null,- val scheduledRecordings: List<ScheduledRecordingBackup>? = null+ val scheduledRecordings: List<ScheduledRecordingBackup>? = null,+ val portableProviderPreferences: PortableProviderPreferencesBackup? = null+)++/**+ * Provider-scoped preference values expressed without local Room/DataStore identifiers.+ * Older backups omit this field and retain the legacy preference map for compatibility.+ */+data class PortableProviderPreferencesBackup(+ val providers: List<BackupProviderReference> = emptyList(),+ val activeProvider: BackupProviderReference? = null,+ val guideDefaultCategory: PortableCategoryReference? = null,+ val guideDefaultVirtualCategoryId: Long? = null,+ val guideDefaultCategorySpecified: Boolean = false,+ val promotedLiveGroups: List<PortableVirtualGroupReference> = emptyList(),+ val hiddenChannels: List<PortableChannelReference> = emptyList(),+ val hiddenCategories: List<PortableCategoryReference> = emptyList(),+ val unresolvedReferences: List<String> = emptyList()+)++data class BackupProviderReference(+ val serverUrl: String,+ val username: String,+ val stalkerMacAddress: String? = null+)++data class PortableCategoryReference(+ val provider: BackupProviderReference,+ val name: String,+ val type: ContentType,+ val remoteCategoryId: Long? = null+)++data class PortableVirtualGroupReference(+ val provider: BackupProviderReference,+ val name: String,+ val contentType: ContentType+)++data class PortableChannelReference(+ val provider: BackupProviderReference,+ val streamId: Long,+ val name: String,+ val streamUrl: String)data class ProtectedCategoryBackup(@@ -119,9 +162,22 @@ data class RecordingScheduleImportSummary(get() = outcomes.count { it.disposition == RecordingScheduleImportDisposition.FAILED }}+/**+ * The durable outcome of a restore operation. A successful [Result] means the outcome below is+ * authoritative; callers must not present a partial restore as a total failure.+ */+enum class BackupRestoreOutcome {+ COMPLETE,+ PARTIAL,+ FAILED_BEFORE_COMMIT+}+data class BackupImportResult(+ val outcome: BackupRestoreOutcome = BackupRestoreOutcome.COMPLETE,val importedSections: List<String> = emptyList(),val skippedSections: List<String> = emptyList(),+ val failedSections: List<String> = emptyList(),+ val unresolvedReferences: List<String> = emptyList(),val recordingScheduleImport: RecordingScheduleImportSummary? = null)diff --git a/domain/src/main/java/com/streamvault/domain/manager/RecordingManager.kt b/domain/src/main/java/com/streamvault/domain/manager/RecordingManager.ktindex ce62820d..a49ab9ed 100644--- a/domain/src/main/java/com/streamvault/domain/manager/RecordingManager.kt+++ b/domain/src/main/java/com/streamvault/domain/manager/RecordingManager.kt@@ -2,6 +2,8 @@ package com.streamvault.domain.managerimport com.streamvault.domain.model.RecordingItemimport com.streamvault.domain.model.RecordingRequest+import com.streamvault.domain.model.RecordingReconciliationResult+import com.streamvault.domain.model.RecordingReconciliationSummaryimport com.streamvault.domain.model.RecordingStorageConfigimport com.streamvault.domain.model.RecordingStorageStateimport com.streamvault.domain.model.Result@@ -28,7 +30,8 @@ interface RecordingManager {Result.error("Schedule enablement is not supported by this recording manager.")suspend fun updateStorageConfig(config: RecordingStorageConfig): Result<RecordingStorageState> =Result.error("Storage configuration is not supported by this recording manager.")- suspend fun reconcileRecordingState(): Result<Unit> = Result.success(Unit)+ suspend fun reconcileRecordingState(): RecordingReconciliationResult =+ RecordingReconciliationResult.Complete(RecordingReconciliationSummary())suspend fun promoteScheduledRecording(recordingId: String): Result<Unit> =Result.error("Scheduled promotion is not supported by this recording manager.")suspend fun skipOccurrence(recordingId: String): Result<Unit> =diff --git a/domain/src/main/java/com/streamvault/domain/model/ProgramReminder.kt b/domain/src/main/java/com/streamvault/domain/model/ProgramReminder.ktindex c6843663..b439e4a3 100644--- a/domain/src/main/java/com/streamvault/domain/model/ProgramReminder.kt+++ b/domain/src/main/java/com/streamvault/domain/model/ProgramReminder.kt@@ -1,5 +1,14 @@package com.streamvault.domain.model+enum class ProgramReminderDeliveryState {+ PENDING,+ DELIVERING,+ DELIVERED,+ BLOCKED,+ FAILED,+ DISMISSED+}+data class ProgramReminder(val id: Long = 0,val providerId: Long,@@ -12,5 +21,9 @@ data class ProgramReminder(val isDismissed: Boolean = false,val notifiedAt: Long? = null,val exactAlarmArmed: Boolean = true,+ val deliveryState: ProgramReminderDeliveryState = ProgramReminderDeliveryState.PENDING,+ val deliveryAttemptedAt: Long? = null,+ val deliveryAttemptCount: Int = 0,+ val deliveryFailureReason: String? = null,val createdAt: Long = System.currentTimeMillis())diff --git a/domain/src/main/java/com/streamvault/domain/model/RecordingModels.kt b/domain/src/main/java/com/streamvault/domain/model/RecordingModels.ktindex 6dd924af..3786cc90 100644--- a/domain/src/main/java/com/streamvault/domain/model/RecordingModels.kt+++ b/domain/src/main/java/com/streamvault/domain/model/RecordingModels.kt@@ -34,6 +34,36 @@ enum class RecordingRecurrence {WEEKLY}+data class RecordingReconciliationSummary(+ val rowsInspected: Int = 0,+ val rowsRepaired: Int = 0,+ val rowsQuarantined: Int = 0+)++data class RecordingReconciliationRowFailure(+ val recordingId: String,+ val reason: String+)++sealed interface RecordingReconciliationResult {+ data class Complete(+ val summary: RecordingReconciliationSummary+ ) : RecordingReconciliationResult++ data class Partial(+ val summary: RecordingReconciliationSummary,+ val rowFailures: List<RecordingReconciliationRowFailure>+ ) : RecordingReconciliationResult++ data class TransientFailure(+ val message: String+ ) : RecordingReconciliationResult++ data class PermanentFailure(+ val message: String+ ) : RecordingReconciliationResult+}+data class RecordingRequest(val providerId: Long,val channelId: Long,diff --git a/domain/src/main/java/com/streamvault/domain/repository/ProviderRepository.kt b/domain/src/main/java/com/streamvault/domain/repository/ProviderRepository.ktindex 546b0967..d63417f6 100644--- a/domain/src/main/java/com/streamvault/domain/repository/ProviderRepository.kt+++ b/domain/src/main/java/com/streamvault/domain/repository/ProviderRepository.kt@@ -21,13 +21,24 @@ data class ProviderDeleteProgress(val fraction: Float? = null)+data class ProviderDeleteOutcome(+ val providerId: Long,+ val pendingCleanupActions: Int,+ val reconciliationRequested: Boolean+) {+ val cleanupPending: Boolean get() = pendingCleanupActions > 0+}+interface ProviderRepository {fun getProviders(): Flow<List<Provider>>fun getActiveProvider(): Flow<Provider?>suspend fun getProvider(id: Long): Provider?suspend fun addProvider(provider: Provider): Result<Long>suspend fun updateProvider(provider: Provider): Result<Unit>- suspend fun deleteProvider(id: Long, onProgress: ((ProviderDeleteProgress) -> Unit)? = null): Result<Unit>+ suspend fun deleteProvider(+ id: Long,+ onProgress: ((ProviderDeleteProgress) -> Unit)? = null+ ): Result<ProviderDeleteOutcome>/*** Returns cleartext credentials for all providers that have both adiff --git a/domain/src/main/java/com/streamvault/domain/usecase/ImportBackup.kt b/domain/src/main/java/com/streamvault/domain/usecase/ImportBackup.ktindex e460b93e..d63047cd 100644--- a/domain/src/main/java/com/streamvault/domain/usecase/ImportBackup.kt+++ b/domain/src/main/java/com/streamvault/domain/usecase/ImportBackup.kt@@ -4,6 +4,7 @@ import com.streamvault.domain.manager.BackupImportPlanimport com.streamvault.domain.manager.BackupImportResultimport com.streamvault.domain.manager.BackupManagerimport com.streamvault.domain.manager.BackupPreview+import com.streamvault.domain.manager.BackupRestoreOutcomeimport com.streamvault.domain.model.Resultimport javax.inject.Inject@@ -30,13 +31,25 @@ sealed class ImportBackupResult {data class Success(val result: BackupImportResult) : ImportBackupResult() {val importedSummary: Stringget() {- val baseSummary = result.importedSections.joinToString().ifBlank { "Nothing imported" }+ val baseSummary = when (result.outcome) {+ BackupRestoreOutcome.COMPLETE ->+ result.importedSections.joinToString().ifBlank { "Nothing imported" }+ BackupRestoreOutcome.PARTIAL ->+ "Partially imported: ${result.importedSections.joinToString().ifBlank { "nothing" }}"+ BackupRestoreOutcome.FAILED_BEFORE_COMMIT -> "Nothing was committed"+ }+ val failureSummary = result.failedSections+ .takeIf { it.isNotEmpty() }+ ?.joinToString(prefix = "Failed: ")+ val unresolvedSummary = result.unresolvedReferences+ .takeIf { it.isNotEmpty() }+ ?.joinToString(prefix = "Unresolved: ")val recordingSummary = result.recordingScheduleImport?.takeIf { it.failedCount > 0 || it.skippedCount > 0 }?.let { summary ->"Recording schedules: ${summary.importedCount} imported, ${summary.skippedCount} skipped, ${summary.failedCount} failed"}- return listOf(baseSummary, recordingSummary)+ return listOf(baseSummary, failureSummary, unresolvedSummary, recordingSummary).filterNotNull().joinToString(separator = ". ")}@@ -75,4 +88,4 @@ class ImportBackup @Inject constructor(is Result.Loading -> ImportBackupResult.Error("Unexpected loading state")}}-}\ No newline at end of file+}diff --git a/domain/src/main/java/com/streamvault/domain/util/PersistedTimestampPolicy.kt b/domain/src/main/java/com/streamvault/domain/util/PersistedTimestampPolicy.ktnew file mode 100644index 00000000..85edd323--- /dev/null+++ b/domain/src/main/java/com/streamvault/domain/util/PersistedTimestampPolicy.kt@@ -0,0 +1,22 @@+package com.streamvault.domain.util++/**+ * Freshness policy for wall-clock timestamps that survive process death.+ *+ * A missing, non-positive, or future timestamp cannot prove that work is still live. Treating+ * those values as stale prevents a manual or NTP clock correction from suppressing recovery+ * until wall time catches up. In-process elapsed durations should use a monotonic clock instead.+ */+object PersistedTimestampPolicy {+ fun isFresh(+ timestampMillis: Long?,+ nowMillis: Long,+ freshForMillis: Long+ ): Boolean {+ if (timestampMillis == null || timestampMillis <= 0L || freshForMillis <= 0L) {+ return false+ }+ if (timestampMillis > nowMillis) return false+ return nowMillis - timestampMillis < freshForMillis+ }+}diff --git a/domain/src/test/java/com/streamvault/domain/usecase/SyncProviderTest.kt b/domain/src/test/java/com/streamvault/domain/usecase/SyncProviderTest.ktindex 70a06220..8032024b 100644--- a/domain/src/test/java/com/streamvault/domain/usecase/SyncProviderTest.kt+++ b/domain/src/test/java/com/streamvault/domain/usecase/SyncProviderTest.kt@@ -105,7 +105,10 @@ private class FakeSyncProviderRepository(override suspend fun updateProvider(provider: Provider): Result<Unit> = error("Not used in test")- override suspend fun deleteProvider(id: Long, onProgress: ((ProviderDeleteProgress) -> Unit)?): Result<Unit> = error("Not used in test")+ override suspend fun deleteProvider(+ id: Long,+ onProgress: ((ProviderDeleteProgress) -> Unit)?+ ): Result<com.streamvault.domain.repository.ProviderDeleteOutcome> = error("Not used in test")override suspend fun getAllProviderCredentials(): List<ProviderCredentials> = emptyList()diff --git a/domain/src/test/java/com/streamvault/domain/usecase/ValidateAndAddProviderTest.kt b/domain/src/test/java/com/streamvault/domain/usecase/ValidateAndAddProviderTest.ktindex 62ffe179..b3bcc43e 100644--- a/domain/src/test/java/com/streamvault/domain/usecase/ValidateAndAddProviderTest.kt+++ b/domain/src/test/java/com/streamvault/domain/usecase/ValidateAndAddProviderTest.kt@@ -648,7 +648,10 @@ private class FakeProviderRepository : ProviderRepository {override suspend fun updateProvider(provider: Provider): Result<Unit> = error("Not used in test")- override suspend fun deleteProvider(id: Long, onProgress: ((ProviderDeleteProgress) -> Unit)?): Result<Unit> = error("Not used in test")+ override suspend fun deleteProvider(+ id: Long,+ onProgress: ((ProviderDeleteProgress) -> Unit)?+ ): Result<com.streamvault.domain.repository.ProviderDeleteOutcome> = error("Not used in test")override suspend fun getAllProviderCredentials(): List<ProviderCredentials> = emptyList()diff --git a/domain/src/test/java/com/streamvault/domain/util/PersistedTimestampPolicyTest.kt b/domain/src/test/java/com/streamvault/domain/util/PersistedTimestampPolicyTest.ktnew file mode 100644index 00000000..c6a4089e--- /dev/null+++ b/domain/src/test/java/com/streamvault/domain/util/PersistedTimestampPolicyTest.kt@@ -0,0 +1,64 @@+package com.streamvault.domain.util++import com.google.common.truth.Truth.assertThat+import org.junit.Test++class PersistedTimestampPolicyTest {++ @Test+ fun `future timestamp after backward clock jump is stale`() {+ assertThat(+ PersistedTimestampPolicy.isFresh(+ timestampMillis = 10_001L,+ nowMillis = 10_000L,+ freshForMillis = 1_000L+ )+ ).isFalse()+ }++ @Test+ fun `forward clock jump beyond window is stale`() {+ assertThat(+ PersistedTimestampPolicy.isFresh(+ timestampMillis = 10_000L,+ nowMillis = 20_000L,+ freshForMillis = 1_000L+ )+ ).isFalse()+ }++ @Test+ fun `exact freshness threshold is stale`() {+ assertThat(+ PersistedTimestampPolicy.isFresh(+ timestampMillis = 10_000L,+ nowMillis = 11_000L,+ freshForMillis = 1_000L+ )+ ).isFalse()+ }++ @Test+ fun `zero negative and missing timestamps are stale`() {+ listOf<Long?>(null, 0L, -1L).forEach { timestamp ->+ assertThat(+ PersistedTimestampPolicy.isFresh(+ timestampMillis = timestamp,+ nowMillis = 10_000L,+ freshForMillis = 1_000L+ )+ ).isFalse()+ }+ }++ @Test+ fun `positive timestamp inside window is fresh`() {+ assertThat(+ PersistedTimestampPolicy.isFresh(+ timestampMillis = 10_000L,+ nowMillis = 10_999L,+ freshForMillis = 1_000L+ )+ ).isTrue()+ }+}