StreamVault is a TV-first free IPTV player for Android TV built with Kotlin, Jetpack Compose, Room, Hilt, and Media3.
Kotlin iptv-player
1.0.5: data layer hardening, performance, and new features
David Nashashe9d2e55ad132
diff --git a/app/src/main/java/com/streamvault/app/MainActivity.kt b/app/src/main/java/com/streamvault/app/MainActivity.ktindex 801e539d..22a975f6 100644--- a/app/src/main/java/com/streamvault/app/MainActivity.kt+++ b/app/src/main/java/com/streamvault/app/MainActivity.kt@@ -181,12 +181,13 @@ class MainActivity : ComponentActivity() {enabled: Boolean,isPlaying: Boolean,videoWidth: Int,- videoHeight: Int+ videoHeight: Int,+ pixelWidthHeightRatio: Float = 1f) {playerPictureInPictureState = PlayerPictureInPictureState(enabled = enabled,isPlaying = isPlaying,- aspectRatio = videoAspectRatioOrNull(videoWidth, videoHeight)+ aspectRatio = videoAspectRatioOrNull(videoWidth, videoHeight, pixelWidthHeightRatio))applyPlayerPictureInPictureParams()}@@ -241,9 +242,10 @@ class MainActivity : ComponentActivity() {return builder.build()}- private fun videoAspectRatioOrNull(videoWidth: Int, videoHeight: Int): Rational? {+ private fun videoAspectRatioOrNull(videoWidth: Int, videoHeight: Int, pixelWidthHeightRatio: Float = 1f): Rational? {if (videoWidth <= 0 || videoHeight <= 0) return null- return Rational(videoWidth, videoHeight)+ val displayWidth = (videoWidth * pixelWidthHeightRatio).toInt().coerceAtLeast(1)+ return Rational(displayWidth, videoHeight)}private fun handleExternalIntent(intent: Intent?) {diff --git a/app/src/main/java/com/streamvault/app/StreamVaultApp.kt b/app/src/main/java/com/streamvault/app/StreamVaultApp.ktindex 98017ac5..af93e88b 100644--- a/app/src/main/java/com/streamvault/app/StreamVaultApp.kt+++ b/app/src/main/java/com/streamvault/app/StreamVaultApp.kt@@ -26,6 +26,8 @@ import androidx.work.NetworkTypeimport androidx.work.PeriodicWorkRequestBuilderimport androidx.work.WorkManagerimport com.streamvault.data.manager.recording.RecordingReconcileWorker+import com.streamvault.data.sync.ProviderSyncWorker+import com.streamvault.player.timeshift.TimeshiftDiskManagerimport javax.inject.Inject@HiltAndroidApp@@ -42,6 +44,11 @@ class StreamVaultApp : Application(), SingletonImageLoader.Factory {override fun onCreate() {super.onCreate()runtimeDiagnosticsManager.start()+ applicationScope.launch {+ // Clean up any timeshift temp directories left behind by crashes, OOM kills, or+ // force-stops from the previous run. activeSessionDir = null means wipe everything.+ TimeshiftDiskManager(applicationContext).cleanupStaleDirectories(activeSessionDir = null)+ }applicationScope.launch {refreshCachedAppUpdateIfNeeded()}@@ -64,6 +71,7 @@ class StreamVaultApp : Application(), SingletonImageLoader.Factory {gcWorkRequest)+ ProviderSyncWorker.enqueuePeriodic(this)RecordingReconcileWorker.enqueuePeriodic(this)RecordingReconcileWorker.enqueueOneShot(this)}diff --git a/app/src/main/java/com/streamvault/app/cast/CastModels.kt b/app/src/main/java/com/streamvault/app/cast/CastModels.ktindex 1fde2de6..0a76f668 100644--- a/app/src/main/java/com/streamvault/app/cast/CastModels.kt+++ b/app/src/main/java/com/streamvault/app/cast/CastModels.kt@@ -1,5 +1,14 @@package com.streamvault.app.cast+/**+ * Media payload sent to a Chromecast receiver.+ *+ * **Live channel URL strategy:** For Xtream live channels the [url] must be+ * the credential-based portal URL (no expiry tokens) so that long-running Cast+ * sessions are not interrupted when a tokenized CDN URL expires.+ * [PlayerViewModelActions.buildCastRequest] passes `preferStableUrl = true`+ * when resolving the live stream URL.+ */data class CastMediaRequest(val url: String,val title: String,diff --git a/app/src/main/java/com/streamvault/app/di/DatabaseModule.kt b/app/src/main/java/com/streamvault/app/di/DatabaseModule.ktindex cc7201cc..4477eed2 100644--- a/app/src/main/java/com/streamvault/app/di/DatabaseModule.kt+++ b/app/src/main/java/com/streamvault/app/di/DatabaseModule.kt@@ -3,8 +3,11 @@ package com.streamvault.app.diimport android.content.Contextimport androidx.room.Roomimport androidx.room.RoomDatabase+import androidx.sqlite.db.framework.FrameworkSQLiteOpenHelperFactory+import com.streamvault.app.BuildConfigimport com.streamvault.data.local.StreamVaultDatabaseimport com.streamvault.data.local.dao.*+import com.streamvault.data.local.dao.ChannelPreferenceDaoimport dagger.Moduleimport dagger.Providesimport dagger.hilt.InstallIn@@ -15,6 +18,7 @@ import javax.inject.Singleton@Module@InstallIn(SingletonComponent::class)object DatabaseModule {+ private const val DEBUG_SLOW_QUERY_THRESHOLD_MS = 100L@Provides@Singleton@@ -25,6 +29,16 @@ object DatabaseModule {"streamvault.db").setJournalMode(RoomDatabase.JournalMode.WRITE_AHEAD_LOGGING)+ .openHelperFactory(+ if (BuildConfig.DEBUG) {+ SlowQueryLoggingOpenHelperFactory(+ delegate = FrameworkSQLiteOpenHelperFactory(),+ slowQueryThresholdMs = DEBUG_SLOW_QUERY_THRESHOLD_MS+ )+ } else {+ FrameworkSQLiteOpenHelperFactory()+ }+ ).addMigrations(StreamVaultDatabase.MIGRATION_1_2,StreamVaultDatabase.MIGRATION_2_3,@@ -54,7 +68,14 @@ object DatabaseModule {StreamVaultDatabase.MIGRATION_26_27,StreamVaultDatabase.MIGRATION_27_28,StreamVaultDatabase.MIGRATION_28_29,- StreamVaultDatabase.MIGRATION_29_30+ StreamVaultDatabase.MIGRATION_29_30,+ StreamVaultDatabase.MIGRATION_30_31,+ StreamVaultDatabase.MIGRATION_31_32,+ StreamVaultDatabase.MIGRATION_32_33,+ StreamVaultDatabase.MIGRATION_33_34,+ StreamVaultDatabase.MIGRATION_34_35,+ StreamVaultDatabase.MIGRATION_35_36,+ StreamVaultDatabase.MIGRATION_36_37)// NOTE: fallbackToDestructiveMigration() intentionally removed.// All future schema changes MUST add a corresponding Migration in StreamVaultDatabase.@@ -72,6 +93,8 @@ object DatabaseModule {@Provides fun provideFavoriteDao(db: StreamVaultDatabase): FavoriteDao = db.favoriteDao()@Provides fun provideVirtualGroupDao(db: StreamVaultDatabase): VirtualGroupDao = db.virtualGroupDao()@Provides fun providePlaybackHistoryDao(db: StreamVaultDatabase): PlaybackHistoryDao = db.playbackHistoryDao()+ @Provides fun provideTmdbIdentityDao(db: StreamVaultDatabase): TmdbIdentityDao = db.tmdbIdentityDao()+ @Provides fun provideSearchHistoryDao(db: StreamVaultDatabase): SearchHistoryDao = db.searchHistoryDao()@Provides fun provideSyncMetadataDao(db: StreamVaultDatabase): SyncMetadataDao = db.syncMetadataDao()@Provides fun provideMovieCategoryHydrationDao(db: StreamVaultDatabase): MovieCategoryHydrationDao = db.movieCategoryHydrationDao()@Provides fun provideSeriesCategoryHydrationDao(db: StreamVaultDatabase): SeriesCategoryHydrationDao = db.seriesCategoryHydrationDao()@@ -84,5 +107,6 @@ object DatabaseModule {@Provides fun provideCombinedM3uProfileMemberDao(db: StreamVaultDatabase): CombinedM3uProfileMemberDao = db.combinedM3uProfileMemberDao()@Provides fun provideRecordingScheduleDao(db: StreamVaultDatabase): RecordingScheduleDao = db.recordingScheduleDao()@Provides fun provideRecordingRunDao(db: StreamVaultDatabase): RecordingRunDao = db.recordingRunDao()+ @Provides fun provideProgramReminderDao(db: StreamVaultDatabase): ProgramReminderDao = db.programReminderDao()@Provides fun provideRecordingStorageDao(db: StreamVaultDatabase): RecordingStorageDao = db.recordingStorageDao()}diff --git a/app/src/main/java/com/streamvault/app/di/NetworkModule.kt b/app/src/main/java/com/streamvault/app/di/NetworkModule.ktindex 270bf225..de84a6b2 100644--- a/app/src/main/java/com/streamvault/app/di/NetworkModule.kt+++ b/app/src/main/java/com/streamvault/app/di/NetworkModule.kt@@ -18,8 +18,10 @@ import dagger.hilt.InstallInimport dagger.hilt.android.qualifiers.ApplicationContextimport dagger.hilt.components.SingletonComponentimport kotlinx.serialization.json.Json+import okhttp3.Cacheimport okhttp3.OkHttpClientimport okhttp3.logging.HttpLoggingInterceptor+import java.io.Fileimport java.util.concurrent.TimeUnit.SECONDSimport javax.inject.Singleton@@ -46,6 +48,12 @@ object NetworkModule {}return OkHttpClient.Builder()+ .cache(+ Cache(+ directory = File(context.cacheDir, "streamvault_http_cache"),+ maxSize = 256L * 1024 * 1024+ )+ ).connectTimeout(NetworkTimeoutConfig.CONNECT_TIMEOUT_SECONDS, SECONDS).readTimeout(NetworkTimeoutConfig.READ_TIMEOUT_SECONDS, SECONDS).writeTimeout(NetworkTimeoutConfig.WRITE_TIMEOUT_SECONDS, SECONDS)diff --git a/app/src/main/java/com/streamvault/app/di/RepositoryModule.kt b/app/src/main/java/com/streamvault/app/di/RepositoryModule.ktindex bb0416bb..8434a8d3 100644--- a/app/src/main/java/com/streamvault/app/di/RepositoryModule.kt+++ b/app/src/main/java/com/streamvault/app/di/RepositoryModule.kt@@ -69,6 +69,9 @@ abstract class RepositoryModule {@Binds @Singletonabstract fun bindRecordingManager(impl: com.streamvault.data.manager.RecordingManagerImpl): com.streamvault.domain.manager.RecordingManager+ @Binds @Singleton+ abstract fun bindProgramReminderManager(impl: com.streamvault.data.manager.ProgramReminderManagerImpl): com.streamvault.domain.manager.ProgramReminderManager+@Binds @Singletonabstract fun bindParentalControlSessionStore(impl: PreferencesRepository): ParentalControlSessionStorediff --git a/app/src/main/java/com/streamvault/app/di/SlowQueryLoggingOpenHelperFactory.kt b/app/src/main/java/com/streamvault/app/di/SlowQueryLoggingOpenHelperFactory.ktnew file mode 100644index 00000000..a4df6b87--- /dev/null+++ b/app/src/main/java/com/streamvault/app/di/SlowQueryLoggingOpenHelperFactory.kt@@ -0,0 +1,129 @@+package com.streamvault.app.di++import android.database.Cursor+import android.os.SystemClock+import android.util.Log+import androidx.sqlite.db.SupportSQLiteDatabase+import androidx.sqlite.db.SupportSQLiteOpenHelper+import androidx.sqlite.db.SupportSQLiteQuery+import androidx.sqlite.db.SupportSQLiteStatement++internal class SlowQueryLoggingOpenHelperFactory(+ private val delegate: SupportSQLiteOpenHelper.Factory,+ private val slowQueryThresholdMs: Long,+ private val tag: String = "RoomSlowQuery"+) : SupportSQLiteOpenHelper.Factory {++ override fun create(configuration: SupportSQLiteOpenHelper.Configuration): SupportSQLiteOpenHelper {+ return SlowQueryLoggingOpenHelper(+ delegate = delegate.create(configuration),+ slowQueryThresholdMs = slowQueryThresholdMs,+ tag = tag+ )+ }+}++private class SlowQueryLoggingOpenHelper(+ private val delegate: SupportSQLiteOpenHelper,+ private val slowQueryThresholdMs: Long,+ private val tag: String+) : SupportSQLiteOpenHelper by delegate {++ override val writableDatabase: SupportSQLiteDatabase+ get() = SlowQueryLoggingDatabase(delegate.writableDatabase, slowQueryThresholdMs, tag)++ override val readableDatabase: SupportSQLiteDatabase+ get() = SlowQueryLoggingDatabase(delegate.readableDatabase, slowQueryThresholdMs, tag)+}++private class SlowQueryLoggingDatabase(+ private val delegate: SupportSQLiteDatabase,+ private val slowQueryThresholdMs: Long,+ private val tag: String+) : SupportSQLiteDatabase by delegate {++ override fun compileStatement(sql: String): SupportSQLiteStatement {+ return SlowQueryLoggingStatement(+ delegate = delegate.compileStatement(sql),+ sql = sql,+ slowQueryThresholdMs = slowQueryThresholdMs,+ tag = tag+ )+ }++ override fun query(query: String): Cursor =+ logSlowSql(query) { delegate.query(query) }++ override fun query(query: String, bindArgs: Array<out Any?>): Cursor =+ logSlowSql(query) { delegate.query(query, bindArgs) }++ override fun query(query: SupportSQLiteQuery): Cursor =+ logSlowSql(query.sql) { delegate.query(query) }++ override fun query(query: SupportSQLiteQuery, cancellationSignal: android.os.CancellationSignal?): Cursor =+ logSlowSql(query.sql) { delegate.query(query, cancellationSignal) }++ override fun execSQL(sql: String) {+ logSlowSql(sql) { delegate.execSQL(sql) }+ }++ override fun execSQL(sql: String, bindArgs: Array<out Any?>) {+ logSlowSql(sql) { delegate.execSQL(sql, bindArgs) }+ }++ private inline fun <T> logSlowSql(sql: String, block: () -> T): T {+ val startedAt = SystemClock.elapsedRealtimeNanos()+ try {+ return block()+ } finally {+ val elapsedMs = (SystemClock.elapsedRealtimeNanos() - startedAt) / 1_000_000+ if (elapsedMs >= slowQueryThresholdMs) {+ Log.w(tag, "Slow SQL (${elapsedMs}ms): ${sql.normalizeForLog()}")+ }+ }+ }+}++private class SlowQueryLoggingStatement(+ private val delegate: SupportSQLiteStatement,+ private val sql: String,+ private val slowQueryThresholdMs: Long,+ private val tag: String+) : SupportSQLiteStatement by delegate {++ override fun execute() {+ logSlowStatement { delegate.execute() }+ }++ override fun executeUpdateDelete(): Int =+ logSlowStatement { delegate.executeUpdateDelete() }++ override fun executeInsert(): Long =+ logSlowStatement { delegate.executeInsert() }++ override fun simpleQueryForLong(): Long =+ logSlowStatement { delegate.simpleQueryForLong() }++ override fun simpleQueryForString(): String? =+ logSlowStatement { delegate.simpleQueryForString() }++ private inline fun <T> logSlowStatement(block: () -> T): T {+ val startedAt = SystemClock.elapsedRealtimeNanos()+ try {+ return block()+ } finally {+ val elapsedMs = (SystemClock.elapsedRealtimeNanos() - startedAt) / 1_000_000+ if (elapsedMs >= slowQueryThresholdMs) {+ Log.w(tag, "Slow SQL (${elapsedMs}ms): ${sql.normalizeForLog()}")+ }+ }+ }+}++private fun String.normalizeForLog(): String {+ return trim()+ .replace(Regex("\\s+"), " ")+ .let { normalized ->+ if (normalized.length <= 240) normalized else normalized.take(237) + "..."+ }+}diff --git a/app/src/main/java/com/streamvault/app/navigation/AppNavigation.kt b/app/src/main/java/com/streamvault/app/navigation/AppNavigation.ktindex 1528550a..51b786bd 100644--- a/app/src/main/java/com/streamvault/app/navigation/AppNavigation.kt+++ b/app/src/main/java/com/streamvault/app/navigation/AppNavigation.kt@@ -40,6 +40,8 @@ data class PlayerNavigationRequest(val categoryId: Long? = null,val providerId: Long? = null,val isVirtual: Boolean = false,+ val combinedProfileId: Long? = null,+ val combinedSourceFilterProviderId: Long? = null,val contentType: String = "LIVE",val artworkUrl: String? = null,val archiveStartMs: Long? = null,@@ -88,6 +90,8 @@ object Routes {categoryId: Long? = channel.categoryId,providerId: Long? = channel.providerId,isVirtual: Boolean = false,+ combinedProfileId: Long? = null,+ combinedSourceFilterProviderId: Long? = null,returnRoute: String? = null): PlayerNavigationRequest {val effectiveCategoryId = categoryId ?: ChannelRepository.ALL_CHANNELS_ID@@ -99,6 +103,8 @@ object Routes {categoryId = effectiveCategoryId,providerId = providerId,isVirtual = isVirtual,+ combinedProfileId = combinedProfileId,+ combinedSourceFilterProviderId = combinedSourceFilterProviderId,contentType = "LIVE",returnRoute = returnRoute)@@ -141,6 +147,8 @@ object Routes {categoryId: Long? = null,providerId: Long? = null,isVirtual: Boolean = false,+ combinedProfileId: Long? = null,+ combinedSourceFilterProviderId: Long? = null,contentType: String = "LIVE",artworkUrl: String? = null,archiveStartMs: Long? = null,@@ -159,6 +167,8 @@ object Routes {categoryId = categoryId,providerId = providerId,isVirtual = isVirtual,+ combinedProfileId = combinedProfileId,+ combinedSourceFilterProviderId = combinedSourceFilterProviderId,contentType = contentType,artworkUrl = artworkUrl,archiveStartMs = archiveStartMs,@@ -298,24 +308,26 @@ fun AppNavigation(mainActivity: MainActivity) {onAddProvider = dropUnlessResumed {navController.navigate(Routes.providerSetup(null))},- onChannelClick = { channel ->+ onRecentChannelClick = { channel, combinedProfileId ->navController.navigateToPlayer(Routes.livePlayer(channel = channel,- categoryId = channel.categoryId ?: ChannelRepository.ALL_CHANNELS_ID,+ categoryId = com.streamvault.domain.model.VirtualCategoryIds.RECENT,providerId = channel.providerId,- isVirtual = false,+ isVirtual = true,+ combinedProfileId = combinedProfileId,returnRoute = Routes.HOME))},- onFavoriteChannelClick = { channel ->+ onFavoriteChannelClick = { channel, combinedProfileId ->navController.navigateToPlayer(Routes.livePlayer(channel = channel,categoryId = com.streamvault.domain.model.VirtualCategoryIds.FAVORITES,providerId = channel.providerId,isVirtual = true,+ combinedProfileId = combinedProfileId,returnRoute = Routes.HOME))@@ -383,13 +395,15 @@ fun AppNavigation(mainActivity: MainActivity) {) { backStackEntry ->val initialCategoryId = backStackEntry.arguments?.getLong("categoryId")?.takeIf { it != -1L }HomeScreen(- onChannelClick = { channel, category, provider ->+ onChannelClick = { channel, category, provider, combinedProfileId, combinedSourceFilterProviderId ->navController.navigateToPlayer(Routes.livePlayer(channel = channel,categoryId = category?.id,providerId = provider?.id,isVirtual = category?.isVirtual == true,+ combinedProfileId = combinedProfileId,+ combinedSourceFilterProviderId = combinedSourceFilterProviderId,returnRoute = Routes.liveTv(category?.id)))@@ -437,27 +451,29 @@ fun AppNavigation(mainActivity: MainActivity) {initialCategoryId = epgCategoryId,initialAnchorTime = epgAnchorTime,initialFavoritesOnly = epgFavoritesOnly,- onPlayChannel = { channel, returnRoute ->+ onPlayChannel = { channel, categoryId, isVirtual, combinedProfileId, returnRoute ->navController.navigateToPlayer(Routes.livePlayer(channel = channel,- categoryId = channel.categoryId ?: ChannelRepository.ALL_CHANNELS_ID,+ categoryId = categoryId,providerId = channel.providerId,- isVirtual = false,+ isVirtual = isVirtual,+ combinedProfileId = combinedProfileId,returnRoute = returnRoute))},- onPlayArchive = { channel, program, returnRoute ->+ onPlayArchive = { channel, program, categoryId, isVirtual, combinedProfileId, returnRoute ->navController.navigateToPlayer(Routes.player(streamUrl = channel.streamUrl,title = channel.name,channelId = channel.epgChannelId,internalId = channel.id,- categoryId = channel.categoryId ?: ChannelRepository.ALL_CHANNELS_ID,+ categoryId = categoryId,providerId = channel.providerId,- isVirtual = false,+ isVirtual = isVirtual,+ combinedProfileId = combinedProfileId,contentType = "LIVE",archiveStartMs = program.startTime,archiveEndMs = program.endTime,@@ -547,6 +563,8 @@ fun AppNavigation(mainActivity: MainActivity) {categoryId = playerRequest?.categoryId,providerId = playerRequest?.providerId,isVirtual = playerRequest?.isVirtual ?: false,+ combinedProfileId = playerRequest?.combinedProfileId,+ combinedSourceFilterProviderId = playerRequest?.combinedSourceFilterProviderId,contentType = playerRequest?.contentType ?: "LIVE",artworkUrl = playerRequest?.artworkUrl,archiveStartMs = playerRequest?.archiveStartMs,diff --git a/app/src/main/java/com/streamvault/app/tvinput/TvInputChannelSyncManager.kt b/app/src/main/java/com/streamvault/app/tvinput/TvInputChannelSyncManager.ktindex e83204df..91f81e57 100644--- a/app/src/main/java/com/streamvault/app/tvinput/TvInputChannelSyncManager.kt+++ b/app/src/main/java/com/streamvault/app/tvinput/TvInputChannelSyncManager.kt@@ -90,7 +90,7 @@ class TvInputChannelSyncManager @Inject constructor(val merged = mutableMapOf<String, List<Program>>()epgIds.distinct().chunked(EPG_QUERY_CHUNK_SIZE).forEach { chunk ->- merged += epgRepository.getProgramsForChannels(providerId, chunk, start, end).first()+ merged += epgRepository.getProgramsForChannelsSnapshot(providerId, chunk, start, end)}return merged}diff --git a/app/src/main/java/com/streamvault/app/ui/components/dialogs/AddToGroupDialog.kt b/app/src/main/java/com/streamvault/app/ui/components/dialogs/AddToGroupDialog.ktindex 20dc3ca4..039ad2b7 100644--- a/app/src/main/java/com/streamvault/app/ui/components/dialogs/AddToGroupDialog.kt+++ b/app/src/main/java/com/streamvault/app/ui/components/dialogs/AddToGroupDialog.kt@@ -46,7 +46,8 @@ fun AddToGroupDialog(onRemoveFromGroup: (Category) -> Unit,onCreateGroup: (String) -> Unit,isQueuedForSplitScreen: Boolean = false,- onOpenSplitScreenPlanner: (() -> Unit)? = null+ onOpenSplitScreenPlanner: (() -> Unit)? = null,+ onRemoveFromRecent: (() -> Unit)? = null) {var showCreateGroup by remember { mutableStateOf(false) }val isTelevisionDevice = rememberIsTelevisionDevice()@@ -75,6 +76,7 @@ fun AddToGroupDialog(val safeDismiss = { if (canInteract) onDismiss() }val safeToggleFavorite = { if (canInteract) onToggleFavorite() }val safeOpenSplitScreenPlanner = { if (canInteract) onOpenSplitScreenPlanner?.invoke() }+ val safeRemoveFromRecent = { if (canInteract) onRemoveFromRecent?.invoke() }val safeCreateGroup = { if (canInteract) showCreateGroup = true }val safeAddToGroup: (Category) -> Unit = { group -> if (canInteract) onAddToGroup(group) }val safeRemoveFromGroup: (Category) -> Unit = { group -> if (canInteract) onRemoveFromGroup(group) }@@ -218,6 +220,47 @@ fun AddToGroupDialog(}}+ // ── Remove from Recent ───────────────────────+ if (onRemoveFromRecent != null) {+ item {+ var isFocused by remember { mutableStateOf(false) }+ Button(+ onClick = safeRemoveFromRecent,+ modifier = Modifier+ .fillMaxWidth()+ .onFocusChanged { isFocused = it.isFocused }+ .background(+ color = if (isFocused) AppColors.Focus else Color.Transparent,+ shape = CircleShape+ )+ .border(+ if (isFocused) 3.dp else 0.dp,+ if (isFocused) AppColors.Focus else Color.Transparent,+ CircleShape+ )+ .mouseClickable(onClick = safeRemoveFromRecent),+ colors = ButtonDefaults.colors(+ containerColor = when {+ isFocused -> AppColors.Focus+ else -> MaterialTheme.colorScheme.errorContainer+ },+ contentColor = if (isFocused) Color.Black else MaterialTheme.colorScheme.onErrorContainer+ )+ ) {+ Icon(+ imageVector = Icons.Default.Close,+ contentDescription = stringResource(R.string.channel_options_remove_from_recent),+ tint = if (isFocused) Color.Black else MaterialTheme.colorScheme.onErrorContainer+ )+ Spacer(modifier = Modifier.width(8.dp))+ Text(+ text = stringResource(R.string.channel_options_remove_from_recent),+ color = if (isFocused) Color.Black else MaterialTheme.colorScheme.onErrorContainer+ )+ }+ }+ }+// ── Custom Groups Section ─────────────────────item {Box(diff --git a/app/src/main/java/com/streamvault/app/ui/components/dialogs/CategoryOptionsDialog.kt b/app/src/main/java/com/streamvault/app/ui/components/dialogs/CategoryOptionsDialog.ktindex 531d84c6..80a0dcb9 100644--- a/app/src/main/java/com/streamvault/app/ui/components/dialogs/CategoryOptionsDialog.kt+++ b/app/src/main/java/com/streamvault/app/ui/components/dialogs/CategoryOptionsDialog.kt@@ -46,6 +46,8 @@ fun CategoryOptionsDialog(onTogglePinned: (() -> Unit)? = null,onRename: (() -> Unit)? = null,onHide: (() -> Unit)? = null,+ onHideFromLiveTV: (() -> Unit)? = null,+ onClearAll: (() -> Unit)? = null,onToggleLock: (() -> Unit)? = null,onDelete: (() -> Unit)? = null,onReorderChannels: (() -> Unit)? = null@@ -146,6 +148,21 @@ fun CategoryOptionsDialog()}+ if (onHideFromLiveTV != null) {+ PremiumDialogAction(+ label = stringResource(R.string.category_options_hide_from_live_tv),+ onClick = { if (canInteract) onHideFromLiveTV() }+ )+ }++ if (onClearAll != null) {+ PremiumDialogAction(+ label = stringResource(R.string.category_options_clear_recent),+ onClick = { if (canInteract) onClearAll() },+ destructive = true+ )+ }+if (onReorderChannels != null) {PremiumDialogAction(label = stringResource(R.string.category_options_reorder),diff --git a/app/src/main/java/com/streamvault/app/ui/components/dialogs/ProgramHistoryDialog.kt b/app/src/main/java/com/streamvault/app/ui/components/dialogs/ProgramHistoryDialog.ktindex daa5ddc0..1d744dd9 100644--- a/app/src/main/java/com/streamvault/app/ui/components/dialogs/ProgramHistoryDialog.kt+++ b/app/src/main/java/com/streamvault/app/ui/components/dialogs/ProgramHistoryDialog.kt@@ -136,13 +136,14 @@ fun ProgramHistoryDialog(.border(width = if (isFocused) 2.dp else 1.dp,color = if (isFocused) {- MaterialTheme.colorScheme.primary+ Color.White} else {unfocusedBorderColor},shape = RoundedCornerShape(8.dp)),shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(8.dp)),+ scale = ClickableSurfaceDefaults.scale(focusedScale = 1.0f),colors = ClickableSurfaceDefaults.colors(containerColor = Color.Transparent,focusedContainerColor = focusedContainerColordiff --git a/app/src/main/java/com/streamvault/app/ui/components/shell/AppMediaCards.kt b/app/src/main/java/com/streamvault/app/ui/components/shell/AppMediaCards.ktindex 1c4fe0c4..724b8e9c 100644--- a/app/src/main/java/com/streamvault/app/ui/components/shell/AppMediaCards.kt+++ b/app/src/main/java/com/streamvault/app/ui/components/shell/AppMediaCards.kt@@ -160,9 +160,13 @@ fun LiveChannelRowCard(}Text(text = buildString {- val numberLabel = channel.number.takeIf { it > 0 }?.toString()?.padStart(2, '0') ?: "--"- append(numberLabel)- append(" ")+ val numberLabel = channel.number.takeIf { it > 0 }?.toString()?.padStart(2, '0')+ if (numberLabel != null) {+ append(numberLabel)+ append(" ")+ } else if (channel.number == 0) {+ append("-- ")+ }append(channel.name)},style = if (isDense) MaterialTheme.typography.bodyLarge else MaterialTheme.typography.titleSmall,diff --git a/app/src/main/java/com/streamvault/app/ui/components/shell/VodClassicBrowser.kt b/app/src/main/java/com/streamvault/app/ui/components/shell/VodClassicBrowser.ktindex faf479e3..e27ed677 100644--- a/app/src/main/java/com/streamvault/app/ui/components/shell/VodClassicBrowser.kt+++ b/app/src/main/java/com/streamvault/app/ui/components/shell/VodClassicBrowser.kt@@ -143,6 +143,7 @@ fun VodClassicContentHeader(title: String,subtitle: String,actions: List<VodActionChip>,+ selectedActionKey: String? = null,modifier: Modifier = Modifier) {Row(@@ -177,7 +178,10 @@ fun VodClassicContentHeader(verticalAlignment = Alignment.CenterVertically) {actions.forEach { action ->- VodClassicHeaderActionButton(action = action)+ VodClassicHeaderActionButton(+ action = action,+ isSelected = action.key == selectedActionKey+ )}}}@@ -186,6 +190,7 @@ fun VodClassicContentHeader(@Composableprivate fun VodClassicHeaderActionButton(action: VodActionChip,+ isSelected: Boolean = false,modifier: Modifier = Modifier) {TvClickableSurface(@@ -193,9 +198,9 @@ private fun VodClassicHeaderActionButton(modifier = modifier,shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(18.dp)),colors = ClickableSurfaceDefaults.colors(- containerColor = AppColors.SurfaceElevated,+ containerColor = if (isSelected) AppColors.Brand.copy(alpha = 0.18f) else AppColors.SurfaceElevated,focusedContainerColor = AppColors.SurfaceEmphasis,- contentColor = AppColors.TextPrimary,+ contentColor = if (isSelected) AppColors.BrandStrong else AppColors.TextPrimary,focusedContentColor = AppColors.TextPrimary),border = ClickableSurfaceDefaults.border(@@ -206,12 +211,25 @@ private fun VodClassicHeaderActionButton(),scale = ClickableSurfaceDefaults.scale(focusedScale = 1f)) {- Text(- text = action.label,- style = MaterialTheme.typography.titleSmall,+ Column(modifier = Modifier.padding(horizontal = 18.dp, vertical = 10.dp),- maxLines = 1,- overflow = TextOverflow.Ellipsis- )+ verticalArrangement = Arrangement.spacedBy(2.dp)+ ) {+ Text(+ text = action.label,+ style = MaterialTheme.typography.titleSmall,+ maxLines = 1,+ overflow = TextOverflow.Ellipsis+ )+ action.detail?.takeIf { it.isNotBlank() }?.let { detail ->+ Text(+ text = detail,+ style = MaterialTheme.typography.labelSmall,+ color = if (isSelected) AppColors.Brand else AppColors.TextSecondary,+ maxLines = 1,+ overflow = TextOverflow.Ellipsis+ )+ }+ }}}diff --git a/app/src/main/java/com/streamvault/app/ui/screens/dashboard/DashboardScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/dashboard/DashboardScreen.ktindex c01d3605..49fd4d21 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/dashboard/DashboardScreen.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/dashboard/DashboardScreen.kt@@ -88,8 +88,8 @@ import com.streamvault.app.ui.interaction.TvIconButtonfun DashboardScreen(onNavigate: (String) -> Unit,onAddProvider: () -> Unit,- onChannelClick: (Channel) -> Unit,- onFavoriteChannelClick: (Channel) -> Unit,+ onRecentChannelClick: (Channel, Long?) -> Unit,+ onFavoriteChannelClick: (Channel, Long?) -> Unit,onMovieClick: (Movie) -> Unit,onSeriesClick: (Series) -> Unit,onPlaybackHistoryClick: (PlaybackHistory) -> Unit,@@ -176,7 +176,9 @@ fun DashboardScreen(title = stringResource(R.string.dashboard_favorite_channels),channels = uiState.favoriteChannels,onSeeAll = { onNavigate(Routes.liveTv(com.streamvault.domain.model.VirtualCategoryIds.FAVORITES)) },- onChannelClick = onFavoriteChannelClick+ onChannelClick = { channel ->+ onFavoriteChannelClick(channel, uiState.currentCombinedProfileId)+ })DashboardHomeSection.RECENT_CHANNELS -> CategoryRow(@@ -187,7 +189,7 @@ fun DashboardScreen() { channel ->ChannelCard(channel = channel,- onClick = { onChannelClick(channel) }+ onClick = { onRecentChannelClick(channel, uiState.currentCombinedProfileId) })}diff --git a/app/src/main/java/com/streamvault/app/ui/screens/dashboard/DashboardViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/dashboard/DashboardViewModel.ktindex 388d0154..ca77fdb8 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/dashboard/DashboardViewModel.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/dashboard/DashboardViewModel.kt@@ -6,9 +6,11 @@ import com.streamvault.app.BuildConfigimport com.streamvault.data.preferences.PreferencesRepositoryimport com.streamvault.data.sync.SyncManagerimport com.streamvault.app.update.AppUpdateInstaller+import com.streamvault.domain.model.ActiveLiveSourceimport com.streamvault.domain.model.Categoryimport com.streamvault.domain.model.Channelimport com.streamvault.domain.model.ContentType+import com.streamvault.domain.model.Favoriteimport com.streamvault.domain.model.Movieimport com.streamvault.domain.model.PlaybackHistoryimport com.streamvault.domain.model.Provider@@ -18,6 +20,7 @@ import com.streamvault.domain.model.Seriesimport com.streamvault.domain.model.SyncStateimport com.streamvault.domain.model.VirtualCategoryIdsimport com.streamvault.domain.repository.ChannelRepository+import com.streamvault.domain.repository.CombinedM3uRepositoryimport com.streamvault.domain.repository.FavoriteRepositoryimport com.streamvault.domain.repository.MovieRepositoryimport com.streamvault.domain.repository.PlaybackHistoryRepository@@ -40,7 +43,10 @@ import kotlinx.coroutines.flow.MutableStateFlowimport kotlinx.coroutines.flow.StateFlowimport kotlinx.coroutines.flow.asStateFlowimport kotlinx.coroutines.flow.combine+import kotlinx.coroutines.flow.distinctUntilChanged+import kotlinx.coroutines.flow.emitAllimport kotlinx.coroutines.flow.flatMapLatest+import kotlinx.coroutines.flow.flowimport kotlinx.coroutines.flow.flowOfimport kotlinx.coroutines.flow.mapimport kotlinx.coroutines.flow.onStart@@ -51,6 +57,7 @@ import kotlinx.coroutines.launchclass DashboardViewModel @Inject constructor(@ApplicationContext private val appContext: Context,private val providerRepository: ProviderRepository,+ private val combinedM3uRepository: CombinedM3uRepository,private val favoriteRepository: FavoriteRepository,private val channelRepository: ChannelRepository,private val playbackHistoryRepository: PlaybackHistoryRepository,@@ -76,96 +83,50 @@ class DashboardViewModel @Inject constructor(init {viewModelScope.launch {- providerRepository.getActiveProvider()- .flatMapLatest { provider ->- if (provider == null) {- flowOf(DashboardUiState(isLoading = false))- } else {- val contentShelves = combine(- observeFavoriteChannels(provider.id).onStart { emit(emptyList()) },- observeRecentChannels(provider.id).onStart { emit(emptyList()) },- observeContinueWatching(provider.id).onStart { emit(emptyList()) },- movieRepository.getMovies(provider.id).map { movies ->- movies- .filterNot(::shouldHideVodFromHome)- .sortedByDescending(::movieFreshnessScore)- .take(MOVIE_SHELF_LIMIT)- }.onStart { emit(emptyList()) },- seriesRepository.getSeries(provider.id).map { series ->- series- .filterNot(::shouldHideVodFromHome)- .sortedByDescending(::seriesFreshnessScore)- .take(SERIES_SHELF_LIMIT)- }.onStart { emit(emptyList()) }- ) { favoriteChannels, recentChannels, continueWatching, recentMovies, recentSeries ->- DashboardContentShelves(- favoriteChannels = favoriteChannels,- recentChannels = recentChannels,- continueWatching = continueWatching,- recentMovies = recentMovies,- recentSeries = recentSeries- )+ combine(+ combinedM3uRepository.getActiveLiveSource(),+ providerRepository.getActiveProvider()+ ) { activeSource, activeProvider ->+ Pair(activeSource ?: activeProvider?.id?.let { ActiveLiveSource.ProviderSource(it) }, activeProvider)+ }+ .distinctUntilChanged { old, new ->+ old.first == new.first && old.second?.id == new.second?.id+ }+ .flatMapLatest { (activeSource, activeProvider) ->+ flow {+ if (activeSource == null && activeProvider == null) {+ emit(DashboardUiState(isLoading = false))+ return@flow}- combine(- contentShelves,- buildLiveContext(provider.id).onStart {- emit(DashboardLiveContext(lastVisitedCategory = null, shortcuts = emptyList()))- },- channelRepository.getChannels(provider.id).map { it.size }.onStart { emit(0) },- movieRepository.getLibraryCount(provider.id).onStart { emit(0) },- seriesRepository.getLibraryCount(provider.id).onStart { emit(0) }- ) { shelves, liveContext, liveChannelCount, movieCount, seriesCount ->- DashboardSnapshot(- shelves = shelves,- liveContext = liveContext,- liveChannelCount = liveChannelCount,- movieCount = movieCount,- seriesCount = seriesCount,- updateNotice = null- )- }.combine(observeUpdateNotice().onStart { emit(null) }) { snapshot, updateNotice ->- snapshot.copy(updateNotice = updateNotice)- }.combine(syncManager.syncStateForProvider(provider.id).onStart { emit(SyncState.Idle) }) { snapshot, syncState ->- DashboardUiState(- provider = provider,- favoriteChannels = snapshot.shelves.favoriteChannels,- recentChannels = snapshot.shelves.recentChannels,- continueWatching = snapshot.shelves.continueWatching,- recentMovies = snapshot.shelves.recentMovies,- recentSeries = snapshot.shelves.recentSeries,- lastLiveCategory = snapshot.liveContext.lastVisitedCategory,- liveShortcuts = snapshot.liveContext.shortcuts,- stats = DashboardStats(- liveChannelCount = snapshot.liveChannelCount,- favoriteChannelCount = snapshot.shelves.favoriteChannels.size,- recentChannelCount = snapshot.shelves.recentChannels.size,- continueWatchingCount = snapshot.shelves.continueWatching.size,- movieLibraryCount = snapshot.movieCount,- seriesLibraryCount = snapshot.seriesCount- ),- feature = buildFeature(- providerName = provider.name,- recentChannels = snapshot.shelves.recentChannels,- continueWatching = snapshot.shelves.continueWatching,- recentMovies = snapshot.shelves.recentMovies,- recentSeries = snapshot.shelves.recentSeries- ),- providerHealth = DashboardProviderHealth(- status = provider.status,- type = provider.type,- lastSyncedAt = provider.lastSyncedAt,- expirationDate = provider.expirationDate,- maxConnections = provider.maxConnections- ),- providerWarnings = when (syncState) {- is SyncState.Partial -> syncState.warnings- is SyncState.Error -> listOf(syncState.message)- else -> emptyList()- },- updateNotice = snapshot.updateNotice,- isLoading = false- )+ when (activeSource) {+ is ActiveLiveSource.ProviderSource -> {+ val provider = activeProvider?.takeIf { it.id == activeSource.providerId }+ ?: providerRepository.getProvider(activeSource.providerId)+ ?: run {+ emit(DashboardUiState(isLoading = false))+ return@flow+ }+ emitAll(observeDashboard(provider, listOf(provider.id), combinedProfileId = null))+ }++ is ActiveLiveSource.CombinedM3uSource -> {+ val liveProviderIds = combinedM3uRepository.getProfile(activeSource.profileId)+ ?.members+ .orEmpty()+ .filter { it.enabled }+ .map { it.providerId }+ .distinct()+ val provider = activeProvider+ ?: liveProviderIds.firstOrNull()?.let { providerRepository.getProvider(it) }+ ?: run {+ emit(DashboardUiState(isLoading = false, currentCombinedProfileId = activeSource.profileId))+ return@flow+ }+ emitAll(observeDashboard(provider, liveProviderIds, combinedProfileId = activeSource.profileId))+ }++ null -> emit(DashboardUiState(isLoading = false))}}}@@ -175,8 +136,105 @@ class DashboardViewModel @Inject constructor(}}- private fun observeFavoriteChannels(providerId: Long): Flow<List<Channel>> =- favoriteRepository.getFavorites(ContentType.LIVE)+ private fun observeDashboard(+ provider: Provider,+ liveProviderIds: List<Long>,+ combinedProfileId: Long?+ ): Flow<DashboardUiState> {+ val contentShelves = combine(+ observeFavoriteChannels(liveProviderIds).onStart { emit(emptyList()) },+ observeRecentChannels(liveProviderIds).onStart { emit(emptyList()) },+ observeContinueWatching(provider.id).onStart { emit(emptyList()) },+ movieRepository.getMovies(provider.id).map { movies ->+ movies+ .filterNot(::shouldHideVodFromHome)+ .sortedByDescending(::movieFreshnessScore)+ .take(MOVIE_SHELF_LIMIT)+ }.onStart { emit(emptyList()) },+ seriesRepository.getSeries(provider.id).map { series ->+ series+ .filterNot(::shouldHideVodFromHome)+ .sortedByDescending(::seriesFreshnessScore)+ .take(SERIES_SHELF_LIMIT)+ }.onStart { emit(emptyList()) }+ ) { favoriteChannels, recentChannels, continueWatching, recentMovies, recentSeries ->+ DashboardContentShelves(+ favoriteChannels = favoriteChannels,+ recentChannels = recentChannels,+ continueWatching = continueWatching,+ recentMovies = recentMovies,+ recentSeries = recentSeries+ )+ }++ return combine(+ contentShelves,+ buildLiveContext(+ providerIds = liveProviderIds,+ lastVisitedProviderId = provider.id.takeIf { combinedProfileId == null }+ ).onStart {+ emit(DashboardLiveContext(lastVisitedCategory = null, shortcuts = emptyList()))+ },+ observeLiveChannelCount(liveProviderIds).onStart { emit(0) },+ movieRepository.getLibraryCount(provider.id).onStart { emit(0) },+ seriesRepository.getLibraryCount(provider.id).onStart { emit(0) }+ ) { shelves, liveContext, liveChannelCount, movieCount, seriesCount ->+ DashboardSnapshot(+ shelves = shelves,+ liveContext = liveContext,+ liveChannelCount = liveChannelCount,+ movieCount = movieCount,+ seriesCount = seriesCount,+ updateNotice = null+ )+ }.combine(observeUpdateNotice().onStart { emit(null) }) { snapshot, updateNotice ->+ snapshot.copy(updateNotice = updateNotice)+ }.combine(syncManager.syncStateForProvider(provider.id).onStart { emit(SyncState.Idle) }) { snapshot, syncState ->+ DashboardUiState(+ provider = provider,+ favoriteChannels = snapshot.shelves.favoriteChannels,+ recentChannels = snapshot.shelves.recentChannels,+ continueWatching = snapshot.shelves.continueWatching,+ recentMovies = snapshot.shelves.recentMovies,+ recentSeries = snapshot.shelves.recentSeries,+ lastLiveCategory = snapshot.liveContext.lastVisitedCategory,+ liveShortcuts = snapshot.liveContext.shortcuts,+ currentCombinedProfileId = combinedProfileId,+ stats = DashboardStats(+ liveChannelCount = snapshot.liveChannelCount,+ favoriteChannelCount = snapshot.shelves.favoriteChannels.size,+ recentChannelCount = snapshot.shelves.recentChannels.size,+ continueWatchingCount = snapshot.shelves.continueWatching.size,+ movieLibraryCount = snapshot.movieCount,+ seriesLibraryCount = snapshot.seriesCount+ ),+ feature = buildFeature(+ providerName = provider.name,+ recentChannels = snapshot.shelves.recentChannels,+ continueWatching = snapshot.shelves.continueWatching,+ recentMovies = snapshot.shelves.recentMovies,+ recentSeries = snapshot.shelves.recentSeries+ ),+ providerHealth = DashboardProviderHealth(+ status = provider.status,+ type = provider.type,+ lastSyncedAt = provider.lastSyncedAt,+ expirationDate = provider.expirationDate,+ maxConnections = provider.maxConnections+ ),+ providerWarnings = when (syncState) {+ is SyncState.Partial -> syncState.warnings+ is SyncState.Error -> listOf(syncState.message)+ else -> emptyList()+ },+ updateNotice = snapshot.updateNotice,+ isLoading = false+ )+ }+ }++ private fun observeFavoriteChannels(providerIds: List<Long>): Flow<List<Channel>> =+ observeLiveFavorites(providerIds).map { favorites ->favorites.filter { it.groupId == null }@@ -186,17 +244,15 @@ class DashboardViewModel @Inject constructor(}.flatMapLatest(::loadChannelsByOrderedIds)- private fun observeRecentChannels(providerId: Long): Flow<List<Channel>> =- playbackHistoryRepository.getRecentlyWatchedByProvider(providerId, RECENT_CHANNEL_LIMIT)- .map { history ->- history- .filter { it.contentType == ContentType.LIVE }- .sortedByDescending { it.lastWatchedAt }- .distinctBy { it.contentId }- .map { it.contentId }- .take(RECENT_CHANNEL_LIMIT)+ private fun observeRecentChannels(providerIds: List<Long>): Flow<List<Channel>> =+ preferencesRepository.showRecentChannelsCategory.flatMapLatest { show ->+ if (!show) {+ flowOf(emptyList())+ } else {+ observeRecentLiveIds(providerIds, RECENT_CHANNEL_LIMIT)+ .flatMapLatest(::loadChannelsByOrderedIds)}- .flatMapLatest(::loadChannelsByOrderedIds)+ }private fun observeContinueWatching(providerId: Long): Flow<List<PlaybackHistory>> =getContinueWatching(@@ -205,10 +261,17 @@ class DashboardViewModel @Inject constructor(scope = ContinueWatchingScope.ALL_VOD)- private fun buildLiveContext(providerId: Long): Flow<DashboardLiveContext> =- combine(- getCustomCategories(ContentType.LIVE),- preferencesRepository.getLastLiveCategoryId(providerId),+ private fun buildLiveContext(+ providerIds: List<Long>,+ lastVisitedProviderId: Long?+ ): Flow<DashboardLiveContext> {+ if (providerIds.isEmpty()) {+ return flowOf(DashboardLiveContext(lastVisitedCategory = null, shortcuts = emptyList()))+ }++ return combine(+ getCustomCategories(providerIds, ContentType.LIVE),+ lastVisitedProviderId?.let(preferencesRepository::getLastLiveCategoryId) ?: flowOf(null),preferencesRepository.promotedLiveGroupIds) { customCategories, lastVisitedCategoryId, promotedGroupIds ->val lastVisitedCategory = customCategories.firstOrNull { it.id == lastVisitedCategoryId }@@ -259,6 +322,49 @@ class DashboardViewModel @Inject constructor(shortcuts = shortcuts)}+ }++ private fun observeLiveChannelCount(providerIds: List<Long>): Flow<Int> = when (providerIds.size) {+ 0 -> flowOf(0)+ 1 -> channelRepository.getChannels(providerIds.first()).map { it.size }+ else -> combine(providerIds.map { providerId ->+ channelRepository.getChannels(providerId).map { channels -> channels.size }+ }) { counts ->+ counts.sum()+ }+ }++ private fun observeLiveFavorites(providerIds: List<Long>): Flow<List<Favorite>> = when (providerIds.size) {+ 0 -> flowOf(emptyList())+ 1 -> favoriteRepository.getFavorites(providerIds.first(), ContentType.LIVE)+ else -> favoriteRepository.getFavorites(providerIds, ContentType.LIVE)+ }++ private fun observeRecentLiveIds(providerIds: List<Long>, limit: Int): Flow<List<Long>> = when (providerIds.size) {+ 0 -> flowOf(emptyList())+ 1 -> playbackHistoryRepository.getRecentlyWatchedByProvider(providerIds.first(), limit)+ .map { history ->+ history+ .filter { it.contentType == ContentType.LIVE }+ .sortedByDescending { it.lastWatchedAt }+ .distinctBy { it.contentId }+ .map { it.contentId }+ .take(limit)+ }+ else -> combine(providerIds.map { providerId ->+ playbackHistoryRepository.getRecentlyWatchedByProvider(providerId, limit)+ }) { histories ->+ histories.toList()+ .flatMap { it }+ .asSequence()+ .filter { it.contentType == ContentType.LIVE }+ .sortedByDescending { it.lastWatchedAt }+ .distinctBy { it.providerId to it.contentId }+ .map { it.contentId }+ .take(limit)+ .toList()+ }+ }private fun loadChannelsByOrderedIds(ids: List<Long>): Flow<List<Channel>> {if (ids.isEmpty()) return flowOf(emptyList())@@ -474,6 +580,7 @@ data class DashboardUiState(val feature: DashboardFeature = DashboardFeature(),val providerHealth: DashboardProviderHealth = DashboardProviderHealth(),val providerWarnings: List<String> = emptyList(),+ val currentCombinedProfileId: Long? = null,val updateNotice: DashboardUpdateNotice? = null,val stats: DashboardStats = DashboardStats(),val userMessage: String? = null,diff --git a/app/src/main/java/com/streamvault/app/ui/screens/epg/EpgGridComponents.kt b/app/src/main/java/com/streamvault/app/ui/screens/epg/EpgGridComponents.ktindex 7d841eb9..42edec74 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/epg/EpgGridComponents.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/epg/EpgGridComponents.kt@@ -397,7 +397,7 @@ fun EpgRow(verticalArrangement = Arrangement.spacedBy(0.dp)) {Text(- text = "${channel.number}. ${channel.name}",+ text = if (channel.number > 0) "${channel.number}. ${channel.name}" else channel.name,style = MaterialTheme.typography.labelLarge,color = if (isFocused) TextPrimary else OnSurface,maxLines = 1,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 6a770847..978466f0 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@@ -109,6 +109,7 @@ import com.streamvault.domain.model.EpgMatchTypeimport com.streamvault.domain.model.EpgOverrideCandidateimport com.streamvault.domain.model.EpgSourceTypeimport com.streamvault.domain.model.Program+import com.streamvault.domain.model.VirtualCategoryIdsimport com.streamvault.domain.repository.ChannelRepositoryimport java.text.SimpleDateFormatimport java.util.Calendar@@ -134,13 +135,14 @@ fun FullEpgScreen(initialCategoryId: Long? = null,initialAnchorTime: Long? = null,initialFavoritesOnly: Boolean = false,- onPlayChannel: (Channel, String) -> Unit,- onPlayArchive: (Channel, Program, String) -> Unit,+ onPlayChannel: (Channel, Long, Boolean, Long?, String) -> Unit,+ onPlayArchive: (Channel, Program, Long, Boolean, Long?, String) -> Unit,onNavigate: (String) -> Unit,viewModel: EpgViewModel = hiltViewModel()) {val uiState by viewModel.uiState.collectAsStateWithLifecycle()val overrideUiState by viewModel.overrideUiState.collectAsStateWithLifecycle()+ val programReminderUiState by viewModel.programReminderUiState.collectAsStateWithLifecycle()var selectedProgram by remember { mutableStateOf<Pair<Channel, Program>?>(null) }var focusedChannel by remember { mutableStateOf<Channel?>(null) }var focusedProgram by remember { mutableStateOf<Program?>(null) }@@ -163,13 +165,38 @@ fun FullEpgScreen(val categoriesById = remember(uiState.categories) {uiState.categories.associateBy { it.id }}+ val playerCategoryId = remember(uiState.selectedCategoryId, uiState.showFavoritesOnly) {+ if (uiState.showFavoritesOnly && uiState.selectedCategoryId == ChannelRepository.ALL_CHANNELS_ID) {+ VirtualCategoryIds.FAVORITES+ } else {+ uiState.selectedCategoryId+ }+ }+ val playerIsVirtualCategory = playerCategoryId == VirtualCategoryIds.FAVORITES ||+ playerCategoryId == VirtualCategoryIds.RECENT ||+ playerCategoryId < 0Lfun executeLockedGuideAction(action: LockedGuideAction) {when (action) {is LockedGuideAction.SelectCategory -> viewModel.selectCategory(action.category.id)is LockedGuideAction.OpenProgram -> selectedProgram = action.channel to action.program- is LockedGuideAction.PlayChannel -> onPlayChannel(action.channel, action.returnRoute)- is LockedGuideAction.PlayArchive -> onPlayArchive(action.channel, action.program, action.returnRoute)+ is LockedGuideAction.PlayChannel ->+ onPlayChannel(+ action.channel,+ playerCategoryId,+ playerIsVirtualCategory,+ uiState.combinedProfileId,+ action.returnRoute+ )+ is LockedGuideAction.PlayArchive ->+ onPlayArchive(+ action.channel,+ action.program,+ playerCategoryId,+ playerIsVirtualCategory,+ uiState.combinedProfileId,+ action.returnRoute+ )}}@@ -350,7 +377,13 @@ fun FullEpgScreen(if (isGuideChannelLocked(channel, categoriesById, uiState.parentalControlLevel)) {requestLockedGuideAction(LockedGuideAction.PlayChannel(channel, returnRoute))} else {- onPlayChannel(channel, returnRoute)+ onPlayChannel(+ channel,+ playerCategoryId,+ playerIsVirtualCategory,+ uiState.combinedProfileId,+ returnRoute+ )}},onProgramClick = { channel, program ->@@ -470,6 +503,31 @@ fun FullEpgScreen(if (dialogState != null) {GuideNowProvider {val (channel, program) = dialogState+ val reminderProviderId = program.providerId.takeIf { it > 0L } ?: channel.providerId+ LaunchedEffect(channel.id, reminderProviderId, program.channelId, program.title, program.startTime) {+ viewModel.loadProgramReminderState(channel, program)+ }+ val reminderStateMatches = programReminderUiState.matches(+ providerId = reminderProviderId,+ channelId = program.channelId,+ programTitle = program.title,+ programStartTime = program.startTime+ )+ val reminderButtonLabel = if (+ reminderProviderId > 0L &&+ program.channelId.isNotBlank() &&+ program.startTime > currentGuideNow() + 60_000L+ ) {+ when {+ reminderStateMatches && programReminderUiState.isLoading ->+ stringResource(R.string.epg_program_reminder_loading)+ reminderStateMatches && programReminderUiState.isScheduled ->+ stringResource(R.string.epg_program_reminder_cancel)+ else -> stringResource(R.string.epg_program_reminder_set)+ }+ } else {+ null+ }CompactGuideProgramDialog(channel = channel,program = program,@@ -481,7 +539,13 @@ fun FullEpgScreen(if (isGuideChannelLocked(channel, categoriesById, uiState.parentalControlLevel)) {requestLockedGuideAction(LockedGuideAction.PlayChannel(channel, returnRoute))} else {- onPlayChannel(channel, returnRoute)+ onPlayChannel(+ channel,+ playerCategoryId,+ playerIsVirtualCategory,+ uiState.combinedProfileId,+ returnRoute+ )}},onWatchArchive = if (program.hasArchive || channel.catchUpSupported) {@@ -490,7 +554,14 @@ fun FullEpgScreen(if (isGuideChannelLocked(channel, categoriesById, uiState.parentalControlLevel)) {requestLockedGuideAction(LockedGuideAction.PlayArchive(channel, program, returnRoute))} else {- onPlayArchive(channel, program, returnRoute)+ onPlayArchive(+ channel,+ program,+ playerCategoryId,+ playerIsVirtualCategory,+ uiState.combinedProfileId,+ returnRoute+ )}}} else {@@ -503,6 +574,10 @@ fun FullEpgScreen(}} else {null+ },+ reminderButtonLabel = reminderButtonLabel,+ onToggleReminder = reminderButtonLabel?.let {+ { viewModel.toggleProgramReminder(channel, program) }})}diff --git a/app/src/main/java/com/streamvault/app/ui/screens/epg/EpgScreenDialogs.kt b/app/src/main/java/com/streamvault/app/ui/screens/epg/EpgScreenDialogs.ktindex 0a61e476..5d3d168e 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/epg/EpgScreenDialogs.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/epg/EpgScreenDialogs.kt@@ -303,7 +303,9 @@ internal fun CompactGuideProgramDialog(onDismiss: () -> Unit,onWatchLive: () -> Unit,onWatchArchive: (() -> Unit)?,- onManageEpgMatch: (() -> Unit)?+ onManageEpgMatch: (() -> Unit)?,+ reminderButtonLabel: String?,+ onToggleReminder: (() -> Unit)?) {var showDetails by rememberSaveable(program.startTime, program.endTime, program.title) { mutableStateOf(false) }val format = remember { SimpleDateFormat("HH:mm", Locale.getDefault()) }@@ -327,7 +329,14 @@ internal fun CompactGuideProgramDialog(overflow = TextOverflow.Ellipsis)Text(- text = "${channel.number}. ${channel.name} | ${format.format(Date(program.startTime))} - ${format.format(Date(program.endTime))}",+ text = buildString {+ if (channel.number > 0) { append(channel.number); append(". ") }+ append(channel.name)+ append(" | ")+ append(format.format(Date(program.startTime)))+ append(" - ")+ append(format.format(Date(program.endTime)))+ },style = MaterialTheme.typography.bodyMedium,color = OnSurfaceDim,maxLines = 2,@@ -390,6 +399,18 @@ internal fun CompactGuideProgramDialog(Text(stringResource(R.string.epg_override_manage))}}+ if (reminderButtonLabel != null && onToggleReminder != null) {+ TvButton(+ onClick = onToggleReminder,+ modifier = Modifier.fillMaxWidth(),+ colors = ButtonDefaults.colors(+ containerColor = SurfaceHighlight,+ contentColor = OnSurface+ )+ ) {+ Text(reminderButtonLabel)+ }+ }TvButton(onClick = { showDetails = !showDetails },modifier = Modifier.fillMaxWidth(),@@ -460,7 +481,7 @@ internal fun EpgOverrideDialog(color = OnSurface)Text(- text = "${channel.number}. ${channel.name}",+ text = if (channel.number > 0) "${channel.number}. ${channel.name}" else channel.name,style = MaterialTheme.typography.bodyMedium,color = OnSurfaceDim)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 ec485d34..51a712c7 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@@ -5,6 +5,7 @@ import androidx.lifecycle.ViewModelimport androidx.lifecycle.viewModelScopeimport com.streamvault.app.ui.model.applyProviderCategoryDisplayPreferencesimport com.streamvault.domain.manager.ParentalControlManager+import com.streamvault.domain.manager.ProgramReminderManagerimport com.streamvault.domain.model.ActiveLiveSourceimport com.streamvault.domain.model.Categoryimport com.streamvault.domain.model.ChannelEpgMapping@@ -12,6 +13,7 @@ import com.streamvault.domain.model.Channelimport com.streamvault.domain.model.CombinedCategoryimport com.streamvault.domain.model.ContentTypeimport com.streamvault.domain.model.EpgOverrideCandidate+import com.streamvault.domain.model.Favoriteimport com.streamvault.domain.model.Programimport com.streamvault.domain.model.VirtualCategoryIdsimport com.streamvault.domain.repository.ChannelRepository@@ -47,6 +49,7 @@ data class EpgUiState(val currentProviderName: String? = null,val providerSourceLabel: String = "",val providerArchiveSummary: String = "",+ val combinedProfileId: Long? = null,val categories: List<Category> = emptyList(),val selectedCategoryId: Long = ChannelRepository.ALL_CHANNELS_ID,val programSearchQuery: String = "",@@ -81,6 +84,21 @@ data class EpgOverrideUiState(val error: String? = null)+data class ProgramReminderUiState(+ val providerId: Long = 0L,+ val channelId: String = "",+ val programTitle: String = "",+ val programStartTime: Long = 0L,+ val isScheduled: Boolean = false,+ val isLoading: Boolean = false+) {+ fun matches(providerId: Long, channelId: String, programTitle: String, programStartTime: Long): Boolean =+ this.providerId == providerId &&+ this.channelId == channelId &&+ this.programTitle == programTitle &&+ this.programStartTime == programStartTime+}+enum class GuideChannelMode {ALL,ANCHORED,@@ -160,6 +178,18 @@ private data class GuideSelectionRequest(val isStartupSelection: Boolean)+private data class CombinedGuideDependencies(+ val combinedCategories: List<CombinedCategory>,+ val providerIds: List<Long>,+ val customCategories: List<Category>,+ val selection: Pair<GuideSelectionSeed, Int>+)++private data class CombinedGuideRequest(+ val request: GuideBaseRequest,+ val providerIds: List<Long>+)+@HiltViewModelclass EpgViewModel @Inject constructor(private val providerRepository: ProviderRepository,@@ -170,6 +200,7 @@ class EpgViewModel @Inject constructor(private val favoriteRepository: FavoriteRepository,private val preferencesRepository: PreferencesRepository,private val parentalControlManager: ParentalControlManager,+ private val programReminderManager: ProgramReminderManager,private val getCustomCategories: GetCustomCategories) : ViewModel() {@@ -201,6 +232,8 @@ class EpgViewModel @Inject constructor(private val baseGuideSnapshot = MutableStateFlow<GuideBaseSnapshot?>(null)private val _overrideUiState = MutableStateFlow(EpgOverrideUiState())val overrideUiState: StateFlow<EpgOverrideUiState> = _overrideUiState.asStateFlow()+ private val _programReminderUiState = MutableStateFlow(ProgramReminderUiState())+ val programReminderUiState: StateFlow<ProgramReminderUiState> = _programReminderUiState.asStateFlow()private var overrideSearchJob: Job? = nullprivate var combinedCategoriesById: Map<Long, CombinedCategory> = emptyMap()@@ -256,6 +289,76 @@ class EpgViewModel @Inject constructor(_overrideUiState.value = EpgOverrideUiState()}+ fun loadProgramReminderState(channel: Channel, program: Program) {+ val providerId = program.providerId.takeIf { it > 0L } ?: channel.providerId+ val channelId = program.channelId+ if (providerId <= 0L || channelId.isBlank()) {+ _programReminderUiState.value = ProgramReminderUiState()+ return+ }+ _programReminderUiState.update {+ it.copy(+ providerId = providerId,+ channelId = channelId,+ programTitle = program.title,+ programStartTime = program.startTime,+ isLoading = true+ )+ }+ viewModelScope.launch {+ val scheduled = programReminderManager.isReminderScheduled(+ providerId = providerId,+ channelId = channelId,+ programTitle = program.title,+ programStartTime = program.startTime+ )+ _programReminderUiState.value = ProgramReminderUiState(+ providerId = providerId,+ channelId = channelId,+ programTitle = program.title,+ programStartTime = program.startTime,+ isScheduled = scheduled,+ isLoading = false+ )+ }+ }++ fun toggleProgramReminder(channel: Channel, program: Program) {+ val providerId = program.providerId.takeIf { it > 0L } ?: channel.providerId+ val channelId = program.channelId+ if (providerId <= 0L || channelId.isBlank()) return+ val currentState = _programReminderUiState.value+ val isScheduled = currentState.matches(providerId, channelId, program.title, program.startTime) &&+ currentState.isScheduled+ _programReminderUiState.update {+ it.copy(+ providerId = providerId,+ channelId = channelId,+ programTitle = program.title,+ programStartTime = program.startTime,+ isLoading = true+ )+ }+ viewModelScope.launch {+ if (isScheduled) {+ programReminderManager.cancelReminder(+ providerId = providerId,+ channelId = channelId,+ programTitle = program.title,+ programStartTime = program.startTime+ )+ } else {+ programReminderManager.scheduleReminder(+ providerId = providerId,+ channelId = channelId,+ channelName = channel.name,+ program = program+ )+ }+ loadProgramReminderState(channel, program)+ }+ }+fun updateEpgOverrideSearch(query: String) {val channel = _overrideUiState.value.channel ?: return_overrideUiState.update {@@ -421,6 +524,7 @@ class EpgViewModel @Inject constructor(currentProviderName = null,providerSourceLabel = "",providerArchiveSummary = "",+ combinedProfileId = null,categories = emptyList(),channels = emptyList(),programsByChannel = emptyMap(),@@ -442,12 +546,14 @@ class EpgViewModel @Inject constructor(when (activeSource) {is ActiveLiveSource.ProviderSource -> {+ _uiState.update { it.copy(combinedProfileId = null) }val provider = activeProvider?.takeIf { it.id == activeSource.providerId }?: providerRepository.getProvider(activeSource.providerId)?: return@collectLatestobserveSingleProviderGuide(provider)}is ActiveLiveSource.CombinedM3uSource -> {+ _uiState.update { it.copy(combinedProfileId = activeSource.profileId) }observeCombinedGuide(activeSource.profileId)}null -> Unit@@ -459,7 +565,7 @@ class EpgViewModel @Inject constructor(private suspend fun observeSingleProviderGuide(provider: com.streamvault.domain.model.Provider) {combine(channelRepository.getCategories(provider.id),- getCustomCategories(ContentType.LIVE),+ getCustomCategories(provider.id, ContentType.LIVE),preferencesRepository.getHiddenCategoryIds(provider.id, ContentType.LIVE),preferencesRepository.getCategorySortMode(provider.id, ContentType.LIVE)) { providerCategories, customCategories, hiddenCategoryIds, sortMode ->@@ -469,6 +575,8 @@ class EpgViewModel @Inject constructor(hiddenCategoryIds = hiddenCategoryIds,sortMode = sortMode)+ }.combine(preferencesRepository.showAllChannelsCategory) { data, showAll ->+ data.copy(showAllChannels = showAll)}.combine(combine(@@ -504,7 +612,8 @@ class EpgViewModel @Inject constructor()val orderedCategories = buildGuideCategoryList(providerCategories = visibleProviderCategories,- customCategories = categoryData.customCategories+ customCategories = categoryData.customCategories,+ showAllChannels = categoryData.showAllChannels)val resolvedCategoryId = resolveGuideCategorySelection(requestedCategoryId = selection.requestedCategoryId,@@ -547,7 +656,7 @@ class EpgViewModel @Inject constructor()}- combine(loadGuideChannelsForProvider(provider.id, request), favoriteRepository.getFavorites(ContentType.LIVE)) { preferredChannels, favorites ->+ combine(loadGuideChannelsForProvider(provider.id, request), favoriteRepository.getFavorites(provider.id, ContentType.LIVE)) { preferredChannels, favorites ->val favoriteIds = favorites.map { it.contentId }.toSet()GuideChannelSelection(channels = preferredChannels.filterNot { channel -> channel.categoryId in request.hiddenCategoryIds },@@ -581,9 +690,13 @@ class EpgViewModel @Inject constructor(}private suspend fun observeCombinedGuide(profileId: Long) {+ val providerIdsFlow = combinedProviderIdsFlow(profileId)combine(combinedM3uRepository.getCombinedCategories(profileId),- getCustomCategories(ContentType.LIVE),+ providerIdsFlow,+ providerIdsFlow.flatMapLatest { providerIds ->+ getCustomCategories(providerIds, ContentType.LIVE)+ },combine(selectedCategoryId,startupCategoryId,@@ -600,30 +713,43 @@ class EpgViewModel @Inject constructor(}.combine(preferencesRepository.parentalControlLevel) { selection, parentalControlLevel ->selection to parentalControlLevel}- ) { combinedCategories, customCategories, selection ->+ ) { combinedCategories, providerIds, customCategories, selection ->combinedCategoriesById = combinedCategories.associateBy { it.category.id }+ CombinedGuideDependencies(+ combinedCategories = combinedCategories,+ providerIds = providerIds,+ customCategories = customCategories,+ selection = selection+ )+ }.combine(preferencesRepository.showAllChannelsCategory) { data, showAllChannels ->val categories = buildGuideCategoryList(- providerCategories = combinedCategories.map { it.category },- customCategories = customCategories+ providerCategories = data.combinedCategories.map { it.category },+ customCategories = data.customCategories,+ showAllChannels = showAllChannels)val resolvedCategoryId = resolveGuideCategorySelection(- requestedCategoryId = selection.first.requestedCategoryId,+ requestedCategoryId = data.selection.first.requestedCategoryId,categories = categories,- parentalControlLevel = selection.second,+ parentalControlLevel = data.selection.second,unlockedCategoryIds = emptySet(),- fallbackFromEmptyFavorites = selection.first.isStartupSelection+ fallbackFromEmptyFavorites = data.selection.first.isStartupSelection)- GuideBaseRequest(- categories = categories,- hiddenCategoryIds = emptySet(),- resolvedCategoryId = resolvedCategoryId,- parentalControlLevel = selection.second,- anchorTime = selection.first.anchorTime,- favoritesOnly = selection.first.favoritesOnly,- windowStart = selection.first.anchorTime - LOOKBACK_MS,- windowEnd = selection.first.anchorTime + LOOKAHEAD_MS+ CombinedGuideRequest(+ request = GuideBaseRequest(+ categories = categories,+ hiddenCategoryIds = emptySet(),+ resolvedCategoryId = resolvedCategoryId,+ parentalControlLevel = data.selection.second,+ anchorTime = data.selection.first.anchorTime,+ favoritesOnly = data.selection.first.favoritesOnly,+ windowStart = data.selection.first.anchorTime - LOOKBACK_MS,+ windowEnd = data.selection.first.anchorTime + LOOKAHEAD_MS+ ),+ providerIds = data.providerIds)- }.collectLatest { request ->+ }.collectLatest { combinedRequest ->+ val request = combinedRequest.request+ val providerIds = combinedRequest.providerIdsval categories = request.categoriesval profile = combinedM3uRepository.getProfile(profileId)val profileName = profile?.name ?: "Combined M3U"@@ -647,8 +773,8 @@ class EpgViewModel @Inject constructor(}combine(- combinedGuideChannels(profileId, request.resolvedCategoryId),- favoriteRepository.getFavorites(ContentType.LIVE)+ combinedGuideChannels(profileId, request.resolvedCategoryId, providerIds),+ observeLiveFavorites(providerIds)) { channels, favorites ->val favoriteIds = favorites.map { it.contentId }.toSet()val preferredChannels = if (request.favoritesOnly) channels.filter { it.id in favoriteIds } else channels@@ -676,13 +802,13 @@ class EpgViewModel @Inject constructor(}}- private fun combinedGuideChannels(profileId: Long, categoryId: Long) =+ private fun combinedGuideChannels(profileId: Long, categoryId: Long, providerIds: List<Long>) =if (categoryId == ChannelRepository.ALL_CHANNELS_ID) {val flows = combinedCategoriesById.values.map { combinedM3uRepository.getCombinedChannels(profileId, it) }if (flows.isEmpty()) kotlinx.coroutines.flow.flowOf(emptyList())else combine(flows) { arrays -> arrays.toList().flatMap { it } }} else if (categoryId == VirtualCategoryIds.FAVORITES) {- favoriteRepository.getFavorites(ContentType.LIVE)+ observeLiveFavorites(providerIds).map { favorites -> favorites.sortedBy { it.position }.map { it.contentId } }.flatMapLatest(::loadGuideChannelsByOrderedIds)} else if (categoryId < 0L) {@@ -880,7 +1006,8 @@ class EpgViewModel @Inject constructor(private fun buildGuideCategoryList(providerCategories: List<Category>,- customCategories: List<Category>+ customCategories: List<Category>,+ showAllChannels: Boolean = true): List<Category> {val favoritesCategory = customCategories.find { it.id == VirtualCategoryIds.FAVORITES }return buildList {@@ -888,14 +1015,16 @@ class EpgViewModel @Inject constructor(add(favoritesCategory)}addAll(customCategories.filter { it.id != VirtualCategoryIds.FAVORITES })- add(- Category(- id = ChannelRepository.ALL_CHANNELS_ID,- name = "All Channels",- type = ContentType.LIVE,- count = providerCategories.sumOf(Category::count)+ if (showAllChannels) {+ add(+ Category(+ id = ChannelRepository.ALL_CHANNELS_ID,+ name = "All Channels",+ type = ContentType.LIVE,+ count = providerCategories.sumOf(Category::count)+ ))- )+ }addAll(providerCategories)}}@@ -907,7 +1036,7 @@ class EpgViewModel @Inject constructor(ChannelRepository.ALL_CHANNELS_ID -> combine(channelRepository.getChannelsByNumber(providerId, request.resolvedCategoryId),channelRepository.getChannelsWithoutErrors(providerId, request.resolvedCategoryId),- favoriteRepository.getFavorites(ContentType.LIVE)+ favoriteRepository.getFavorites(providerId, ContentType.LIVE)) { channelsByNumber, healthyChannels, favorites ->val favoriteIds = favorites.map { it.contentId }.toSet()if (request.favoritesOnly) {@@ -918,7 +1047,7 @@ class EpgViewModel @Inject constructor(}}- VirtualCategoryIds.FAVORITES -> favoriteRepository.getFavorites(ContentType.LIVE)+ VirtualCategoryIds.FAVORITES -> favoriteRepository.getFavorites(providerId, ContentType.LIVE).map { favorites -> favorites.sortedBy { it.position }.map { it.contentId } }.flatMapLatest { ids -> loadGuideChannelsByOrderedIds(ids, providerId) }@@ -929,7 +1058,7 @@ class EpgViewModel @Inject constructor(else -> combine(channelRepository.getChannelsByNumber(providerId, request.resolvedCategoryId),channelRepository.getChannelsWithoutErrors(providerId, request.resolvedCategoryId),- favoriteRepository.getFavorites(ContentType.LIVE)+ favoriteRepository.getFavorites(providerId, ContentType.LIVE)) { channelsByNumber, healthyChannels, favorites ->val favoriteIds = favorites.map { it.contentId }.toSet()if (request.favoritesOnly) {@@ -941,6 +1070,18 @@ class EpgViewModel @Inject constructor(}}+ private fun combinedProviderIdsFlow(profileId: Long): kotlinx.coroutines.flow.Flow<List<Long>> = kotlinx.coroutines.flow.flow {+ emit(combinedM3uRepository.getProfile(profileId)?.members.orEmpty())+ }.map { members ->+ members.filter { it.enabled }.map { it.providerId }+ }++ private fun observeLiveFavorites(providerIds: List<Long>): kotlinx.coroutines.flow.Flow<List<Favorite>> = when (providerIds.size) {+ 0 -> kotlinx.coroutines.flow.flowOf(emptyList())+ 1 -> favoriteRepository.getFavorites(providerIds.first(), ContentType.LIVE)+ else -> favoriteRepository.getFavorites(providerIds, ContentType.LIVE)+ }+private fun loadGuideChannelsByOrderedIds(ids: List<Long>, providerId: Long? = null) =if (ids.isEmpty()) {kotlinx.coroutines.flow.flowOf(emptyList())@@ -993,7 +1134,7 @@ class EpgViewModel @Inject constructor(}.distinct()runCatching {if (xmltvKeys.isEmpty()) emptyMap()- else epgRepository.getProgramsForChannels(providerId, xmltvKeys, windowStart, windowEnd).first()+ else epgRepository.getProgramsForChannelsSnapshot(providerId, xmltvKeys, windowStart, windowEnd)}.getOrElse { emptyMap() }} else {emptyMap()@@ -1184,8 +1325,7 @@ class EpgViewModel @Inject constructor(unlockedCategoryIds: Set<Long>,fallbackFromEmptyFavorites: Boolean = false): Long {- val requestedExists = requestedCategoryId == ChannelRepository.ALL_CHANNELS_ID ||- categories.any { it.id == requestedCategoryId }+ val requestedExists = categories.any { it.id == requestedCategoryId }if (requestedCategoryId == ChannelRepository.ALL_CHANNELS_ID && requestedExists) {return ChannelRepository.ALL_CHANNELS_ID}@@ -1193,7 +1333,13 @@ class EpgViewModel @Inject constructor(val requestedCategory = categories.firstOrNull { it.id == requestedCategoryId }if (requestedCategory != null && isGuideCategoryAccessible(requestedCategory, parentalControlLevel, unlockedCategoryIds)) {if (fallbackFromEmptyFavorites && requestedCategory.id == VirtualCategoryIds.FAVORITES && requestedCategory.count <= 0) {- return ChannelRepository.ALL_CHANNELS_ID+ return categories.find { it.id == ChannelRepository.ALL_CHANNELS_ID }?.id+ ?: categories.firstOrNull {+ !(it.id == VirtualCategoryIds.FAVORITES && it.count <= 0) &&+ isGuideCategoryAccessible(it, parentalControlLevel, unlockedCategoryIds)+ }?.id+ ?: categories.firstOrNull()?.id+ ?: ChannelRepository.ALL_CHANNELS_ID}return requestedCategory.id}@@ -1204,7 +1350,7 @@ class EpgViewModel @Inject constructor(} else {isGuideCategoryAccessible(category, parentalControlLevel, unlockedCategoryIds)}- }?.id ?: ChannelRepository.ALL_CHANNELS_ID+ }?.id ?: categories.firstOrNull()?.id ?: ChannelRepository.ALL_CHANNELS_ID}private fun isGuideCategoryAccessible(@@ -1238,5 +1384,6 @@ private data class GuideCategoryData(val providerCategories: List<Category>,val customCategories: List<Category>,val hiddenCategoryIds: Set<Long>,- val sortMode: com.streamvault.domain.model.CategorySortMode+ val sortMode: com.streamvault.domain.model.CategorySortMode,+ val showAllChannels: Boolean = true)diff --git a/app/src/main/java/com/streamvault/app/ui/screens/favorites/FavoritesViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/favorites/FavoritesViewModel.ktindex 38b73c9f..f42c27e4 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/favorites/FavoritesViewModel.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/favorites/FavoritesViewModel.kt@@ -136,7 +136,12 @@ class FavoritesViewModel @Inject constructor(val uiState: StateFlow<FavoritesUiState> = _uiState.asStateFlow()init {- val globalSectionFlow = observeFavoriteItems(favoriteRepository.getFavorites(null))+ val providerIdsFlow = providerRepository.getProviders()+ .map { providers -> providers.map { it.id } }++ val globalSectionFlow = providerIdsFlow.flatMapLatest { providerIds ->+ observeFavoriteItems(favoriteRepository.getFavorites(providerIds))+ }.map { items ->FavoriteSectionUiModel(key = GLOBAL_SECTION_KEY,@@ -147,52 +152,60 @@ class FavoritesViewModel @Inject constructor()}- val allGroupsFlow = combine(- favoriteRepository.getGroups(ContentType.LIVE),- favoriteRepository.getGroups(ContentType.MOVIE),- favoriteRepository.getGroups(ContentType.SERIES)- ) { liveGroups, movieGroups, seriesGroups ->- (liveGroups + movieGroups + seriesGroups)- .sortedWith(compareBy<VirtualGroup>({ it.contentType.ordinal }, { it.position }, { it.name.lowercase() }))+ val allGroupsFlow = providerIdsFlow.flatMapLatest { providerIds ->+ combine(+ favoriteRepository.getGroups(providerIds, ContentType.LIVE),+ favoriteRepository.getGroups(providerIds, ContentType.MOVIE),+ favoriteRepository.getGroups(providerIds, ContentType.SERIES)+ ) { liveGroups, movieGroups, seriesGroups ->+ (liveGroups + movieGroups + seriesGroups)+ .sortedWith(compareBy<VirtualGroup>({ it.contentType.ordinal }, { it.position }, { it.name.lowercase() }))+ }}- val liveGroupManagementFlow = combine(- favoriteRepository.getGroups(ContentType.LIVE),- favoriteRepository.getGroupFavoriteCounts(ContentType.LIVE),- preferencesRepository.promotedLiveGroupIds- ) { liveGroups, liveCounts, promotedLiveGroupIds ->- liveGroups.map { group ->- SavedGroupManagementUiModel(- group = group,- itemCount = liveCounts[group.id] ?: 0,- isPromotedOnHome = group.id in promotedLiveGroupIds- )+ val liveGroupManagementFlow = providerIdsFlow.flatMapLatest { providerIds ->+ combine(+ favoriteRepository.getGroups(providerIds, ContentType.LIVE),+ favoriteRepository.getFavorites(providerIds, ContentType.LIVE).map(::countFavoritesByGroup),+ preferencesRepository.promotedLiveGroupIds+ ) { liveGroups, liveCounts, promotedLiveGroupIds ->+ liveGroups.map { group ->+ SavedGroupManagementUiModel(+ group = group,+ itemCount = liveCounts[group.id] ?: 0,+ isPromotedOnHome = group.id in promotedLiveGroupIds+ )+ }}}- val movieGroupManagementFlow = combine(- favoriteRepository.getGroups(ContentType.MOVIE),- favoriteRepository.getGroupFavoriteCounts(ContentType.MOVIE)- ) { movieGroups, movieCounts ->- movieGroups.map { group ->- SavedGroupManagementUiModel(- group = group,- itemCount = movieCounts[group.id] ?: 0,- isPromotedOnHome = false- )+ val movieGroupManagementFlow = providerIdsFlow.flatMapLatest { providerIds ->+ combine(+ favoriteRepository.getGroups(providerIds, ContentType.MOVIE),+ favoriteRepository.getFavorites(providerIds, ContentType.MOVIE).map(::countFavoritesByGroup)+ ) { movieGroups, movieCounts ->+ movieGroups.map { group ->+ SavedGroupManagementUiModel(+ group = group,+ itemCount = movieCounts[group.id] ?: 0,+ isPromotedOnHome = false+ )+ }}}- val seriesGroupManagementFlow = combine(- favoriteRepository.getGroups(ContentType.SERIES),- favoriteRepository.getGroupFavoriteCounts(ContentType.SERIES)- ) { seriesGroups, seriesCounts ->- seriesGroups.map { group ->- SavedGroupManagementUiModel(- group = group,- itemCount = seriesCounts[group.id] ?: 0,- isPromotedOnHome = false- )+ val seriesGroupManagementFlow = providerIdsFlow.flatMapLatest { providerIds ->+ combine(+ favoriteRepository.getGroups(providerIds, ContentType.SERIES),+ favoriteRepository.getFavorites(providerIds, ContentType.SERIES).map(::countFavoritesByGroup)+ ) { seriesGroups, seriesCounts ->+ seriesGroups.map { group ->+ SavedGroupManagementUiModel(+ group = group,+ itemCount = seriesCounts[group.id] ?: 0,+ isPromotedOnHome = false+ )+ }}}@@ -426,6 +439,7 @@ class FavoritesViewModel @Inject constructor(viewModelScope.launch {val targetGroups = _uiState.value.managedGroups.filter { it.group.contentType == item.favorite.contentType }+ .filter { it.group.providerId == item.favorite.providerId }.filter { it.group.id != item.favorite.groupId }_uiState.update {it.copy(@@ -439,6 +453,7 @@ class FavoritesViewModel @Inject constructor(fun removeFromSavedContext(item: FavoriteUiModel) {viewModelScope.launch {favoriteRepository.removeFavorite(+ providerId = item.favorite.providerId,contentId = item.favorite.contentId,contentType = item.favorite.contentType,groupId = item.favorite.groupId@@ -456,11 +471,13 @@ class FavoritesViewModel @Inject constructor(fun moveItemToGroup(item: FavoriteUiModel, targetGroupId: Long) {viewModelScope.launch {favoriteRepository.addFavorite(+ providerId = item.favorite.providerId,contentId = item.favorite.contentId,contentType = item.favorite.contentType,groupId = targetGroupId)favoriteRepository.removeFavorite(+ providerId = item.favorite.providerId,contentId = item.favorite.contentId,contentType = item.favorite.contentType,groupId = item.favorite.groupId@@ -527,6 +544,7 @@ class FavoritesViewModel @Inject constructor(fun startMergeGroup(group: SavedGroupManagementUiModel) {val candidates = _uiState.value.managedGroups.filter { it.group.contentType == group.group.contentType && it.group.id != group.group.id }+ .filter { it.group.providerId == group.group.providerId }_uiState.update {it.copy(mergeSourceGroup = group,@@ -541,11 +559,13 @@ class FavoritesViewModel @Inject constructor(val items = favoriteRepository.getFavoritesByGroup(source.group.id).first()items.forEach { favorite ->favoriteRepository.addFavorite(+ providerId = favorite.providerId,contentId = favorite.contentId,contentType = favorite.contentType,groupId = targetGroupId)favoriteRepository.removeFavorite(+ providerId = favorite.providerId,contentId = favorite.contentId,contentType = favorite.contentType,groupId = source.group.id@@ -695,6 +715,13 @@ class FavoritesViewModel @Inject constructor(private const val GLOBAL_SECTION_KEY = "global"private fun sectionKeyForGroup(groupId: Long): String = "group:$groupId"++ private fun countFavoritesByGroup(favorites: List<Favorite>): Map<Long, Int> =+ favorites+ .asSequence()+ .mapNotNull(Favorite::groupId)+ .groupingBy { it }+ .eachCount()}}diff --git a/app/src/main/java/com/streamvault/app/ui/screens/home/HomeScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/home/HomeScreen.ktindex a9f81b9b..de5c74f0 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/home/HomeScreen.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/home/HomeScreen.kt@@ -68,11 +68,13 @@ import com.streamvault.app.ui.design.requestFocusSafelyimport androidx.activity.compose.BackHandlerimport com.streamvault.app.ui.model.LiveTvQuickFilterVisibilityModeimport com.streamvault.app.ui.theme.*+import com.streamvault.domain.model.ActiveLiveSourceimport com.streamvault.domain.model.Categoryimport com.streamvault.domain.model.Channelimport com.streamvault.domain.model.Providerimport kotlinx.coroutines.launchimport kotlinx.coroutines.flow.distinctUntilChanged+import kotlinx.coroutines.flow.filterimport androidx.compose.ui.res.stringResourceimport com.streamvault.app.Rimport com.streamvault.app.ui.model.LiveTvChannelMode@@ -129,7 +131,7 @@ private fun HomeLoadingPane(@Composablefun HomeScreen(- onChannelClick: (Channel, Category?, Provider?) -> Unit,+ onChannelClick: (Channel, Category?, Provider?, Long?, Long?) -> Unit,onNavigate: (String) -> Unit,currentRoute: String,initialCategoryId: Long? = null,@@ -1045,6 +1047,19 @@ fun HomeScreen(}}+ // Load more channels when the user scrolls near the end of the list+ LaunchedEffect(channelListState) {+ snapshotFlow {+ val info = channelListState.layoutInfo+ val lastVisible = info.visibleItemsInfo.lastOrNull()?.index ?: -1+ val total = info.totalItemsCount+ uiState.hasMoreChannels && total > 0 && lastVisible >= total - 5+ }+ .distinctUntilChanged()+ .filter { it }+ .collect { viewModel.loadMoreChannels() }+ }+DisposableEffect(Unit) {onDispose {viewModel.updateVisibleChannelWindow(emptyList(), null)@@ -1106,12 +1121,24 @@ fun HomeScreen(} else if (isProMode) {if (uiState.previewChannelId == channel.id) {viewModel.clearPreview()- onChannelClick(channel, uiState.selectedCategory, resolveProviderForChannel(channel))+ onChannelClick(+ channel,+ uiState.selectedCategory,+ resolveProviderForChannel(channel),+ (uiState.activeLiveSource as? ActiveLiveSource.CombinedM3uSource)?.profileId,+ uiState.selectedCombinedSourceProviderId+ )} else {viewModel.previewChannel(channel)}} else {- onChannelClick(channel, uiState.selectedCategory, resolveProviderForChannel(channel))+ onChannelClick(+ channel,+ uiState.selectedCategory,+ resolveProviderForChannel(channel),+ (uiState.activeLiveSource as? ActiveLiveSource.CombinedM3uSource)?.profileId,+ uiState.selectedCombinedSourceProviderId+ )}}},diff --git a/app/src/main/java/com/streamvault/app/ui/screens/home/HomeScreenDialogs.kt b/app/src/main/java/com/streamvault/app/ui/screens/home/HomeScreenDialogs.ktindex 221e9452..b049dff9 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/home/HomeScreenDialogs.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/home/HomeScreenDialogs.kt@@ -54,7 +54,7 @@ internal fun HomeDialogsHost(onShowAddQuickFilterDialogChange: (Boolean) -> Unit,onShowSplitManagerDialogChange: (Boolean) -> Unit,onPendingSplitPlannerChannelChange: (Channel?) -> Unit,- onChannelClick: (Channel, Category?, Provider?) -> Unit,+ onChannelClick: (Channel, Category?, Provider?, Long?, Long?) -> Unit,resolveProviderForChannel: (Channel) -> Provider?,onNavigate: (String) -> Unit,scope: CoroutineScope@@ -99,7 +99,7 @@ internal fun HomeDialogsHost(pendingUnlockChannel?.let { channel ->viewModel.clearPreview()- onChannelClick(channel, uiState.selectedCategory, resolveProviderForChannel(channel))+ onChannelClick(channel, uiState.selectedCategory, resolveProviderForChannel(channel), null, null)onPendingUnlockChannelChange(null)}@@ -141,6 +141,21 @@ internal fun HomeDialogsHost(onHide = if (!isCategoryLocked && !category.isVirtual && category.id != ChannelRepository.ALL_CHANNELS_ID) {{ viewModel.hideCategory(category) }} else null,+ onHideFromLiveTV = if (!isCategoryLocked && category.id in setOf(VirtualCategoryIds.RECENT, ChannelRepository.ALL_CHANNELS_ID)) {+ {+ when (category.id) {+ VirtualCategoryIds.RECENT -> viewModel.setShowRecentChannelsCategory(false)+ ChannelRepository.ALL_CHANNELS_ID -> viewModel.setShowAllChannelsCategory(false)+ }+ viewModel.dismissCategoryOptions()+ }+ } else null,+ onClearAll = if (!isCategoryLocked && category.id == VirtualCategoryIds.RECENT) {+ {+ viewModel.clearRecentChannels()+ viewModel.dismissCategoryOptions()+ }+ } else null,onRename = if (!isCategoryLocked && category.isVirtual && category.id !in setOf(VirtualCategoryIds.FAVORITES, VirtualCategoryIds.RECENT)) {{ viewModel.requestRenameGroup(category) }} else null,@@ -228,7 +243,13 @@ internal fun HomeDialogsHost(onRemoveFromGroup = { group -> viewModel.removeFromGroup(channel, group) },onCreateGroup = { name -> viewModel.createCustomGroup(name) },isQueuedForSplitScreen = multiViewViewModel.isQueued(channel.id),- onOpenSplitScreenPlanner = { onPendingSplitPlannerChannelChange(channel) }+ onOpenSplitScreenPlanner = { onPendingSplitPlannerChannelChange(channel) },+ onRemoveFromRecent = if (uiState.selectedCategory?.id == VirtualCategoryIds.RECENT) {+ {+ viewModel.removeChannelFromRecent(channel)+ viewModel.onDismissDialog()+ }+ } else null)}diff --git a/app/src/main/java/com/streamvault/app/ui/screens/home/HomeViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/home/HomeViewModel.ktindex d46c9e46..634ccab5 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/home/HomeViewModel.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/home/HomeViewModel.kt@@ -21,6 +21,7 @@ import com.streamvault.domain.model.ChannelNumberingModeimport com.streamvault.domain.model.CombinedCategoryimport com.streamvault.domain.model.CombinedM3uProfileMemberimport com.streamvault.domain.model.ContentType+import com.streamvault.domain.model.Favoriteimport com.streamvault.domain.model.PlaybackHistoryimport com.streamvault.domain.model.Programimport com.streamvault.domain.model.Provider@@ -80,6 +81,9 @@ class HomeViewModel @Inject constructor() : ViewModel() {private companion object {const val MIN_CHANNEL_SEARCH_QUERY_LENGTH = 2+ const val CHANNEL_PAGE_SIZE = 200+ const val CHANNEL_SEARCH_PAGE_SIZE = 300+ const val LOAD_MORE_THRESHOLD = 5}private val appContext = application@@ -88,6 +92,8 @@ class HomeViewModel @Inject constructor(val uiState: StateFlow<HomeUiState> = _uiState.asStateFlow()private val _localChannels = MutableStateFlow<List<Channel>>(emptyList())+ private val _channelBrowseLimit = MutableStateFlow(CHANNEL_PAGE_SIZE)+ private val _channelSearchLimit = MutableStateFlow(CHANNEL_SEARCH_PAGE_SIZE)private val _preferredInitialCategoryId = MutableStateFlow<Long?>(null)private val _visibleChannelWindow = MutableStateFlow<Set<Long>>(emptySet())private val _epgProgramMap = MutableStateFlow<Map<String, Program>>(emptyMap())@@ -224,9 +230,9 @@ class HomeViewModel @Inject constructor(viewModelScope.launch {combine(_localChannels,- favoriteRepository.getFavorites(ContentType.LIVE),+ observeCurrentLiveFavorites(),_epgProgramMap- ) { channels, favorites, epgProgramMap ->+ ) { channels: List<Channel>, favorites: List<Favorite>, epgProgramMap: Map<String, Program> ->Triple(channels, favorites, epgProgramMap)}.collectLatest { (channels, favorites, epgProgramMap) ->val favoriteIds = favorites.map { it.contentId }.toSet()@@ -399,7 +405,7 @@ class HomeViewModel @Inject constructor(_uiState.update { it.copy(isCategoriesLoading = true, errorMessage = null) }combine(channelRepository.getCategories(providerId),- getCustomCategories(),+ getCustomCategories(providerId, ContentType.LIVE),preferencesRepository.defaultCategoryId,preferencesRepository.getLastLiveCategoryId(providerId),preferencesRepository.getHiddenCategoryIds(providerId, ContentType.LIVE),@@ -454,6 +460,10 @@ class HomeViewModel @Inject constructor(lastVisitedCategoryId = lastVisitedCategoryId,pinnedCategoryIds = pinnedCategoryIds)+ }.combine(preferencesRepository.showRecentChannelsCategory) { ctx, showRecent ->+ if (!showRecent) ctx.copy(categories = ctx.categories.filter { it.id != VirtualCategoryIds.RECENT }) else ctx+ }.combine(preferencesRepository.showAllChannelsCategory) { ctx, showAll ->+ if (!showAll) ctx.copy(categories = ctx.categories.filter { it.id != ChannelRepository.ALL_CHANNELS_ID }) else ctx}.collect { selectionContext ->val categories = selectionContext.categoriesval defaultId = selectionContext.defaultCategoryId@@ -523,9 +533,10 @@ class HomeViewModel @Inject constructor(categoriesJob = viewModelScope.launch {try {_uiState.update { it.copy(isCategoriesLoading = true, errorMessage = null, pinnedCategoryIds = emptySet()) }+ val providerIds = currentCombinedProviderIds()combine(combinedM3uRepository.getCombinedCategories(profileId),- getCustomCategories()+ getCustomCategories(providerIds, ContentType.LIVE)) { combinedCategories, customCats ->combinedCategoriesById = combinedCategories.associateBy { it.category.id }val recentCategory = Category(@@ -554,6 +565,10 @@ class HomeViewModel @Inject constructor(lastVisitedCategoryId = null,pinnedCategoryIds = emptySet())+ }.combine(preferencesRepository.showRecentChannelsCategory) { ctx, showRecent ->+ if (!showRecent) ctx.copy(categories = ctx.categories.filter { it.id != VirtualCategoryIds.RECENT }) else ctx+ }.combine(preferencesRepository.showAllChannelsCategory) { ctx, showAll ->+ if (!showAll) ctx.copy(categories = ctx.categories.filter { it.id != ChannelRepository.ALL_CHANNELS_ID }) else ctx}.collect { selectionContext ->val categories = selectionContext.categories_uiState.update {@@ -638,6 +653,8 @@ class HomeViewModel @Inject constructor(private fun loadChannelsForCategory(category: Category) {loadChannelsJob?.cancel()+ _channelBrowseLimit.value = CHANNEL_PAGE_SIZE+ _channelSearchLimit.value = CHANNEL_SEARCH_PAGE_SIZEloadChannelsJob = viewModelScope.launch {try {_uiState.update {@@ -662,7 +679,24 @@ class HomeViewModel @Inject constructor(if (allFlows.isEmpty()) flowOf(emptyList())else combine(allFlows) { arrays -> arrays.toList().flatMap { it } }} else if (category.isVirtual) {- flowOf(emptyList())+ val providerIds = currentLiveProviderIds()+ when (category.id) {+ VirtualCategoryIds.RECENT -> {+ observeRecentLiveIds(providerIds, limit = 24)+ .flatMapLatest(::loadChannelsByOrderedIds)+ }+ VirtualCategoryIds.FAVORITES -> {+ observeLiveFavorites(providerIds)+ .map { favorites -> favorites.sortedBy { it.position }.map { it.contentId } }+ .flatMapLatest(::loadChannelsByOrderedIds)+ }+ else -> {+ val groupId = -category.id+ favoriteRepository.getFavoritesByGroup(groupId)+ .map { favorites -> favorites.sortedBy { it.position }.map { it.contentId } }+ .flatMapLatest(::loadChannelsByOrderedIds)+ }+ }} else {val combinedCategory = combinedCategoriesById[category.id]if (combinedCategory == null) {@@ -687,7 +721,7 @@ class HomeViewModel @Inject constructor(.map { it.toRecentLiveContentIds() }.flatMapLatest { ids -> loadChannelsByOrderedIds(ids) }} else if (category.id == VirtualCategoryIds.FAVORITES) {- favoriteRepository.getFavorites(ContentType.LIVE)+ favoriteRepository.getFavorites(providerId, ContentType.LIVE).map { favorites -> favorites.sortedBy { it.position }.map { it.contentId } }.flatMapLatest { ids -> loadChannelsByOrderedIds(ids) }} else {@@ -712,11 +746,15 @@ class HomeViewModel @Inject constructor(queryFlow.flatMapLatest { query ->val trimmedQuery = query.trim()if (trimmedQuery.isBlank()) {- channelRepository.getChannelsByCategory(providerId, category.id)+ _channelBrowseLimit.flatMapLatest { limit ->+ channelRepository.getChannelsByCategoryPage(providerId, category.id, limit)+ }} else if (trimmedQuery.length < MIN_CHANNEL_SEARCH_QUERY_LENGTH) {flowOf(emptyList())} else {- channelRepository.searchChannelsByCategory(providerId, category.id, trimmedQuery)+ _channelSearchLimit.flatMapLatest { limit ->+ channelRepository.searchChannelsByCategoryPaged(providerId, category.id, trimmedQuery, limit)+ }}}}@@ -734,14 +772,22 @@ class HomeViewModel @Inject constructor(channel.copy(number = index + 1)}ChannelNumberingMode.PROVIDER -> visibleChannels+ ChannelNumberingMode.HIDDEN -> visibleChannels.map { it.copy(number = 0) }}}.collect { displayedChannels ->+ val currentQuery = _uiState.value.channelSearchQuery.trim()+ val currentLimit = if (currentQuery.length < MIN_CHANNEL_SEARCH_QUERY_LENGTH) {+ _channelBrowseLimit.value+ } else {+ _channelSearchLimit.value+ }_localChannels.value = displayedChannels_uiState.update {it.copy(hasChannels = displayedChannels.isNotEmpty(),isLoading = displayedChannels.isEmpty() && it.isSyncing,- errorMessage = null+ errorMessage = null,+ hasMoreChannels = displayedChannels.size >= currentLimit)}}@@ -845,9 +891,19 @@ class HomeViewModel @Inject constructor(fun updateChannelSearchQuery(query: String) {if (_uiState.value.isChannelReorderMode) return+ _channelSearchLimit.value = CHANNEL_SEARCH_PAGE_SIZE_uiState.update { it.copy(channelSearchQuery = query) }}+ fun loadMoreChannels() {+ val currentQuery = _uiState.value.channelSearchQuery.trim()+ if (currentQuery.length < MIN_CHANNEL_SEARCH_QUERY_LENGTH) {+ _channelBrowseLimit.update { it + CHANNEL_PAGE_SIZE }+ } else {+ _channelSearchLimit.update { it + CHANNEL_SEARCH_PAGE_SIZE }+ }+ }+fun previewChannel(channel: Channel) {if (_uiState.value.liveTvChannelMode != LiveTvChannelMode.PRO) returnif (_uiState.value.previewChannelId == channel.id && _uiState.value.previewPlayerEngine != null) return@@ -1047,6 +1103,7 @@ class HomeViewModel @Inject constructor(fun addFavorite(channel: Channel) {viewModelScope.launch {favoriteRepository.addFavorite(+ providerId = channel.providerId,contentId = channel.id,contentType = ContentType.LIVE,groupId = null@@ -1059,6 +1116,7 @@ class HomeViewModel @Inject constructor(fun removeFavorite(channel: Channel) {viewModelScope.launch {favoriteRepository.removeFavorite(+ providerId = channel.providerId,contentId = channel.id,contentType = ContentType.LIVE,groupId = null@@ -1084,7 +1142,12 @@ class HomeViewModel @Inject constructor(}viewModelScope.launch {- favoriteRepository.createGroup(trimmed, contentType = ContentType.LIVE)+ val providerId = resolveLiveWriteProviderId()+ if (providerId == null) {+ _uiState.update { it.copy(userMessage = appContext.getString(R.string.home_error_load_failed)) }+ return@launch+ }+ favoriteRepository.createGroup(providerId, trimmed, contentType = ContentType.LIVE)_uiState.update { it.copy(userMessage = appContext.getString(R.string.home_group_created, trimmed)) }}}@@ -1201,6 +1264,7 @@ class HomeViewModel @Inject constructor(viewModelScope.launch {val groupId = -category.idfavoriteRepository.addFavorite(+ providerId = channel.providerId,contentId = channel.id,contentType = ContentType.LIVE,groupId = groupId@@ -1215,6 +1279,7 @@ class HomeViewModel @Inject constructor(viewModelScope.launch {val groupId = -category.idfavoriteRepository.removeFavorite(+ providerId = channel.providerId,contentId = channel.id,contentType = ContentType.LIVE,groupId = groupId@@ -1242,7 +1307,7 @@ class HomeViewModel @Inject constructor(val groupId = if (currentCategory.id == VirtualCategoryIds.FAVORITES) null else -currentCategory.idval favoritesFlow = if (groupId == null) {- favoriteRepository.getFavorites(ContentType.LIVE)+ observeLiveFavorites(currentLiveProviderIds())} else {favoriteRepository.getFavoritesByGroup(groupId)}@@ -1252,8 +1317,6 @@ class HomeViewModel @Inject constructor(val reorderedFavorites = currentList.mapNotNull { ch ->favoriteMap[ch.id]- }.mapIndexed { i, fav ->- fav.copy(position = i)}favoriteRepository.reorderFavorites(reorderedFavorites)@@ -1277,7 +1340,7 @@ class HomeViewModel @Inject constructor(fun onShowDialog(channel: Channel) {_uiState.update { it.copy(showDialog = true, selectedChannelForDialog = channel) }viewModelScope.launch {- val memberships = favoriteRepository.getGroupMemberships(channel.id, ContentType.LIVE)+ val memberships = favoriteRepository.getGroupMemberships(channel.providerId, channel.id, ContentType.LIVE)_uiState.update { it.copy(dialogGroupMemberships = memberships) }}}@@ -1363,6 +1426,28 @@ class HomeViewModel @Inject constructor(}}+ fun setShowAllChannelsCategory(enabled: Boolean) {+ viewModelScope.launch { preferencesRepository.setShowAllChannelsCategory(enabled) }+ }++ fun setShowRecentChannelsCategory(enabled: Boolean) {+ viewModelScope.launch { preferencesRepository.setShowRecentChannelsCategory(enabled) }+ }++ fun clearRecentChannels() {+ val providerId = _uiState.value.provider?.id ?: return+ viewModelScope.launch {+ playbackHistoryRepository.clearLiveHistoryForProvider(providerId)+ }+ }++ fun removeChannelFromRecent(channel: Channel) {+ val providerId = _uiState.value.provider?.id ?: return+ viewModelScope.launch {+ playbackHistoryRepository.removeFromHistory(channel.id, ContentType.LIVE, providerId)+ }+ }+fun toggleCategoryPinned(category: Category) {if (_uiState.value.isCombinedLiveSource) returnif (category.isVirtual || category.id == ChannelRepository.ALL_CHANNELS_ID) return@@ -1450,7 +1535,7 @@ class HomeViewModel @Inject constructor(val groupId = if (category.id == VirtualCategoryIds.FAVORITES) null else -category.idval favoritesFlow = if (groupId == null) {- favoriteRepository.getFavorites(ContentType.LIVE)+ observeLiveFavorites(currentLiveProviderIds())} else {favoriteRepository.getFavoritesByGroup(groupId)}@@ -1462,8 +1547,6 @@ class HomeViewModel @Inject constructor(// Map the sorted Channel list back to Favorite entities with new positionsval reorderedFavorites = currentList.mapNotNull { ch ->favoriteMap[ch.id]- }.mapIndexed { i, fav ->- fav.copy(position = i)}// Persist the new order in DB@@ -1490,7 +1573,7 @@ class HomeViewModel @Inject constructor(val groupId = if (category.id == VirtualCategoryIds.FAVORITES) null else -category.idval favorites = if (groupId == null) {- favoriteRepository.getFavorites(ContentType.LIVE).first()+ observeLiveFavorites(currentLiveProviderIds()).first()} else {favoriteRepository.getFavoritesByGroup(groupId).first()}@@ -1510,6 +1593,55 @@ class HomeViewModel @Inject constructor(.map { it.contentId }.toList()+ private fun currentCombinedProviderIds(): List<Long> =+ _uiState.value.currentCombinedProfileMembers+ .filter { it.enabled }+ .map { it.providerId }++ private fun currentLiveProviderIds(state: HomeUiState = _uiState.value): List<Long> = when (val source = state.activeLiveSource) {+ is ActiveLiveSource.ProviderSource -> listOf(source.providerId)+ is ActiveLiveSource.CombinedM3uSource -> state.currentCombinedProfileMembers+ .filter { it.enabled }+ .map { it.providerId }+ null -> state.provider?.id?.let(::listOf).orEmpty()+ }++ private fun observeCurrentLiveFavorites(): Flow<List<Favorite>> =+ _uiState.map(::currentLiveProviderIds)+ .distinctUntilChanged()+ .flatMapLatest(::observeLiveFavorites)++ private fun observeLiveFavorites(providerIds: List<Long>): Flow<List<Favorite>> = when (providerIds.size) {+ 0 -> flowOf(emptyList())+ 1 -> favoriteRepository.getFavorites(providerIds.first(), ContentType.LIVE)+ else -> favoriteRepository.getFavorites(providerIds, ContentType.LIVE)+ }++ private fun observeRecentLiveIds(providerIds: List<Long>, limit: Int): Flow<List<Long>> = when (providerIds.size) {+ 0 -> flowOf(emptyList())+ 1 -> playbackHistoryRepository.getRecentlyWatchedByProvider(providerIds.first(), limit)+ .map { history -> history.toRecentLiveContentIds().take(limit) }+ else -> combine(providerIds.map { providerId ->+ playbackHistoryRepository.getRecentlyWatchedByProvider(providerId, limit)+ }) { histories ->+ histories.toList()+ .flatMap { it }+ .asSequence()+ .filter { it.contentType == ContentType.LIVE }+ .sortedByDescending { it.lastWatchedAt }+ .distinctBy { it.providerId to it.contentId }+ .map { it.contentId }+ .take(limit)+ .toList()+ }+ }++ private fun resolveLiveWriteProviderId(preferredProviderId: Long? = null): Long? =+ preferredProviderId+ ?: _uiState.value.provider?.id+ ?: _uiState.value.selectedCombinedSourceProviderId+ ?: currentLiveProviderIds().singleOrNull()+override fun onCleared() {epgJob?.cancel()loadChannelsJob?.cancel()@@ -1536,6 +1668,7 @@ data class HomeUiState(val selectedCategory: Category? = null,val filteredChannels: List<Channel> = emptyList(),val hasChannels: Boolean = false,+ val hasMoreChannels: Boolean = false,val isLoading: Boolean = true,val isCategoriesLoading: Boolean = true,val isSyncing: Boolean = false,diff --git a/app/src/main/java/com/streamvault/app/ui/screens/movies/MoviesScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/movies/MoviesScreen.ktindex 9aa97500..1463ad18 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/movies/MoviesScreen.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/movies/MoviesScreen.kt@@ -87,6 +87,7 @@ import com.streamvault.app.ui.model.VodViewModeimport com.streamvault.app.ui.screens.vod.HandleVodUserMessageimport com.streamvault.app.ui.screens.vod.ProtectedVodPinDialogimport com.streamvault.app.ui.screens.vod.VodBrowseDefaults+import com.streamvault.app.ui.screens.vod.vodActiveFilterSortDetailimport kotlinx.coroutines.delay@OptIn(ExperimentalFoundationApi::class)@@ -736,6 +737,8 @@ private fun MoviesVodContent(if (!uiState.isReorderMode) {item(span = { GridItemSpan(maxLineSpan) }) {+ val browseOptionsDetail = vodActiveFilterSortDetail(selectedFilterType, selectedSortBy)+ val hasActiveFilterSort = selectedFilterType != LibraryFilterType.ALL || selectedSortBy != LibrarySortBy.LIBRARYVodActionChipRow(actions = buildList {add(@@ -765,6 +768,7 @@ private fun MoviesVodContent(VodActionChip(key = "browse_options",label = stringResource(R.string.library_action_filters_sort),+ detail = browseOptionsDetail,onClick = { showBrowseOptions = true }))@@ -778,6 +782,7 @@ private fun MoviesVodContent()}},+ selectedKey = if (hasActiveFilterSort) "browse_options" else null,modifier = Modifier.padding(top = 2.dp, bottom = 2.dp))}@@ -1061,6 +1066,7 @@ private fun MoviesVodClassicContent(modifier = Modifier.fillMaxSize(),verticalArrangement = Arrangement.spacedBy(14.dp)) {+ val hasActiveFilterSortClassic = selectedFilterType != LibraryFilterType.ALL || selectedSortBy != LibrarySortBy.LIBRARYVodClassicContentHeader(title = when {selectedKey == "all" -> allLabel@@ -1086,10 +1092,12 @@ private fun MoviesVodClassicContent(VodActionChip(key = "browse_options",label = stringResource(R.string.library_action_filters_sort),+ detail = vodActiveFilterSortDetail(selectedFilterType, selectedSortBy),onClick = { showBrowseOptions = true }))- }+ },+ selectedActionKey = if (hasActiveFilterSortClassic) "browse_options" else null)if (showSearchBar) {diff --git a/app/src/main/java/com/streamvault/app/ui/screens/movies/MoviesViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/movies/MoviesViewModel.ktindex c20cc445..e355599f 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/movies/MoviesViewModel.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/movies/MoviesViewModel.kt@@ -133,8 +133,8 @@ class MoviesViewModel @Inject constructor(.flatMapLatest { provider ->activeProviderId = provider.idcombine(- favoriteRepository.getAllFavorites(ContentType.MOVIE),- getCustomCategories(ContentType.MOVIE),+ favoriteRepository.getAllFavorites(provider.id, ContentType.MOVIE),+ getCustomCategories(provider.id, ContentType.MOVIE),movieRepository.getCategories(provider.id),movieRepository.getCategoryItemCounts(provider.id),movieRepository.getLibraryCount(provider.id),@@ -272,8 +272,8 @@ class MoviesViewModel @Inject constructor(.filterNotNull().flatMapLatest { provider ->combine(- favoriteRepository.getAllFavorites(ContentType.MOVIE),- getCustomCategories(ContentType.MOVIE),+ favoriteRepository.getAllFavorites(provider.id, ContentType.MOVIE),+ getCustomCategories(provider.id, ContentType.MOVIE),movieRepository.getCategories(provider.id),preferencesRepository.getHiddenCategoryIds(provider.id, ContentType.MOVIE),preferencesRepository.getCategorySortMode(provider.id, ContentType.MOVIE)@@ -366,7 +366,7 @@ class MoviesViewModel @Inject constructor(.filterNotNull().flatMapLatest { provider ->combine(- favoriteRepository.getAllFavorites(ContentType.MOVIE),+ favoriteRepository.getAllFavorites(provider.id, ContentType.MOVIE),playbackHistoryRepository.getRecentlyWatchedByProvider(provider.id, limit = 24),movieRepository.getTopRatedPreview(provider.id, VodBrowseDefaults.PREVIEW_ROW_LIMIT),movieRepository.getFreshPreview(provider.id, VodBrowseDefaults.PREVIEW_ROW_LIMIT)@@ -456,9 +456,12 @@ class MoviesViewModel @Inject constructor(}viewModelScope.launch {- getCustomCategories(ContentType.MOVIE).collect { categories ->- _uiState.update { it.copy(categories = categories) }- }+ providerRepository.getActiveProvider()+ .filterNotNull()+ .flatMapLatest { provider -> getCustomCategories(provider.id, ContentType.MOVIE) }+ .collect { categories ->+ _uiState.update { it.copy(categories = categories) }+ }}}@@ -568,6 +571,7 @@ class MoviesViewModel @Inject constructor(viewModelScope.launch {val dialogSelection = loadVodDialogSelection(item = movie,+ providerId = movie.providerId,itemId = movie.id,contentType = ContentType.MOVIE,favoriteRepository = favoriteRepository,@@ -591,14 +595,14 @@ class MoviesViewModel @Inject constructor(fun addFavorite(movie: Movie) {viewModelScope.launch {- setVodFavorite(movie.id, ContentType.MOVIE, true, favoriteRepository)+ setVodFavorite(movie.providerId, movie.id, ContentType.MOVIE, true, favoriteRepository)_uiState.update { it.copy(selectedMovieForDialog = movie.copy(isFavorite = true)) }}}fun removeFavorite(movie: Movie) {viewModelScope.launch {- setVodFavorite(movie.id, ContentType.MOVIE, false, favoriteRepository)+ setVodFavorite(movie.providerId, movie.id, ContentType.MOVIE, false, favoriteRepository)_uiState.update { it.copy(selectedMovieForDialog = movie.copy(isFavorite = false)) }}}@@ -606,6 +610,7 @@ class MoviesViewModel @Inject constructor(fun addToGroup(movie: Movie, group: Category) {viewModelScope.launch {val memberships = updateVodGroupMembership(+ providerId = movie.providerId,itemId = movie.id,groupId = group.id,contentType = ContentType.MOVIE,@@ -619,6 +624,7 @@ class MoviesViewModel @Inject constructor(fun removeFromGroup(movie: Movie, group: Category) {viewModelScope.launch {val memberships = updateVodGroupMembership(+ providerId = movie.providerId,itemId = movie.id,groupId = group.id,contentType = ContentType.MOVIE,@@ -638,11 +644,13 @@ class MoviesViewModel @Inject constructor(}viewModelScope.launch {- when (val result = createVodGroup(normalizedName, ContentType.MOVIE, favoriteRepository)) {+ val providerId = activeProviderId ?: return@launch+ when (val result = createVodGroup(providerId, normalizedName, ContentType.MOVIE, favoriteRepository)) {is Result.Success -> {val selectedMovie = _uiState.value.selectedMovieForDialogval memberships = if (selectedMovie != null) {updateVodGroupMembership(+ providerId = selectedMovie.providerId,itemId = selectedMovie.id,groupId = result.data.id,contentType = ContentType.MOVIE,@@ -843,6 +851,7 @@ class MoviesViewModel @Inject constructor(viewModelScope.launch {try {saveVodReorder(+ providerId = activeProviderId ?: return@launch,category = category,currentItems = currentList,contentType = ContentType.MOVIE,@@ -856,6 +865,7 @@ class MoviesViewModel @Inject constructor(private suspend fun loadReorderMovies(category: Category): List<Movie> {return loadVodReorderItems(+ providerId = activeProviderId ?: return emptyList(),category = category,contentType = ContentType.MOVIE,favoriteRepository = favoriteRepository,diff --git a/app/src/main/java/com/streamvault/app/ui/screens/multiview/MultiViewViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/multiview/MultiViewViewModel.ktindex 3fe330e5..ba4c9ee1 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/multiview/MultiViewViewModel.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/multiview/MultiViewViewModel.kt@@ -504,7 +504,7 @@ class MultiViewViewModel @Inject constructor(}currentProviderId = providerIdcombine(- favoriteRepository.getFavorites(com.streamvault.domain.model.ContentType.LIVE),+ favoriteRepository.getFavorites(providerId, com.streamvault.domain.model.ContentType.LIVE),playbackHistoryRepository.getRecentlyWatchedByProvider(providerId, limit = 12)) { favorites, history ->val favoriteIds = favorites.map { it.contentId }diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerScreen.ktindex 75d78a19..cfaeb82d 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerScreen.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerScreen.kt@@ -111,6 +111,8 @@ fun PlayerScreen(categoryId: Long? = null,providerId: Long? = null,isVirtual: Boolean = false,+ combinedProfileId: Long? = null,+ combinedSourceFilterProviderId: Long? = null,contentType: String = "LIVE",archiveStartMs: Long? = null,archiveEndMs: Long? = null,@@ -164,6 +166,7 @@ fun PlayerScreen(val canOpenEpisodePicker = contentType == "SERIES_EPISODE" &¤tSeriesSeasons?.any { it.episodes.isNotEmpty() } == true+ val isCatchUpPlayback by viewModel.isCatchUpPlayback.collectAsStateWithLifecycle()val showChannelListOverlay by viewModel.showChannelListOverlay.collectAsStateWithLifecycle()val showCategoryListOverlay by viewModel.showCategoryListOverlay.collectAsStateWithLifecycle()val availableCategories by viewModel.availableCategories.collectAsStateWithLifecycle()@@ -203,11 +206,9 @@ fun PlayerScreen(val focusRequester = remember { FocusRequester() }val channelListFocusRequester = remember { FocusRequester() }val categoryListFocusRequester = remember { FocusRequester() }- val epgFocusRequester = remember { FocusRequester() }val playButtonFocusRequester = remember { FocusRequester() }val quickActionsFocusRequester = remember { FocusRequester() }- val channelInfoFocusRequester = remember { FocusRequester() } // NEW- var lastFocusedEpgProgramToken by rememberSaveable { mutableStateOf<Long?>(null) }+ val channelInfoFocusRequester = remember { FocusRequester() }val layoutDirection = LocalLayoutDirection.currentval isRtl = layoutDirection == LayoutDirection.Rtlval currentPictureInPictureMode by rememberUpdatedState(isInPictureInPictureMode)@@ -222,12 +223,15 @@ fun PlayerScreen(focusRequester.requestFocus()}- LaunchedEffect(mainActivity, streamUrl, playbackState, isPlaying, videoFormat.width, videoFormat.height) {+ LaunchedEffect(mainActivity, streamUrl, playbackState, isPlaying, videoFormat.width, videoFormat.height, videoFormat.pixelWidthHeightRatio) {mainActivity?.updatePlayerPictureInPictureState(- enabled = streamUrl.isNotBlank() && playbackState != PlaybackState.ERROR,+ enabled = streamUrl.isNotBlank()+ && playbackState != PlaybackState.ERROR+ && (isPlaying || playbackState == PlaybackState.READY || playbackState == PlaybackState.BUFFERING),isPlaying = isPlaying,videoWidth = videoFormat.width,- videoHeight = videoFormat.height+ videoHeight = videoFormat.height,+ pixelWidthHeightRatio = videoFormat.pixelWidthHeightRatio)}@@ -286,7 +290,6 @@ fun PlayerScreen(when {showCategoryListOverlay -> categoryListFocusRequester.requestFocusSafely(tag = "PlayerScreen", target = "Category list overlay")showChannelListOverlay -> channelListFocusRequester.requestFocusSafely(tag = "PlayerScreen", target = "Channel list overlay")- showEpgOverlay -> epgFocusRequester.requestFocusSafely(tag = "PlayerScreen", target = "EPG overlay")showChannelInfoOverlay -> channelInfoFocusRequester.requestFocusSafely(tag = "PlayerScreen", target = "Channel info overlay")}}@@ -350,7 +353,7 @@ fun PlayerScreen()}- LaunchedEffect(streamUrl, epgChannelId, title, artworkUrl, internalChannelId, categoryId, providerId, isVirtual, contentType, archiveStartMs, archiveEndMs, archiveTitle, seriesId, seasonNumber, episodeNumber) {+ LaunchedEffect(streamUrl, epgChannelId, internalChannelId, categoryId, providerId, isVirtual, combinedProfileId, combinedSourceFilterProviderId, contentType, archiveStartMs, archiveEndMs, archiveTitle, seriesId, seasonNumber, episodeNumber) {viewModel.prepare(streamUrl = streamUrl,epgChannelId = epgChannelId,@@ -358,6 +361,8 @@ fun PlayerScreen(categoryId = categoryId ?: -1,providerId = providerId ?: -1,isVirtual = isVirtual,+ combinedProfileId = combinedProfileId,+ combinedSourceFilterProviderId = combinedSourceFilterProviderId,contentType = contentType,title = title,artworkUrl = artworkUrl,@@ -457,11 +462,23 @@ fun PlayerScreen(when {anyOverlayVisible -> return@detectTapGesturesshowControls -> viewModel.toggleControls()- contentType == "LIVE" -> viewModel.openChannelInfoOverlay()+ contentType == "LIVE" && !isCatchUpPlayback -> viewModel.openChannelInfoOverlay()else -> viewModel.toggleControls()}}}+ // --- Key handler ownership ---+ // onPreviewKeyEvent (top-down): DPAD_UP, DPAD_DOWN, CHANNEL_UP, CHANNEL_DOWN+ // for live-TV channel zapping when no overlay/dialog is open. Fires BEFORE+ // child composables see the event, so overlays that consume DPAD_UP/DOWN+ // internally get priority (early returns above).+ // onKeyEvent (bottom-up): all other keys — DPAD_CENTER, BACK, MEDIA_*,+ // numeric digits, MUTE, GUIDE, INFO, MENU, and the CHANNEL_UP/DOWN+ // fallback for non-LIVE content types or when channelInfoSubPanelOpen.+ // CHANNEL_UP/DOWN appear in BOTH handlers. onPreviewKeyEvent intercepts them+ // first for live content with no sub-panel; onKeyEvent handles the remaining+ // cases (non-LIVE content, sub-panel open). This is intentional — the preview+ // handler returns false for those remaining cases, letting onKeyEvent run..onPreviewKeyEvent { event ->if (event.nativeKeyEvent.action != KeyEvent.ACTION_DOWN) {return@onPreviewKeyEvent false@@ -541,10 +558,10 @@ fun PlayerScreen(if (showChannelListOverlay || showEpgOverlay || showChannelInfoOverlay || showDiagnostics) {viewModel.onLiveOverlayInteraction()}- if (contentType == "LIVE" && viewModel.hasPendingNumericChannelInput()) {+ if (contentType == "LIVE" && !isCatchUpPlayback && viewModel.hasPendingNumericChannelInput()) {viewModel.commitNumericChannelInput()true- } else if (contentType == "LIVE") {+ } else if (contentType == "LIVE" && !isCatchUpPlayback) {if (showChannelInfoOverlay) viewModel.closeChannelInfoOverlay()else viewModel.openChannelInfoOverlay()true@@ -559,12 +576,12 @@ fun PlayerScreen(if (showChannelListOverlay || showCategoryListOverlay || showEpgOverlay || showChannelInfoOverlay || showDiagnostics) {viewModel.onLiveOverlayInteraction()}- if (showControls && contentType != "LIVE") return@onKeyEvent false- if (showChannelListOverlay && contentType == "LIVE") {+ if (showControls && (contentType != "LIVE" || isCatchUpPlayback)) return@onKeyEvent false+ if (showChannelListOverlay && contentType == "LIVE" && !isCatchUpPlayback) {// Second left press while channel list is open → open category listviewModel.openCategoryListOverlay()true- } else if (contentType == "LIVE" && !showChannelListOverlay && !showCategoryListOverlay && !showEpgOverlay && !showChannelInfoOverlay) {+ } else if (contentType == "LIVE" && !isCatchUpPlayback && !showChannelListOverlay && !showCategoryListOverlay && !showEpgOverlay && !showChannelInfoOverlay) {if (isRtl) viewModel.openEpgOverlay() else viewModel.openChannelListOverlay()true} else if (!showChannelListOverlay && !showCategoryListOverlay && !showEpgOverlay && !showChannelInfoOverlay) {@@ -578,8 +595,8 @@ fun PlayerScreen(if (showChannelListOverlay || showEpgOverlay || showChannelInfoOverlay || showDiagnostics) {viewModel.onLiveOverlayInteraction()}- if (showControls && contentType != "LIVE") return@onKeyEvent false- if (contentType == "LIVE" && !showChannelListOverlay && !showEpgOverlay && !showChannelInfoOverlay) {+ if (showControls && (contentType != "LIVE" || isCatchUpPlayback)) return@onKeyEvent false+ if (contentType == "LIVE" && !isCatchUpPlayback && !showChannelListOverlay && !showEpgOverlay && !showChannelInfoOverlay) {if (isRtl) viewModel.openChannelListOverlay() else viewModel.openEpgOverlay()true} else if (!showChannelListOverlay && !showEpgOverlay && !showChannelInfoOverlay) {@@ -595,9 +612,9 @@ fun PlayerScreen(}if (showChannelInfoOverlay && channelInfoSubPanelOpen) return@onKeyEvent falseif (showChannelListOverlay || showCategoryListOverlay || showEpgOverlay || showChannelInfoOverlay) return@onKeyEvent false- if (showControls && contentType != "LIVE") return@onKeyEvent false+ if (showControls && (contentType != "LIVE" || isCatchUpPlayback)) return@onKeyEvent false- if (contentType == "LIVE") {+ if (contentType == "LIVE" && !isCatchUpPlayback) {viewModel.playNext()} else if (canOpenEpisodePicker) {showEpisodePicker = true@@ -612,9 +629,9 @@ fun PlayerScreen(}if (showChannelInfoOverlay && channelInfoSubPanelOpen) return@onKeyEvent falseif (showChannelListOverlay || showCategoryListOverlay || showEpgOverlay) return@onKeyEvent false- if (showControls && contentType != "LIVE") return@onKeyEvent false+ if (showControls && (contentType != "LIVE" || isCatchUpPlayback)) return@onKeyEvent false- if (contentType == "LIVE") {+ if (contentType == "LIVE" && !isCatchUpPlayback) {viewModel.playPrevious()} else {viewModel.toggleControls()@@ -835,6 +852,7 @@ fun PlayerScreen(visible = showControls,title = playbackTitle.ifBlank { title },contentType = contentType,+ isCatchUpPlayback = isCatchUpPlayback,isPlaying = isPlaying,currentProgram = currentProgram,currentChannelName = currentChannel?.name,@@ -1021,18 +1039,11 @@ fun PlayerScreen(currentProgram = currentProgram,nextProgram = nextProgram,upcomingPrograms = upcomingPrograms,- overlayFocusRequester = epgFocusRequester,- preferredFocusedProgramToken = lastFocusedEpgProgramToken,- onFocusedProgramChange = { token -> lastFocusedEpgProgramToken = token },onDismiss = { viewModel.closeOverlays() },onOpenArchiveBrowser = {showProgramHistory = trueviewModel.closeOverlays()},- onPlayCatchUp = { program ->- viewModel.playCatchUp(program)- viewModel.closeOverlays()- },onOverlayInteracted = viewModel::onLiveOverlayInteraction)}@@ -1127,6 +1138,7 @@ private fun PlayerControlsOverlayHost(visible: Boolean,title: String,contentType: String,+ isCatchUpPlayback: Boolean = false,isPlaying: Boolean,currentProgram: Program?,currentChannelName: String?,@@ -1181,6 +1193,7 @@ private fun PlayerControlsOverlayHost(visible = visible,title = title,contentType = contentType,+ isCatchUpPlayback = isCatchUpPlayback,isPlaying = isPlaying,currentProgram = currentProgram,currentChannelName = currentChannelName,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 73930168..a2a4297d 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@@ -16,10 +16,13 @@ import com.streamvault.data.security.CredentialDecryptionExceptionimport com.streamvault.domain.manager.RecordingManagerimport com.streamvault.domain.model.Categoryimport com.streamvault.domain.model.ChannelNumberingMode+import com.streamvault.domain.model.CombinedCategory+import com.streamvault.domain.model.CombinedM3uProfileMemberimport com.streamvault.domain.model.Programimport com.streamvault.domain.model.ContentTypeimport com.streamvault.domain.model.DecoderModeimport com.streamvault.domain.model.Episode+import com.streamvault.domain.model.Favoriteimport com.streamvault.domain.model.PlaybackHistoryimport com.streamvault.domain.model.RecordingItemimport com.streamvault.domain.model.RecordingRecurrence@@ -36,6 +39,7 @@ import com.streamvault.domain.usecase.MarkAsWatchedimport com.streamvault.domain.usecase.ScheduleRecordingimport com.streamvault.domain.usecase.ScheduleRecordingCommandimport com.streamvault.domain.repository.ChannelRepository+import com.streamvault.domain.repository.CombinedM3uRepositoryimport com.streamvault.domain.repository.EpgRepositoryimport com.streamvault.domain.repository.MovieRepositoryimport com.streamvault.domain.repository.PlaybackHistoryRepository@@ -52,6 +56,7 @@ import dagger.hilt.android.lifecycle.HiltViewModelimport kotlinx.coroutines.ExperimentalCoroutinesApiimport kotlinx.coroutines.Jobimport kotlinx.coroutines.delay+import kotlinx.coroutines.ensureActiveimport kotlinx.coroutines.flow.*import kotlinx.coroutines.launchimport kotlinx.coroutines.withContext@@ -73,6 +78,7 @@ class PlayerViewModel @Inject constructor(private val favoriteRepository: com.streamvault.domain.repository.FavoriteRepository,internal val playbackHistoryRepository: PlaybackHistoryRepository,private val providerRepository: com.streamvault.domain.repository.ProviderRepository,+ private val combinedM3uRepository: CombinedM3uRepository,private val preferencesRepository: com.streamvault.data.preferences.PreferencesRepository,private val getCustomCategories: GetCustomCategories,private val markAsWatched: MarkAsWatched,@@ -90,11 +96,19 @@ class PlayerViewModel @Inject constructor(private const val MAX_PROGRAM_HISTORY_ITEMS = 18private const val MAX_UPCOMING_PROGRAM_ITEMS = 24private const val PLAYER_EPG_REFRESH_INTERVAL_MS = 30_000L+ private const val MIN_WATCHED_FOR_AUTO_PLAY_MS = 5_000L+ private const val TOKEN_RENEWAL_LEAD_MS = 60_000L+ private const val TOKEN_RENEWAL_CHECK_INTERVAL_MS = 10_000L+ private const val LOW_BANDWIDTH_THRESHOLD_BPS = 500_000L+ private const val LOW_BANDWIDTH_DURATION_SECONDS = 30}internal val showControlsFlow = MutableStateFlow(false)val showControls: StateFlow<Boolean> = showControlsFlow.asStateFlow()+ private val _isCatchUpPlayback = MutableStateFlow(false)+ val isCatchUpPlayback: StateFlow<Boolean> = _isCatchUpPlayback.asStateFlow()+internal val showZapOverlayFlow = MutableStateFlow(false)val showZapOverlay: StateFlow<Boolean> = showZapOverlayFlow.asStateFlow()@@ -193,6 +207,8 @@ class PlayerViewModel @Inject constructor(private val failedStreamsThisSession = mutableMapOf<String, Int>()private var hasRetriedWithSoftwareDecoder = falseprivate var hasRetriedXtreamAuthRefresh = false+ private val probePassedProviderIds = mutableSetOf<Long>()+ private val notifiedRecordingFailureIds = mutableSetOf<String>()internal var lastRecordedLivePlaybackKey: Pair<Long, Long>? = nullprivate var currentStreamClassLabel: String = "Primary"private var prepareRequestVersion: Long = 0L@@ -200,6 +216,10 @@ class PlayerViewModel @Inject constructor(private var currentResolvedPlaybackUrl: String = ""internal var pendingCatchUpUrls: List<String> = emptyList()internal var channelNumberingMode: ChannelNumberingMode = ChannelNumberingMode.GROUP+ set(value) {+ field = value+ rebuildChannelNumberIndex()+ }private var activeEpgRequestKey: EpgRequestKey? = nullinternal var playerControlsTimeoutMs: Long = 5_000Linternal var liveOverlayTimeoutMs: Long = 4_000L@@ -209,11 +229,36 @@ class PlayerViewModel @Inject constructor(private var timeshiftConfig: TimeshiftConfig = TimeshiftConfig()// Zapping state+ //+ // Invariant: `currentChannelIndex` is always -1 (no channel loaded) or a valid index+ // into `channelList`. Code that updates either field must maintain this relationship.+ // `channelList` is replaced asynchronously by the playlist flow collector; after+ // replacement, `currentChannelIndex` is recomputed in the same collector block,+ // so the invariant holds at rest. `changeChannel()` verifies the invariant at entry.+ /**+ * Ordered list of channels in the current category, set by the playlist [combine]+ * collector. Linked to [currentChannelIndex] — see invariant comment above.+ */internal var channelList: List<com.streamvault.domain.model.Channel> = emptyList()+ set(value) {+ field = value+ rebuildChannelNumberIndex()+ }+ internal var channelNumberIndex: Map<Int, com.streamvault.domain.model.Channel> = emptyMap()+ private set++ private fun rebuildChannelNumberIndex() {+ channelNumberIndex = channelList.withIndex().associate { (index, channel) ->+ resolveChannelNumber(channel, index) to channel+ }+ }+internal var currentChannelIndex = -1internal var previousChannelIndex = -1internal var currentCategoryId: Long = -1internal var currentProviderId: Long = -1L+ internal var currentCombinedProfileId: Long? = null+ internal var currentCombinedSourceFilterProviderId: Long? = nullinternal var currentContentId: Long = -1Linternal var currentContentType: ContentType = ContentType.LIVEinternal var currentTitle: String = ""@@ -221,6 +266,8 @@ class PlayerViewModel @Inject constructor(private var currentSeasonNumber: Int? = nullprivate var currentEpisodeNumber: Int? = nullinternal var isVirtualCategory: Boolean = false+ private var currentCombinedProfileMembers: List<CombinedM3uProfileMember> = emptyList()+ private var combinedCategoriesById: Map<Long, CombinedCategory> = emptyMap()private var lastObservedPlaybackState: PlaybackState = PlaybackState.IDLEprivate var epgJob: Job? = null@@ -229,10 +276,14 @@ class PlayerViewModel @Inject constructor(private var lastVisitedCategoryJob: Job? = nullinternal var controlsHideJob: Job? = nullprivate var seekPreviewJob: Job? = null+ private var thumbnailPreloadJob: Job? = null+ private var lowBandwidthMonitorJob: Job? = nullprivate var progressTrackingJob: Job? = null+ private var tokenRenewalJob: Job? = nullinternal var zapOverlayJob: Job? = nullprivate var aspectRatioJob: Job? = nullinternal var zapBufferWatchdogJob: Job? = null+ internal var zapAutoRevertEnabled: Boolean = trueprivate var isAppInForeground: Boolean = trueprivate var shouldResumeAfterForeground: Boolean = falseprivate var seekPreviewRequestVersion: Long = 0L@@ -340,6 +391,8 @@ class PlayerViewModel @Inject constructor()}}+ } else {+ startThumbnailPreload()}}}@@ -350,8 +403,17 @@ class PlayerViewModel @Inject constructor(showRetryNotice(status)}}+ viewModelScope.launch {+ playerEngine.audioFocusDenied.collect {+ showPlayerNotice(+ message = "Waiting for audio \u2014 unmute device and press Play",+ durationMs = 8_000L+ )+ }+ }viewModelScope.launch {recordingManager.observeRecordingItems().collect { items ->+ handleRecordingStateChanges(previousItems = _recordingItems.value, newItems = items)_recordingItems.value = itemsrefreshCurrentChannelRecording(items)}@@ -389,6 +451,9 @@ class PlayerViewModel @Inject constructor(diagnosticsTimeoutMs = timeouts.diagnosticsMs}}+ viewModelScope.launch {+ preferencesRepository.zapAutoRevert.collect { zapAutoRevertEnabled = it }+ }viewModelScope.launch {preferencesRepository.playerMediaSessionEnabled.collect(playerEngine::setMediaSessionEnabled)}@@ -421,6 +486,32 @@ class PlayerViewModel @Inject constructor(}}}+ viewModelScope.launch {+ var consecutiveLowBandwidthSeconds = 0+ var noticeShown = false+ playerEngine.playerStats.collect { stats ->+ if (!playerEngine.isPlaying.value || currentContentType != ContentType.LIVE) {+ consecutiveLowBandwidthSeconds = 0+ noticeShown = false+ return@collect+ }+ val bps = stats.bandwidthEstimate+ if (bps in 1 until LOW_BANDWIDTH_THRESHOLD_BPS) {+ consecutiveLowBandwidthSeconds+++ } else {+ consecutiveLowBandwidthSeconds = 0+ noticeShown = false+ }+ if (consecutiveLowBandwidthSeconds >= LOW_BANDWIDTH_DURATION_SECONDS && !noticeShown) {+ noticeShown = true+ showPlayerNotice(+ message = "Network speed is low \u2014 stream quality reduced",+ recoveryType = PlayerRecoveryType.NETWORK,+ durationMs = 10_000L+ )+ }+ }+ }}private fun handlePlaybackError(error: PlayerError) {@@ -452,6 +543,17 @@ class PlayerViewModel @Inject constructor(val recoveryType = classifyPlaybackError(error)val channel = currentChannelFlow.value?.sanitizedForPlayer()+ if (recoveryType == PlayerRecoveryType.DRM) {+ if (!isActivePlaybackSession(requestVersion, playbackUrl)) return@launch+ showPlayerNotice(+ message = "This channel requires DRM support that is not available. " ++ "Your subscription may not include this content.",+ recoveryType = PlayerRecoveryType.DRM,+ actions = buildRecoveryActions(PlayerRecoveryType.DRM)+ )+ return@launch+ }+if (currentContentType != ContentType.LIVE || channel == null) {if (!isActivePlaybackSession(requestVersion, playbackUrl)) return@launchshowPlayerNotice(@@ -549,6 +651,34 @@ class PlayerViewModel @Inject constructor(}}+ private fun handleRecordingStateChanges(+ previousItems: List<RecordingItem>,+ newItems: List<RecordingItem>+ ) {+ val previousStatuses = previousItems.associateBy(RecordingItem::id)+ val failedNow = newItems.firstOrNull { item ->+ previousStatuses[item.id]?.status == RecordingStatus.RECORDING &&+ item.status == RecordingStatus.FAILED &&+ notifiedRecordingFailureIds.add(item.id)+ }++ notifiedRecordingFailureIds.retainAll(+ newItems.asSequence()+ .filter { it.status == RecordingStatus.FAILED }+ .map { it.id }+ .toSet()+ )++ failedNow?.let { item ->+ val title = item.programTitle?.takeIf { it.isNotBlank() } ?: item.channelName+ val detail = item.failureReason?.takeIf { it.isNotBlank() } ?: "The provider stopped serving the recording stream."+ showPlayerNotice(+ message = "Recording failed for $title. $detail",+ durationMs = maxOf(playerNoticeTimeoutMs, 8_000L)+ )+ }+ }+private data class PlaybackProbeFailure(val message: String,val recoveryType: PlayerRecoveryType@@ -665,8 +795,26 @@ class PlayerViewModel @Inject constructor(}}+ private fun startThumbnailPreload() {+ thumbnailPreloadJob?.cancel()+ val url = currentResolvedPlaybackUrl.ifBlank { currentStreamUrl }+ if (url.isBlank() || !seekThumbnailProvider.supportsFrameExtraction(url)) return+ val durationMs = playerEngine.duration.value+ if (durationMs <= 0L) return+ thumbnailPreloadJob = viewModelScope.launch(Dispatchers.Default) {+ val bucketMs = 10_000L+ var pos = 0L+ while (pos <= durationMs) {+ ensureActive()+ seekThumbnailProvider.loadFrame(url, pos)+ pos += bucketMs+ }+ }+ }+internal fun beginPlaybackSession(): Long {recoveryJob?.cancel()+ thumbnailPreloadJob?.cancel()hasRetriedXtreamAuthRefresh = falsereturn ++prepareRequestVersion}@@ -791,8 +939,12 @@ class PlayerViewModel @Inject constructor(viewModelScope.launch {persistPlaybackCompletion()if (currentContentType == ContentType.SERIES_EPISODE) {- _nextEpisode.value?.let { episode ->- playEpisode(episode, showResumePrompt = false)+ val position = playerEngine.currentPosition.value+ val duration = playerEngine.duration.value+ if (position > MIN_WATCHED_FOR_AUTO_PLAY_MS || duration > 0L) {+ _nextEpisode.value?.let { episode ->+ playEpisode(episode, showResumePrompt = false)+ }}}}@@ -872,6 +1024,7 @@ class PlayerViewModel @Inject constructor()return false}+ currentProviderId.takeIf { it > 0L }?.let { probePassedProviderIds.add(it) }playerEngine.setMuted(preferencesRepository.playerMuted.first())playerEngine.setPlaybackSpeed(if (currentContentType == ContentType.LIVE) {@@ -893,6 +1046,7 @@ class PlayerViewModel @Inject constructor(if (!isActivePlaybackSession(requestVersion)) return falsecurrentResolvedPlaybackUrl = streamInfo.urlplayerEngine.prepare(streamInfo)+ startTokenRenewalMonitoring(streamInfo.expirationTime)return true}@@ -930,6 +1084,7 @@ class PlayerViewModel @Inject constructor(private suspend fun shouldProbePlaybackUrl(url: String): Boolean {if (!url.startsWith("http://") && !url.startsWith("https://")) return falseval providerId = currentProviderId.takeIf { it > 0L } ?: return false+ if (providerId in probePassedProviderIds) return falseval provider = providerRepository.getProvider(providerId) ?: return falsereturn provider.type == com.streamvault.domain.model.ProviderType.XTREAM_CODES &&(xtreamStreamUrlResolver.isInternalStreamUrl(currentStreamUrl) || xtreamStreamUrlResolver.isInternalStreamUrl(url))@@ -942,6 +1097,8 @@ class PlayerViewModel @Inject constructor(categoryId: Long = -1,providerId: Long = -1,isVirtual: Boolean = false,+ combinedProfileId: Long? = null,+ combinedSourceFilterProviderId: Long? = null,contentType: String = "CHANNEL",title: String = "",artworkUrl: String? = null,@@ -961,8 +1118,15 @@ class PlayerViewModel @Inject constructor(val requestVersion = beginPlaybackSession()val previousProviderId = currentProviderIdval previousCategoryId = currentCategoryId+ val previousCombinedProfileId = currentCombinedProfileId+ val previousCombinedSourceFilterProviderId = currentCombinedSourceFilterProviderIdval shouldReloadPlaylist = categoryId != -1L &&- (categoryId != previousCategoryId || providerId != previousProviderId)+ (+ categoryId != previousCategoryId ||+ providerId != previousProviderId ||+ combinedProfileId != previousCombinedProfileId ||+ combinedSourceFilterProviderId != previousCombinedSourceFilterProviderId+ )clearSeekPreview()currentResolvedPlaybackUrl = ""currentStreamUrl = streamUrl@@ -972,10 +1136,24 @@ class PlayerViewModel @Inject constructor(currentArtworkUrl = artworkUrlcurrentContentType = try { ContentType.valueOf(contentType) } catch (e: Exception) { ContentType.LIVE }currentProviderId = providerId+ currentCombinedProfileId = combinedProfileId?.takeIf { it > 0L }+ currentCombinedSourceFilterProviderId = combinedSourceFilterProviderId?.takeIf { it > 0L }currentSeriesId = seriesId?.takeIf { it > 0L }currentSeasonNumber = seasonNumbercurrentEpisodeNumber = episodeNumbercurrentStreamClassLabel = if (hasArchiveRequest) "Catch-up" else "Primary"+ if (currentContentType == ContentType.LIVE && currentCombinedProfileId != null) {+ val activeCombinedProfileId = currentCombinedProfileId+ viewModelScope.launch {+ val members = activeCombinedProfileId?.let { combinedM3uRepository.getProfile(it)?.members }.orEmpty()+ if (currentCombinedProfileId == activeCombinedProfileId) {+ currentCombinedProfileMembers = members+ }+ }+ } else {+ currentCombinedProfileMembers = emptyList()+ combinedCategoriesById = emptyMap()+ }if (!hasArchiveRequest) {pendingCatchUpUrls = emptyList()}@@ -1207,6 +1385,33 @@ class PlayerViewModel @Inject constructor(}}+ private fun startTokenRenewalMonitoring(expirationTime: Long?) {+ tokenRenewalJob?.cancel()+ tokenRenewalJob = null+ val expiry = expirationTime?.takeIf { it > 0L } ?: return+ val requestVersion = prepareRequestVersion+ tokenRenewalJob = viewModelScope.launch {+ while (true) {+ delay(TOKEN_RENEWAL_CHECK_INTERVAL_MS)+ if (!playerEngine.isPlaying.value) continue+ val remaining = expiry - System.currentTimeMillis()+ if (remaining > TOKEN_RENEWAL_LEAD_MS) continue+ if (!isActivePlaybackSession(requestVersion)) return@launch+ val refreshed = resolvePlaybackStreamInfo(+ logicalUrl = currentStreamUrl,+ internalContentId = currentContentId,+ providerId = currentProviderId,+ contentType = currentContentType+ ) ?: return@launch+ if (!isActivePlaybackSession(requestVersion)) return@launch+ currentResolvedPlaybackUrl = refreshed.url+ playerEngine.renewStreamUrl(refreshed)+ startTokenRenewalMonitoring(refreshed.expirationTime)+ return@launch+ }+ }+ }+fun onAppBackgrounded() {if (!isAppInForeground) returnisAppInForeground = false@@ -1255,6 +1460,13 @@ class PlayerViewModel @Inject constructor(return}+ val requestKey = EpgRequestKey(+ providerId = providerId,+ internalChannelId = internalChannelId,+ epgChannelId = epgChannelId,+ streamId = streamId+ )+epgJob = viewModelScope.launch {while (true) {val now = System.currentTimeMillis()@@ -1269,10 +1481,13 @@ class PlayerViewModel @Inject constructor(endTime = end)+ if (activeEpgRequestKey != requestKey) return@launch+if (programs.isNotEmpty()) {applyProgramTimeline(programs, now)} else {applyRemoteProgramFallback(providerId, epgChannelId, streamId, now)+ if (activeEpgRequestKey != requestKey) return@launch}delay(PLAYER_EPG_REFRESH_INTERVAL_MS)@@ -1335,7 +1550,9 @@ class PlayerViewModel @Inject constructor(internal fun loadPlaylist(categoryId: Long, providerId: Long, isVirtual: Boolean, initialChannelId: Long) {playlistJob?.cancel()playlistJob = viewModelScope.launch {- val flows = if (isVirtual) {+ val flows = currentCombinedProfileId?.let { profileId ->+ observeCombinedLivePlaylist(profileId, categoryId)+ } ?: if (isVirtual) {if (categoryId == VirtualCategoryIds.RECENT) {playbackHistoryRepository.getRecentlyWatchedByProvider(providerId, limit = 24).map { history ->@@ -1355,7 +1572,7 @@ class PlayerViewModel @Inject constructor(}} else if (categoryId == VirtualCategoryIds.FAVORITES) {// Global Favorites — preserve user-defined position order- favoriteRepository.getFavorites(com.streamvault.domain.model.ContentType.LIVE)+ favoriteRepository.getFavorites(currentProviderId, com.streamvault.domain.model.ContentType.LIVE).map { favorites -> favorites.sortedBy { it.position }.map { it.contentId } }.flatMapLatest { ids ->if (ids.isEmpty()) flowOf(emptyList())@@ -1386,15 +1603,17 @@ class PlayerViewModel @Inject constructor(channel.copy(number = index + 1)}ChannelNumberingMode.PROVIDER -> channels+ ChannelNumberingMode.HIDDEN -> channels.map { it.copy(number = 0) }}numberingMode to displayedChannels.sanitizedChannelsForPlayer()}.collect { (numberingMode, displayedChannels) ->channelNumberingMode = numberingModechannelList = displayedChannelscurrentChannelFlowList.value = displayedChannels- // Recalculate index based on initial ID or URL- if (initialChannelId != -1L) {- currentChannelIndex = channelList.indexOfFirst { it.id == initialChannelId }+ // Recalculate index based on current content ID (keeps overlay correct after zap/auto-revert)+ val targetId = if (currentContentId != -1L) currentContentId else initialChannelId+ if (targetId != -1L) {+ currentChannelIndex = channelList.indexOfFirst { it.id == targetId }}if (currentChannelIndex == -1) {currentChannelIndex = channelList.indexOfFirst { it.streamUrl == currentStreamUrl }@@ -1405,6 +1624,13 @@ class PlayerViewModel @Inject constructor(refreshCurrentChannelRecording()val ch = channelList[currentChannelIndex]displayChannelNumberFlow.value = resolveChannelNumber(ch, currentChannelIndex)+ } else if (displayedChannels.isNotEmpty() && currentContentId != -1L) {+ // Channel was removed from the provider playlist+ showPlayerNotice(+ message = "Channel not found in current playlist",+ recoveryType = PlayerRecoveryType.SOURCE,+ actions = listOf(PlayerNoticeAction.OPEN_GUIDE)+ )}}}@@ -1413,31 +1639,151 @@ class PlayerViewModel @Inject constructor(// Store current URL to find index laterinternal var currentStreamUrl: String = ""+ private fun observeCombinedLivePlaylist(profileId: Long, categoryId: Long): Flow<List<com.streamvault.domain.model.Channel>> = when {+ categoryId == ChannelRepository.ALL_CHANNELS_ID -> {+ combinedM3uRepository.getCombinedCategories(profileId).flatMapLatest { combinedCategories ->+ combinedCategoriesById = combinedCategories.associateBy { it.category.id }+ val flows = combinedCategories.map { combinedM3uRepository.getCombinedChannels(profileId, it) }+ if (flows.isEmpty()) {+ flowOf(emptyList())+ } else {+ combine(flows) { arrays ->+ arrays.toList().flatMap { it }+ }.map(::applyCombinedSourceProviderFilter)+ }+ }+ }++ categoryId == VirtualCategoryIds.RECENT -> {+ combinedProviderIdsFlow(profileId)+ .flatMapLatest { providerIds -> observeRecentLiveIds(effectiveCombinedProviderIds(providerIds), 24) }+ .flatMapLatest { ids -> loadLiveChannelsByOrderedIds(ids, currentCombinedSourceFilterProviderId) }+ }++ categoryId == VirtualCategoryIds.FAVORITES -> {+ combinedProviderIdsFlow(profileId)+ .flatMapLatest { providerIds -> observeLiveFavorites(effectiveCombinedProviderIds(providerIds)) }+ .map { favorites -> favorites.sortedBy { it.position }.map { it.contentId } }+ .flatMapLatest { ids -> loadLiveChannelsByOrderedIds(ids, currentCombinedSourceFilterProviderId) }+ }++ categoryId < 0L -> {+ favoriteRepository.getFavoritesByGroup(-categoryId)+ .map { favorites ->+ favorites+ .sortedBy { it.position }+ .let { groupFavorites ->+ currentCombinedSourceFilterProviderId?.let { selectedProviderId ->+ groupFavorites.filter { it.providerId == selectedProviderId }+ } ?: groupFavorites+ }+ .map { it.contentId }+ }+ .flatMapLatest { ids -> loadLiveChannelsByOrderedIds(ids, currentCombinedSourceFilterProviderId) }+ }++ else -> {+ combinedM3uRepository.getCombinedCategories(profileId).flatMapLatest { combinedCategories ->+ combinedCategoriesById = combinedCategories.associateBy { it.category.id }+ val combinedCategory = combinedCategoriesById[categoryId]+ if (combinedCategory == null) {+ flowOf(emptyList())+ } else {+ combinedM3uRepository.getCombinedChannels(profileId, combinedCategory)+ .map(::applyCombinedSourceProviderFilter)+ }+ }+ }+ }++ private fun applyCombinedSourceProviderFilter(channels: List<com.streamvault.domain.model.Channel>): List<com.streamvault.domain.model.Channel> {+ val selectedProviderId = currentCombinedSourceFilterProviderId ?: return channels+ return channels.filter { it.providerId == selectedProviderId }+ }++ private fun loadLiveChannelsByOrderedIds(ids: List<Long>, providerId: Long? = null): Flow<List<com.streamvault.domain.model.Channel>> =+ if (ids.isEmpty()) {+ flowOf(emptyList())+ } else {+ channelRepository.getChannelsByIds(ids).map { unsorted ->+ val filtered = providerId?.let { requiredProviderId ->+ unsorted.filter { it.providerId == requiredProviderId }+ } ?: unsorted+ val channelsById = filtered.associateBy { it.id }+ ids.mapNotNull { channelsById[it] }+ }+ }++ private fun combinedProviderIdsFlow(profileId: Long): Flow<List<Long>> = flow {+ emit(combinedM3uRepository.getProfile(profileId)?.members.orEmpty())+ }.map { members ->+ currentCombinedProfileMembers = members+ members.filter { it.enabled }.map { it.providerId }+ }++ private fun effectiveCombinedProviderIds(providerIds: List<Long>): List<Long> =+ currentCombinedSourceFilterProviderId?.let { selectedProviderId ->+ providerIds.filter { it == selectedProviderId }+ } ?: providerIds++ private fun observeLiveFavorites(providerIds: List<Long>): Flow<List<Favorite>> = when (providerIds.size) {+ 0 -> flowOf(emptyList())+ 1 -> favoriteRepository.getFavorites(providerIds.first(), ContentType.LIVE)+ else -> favoriteRepository.getFavorites(providerIds, ContentType.LIVE)+ }++ private fun observeRecentLiveIds(providerIds: List<Long>, limit: Int): Flow<List<Long>> = when (providerIds.size) {+ 0 -> flowOf(emptyList())+ 1 -> playbackHistoryRepository.getRecentlyWatchedByProvider(providerIds.first(), limit)+ .map { history ->+ history.asSequence()+ .filter { it.contentType == ContentType.LIVE }+ .sortedByDescending { it.lastWatchedAt }+ .distinctBy { it.contentId }+ .map { it.contentId }+ .take(limit)+ .toList()+ }+ else -> combine(providerIds.map { providerId ->+ playbackHistoryRepository.getRecentlyWatchedByProvider(providerId, limit)+ }) { histories ->+ histories.toList()+ .flatMap { it }+ .asSequence()+ .filter { it.contentType == ContentType.LIVE }+ .sortedByDescending { it.lastWatchedAt }+ .distinctBy { it.providerId to it.contentId }+ .map { it.contentId }+ .take(limit)+ .toList()+ }+ }+private fun observeRecentChannels() {recentChannelsJob?.cancel()- if (currentContentType != ContentType.LIVE || currentProviderId <= 0) {+ if (currentContentType != ContentType.LIVE || (currentProviderId <= 0 && currentCombinedProfileId == null)) {recentChannelsFlow.value = emptyList()return}recentChannelsJob = viewModelScope.launch {+ val recentFlow = currentCombinedProfileId?.let { profileId ->+ combinedProviderIdsFlow(profileId)+ .flatMapLatest { providerIds -> observeRecentLiveIds(effectiveCombinedProviderIds(providerIds), 12) }+ .flatMapLatest { ids -> loadLiveChannelsByOrderedIds(ids, currentCombinedSourceFilterProviderId) }+ } ?: playbackHistoryRepository.getRecentlyWatchedByProvider(currentProviderId, limit = 12)+ .map { history ->+ history.asSequence()+ .filter { it.contentType == ContentType.LIVE }+ .sortedByDescending { it.lastWatchedAt }+ .distinctBy { it.contentId }+ .map { it.contentId }+ .toList()+ }+ .flatMapLatest { ids -> loadLiveChannelsByOrderedIds(ids) }+combine(- playbackHistoryRepository.getRecentlyWatchedByProvider(currentProviderId, limit = 12)- .map { history ->- history.asSequence()- .filter { it.contentType == ContentType.LIVE }- .sortedByDescending { it.lastWatchedAt }- .distinctBy { it.contentId }- .map { it.contentId }- .toList()- }- .flatMapLatest { ids ->- if (ids.isEmpty()) flowOf(emptyList())- else channelRepository.getChannelsByIds(ids).map { channels ->- val channelMap = channels.associateBy { it.id }- ids.mapNotNull { channelMap[it] }- }- },+ recentFlow,preferencesRepository.liveChannelNumberingMode) { channels, numberingMode ->numberingMode to channels@@ -1459,15 +1805,49 @@ class PlayerViewModel @Inject constructor(private fun observeLastVisitedCategory() {lastVisitedCategoryJob?.cancel()- if (currentContentType != ContentType.LIVE || currentProviderId <= 0) {+ if (currentContentType != ContentType.LIVE || (currentProviderId <= 0 && currentCombinedProfileId == null)) {_lastVisitedCategory.value = nullreturn}lastVisitedCategoryJob = viewModelScope.launch {- combine(+ val categoriesFlow = currentCombinedProfileId?.let { profileId ->+ combinedProviderIdsFlow(profileId).flatMapLatest { providerIds ->+ combine(+ combinedM3uRepository.getCombinedCategories(profileId),+ getCustomCategories(providerIds, ContentType.LIVE)+ ) { combinedCategories, customCategories ->+ combinedCategoriesById = combinedCategories.associateBy { it.category.id }+ buildList {+ val favoritesCategory = customCategories.find { it.id == VirtualCategoryIds.FAVORITES }+ if (favoritesCategory != null) {+ add(favoritesCategory)+ }+ add(+ Category(+ id = VirtualCategoryIds.RECENT,+ name = "Recent",+ type = ContentType.LIVE,+ isVirtual = true,+ count = 0+ )+ )+ addAll(customCategories.filter { it.id != VirtualCategoryIds.FAVORITES })+ add(+ Category(+ id = ChannelRepository.ALL_CHANNELS_ID,+ name = "All Channels",+ type = ContentType.LIVE,+ count = combinedCategories.sumOf { it.category.count }+ )+ )+ addAll(combinedCategories.map { it.category })+ } to null+ }+ }+ } ?: combine(channelRepository.getCategories(currentProviderId),- getCustomCategories(ContentType.LIVE),+ getCustomCategories(currentProviderId, ContentType.LIVE),preferencesRepository.getLastLiveCategoryId(currentProviderId)) { providerCategories, customCategories, lastVisitedCategoryId ->val allCategories = customCategories + providerCategories@@ -1476,8 +1856,10 @@ class PlayerViewModel @Inject constructor(} else {allCategories.firstOrNull { it.id == lastVisitedCategoryId }}- Pair(allCategories, lastVisited)- }.collect { (allCategories, lastVisited) ->+ allCategories to lastVisited+ }++ categoriesFlow.collect { (allCategories, lastVisited) ->availableCategoriesFlow.value = allCategories_lastVisitedCategory.value = lastVisited}@@ -1486,7 +1868,7 @@ class PlayerViewModel @Inject constructor(fun openLastVisitedCategory() {val category = _lastVisitedCategory.value ?: return- if (currentContentType != ContentType.LIVE || currentProviderId <= 0) return+ if (currentContentType != ContentType.LIVE) returncurrentCategoryId = category.idactiveCategoryIdFlow.value = category.id@@ -1585,6 +1967,7 @@ class PlayerViewModel @Inject constructor(internal fun updateStreamClass(label: String) {currentStreamClassLabel = label+ _isCatchUpPlayback.value = (label == "Catch-up")_playerDiagnostics.update { it.copy(streamClassLabel = label) }}@@ -1637,6 +2020,7 @@ class PlayerViewModel @Inject constructor(if (!isActivePlaybackSession(requestVersion, playbackUrl)) return falsehasRetriedXtreamAuthRefresh = true+ probePassedProviderIds.remove(currentProviderId)setLastFailureReason(error.message)appendRecoveryAction("Refreshed Xtream playback URL after auth failure")showPlayerNotice(@@ -1768,10 +2152,18 @@ class PlayerViewModel @Inject constructor(}internal fun scheduleZapBufferWatchdog(targetIndex: Int) {+ if (!zapAutoRevertEnabled) returnzapBufferWatchdogJob?.cancel()val requestVersion = prepareRequestVersionzapBufferWatchdogJob = viewModelScope.launch {- delay(9000)+ // Check every second for 15 s; back off immediately once the stream starts playing+ repeat(15) {+ delay(1000)+ if (!isActivePlaybackSession(requestVersion)) return@launch+ if (currentChannelIndex != targetIndex) return@launch+ val state = playerEngine.playbackState.value+ if (state == PlaybackState.READY || state == PlaybackState.ENDED) return@launch+ }if (!isActivePlaybackSession(requestVersion)) return@launchval stillOnTarget = currentChannelIndex == targetIndexval state = playerEngine.playbackState.value@@ -1798,7 +2190,11 @@ class PlayerViewModel @Inject constructor(val fallbackIndex = previousChannelIndexif (fallbackIndex in channelList.indices && fallbackIndex != currentChannelIndex) {android.util.Log.w("PlayerVM", "Falling back to previous channel: $reason")- changeChannel(fallbackIndex)+ // Save before changeChannel overwrites previousChannelIndex with the bad channel's index+ val savedPrevious = previousChannelIndex+ changeChannel(fallbackIndex, isAutoFallback = true)+ // Restore so that zapToLastChannel and a spurious second watchdog don't point at the bad channel+ previousChannelIndex = savedPreviousreturn true}return false@@ -1917,7 +2313,6 @@ class PlayerViewModel @Inject constructor()if (!preparePlayer(catchupStream, requestVersion)) returnplayerEngine.play()- showControlsFlow.value = true}fun playCatchUp(program: Program) {@@ -2088,10 +2483,21 @@ class PlayerViewModel @Inject constructor(return}val currentId = if (currentChannelIndex != -1 && channelList.isNotEmpty()) channelList[currentChannelIndex].id else -1L- prepare(streamUrl, epgChannelId, currentId, currentCategoryId, currentProviderId, isVirtualCategory, currentContentType.name, currentTitle)+ prepare(+ streamUrl = streamUrl,+ epgChannelId = epgChannelId,+ internalChannelId = currentId,+ categoryId = currentCategoryId,+ providerId = currentProviderId,+ isVirtual = isVirtualCategory,+ combinedProfileId = currentCombinedProfileId,+ combinedSourceFilterProviderId = currentCombinedSourceFilterProviderId,+ contentType = currentContentType.name,+ title = currentTitle+ )}- private suspend fun resolvePlaybackStreamInfo(+ internal suspend fun resolvePlaybackStreamInfo(logicalUrl: String,internalContentId: Long,providerId: Long,@@ -2151,10 +2557,12 @@ class PlayerViewModel @Inject constructor(fallbackContentType = contentType,fallbackContainerExtension = fallbackContainerExtension)?.let { resolved ->+ val ext = resolved.containerExtension ?: fallbackContainerExtensionreturn com.streamvault.domain.model.StreamInfo(url = resolved.url,title = currentTitle,- containerExtension = fallbackContainerExtension,+ streamType = com.streamvault.domain.model.StreamType.fromContainerExtension(ext),+ containerExtension = ext,expirationTime = resolved.expirationTime)}@@ -2169,6 +2577,7 @@ class PlayerViewModel @Inject constructor(com.streamvault.domain.model.StreamInfo(url = it,title = currentTitle,+ streamType = com.streamvault.domain.model.StreamType.fromContainerExtension(fallbackContainerExtension),containerExtension = fallbackContainerExtension)}@@ -2210,6 +2619,7 @@ class PlayerViewModel @Inject constructor(zapOverlayJob?.cancel()zapBufferWatchdogJob?.cancel()progressTrackingJob?.cancel()+ tokenRenewalJob?.cancel()aspectRatioJob?.cancel()recentChannelsJob?.cancel()lastVisitedCategoryJob?.cancel()diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModelActions.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModelActions.ktindex 688603bc..7d61e898 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModelActions.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModelActions.kt@@ -146,7 +146,10 @@ internal suspend fun PlayerViewModel.buildCastRequest(): CastMediaRequest? {return when (currentContentType) {ContentType.LIVE -> {val channel = currentChannel.value ?: return null- val streamInfo = channelRepository.getStreamInfo(channel).getOrNull() ?: return null+ // Use preferStableUrl = true for Cast: the credential-based portal URL+ // does not expire, unlike the tokenized direct-source CDN URL.+ val streamInfo = channelRepository.getStreamInfo(channel, preferStableUrl = true)+ .getOrNull() ?: return nullstreamInfo.toCastRequest(title = mediaTitle.value ?: channel.name,subtitle = currentProgram.value?.title,diff --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 29e26cbf..9233a303 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@@ -4,14 +4,23 @@ import androidx.lifecycle.viewModelScopeimport com.streamvault.domain.model.ChannelNumberingModeimport com.streamvault.domain.model.ContentTypeimport com.streamvault.domain.model.PlaybackHistory-import com.streamvault.domain.model.StreamInfo-import com.streamvault.domain.model.StreamTypeimport kotlinx.coroutines.delayimport kotlinx.coroutines.flow.updateimport kotlinx.coroutines.flow.filterimport kotlinx.coroutines.flow.takeimport kotlinx.coroutines.launch+internal const val MAX_NUMERIC_CHANNEL_INPUT_DIGITS = 6++internal fun appendNumericChannelDigit(currentBuffer: String, digit: Int): String {+ val nextDigit = digit.toString()+ return if (currentBuffer.length >= MAX_NUMERIC_CHANNEL_INPUT_DIGITS) {+ nextDigit+ } else {+ currentBuffer + nextDigit+ }+}+fun PlayerViewModel.playNext() {clearNumericChannelInput()if (channelList.isEmpty()) return@@ -59,16 +68,7 @@ fun PlayerViewModel.inputNumericChannelDigit(digit: Int) {if (currentContentType != ContentType.LIVE || channelList.isEmpty()) returnif (digit !in 0..9) return- if (numericInputBuffer.isBlank() && digit == 0 && hasLastChannel()) {- zapToLastChannel()- return- }-- numericInputBuffer = if (numericInputBuffer.length >= 4) {- digit.toString()- } else {- numericInputBuffer + digit.toString()- }+ numericInputBuffer = appendNumericChannelDigit(numericInputBuffer, digit)val exactMatch = resolveChannelByNumber(numericInputBuffer.toIntOrNull())val previewMatch = exactMatch ?: resolveChannelByPrefix(numericInputBuffer)@@ -85,6 +85,13 @@ fun PlayerViewModel.commitNumericChannelInput() {numericInputCommitJob?.cancel()if (numericInputBuffer.isBlank()) return+ // "0" committed alone after timeout → zap to last channel (standard IPTV remote behaviour)+ if (numericInputBuffer == "0" && hasLastChannel()) {+ clearNumericChannelInput()+ zapToLastChannel()+ return+ }+val targetChannel = resolveChannelByNumber(numericInputBuffer.toIntOrNull())if (targetChannel != null) {val targetIndex = channelList.indexOfFirst { it.id == targetChannel.id }@@ -115,7 +122,10 @@ fun PlayerViewModel.clearNumericChannelInput() {numericChannelInputFlow.value = null}-internal fun PlayerViewModel.changeChannel(index: Int) {+internal fun PlayerViewModel.changeChannel(index: Int, isAutoFallback: Boolean = false) {+ check(index in channelList.indices) {+ "changeChannel index=$index out of channelList bounds (size=${channelList.size})"+ }clearNumericChannelInput()if (currentChannelIndex != -1 && currentChannelIndex != index) {previousChannelIndex = currentChannelIndex@@ -137,14 +147,9 @@ internal fun PlayerViewModel.changeChannel(index: Int) {playerEngine.setScrubbingMode(true)viewModelScope.launch {- val resolvedUrl = resolvePlaybackUrl(channel.streamUrl, channel.id, channel.providerId, ContentType.LIVE)+ val streamInfo = resolvePlaybackStreamInfo(channel.streamUrl, channel.id, channel.providerId, ContentType.LIVE)?: return@launchif (!isActivePlaybackSession(requestVersion, channel.streamUrl)) return@launch- val streamInfo = StreamInfo(- url = resolvedUrl,- title = currentTitle,- streamType = StreamType.UNKNOWN- )if (!preparePlayer(streamInfo, requestVersion)) return@launchplayerEngine.play()@@ -175,7 +180,7 @@ internal fun PlayerViewModel.changeChannel(index: Int) {triedAlternativeStreams.add(channel.streamUrl)if (currentContentType == ContentType.LIVE) {recordLivePlayback(channel)- scheduleZapBufferWatchdog(index)+ if (!isAutoFallback) scheduleZapBufferWatchdog(index)}}@@ -184,19 +189,13 @@ internal fun PlayerViewModel.preloadAdjacentChannel(currentIndex: Int) {val nextIndex = (currentIndex + 1) % channelList.sizeval nextChannel = channelList[nextIndex]viewModelScope.launch {- val nextUrl = resolvePlaybackUrl(+ val streamInfo = resolvePlaybackStreamInfo(nextChannel.streamUrl,nextChannel.id,nextChannel.providerId,ContentType.LIVE) ?: return@launch- playerEngine.preload(- StreamInfo(- url = nextUrl,- title = nextChannel.name,- streamType = StreamType.UNKNOWN- )- )+ playerEngine.preload(streamInfo)}}@@ -234,18 +233,12 @@ internal fun PlayerViewModel.scheduleNumericChannelCommit() {internal fun PlayerViewModel.resolveChannelByNumber(number: Int?): com.streamvault.domain.model.Channel? {if (number == null) return null- return channelList- .withIndex()- .firstOrNull { (index, channel) -> resolveChannelNumber(channel, index) == number }- ?.value+ return channelNumberIndex[number]}internal fun PlayerViewModel.resolveChannelByPrefix(prefix: String): com.streamvault.domain.model.Channel? {- return channelList- .withIndex()- .firstOrNull { (index, channel) ->- resolveChannelNumber(channel, index).toString().startsWith(prefix)- }+ return channelNumberIndex.entries+ .firstOrNull { (key, _) -> key.toString().startsWith(prefix) }?.value}@@ -255,4 +248,5 @@ internal fun PlayerViewModel.resolveChannelNumber(): Int = when (channelNumberingMode) {ChannelNumberingMode.GROUP -> if (index >= 0) index + 1 else channel.number.takeIf { it > 0 } ?: 0ChannelNumberingMode.PROVIDER -> channel.number.takeIf { it > 0 } ?: if (index >= 0) index + 1 else 0+ ChannelNumberingMode.HIDDEN -> 0}diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerControlsChrome.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerControlsChrome.ktindex effb50e2..2d25faa9 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerControlsChrome.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerControlsChrome.kt@@ -95,6 +95,7 @@ fun PlayerControlsOverlay(visible: Boolean,title: String,contentType: String,+ isCatchUpPlayback: Boolean = false,isPlaying: Boolean,currentProgram: Program?,currentChannelName: String?,@@ -179,6 +180,7 @@ fun PlayerControlsOverlay(PlayerBottomBar(title = title,contentType = contentType,+ isCatchUpPlayback = isCatchUpPlayback,isPlaying = isPlaying,currentProgram = currentProgram,currentChannelName = currentChannelName,@@ -257,13 +259,15 @@ fun PlayerZapOverlay(.widthIn(min = 320.dp, max = 460.dp)) {Row(verticalAlignment = Alignment.CenterVertically) {- Text(- text = displayChannelNumber.toString(),- style = MaterialTheme.typography.headlineMedium,- color = Primary,- fontWeight = FontWeight.Bold- )- Spacer(modifier = Modifier.width(16.dp))+ if (displayChannelNumber > 0) {+ Text(+ text = displayChannelNumber.toString(),+ style = MaterialTheme.typography.headlineMedium,+ color = Primary,+ fontWeight = FontWeight.Bold+ )+ Spacer(modifier = Modifier.width(16.dp))+ }Column {Text(text = channelName.orEmpty(),@@ -499,6 +503,7 @@ private fun PlayerTopBar(private fun PlayerBottomBar(title: String,contentType: String,+ isCatchUpPlayback: Boolean = false,isPlaying: Boolean,currentProgram: Program?,currentChannelName: String?,@@ -546,7 +551,7 @@ private fun PlayerBottomBar(onSeekPreviewPositionChanged: (Long?) -> Unit,modifier: Modifier = Modifier) {- val isVod = contentType != "LIVE"+ val isVod = contentType != "LIVE" || isCatchUpPlaybackBox(modifier = modifier.fillMaxWidth()@@ -624,7 +629,9 @@ private fun PlayerBottomBar(onTogglePlayPause = onTogglePlayPause,onSeekBackward = onSeekBackward,onSeekForward = onSeekForward,- onSeekToLiveEdge = onSeekToLiveEdge+ onSeekToLiveEdge = onSeekToLiveEdge,+ onSeekToPosition = onSeekToPosition,+ onSetScrubbingMode = onSetScrubbingMode)} else {PlayerVodInfo(@@ -703,7 +710,9 @@ private fun PlayerLiveInfo(onTogglePlayPause: () -> Unit,onSeekBackward: () -> Unit,onSeekForward: () -> Unit,- onSeekToLiveEdge: () -> Unit+ onSeekToLiveEdge: () -> Unit,+ onSeekToPosition: (Long) -> Unit,+ onSetScrubbingMode: (Boolean) -> Unit) {val showTimeshiftControls = timeshiftUiState.available && !isCastConnectedval primaryActions = buildList {@@ -763,7 +772,9 @@ private fun PlayerLiveInfo(},accent = true)- PlayerMetaPill(text = stringResource(R.string.player_live_channel, displayChannelNumber))+ if (displayChannelNumber > 0) {+ PlayerMetaPill(text = stringResource(R.string.player_live_channel, displayChannelNumber))+ }if (currentProgram?.hasArchive == true) {PlayerMetaPill(text = stringResource(R.string.player_archive_badge))}@@ -791,7 +802,11 @@ private fun PlayerLiveInfo()Text(text = if (currentProgram != null) {- stringResource(R.string.channel_number_name_format, displayChannelNumber, currentChannelName.orEmpty())+ if (displayChannelNumber > 0) {+ stringResource(R.string.channel_number_name_format, displayChannelNumber, currentChannelName.orEmpty())+ } else {+ currentChannelName.orEmpty()+ }} else {stringResource(R.string.player_no_guide_data)},@@ -804,96 +819,18 @@ private fun PlayerLiveInfo(Spacer(modifier = Modifier.height(16.dp))if (showTimeshiftControls) {- Surface(- shape = RoundedCornerShape(20.dp),- colors = SurfaceDefaults.colors(containerColor = Color.White.copy(alpha = 0.06f))- ) {- Row(- modifier = Modifier- .fillMaxWidth()- .padding(horizontal = 14.dp, vertical = 12.dp),- horizontalArrangement = Arrangement.spacedBy(12.dp),- verticalAlignment = Alignment.CenterVertically- ) {- Surface(- shape = RoundedCornerShape(999.dp),- colors = SurfaceDefaults.colors(containerColor = Color.Black.copy(alpha = 0.24f))- ) {- Row(- modifier = Modifier.padding(horizontal = 8.dp, vertical = 8.dp),- horizontalArrangement = Arrangement.spacedBy(10.dp),- verticalAlignment = Alignment.CenterVertically- ) {- PlayerTransportButton(- label = "\u23EA",- contentDescription = stringResource(R.string.player_rewind),- onClick = onSeekBackward,- modifier = Modifier.focusProperties { down = quickActionsFocusRequester }- )- TvClickableSurface(- onClick = onTogglePlayPause,- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(50)),- colors = ClickableSurfaceDefaults.colors(- containerColor = Primary.copy(alpha = 0.84f),- focusedContainerColor = Primary- ),- modifier = Modifier- .size(62.dp)- .focusRequester(playButtonFocusRequester)- .focusProperties { down = quickActionsFocusRequester }- ) {- Box(contentAlignment = Alignment.Center, modifier = Modifier.fillMaxSize()) {- if (isPlaying) {- Text(text = "II", style = MaterialTheme.typography.headlineMedium, color = Color.White)- } else {- Icon(- imageVector = Icons.Default.PlayArrow,- contentDescription = stringResource(R.string.player_play),- tint = Color.White,- modifier = Modifier.size(30.dp)- )- }- }- }- PlayerTransportButton(- label = "\u23E9",- contentDescription = stringResource(R.string.player_forward),- onClick = onSeekForward,- modifier = Modifier.focusProperties { down = quickActionsFocusRequester }- )- }- }- Column(modifier = Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(6.dp)) {- Text(- text = timeshiftUiState.statusMessage.ifBlank {- if (timeshiftUiState.bufferDepthMs > 0L) {- stringResource(R.string.player_live_timeshift_buffering)- } else {- stringResource(R.string.player_live_timeshift_ready)- }- },- style = MaterialTheme.typography.labelLarge,- color = Color.White- )- Text(- text = if (timeshiftUiState.bufferedBehindLiveMs > 1_000L) {- stringResource(R.string.player_live_offset, formatDuration(timeshiftUiState.bufferedBehindLiveMs))- } else {- stringResource(R.string.player_live_ready)- },- style = MaterialTheme.typography.labelMedium,- color = Color.White.copy(alpha = 0.72f)- )- }- if (timeshiftUiState.canSeekToLive) {- PlayerQuickSettingsButton(- text = stringResource(R.string.player_jump_to_live),- onClick = onSeekToLiveEdge- )- }- }- }-+ LiveTimeshiftScrubber(+ timeshiftUiState = timeshiftUiState,+ isPlaying = isPlaying,+ playButtonFocusRequester = playButtonFocusRequester,+ quickActionsFocusRequester = quickActionsFocusRequester,+ onTogglePlayPause = onTogglePlayPause,+ onSeekBackward = onSeekBackward,+ onSeekForward = onSeekForward,+ onSeekToPosition = onSeekToPosition,+ onSeekToLiveEdge = onSeekToLiveEdge,+ onSetScrubbingMode = onSetScrubbingMode+ )Spacer(modifier = Modifier.height(16.dp))}@@ -1523,6 +1460,241 @@ private fun PlayerQuickActionRows(}}+@Composable+private fun LiveTimeshiftScrubber(+ timeshiftUiState: PlayerTimeshiftUiState,+ isPlaying: Boolean,+ playButtonFocusRequester: FocusRequester,+ quickActionsFocusRequester: FocusRequester,+ onTogglePlayPause: () -> Unit,+ onSeekBackward: () -> Unit,+ onSeekForward: () -> Unit,+ onSeekToPosition: (Long) -> Unit,+ onSeekToLiveEdge: () -> Unit,+ onSetScrubbingMode: (Boolean) -> Unit,+ modifier: Modifier = Modifier+) {+ val bufferDepthMs = timeshiftUiState.bufferDepthMs.coerceAtLeast(1L)+ val bufferedBehindLive = timeshiftUiState.bufferedBehindLiveMs+ val targetFraction = remember(bufferedBehindLive, bufferDepthMs) {+ 1f - (bufferedBehindLive.toFloat() / bufferDepthMs.toFloat()).coerceIn(0f, 1f)+ }+ var scrubberFraction by remember { mutableStateOf(targetFraction) }+ var isScrubbing by remember { mutableStateOf(false) }+ val latestSeekCallback by rememberUpdatedState(onSeekToPosition)+ val latestScrubbingCallback by rememberUpdatedState(onSetScrubbingMode)+ val latestSeekBackward by rememberUpdatedState(onSeekBackward)+ val latestSeekForward by rememberUpdatedState(onSeekForward)+ val latestSeekToLiveEdge by rememberUpdatedState(onSeekToLiveEdge)++ LaunchedEffect(targetFraction, isScrubbing) {+ if (!isScrubbing) scrubberFraction = targetFraction+ }++ val engineState = timeshiftUiState.engineState+ val oldestWallMs = engineState.bufferStartMs+ val oldestLabel = if (oldestWallMs > 0L) {+ SimpleDateFormat("HH:mm", Locale.getDefault()).format(Date(oldestWallMs))+ } else if (bufferDepthMs > 1_000L) {+ "-${formatTimeshiftDuration(bufferDepthMs)}"+ } else {+ ""+ }++ val currentOffsetMs = if (isScrubbing) {+ ((1f - scrubberFraction) * bufferDepthMs.toFloat()).toLong()+ } else {+ bufferedBehindLive+ }++ var liveDotVisible by remember { mutableStateOf(true) }+ LaunchedEffect(Unit) {+ while (true) {+ delay(700L)+ liveDotVisible = !liveDotVisible+ }+ }++ val scrubberCd = stringResource(R.string.player_live_scrubber_cd)++ Surface(+ shape = RoundedCornerShape(20.dp),+ colors = SurfaceDefaults.colors(containerColor = Color.White.copy(alpha = 0.06f)),+ modifier = modifier+ ) {+ Row(+ modifier = Modifier+ .fillMaxWidth()+ .padding(horizontal = 14.dp, vertical = 12.dp),+ horizontalArrangement = Arrangement.spacedBy(12.dp),+ verticalAlignment = Alignment.CenterVertically+ ) {+ // Transport controls pill+ Surface(+ shape = RoundedCornerShape(999.dp),+ colors = SurfaceDefaults.colors(containerColor = Color.Black.copy(alpha = 0.24f))+ ) {+ Row(+ modifier = Modifier.padding(horizontal = 8.dp, vertical = 8.dp),+ horizontalArrangement = Arrangement.spacedBy(10.dp),+ verticalAlignment = Alignment.CenterVertically+ ) {+ PlayerTransportButton(+ label = "\u23EA",+ contentDescription = stringResource(R.string.player_rewind),+ onClick = onSeekBackward,+ modifier = Modifier.focusProperties { down = quickActionsFocusRequester }+ )+ TvClickableSurface(+ onClick = onTogglePlayPause,+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(50)),+ colors = ClickableSurfaceDefaults.colors(+ containerColor = Primary.copy(alpha = 0.84f),+ focusedContainerColor = Primary+ ),+ modifier = Modifier+ .size(62.dp)+ .focusRequester(playButtonFocusRequester)+ .focusProperties { down = quickActionsFocusRequester }+ ) {+ Box(contentAlignment = Alignment.Center, modifier = Modifier.fillMaxSize()) {+ if (isPlaying) {+ Text(text = "II", style = MaterialTheme.typography.headlineMedium, color = Color.White)+ } else {+ Icon(+ imageVector = Icons.Default.PlayArrow,+ contentDescription = stringResource(R.string.player_play),+ tint = Color.White,+ modifier = Modifier.size(30.dp)+ )+ }+ }+ }+ PlayerTransportButton(+ label = "\u23E9",+ contentDescription = stringResource(R.string.player_forward),+ onClick = onSeekForward,+ modifier = Modifier.focusProperties { down = quickActionsFocusRequester }+ )+ }+ }++ // Scrubber section+ Column(+ modifier = Modifier.weight(1f),+ verticalArrangement = Arrangement.spacedBy(6.dp)+ ) {+ // Labels: oldest time | current offset | LIVE badge+ Row(+ modifier = Modifier.fillMaxWidth(),+ horizontalArrangement = Arrangement.SpaceBetween,+ verticalAlignment = Alignment.CenterVertically+ ) {+ Text(+ text = oldestLabel,+ style = MaterialTheme.typography.labelSmall,+ color = Color.White.copy(alpha = 0.55f)+ )+ Text(+ text = if (currentOffsetMs < 2_000L) {+ stringResource(R.string.player_live_ready)+ } else {+ stringResource(R.string.player_live_offset, formatTimeshiftDuration(currentOffsetMs))+ },+ style = MaterialTheme.typography.labelMedium,+ fontWeight = if (currentOffsetMs < 2_000L) FontWeight.Bold else FontWeight.Normal,+ color = if (currentOffsetMs < 2_000L) Primary else Color.White+ )+ // LIVE edge badge with pulsing dot+ Row(+ horizontalArrangement = Arrangement.spacedBy(4.dp),+ verticalAlignment = Alignment.CenterVertically+ ) {+ Box(+ modifier = Modifier+ .size(7.dp)+ .background(+ color = Color.Red.copy(alpha = if (liveDotVisible) 0.95f else 0.30f),+ shape = RoundedCornerShape(999.dp)+ )+ )+ Text(+ text = stringResource(R.string.player_jump_to_live_short),+ style = MaterialTheme.typography.labelSmall,+ fontWeight = FontWeight.Bold,+ color = Color.White.copy(alpha = 0.85f)+ )+ }+ }++ // Timeline slider+ Slider(+ value = scrubberFraction,+ onValueChange = { newValue ->+ val clamped = newValue.coerceIn(0f, 1f)+ if (!isScrubbing) {+ isScrubbing = true+ latestScrubbingCallback(true)+ }+ scrubberFraction = clamped+ },+ onValueChangeFinished = {+ val finalFraction = scrubberFraction.coerceIn(0f, 1f)+ if (finalFraction >= 0.995f) {+ latestSeekToLiveEdge()+ } else {+ latestSeekCallback((finalFraction * bufferDepthMs.toFloat()).toLong())+ }+ if (isScrubbing) {+ latestScrubbingCallback(false)+ isScrubbing = false+ }+ },+ modifier = Modifier+ .fillMaxWidth()+ .focusProperties {+ down = quickActionsFocusRequester+ up = playButtonFocusRequester+ }+ .onPreviewKeyEvent { event ->+ if (event.nativeKeyEvent.action != android.view.KeyEvent.ACTION_DOWN) {+ return@onPreviewKeyEvent false+ }+ when (event.nativeKeyEvent.keyCode) {+ android.view.KeyEvent.KEYCODE_DPAD_LEFT -> { latestSeekBackward(); true }+ android.view.KeyEvent.KEYCODE_DPAD_RIGHT -> {+ if (timeshiftUiState.canSeekToLive) latestSeekForward() else latestSeekToLiveEdge()+ true+ }+ else -> false+ }+ }+ .semantics { contentDescription = scrubberCd },+ enabled = bufferDepthMs > 2_000L,+ colors = SliderDefaults.colors(+ activeTrackColor = Primary,+ inactiveTrackColor = Color.White.copy(alpha = 0.22f),+ thumbColor = Primary+ )+ )+ }+ }+ }+}++private fun formatTimeshiftDuration(ms: Long): String {+ val totalSeconds = ms / 1_000L+ val minutes = totalSeconds / 60L+ val seconds = totalSeconds % 60L+ val hours = minutes / 60L+ val remainingMinutes = minutes % 60L+ return if (hours > 0L) {+ String.format(Locale.getDefault(), "%d:%02d:%02d", hours, remainingMinutes, seconds)+ } else {+ String.format(Locale.getDefault(), "%d:%02d", minutes, seconds)+ }+}+private fun formatDuration(ms: Long): String {val totalSeconds = ms / 1000val minutes = totalSeconds / 60diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerOverlays.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerOverlays.ktindex 9426ddaf..4f211808 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerOverlays.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerOverlays.kt@@ -297,10 +297,12 @@ fun ChannelInfoOverlay(horizontalArrangement = Arrangement.spacedBy(8.dp),verticalAlignment = Alignment.CenterVertically) {- StatusPill(- label = stringResource(R.string.player_live_channel, displayChannelNumber),- containerColor = AppColors.BrandMuted- )+ if (displayChannelNumber > 0) {+ StatusPill(+ label = stringResource(R.string.player_live_channel, displayChannelNumber),+ containerColor = AppColors.BrandMuted+ )+ }if (showTimeshiftControls) {StatusPill(label = stringResource(R.string.player_live_rewind_badge),@@ -1039,7 +1041,13 @@ private fun CompactMenuActionButton(shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(12.dp)),colors = ClickableSurfaceDefaults.colors(containerColor = Color.White.copy(alpha = 0.08f),- focusedContainerColor = Primary.copy(alpha = 0.88f)+ focusedContainerColor = Color.White.copy(alpha = 0.16f)+ ),+ scale = ClickableSurfaceDefaults.scale(focusedScale = 1.0f),+ border = ClickableSurfaceDefaults.border(+ focusedBorder = Border(+ border = androidx.compose.foundation.BorderStroke(1.5.dp, Color.White.copy(alpha = 0.75f))+ )),modifier = modifier.onFocusChanged {@@ -1519,12 +1527,8 @@ fun EpgOverlay(currentProgram: Program?,nextProgram: Program?,upcomingPrograms: List<Program>,- overlayFocusRequester: FocusRequester = remember { FocusRequester() },- preferredFocusedProgramToken: Long? = null,- onFocusedProgramChange: (Long) -> Unit = {},onDismiss: () -> Unit,onOpenArchiveBrowser: (() -> Unit)? = null,- onPlayCatchUp: (Program) -> Unit,onOverlayInteracted: () -> Unit = {}) {val timeFormat = SimpleDateFormat("HH:mm", Locale.getDefault())@@ -1704,33 +1708,14 @@ fun EpgOverlay(items(displayPrograms.size) { index ->val program = displayPrograms[index]val isNext = index == 0 && nextProgram != null- val focusToken = if (program.id > 0) program.id else program.startTime- val shouldRequestFocus = preferredFocusedProgramToken?.let { it == focusToken } ?: (index == 0)- TvClickableSurface(- onClick = {- if (program.hasArchive || currentChannel?.catchUpSupported == true) {- onOverlayInteracted()- onPlayCatchUp(program)- }- },- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(12.dp)),- colors = ClickableSurfaceDefaults.colors(- containerColor = if (isNext) Primary.copy(alpha = 0.08f) else Color.Transparent,- focusedContainerColor = Primary.copy(alpha = 0.2f)- ),+ Box(modifier = Modifier.fillMaxWidth()- .then(- if (shouldRequestFocus) Modifier.focusRequester(overlayFocusRequester)- else Modifier+ .clip(RoundedCornerShape(12.dp))+ .background(+ if (isNext) Primary.copy(alpha = 0.08f) else Color.Transparent)- .onFocusChanged {- if (it.isFocused) {- onOverlayInteracted()- onFocusedProgramChange(focusToken)- }- }) {Column(modifier = Modifier.padding(12.dp)) {if (isNext) {@@ -1825,6 +1810,9 @@ fun DiagnosticsOverlay(PlayerMetaRow(stringResource(R.string.player_diagnostics_video_codec), stats.videoCodec)PlayerMetaRow(stringResource(R.string.player_diagnostics_video_bitrate), "${stats.videoBitrate / 1000} kbps")PlayerMetaRow(stringResource(R.string.player_diagnostics_dropped_frames), stats.droppedFrames.toString())+ if (stats.ttffMs > 0L) {+ PlayerMetaRow("TTFF", "${stats.ttffMs} ms")+ }PlayerOverlaySectionLabel(stringResource(R.string.player_diagnostics_section_audio))PlayerMetaRow(stringResource(R.string.player_diagnostics_audio_codec), stats.audioCodec)PlayerOverlaySectionLabel(stringResource(R.string.player_diagnostics_section_recovery))diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerSystemOverlays.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerSystemOverlays.ktindex 24d3307e..f69d7c0b 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerSystemOverlays.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerSystemOverlays.kt@@ -150,14 +150,17 @@ fun PlayerErrorOverlay(onAction: (PlayerNoticeAction) -> Unit,modifier: Modifier = Modifier) {- val errorMessage = when (playerError) {+ val fallbackMessage = when (playerError) {is PlayerError.NetworkError -> stringResource(R.string.player_error_network)is PlayerError.SourceError -> stringResource(R.string.player_error_source)is PlayerError.DecoderError -> stringResource(R.string.player_error_decoder)is PlayerError.DrmError -> stringResource(R.string.player_error_drm)- is PlayerError.UnknownError -> playerError.message ?: stringResource(R.string.player_error_unknown)+ is PlayerError.UnknownError -> stringResource(R.string.player_error_unknown)null -> stringResource(R.string.player_error_unknown)}+ // Prefer the detailed engine message (e.g. "No decoder available for codec H.265/HEVC")+ // and fall back to the generic localised string when the message is absent or unhelpful.+ val errorMessage = playerError?.message?.takeIf { it.isNotBlank() } ?: fallbackMessageval recoveryActions = buildList {add(PlayerNoticeAction.RETRY)if (contentType == "LIVE" && hasAlternateStream) add(PlayerNoticeAction.ALTERNATE_STREAM)diff --git a/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupScreen.ktindex d07629bc..5529279e 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupScreen.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupScreen.kt@@ -63,6 +63,7 @@ import androidx.tv.material3.*import com.streamvault.app.Rimport com.streamvault.app.device.rememberIsTelevisionDeviceimport com.streamvault.app.ui.components.dialogs.PremiumDialog+import com.streamvault.app.ui.components.dialogs.PremiumDialogFooterButtonimport com.streamvault.app.ui.components.shell.StatusPillimport com.streamvault.app.ui.theme.*import com.streamvault.data.util.ProviderInputSanitizer@@ -339,24 +340,24 @@ fun ProviderSetupScreen(}if (showDiscardDraftDialog) {- androidx.compose.material3.AlertDialog(+ PremiumDialog(+ title = stringResource(R.string.setup_discard_draft_title),+ subtitle = stringResource(R.string.setup_discard_draft_body),onDismissRequest = { showDiscardDraftDialog = false },- title = { Text(stringResource(R.string.setup_discard_draft_title)) },- text = { Text(stringResource(R.string.setup_discard_draft_body), color = OnSurface) },- confirmButton = {- TextButton(+ content = {},+ footer = {+ PremiumDialogFooterButton(+ label = stringResource(R.string.setup_discard_draft_cancel),+ onClick = { showDiscardDraftDialog = false }+ )+ PremiumDialogFooterButton(+ label = stringResource(R.string.setup_discard_draft_confirm),onClick = {showDiscardDraftDialog = falseonBack()- }- ) {- Text(stringResource(R.string.setup_discard_draft_confirm), color = Primary)- }- },- dismissButton = {- TextButton(onClick = { showDiscardDraftDialog = false }) {- Text(stringResource(R.string.setup_discard_draft_cancel), color = OnSurface)- }+ },+ emphasized = true+ )})}diff --git a/app/src/main/java/com/streamvault/app/ui/screens/search/SearchScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/search/SearchScreen.ktindex 924cbab3..d2f9e7de 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/search/SearchScreen.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/search/SearchScreen.kt@@ -5,6 +5,7 @@ import com.streamvault.app.ui.interaction.TvClickableSurfaceimport androidx.compose.foundation.BorderStrokeimport androidx.compose.foundation.background+import androidx.compose.foundation.borderimport androidx.compose.foundation.layout.*import androidx.compose.foundation.lazy.LazyColumnimport androidx.compose.foundation.lazy.LazyRow@@ -17,7 +18,9 @@ import androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifierimport androidx.compose.ui.focus.FocusRequesterimport androidx.compose.ui.focus.focusRequester+import androidx.compose.ui.focus.onFocusChangedimport androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.vector.ImageVectorimport androidx.compose.ui.platform.LocalFocusManagerimport androidx.compose.ui.res.stringResourceimport androidx.compose.ui.semantics.LiveRegionMode@@ -29,9 +32,15 @@ import androidx.compose.ui.semantics.semanticsimport androidx.compose.ui.semantics.stateDescriptionimport androidx.compose.ui.text.style.TextOverflowimport androidx.compose.ui.unit.dp+import androidx.compose.ui.window.Dialog+import androidx.compose.ui.window.DialogPropertiesimport androidx.hilt.lifecycle.viewmodel.compose.hiltViewModelimport androidx.lifecycle.ViewModelimport androidx.lifecycle.viewModelScope+import androidx.compose.material.icons.Icons+import androidx.compose.material.icons.filled.Close+import androidx.compose.material.icons.filled.Lock+import androidx.compose.material.icons.filled.Starimport androidx.tv.material3.*import com.streamvault.app.Rimport com.streamvault.app.ui.components.CategoryRow@@ -42,18 +51,25 @@ import com.streamvault.app.ui.components.SeriesCardimport com.streamvault.app.ui.components.TvEmptyStateimport com.streamvault.app.ui.components.shell.AppNavigationChromeimport com.streamvault.app.ui.components.shell.AppScreenScaffold+import com.streamvault.app.ui.design.AppColorsimport com.streamvault.app.ui.design.requestFocusSafely+import com.streamvault.app.ui.interaction.mouseClickableimport com.streamvault.app.ui.theme.*import com.streamvault.domain.manager.ParentalControlManagerimport com.streamvault.domain.model.Channel+import com.streamvault.domain.model.ContentTypeimport com.streamvault.domain.model.Movie+import com.streamvault.domain.model.SearchHistoryScopeimport com.streamvault.domain.model.Series+import com.streamvault.domain.repository.CategoryRepository+import com.streamvault.domain.repository.FavoriteRepositoryimport com.streamvault.domain.repository.ProviderRepositoryimport com.streamvault.domain.usecase.SearchContentimport com.streamvault.domain.usecase.SearchContentScopeimport dagger.hilt.android.lifecycle.HiltViewModelimport kotlinx.coroutines.ExperimentalCoroutinesApiimport kotlinx.coroutines.FlowPreview+import kotlinx.coroutines.delayimport kotlinx.coroutines.flow.*import kotlinx.coroutines.launchimport javax.inject.Inject@@ -64,7 +80,9 @@ class SearchViewModel @Inject constructor(private val providerRepository: ProviderRepository,private val searchContent: SearchContent,private val preferencesRepository: com.streamvault.data.preferences.PreferencesRepository,- private val parentalControlManager: ParentalControlManager+ private val parentalControlManager: ParentalControlManager,+ private val favoriteRepository: FavoriteRepository,+ private val categoryRepository: CategoryRepository) : ViewModel() {private companion object {const val MAX_RESULTS_PER_SECTION = 120@@ -76,8 +94,6 @@ class SearchViewModel @Inject constructor(private val _selectedTab = MutableStateFlow(SearchTab.ALL)val selectedTab: StateFlow<SearchTab> = _selectedTab.asStateFlow()- private val _recentQueries = MutableStateFlow<List<String>>(emptyList())- val recentQueries: StateFlow<List<String>> = _recentQueries.asStateFlow()private val _parentalControlLevel = MutableStateFlow(0)private val _activeProviderId = MutableStateFlow<Long?>(null)@@ -93,13 +109,21 @@ class SearchViewModel @Inject constructor(_parentalControlLevel.value = level}}- viewModelScope.launch {- preferencesRepository.recentSearchQueries.collect { queries ->- _recentQueries.value = queries- }- }}+ val recentQueries: StateFlow<List<String>> = combine(+ _selectedTab,+ _activeProviderId+ ) { tab, providerId ->+ tab.toSearchHistoryScope() to providerId+ }.flatMapLatest { (scope, providerId) ->+ preferencesRepository.getRecentSearchQueries(+ scope = scope,+ providerId = providerId,+ limit = MAX_RECENT_QUERIES+ )+ }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), emptyList())+@OptIn(FlowPreview::class)val uiState: StateFlow<SearchUiState> = combine(providerRepository.getActiveProvider(),@@ -156,12 +180,12 @@ class SearchViewModel @Inject constructor(if (normalizedQuery.length < 2) return_query.value = normalizedQuery- val updatedQueries = _recentQueries.updateAndGet { existing ->- (listOf(normalizedQuery) + existing.filterNot { it.equals(normalizedQuery, ignoreCase = true) })- .take(MAX_RECENT_QUERIES)- }viewModelScope.launch {- preferencesRepository.setRecentSearchQueries(updatedQueries)+ preferencesRepository.recordRecentSearchQuery(+ query = normalizedQuery,+ scope = _selectedTab.value.toSearchHistoryScope(),+ providerId = _activeProviderId.value+ )}}@@ -179,9 +203,11 @@ class SearchViewModel @Inject constructor(}fun clearRecentQueries() {- _recentQueries.value = emptyList()viewModelScope.launch {- preferencesRepository.setRecentSearchQueries(emptyList())+ preferencesRepository.clearRecentSearchQueries(+ scope = _selectedTab.value.toSearchHistoryScope(),+ providerId = _activeProviderId.value+ )}}@@ -198,6 +224,43 @@ class SearchViewModel @Inject constructor(val resolvedCategoryId = categoryId ?: returnparentalControlManager.unlockCategory(providerId, resolvedCategoryId)}++ // ── Search item long-press actions ────────────────────────────────++ fun toggleFavorite(contentId: Long, contentType: ContentType, currentlyFavorite: Boolean) {+ viewModelScope.launch {+ val providerId = _activeProviderId.value ?: return@launch+ if (currentlyFavorite) {+ favoriteRepository.removeFavorite(providerId, contentId, contentType)+ } else {+ favoriteRepository.addFavorite(providerId, contentId, contentType)+ }+ }+ }++ fun hideItemCategory(categoryId: Long, contentType: ContentType) {+ val providerId = _activeProviderId.value ?: return+ viewModelScope.launch {+ preferencesRepository.setCategoryHidden(+ providerId = providerId,+ type = contentType,+ categoryId = categoryId,+ hidden = true+ )+ }+ }++ fun toggleCategoryProtection(categoryId: Long, contentType: ContentType, currentlyProtected: Boolean) {+ val providerId = _activeProviderId.value ?: return+ viewModelScope.launch {+ categoryRepository.setCategoryProtection(+ providerId = providerId,+ categoryId = categoryId,+ type = contentType,+ isProtected = !currentlyProtected+ )+ }+ }}private data class SearchFilterParams(@@ -222,6 +285,13 @@ private fun SearchTab.toSearchScope(): SearchContentScope = when (this) {SearchTab.SERIES -> SearchContentScope.SERIES}+private fun SearchTab.toSearchHistoryScope(): SearchHistoryScope = when (this) {+ SearchTab.ALL -> SearchHistoryScope.ALL+ SearchTab.LIVE -> SearchHistoryScope.LIVE+ SearchTab.MOVIES -> SearchHistoryScope.MOVIE+ SearchTab.SERIES -> SearchHistoryScope.SERIES+}+data class SearchUiState(val channels: List<Channel> = emptyList(),val movies: List<Movie> = emptyList(),@@ -262,6 +332,34 @@ fun SearchScreen(var pendingSeries by remember { mutableStateOf<Series?>(null) }val scope = rememberCoroutineScope()val selectedStateLabel = stringResource(R.string.a11y_selected)++ // ── Long-press actions dialog state ───────────────────────────────+ var showActionsDialog by remember { mutableStateOf(false) }+ var actionsChannel by remember { mutableStateOf<Channel?>(null) }+ var actionsMovie by remember { mutableStateOf<Movie?>(null) }+ var actionsSeries by remember { mutableStateOf<Series?>(null) }+ var actionsIsFavorite by remember { mutableStateOf(false) }+ // Separate PIN purpose: unlock-to-play vs toggle-parental-protection+ var pinIsForProtectionToggle by remember { mutableStateOf(false) }+ var pendingProtectionCategoryId by remember { mutableStateOf<Long?>(null) }+ var pendingProtectionContentType by remember { mutableStateOf<ContentType?>(null) }+ var pendingProtectionCurrentlyProtected by remember { mutableStateOf(false) }++ fun showChannelActions(channel: Channel) {+ actionsChannel = channel; actionsMovie = null; actionsSeries = null+ actionsIsFavorite = channel.isFavorite+ showActionsDialog = true+ }+ fun showMovieActions(movie: Movie) {+ actionsChannel = null; actionsMovie = movie; actionsSeries = null+ actionsIsFavorite = movie.isFavorite+ showActionsDialog = true+ }+ fun showSeriesActions(series: Series) {+ actionsChannel = null; actionsMovie = null; actionsSeries = series+ actionsIsFavorite = series.isFavorite+ showActionsDialog = true+ }val channelRows = remember(uiState.channels) { uiState.channels.chunked(4) }val movieRows = remember(uiState.movies) { uiState.movies.chunked(6) }val seriesRows = remember(uiState.series) { uiState.series.chunked(6) }@@ -301,21 +399,37 @@ fun SearchScreen(pendingChannel = nullpendingMovie = nullpendingSeries = null+ pinIsForProtectionToggle = false+ pendingProtectionCategoryId = null+ pendingProtectionContentType = null},onPinEntered = { pin ->scope.launch {if (viewModel.verifyPin(pin)) {- pendingChannel?.categoryId?.let(viewModel::unlockCategory)- pendingMovie?.categoryId?.let(viewModel::unlockCategory)- pendingSeries?.categoryId?.let(viewModel::unlockCategory)- showPinDialog = false- pinError = null- pendingChannel?.let { onChannelClick(it) }- pendingMovie?.let { onMovieClick(it) }- pendingSeries?.let { onSeriesClick(it) }- pendingChannel = null- pendingMovie = null- pendingSeries = null+ if (pinIsForProtectionToggle) {+ val catId = pendingProtectionCategoryId+ val ct = pendingProtectionContentType+ if (catId != null && ct != null) {+ viewModel.toggleCategoryProtection(catId, ct, pendingProtectionCurrentlyProtected)+ }+ showPinDialog = false+ pinError = null+ pinIsForProtectionToggle = false+ pendingProtectionCategoryId = null+ pendingProtectionContentType = null+ } else {+ pendingChannel?.categoryId?.let(viewModel::unlockCategory)+ pendingMovie?.categoryId?.let(viewModel::unlockCategory)+ pendingSeries?.categoryId?.let(viewModel::unlockCategory)+ showPinDialog = false+ pinError = null+ pendingChannel?.let { onChannelClick(it) }+ pendingMovie?.let { onMovieClick(it) }+ pendingSeries?.let { onSeriesClick(it) }+ pendingChannel = null+ pendingMovie = null+ pendingSeries = null+ }} else {pinError = context.getString(R.string.search_incorrect_pin)}@@ -327,6 +441,46 @@ fun SearchScreen(val selectedTabDescription = selectedStateLabel+ // ── Long-press actions dialog ─────────────────────────────────────+ if (showActionsDialog) {+ val actionsTitle = actionsChannel?.name ?: actionsMovie?.name ?: actionsSeries?.name ?: ""+ val actionsCategoryId = actionsChannel?.categoryId ?: actionsMovie?.categoryId ?: actionsSeries?.categoryId+ val actionsIsProtected = actionsChannel?.isUserProtected ?: actionsMovie?.isUserProtected ?: actionsSeries?.isUserProtected ?: false+ val actionsContentType = when {+ actionsChannel != null -> ContentType.LIVE+ actionsMovie != null -> ContentType.MOVIE+ else -> ContentType.SERIES+ }+ val actionsItemId = actionsChannel?.id ?: actionsMovie?.id ?: actionsSeries?.id ?: 0L+ SearchItemActionsDialog(+ title = actionsTitle,+ isFavorite = actionsIsFavorite,+ isProtected = actionsIsProtected,+ hasCategoryId = actionsCategoryId != null,+ onDismiss = { showActionsDialog = false },+ onToggleFavorite = {+ viewModel.toggleFavorite(actionsItemId, actionsContentType, actionsIsFavorite)+ actionsIsFavorite = !actionsIsFavorite+ },+ onHide = if (actionsCategoryId != null) {+ {+ viewModel.hideItemCategory(actionsCategoryId, actionsContentType)+ showActionsDialog = false+ }+ } else null,+ onToggleLock = if (actionsCategoryId != null) {+ {+ showActionsDialog = false+ pendingProtectionCategoryId = actionsCategoryId+ pendingProtectionContentType = actionsContentType+ pendingProtectionCurrentlyProtected = actionsIsProtected+ pinIsForProtectionToggle = true+ showPinDialog = true+ }+ } else null+ )+ }+AppScreenScaffold(currentRoute = currentRoute,onNavigate = onNavigate,@@ -419,7 +573,8 @@ fun SearchScreen(} else {onChannelClick(channel)}- }+ },+ onLongClick = { showChannelActions(channel) })}}@@ -447,7 +602,8 @@ fun SearchScreen(} else {onMovieClick(movie)}- }+ },+ onLongClick = { showMovieActions(movie) })}}@@ -475,7 +631,8 @@ fun SearchScreen(} else {onSeriesClick(seriesItem)}- }+ },+ onLongClick = { showSeriesActions(seriesItem) })}}@@ -513,7 +670,8 @@ fun SearchScreen(} else {onChannelClick(channel)}- }+ },+ onChannelLongClick = { channel -> showChannelActions(channel) })}@@ -536,7 +694,8 @@ fun SearchScreen(} else {onMovieClick(movie)}- }+ },+ onMovieLongClick = { movie -> showMovieActions(movie) })}@@ -559,7 +718,8 @@ fun SearchScreen(} else {onSeriesClick(seriesItem)}- }+ },+ onSeriesLongClick = { seriesItem -> showSeriesActions(seriesItem) })}}@@ -803,7 +963,8 @@ private fun <T : Any> SearchResultRail(private fun SearchChannelGridRow(channels: List<Channel>,isLocked: (Channel) -> Boolean,- onChannelClick: (Channel, Boolean) -> Unit+ onChannelClick: (Channel, Boolean) -> Unit,+ onChannelLongClick: (Channel) -> Unit) {Row(modifier = Modifier.fillMaxWidth(),@@ -814,7 +975,8 @@ private fun SearchChannelGridRow(ChannelCard(channel = channel,isLocked = locked,- onClick = { onChannelClick(channel, locked) }+ onClick = { onChannelClick(channel, locked) },+ onLongClick = { onChannelLongClick(channel) })}}@@ -824,7 +986,8 @@ private fun SearchChannelGridRow(private fun SearchMovieGridRow(movies: List<Movie>,isLocked: (Movie) -> Boolean,- onMovieClick: (Movie, Boolean) -> Unit+ onMovieClick: (Movie, Boolean) -> Unit,+ onMovieLongClick: (Movie) -> Unit) {Row(modifier = Modifier.fillMaxWidth(),@@ -835,7 +998,8 @@ private fun SearchMovieGridRow(MovieCard(movie = movie,isLocked = locked,- onClick = { onMovieClick(movie, locked) }+ onClick = { onMovieClick(movie, locked) },+ onLongClick = { onMovieLongClick(movie) })}}@@ -845,7 +1009,8 @@ private fun SearchMovieGridRow(private fun SearchSeriesGridRow(seriesItems: List<Series>,isLocked: (Series) -> Boolean,- onSeriesClick: (Series, Boolean) -> Unit+ onSeriesClick: (Series, Boolean) -> Unit,+ onSeriesLongClick: (Series) -> Unit) {Row(modifier = Modifier.fillMaxWidth(),@@ -856,7 +1021,8 @@ private fun SearchSeriesGridRow(SeriesCard(series = seriesItem,isLocked = locked,- onClick = { onSeriesClick(seriesItem, locked) }+ onClick = { onSeriesClick(seriesItem, locked) },+ onLongClick = { onSeriesLongClick(seriesItem) })}}@@ -919,3 +1085,173 @@ private fun SearchMessageState()}+// ── Long-press actions dialog ─────────────────────────────────────────────++@OptIn(ExperimentalTvMaterial3Api::class)+@Composable+private fun SearchItemActionsDialog(+ title: String,+ isFavorite: Boolean,+ isProtected: Boolean,+ hasCategoryId: Boolean,+ onDismiss: () -> Unit,+ onToggleFavorite: () -> Unit,+ onHide: (() -> Unit)?,+ onToggleLock: (() -> Unit)?+) {+ // Ghost-click debounce: ignore select key-up inherited from the long-press gesture+ var canInteract by remember { mutableStateOf(false) }+ val firstFocusRequester = remember { FocusRequester() }+ LaunchedEffect(Unit) {+ runCatching { firstFocusRequester.requestFocus() }+ delay(500)+ canInteract = true+ }++ val safeDismiss = { if (canInteract) onDismiss() }++ Dialog(+ onDismissRequest = safeDismiss,+ properties = DialogProperties(usePlatformDefaultWidth = false)+ ) {+ Surface(+ shape = RoundedCornerShape(20.dp),+ colors = SurfaceDefaults.colors(containerColor = AppColors.SurfaceElevated),+ modifier = Modifier+ .width(360.dp)+ .padding(16.dp)+ ) {+ Column(modifier = Modifier.padding(20.dp)) {+ // Header+ Row(+ modifier = Modifier+ .fillMaxWidth()+ .padding(bottom = 16.dp),+ horizontalArrangement = Arrangement.SpaceBetween,+ verticalAlignment = Alignment.CenterVertically+ ) {+ Text(+ text = title,+ style = MaterialTheme.typography.titleMedium,+ color = AppColors.TextPrimary,+ maxLines = 2,+ overflow = TextOverflow.Ellipsis,+ modifier = Modifier.weight(1f)+ )+ IconButton(+ onClick = safeDismiss,+ modifier = Modifier.mouseClickable(onClick = safeDismiss)+ ) {+ Icon(Icons.Default.Close, contentDescription = stringResource(R.string.search_actions_dismiss))+ }+ }++ Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {+ // ── Favorite toggle ──────────────────────────────+ SearchActionButton(+ icon = Icons.Default.Star,+ label = if (isFavorite) stringResource(R.string.search_actions_remove_favorite)+ else stringResource(R.string.search_actions_add_favorite),+ isActive = isFavorite,+ focusRequester = firstFocusRequester,+ onClick = { if (canInteract) onToggleFavorite() }+ )++ // ── Hide category ────────────────────────────────+ if (onHide != null) {+ SearchActionButton(+ icon = Icons.Default.Close,+ label = stringResource(R.string.search_actions_hide_category),+ isActive = false,+ onClick = { if (canInteract) onHide() }+ )+ } else {+ SearchActionButton(+ icon = Icons.Default.Close,+ label = stringResource(R.string.search_actions_hide_no_category),+ isActive = false,+ enabled = false,+ onClick = {}+ )+ }++ // ── Parental lock toggle ─────────────────────────+ if (onToggleLock != null) {+ SearchActionButton(+ icon = Icons.Default.Lock,+ label = if (isProtected) stringResource(R.string.search_actions_unlock)+ else stringResource(R.string.search_actions_lock),+ isActive = isProtected,+ onClick = { if (canInteract) onToggleLock() }+ )+ } else {+ SearchActionButton(+ icon = Icons.Default.Lock,+ label = stringResource(R.string.search_actions_lock_no_category),+ isActive = false,+ enabled = false,+ onClick = {}+ )+ }+ }+ }+ }+ }+}++@OptIn(ExperimentalTvMaterial3Api::class)+@Composable+private fun SearchActionButton(+ icon: ImageVector,+ label: String,+ isActive: Boolean,+ onClick: () -> Unit,+ modifier: Modifier = Modifier,+ focusRequester: FocusRequester? = null,+ enabled: Boolean = true+) {+ var isFocused by remember { mutableStateOf(false) }+ val baseModifier = modifier+ .fillMaxWidth()+ .onFocusChanged { isFocused = it.isFocused }+ .then(+ if (focusRequester != null) Modifier.focusRequester(focusRequester) else Modifier+ )+ .border(+ width = if (isFocused) 2.dp else 0.dp,+ color = if (isFocused) AppColors.Focus else Color.Transparent,+ shape = RoundedCornerShape(12.dp)+ )+ .mouseClickable(onClick = onClick)++ Button(+ onClick = onClick,+ enabled = enabled,+ modifier = baseModifier,+ colors = ButtonDefaults.colors(+ containerColor = when {+ !enabled -> AppColors.Surface.copy(alpha = 0.3f)+ isFocused -> AppColors.Focus+ isActive -> AppColors.Warning.copy(alpha = 0.85f)+ else -> AppColors.Brand.copy(alpha = 0.70f)+ },+ contentColor = if (!enabled) AppColors.TextSecondary else Color.Black,+ disabledContainerColor = AppColors.Surface.copy(alpha = 0.3f),+ disabledContentColor = AppColors.TextSecondary+ ),+ shape = ButtonDefaults.shape(shape = RoundedCornerShape(12.dp))+ ) {+ Icon(+ imageVector = icon,+ contentDescription = null,+ modifier = Modifier.size(20.dp)+ )+ Spacer(modifier = Modifier.width(10.dp))+ Text(+ text = label,+ style = MaterialTheme.typography.bodyMedium,+ maxLines = 1,+ overflow = TextOverflow.Ellipsis+ )+ }+}diff --git a/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesScreen.ktindex 86b4b89d..bf62d248 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesScreen.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesScreen.kt@@ -88,6 +88,7 @@ import com.streamvault.app.ui.model.VodViewModeimport com.streamvault.app.ui.screens.vod.HandleVodUserMessageimport com.streamvault.app.ui.screens.vod.ProtectedVodPinDialogimport com.streamvault.app.ui.screens.vod.VodBrowseDefaults+import com.streamvault.app.ui.screens.vod.vodActiveFilterSortDetailimport kotlinx.coroutines.delay@OptIn(ExperimentalFoundationApi::class)@@ -722,6 +723,8 @@ private fun SeriesVodContent(if (!uiState.isReorderMode) {item(span = { GridItemSpan(maxLineSpan) }) {+ val browseOptionsDetail = vodActiveFilterSortDetail(selectedFilterType, selectedSortBy)+ val hasActiveFilterSort = selectedFilterType != LibraryFilterType.ALL || selectedSortBy != LibrarySortBy.LIBRARYVodActionChipRow(actions = buildList {add(@@ -751,6 +754,7 @@ private fun SeriesVodContent(VodActionChip(key = "browse_options",label = stringResource(R.string.library_action_filters_sort),+ detail = browseOptionsDetail,onClick = { showBrowseOptions = true }))@@ -764,6 +768,7 @@ private fun SeriesVodContent()}},+ selectedKey = if (hasActiveFilterSort) "browse_options" else null,modifier = Modifier.padding(top = 2.dp, bottom = 2.dp))}@@ -1047,6 +1052,7 @@ private fun SeriesVodClassicContent(modifier = Modifier.fillMaxSize(),verticalArrangement = Arrangement.spacedBy(14.dp)) {+ val hasActiveFilterSortClassic = selectedFilterType != LibraryFilterType.ALL || selectedSortBy != LibrarySortBy.LIBRARYVodClassicContentHeader(title = when {selectedKey == "all" -> allLabel@@ -1072,10 +1078,12 @@ private fun SeriesVodClassicContent(VodActionChip(key = "browse_options",label = stringResource(R.string.library_action_filters_sort),+ detail = vodActiveFilterSortDetail(selectedFilterType, selectedSortBy),onClick = { showBrowseOptions = true }))- }+ },+ selectedActionKey = if (hasActiveFilterSortClassic) "browse_options" else null)if (showSearchBar) {diff --git a/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesViewModel.ktindex f0a8b9d9..96e6010d 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesViewModel.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesViewModel.kt@@ -132,8 +132,8 @@ class SeriesViewModel @Inject constructor(.flatMapLatest { provider ->activeProviderId = provider.idcombine(- favoriteRepository.getAllFavorites(ContentType.SERIES),- getCustomCategories(ContentType.SERIES),+ favoriteRepository.getAllFavorites(provider.id, ContentType.SERIES),+ getCustomCategories(provider.id, ContentType.SERIES),seriesRepository.getCategories(provider.id),seriesRepository.getCategoryItemCounts(provider.id),seriesRepository.getLibraryCount(provider.id),@@ -270,8 +270,8 @@ class SeriesViewModel @Inject constructor(.filterNotNull().flatMapLatest { provider ->combine(- favoriteRepository.getAllFavorites(ContentType.SERIES),- getCustomCategories(ContentType.SERIES),+ favoriteRepository.getAllFavorites(provider.id, ContentType.SERIES),+ getCustomCategories(provider.id, ContentType.SERIES),seriesRepository.getCategories(provider.id),playbackHistoryRepository.getRecentlyWatchedByProvider(provider.id, limit = 2_000),preferencesRepository.getHiddenCategoryIds(provider.id, ContentType.SERIES),@@ -368,7 +368,7 @@ class SeriesViewModel @Inject constructor(.filterNotNull().flatMapLatest { provider ->combine(- favoriteRepository.getAllFavorites(ContentType.SERIES),+ favoriteRepository.getAllFavorites(provider.id, ContentType.SERIES),playbackHistoryRepository.getRecentlyWatchedByProvider(provider.id, limit = 24),seriesRepository.getTopRatedPreview(provider.id, VodBrowseDefaults.PREVIEW_ROW_LIMIT),seriesRepository.getFreshPreview(provider.id, VodBrowseDefaults.PREVIEW_ROW_LIMIT)@@ -460,9 +460,12 @@ class SeriesViewModel @Inject constructor(}viewModelScope.launch {- getCustomCategories(ContentType.SERIES).collect { categories ->- _uiState.update { it.copy(categories = categories) }- }+ providerRepository.getActiveProvider()+ .filterNotNull()+ .flatMapLatest { provider -> getCustomCategories(provider.id, ContentType.SERIES) }+ .collect { categories ->+ _uiState.update { it.copy(categories = categories) }+ }}}@@ -572,6 +575,7 @@ class SeriesViewModel @Inject constructor(viewModelScope.launch {val dialogSelection = loadVodDialogSelection(item = series,+ providerId = series.providerId,itemId = series.id,contentType = ContentType.SERIES,favoriteRepository = favoriteRepository,@@ -595,14 +599,14 @@ class SeriesViewModel @Inject constructor(fun addFavorite(series: Series) {viewModelScope.launch {- setVodFavorite(series.id, ContentType.SERIES, true, favoriteRepository)+ setVodFavorite(series.providerId, series.id, ContentType.SERIES, true, favoriteRepository)_uiState.update { it.copy(selectedSeriesForDialog = series.copy(isFavorite = true)) }}}fun removeFavorite(series: Series) {viewModelScope.launch {- setVodFavorite(series.id, ContentType.SERIES, false, favoriteRepository)+ setVodFavorite(series.providerId, series.id, ContentType.SERIES, false, favoriteRepository)_uiState.update { it.copy(selectedSeriesForDialog = series.copy(isFavorite = false)) }}}@@ -610,6 +614,7 @@ class SeriesViewModel @Inject constructor(fun addToGroup(series: Series, group: Category) {viewModelScope.launch {val memberships = updateVodGroupMembership(+ providerId = series.providerId,itemId = series.id,groupId = group.id,contentType = ContentType.SERIES,@@ -623,6 +628,7 @@ class SeriesViewModel @Inject constructor(fun removeFromGroup(series: Series, group: Category) {viewModelScope.launch {val memberships = updateVodGroupMembership(+ providerId = series.providerId,itemId = series.id,groupId = group.id,contentType = ContentType.SERIES,@@ -642,11 +648,13 @@ class SeriesViewModel @Inject constructor(}viewModelScope.launch {- when (val result = createVodGroup(normalizedName, ContentType.SERIES, favoriteRepository)) {+ val providerId = activeProviderId ?: return@launch+ when (val result = createVodGroup(providerId, normalizedName, ContentType.SERIES, favoriteRepository)) {is Result.Success -> {val selectedSeries = _uiState.value.selectedSeriesForDialogval memberships = if (selectedSeries != null) {updateVodGroupMembership(+ providerId = selectedSeries.providerId,itemId = selectedSeries.id,groupId = result.data.id,contentType = ContentType.SERIES,@@ -847,6 +855,7 @@ class SeriesViewModel @Inject constructor(viewModelScope.launch {try {saveVodReorder(+ providerId = activeProviderId ?: return@launch,category = category,currentItems = currentList,contentType = ContentType.SERIES,@@ -860,6 +869,7 @@ class SeriesViewModel @Inject constructor(private suspend fun loadReorderSeries(category: Category): List<Series> {return loadVodReorderItems(+ providerId = activeProviderId ?: return emptyList(),category = category,contentType = ContentType.SERIES,favoriteRepository = favoriteRepository,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 9b90dc7a..df9e7942 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@@ -6,6 +6,7 @@ import kotlinx.coroutines.flow.MutableStateFlowimport kotlinx.coroutines.flow.updateimport kotlinx.coroutines.launchimport com.streamvault.app.R+import com.streamvault.app.update.AppUpdateDownloadStatusimport com.streamvault.app.update.AppUpdateInstallerimport com.streamvault.app.update.GitHubReleaseCheckerimport com.streamvault.data.preferences.PreferencesRepository@@ -29,7 +30,8 @@ internal class SettingsAppUpdateActions(fun checkForAppUpdates(scope: CoroutineScope,manual: Boolean,- isRemoteVersionNewer: (Int?, String) -> Boolean+ isRemoteVersionNewer: (Int?, String) -> Boolean,+ autoDownload: Boolean = false) {if (updateCheckInFlight) returnupdateCheckInFlight = true@@ -95,6 +97,14 @@ internal class SettingsAppUpdateActions()}appUpdateInstaller.refreshState()+ if (autoDownload && updateAvailable) {+ val currentDownloadStatus = appUpdateInstaller.downloadState.value.status+ if (currentDownloadStatus != AppUpdateDownloadStatus.Downloading &&+ currentDownloadStatus != AppUpdateDownloadStatus.Downloaded+ ) {+ downloadLatestUpdate(scope)+ }+ }}Result.Loading -> {uiState.update { it.copy(isCheckingForUpdates = false) }diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsDialogComponents.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsDialogComponents.ktindex a2089e24..5628b9c3 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsDialogComponents.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsDialogComponents.kt@@ -1,5 +1,6 @@package com.streamvault.app.ui.screens.settings+import androidx.compose.foundation.BorderStrokeimport androidx.compose.foundation.backgroundimport androidx.compose.foundation.borderimport androidx.compose.foundation.clickable@@ -1152,12 +1153,18 @@ internal fun summarizeRecordingOutputPath(path: String): String {}@Composable-internal fun RecordingActionButton(label: String, accent: Color, onClick: () -> Unit) {+internal fun RecordingActionButton(+ label: String,+ accent: Color,+ modifier: Modifier = Modifier,+ onClick: () -> Unit+) {TvButton(onClick = onClick,modifier = Modifier- .widthIn(min = 190.dp, max = 260.dp)- .heightIn(min = 52.dp),+ .widthIn(min = 168.dp, max = 220.dp)+ .heightIn(min = 52.dp)+ .then(modifier),shape = ButtonDefaults.shape(RoundedCornerShape(10.dp)),colors = ButtonDefaults.colors(containerColor = accent.copy(alpha = 0.14f),@@ -1165,6 +1172,16 @@ internal fun RecordingActionButton(label: String, accent: Color, onClick: () ->contentColor = accent,focusedContentColor = accent),+ border = ButtonDefaults.border(+ border = Border(+ border = BorderStroke(1.dp, Color.White.copy(alpha = 0.08f)),+ shape = RoundedCornerShape(10.dp)+ ),+ focusedBorder = Border(+ border = BorderStroke(FocusSpec.BorderWidth, Color.White),+ shape = RoundedCornerShape(10.dp)+ )+ ),scale = ButtonDefaults.scale(focusedScale = 1f)) {Text(@@ -1356,10 +1373,12 @@ internal fun VodViewMode.descriptionResId(): Int = when (this) {internal fun ChannelNumberingMode.labelResId(): Int = when (this) {ChannelNumberingMode.GROUP -> R.string.settings_live_channel_numbering_groupChannelNumberingMode.PROVIDER -> R.string.settings_live_channel_numbering_provider+ ChannelNumberingMode.HIDDEN -> R.string.settings_live_channel_numbering_hidden}internal fun ChannelNumberingMode.descriptionResId(): Int = when (this) {ChannelNumberingMode.GROUP -> R.string.settings_live_channel_numbering_group_descChannelNumberingMode.PROVIDER -> R.string.settings_live_channel_numbering_provider_desc+ ChannelNumberingMode.HIDDEN -> R.string.settings_live_channel_numbering_hidden_desc}diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsEpgActions.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsEpgActions.ktindex f6990692..a9576ad3 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsEpgActions.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsEpgActions.kt@@ -3,24 +3,23 @@ package com.streamvault.app.ui.screens.settingsimport com.streamvault.domain.model.Resultimport com.streamvault.domain.repository.EpgSourceRepositoryimport kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Jobimport kotlinx.coroutines.flow.MutableStateFlowimport kotlinx.coroutines.flow.updateimport kotlinx.coroutines.launch+import java.util.concurrent.ConcurrentHashMapinternal class SettingsEpgActions(private val epgSourceRepository: EpgSourceRepository,private val uiState: MutableStateFlow<SettingsUiState>) {- fun loadEpgSources(scope: CoroutineScope) {- scope.launch {- epgSourceRepository.getAllSources().collect { sources ->- uiState.update { it.copy(epgSources = sources) }- }- }- }+ // Tracks the active assignment-collector job per provider so recompositions+ // cancel the old coroutine rather than leaking it in viewModelScope.+ private val assignmentJobs = ConcurrentHashMap<Long, Job>()fun loadEpgAssignments(scope: CoroutineScope, providerId: Long) {- scope.launch {+ assignmentJobs[providerId]?.cancel()+ assignmentJobs[providerId] = scope.launch {epgSourceRepository.getAssignmentsForProvider(providerId).collect { assignments ->val summary = epgSourceRepository.getResolutionSummary(providerId)uiState.update {@@ -44,7 +43,10 @@ internal class SettingsEpgActions(fun deleteEpgSource(scope: CoroutineScope, sourceId: Long) {scope.launch {- val affectedProviders = loadedProvidersForSource(sourceId)+ uiState.update { it.copy(epgPendingDeleteSourceId = null) }+ // Query from the repository BEFORE deletion so we capture all affected+ // providers, not just those already loaded into the UI state.+ val affectedProviders = epgSourceRepository.getProviderIdsForSource(sourceId)epgSourceRepository.deleteSource(sourceId)refreshLoadedResolutionSummaries(affectedProviders)}@@ -52,7 +54,9 @@ internal class SettingsEpgActions(fun toggleEpgSourceEnabled(scope: CoroutineScope, sourceId: Long, enabled: Boolean) {scope.launch {- val affectedProviders = loadedProvidersForSource(sourceId)+ // Query from the repository so all assigned providers are refreshed regardless+ // of which ones have been opened in the UI.+ val affectedProviders = epgSourceRepository.getProviderIdsForSource(sourceId)epgSourceRepository.setSourceEnabled(sourceId, enabled)refreshLoadedResolutionSummaries(affectedProviders)}@@ -60,7 +64,7 @@ internal class SettingsEpgActions(fun refreshEpgSource(scope: CoroutineScope, sourceId: Long) {scope.launch {- uiState.update { it.copy(isSyncing = true) }+ uiState.update { it.copy(refreshingEpgSourceIds = it.refreshingEpgSourceIds + sourceId) }val affectedProviders = loadedProvidersForSource(sourceId)val result = epgSourceRepository.refreshSource(sourceId)if (result !is Result.Error) {@@ -68,7 +72,7 @@ internal class SettingsEpgActions(}uiState.update {it.copy(- isSyncing = false,+ refreshingEpgSourceIds = it.refreshingEpgSourceIds - sourceId,userMessage = if (result is Result.Error) result.message else "EPG source refreshed")}@@ -102,8 +106,11 @@ internal class SettingsEpgActions(if (index <= 0) return@launchval current = assignments[index]val previous = assignments[index - 1]- epgSourceRepository.updateAssignmentPriority(providerId, current.epgSourceId, previous.priority)- epgSourceRepository.updateAssignmentPriority(providerId, previous.epgSourceId, current.priority)+ epgSourceRepository.swapAssignmentPriorities(+ providerId,+ current.epgSourceId, previous.priority,+ previous.epgSourceId, current.priority+ )refreshProviderEpgSummary(providerId)}}@@ -115,8 +122,11 @@ internal class SettingsEpgActions(if (index == -1 || index >= assignments.lastIndex) return@launchval current = assignments[index]val next = assignments[index + 1]- epgSourceRepository.updateAssignmentPriority(providerId, current.epgSourceId, next.priority)- epgSourceRepository.updateAssignmentPriority(providerId, next.epgSourceId, current.priority)+ epgSourceRepository.swapAssignmentPriorities(+ providerId,+ current.epgSourceId, next.priority,+ next.epgSourceId, current.priority+ )refreshProviderEpgSummary(providerId)}}diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsEpgSection.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsEpgSection.ktindex 971d1604..719a9bea 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsEpgSection.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsEpgSection.kt@@ -2,11 +2,13 @@ package com.streamvault.app.ui.screens.settingsimport androidx.activity.compose.rememberLauncherForActivityResultimport androidx.activity.result.contract.ActivityResultContracts+import androidx.compose.foundation.BorderStrokeimport androidx.compose.foundation.backgroundimport androidx.compose.foundation.layout.Arrangementimport androidx.compose.foundation.layout.Boximport androidx.compose.foundation.layout.Columnimport androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.FlowRowimport androidx.compose.foundation.layout.Spacerimport androidx.compose.foundation.layout.fillMaxWidthimport androidx.compose.foundation.layout.padding@@ -26,10 +28,12 @@ import androidx.compose.ui.graphics.Colorimport androidx.compose.ui.platform.LocalContextimport androidx.compose.ui.text.font.FontWeightimport androidx.compose.ui.unit.dp+import androidx.tv.material3.Borderimport androidx.tv.material3.ClickableSurfaceDefaultsimport androidx.tv.material3.MaterialThemeimport androidx.tv.material3.Textimport androidx.compose.foundation.lazy.items+import com.streamvault.app.ui.design.FocusSpecimport com.streamvault.app.ui.interaction.TvClickableSurfaceimport com.streamvault.app.ui.theme.OnSurfaceDimimport com.streamvault.app.ui.theme.Primary@@ -85,19 +89,21 @@ internal fun LazyListScope.epgSourcesSection(if (source.lastError != null) {Text("Error: ${source.lastError}", style = MaterialTheme.typography.bodySmall, color = Color(0xFFEF5350))}- if (source.lastSuccessAt != null) {+ if (source.lastSuccessAt > 0L) {val ago = (System.currentTimeMillis() - source.lastSuccessAt) / 60000Text("Last synced: ${ago}m ago", style = MaterialTheme.typography.bodySmall, color = OnSurfaceDim)}}+ val sourceActionShape = RoundedCornerShape(8.dp)Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {TvClickableSurface(onClick = { viewModel.toggleEpgSourceEnabled(source.id, !source.enabled) },- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(8.dp)),+ shape = ClickableSurfaceDefaults.shape(sourceActionShape),colors = ClickableSurfaceDefaults.colors(containerColor = if (source.enabled) Color(0xFF66BB6A).copy(alpha = 0.2f) else Color.White.copy(alpha = 0.08f),focusedContainerColor = if (source.enabled) Color(0xFF66BB6A).copy(alpha = 0.4f) else Color.White.copy(alpha = 0.15f)),+ border = epgActionBorder(sourceActionShape),scale = ClickableSurfaceDefaults.scale(focusedScale = 1f)) {Text(@@ -109,25 +115,60 @@ internal fun LazyListScope.epgSourcesSection(}TvClickableSurface(onClick = { viewModel.refreshEpgSource(source.id) },- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(8.dp)),+ shape = ClickableSurfaceDefaults.shape(sourceActionShape),colors = ClickableSurfaceDefaults.colors(containerColor = Primary.copy(alpha = 0.15f),focusedContainerColor = Primary.copy(alpha = 0.3f)),- scale = ClickableSurfaceDefaults.scale(focusedScale = 1f)+ border = epgActionBorder(sourceActionShape, enabled = source.id !in uiState.refreshingEpgSourceIds),+ scale = ClickableSurfaceDefaults.scale(focusedScale = 1f),+ enabled = source.id !in uiState.refreshingEpgSourceIds) {- Text("Refresh", modifier = Modifier.padding(horizontal = 12.dp, vertical = 6.dp), style = MaterialTheme.typography.labelSmall, color = Primary)+ Text(+ if (source.id in uiState.refreshingEpgSourceIds) "..." else "Refresh",+ modifier = Modifier.padding(horizontal = 12.dp, vertical = 6.dp),+ style = MaterialTheme.typography.labelSmall,+ color = Primary+ )}- TvClickableSurface(- onClick = { viewModel.deleteEpgSource(source.id) },- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(8.dp)),- colors = ClickableSurfaceDefaults.colors(- containerColor = Color(0xFFEF5350).copy(alpha = 0.12f),- focusedContainerColor = Color(0xFFEF5350).copy(alpha = 0.25f)- ),- scale = ClickableSurfaceDefaults.scale(focusedScale = 1f)- ) {- Text("Delete", modifier = Modifier.padding(horizontal = 12.dp, vertical = 6.dp), style = MaterialTheme.typography.labelSmall, color = Color(0xFFEF5350))+ if (uiState.epgPendingDeleteSourceId == source.id) {+ TvClickableSurface(+ onClick = { viewModel.setPendingDeleteEpgSource(null) },+ shape = ClickableSurfaceDefaults.shape(sourceActionShape),+ colors = ClickableSurfaceDefaults.colors(+ containerColor = Color.White.copy(alpha = 0.08f),+ focusedContainerColor = Color.White.copy(alpha = 0.15f)+ ),+ border = epgActionBorder(sourceActionShape),+ scale = ClickableSurfaceDefaults.scale(focusedScale = 1f)+ ) {+ Text("Cancel", modifier = Modifier.padding(horizontal = 12.dp, vertical = 6.dp), style = MaterialTheme.typography.labelSmall, color = OnSurfaceDim)+ }+ TvClickableSurface(+ onClick = { viewModel.deleteEpgSource(source.id) },+ shape = ClickableSurfaceDefaults.shape(sourceActionShape),+ colors = ClickableSurfaceDefaults.colors(+ containerColor = Color(0xFFEF5350).copy(alpha = 0.25f),+ focusedContainerColor = Color(0xFFEF5350).copy(alpha = 0.45f)+ ),+ border = epgActionBorder(sourceActionShape),+ scale = ClickableSurfaceDefaults.scale(focusedScale = 1f)+ ) {+ Text("Confirm Delete", modifier = Modifier.padding(horizontal = 12.dp, vertical = 6.dp), style = MaterialTheme.typography.labelSmall, color = Color(0xFFEF5350))+ }+ } else {+ TvClickableSurface(+ onClick = { viewModel.setPendingDeleteEpgSource(source.id) },+ shape = ClickableSurfaceDefaults.shape(sourceActionShape),+ colors = ClickableSurfaceDefaults.colors(+ containerColor = Color(0xFFEF5350).copy(alpha = 0.12f),+ focusedContainerColor = Color(0xFFEF5350).copy(alpha = 0.25f)+ ),+ border = epgActionBorder(sourceActionShape),+ scale = ClickableSurfaceDefaults.scale(focusedScale = 1f)+ ) {+ Text("Delete", modifier = Modifier.padding(horizontal = 12.dp, vertical = 6.dp), style = MaterialTheme.typography.labelSmall, color = Color(0xFFEF5350))+ }}}}@@ -171,8 +212,18 @@ internal fun LazyListScope.epgSourcesSection(Text(provider.name, style = MaterialTheme.typography.titleSmall, color = Color.White)if (resolutionSummary != null) {val matchedChannels = (resolutionSummary.totalChannels - resolutionSummary.unresolvedChannels).coerceAtLeast(0)+ val summaryParts = buildList {+ add("Matched $matchedChannels/${resolutionSummary.totalChannels} channels")+ if (resolutionSummary.exactIdMatches > 0) add("${resolutionSummary.exactIdMatches} exact")+ if (resolutionSummary.normalizedNameMatches > 0) add("${resolutionSummary.normalizedNameMatches} name")+ if (resolutionSummary.providerNativeMatches > 0) add("${resolutionSummary.providerNativeMatches} provider")+ if (resolutionSummary.manualMatches > 0) add("${resolutionSummary.manualMatches} manual")+ if (resolutionSummary.unresolvedChannels > 0) add("${resolutionSummary.unresolvedChannels} without EPG")+ if (resolutionSummary.lowConfidenceChannels > 0) add("${resolutionSummary.lowConfidenceChannels} weak")+ if (resolutionSummary.rematchCandidateChannels > 0) add("${resolutionSummary.rematchCandidateChannels} need review")+ }Text(- text = "Matched $matchedChannels/${resolutionSummary.totalChannels} channels - ${resolutionSummary.exactIdMatches} exact - ${resolutionSummary.normalizedNameMatches} name - ${resolutionSummary.providerNativeMatches} provider",+ text = summaryParts.joinToString(" \u2022 "),style = MaterialTheme.typography.bodySmall,color = OnSurfaceDim)@@ -189,16 +240,18 @@ internal fun LazyListScope.epgSourcesSection(color = Color.White,modifier = Modifier.weight(1f))+ val priorityActionShape = RoundedCornerShape(6.dp)Row(horizontalArrangement = Arrangement.spacedBy(6.dp), verticalAlignment = Alignment.CenterVertically) {TvClickableSurface(onClick = { viewModel.moveEpgSourceAssignmentUp(provider.id, assignment.epgSourceId) },enabled = assignmentIndex > 0,- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(6.dp)),+ shape = ClickableSurfaceDefaults.shape(priorityActionShape),colors = ClickableSurfaceDefaults.colors(containerColor = Color.White.copy(alpha = 0.08f),focusedContainerColor = Color.White.copy(alpha = 0.16f),disabledContainerColor = Color.White.copy(alpha = 0.04f)),+ border = epgActionBorder(priorityActionShape, enabled = assignmentIndex > 0),scale = ClickableSurfaceDefaults.scale(focusedScale = 1f)) {Text("Up", modifier = Modifier.padding(horizontal = 8.dp, vertical = 4.dp), style = MaterialTheme.typography.labelSmall, color = Color.White)@@ -206,12 +259,13 @@ internal fun LazyListScope.epgSourcesSection(TvClickableSurface(onClick = { viewModel.moveEpgSourceAssignmentDown(provider.id, assignment.epgSourceId) },enabled = assignmentIndex < assignments.lastIndex,- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(6.dp)),+ shape = ClickableSurfaceDefaults.shape(priorityActionShape),colors = ClickableSurfaceDefaults.colors(containerColor = Color.White.copy(alpha = 0.08f),focusedContainerColor = Color.White.copy(alpha = 0.16f),disabledContainerColor = Color.White.copy(alpha = 0.04f)),+ border = epgActionBorder(priorityActionShape, enabled = assignmentIndex < assignments.lastIndex),scale = ClickableSurfaceDefaults.scale(focusedScale = 1f)) {Text("Down", modifier = Modifier.padding(horizontal = 8.dp, vertical = 4.dp), style = MaterialTheme.typography.labelSmall, color = Color.White)@@ -220,11 +274,12 @@ internal fun LazyListScope.epgSourcesSection(Spacer(modifier = Modifier.width(6.dp))TvClickableSurface(onClick = { viewModel.unassignEpgSourceFromProvider(provider.id, assignment.epgSourceId) },- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(6.dp)),+ shape = ClickableSurfaceDefaults.shape(priorityActionShape),colors = ClickableSurfaceDefaults.colors(containerColor = Color(0xFFEF5350).copy(alpha = 0.12f),focusedContainerColor = Color(0xFFEF5350).copy(alpha = 0.25f)),+ border = epgActionBorder(priorityActionShape),scale = ClickableSurfaceDefaults.scale(focusedScale = 1f)) {Text("Remove", modifier = Modifier.padding(horizontal = 8.dp, vertical = 4.dp), style = MaterialTheme.typography.labelSmall, color = Color(0xFFEF5350))@@ -234,15 +289,20 @@ internal fun LazyListScope.epgSourcesSection(}if (unassignedSources.isNotEmpty()) {- Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {+ FlowRow(+ horizontalArrangement = Arrangement.spacedBy(8.dp),+ verticalArrangement = Arrangement.spacedBy(6.dp)+ ) {unassignedSources.forEach { source ->+ val assignActionShape = RoundedCornerShape(8.dp)TvClickableSurface(onClick = { viewModel.assignEpgSourceToProvider(provider.id, source.id) },- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(8.dp)),+ shape = ClickableSurfaceDefaults.shape(assignActionShape),colors = ClickableSurfaceDefaults.colors(containerColor = Color(0xFF66BB6A).copy(alpha = 0.12f),focusedContainerColor = Color(0xFF66BB6A).copy(alpha = 0.25f)),+ border = epgActionBorder(assignActionShape),scale = ClickableSurfaceDefaults.scale(focusedScale = 1f)) {Text("+ ${source.name}", modifier = Modifier.padding(horizontal = 12.dp, vertical = 6.dp), style = MaterialTheme.typography.labelSmall, color = Color(0xFF66BB6A))@@ -290,21 +350,24 @@ private fun AddEpgSourceCard(viewModel: SettingsViewModel) {EpgSourceTextField(value = newUrl,onValueChange = { newUrl = it },- placeholder = "XMLTV URL (HTTPS) or browse file"+ placeholder = "XMLTV URL (HTTP/HTTPS) or browse file")}+ val addActionShape = RoundedCornerShape(8.dp)TvClickableSurface(onClick = { filePickerLauncher.launch(arrayOf("*/*")) },- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(8.dp)),+ shape = ClickableSurfaceDefaults.shape(addActionShape),colors = ClickableSurfaceDefaults.colors(containerColor = Primary.copy(alpha = 0.15f),focusedContainerColor = Primary.copy(alpha = 0.3f)),+ border = epgActionBorder(addActionShape),scale = ClickableSurfaceDefaults.scale(focusedScale = 1f)) {Text("Browse", modifier = Modifier.padding(horizontal = 12.dp, vertical = 10.dp), style = MaterialTheme.typography.labelMedium, color = Primary)}}+ val addSourceShape = RoundedCornerShape(8.dp)TvClickableSurface(onClick = {if (newName.isNotBlank() && newUrl.isNotBlank()) {@@ -313,11 +376,12 @@ private fun AddEpgSourceCard(viewModel: SettingsViewModel) {newUrl = ""}},- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(8.dp)),+ shape = ClickableSurfaceDefaults.shape(addSourceShape),colors = ClickableSurfaceDefaults.colors(containerColor = Color(0xFF66BB6A).copy(alpha = 0.2f),focusedContainerColor = Color(0xFF66BB6A).copy(alpha = 0.4f)),+ border = epgActionBorder(addSourceShape),scale = ClickableSurfaceDefaults.scale(focusedScale = 1f)) {Text("Add Source", modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp), color = Color(0xFF66BB6A), fontWeight = FontWeight.Medium)@@ -326,6 +390,19 @@ private fun AddEpgSourceCard(viewModel: SettingsViewModel) {}}+@Composable+private fun epgActionBorder(shape: RoundedCornerShape, enabled: Boolean = true) =+ ClickableSurfaceDefaults.border(+ border = Border(+ border = BorderStroke(1.dp, Color.White.copy(alpha = if (enabled) 0.08f else 0.04f)),+ shape = shape+ ),+ focusedBorder = Border(+ border = BorderStroke(FocusSpec.BorderWidth, Color.White),+ shape = shape+ )+ )+private fun displayableEpgUrl(url: String): String = when {url.startsWith("content://") -> {val lastSegment = try { android.net.Uri.parse(url).lastPathSegment } catch (_: Exception) { null }diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsProviderComponents.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsProviderComponents.ktindex 72f0a06a..11077ec4 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsProviderComponents.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsProviderComponents.kt@@ -28,6 +28,7 @@ import androidx.compose.ui.focus.onFocusChangedimport androidx.compose.ui.graphics.Colorimport androidx.compose.ui.graphics.SolidColorimport androidx.compose.ui.input.key.onPreviewKeyEvent+import androidx.compose.ui.platform.LocalDensityimport androidx.compose.ui.platform.LocalSoftwareKeyboardControllerimport androidx.compose.ui.res.stringResourceimport androidx.compose.ui.text.TextRange@@ -619,6 +620,7 @@ internal fun ProviderSettingsCard(isActive: Boolean,isSyncing: Boolean,diagnostics: ProviderDiagnosticsUiModel?,+ databaseMaintenance: DatabaseMaintenanceUiModel?,syncWarnings: List<String>,onRetryWarningAction: (ProviderWarningAction) -> Unit,onConnect: () -> Unit,@@ -712,7 +714,8 @@ internal fun ProviderSettingsCard(ProviderDiagnosticsPanel(provider = provider,- diagnostics = model+ diagnostics = model,+ databaseMaintenance = databaseMaintenance)}@@ -1145,7 +1148,8 @@ internal fun SettingsOverviewCard(@Composableprivate fun ProviderDiagnosticsPanel(provider: Provider,- diagnostics: ProviderDiagnosticsUiModel+ diagnostics: ProviderDiagnosticsUiModel,+ databaseMaintenance: DatabaseMaintenanceUiModel?) {Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {Text(@@ -1202,6 +1206,96 @@ private fun ProviderDiagnosticsPanel(style = MaterialTheme.typography.labelSmall,color = OnSurface)+ diagnostics.healthSummary(provider.type)?.let { summary ->+ Text(+ text = summary,+ style = MaterialTheme.typography.bodySmall,+ color = ErrorColor,+ fontWeight = FontWeight.Medium+ )+ }+ databaseMaintenance?.let { report ->+ DatabaseMaintenancePanel(report = report)+ }+ }+}++@Composable+private fun DatabaseMaintenancePanel(report: DatabaseMaintenanceUiModel) {+ Column(+ modifier = Modifier+ .fillMaxWidth()+ .background(Color.White.copy(alpha = 0.04f), RoundedCornerShape(10.dp))+ .padding(12.dp),+ verticalArrangement = Arrangement.spacedBy(6.dp)+ ) {+ Text(+ text = "Database Health",+ style = MaterialTheme.typography.titleSmall,+ color = Primary+ )+ Text(+ text = "Last maintenance ${formatDiagnosticTimestamp(report.ranAt)}",+ style = MaterialTheme.typography.bodySmall,+ color = OnSurface+ )+ Text(+ text = buildString {+ append("Pruned ")+ append(report.deletedPrograms)+ append(" internal programs, ")+ append(report.deletedExternalProgrammes)+ append(" external programs, ")+ append(report.deletedOrphanEpisodes)+ append(" orphan episodes, and ")+ append(report.deletedStaleFavorites)+ append(" stale favorites.")+ },+ style = MaterialTheme.typography.bodySmall,+ color = OnSurfaceDim+ )+ Text(+ text = buildString {+ append("Main DB ")+ append(formatMaintenanceBytes(report.mainDbBytes))+ append(" • WAL ")+ append(formatMaintenanceBytes(report.walBytes))+ append(" • Reclaimable ")+ append(formatMaintenanceBytes(report.reclaimableBytes))+ append(" • VACUUM ")+ append(if (report.vacuumRan) "ran" else "not needed or skipped")+ },+ style = MaterialTheme.typography.bodySmall,+ color = OnSurface+ )+ Text(+ text = buildString {+ append("Rows: channels ")+ append(formatMaintenanceCount(report.channelRows))+ append(", movies ")+ append(formatMaintenanceCount(report.movieRows))+ append(", series ")+ append(formatMaintenanceCount(report.seriesRows))+ append(", episodes ")+ append(formatMaintenanceCount(report.episodeRows))+ },+ style = MaterialTheme.typography.bodySmall,+ color = OnSurfaceDim+ )+ Text(+ text = buildString {+ append("Programs ")+ append(formatMaintenanceCount(report.programRows))+ append(", external EPG ")+ append(formatMaintenanceCount(report.epgProgrammeRows))+ append(", history ")+ append(formatMaintenanceCount(report.playbackHistoryRows))+ append(", favorites ")+ append(formatMaintenanceCount(report.favoriteRows))+ },+ style = MaterialTheme.typography.bodySmall,+ color = OnSurfaceDim+ )}}@@ -1211,13 +1305,7 @@ private fun ProviderDiagnosticPill(count: Int,timestamp: Long) {- val syncLabel = remember(timestamp) {- if (timestamp <= 0L) {- null- } else {- java.text.SimpleDateFormat("MMM d, HH:mm", java.util.Locale.getDefault()).format(java.util.Date(timestamp))- }- }+ val syncLabel = remember(timestamp) { formatDiagnosticTimestamp(timestamp) }Surface(shape = RoundedCornerShape(10.dp),colors = SurfaceDefaults.colors(@@ -1247,6 +1335,70 @@ private fun ProviderDiagnosticPill(}}+private fun ProviderDiagnosticsUiModel.healthSummary(providerType: ProviderType): String? {+ val warnings = buildList {+ if (liveSequentialFailuresRemembered) {+ add("Live sync needs attention")+ }+ if (movieParallelFailuresRemembered) {+ add(+ if (movieWarningsCount > 0) {+ "Movies have $movieWarningsCount remembered warning(s)"+ } else {+ "Movie sync still has remembered warnings"+ }+ )+ }+ if (movieCatalogStale) {+ add("Movie catalog is running stale")+ }+ if (providerType == ProviderType.XTREAM_CODES && seriesSequentialFailuresRemembered) {+ add("Series sync needs attention")+ }+ }+ if (warnings.isEmpty()) {+ val streakParts = buildList {+ if (liveHealthySyncStreak > 0) add("Live streak $liveHealthySyncStreak")+ if (movieHealthySyncStreak > 0) add("Movies streak $movieHealthySyncStreak")+ if (providerType == ProviderType.XTREAM_CODES && seriesHealthySyncStreak > 0) {+ add("Series streak $seriesHealthySyncStreak")+ }+ }+ return streakParts.takeIf { it.isNotEmpty() }?.joinToString(" • ")+ }+ return warnings.joinToString(" • ")+}++private fun formatDiagnosticTimestamp(timestamp: Long): String? =+ if (timestamp <= 0L) {+ null+ } else {+ java.text.SimpleDateFormat("MMM d, HH:mm", java.util.Locale.getDefault()).format(java.util.Date(timestamp))+ }++private fun formatMaintenanceBytes(bytes: Long): String {+ if (bytes <= 0L) return "0 B"+ val units = arrayOf("B", "KB", "MB", "GB", "TB")+ var value = bytes.toDouble()+ var unitIndex = 0+ while (value >= 1024.0 && unitIndex < units.lastIndex) {+ value /= 1024.0+ unitIndex+++ }+ val formatted = if (value >= 10 || unitIndex == 0) {+ value.toInt().toString()+ } else {+ String.format(Locale.US, "%.1f", value)+ }+ return "$formatted ${units[unitIndex]}"+}++private fun formatMaintenanceCount(value: Long): String = when {+ value >= 1_000_000L -> String.format(Locale.US, "%.1fM", value / 1_000_000.0)+ value >= 1_000L -> String.format(Locale.US, "%.1fk", value / 1_000.0)+ else -> value.toString()+}+@Composableinternal fun SettingsOverviewStat(label: String,@@ -1333,6 +1485,16 @@ internal fun EpgSourceTextField(}val isFocused = hasContainerFocus || hasInputFocus+ // Re-call bringIntoView on every frame of the keyboard animation so the+ // LazyColumn keeps scrolling the focused field into view as imePadding shrinks.+ val density = LocalDensity.current+ val imeBottom = WindowInsets.ime.getBottom(density)+ LaunchedEffect(imeBottom) {+ if ((hasInputFocus || hasContainerFocus) && imeBottom > 0) {+ runCatching { bringIntoViewRequester.bringIntoView() }+ }+ }+fun requestBringIntoView(delayMillis: Long = 0L) {coroutineScope.launch {if (delayMillis > 0) {diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsProviderSection.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsProviderSection.ktindex 066b9315..b1f39dc2 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsProviderSection.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsProviderSection.kt@@ -95,6 +95,7 @@ internal fun LazyListScope.providerSection(isActive = selectedProvider.id == uiState.activeProviderId,isSyncing = uiState.isSyncing,diagnostics = uiState.diagnosticsByProvider[selectedProvider.id],+ databaseMaintenance = uiState.databaseMaintenance,syncWarnings = uiState.syncWarningsByProvider[selectedProvider.id].orEmpty(),onRetryWarningAction = { action -> viewModel.retryWarningAction(selectedProvider.id, action) },onConnect = { viewModel.setActiveProvider(selectedProvider.id) },diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsRecordingComponents.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsRecordingComponents.ktindex b3ff6f02..8eaa556c 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsRecordingComponents.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsRecordingComponents.kt@@ -2,6 +2,8 @@ package com.streamvault.app.ui.screens.settingsimport androidx.compose.foundation.BorderStrokeimport androidx.compose.foundation.background+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.itemsimport androidx.compose.foundation.layout.*import androidx.compose.foundation.shape.RoundedCornerShapeimport androidx.compose.material3.CircularProgressIndicator@@ -15,14 +17,18 @@ import androidx.compose.runtime.setValueimport androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifierimport androidx.compose.ui.focus.FocusRequester+import androidx.compose.ui.focus.onFocusChangedimport androidx.compose.ui.focus.focusRequesterimport androidx.compose.ui.graphics.Colorimport androidx.compose.ui.text.font.FontWeightimport androidx.compose.ui.text.style.TextOverflowimport androidx.compose.ui.unit.dpimport androidx.compose.ui.res.stringResource+import androidx.compose.ui.window.Dialog+import androidx.compose.ui.window.DialogPropertiesimport androidx.tv.material3.*import com.streamvault.app.R+import com.streamvault.app.ui.components.TvEmptyStateimport com.streamvault.app.ui.components.dialogs.PremiumDialogimport com.streamvault.app.ui.components.dialogs.PremiumDialogActionButtonimport com.streamvault.app.ui.components.dialogs.PremiumDialogFooterButton@@ -328,6 +334,7 @@ internal fun RecordingOverviewCard(onChangePattern: () -> Unit,onChangeRetention: () -> Unit,onChangeConcurrency: () -> Unit,+ onOpenBrowser: () -> Unit,onRepairSchedule: () -> Unit) {Surface(@@ -337,25 +344,48 @@ internal fun RecordingOverviewCard() {Column(modifier = Modifier.padding(20.dp),- verticalArrangement = Arrangement.spacedBy(14.dp)+ verticalArrangement = Arrangement.spacedBy(16.dp)) {- Text(- text = stringResource(R.string.settings_recording_storage_title),- style = MaterialTheme.typography.titleMedium,- color = Primary- )- treeLabel?.takeIf { it.isNotBlank() }?.let {- Text(- text = it,- style = MaterialTheme.typography.bodySmall,- color = Secondary+ Row(+ modifier = Modifier.fillMaxWidth(),+ horizontalArrangement = Arrangement.SpaceBetween,+ verticalAlignment = Alignment.Top+ ) {+ Column(+ modifier = Modifier.weight(1f),+ verticalArrangement = Arrangement.spacedBy(6.dp)+ ) {+ Text(+ text = stringResource(R.string.settings_recording_storage_title),+ style = MaterialTheme.typography.titleMedium,+ color = Primary+ )+ treeLabel?.takeIf { it.isNotBlank() }?.let {+ Text(+ text = it,+ style = MaterialTheme.typography.bodySmall,+ color = Secondary,+ maxLines = 1,+ overflow = TextOverflow.Ellipsis+ )+ }+ Text(+ text = outputDirectory ?: stringResource(R.string.settings_recording_storage_unknown),+ style = MaterialTheme.typography.bodySmall,+ color = OnSurfaceDim,+ maxLines = 2,+ overflow = TextOverflow.Ellipsis+ )+ }+ StatusTonePill(+ label = if (isWritable) {+ stringResource(R.string.settings_recording_storage_ready)+ } else {+ stringResource(R.string.settings_recording_storage_unavailable)+ },+ accent = if (isWritable) OnSurface else ErrorColor)}- Text(- text = outputDirectory ?: stringResource(R.string.settings_recording_storage_unknown),- style = MaterialTheme.typography.bodySmall,- color = OnSurfaceDim- )Row(modifier = Modifier.fillMaxWidth(),horizontalArrangement = Arrangement.spacedBy(12.dp)@@ -376,11 +406,6 @@ internal fun RecordingOverviewCard(modifier = Modifier.weight(1f))}- Text(- text = if (isWritable) stringResource(R.string.settings_recording_storage_ready) else stringResource(R.string.settings_recording_storage_unavailable),- style = MaterialTheme.typography.bodySmall,- color = if (isWritable) Primary else ErrorColor- )FlowRow(horizontalArrangement = Arrangement.spacedBy(10.dp),verticalArrangement = Arrangement.spacedBy(10.dp)@@ -400,23 +425,623 @@ internal fun RecordingOverviewCard(value = maxSimultaneousRecordings.toString())}+ Column(+ modifier = Modifier.fillMaxWidth(),+ verticalArrangement = Arrangement.spacedBy(10.dp)+ ) {+ Row(+ modifier = Modifier.fillMaxWidth(),+ horizontalArrangement = Arrangement.spacedBy(10.dp)+ ) {+ RecordingActionButton(+ label = stringResource(R.string.settings_recording_choose_folder),+ accent = OnBackground,+ modifier = Modifier.weight(1f),+ onClick = onChooseFolder+ )+ RecordingActionButton(+ label = stringResource(R.string.settings_recording_use_app_storage),+ accent = OnBackground,+ modifier = Modifier.weight(1f),+ onClick = onUseAppStorage+ )+ }+ Row(+ modifier = Modifier.fillMaxWidth(),+ horizontalArrangement = Arrangement.spacedBy(10.dp)+ ) {+ RecordingActionButton(+ label = stringResource(R.string.settings_recording_pattern_title),+ accent = OnBackground,+ modifier = Modifier.weight(1f),+ onClick = onChangePattern+ )+ RecordingActionButton(+ label = stringResource(R.string.settings_recording_retention_title),+ accent = OnBackground,+ modifier = Modifier.weight(1f),+ onClick = onChangeRetention+ )+ RecordingActionButton(+ label = stringResource(R.string.settings_recording_concurrency_title),+ accent = OnBackground,+ modifier = Modifier.weight(1f),+ onClick = onChangeConcurrency+ )+ }+ Row(+ modifier = Modifier.fillMaxWidth(),+ horizontalArrangement = Arrangement.spacedBy(10.dp)+ ) {+ RecordingActionButton(+ label = stringResource(R.string.settings_recording_open_browser),+ accent = OnBackground,+ modifier = Modifier.weight(1f),+ onClick = onOpenBrowser+ )+ RecordingActionButton(+ label = stringResource(R.string.settings_recording_reconcile),+ accent = OnBackground,+ modifier = Modifier.weight(1f),+ onClick = onRepairSchedule+ )+ }+ }+ }+ }+}++@OptIn(ExperimentalLayoutApi::class)+@Composable+internal fun RecordingDashboardSection(+ treeLabel: String?,+ outputDirectory: String?,+ availableBytes: Long?,+ isWritable: Boolean,+ activeCount: Int,+ scheduledCount: Int,+ fileNamePattern: String,+ retentionDays: Int?,+ maxSimultaneousRecordings: Int,+ onChooseFolder: () -> Unit,+ onUseAppStorage: () -> Unit,+ onChangePattern: () -> Unit,+ onChangeRetention: () -> Unit,+ onChangeConcurrency: () -> Unit,+ onRepairSchedule: () -> Unit,+ onOpenBrowser: () -> Unit+) {+ RecordingOverviewCard(+ treeLabel = treeLabel,+ outputDirectory = outputDirectory,+ availableBytes = availableBytes,+ isWritable = isWritable,+ activeCount = activeCount,+ scheduledCount = scheduledCount,+ fileNamePattern = fileNamePattern,+ retentionDays = retentionDays,+ maxSimultaneousRecordings = maxSimultaneousRecordings,+ onChooseFolder = onChooseFolder,+ onUseAppStorage = onUseAppStorage,+ onChangePattern = onChangePattern,+ onChangeRetention = onChangeRetention,+ onChangeConcurrency = onChangeConcurrency,+ onOpenBrowser = onOpenBrowser,+ onRepairSchedule = onRepairSchedule+ )+}++@OptIn(ExperimentalLayoutApi::class)+@Composable+internal fun RecordingBrowserDialog(+ recordingItems: List<RecordingItem>,+ selectedRecordingId: String?,+ onSelectedRecordingChange: (String) -> Unit,+ onDismiss: () -> Unit,+ onPlay: (RecordingItem) -> Unit,+ onStop: (RecordingItem) -> Unit,+ onCancel: (RecordingItem) -> Unit,+ onDelete: (RecordingItem) -> Unit,+ onRetry: (RecordingItem) -> Unit,+ onToggleSchedule: (RecordingItem, Boolean) -> Unit+) {+ Dialog(+ onDismissRequest = onDismiss,+ properties = DialogProperties(+ dismissOnBackPress = true,+ dismissOnClickOutside = false,+ usePlatformDefaultWidth = false+ )+ ) {+ Box(+ modifier = Modifier+ .fillMaxSize()+ .background(Color.Black.copy(alpha = 0.68f)),+ contentAlignment = Alignment.Center+ ) {+ Surface(+ modifier = Modifier+ .fillMaxWidth(0.93f)+ .fillMaxHeight(0.9f),+ colors = SurfaceDefaults.colors(containerColor = SurfaceElevated),+ shape = RoundedCornerShape(22.dp)+ ) {+ Column(+ modifier = Modifier.fillMaxSize().padding(20.dp),+ verticalArrangement = Arrangement.spacedBy(16.dp)+ ) {+ Row(+ modifier = Modifier.fillMaxWidth(),+ horizontalArrangement = Arrangement.SpaceBetween,+ verticalAlignment = Alignment.CenterVertically+ ) {+ Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {+ Text(+ text = stringResource(R.string.settings_recording_title),+ style = MaterialTheme.typography.headlineSmall,+ color = OnBackground+ )+ Text(+ text = if (recordingItems.isNotEmpty()) {+ stringResource(R.string.settings_recording_item_count, recordingItems.size)+ } else {+ stringResource(R.string.settings_recording_empty_title)+ },+ style = MaterialTheme.typography.bodySmall,+ color = OnSurfaceDim+ )+ }+ CompactRecordingActionChip(+ label = stringResource(R.string.settings_cancel),+ accent = OnBackground,+ onClick = onDismiss+ )+ }++ if (recordingItems.isEmpty()) {+ Box(+ modifier = Modifier.fillMaxSize(),+ contentAlignment = Alignment.Center+ ) {+ TvEmptyState(+ title = stringResource(R.string.settings_recording_empty_title),+ subtitle = stringResource(R.string.settings_recording_empty_subtitle)+ )+ }+ } else {+ RecordingBrowserPanel(+ recordingItems = recordingItems,+ selectedRecordingId = selectedRecordingId,+ onSelectedRecordingChange = onSelectedRecordingChange,+ onPlay = onPlay,+ onStop = onStop,+ onCancel = onCancel,+ onDelete = onDelete,+ onRetry = onRetry,+ onToggleSchedule = onToggleSchedule+ )+ }+ }+ }+ }+ }+}++@OptIn(ExperimentalLayoutApi::class)+@Composable+private fun RecordingBrowserPanel(+ recordingItems: List<RecordingItem>,+ selectedRecordingId: String?,+ onSelectedRecordingChange: (String) -> Unit,+ onPlay: (RecordingItem) -> Unit,+ onStop: (RecordingItem) -> Unit,+ onCancel: (RecordingItem) -> Unit,+ onDelete: (RecordingItem) -> Unit,+ onRetry: (RecordingItem) -> Unit,+ onToggleSchedule: (RecordingItem, Boolean) -> Unit+) {+ val selectedItem = recordingItems.firstOrNull { it.id == selectedRecordingId } ?: recordingItems.first()++ Row(+ modifier = Modifier.fillMaxSize(),+ horizontalArrangement = Arrangement.spacedBy(16.dp),+ verticalAlignment = Alignment.Top+ ) {+ Surface(+ modifier = Modifier+ .width(380.dp)+ .fillMaxHeight(),+ colors = SurfaceDefaults.colors(containerColor = SurfaceElevated),+ shape = RoundedCornerShape(16.dp)+ ) {+ Column(+ modifier = Modifier.fillMaxSize().padding(14.dp),+ verticalArrangement = Arrangement.spacedBy(12.dp)+ ) {+ Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {+ Text(+ text = stringResource(R.string.settings_recording_title),+ style = MaterialTheme.typography.titleSmall,+ color = Primary+ )+ Text(+ text = "${recordingItems.size} items",+ style = MaterialTheme.typography.bodySmall,+ color = OnSurfaceDim+ )+ }+ LazyColumn(+ modifier = Modifier.fillMaxSize(),+ verticalArrangement = Arrangement.spacedBy(8.dp),+ contentPadding = PaddingValues(bottom = 4.dp)+ ) {+ items(recordingItems, key = { item -> item.id }) { item ->+ RecordingPickerRow(+ item = item,+ selected = item.id == selectedItem.id,+ onSelected = { onSelectedRecordingChange(item.id) }+ )+ }+ }+ }+ }++ RecordingDetailPanel(+ item = selectedItem,+ modifier = Modifier+ .weight(1f)+ .fillMaxHeight(),+ onPlay = { onPlay(selectedItem) },+ onStop = { onStop(selectedItem) },+ onCancel = { onCancel(selectedItem) },+ onDelete = { onDelete(selectedItem) },+ onRetry = { onRetry(selectedItem) },+ onToggleSchedule = { enabled -> onToggleSchedule(selectedItem, enabled) }+ )+ }+}++@Composable+private fun RecordingPickerRow(+ item: RecordingItem,+ selected: Boolean,+ onSelected: () -> Unit+) {+ val accent = recordingStatusAccent(item.status)+ TvClickableSurface(+ onClick = onSelected,+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(12.dp)),+ colors = ClickableSurfaceDefaults.colors(+ containerColor = if (selected) accent.copy(alpha = 0.14f) else Color.Transparent,+ contentColor = OnBackground,+ focusedContainerColor = SurfaceHighlight.copy(alpha = 0.48f),+ focusedContentColor = OnBackground+ ),+ border = ClickableSurfaceDefaults.border(+ border = Border(+ border = BorderStroke(+ 1.dp,+ if (selected) accent.copy(alpha = 0.55f) else Color.White.copy(alpha = 0.08f)+ ),+ shape = RoundedCornerShape(12.dp)+ ),+ focusedBorder = Border(+ border = BorderStroke(FocusSpec.BorderWidth, Color.White),+ shape = RoundedCornerShape(12.dp)+ )+ ),+ scale = ClickableSurfaceDefaults.scale(focusedScale = 1f),+ modifier = Modifier+ .fillMaxWidth()+ .onFocusChanged { focusState ->+ if (focusState.isFocused) onSelected()+ }+ ) {+ Row(+ modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 10.dp),+ horizontalArrangement = Arrangement.spacedBy(10.dp),+ verticalAlignment = Alignment.CenterVertically+ ) {+ Box(+ modifier = Modifier+ .size(width = 5.dp, height = 36.dp)+ .background(accent.copy(alpha = 0.92f), RoundedCornerShape(999.dp))+ )+ Column(+ modifier = Modifier.weight(1f),+ verticalArrangement = Arrangement.spacedBy(3.dp)+ ) {+ Text(+ text = recordingDisplayTitle(item),+ style = MaterialTheme.typography.bodyMedium,+ color = OnBackground,+ maxLines = 1,+ overflow = TextOverflow.Ellipsis+ )+ Text(+ text = recordingListSecondaryLine(item),+ style = MaterialTheme.typography.labelSmall,+ color = OnSurfaceDim,+ maxLines = 1,+ overflow = TextOverflow.Ellipsis+ )+ }+ Text(+ text = recordingStatusLabel(item.status),+ style = MaterialTheme.typography.labelSmall,+ color = accent,+ maxLines = 1+ )+ }+ }+}++@OptIn(ExperimentalLayoutApi::class)+@Composable+private fun RecordingDetailPanel(+ item: RecordingItem,+ modifier: Modifier = Modifier,+ onPlay: () -> Unit,+ onStop: () -> Unit,+ onCancel: () -> Unit,+ onDelete: () -> Unit,+ onRetry: () -> Unit,+ onToggleSchedule: (Boolean) -> Unit+) {+ val accent = recordingStatusAccent(item.status)+ Surface(+ modifier = modifier,+ colors = SurfaceDefaults.colors(containerColor = SurfaceElevated),+ shape = RoundedCornerShape(16.dp)+ ) {+ Column(+ modifier = Modifier.fillMaxSize().padding(20.dp),+ verticalArrangement = Arrangement.spacedBy(16.dp)+ ) {+ Column(+ modifier = Modifier.fillMaxWidth(),+ verticalArrangement = Arrangement.spacedBy(10.dp)+ ) {+ Text(+ text = recordingDisplayTitle(item),+ style = MaterialTheme.typography.titleLarge,+ color = OnBackground,+ maxLines = 2,+ overflow = TextOverflow.Ellipsis+ )+ recordingDisplaySubtitle(item)?.let { subtitle ->+ Text(+ text = subtitle,+ style = MaterialTheme.typography.bodyMedium,+ color = OnSurfaceDim,+ maxLines = 1,+ overflow = TextOverflow.Ellipsis+ )+ }+ Row(+ horizontalArrangement = Arrangement.spacedBy(8.dp),+ verticalAlignment = Alignment.CenterVertically+ ) {+ StatusTonePill(+ label = recordingStatusLabel(item.status),+ accent = accent+ )+ if (item.recurrence != RecordingRecurrence.NONE) {+ StatusTonePill(+ label = when (item.recurrence) {+ RecordingRecurrence.DAILY -> stringResource(R.string.settings_recording_recurrence_daily)+ RecordingRecurrence.WEEKLY -> stringResource(R.string.settings_recording_recurrence_weekly)+ RecordingRecurrence.NONE -> stringResource(R.string.settings_recording_recurrence_none)+ },+ accent = Secondary+ )+ }+ }+ Text(+ text = stringResource(+ R.string.settings_recording_time_window,+ formatTimestamp(item.scheduledStartMs),+ formatTimestamp(item.scheduledEndMs)+ ),+ style = MaterialTheme.typography.bodySmall,+ color = OnSurface+ )+ }++ Row(+ modifier = Modifier.fillMaxWidth(),+ horizontalArrangement = Arrangement.spacedBy(10.dp)+ ) {+ RecordingMetricCard(+ modifier = Modifier.weight(1f),+ label = stringResource(R.string.settings_recording_source_label),+ value = formatRecordingSourceType(item.sourceType)+ )+ RecordingMetricCard(+ modifier = Modifier.weight(1f),+ label = stringResource(R.string.settings_recording_bytes_label),+ value = formatBytes(item.bytesWritten)+ )+ RecordingMetricCard(+ modifier = Modifier.weight(1f),+ label = stringResource(R.string.settings_recording_speed_label),+ value = if (item.averageThroughputBytesPerSecond > 0L) {+ "${formatBytes(item.averageThroughputBytesPerSecond)}/s"+ } else {+ "N/A"+ }+ )+ }++ if (item.retryCount > 0) {+ RecordingMetaPill(+ label = stringResource(R.string.settings_recording_retry_count_label),+ value = item.retryCount.toString()+ )+ }++ item.outputDisplayPath?.takeIf { output -> output.isNotBlank() }?.let { output ->+ Text(+ text = "${stringResource(R.string.settings_recording_output_label)}: ${summarizeRecordingOutputPath(output)}",+ style = MaterialTheme.typography.bodySmall,+ color = OnSurfaceDim,+ maxLines = 1,+ overflow = TextOverflow.Ellipsis+ )+ }++ item.failureReason?.takeIf { reason -> reason.isNotBlank() }?.let { reason ->+ Text(+ text = reason,+ style = MaterialTheme.typography.bodySmall,+ color = ErrorColor+ )+ }++ if (item.failureCategory != RecordingFailureCategory.NONE) {+ Text(+ text = "${stringResource(R.string.settings_recording_failure_label)}: ${formatRecordingFailureCategory(item.failureCategory)}",+ style = MaterialTheme.typography.bodySmall,+ color = ErrorColor+ )+ }+FlowRow(+ horizontalArrangement = Arrangement.spacedBy(8.dp),+ verticalArrangement = Arrangement.spacedBy(8.dp),modifier = Modifier.fillMaxWidth(),- horizontalArrangement = Arrangement.spacedBy(10.dp),- verticalArrangement = Arrangement.spacedBy(10.dp),- maxItemsInEachRow = 3+ maxItemsInEachRow = 4) {- RecordingActionButton(stringResource(R.string.settings_recording_choose_folder), Primary, onChooseFolder)- RecordingActionButton(stringResource(R.string.settings_recording_use_app_storage), Secondary, onUseAppStorage)- RecordingActionButton(stringResource(R.string.settings_recording_pattern_title), OnBackground, onChangePattern)- RecordingActionButton(stringResource(R.string.settings_recording_retention_title), OnBackground, onChangeRetention)- RecordingActionButton(stringResource(R.string.settings_recording_concurrency_title), OnBackground, onChangeConcurrency)- RecordingActionButton(stringResource(R.string.settings_recording_reconcile), Secondary, onRepairSchedule)+ if (item.status == RecordingStatus.COMPLETED && (!item.outputUri.isNullOrBlank() || !item.outputPath.isNullOrBlank())) {+ CompactRecordingActionChip(+ label = "Play",+ accent = Primary,+ onClick = onPlay+ )+ }+ if (item.status == RecordingStatus.RECORDING) {+ CompactRecordingActionChip(+ label = stringResource(R.string.settings_recording_stop),+ accent = ErrorColor,+ onClick = onStop+ )+ }+ if (item.status == RecordingStatus.SCHEDULED) {+ CompactRecordingActionChip(+ label = stringResource(+ if (item.scheduleEnabled) R.string.settings_recording_disable+ else R.string.settings_recording_enable+ ),+ accent = Secondary,+ onClick = { onToggleSchedule(!item.scheduleEnabled) }+ )+ CompactRecordingActionChip(+ label = stringResource(R.string.settings_recording_cancel),+ accent = OnBackground,+ onClick = onCancel+ )+ }+ if (item.status == RecordingStatus.COMPLETED || item.status == RecordingStatus.FAILED || item.status == RecordingStatus.CANCELLED) {+ if (item.status == RecordingStatus.FAILED) {+ CompactRecordingActionChip(+ label = stringResource(R.string.settings_recording_retry),+ accent = Primary,+ onClick = onRetry+ )+ }+ CompactRecordingActionChip(+ label = stringResource(R.string.settings_recording_delete),+ accent = OnBackground,+ onClick = onDelete+ )+ }}}}}+@Composable+private fun RecordingMetricCard(+ label: String,+ value: String,+ modifier: Modifier = Modifier+) {+ Column(+ modifier = modifier+ .background(Color.White.copy(alpha = 0.05f), RoundedCornerShape(12.dp))+ .padding(horizontal = 12.dp, vertical = 10.dp),+ verticalArrangement = Arrangement.spacedBy(4.dp)+ ) {+ Text(+ text = label,+ style = MaterialTheme.typography.labelSmall,+ color = OnSurfaceDim+ )+ Text(+ text = value,+ style = MaterialTheme.typography.titleSmall,+ color = OnBackground,+ maxLines = 1,+ overflow = TextOverflow.Ellipsis+ )+ }+}++@Composable+private fun StatusTonePill(+ label: String,+ accent: Color+) {+ Box(+ modifier = Modifier+ .background(accent.copy(alpha = 0.14f), RoundedCornerShape(999.dp))+ .padding(horizontal = 10.dp, vertical = 6.dp)+ ) {+ Text(+ text = label,+ style = MaterialTheme.typography.labelSmall,+ color = accent+ )+ }+}++private fun recordingDisplayTitle(item: RecordingItem): String {+ val title = item.programTitle?.trim().orEmpty()+ return if (title.isNotBlank()) title else item.channelName+}++private fun recordingDisplaySubtitle(item: RecordingItem): String? {+ val title = item.programTitle?.trim().orEmpty()+ return if (title.isNotBlank() && title != item.channelName) item.channelName else null+}++@Composable+private fun recordingListSecondaryLine(item: RecordingItem): String {+ val subtitle = recordingDisplaySubtitle(item)+ return subtitle ?: stringResource(+ R.string.settings_recording_time_window,+ formatTimestamp(item.scheduledStartMs),+ formatTimestamp(item.scheduledEndMs)+ )+}++@Composable+private fun recordingStatusLabel(status: RecordingStatus): String = when (status) {+ RecordingStatus.SCHEDULED -> stringResource(R.string.settings_recording_status_scheduled)+ RecordingStatus.RECORDING -> stringResource(R.string.settings_recording_status_recording)+ RecordingStatus.COMPLETED -> stringResource(R.string.settings_recording_status_completed)+ RecordingStatus.FAILED -> stringResource(R.string.settings_recording_status_failed)+ RecordingStatus.CANCELLED -> stringResource(R.string.settings_recording_status_cancelled)+}++private fun recordingStatusAccent(status: RecordingStatus): Color = when (status) {+ RecordingStatus.RECORDING -> Primary+ RecordingStatus.SCHEDULED -> Secondary+ RecordingStatus.COMPLETED -> Color(0xFF7BA7FF)+ RecordingStatus.FAILED -> ErrorColor+ RecordingStatus.CANCELLED -> OnSurfaceDim+}+@Composableinternal fun RecordingItemCard(item: RecordingItem,@@ -530,7 +1155,7 @@ internal fun RecordingItemCard(value = if (item.averageThroughputBytesPerSecond > 0L) {"${formatBytes(item.averageThroughputBytesPerSecond)}/s"} else {- "ג€“"+ "N/A"})if (item.retryCount > 0) {diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsScreen.ktindex dceb9aa1..ed905c64 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsScreen.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsScreen.kt@@ -3,9 +3,6 @@ package com.streamvault.app.ui.screens.settingsimport androidx.compose.foundation.backgroundimport androidx.compose.foundation.borderimport androidx.compose.foundation.BorderStroke-import androidx.compose.foundation.relocation.BringIntoViewRequester-import androidx.compose.foundation.relocation.bringIntoViewRequester-import androidx.compose.foundation.rememberScrollStateimport androidx.compose.ui.draw.clipimport androidx.compose.foundation.layout.*import androidx.compose.foundation.lazy.LazyColumn@@ -13,7 +10,6 @@ import androidx.compose.foundation.lazy.LazyRowimport androidx.compose.foundation.lazy.itemsimport androidx.compose.foundation.shape.RoundedCornerShapeimport androidx.compose.foundation.text.BasicTextField-import androidx.compose.foundation.verticalScrollimport androidx.lifecycle.compose.collectAsStateWithLifecycleimport androidx.compose.runtime.*import androidx.compose.runtime.saveable.rememberSaveable@@ -23,7 +19,6 @@ import androidx.compose.foundation.focusableimport androidx.compose.ui.focus.FocusRequesterimport androidx.compose.ui.focus.focusPropertiesimport androidx.compose.ui.focus.focusRequester-import androidx.compose.ui.focus.onFocusChangedimport androidx.compose.ui.input.key.onKeyEventimport androidx.compose.ui.input.key.onPreviewKeyEventimport androidx.compose.ui.platform.LocalSoftwareKeyboardController@@ -246,6 +241,8 @@ fun SettingsScreen(var showRecordingPatternDialog by rememberSaveable { mutableStateOf(false) }var showRecordingRetentionDialog by rememberSaveable { mutableStateOf(false) }var showRecordingConcurrencyDialog by rememberSaveable { mutableStateOf(false) }+ var showRecordingBrowserDialog by rememberSaveable { mutableStateOf(false) }+ var selectedRecordingId by rememberSaveable { mutableStateOf<String?>(null) }var categorySortDialogType by rememberSaveable { mutableStateOf<String?>(null) }var selectedCategory by rememberSaveable { mutableStateOf(0) }var pinError by rememberSaveable { mutableStateOf<String?>(null) }@@ -289,6 +286,15 @@ fun SettingsScreen(}}+ LaunchedEffect(uiState.recordingItems) {+ selectedRecordingId = when {+ uiState.recordingItems.isEmpty() -> null+ selectedRecordingId == null -> uiState.recordingItems.first().id+ uiState.recordingItems.any { item -> item.id == selectedRecordingId } -> selectedRecordingId+ else -> uiState.recordingItems.first().id+ }+ }+LaunchedEffect(currentRoute, selectedCategory) {delay(80)settingsNavFocusRequester.requestFocusSafely(tag = "SettingsScreen", target = "Selected settings section")@@ -400,7 +406,8 @@ fun SettingsScreen(LazyColumn(modifier = Modifier.weight(1f)- .fillMaxHeight(),+ .fillMaxHeight()+ .imePadding(),contentPadding = PaddingValues(start = 20.dp, top = 76.dp, end = 20.dp, bottom = 32.dp),verticalArrangement = Arrangement.spacedBy(10.dp),userScrollEnabled = !uiState.isSyncing@@ -511,6 +518,29 @@ fun SettingsScreen(color = OnBackground.copy(alpha = 0.6f),modifier = Modifier.padding(horizontal = 8.dp, vertical = 4.dp))+ HorizontalDivider(color = Color.White.copy(alpha = 0.07f), modifier = Modifier.padding(vertical = 4.dp))+ TvClickableSurface(+ onClick = { viewModel.setZapAutoRevert(!uiState.zapAutoRevert) },+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(8.dp)),+ colors = ClickableSurfaceDefaults.colors(+ containerColor = Color.Transparent,+ focusedContainerColor = Primary.copy(alpha = 0.15f)+ ),+ scale = ClickableSurfaceDefaults.scale(focusedScale = 1f),+ modifier = Modifier.fillMaxWidth()+ ) {+ Row(+ modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp, vertical = 12.dp),+ horizontalArrangement = Arrangement.SpaceBetween,+ verticalAlignment = Alignment.CenterVertically+ ) {+ Column(modifier = Modifier.weight(1f)) {+ Text(text = stringResource(R.string.settings_zap_auto_revert), style = MaterialTheme.typography.bodyMedium, color = OnSurface)+ Text(text = stringResource(R.string.settings_zap_auto_revert_subtitle), style = MaterialTheme.typography.bodySmall, color = OnBackground.copy(alpha = 0.6f))+ }+ Switch(checked = uiState.zapAutoRevert, onCheckedChange = { viewModel.setZapAutoRevert(it) })+ }+ }ClickableSettingsRow(label = stringResource(R.string.settings_decoder_mode),value = decoderModeLabel,@@ -618,6 +648,50 @@ fun SettingsScreen(Switch(checked = uiState.showLiveSourceSwitcher, onCheckedChange = { viewModel.setShowLiveSourceSwitcher(it) })}}+ TvClickableSurface(+ onClick = { viewModel.setShowAllChannelsCategory(!uiState.showAllChannelsCategory) },+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(8.dp)),+ colors = ClickableSurfaceDefaults.colors(+ containerColor = Color.Transparent,+ focusedContainerColor = Primary.copy(alpha = 0.15f)+ ),+ scale = ClickableSurfaceDefaults.scale(focusedScale = 1f),+ modifier = Modifier.fillMaxWidth()+ ) {+ Row(+ modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp, vertical = 12.dp),+ horizontalArrangement = Arrangement.SpaceBetween,+ verticalAlignment = Alignment.CenterVertically+ ) {+ Column(modifier = Modifier.weight(1f)) {+ Text(text = stringResource(R.string.settings_show_all_channels_category), style = MaterialTheme.typography.bodyMedium, color = OnSurface)+ Text(text = stringResource(R.string.settings_show_all_channels_category_subtitle), style = MaterialTheme.typography.bodySmall, color = OnBackground.copy(alpha = 0.6f))+ }+ Switch(checked = uiState.showAllChannelsCategory, onCheckedChange = { viewModel.setShowAllChannelsCategory(it) })+ }+ }+ TvClickableSurface(+ onClick = { viewModel.setShowRecentChannelsCategory(!uiState.showRecentChannelsCategory) },+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(8.dp)),+ colors = ClickableSurfaceDefaults.colors(+ containerColor = Color.Transparent,+ focusedContainerColor = Primary.copy(alpha = 0.15f)+ ),+ scale = ClickableSurfaceDefaults.scale(focusedScale = 1f),+ modifier = Modifier.fillMaxWidth()+ ) {+ Row(+ modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp, vertical = 12.dp),+ horizontalArrangement = Arrangement.SpaceBetween,+ verticalAlignment = Alignment.CenterVertically+ ) {+ Column(modifier = Modifier.weight(1f)) {+ Text(text = stringResource(R.string.settings_show_recent_channels_category), style = MaterialTheme.typography.bodyMedium, color = OnSurface)+ Text(text = stringResource(R.string.settings_show_recent_channels_category_subtitle), style = MaterialTheme.typography.bodySmall, color = OnBackground.copy(alpha = 0.6f))+ }+ Switch(checked = uiState.showRecentChannelsCategory, onCheckedChange = { viewModel.setShowRecentChannelsCategory(it) })+ }+ }ClickableSettingsRow(label = stringResource(R.string.settings_live_tv_quick_filters),value = formatLiveTvQuickFiltersValue(uiState.liveTvCategoryFilters, context),@@ -807,7 +881,7 @@ fun SettingsScreen(// ג”€ג”€ 3: Recordings ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€else if (selectedCategory == 4) {item {- RecordingOverviewCard(+ RecordingDashboardSection(treeLabel = uiState.recordingStorageState.displayName,outputDirectory = uiState.recordingStorageState.outputDirectory,availableBytes = uiState.recordingStorageState.availableBytes,@@ -822,53 +896,10 @@ fun SettingsScreen(onChangePattern = { showRecordingPatternDialog = true },onChangeRetention = { showRecordingRetentionDialog = true },onChangeConcurrency = { showRecordingConcurrencyDialog = true },- onRepairSchedule = { viewModel.reconcileRecordings() }+ onRepairSchedule = { viewModel.reconcileRecordings() },+ onOpenBrowser = { showRecordingBrowserDialog = true })}- if (uiState.recordingItems.isEmpty()) {- item {- TvClickableSurface(- onClick = {},- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(12.dp)),- colors = ClickableSurfaceDefaults.colors(- containerColor = Color.Transparent,- focusedContainerColor = Primary.copy(alpha = 0.1f)- ),- modifier = Modifier.fillMaxWidth().padding(top = 8.dp, bottom = 8.dp)- ) {- TvEmptyState(- title = stringResource(R.string.settings_recording_empty_title),- subtitle = stringResource(R.string.settings_recording_empty_subtitle)- )- }- }- } else {- items(uiState.recordingItems, key = { it.id }) { item ->- RecordingItemCard(- item = item,- onPlay = {- val playbackUrl = item.playbackUrl()- if (!playbackUrl.isNullOrBlank()) {- mainActivity?.openPlayer(- Routes.player(- streamUrl = playbackUrl,- title = item.programTitle ?: item.channelName,- internalId = -1L,- providerId = null,- contentType = "MOVIE",- returnRoute = currentRoute- )- )- }- },- onStop = { viewModel.stopRecording(item.id) },- onCancel = { viewModel.cancelRecording(item.id) },- onDelete = { viewModel.deleteRecording(item.id) },- onRetry = { viewModel.retryRecording(item.id) },- onToggleSchedule = { enabled -> viewModel.setRecordingScheduleEnabled(item.id, enabled) }- )- }- }}// ג”€ג”€ 4: Backup ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€@@ -933,6 +964,15 @@ fun SettingsScreen(// ג”€ג”€ 6: About ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€else if (selectedCategory == 7) {item {+ val downloadStatus = uiState.appUpdate.downloadStatus+ LaunchedEffect(downloadStatus) {+ if (downloadStatus == com.streamvault.app.update.AppUpdateDownloadStatus.Downloading) {+ while (true) {+ delay(2000L)+ viewModel.refreshDownloadState()+ }+ }+ }SettingsSectionHeader(title = stringResource(R.string.settings_updates_title),subtitle = stringResource(R.string.settings_updates_subtitle)@@ -946,6 +986,16 @@ fun SettingsScreen(checked = uiState.autoCheckAppUpdates,onCheckedChange = viewModel::setAutoCheckAppUpdates)+ if (uiState.autoCheckAppUpdates) {+ SwitchSettingsRow(+ label = stringResource(R.string.settings_update_auto_download),+ value = stringResource(+ if (uiState.autoDownloadAppUpdates) R.string.settings_enabled else R.string.settings_disabled+ ),+ checked = uiState.autoDownloadAppUpdates,+ onCheckedChange = viewModel::setAutoDownloadAppUpdates+ )+ }SettingsRow(label = stringResource(R.string.settings_update_latest_release),value = formatLatestReleaseLabel(uiState.appUpdate, context)@@ -1024,6 +1074,37 @@ fun SettingsScreen(.padding(bottom = 16.dp))+ if (showRecordingBrowserDialog) {+ RecordingBrowserDialog(+ recordingItems = uiState.recordingItems,+ selectedRecordingId = selectedRecordingId,+ onSelectedRecordingChange = { selectedRecordingId = it },+ onDismiss = { showRecordingBrowserDialog = false },+ onPlay = { item ->+ val playbackUrl = item.playbackUrl()+ if (!playbackUrl.isNullOrBlank()) {+ mainActivity?.openPlayer(+ Routes.player(+ streamUrl = playbackUrl,+ title = item.programTitle ?: item.channelName,+ internalId = -1L,+ providerId = null,+ contentType = "MOVIE",+ returnRoute = currentRoute+ )+ )+ }+ },+ onStop = { item -> viewModel.stopRecording(item.id) },+ onCancel = { item -> viewModel.cancelRecording(item.id) },+ onDelete = { item -> viewModel.deleteRecording(item.id) },+ onRetry = { item -> viewModel.retryRecording(item.id) },+ onToggleSchedule = { item, enabled ->+ viewModel.setRecordingScheduleEnabled(item.id, enabled)+ }+ )+ }+SettingsScreenDialogs(uiState = uiState,viewModel = viewModel,diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsStateBindings.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsStateBindings.ktindex 6dbba56c..c030e2e4 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsStateBindings.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsStateBindings.kt@@ -72,6 +72,8 @@ internal fun observeSettingsPreferenceSnapshot(xtreamBase64TextCompatibility = false,liveTvChannelMode = LiveTvChannelMode.PRO,showLiveSourceSwitcher = false,+ showAllChannelsCategory = true,+ showRecentChannelsCategory = true,liveTvCategoryFilters = emptyList(),liveTvQuickFilterVisibilityMode = LiveTvQuickFilterVisibilityMode.ALWAYS_VISIBLE,liveChannelNumberingMode = ChannelNumberingMode.GROUP,@@ -79,7 +81,9 @@ internal fun observeSettingsPreferenceSnapshot(guideDefaultCategoryId = VirtualCategoryIds.FAVORITES,guideDefaultCategoryOptions = emptyList(),preventStandbyDuringPlayback = true,+ zapAutoRevert = true,autoCheckAppUpdates = true,+ autoDownloadAppUpdates = false,lastAppUpdateCheckAt = null,cachedAppUpdateVersionName = null,cachedAppUpdateVersionCode = null,@@ -140,6 +144,10 @@ internal fun observeSettingsPreferenceSnapshot(snapshot.copy(liveTvChannelMode = LiveTvChannelMode.fromStorage(liveTvChannelMode))}.combine(preferencesRepository.showLiveSourceSwitcher) { snapshot, showLiveSourceSwitcher ->snapshot.copy(showLiveSourceSwitcher = showLiveSourceSwitcher)+ }.combine(preferencesRepository.showAllChannelsCategory) { snapshot, showAllChannelsCategory ->+ snapshot.copy(showAllChannelsCategory = showAllChannelsCategory)+ }.combine(preferencesRepository.showRecentChannelsCategory) { snapshot, showRecentChannelsCategory ->+ snapshot.copy(showRecentChannelsCategory = showRecentChannelsCategory)}.combine(preferencesRepository.liveTvCategoryFilters) { snapshot, liveTvCategoryFilters ->snapshot.copy(liveTvCategoryFilters = liveTvCategoryFilters)}.combine(preferencesRepository.liveTvQuickFilterVisibility) { snapshot, visibilityMode ->@@ -154,8 +162,12 @@ internal fun observeSettingsPreferenceSnapshot(snapshot.copy(guideDefaultCategoryId = guideDefaultCategoryId ?: VirtualCategoryIds.FAVORITES)}.combine(preferencesRepository.preventStandbyDuringPlayback) { snapshot, preventStandby ->snapshot.copy(preventStandbyDuringPlayback = preventStandby)+ }.combine(preferencesRepository.zapAutoRevert) { snapshot, zapAutoRevert ->+ snapshot.copy(zapAutoRevert = zapAutoRevert)}.combine(preferencesRepository.autoCheckAppUpdates) { snapshot, autoCheckAppUpdates ->snapshot.copy(autoCheckAppUpdates = autoCheckAppUpdates)+ }.combine(preferencesRepository.autoDownloadAppUpdates) { snapshot, autoDownloadAppUpdates ->+ snapshot.copy(autoDownloadAppUpdates = autoDownloadAppUpdates)}.combine(preferencesRepository.lastAppUpdateCheckTimestamp) { snapshot, lastAppUpdateCheckAt ->snapshot.copy(lastAppUpdateCheckAt = lastAppUpdateCheckAt)}.combine(preferencesRepository.cachedAppUpdateVersionName) { snapshot, versionName ->@@ -210,6 +222,8 @@ internal fun SettingsUiState.applyPreferenceSnapshot(snapshot: SettingsPreferencxtreamBase64TextCompatibility = snapshot.xtreamBase64TextCompatibility,liveTvChannelMode = snapshot.liveTvChannelMode,showLiveSourceSwitcher = snapshot.showLiveSourceSwitcher,+ showAllChannelsCategory = snapshot.showAllChannelsCategory,+ showRecentChannelsCategory = snapshot.showRecentChannelsCategory,liveTvCategoryFilters = snapshot.liveTvCategoryFilters,liveTvQuickFilterVisibilityMode = snapshot.liveTvQuickFilterVisibilityMode,liveChannelNumberingMode = snapshot.liveChannelNumberingMode,@@ -217,7 +231,9 @@ internal fun SettingsUiState.applyPreferenceSnapshot(snapshot: SettingsPreferencguideDefaultCategoryId = snapshot.guideDefaultCategoryId,guideDefaultCategoryOptions = guideDefaultCategoryOptions,preventStandbyDuringPlayback = snapshot.preventStandbyDuringPlayback,+ zapAutoRevert = snapshot.zapAutoRevert,autoCheckAppUpdates = snapshot.autoCheckAppUpdates,+ autoDownloadAppUpdates = snapshot.autoDownloadAppUpdates,appUpdate = cachedAppUpdate.copy(downloadStatus = appUpdate.downloadStatus,downloadedVersionName = appUpdate.downloadedVersionName,@@ -255,6 +271,12 @@ internal fun observeProviderDiagnostics(movieSyncMode = metadata?.movieSyncMode ?: VodSyncMode.UNKNOWN,movieWarningsCount = metadata?.movieWarningsCount ?: 0,movieCatalogStale = metadata?.movieCatalogStale ?: false,+ liveSequentialFailuresRemembered = metadata?.liveSequentialFailuresRemembered ?: false,+ liveHealthySyncStreak = metadata?.liveHealthySyncStreak ?: 0,+ movieParallelFailuresRemembered = metadata?.movieParallelFailuresRemembered ?: false,+ movieHealthySyncStreak = metadata?.movieHealthySyncStreak ?: 0,+ seriesSequentialFailuresRemembered = metadata?.seriesSequentialFailuresRemembered ?: false,+ seriesHealthySyncStreak = metadata?.seriesHealthySyncStreak ?: 0,capabilitySummary = buildCapabilitySummary(application, provider),sourceLabel = provider.sourceLabel(),expirySummary = provider.expirySummary(),diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsViewModel.ktindex a3795d8e..ebab238b 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsViewModel.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsViewModel.kt@@ -145,15 +145,17 @@ class SettingsViewModel @Inject constructor(viewModelScope.launch {combine(preferencesRepository.autoCheckAppUpdates,- preferencesRepository.lastAppUpdateCheckTimestamp- ) { autoCheckEnabled, lastCheckedAt ->- autoCheckEnabled to lastCheckedAt- }.distinctUntilChanged().collect { (autoCheckEnabled, lastCheckedAt) ->+ preferencesRepository.lastAppUpdateCheckTimestamp,+ preferencesRepository.autoDownloadAppUpdates+ ) { autoCheckEnabled, lastCheckedAt, autoDownload ->+ Triple(autoCheckEnabled, lastCheckedAt, autoDownload)+ }.distinctUntilChanged().collect { (autoCheckEnabled, lastCheckedAt, autoDownload) ->if (autoCheckEnabled && appUpdateActions.shouldAutoCheckForUpdates(lastCheckedAt)) {appUpdateActions.checkForAppUpdates(scope = viewModelScope,manual = false,- isRemoteVersionNewer = ::isRemoteVersionNewer+ isRemoteVersionNewer = ::isRemoteVersionNewer,+ autoDownload = autoDownload)}}@@ -199,6 +201,12 @@ class SettingsViewModel @Inject constructor(}}+ viewModelScope.launch {+ preferencesRepository.lastMaintenanceSnapshot.collect { snapshot ->+ _uiState.update { it.copy(databaseMaintenance = snapshot?.toUiModel()) }+ }+ }+viewModelScope.launch {observeCategoryManagement(activeProviderIdFlow = activeProviderIdFlow,@@ -231,6 +239,12 @@ class SettingsViewModel @Inject constructor(_uiState.update { it.copy(recordingStorageState = storage) }}}++ viewModelScope.launch {+ epgSourceRepository.getAllSources().collect { sources ->+ _uiState.update { it.copy(epgSources = sources) }+ }+ }}fun setActiveProvider(providerId: Long) {@@ -301,6 +315,18 @@ class SettingsViewModel @Inject constructor(}}+ fun setShowAllChannelsCategory(enabled: Boolean) {+ viewModelScope.launch {+ preferencesRepository.setShowAllChannelsCategory(enabled)+ }+ }++ fun setShowRecentChannelsCategory(enabled: Boolean) {+ viewModelScope.launch {+ preferencesRepository.setShowRecentChannelsCategory(enabled)+ }+ }+fun setLiveTvQuickFilterVisibilityMode(mode: LiveTvQuickFilterVisibilityMode) {viewModelScope.launch {preferencesRepository.setLiveTvQuickFilterVisibility(mode.storageValue)@@ -372,6 +398,18 @@ class SettingsViewModel @Inject constructor(}}+ fun setAutoDownloadAppUpdates(enabled: Boolean) {+ viewModelScope.launch {+ preferencesRepository.setAutoDownloadAppUpdates(enabled)+ }+ }++ fun refreshDownloadState() {+ viewModelScope.launch {+ appUpdateInstaller.refreshState()+ }+ }+fun checkForAppUpdates() {appUpdateActions.checkForAppUpdates(scope = viewModelScope,@@ -432,6 +470,12 @@ class SettingsViewModel @Inject constructor(}}+ fun setZapAutoRevert(enabled: Boolean) {+ viewModelScope.launch {+ preferencesRepository.setZapAutoRevert(enabled)+ }+ }+fun setPlayerDecoderMode(mode: DecoderMode) {viewModelScope.launch {preferencesRepository.setPlayerDecoderMode(mode)@@ -741,10 +785,6 @@ class SettingsViewModel @Inject constructor(// ── EPG Source Management ────────────────────────────────────────- fun loadEpgSources() {- epgActions.loadEpgSources(viewModelScope)- }-fun loadEpgAssignments(providerId: Long) {epgActions.loadEpgAssignments(viewModelScope, providerId)}@@ -753,6 +793,10 @@ class SettingsViewModel @Inject constructor(epgActions.addEpgSource(viewModelScope, name, url)}+ fun setPendingDeleteEpgSource(id: Long?) {+ _uiState.update { it.copy(epgPendingDeleteSourceId = id) }+ }+fun deleteEpgSource(sourceId: Long) {epgActions.deleteEpgSource(viewModelScope, sourceId)}@@ -787,7 +831,14 @@ class SettingsViewModel @Inject constructor(is ActiveLiveSource.CombinedM3uSource -> {combine(combinedM3uRepository.getCombinedCategories(activeSource.profileId),- getCustomCategories(ContentType.LIVE)+ flow {+ emit(combinedM3uRepository.getProfile(activeSource.profileId)?.members.orEmpty())+ }.flatMapLatest { members ->+ getCustomCategories(+ members.filter { it.enabled }.map { it.providerId },+ ContentType.LIVE+ )+ }) { combinedCategories, customCategories ->buildGuideDefaultCategoryOptions(physicalCategories = combinedCategories.map { it.category },@@ -798,7 +849,7 @@ class SettingsViewModel @Inject constructor(is ActiveLiveSource.ProviderSource -> {combine(channelRepository.getCategories(activeSource.providerId),- getCustomCategories(ContentType.LIVE),+ getCustomCategories(activeSource.providerId, ContentType.LIVE),preferencesRepository.getHiddenCategoryIds(activeSource.providerId, ContentType.LIVE),preferencesRepository.getCategorySortMode(activeSource.providerId, ContentType.LIVE)) { categories, customCategories, hiddenCategoryIds, sortMode ->diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsViewModelModels.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsViewModelModels.ktindex 0c517d34..4148da19 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsViewModelModels.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsViewModelModels.kt@@ -9,6 +9,7 @@ import com.streamvault.app.ui.model.VodViewModeimport com.streamvault.app.update.AppUpdateDownloadStateimport com.streamvault.app.update.AppUpdateDownloadStatusimport com.streamvault.app.update.GitHubReleaseInfo+import com.streamvault.data.preferences.DatabaseMaintenanceSnapshotimport com.streamvault.domain.manager.BackupImportPlanimport com.streamvault.domain.manager.BackupPreviewimport com.streamvault.domain.model.ActiveLiveSource@@ -71,6 +72,8 @@ internal data class SettingsPreferenceSnapshot(val xtreamBase64TextCompatibility: Boolean,val liveTvChannelMode: LiveTvChannelMode,val showLiveSourceSwitcher: Boolean,+ val showAllChannelsCategory: Boolean,+ val showRecentChannelsCategory: Boolean,val liveTvCategoryFilters: List<String>,val liveTvQuickFilterVisibilityMode: LiveTvQuickFilterVisibilityMode,val liveChannelNumberingMode: ChannelNumberingMode,@@ -78,7 +81,9 @@ internal data class SettingsPreferenceSnapshot(val guideDefaultCategoryId: Long,val guideDefaultCategoryOptions: List<Category>,val preventStandbyDuringPlayback: Boolean,+ val zapAutoRevert: Boolean,val autoCheckAppUpdates: Boolean,+ val autoDownloadAppUpdates: Boolean,val lastAppUpdateCheckAt: Long?,val cachedAppUpdateVersionName: String?,val cachedAppUpdateVersionCode: Int?,@@ -118,13 +123,67 @@ data class ProviderDiagnosticsUiModel(val movieSyncMode: VodSyncMode = VodSyncMode.UNKNOWN,val movieWarningsCount: Int = 0,val movieCatalogStale: Boolean = false,+ val liveSequentialFailuresRemembered: Boolean = false,+ val liveHealthySyncStreak: Int = 0,+ val movieParallelFailuresRemembered: Boolean = false,+ val movieHealthySyncStreak: Int = 0,+ val seriesSequentialFailuresRemembered: Boolean = false,+ val seriesHealthySyncStreak: Int = 0,val capabilitySummary: String = "",val sourceLabel: String = "",val expirySummary: String = "",val connectionSummary: String = "",val archiveSummary: String = ""+) {+ val hasHealthWarning: Boolean+ get() = liveSequentialFailuresRemembered ||+ movieParallelFailuresRemembered ||+ seriesSequentialFailuresRemembered ||+ movieCatalogStale ||+ movieWarningsCount > 0+}++data class DatabaseMaintenanceUiModel(+ val ranAt: Long,+ val deletedPrograms: Int,+ val deletedExternalProgrammes: Int,+ val deletedOrphanEpisodes: Int,+ val deletedStaleFavorites: Int,+ val vacuumRan: Boolean,+ val mainDbBytes: Long,+ val walBytes: Long,+ val reclaimableBytes: Long,+ val channelRows: Long,+ val movieRows: Long,+ val seriesRows: Long,+ val episodeRows: Long,+ val programRows: Long,+ val epgProgrammeRows: Long,+ val playbackHistoryRows: Long,+ val favoriteRows: Long)+internal fun DatabaseMaintenanceSnapshot.toUiModel(): DatabaseMaintenanceUiModel =+ DatabaseMaintenanceUiModel(+ ranAt = ranAt,+ deletedPrograms = deletedPrograms,+ deletedExternalProgrammes = deletedExternalProgrammes,+ deletedOrphanEpisodes = deletedOrphanEpisodes,+ deletedStaleFavorites = deletedStaleFavorites,+ vacuumRan = vacuumRan,+ mainDbBytes = mainDbBytes,+ walBytes = walBytes,+ reclaimableBytes = reclaimableBytes,+ channelRows = channelRows,+ movieRows = movieRows,+ seriesRows = seriesRows,+ episodeRows = episodeRows,+ programRows = programRows,+ epgProgrammeRows = epgProgrammeRows,+ playbackHistoryRows = playbackHistoryRows,+ favoriteRows = favoriteRows+ )+data class SettingsUiState(val providers: List<Provider> = emptyList(),val combinedProfiles: List<CombinedM3uProfile> = emptyList(),@@ -137,6 +196,7 @@ data class SettingsUiState(val userMessage: String? = null,val syncWarningsByProvider: Map<Long, List<String>> = emptyMap(),val diagnosticsByProvider: Map<Long, ProviderDiagnosticsUiModel> = emptyMap(),+ val databaseMaintenance: DatabaseMaintenanceUiModel? = null,val parentalControlLevel: Int = 0,val hasParentalPin: Boolean = false,val appLanguage: String = "system",@@ -167,6 +227,8 @@ data class SettingsUiState(val xtreamBase64TextCompatibility: Boolean = false,val liveTvChannelMode: LiveTvChannelMode = LiveTvChannelMode.PRO,val showLiveSourceSwitcher: Boolean = false,+ val showAllChannelsCategory: Boolean = true,+ val showRecentChannelsCategory: Boolean = true,val liveTvCategoryFilters: List<String> = emptyList(),val liveTvQuickFilterVisibilityMode: LiveTvQuickFilterVisibilityMode = LiveTvQuickFilterVisibilityMode.ALWAYS_VISIBLE,val liveChannelNumberingMode: ChannelNumberingMode = ChannelNumberingMode.GROUP,@@ -174,12 +236,16 @@ data class SettingsUiState(val guideDefaultCategoryId: Long = com.streamvault.domain.model.VirtualCategoryIds.FAVORITES,val guideDefaultCategoryOptions: List<Category> = emptyList(),val preventStandbyDuringPlayback: Boolean = true,+ val zapAutoRevert: Boolean = true,val categorySortModes: Map<ContentType, CategorySortMode> = emptyMap(),val hiddenCategories: List<Category> = emptyList(),val epgSources: List<com.streamvault.domain.model.EpgSource> = emptyList(),val epgSourceAssignments: Map<Long, List<com.streamvault.domain.model.ProviderEpgSourceAssignment>> = emptyMap(),val epgResolutionSummaries: Map<Long, EpgResolutionSummary> = emptyMap(),+ val refreshingEpgSourceIds: Set<Long> = emptySet(),+ val epgPendingDeleteSourceId: Long? = null,val autoCheckAppUpdates: Boolean = true,+ val autoDownloadAppUpdates: Boolean = false,val isCheckingForUpdates: Boolean = false,val appUpdate: AppUpdateUiModel = AppUpdateUiModel())diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/parental/ParentalControlGroupScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/parental/ParentalControlGroupScreen.ktindex ff5bd58c..f2050c82 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/parental/ParentalControlGroupScreen.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/parental/ParentalControlGroupScreen.kt@@ -54,10 +54,9 @@ import com.streamvault.app.ui.components.dialogs.PinDialogimport com.streamvault.app.ui.components.shell.AppNavigationChromeimport com.streamvault.app.ui.components.shell.AppScreenScaffoldimport com.streamvault.domain.model.ContentType-import kotlinx.coroutines.launchimport com.streamvault.app.ui.interaction.TvClickableSurface-import com.streamvault.app.ui.interaction.TvButtonimport com.streamvault.app.ui.interaction.TvIconButton+import kotlinx.coroutines.launchprivate enum class CategoryControlsMode {PROTECTION,@@ -89,9 +88,21 @@ fun ParentalControlGroupScreen(val snackbarHostState = remember { SnackbarHostState() }val scope = rememberCoroutineScope()var currentMode by rememberSaveable { mutableStateOf(CategoryControlsMode.PROTECTION) }+ var selectedType by rememberSaveable { mutableStateOf(ContentType.LIVE) }var showPinDialog by rememberSaveable { mutableStateOf(false) }var pinAction by rememberSaveable { mutableStateOf<CategoryPinAction?>(null) }var pinError by rememberSaveable { mutableStateOf<String?>(null) }+ val selectedTypeLabel = contentTypeTabLabel(selectedType)+ val filteredCategories = uiState.categories.filter { item ->+ item.category.type == selectedType &&+ (uiState.searchQuery.isBlank() || item.category.name.contains(uiState.searchQuery, ignoreCase = true))+ }+ val hiddenCount = uiState.categories.count { item ->+ item.category.type == selectedType && item.isHidden+ }+ val visibleCount = uiState.categories.count { item ->+ item.category.type == selectedType && !item.isHidden+ }LaunchedEffect(Unit) {backButtonFocusRequester.requestFocus()@@ -154,9 +165,17 @@ fun ParentalControlGroupScreen()}+ item {+ ContentTypeSelectorRow(+ selectedType = selectedType,+ onTypeSelected = { selectedType = it }+ )+ }+item {when (currentMode) {CategoryControlsMode.PROTECTION -> ProtectionSummaryCard(+ selectedTypeLabel = selectedTypeLabel,hasChanges = uiState.hasPendingProtectionChanges,changeCount = uiState.pendingProtectionChangeCount,hasParentalPin = uiState.hasParentalPin,@@ -172,20 +191,21 @@ fun ParentalControlGroupScreen(onReset = viewModel::resetProtectionChanges)CategoryControlsMode.VISIBILITY -> VisibilitySummaryCard(- hiddenCount = uiState.hiddenCategoryCount,- visibleCount = uiState.visibleCategoryCount,- onHideAll = viewModel::hideAllCategories,- onUnhideAll = viewModel::unhideAllCategories+ selectedTypeLabel = selectedTypeLabel,+ hiddenCount = hiddenCount,+ visibleCount = visibleCount,+ onHideAll = { viewModel.hideAllCategories(selectedType) },+ onUnhideAll = { viewModel.unhideAllCategories(selectedType) })}}- if (uiState.categories.isEmpty()) {+ if (filteredCategories.isEmpty()) {item {EmptyCategoryMessage()}} else {- items(uiState.categories, key = { it.key }) { item ->+ items(filteredCategories, key = { it.key }) { item ->when (currentMode) {CategoryControlsMode.PROTECTION -> CategoryProtectionCard(item = item,@@ -248,6 +268,30 @@ fun ParentalControlGroupScreen(}}+@Composable+private fun ContentTypeSelectorRow(+ selectedType: ContentType,+ onTypeSelected: (ContentType) -> Unit+) {+ Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {+ listOf(ContentType.LIVE, ContentType.MOVIE, ContentType.SERIES).forEach { type ->+ CategoryModeChip(+ label = contentTypeTabLabel(type),+ selected = selectedType == type,+ onClick = { onTypeSelected(type) }+ )+ }+ }+}++@Composable+private fun contentTypeTabLabel(type: ContentType): String = when (type) {+ ContentType.LIVE -> stringResource(R.string.nav_live_tv)+ ContentType.MOVIE -> stringResource(R.string.nav_movies)+ ContentType.SERIES,+ ContentType.SERIES_EPISODE -> stringResource(R.string.nav_series)+}+@Composableprivate fun ModeSelectorRow(selectedMode: CategoryControlsMode,@@ -294,6 +338,7 @@ private fun CategoryModeChip(@Composableprivate fun ProtectionSummaryCard(+ selectedTypeLabel: String,hasChanges: Boolean,changeCount: Int,hasParentalPin: Boolean,@@ -307,6 +352,11 @@ private fun ProtectionSummaryCard(.padding(18.dp),verticalArrangement = Arrangement.spacedBy(12.dp)) {+ Text(+ text = selectedTypeLabel,+ style = MaterialTheme.typography.labelMedium,+ color = Color(0xFF7EB1FF)+ )Text(text = stringResource(R.string.settings_category_protection_summary_title),style = MaterialTheme.typography.titleMedium,@@ -347,6 +397,7 @@ private fun ProtectionSummaryCard(@Composableprivate fun VisibilitySummaryCard(+ selectedTypeLabel: String,hiddenCount: Int,visibleCount: Int,onHideAll: () -> Unit,@@ -359,6 +410,11 @@ private fun VisibilitySummaryCard(.padding(18.dp),verticalArrangement = Arrangement.spacedBy(8.dp)) {+ Text(+ text = selectedTypeLabel,+ style = MaterialTheme.typography.labelMedium,+ color = Color(0xFF7EB1FF)+ )Text(text = stringResource(R.string.settings_category_visibility_summary_title),style = MaterialTheme.typography.titleMedium,diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/parental/ParentalControlGroupViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/parental/ParentalControlGroupViewModel.ktindex 2a0a6c66..24f7278d 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/parental/ParentalControlGroupViewModel.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/parental/ParentalControlGroupViewModel.kt@@ -138,40 +138,31 @@ class ParentalControlGroupViewModel @Inject constructor(}}- fun hideAllCategories() {+ fun hideAllCategories(type: ContentType) {viewModelScope.launch {- val categoriesByType = categoryRepository.getCategories(providerId)+ val categoryIds = categoryRepository.getCategories(providerId).first()- .groupBy(Category::type)- ContentType.entries- .filter { it != ContentType.SERIES_EPISODE }- .forEach { type ->- val categoryIds = categoriesByType[type]- .orEmpty()- .map(Category::id)- .toSet()- preferencesRepository.setHiddenCategoryIds(- providerId = providerId,- type = type,- categoryIds = categoryIds- )- }- _userMessage.value = "All categories hidden."+ .asSequence()+ .filter { it.type == type }+ .map(Category::id)+ .toSet()+ preferencesRepository.setHiddenCategoryIds(+ providerId = providerId,+ type = type,+ categoryIds = categoryIds+ )+ _userMessage.value = "${contentTypeMessageLabel(type)} categories hidden."}}- fun unhideAllCategories() {+ fun unhideAllCategories(type: ContentType) {viewModelScope.launch {- ContentType.entries- .filter { it != ContentType.SERIES_EPISODE }- .forEach { type ->- preferencesRepository.setHiddenCategoryIds(- providerId = providerId,- type = type,- categoryIds = emptySet()- )- }- _userMessage.value = "All categories restored."+ preferencesRepository.setHiddenCategoryIds(+ providerId = providerId,+ type = type,+ categoryIds = emptySet()+ )+ _userMessage.value = "${contentTypeMessageLabel(type)} categories restored."}}@@ -223,6 +214,13 @@ class ParentalControlGroupViewModel @Inject constructor(private fun categoryControlKey(category: Category): String = "${category.type.name}:${category.id}"+private fun contentTypeMessageLabel(type: ContentType): String = when (type) {+ ContentType.LIVE -> "Live TV"+ ContentType.MOVIE -> "Movie"+ ContentType.SERIES,+ ContentType.SERIES_EPISODE -> "Series"+}+private data class CategoryUiInputs(val categories: List<Category>,val hiddenByType: Map<ContentType, Set<Long>>,@@ -237,10 +235,7 @@ private fun buildUiState(inputs: CategoryUiInputs,isLoading: Boolean): ParentalControlGroupUiState {- val filteredCategories = inputs.categories.filter { category ->- inputs.query.isBlank() || category.name.contains(inputs.query, ignoreCase = true)- }- val items = filteredCategories.map { category ->+ val items = inputs.categories.map { category ->val isInitiallyProtected = category.isAdult || category.isUserProtectedval isProtected = if (category.isAdult) {truediff --git a/app/src/main/java/com/streamvault/app/ui/screens/vod/VodBrowseStateHelpers.kt b/app/src/main/java/com/streamvault/app/ui/screens/vod/VodBrowseStateHelpers.ktindex 96339102..68dfe4c4 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/vod/VodBrowseStateHelpers.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/vod/VodBrowseStateHelpers.kt@@ -82,4 +82,30 @@ inline fun <State> setVodLibrarySortBy(uiState.update { state ->state.updateState(sortBy, hasSelectedCategory(state))}+}++/**+ * Returns a compact summary label for the currently active filter and/or sort+ * (e.g. "Favorites · Rating"), or null when both are at their defaults.+ * This is used to decorate the "Filter & Sort" action chip so the user can+ * tell at a glance that a non-default browse mode is in effect.+ */+fun vodActiveFilterSortDetail(filter: LibraryFilterType, sort: LibrarySortBy): String? {+ val filterLabel = when (filter) {+ LibraryFilterType.ALL -> null+ LibraryFilterType.FAVORITES -> "Favorites"+ LibraryFilterType.IN_PROGRESS -> "Resume"+ LibraryFilterType.UNWATCHED -> "Unwatched"+ LibraryFilterType.RECENTLY_UPDATED -> "Recent"+ LibraryFilterType.TOP_RATED -> "Top Rated"+ }+ val sortLabel = when (sort) {+ LibrarySortBy.LIBRARY -> null+ LibrarySortBy.TITLE -> "A-Z"+ LibrarySortBy.RELEASE -> "Newest"+ LibrarySortBy.UPDATED -> "Updated"+ LibrarySortBy.RATING -> "Rating"+ LibrarySortBy.WATCH_COUNT -> "Recent Activity"+ }+ return listOfNotNull(filterLabel, sortLabel).joinToString(" · ").ifEmpty { null }}\ No newline at end of filediff --git a/app/src/main/java/com/streamvault/app/ui/screens/vod/VodFavoriteHelpers.kt b/app/src/main/java/com/streamvault/app/ui/screens/vod/VodFavoriteHelpers.ktindex 8f244aca..3691264a 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/vod/VodFavoriteHelpers.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/vod/VodFavoriteHelpers.kt@@ -23,14 +23,15 @@ fun matchesVodGroupMembership(storedGroupId: Long?, categoryId: Long): Boolean {suspend fun <T> loadVodDialogSelection(item: T,+ providerId: Long,itemId: Long,contentType: ContentType,favoriteRepository: FavoriteRepository,copyWithFavorite: (T, Boolean) -> T): VodDialogSelection<T> {- val memberships = favoriteRepository.getGroupMemberships(itemId, contentType)+ val memberships = favoriteRepository.getGroupMemberships(providerId, itemId, contentType).map(::toVirtualVodGroupId)- val isFavorite = favoriteRepository.isFavorite(itemId, contentType)+ val isFavorite = favoriteRepository.isFavorite(providerId, itemId, contentType)return VodDialogSelection(selectedItem = copyWithFavorite(item, isFavorite),groupMemberships = memberships@@ -38,19 +39,21 @@ suspend fun <T> loadVodDialogSelection(}suspend fun setVodFavorite(+ providerId: Long,itemId: Long,contentType: ContentType,isFavorite: Boolean,favoriteRepository: FavoriteRepository) {if (isFavorite) {- favoriteRepository.addFavorite(itemId, contentType)+ favoriteRepository.addFavorite(providerId, itemId, contentType)} else {- favoriteRepository.removeFavorite(itemId, contentType)+ favoriteRepository.removeFavorite(providerId, itemId, contentType)}}suspend fun updateVodGroupMembership(+ providerId: Long,itemId: Long,groupId: Long,contentType: ContentType,@@ -59,17 +62,18 @@ suspend fun updateVodGroupMembership(): List<Long> {val encodedGroupId = toStoredVodGroupId(groupId)if (shouldBeMember) {- favoriteRepository.addFavorite(itemId, contentType, groupId = encodedGroupId)+ favoriteRepository.addFavorite(providerId, itemId, contentType, groupId = encodedGroupId)} else {- favoriteRepository.removeFavorite(itemId, contentType, groupId = encodedGroupId)+ favoriteRepository.removeFavorite(providerId, itemId, contentType, groupId = encodedGroupId)}- return favoriteRepository.getGroupMemberships(itemId, contentType)+ return favoriteRepository.getGroupMemberships(providerId, itemId, contentType).map(::toVirtualVodGroupId)}suspend fun createVodGroup(+ providerId: Long,name: String,contentType: ContentType,favoriteRepository: FavoriteRepository): Result<VirtualGroup> =- favoriteRepository.createGroup(name, contentType = contentType)+ favoriteRepository.createGroup(providerId, name, contentType = contentType)diff --git a/app/src/main/java/com/streamvault/app/ui/screens/vod/VodReorderHelpers.kt b/app/src/main/java/com/streamvault/app/ui/screens/vod/VodReorderHelpers.ktindex dabc469d..c00aa319 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/vod/VodReorderHelpers.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/vod/VodReorderHelpers.kt@@ -7,6 +7,7 @@ import com.streamvault.domain.repository.FavoriteRepositoryimport kotlinx.coroutines.flow.firstsuspend fun <Item> loadVodReorderItems(+ providerId: Long,category: Category,contentType: ContentType,favoriteRepository: FavoriteRepository,@@ -17,7 +18,7 @@ suspend fun <Item> loadVodReorderItems(val groupId = category.reorderGroupId()val favorites = if (groupId == null) {- favoriteRepository.getFavorites(contentType).first()+ favoriteRepository.getFavorites(providerId, contentType).first()} else {favoriteRepository.getFavoritesByGroup(groupId).first()}@@ -51,6 +52,7 @@ fun <Item> moveVodItemDown(items: List<Item>, item: Item): List<Item> {}suspend fun <Item> saveVodReorder(+ providerId: Long,category: Category,currentItems: List<Item>,contentType: ContentType,@@ -59,7 +61,7 @@ suspend fun <Item> saveVodReorder() {val groupId = category.reorderGroupId()val favorites = if (groupId == null) {- favoriteRepository.getFavorites(contentType).first()+ favoriteRepository.getFavorites(providerId, contentType).first()} else {favoriteRepository.getFavoritesByGroup(groupId).first()}@@ -67,8 +69,6 @@ suspend fun <Item> saveVodReorder(val favoriteMap = favorites.associateBy(Favorite::contentId)val reorderedFavorites = currentItems.mapNotNull { item ->favoriteMap[itemId(item)]- }.mapIndexed { index, favorite ->- favorite.copy(position = index)}favoriteRepository.reorderFavorites(reorderedFavorites)@@ -83,4 +83,4 @@ private fun <Item> List<Item>.orderByIds(): List<Item> {val positions = ids.withIndex().associate { it.value to it.index }return sortedBy { item -> positions[itemId(item)] ?: Int.MAX_VALUE }-}\ No newline at end of file+}diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xmlindex 6ca8af34..dc75ef5d 100644--- a/app/src/main/res/values/strings.xml+++ b/app/src/main/res/values/strings.xml@@ -139,6 +139,8 @@<string name="category_options_cancel">Cancel</string><string name="category_options_reorder">Reorder Items</string><string name="category_options_hide">Hide Category</string>+ <string name="category_options_hide_from_live_tv">Hide from Live TV</string>+ <string name="category_options_clear_recent">Clear All Recent</string><string name="category_options_pin">Pin Category</string><string name="category_options_unpin">Unpin Category</string><string name="category_pinned">Pinned %1$s.</string>@@ -152,6 +154,7 @@<string name="add_group_rename">Rename</string><string name="add_group_remove_favorites">Remove from Favorites</string><string name="add_group_add_favorites">Add to Favorites</string>+ <string name="channel_options_remove_from_recent">Remove from Recent</string><string name="add_group_reorder_title">Reorder</string><string name="add_group_move_up">Move Up</string><string name="add_group_move_down">Move Down</string>@@ -176,6 +179,10 @@<string name="live_source_empty_short">Empty</string><string name="settings_show_live_source_switcher">Show Live Source Browser</string><string name="settings_show_live_source_switcher_subtitle">Display the M3U source switcher inside Live TV browsing.</string>+ <string name="settings_show_all_channels_category">Show All Channels category</string>+ <string name="settings_show_all_channels_category_subtitle">Display the virtual All Channels group in Live TV and the EPG guide.</string>+ <string name="settings_show_recent_channels_category">Show Recent Channels category</string>+ <string name="settings_show_recent_channels_category_subtitle">Display recently watched channels in Live TV browsing and on the Home screen.</string><string name="movies_incorrect_pin">Incorrect PIN</string>@@ -350,6 +357,8 @@<string name="settings_live_timeshift_depth_15">15 minutes</string><string name="settings_live_timeshift_depth_30">30 minutes</string><string name="settings_live_timeshift_depth_60">60 minutes</string>+ <string name="settings_zap_auto_revert">Auto-Return on Bad Channel</string>+ <string name="settings_zap_auto_revert_subtitle">Automatically return to the previous working channel if a channel stalls or fails to load.</string><string name="settings_player_controls_timeout">VOD Controls Auto-Hide</string><string name="settings_live_overlay_timeout">Live TV Overlays Auto-Hide</string><string name="settings_player_notice_timeout">Playback Notices Auto-Hide</string>@@ -423,6 +432,8 @@<string name="settings_live_channel_numbering_group_desc">Default behavior. Renumber channels based on their position inside the current category or custom group.</string><string name="settings_live_channel_numbering_provider">Provider Number</string><string name="settings_live_channel_numbering_provider_desc">Keep the original channel number supplied by the playlist provider whenever it exists.</string>+ <string name="settings_live_channel_numbering_hidden">Hidden</string>+ <string name="settings_live_channel_numbering_hidden_desc">Never show channel numbers anywhere in the app.</string><string name="settings_vod_view_mode">VOD layout</string><string name="settings_vod_view_mode_subtitle">Choose between the modern shelves view and a classic split layout.</string><string name="settings_vod_view_mode_modern">Modern</string>@@ -463,6 +474,7 @@<string name="settings_updates_title">Updates</string><string name="settings_updates_subtitle">Check GitHub Releases for newer StreamVault versions without leaving the app.</string><string name="settings_update_auto_check">Automatically check for updates</string>+ <string name="settings_update_auto_download">Automatically download updates</string><string name="settings_update_latest_release">Latest release</string><string name="settings_update_status">Update status</string><string name="settings_update_last_checked">Last checked</string>@@ -594,6 +606,8 @@<string name="settings_recording_active_label">Active</string><string name="settings_recording_scheduled_label">Scheduled</string><string name="settings_recording_space_label">Free Space</string>+ <string name="settings_recording_open_browser">Open Recordings</string>+ <string name="settings_recording_item_count">%1$d items</string><string name="settings_recording_empty_title">No active recordings</string><string name="settings_recording_empty_subtitle">Start a manual recording from live playback or schedule one from the player.</string><string name="settings_recording_status_scheduled">Scheduled</string>@@ -745,6 +759,16 @@<string name="search_hint">Search...</string><string name="search_recent_title">Recent Searches</string><string name="search_clear_history">Clear</string>+ <string name="search_actions_title">%1$s</string>+ <string name="search_actions_add_favorite">Add to Favorites</string>+ <string name="search_actions_remove_favorite">Remove from Favorites</string>+ <string name="search_actions_hide_category">Hide Category</string>+ <string name="search_actions_hide_no_category">Hide (no category)</string>+ <string name="search_actions_lock">Lock with Parental Control</string>+ <string name="search_actions_unlock">Unlock Parental Control</string>+ <string name="search_actions_lock_no_category">Lock (no category)</string>+ <string name="search_actions_dismiss">Dismiss</string>+ <string name="search_actions_pin_subtitle">Enter your parental PIN to confirm</string><string name="library_action_hide_search">Hide Search</string><string name="library_action_filters_sort">Filters & Sort</string><string name="a11y_selected">Selected</string>@@ -961,6 +985,9 @@<string name="epg_show_app_navigation">Show App Nav</string><string name="epg_program_details_show">Program Details</string><string name="epg_program_details_hide">Hide Details</string>+ <string name="epg_program_reminder_set">Remind Me</string>+ <string name="epg_program_reminder_cancel">Cancel Reminder</string>+ <string name="epg_program_reminder_loading">Updating Reminder...</string><string name="epg_hero_no_schedule_hint">This channel has no guide entries in the current window.</string><string name="epg_hero_no_program_description">Program details are limited for this entry.</string><string name="epg_filter_label">Guide Filter</string>@@ -1101,6 +1128,7 @@<string name="player_live_timeshift_ready">Timeshift ready.</string><string name="player_live_timeshift_buffering">Local live rewind is still buffering.</string><string name="player_live_timeshift_failed">Local live rewind is unavailable for this stream.</string>+ <string name="player_live_scrubber_cd">Live rewind timeline. Use left and right to seek.</string><string name="series_loading_details">Loading details...</string><string name="series_not_found">Series not found</string><string name="series_detail_back">Back to library</string>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 b88da6e0..3999ded5 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@@ -4,14 +4,20 @@ import com.google.common.truth.Truth.assertThatimport androidx.lifecycle.ViewModelimport com.streamvault.data.preferences.PreferencesRepositoryimport com.streamvault.domain.manager.ParentalControlManager+import com.streamvault.domain.manager.ProgramReminderManagerimport com.streamvault.domain.model.Categoryimport com.streamvault.domain.model.CategorySortModeimport com.streamvault.domain.model.Channelimport com.streamvault.domain.model.ContentTypeimport com.streamvault.domain.model.Favorite+import com.streamvault.domain.model.ActiveLiveSourceimport com.streamvault.domain.model.Programimport com.streamvault.domain.model.Providerimport com.streamvault.domain.model.ProviderType+import com.streamvault.domain.model.CombinedCategory+import com.streamvault.domain.model.CombinedCategoryBinding+import com.streamvault.domain.model.CombinedM3uProfile+import com.streamvault.domain.model.CombinedM3uProfileMemberimport com.streamvault.domain.repository.ChannelRepositoryimport com.streamvault.domain.repository.CombinedM3uRepositoryimport com.streamvault.domain.repository.EpgRepository@@ -22,6 +28,7 @@ import com.streamvault.domain.usecase.GetCustomCategoriesimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.ExperimentalCoroutinesApiimport kotlinx.coroutines.flow.flowOf+import kotlinx.coroutines.runBlockingimport kotlinx.coroutines.test.StandardTestDispatcherimport kotlinx.coroutines.test.advanceUntilIdleimport kotlinx.coroutines.test.resetMain@@ -37,6 +44,7 @@ import org.mockito.kotlin.atLeastOnceimport org.mockito.kotlin.neverimport org.mockito.kotlin.verifyimport org.mockito.kotlin.whenever+import org.mockito.kotlin.argThat@OptIn(ExperimentalCoroutinesApi::class)class EpgViewModelTest {@@ -49,6 +57,7 @@ class EpgViewModelTest {private val favoriteRepository: FavoriteRepository = mock()private val preferencesRepository: PreferencesRepository = mock()private val parentalControlManager: ParentalControlManager = mock()+ private val programReminderManager: ProgramReminderManager = mock()private val getCustomCategories by lazy { GetCustomCategories(favoriteRepository) }private val createdViewModels = mutableListOf<EpgViewModel>()@@ -57,12 +66,19 @@ class EpgViewModelTest {@Beforefun setup() {Dispatchers.setMain(testDispatcher)+ whenever(providerRepository.getActiveProvider()).thenReturn(flowOf(null))whenever(preferencesRepository.parentalControlLevel).thenReturn(flowOf(0))+ whenever(preferencesRepository.showAllChannelsCategory).thenReturn(flowOf(true))whenever(combinedM3uRepository.getActiveLiveSource()).thenReturn(flowOf(null))whenever(preferencesRepository.guideDefaultCategoryId).thenReturn(flowOf(null))- whenever(favoriteRepository.getGroups(ContentType.LIVE)).thenReturn(flowOf(emptyList()))- whenever(favoriteRepository.getGlobalFavoriteCount(ContentType.LIVE)).thenReturn(flowOf(0))- whenever(favoriteRepository.getGroupFavoriteCounts(ContentType.LIVE)).thenReturn(flowOf(emptyMap()))+ runBlocking {+ whenever(epgRepository.getResolvedProgramsForChannels(any(), any(), any(), any())).thenReturn(emptyMap())+ whenever(epgRepository.getProgramsForChannels(any(), any(), any(), any())).thenReturn(flowOf(emptyMap()))+ }+ whenever(favoriteRepository.getGroups(any<Long>(), eq(ContentType.LIVE))).thenReturn(flowOf(emptyList()))+ whenever(favoriteRepository.getGroups(any<List<Long>>(), eq(ContentType.LIVE))).thenReturn(flowOf(emptyList()))+ whenever(favoriteRepository.getFavorites(any<Long>(), eq(ContentType.LIVE))).thenReturn(flowOf(emptyList()))+ whenever(favoriteRepository.getFavorites(any<List<Long>>(), eq(ContentType.LIVE))).thenReturn(flowOf(emptyList()))}@After@@ -94,6 +110,7 @@ class EpgViewModelTest {favoriteRepository = favoriteRepository,preferencesRepository = preferencesRepository,parentalControlManager = parentalControlManager,+ programReminderManager = programReminderManager,getCustomCategories = getCustomCategories).also(createdViewModels::add)@@ -125,7 +142,7 @@ class EpgViewModelTest {whenever(channelRepository.getChannels(provider.id)).thenReturn(flowOf(channels))whenever(channelRepository.getChannelsByNumber(provider.id, ChannelRepository.ALL_CHANNELS_ID)).thenReturn(flowOf(channels))whenever(channelRepository.getChannelsWithoutErrors(provider.id, ChannelRepository.ALL_CHANNELS_ID)).thenReturn(flowOf(channels))- whenever(favoriteRepository.getFavorites(ContentType.LIVE)).thenReturn(flowOf(emptyList()))+ whenever(favoriteRepository.getFavorites(provider.id, ContentType.LIVE)).thenReturn(flowOf(emptyList()))whenever(preferencesRepository.guideDensity).thenReturn(flowOf(null))whenever(preferencesRepository.guideChannelMode).thenReturn(flowOf(null))whenever(preferencesRepository.guideFavoritesOnly).thenReturn(flowOf(false))@@ -184,7 +201,7 @@ class EpgViewModelTest {whenever(channelRepository.getChannelsByNumber(provider.id, 10L)).thenReturn(flowOf(channels))whenever(channelRepository.getChannelsWithoutErrors(provider.id, ChannelRepository.ALL_CHANNELS_ID)).thenReturn(flowOf(channels))whenever(channelRepository.getChannelsWithoutErrors(provider.id, 10L)).thenReturn(flowOf(channels))- whenever(favoriteRepository.getFavorites(ContentType.LIVE)).thenReturn(flowOf(emptyList()))+ whenever(favoriteRepository.getFavorites(provider.id, ContentType.LIVE)).thenReturn(flowOf(emptyList()))whenever(preferencesRepository.guideDensity).thenReturn(flowOf(null))whenever(preferencesRepository.guideChannelMode).thenReturn(flowOf(null))whenever(preferencesRepository.guideFavoritesOnly).thenReturn(flowOf(false))@@ -278,8 +295,8 @@ class EpgViewModelTest {whenever(channelRepository.getChannelsWithoutErrors(provider.id, 10L)).thenReturn(flowOf(listOf(healthyChannel)))- whenever(favoriteRepository.getFavorites(ContentType.LIVE)).thenReturn(- flowOf(listOf(Favorite(contentId = unhealthyFavorite.id, contentType = ContentType.LIVE)))+ whenever(favoriteRepository.getFavorites(provider.id, ContentType.LIVE)).thenReturn(+ flowOf(listOf(Favorite(providerId = provider.id, contentId = unhealthyFavorite.id, contentType = ContentType.LIVE))))whenever(preferencesRepository.guideDensity).thenReturn(flowOf(null))whenever(preferencesRepository.guideChannelMode).thenReturn(flowOf(null))@@ -298,6 +315,7 @@ class EpgViewModelTest {favoriteRepository = favoriteRepository,preferencesRepository = preferencesRepository,parentalControlManager = parentalControlManager,+ programReminderManager = programReminderManager,getCustomCategories = getCustomCategories)@@ -328,7 +346,7 @@ class EpgViewModelTest {whenever(channelRepository.getCategories(provider.id)).thenReturn(flowOf(listOf(Category(id = 10L, name = "News", count = 1))))whenever(channelRepository.getChannelsByNumber(provider.id, ChannelRepository.ALL_CHANNELS_ID)).thenReturn(flowOf(channels))whenever(channelRepository.getChannelsWithoutErrors(provider.id, ChannelRepository.ALL_CHANNELS_ID)).thenReturn(flowOf(channels))- whenever(favoriteRepository.getFavorites(ContentType.LIVE)).thenReturn(flowOf(emptyList()))+ whenever(favoriteRepository.getFavorites(provider.id, ContentType.LIVE)).thenReturn(flowOf(emptyList()))whenever(preferencesRepository.guideDensity).thenReturn(flowOf(null))whenever(preferencesRepository.guideChannelMode).thenReturn(flowOf(null))whenever(preferencesRepository.guideFavoritesOnly).thenReturn(flowOf(false))@@ -347,6 +365,7 @@ class EpgViewModelTest {favoriteRepository = favoriteRepository,preferencesRepository = preferencesRepository,parentalControlManager = parentalControlManager,+ programReminderManager = programReminderManager,getCustomCategories = getCustomCategories)@@ -355,4 +374,89 @@ class EpgViewModelTest {assertThat(viewModel.uiState.value.selectedCategoryId).isEqualTo(ChannelRepository.ALL_CHANNELS_ID)}++ @Test+ fun `combined guide merges favorites across member providers`() = runTest {+ val providerOneChannel = Channel(+ id = 101L,+ name = "Provider One Favorite",+ providerId = 1L,+ epgChannelId = "one",+ number = 1,+ categoryId = 10L+ )+ val providerTwoChannel = Channel(+ id = 201L,+ name = "Provider Two Favorite",+ providerId = 2L,+ epgChannelId = "two",+ number = 2,+ categoryId = 20L+ )+ val profile = CombinedM3uProfile(+ id = 77L,+ name = "Combined",+ members = listOf(+ CombinedM3uProfileMember(profileId = 77L, providerId = 1L, priority = 0, enabled = true),+ CombinedM3uProfileMember(profileId = 77L, providerId = 2L, priority = 1, enabled = true)+ )+ )++ whenever(combinedM3uRepository.getActiveLiveSource()).thenReturn(+ flowOf(ActiveLiveSource.CombinedM3uSource(profile.id))+ )+ whenever(combinedM3uRepository.getProfile(profile.id)).thenReturn(profile)+ whenever(combinedM3uRepository.getCombinedCategories(profile.id)).thenReturn(+ flowOf(+ listOf(+ CombinedCategory(+ category = Category(id = 10L, name = "One"),+ bindings = listOf(CombinedCategoryBinding(providerId = 1L, providerName = "Provider One", categoryId = 10L))+ ),+ CombinedCategory(+ category = Category(id = 20L, name = "Two"),+ bindings = listOf(CombinedCategoryBinding(providerId = 2L, providerName = "Provider Two", categoryId = 20L))+ )+ )+ )+ )+ whenever(combinedM3uRepository.getCombinedChannels(eq(profile.id), any())).thenAnswer { invocation ->+ val combinedCategory = invocation.getArgument<CombinedCategory>(1)+ when (combinedCategory.category.id) {+ 10L -> flowOf(listOf(providerOneChannel))+ 20L -> flowOf(listOf(providerTwoChannel))+ else -> flowOf(emptyList())+ }+ }+ whenever(channelRepository.getChannelsByIds(listOf(providerOneChannel.id, providerTwoChannel.id))).thenReturn(+ flowOf(listOf(providerOneChannel, providerTwoChannel))+ )+ whenever(favoriteRepository.getFavorites(argThat<List<Long>> { this == listOf(1L, 2L) }, eq(ContentType.LIVE))).thenReturn(+ flowOf(+ listOf(+ Favorite(providerId = 1L, contentId = providerOneChannel.id, contentType = ContentType.LIVE, position = 0),+ Favorite(providerId = 2L, contentId = providerTwoChannel.id, contentType = ContentType.LIVE, position = 1)+ )+ )+ )+ whenever(preferencesRepository.guideDensity).thenReturn(flowOf(null))+ whenever(preferencesRepository.guideChannelMode).thenReturn(flowOf(null))+ whenever(preferencesRepository.guideFavoritesOnly).thenReturn(flowOf(true))+ whenever(preferencesRepository.guideScheduledOnly).thenReturn(flowOf(false))+ whenever(preferencesRepository.guideAnchorTime).thenReturn(flowOf(null))+ whenever(preferencesRepository.guideDefaultCategoryId).thenReturn(flowOf(com.streamvault.domain.model.VirtualCategoryIds.FAVORITES))+ whenever(epgRepository.getResolvedProgramsForChannels(eq(0L), any(), any(), any())).thenReturn(emptyMap())+ whenever(epgRepository.getProgramsForChannels(eq(0L), any(), any(), any())).thenReturn(flowOf(emptyMap()))++ val viewModel = createViewModel()++ advanceUntilIdle()+ waitForUiState {+ viewModel.uiState.value.channels.map { it.id } == listOf(providerOneChannel.id, providerTwoChannel.id)+ }++ assertThat(viewModel.uiState.value.channels.map { it.id })+ .containsExactly(providerOneChannel.id, providerTwoChannel.id)+ verify(favoriteRepository, atLeastOnce()).getFavorites(argThat<List<Long>> { this == listOf(1L, 2L) }, eq(ContentType.LIVE))+ }}diff --git a/app/src/test/java/com/streamvault/app/ui/screens/home/HomeViewModelTest.kt b/app/src/test/java/com/streamvault/app/ui/screens/home/HomeViewModelTest.ktindex fce829f3..2b7a2b3d 100644--- a/app/src/test/java/com/streamvault/app/ui/screens/home/HomeViewModelTest.kt+++ b/app/src/test/java/com/streamvault/app/ui/screens/home/HomeViewModelTest.kt@@ -71,12 +71,15 @@ class HomeViewModelTest {whenever(combinedM3uRepository.getActiveLiveSource()).thenReturn(flowOf(null))whenever(combinedM3uRepository.getActiveLiveSourceOptions()).thenReturn(flowOf(emptyList()))whenever(preferencesRepository.parentalControlLevel).thenReturn(flowOf(0))- whenever(favoriteRepository.getFavorites(any())).thenReturn(flowOf(emptyList()))+ whenever(favoriteRepository.getFavorites(any<Long>(), eq(ContentType.LIVE))).thenReturn(flowOf(emptyList()))+ whenever(favoriteRepository.getFavorites(any<List<Long>>(), eq(ContentType.LIVE))).thenReturn(flowOf(emptyList()))whenever(preferencesRepository.defaultCategoryId).thenReturn(flowOf(null))whenever(preferencesRepository.getLastLiveCategoryId(any())).thenReturn(flowOf(null))whenever(preferencesRepository.liveTvChannelMode).thenReturn(flowOf("COMPACT"))whenever(preferencesRepository.liveTvCategoryFilters).thenReturn(flowOf(emptyList()))whenever(preferencesRepository.liveTvQuickFilterVisibility).thenReturn(flowOf(null))+ whenever(preferencesRepository.showRecentChannelsCategory).thenReturn(flowOf(true))+ whenever(preferencesRepository.showAllChannelsCategory).thenReturn(flowOf(true))whenever(preferencesRepository.showLiveSourceSwitcher).thenReturn(flowOf(false))whenever(preferencesRepository.liveChannelNumberingMode).thenReturn(flowOf(ChannelNumberingMode.PROVIDER))whenever(preferencesRepository.isIncognitoMode).thenReturn(flowOf(false))@@ -84,7 +87,8 @@ class HomeViewModelTest {whenever(preferencesRepository.getCategorySortMode(any(), any())).thenReturn(flowOf(CategorySortMode.DEFAULT))whenever(preferencesRepository.getPinnedCategoryIds(any(), any())).thenReturn(flowOf(emptySet()))whenever(playbackHistoryRepository.getRecentlyWatchedByProvider(any(), any())).thenReturn(flowOf(emptyList()))- whenever(getCustomCategories()).thenReturn(flowOf(emptyList()))+ whenever(getCustomCategories.invoke(any<Long>(), eq(ContentType.LIVE))).thenReturn(flowOf(emptyList()))+ whenever(getCustomCategories.invoke(any<List<Long>>(), eq(ContentType.LIVE))).thenReturn(flowOf(emptyList()))whenever(favoriteRepository.getFavoritesByGroup(any())).thenReturn(flowOf(emptyList()))whenever(parentalControlManager.unlockedCategoriesForProvider(any())).thenReturn(flowOf(emptySet()))whenever(syncManager.syncStateForProvider(any())).thenReturn(flowOf(SyncState.Idle))@@ -166,7 +170,7 @@ class HomeViewModelTest {val category = Category(id = 1L, name = "Sports", parentId = null)// Mock the repositories needed for loading channels- whenever(channelRepository.getChannelsByCategory(any(), any())).thenReturn(flowOf(emptyList()))+ whenever(channelRepository.getChannelsByCategoryPage(any(), any(), any())).thenReturn(flowOf(emptyList()))val provider = Provider(id = 1L, name = "Provider", type = com.streamvault.domain.model.ProviderType.M3U, serverUrl = "http://test")whenever(providerRepository.getActiveProvider()).thenReturn(flowOf(provider))viewModel = createViewModel()@@ -190,7 +194,7 @@ class HomeViewModelTest {)whenever(providerRepository.getActiveProvider()).thenReturn(flowOf(provider))whenever(channelRepository.getCategories(provider.id)).thenReturn(flowOf(emptyList()))- whenever(getCustomCategories()).thenReturn(+ whenever(getCustomCategories.invoke(eq(provider.id), eq(ContentType.LIVE))).thenReturn(flowOf(listOf(Category(@@ -226,7 +230,7 @@ class HomeViewModelTest {)))- whenever(favoriteRepository.getFavorites(ContentType.LIVE)).thenReturn(flowOf(emptyList()))+ whenever(favoriteRepository.getFavorites(provider.id, ContentType.LIVE)).thenReturn(flowOf(emptyList()))viewModel = createViewModel()@@ -246,7 +250,7 @@ class HomeViewModelTest {)whenever(providerRepository.getActiveProvider()).thenReturn(flowOf(provider))whenever(channelRepository.getCategories(provider.id)).thenReturn(flowOf(emptyList()))- whenever(getCustomCategories()).thenReturn(+ whenever(getCustomCategories.invoke(eq(provider.id), eq(ContentType.LIVE))).thenReturn(flowOf(listOf(Category(@@ -258,7 +262,7 @@ class HomeViewModelTest {))whenever(playbackHistoryRepository.getRecentlyWatchedByProvider(eq(provider.id), any())).thenReturn(flowOf(emptyList()))- whenever(favoriteRepository.getFavorites(ContentType.LIVE)).thenReturn(flowOf(emptyList()))+ whenever(favoriteRepository.getFavorites(provider.id, ContentType.LIVE)).thenReturn(flowOf(emptyList()))viewModel = createViewModel()@@ -284,7 +288,7 @@ class HomeViewModelTest {val sportsCategory = Category(id = 5L, name = "Sports")whenever(providerRepository.getActiveProvider()).thenReturn(flowOf(provider))whenever(channelRepository.getCategories(provider.id)).thenReturn(flowOf(listOf(sportsCategory)))- whenever(getCustomCategories()).thenReturn(+ whenever(getCustomCategories.invoke(eq(provider.id), eq(ContentType.LIVE))).thenReturn(flowOf(listOf(Category(@@ -297,7 +301,7 @@ class HomeViewModelTest {)whenever(playbackHistoryRepository.getRecentlyWatchedByProvider(eq(provider.id), any())).thenReturn(flowOf(emptyList()))whenever(preferencesRepository.getLastLiveCategoryId(provider.id)).thenReturn(flowOf(sportsCategory.id))- whenever(favoriteRepository.getFavorites(ContentType.LIVE)).thenReturn(flowOf(emptyList()))+ whenever(favoriteRepository.getFavorites(provider.id, ContentType.LIVE)).thenReturn(flowOf(emptyList()))viewModel = createViewModel()@@ -318,10 +322,10 @@ class HomeViewModelTest {val category = Category(id = 7L, name = "Kids")whenever(providerRepository.getActiveProvider()).thenReturn(flowOf(provider))whenever(channelRepository.getCategories(provider.id)).thenReturn(flowOf(listOf(category)))- whenever(channelRepository.getChannelsByCategory(provider.id, category.id)).thenReturn(flowOf(emptyList()))- whenever(getCustomCategories()).thenReturn(flowOf(emptyList()))+ whenever(channelRepository.getChannelsByCategoryPage(eq(provider.id), eq(category.id), any())).thenReturn(flowOf(emptyList()))+ whenever(getCustomCategories.invoke(eq(provider.id), eq(ContentType.LIVE))).thenReturn(flowOf(emptyList()))whenever(playbackHistoryRepository.getRecentlyWatchedByProvider(eq(provider.id), any())).thenReturn(flowOf(emptyList()))- whenever(favoriteRepository.getFavorites(ContentType.LIVE)).thenReturn(flowOf(emptyList()))+ whenever(favoriteRepository.getFavorites(provider.id, ContentType.LIVE)).thenReturn(flowOf(emptyList()))viewModel = createViewModel()@@ -348,9 +352,9 @@ class HomeViewModelTest {)whenever(providerRepository.getActiveProvider()).thenReturn(flowOf(provider))whenever(channelRepository.getCategories(provider.id)).thenReturn(flowOf(emptyList()))- whenever(getCustomCategories()).thenReturn(flowOf(emptyList()))+ whenever(getCustomCategories.invoke(eq(provider.id), eq(ContentType.LIVE))).thenReturn(flowOf(emptyList()))whenever(playbackHistoryRepository.getRecentlyWatchedByProvider(eq(provider.id), any())).thenReturn(flowOf(emptyList()))- whenever(favoriteRepository.getFavorites(ContentType.LIVE)).thenReturn(flowOf(emptyList()))+ whenever(favoriteRepository.getFavorites(provider.id, ContentType.LIVE)).thenReturn(flowOf(emptyList()))viewModel = createViewModel()@@ -372,15 +376,15 @@ class HomeViewModelTest {val category = Category(id = 11L, name = "News")whenever(providerRepository.getActiveProvider()).thenReturn(flowOf(provider))whenever(channelRepository.getCategories(provider.id)).thenReturn(flowOf(listOf(category)))- whenever(channelRepository.getChannelsByCategory(provider.id, category.id)).thenReturn(+ whenever(channelRepository.getChannelsByCategoryPage(eq(provider.id), eq(category.id), any())).thenReturn(flowOf(listOf(Channel(id = 1L, name = "BBC News", providerId = provider.id, streamUrl = "https://stream"))))- whenever(channelRepository.searchChannelsByCategory(provider.id, category.id, "bbc")).thenReturn(+ whenever(channelRepository.searchChannelsByCategoryPaged(eq(provider.id), eq(category.id), eq("bbc"), any())).thenReturn(flowOf(listOf(Channel(id = 1L, name = "BBC News", providerId = provider.id, streamUrl = "https://stream"))))- whenever(getCustomCategories()).thenReturn(flowOf(emptyList()))+ whenever(getCustomCategories.invoke(eq(provider.id), eq(ContentType.LIVE))).thenReturn(flowOf(emptyList()))whenever(playbackHistoryRepository.getRecentlyWatchedByProvider(eq(provider.id), any())).thenReturn(flowOf(emptyList()))- whenever(favoriteRepository.getFavorites(ContentType.LIVE)).thenReturn(flowOf(emptyList()))+ whenever(favoriteRepository.getFavorites(provider.id, ContentType.LIVE)).thenReturn(flowOf(emptyList()))viewModel = createViewModel()advanceUntilIdle()@@ -390,6 +394,39 @@ class HomeViewModelTest {viewModel.updateChannelSearchQuery("bbc")advanceUntilIdle()- verify(channelRepository).searchChannelsByCategory(provider.id, category.id, "bbc")+ verify(channelRepository).searchChannelsByCategoryPaged(eq(provider.id), eq(category.id), eq("bbc"), any())+ }++ @Test+ fun `hidden numbering mode keeps displayed channel numbers non-negative`() = runTest {+ val provider = Provider(+ id = 31L,+ name = "Provider",+ type = ProviderType.M3U,+ serverUrl = "https://test"+ )+ val category = Category(id = 12L, name = "News")+ val channel = Channel(+ id = 1L,+ name = "BBC News",+ providerId = provider.id,+ streamUrl = "https://stream",+ number = 23+ )+ whenever(preferencesRepository.liveChannelNumberingMode).thenReturn(flowOf(ChannelNumberingMode.HIDDEN))+ whenever(providerRepository.getActiveProvider()).thenReturn(flowOf(provider))+ whenever(channelRepository.getCategories(provider.id)).thenReturn(flowOf(listOf(category)))+ whenever(channelRepository.getChannelsByCategoryPage(eq(provider.id), eq(category.id), any())).thenReturn(flowOf(listOf(channel)))+ whenever(getCustomCategories.invoke(eq(provider.id), eq(ContentType.LIVE))).thenReturn(flowOf(emptyList()))+ whenever(playbackHistoryRepository.getRecentlyWatchedByProvider(eq(provider.id), any())).thenReturn(flowOf(emptyList()))+ whenever(favoriteRepository.getFavorites(provider.id, ContentType.LIVE)).thenReturn(flowOf(emptyList()))++ viewModel = createViewModel()+ advanceUntilIdle()++ viewModel.selectCategory(category)+ advanceUntilIdle()++ assertThat(viewModel.uiState.value.filteredChannels.map(Channel::number)).containsExactly(0)}}diff --git a/app/src/test/java/com/streamvault/app/ui/screens/player/PlayerZapActionsTest.kt b/app/src/test/java/com/streamvault/app/ui/screens/player/PlayerZapActionsTest.ktnew file mode 100644index 00000000..81c981d9--- /dev/null+++ b/app/src/test/java/com/streamvault/app/ui/screens/player/PlayerZapActionsTest.kt@@ -0,0 +1,30 @@+package com.streamvault.app.ui.screens.player++import com.google.common.truth.Truth.assertThat+import org.junit.Test++class PlayerZapActionsTest {++ @Test+ fun `appendNumericChannelDigit keeps up to six digits`() {+ var buffer = ""++ (1..6).forEach { digit ->+ buffer = appendNumericChannelDigit(buffer, digit)+ }++ assertThat(buffer).isEqualTo("123456")+ }++ @Test+ fun `appendNumericChannelDigit restarts after sixth digit`() {+ var buffer = ""++ (1..6).forEach { digit ->+ buffer = appendNumericChannelDigit(buffer, digit)+ }+ buffer = appendNumericChannelDigit(buffer, 7)++ assertThat(buffer).isEqualTo("7")+ }+}\ No newline at end of filediff --git a/app/src/test/java/com/streamvault/app/ui/screens/search/SearchViewModelTest.kt b/app/src/test/java/com/streamvault/app/ui/screens/search/SearchViewModelTest.ktindex 161ee9ca..d1dfac89 100644--- a/app/src/test/java/com/streamvault/app/ui/screens/search/SearchViewModelTest.kt+++ b/app/src/test/java/com/streamvault/app/ui/screens/search/SearchViewModelTest.kt@@ -5,9 +5,12 @@ import com.streamvault.domain.model.Channelimport com.streamvault.domain.model.Movieimport com.streamvault.domain.model.Providerimport com.streamvault.domain.model.ProviderType+import com.streamvault.domain.model.SearchHistoryScopeimport com.streamvault.domain.model.Seriesimport com.streamvault.data.preferences.PreferencesRepositoryimport com.streamvault.domain.manager.ParentalControlManager+import com.streamvault.domain.repository.CategoryRepository+import com.streamvault.domain.repository.FavoriteRepositoryimport com.streamvault.domain.repository.ProviderRepositoryimport com.streamvault.domain.usecase.SearchContentimport com.streamvault.domain.usecase.SearchContentResult@@ -23,8 +26,11 @@ import kotlinx.coroutines.launchimport org.junit.Afterimport org.junit.Beforeimport org.junit.Test+import org.mockito.kotlin.anyOrNullimport org.mockito.kotlin.mockimport org.mockito.kotlin.any+import org.mockito.kotlin.eq+import org.mockito.kotlin.verifyimport org.mockito.kotlin.whenever@OptIn(ExperimentalCoroutinesApi::class)@@ -34,6 +40,8 @@ class SearchViewModelTest {private val searchContent: SearchContent = mock()private val preferencesRepository: PreferencesRepository = mock()private val parentalControlManager: ParentalControlManager = mock()+ private val favoriteRepository: FavoriteRepository = mock()+ private val categoryRepository: CategoryRepository = mock()private lateinit var viewModel: SearchViewModel@@ -42,7 +50,7 @@ class SearchViewModelTest {Dispatchers.setMain(StandardTestDispatcher())whenever(providerRepository.getActiveProvider()).thenReturn(flowOf(null))whenever(preferencesRepository.parentalControlLevel).thenReturn(flowOf(0))- whenever(preferencesRepository.recentSearchQueries).thenReturn(flowOf(emptyList()))+ whenever(preferencesRepository.getRecentSearchQueries(any(), anyOrNull(), any())).thenReturn(flowOf(emptyList()))whenever(parentalControlManager.unlockedCategoriesForProvider(any())).thenReturn(flowOf(emptySet()))whenever(searchContent.invoke(any(), any(), any(), any())).thenReturn(flowOf(SearchContentResult()))@@ -50,7 +58,9 @@ class SearchViewModelTest {providerRepository,searchContent,preferencesRepository,- parentalControlManager+ parentalControlManager,+ favoriteRepository,+ categoryRepository)}@@ -63,37 +73,25 @@ class SearchViewModelTest {fun `submitted queries are stored trimmed deduplicated and capped`() = runTest {viewModel.onQueryChange(" news ")viewModel.onSearchSubmitted()- viewModel.onQueryChange("sports")- viewModel.onSearchSubmitted()- viewModel.onQueryChange("NEWS")- viewModel.onSearchSubmitted()- viewModel.onQueryChange("movies")- viewModel.onSearchSubmitted()- viewModel.onQueryChange("series")- viewModel.onSearchSubmitted()- viewModel.onQueryChange("kids")- viewModel.onSearchSubmitted()- viewModel.onQueryChange("music")- viewModel.onSearchSubmitted()+ advanceUntilIdle()- assertThat(viewModel.recentQueries.value).containsExactly(- "music",- "kids",- "series",- "movies",- "NEWS",- "sports"- ).inOrder()+ verify(preferencesRepository).recordRecentSearchQuery(+ query = eq("news"),+ scope = eq(SearchHistoryScope.ALL),+ providerId = eq(null),+ usedAt = any()+ )}@Testfun `clearRecentQueries removes all stored search shortcuts`() = runTest {- viewModel.onQueryChange("news")- viewModel.onSearchSubmitted()-viewModel.clearRecentQueries()+ advanceUntilIdle()- assertThat(viewModel.recentQueries.value).isEmpty()+ verify(preferencesRepository).clearRecentSearchQueries(+ scope = eq(SearchHistoryScope.ALL),+ providerId = eq(null)+ )}@Test@@ -113,7 +111,9 @@ class SearchViewModelTest {providerRepository,searchContent,preferencesRepository,- parentalControlManager+ parentalControlManager,+ favoriteRepository,+ categoryRepository)val collectorJob = backgroundScope.launch { viewModel.uiState.collect { } }@@ -154,7 +154,9 @@ class SearchViewModelTest {providerRepository,searchContent,preferencesRepository,- parentalControlManager+ parentalControlManager,+ favoriteRepository,+ categoryRepository)val collectorJob = backgroundScope.launch { viewModel.uiState.collect { } }diff --git a/data/schemas/com.streamvault.data.local.StreamVaultDatabase/31.json b/data/schemas/com.streamvault.data.local.StreamVaultDatabase/31.jsonnew file mode 100644index 00000000..46c74504--- /dev/null+++ b/data/schemas/com.streamvault.data.local.StreamVaultDatabase/31.json@@ -0,0 +1,3640 @@+{+ "formatVersion": 1,+ "database": {+ "version": 31,+ "identityHash": "1c84bc379c0d691e69d18d3752547480",+ "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, `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, `xtream_fast_sync_enabled` INTEGER 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": "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": "xtreamFastSyncEnabled",+ "columnName": "xtream_fast_sync_enabled",+ "affinity": "INTEGER",+ "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",+ "unique": true,+ "columnNames": [+ "server_url",+ "username"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_providers_server_url_username` ON `${TABLE_NAME}` (`server_url`, `username`)"+ }+ ]+ },+ {+ "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, `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": "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, `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, 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": "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+ }+ ],+ "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`)"+ }+ ],+ "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, `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, 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": "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+ }+ ],+ "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`)"+ }+ ],+ "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, 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+ }+ ],+ "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, `name` TEXT NOT NULL, `poster_url` TEXT, `backdrop_url` TEXT, `category_id` INTEGER, `category_name` TEXT, `plot` TEXT, `cast` TEXT, `director` TEXT, `genre` TEXT, `release_date` TEXT, `rating` REAL NOT NULL, `tmdb_id` INTEGER, `youtube_trailer` TEXT, `episode_run_time` TEXT, `last_modified` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, PRIMARY KEY(`session_id`, `provider_id`, `series_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON 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": "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",+ "series_id"+ ]+ },+ "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_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, `content_id` INTEGER NOT NULL, `content_type` TEXT NOT NULL, `position` INTEGER NOT NULL, `group_id` INTEGER, `added_at` INTEGER NOT NULL, 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": "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": "addedAt",+ "columnName": "added_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_favorites_content_id_content_type_group_id",+ "unique": true,+ "columnNames": [+ "content_id",+ "content_type",+ "group_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_favorites_content_id_content_type_group_id` ON `${TABLE_NAME}` (`content_id`, `content_type`, `group_id`)"+ },+ {+ "name": "index_favorites_content_type_group_id",+ "unique": false,+ "columnNames": [+ "content_type",+ "group_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_favorites_content_type_group_id` ON `${TABLE_NAME}` (`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": "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, `name` TEXT NOT NULL, `icon_emoji` TEXT, `position` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `content_type` TEXT NOT NULL)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "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_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`)"+ }+ ]+ },+ {+ "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`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "sync_metadata",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `last_live_sync` INTEGER NOT NULL, `last_movie_sync` INTEGER NOT NULL, `last_series_sync` INTEGER NOT NULL, `last_epg_sync` 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": "lastMovieSync",+ "columnName": "last_movie_sync",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastSeriesSync",+ "columnName": "last_series_sync",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastEpgSync",+ "columnName": "last_epg_sync",+ "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, 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"+ }+ ],+ "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, 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"+ }+ ],+ "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)",+ "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+ }+ ],+ "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, `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": "isManualOverride",+ "columnName": "is_manual_override",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_channel_epg_mappings_provider_id_provider_channel_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "provider_channel_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_channel_epg_mappings_provider_id_provider_channel_id` ON `${TABLE_NAME}` (`provider_id`, `provider_channel_id`)"+ },+ {+ "name": "index_channel_epg_mappings_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channel_epg_mappings_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "combined_m3u_profiles",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `enabled` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "enabled",+ "columnName": "enabled",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ }+ },+ {+ "tableName": "combined_m3u_profile_members",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `profile_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `enabled` INTEGER NOT NULL, FOREIGN KEY(`profile_id`) REFERENCES `combined_m3u_profiles`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "profileId",+ "columnName": "profile_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "priority",+ "columnName": "priority",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "enabled",+ "columnName": "enabled",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_combined_m3u_profile_members_profile_id",+ "unique": false,+ "columnNames": [+ "profile_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_combined_m3u_profile_members_profile_id` ON `${TABLE_NAME}` (`profile_id`)"+ },+ {+ "name": "index_combined_m3u_profile_members_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_combined_m3u_profile_members_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_combined_m3u_profile_members_profile_id_provider_id",+ "unique": true,+ "columnNames": [+ "profile_id",+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_combined_m3u_profile_members_profile_id_provider_id` ON `${TABLE_NAME}` (`profile_id`, `provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "combined_m3u_profiles",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "profile_id"+ ],+ "referencedColumns": [+ "id"+ ]+ },+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "recording_schedules",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, `channel_name` TEXT NOT NULL, `stream_url` TEXT NOT NULL, `program_title` TEXT, `requested_start_ms` INTEGER NOT NULL, `requested_end_ms` INTEGER NOT NULL, `recurrence` TEXT NOT NULL, `recurring_rule_id` TEXT, `enabled` INTEGER NOT NULL, `is_manual` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelId",+ "columnName": "channel_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelName",+ "columnName": "channel_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "programTitle",+ "columnName": "program_title",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "requestedStartMs",+ "columnName": "requested_start_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "requestedEndMs",+ "columnName": "requested_end_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "recurrence",+ "columnName": "recurrence",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "recurringRuleId",+ "columnName": "recurring_rule_id",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "enabled",+ "columnName": "enabled",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isManual",+ "columnName": "is_manual",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "priority",+ "columnName": "priority",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_recording_schedules_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_schedules_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_recording_schedules_enabled_requested_start_ms",+ "unique": false,+ "columnNames": [+ "enabled",+ "requested_start_ms"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_schedules_enabled_requested_start_ms` ON `${TABLE_NAME}` (`enabled`, `requested_start_ms`)"+ },+ {+ "name": "index_recording_schedules_recurring_rule_id",+ "unique": false,+ "columnNames": [+ "recurring_rule_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_schedules_recurring_rule_id` ON `${TABLE_NAME}` (`recurring_rule_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "recording_runs",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `schedule_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, `channel_name` TEXT NOT NULL, `stream_url` TEXT NOT NULL, `program_title` TEXT, `scheduled_start_ms` INTEGER NOT NULL, `scheduled_end_ms` INTEGER NOT NULL, `recurrence` TEXT NOT NULL, `recurring_rule_id` TEXT, `status` TEXT NOT NULL, `source_type` TEXT NOT NULL, `resolved_url` TEXT, `headers_json` TEXT NOT NULL, `user_agent` TEXT, `expiration_time` INTEGER, `provider_label` TEXT, `output_uri` TEXT, `output_display_path` TEXT, `bytes_written` INTEGER NOT NULL, `average_throughput_bps` INTEGER NOT NULL, `retry_count` INTEGER NOT NULL, `last_progress_at_ms` INTEGER, `failure_category` TEXT NOT NULL, `failure_reason` TEXT, `terminal_at_ms` INTEGER, `started_at_ms` INTEGER, `ended_at_ms` INTEGER, `schedule_enabled` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `alarm_start_at_ms` INTEGER, `alarm_stop_at_ms` INTEGER, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`schedule_id`) REFERENCES `recording_schedules`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "scheduleId",+ "columnName": "schedule_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelId",+ "columnName": "channel_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelName",+ "columnName": "channel_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "programTitle",+ "columnName": "program_title",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "scheduledStartMs",+ "columnName": "scheduled_start_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "scheduledEndMs",+ "columnName": "scheduled_end_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "recurrence",+ "columnName": "recurrence",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "recurringRuleId",+ "columnName": "recurring_rule_id",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "status",+ "columnName": "status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "sourceType",+ "columnName": "source_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "resolvedUrl",+ "columnName": "resolved_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "headersJson",+ "columnName": "headers_json",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "userAgent",+ "columnName": "user_agent",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "expirationTime",+ "columnName": "expiration_time",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "providerLabel",+ "columnName": "provider_label",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "outputUri",+ "columnName": "output_uri",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "outputDisplayPath",+ "columnName": "output_display_path",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "bytesWritten",+ "columnName": "bytes_written",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "averageThroughputBytesPerSecond",+ "columnName": "average_throughput_bps",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "retryCount",+ "columnName": "retry_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastProgressAtMs",+ "columnName": "last_progress_at_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "failureCategory",+ "columnName": "failure_category",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "failureReason",+ "columnName": "failure_reason",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "terminalAtMs",+ "columnName": "terminal_at_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "startedAtMs",+ "columnName": "started_at_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "endedAtMs",+ "columnName": "ended_at_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "scheduleEnabled",+ "columnName": "schedule_enabled",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "priority",+ "columnName": "priority",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "alarmStartAtMs",+ "columnName": "alarm_start_at_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "alarmStopAtMs",+ "columnName": "alarm_stop_at_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_recording_runs_schedule_id",+ "unique": false,+ "columnNames": [+ "schedule_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_schedule_id` ON `${TABLE_NAME}` (`schedule_id`)"+ },+ {+ "name": "index_recording_runs_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_recording_runs_status_scheduled_start_ms",+ "unique": false,+ "columnNames": [+ "status",+ "scheduled_start_ms"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_status_scheduled_start_ms` ON `${TABLE_NAME}` (`status`, `scheduled_start_ms`)"+ },+ {+ "name": "index_recording_runs_alarm_start_at_ms",+ "unique": false,+ "columnNames": [+ "alarm_start_at_ms"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_alarm_start_at_ms` ON `${TABLE_NAME}` (`alarm_start_at_ms`)"+ },+ {+ "name": "index_recording_runs_alarm_stop_at_ms",+ "unique": false,+ "columnNames": [+ "alarm_stop_at_ms"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_alarm_stop_at_ms` ON `${TABLE_NAME}` (`alarm_stop_at_ms`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "recording_schedules",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "schedule_id"+ ],+ "referencedColumns": [+ "id"+ ]+ },+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "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"+ ]+ }+ }+ ],+ "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, '1c84bc379c0d691e69d18d3752547480')"+ ]+ }+}\ No newline at end of filediff --git a/data/schemas/com.streamvault.data.local.StreamVaultDatabase/32.json b/data/schemas/com.streamvault.data.local.StreamVaultDatabase/32.jsonnew file mode 100644index 00000000..fce8882c--- /dev/null+++ b/data/schemas/com.streamvault.data.local.StreamVaultDatabase/32.json@@ -0,0 +1,3694 @@+{+ "formatVersion": 1,+ "database": {+ "version": 32,+ "identityHash": "7e9582bb9ffc4ecf92bf3cf486687f29",+ "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, `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, `xtream_fast_sync_enabled` INTEGER 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": "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": "xtreamFastSyncEnabled",+ "columnName": "xtream_fast_sync_enabled",+ "affinity": "INTEGER",+ "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",+ "unique": true,+ "columnNames": [+ "server_url",+ "username"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_providers_server_url_username` ON `${TABLE_NAME}` (`server_url`, `username`)"+ }+ ]+ },+ {+ "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, `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": "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, `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, 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": "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+ }+ ],+ "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`)"+ }+ ],+ "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, `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, 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": "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+ }+ ],+ "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`)"+ }+ ],+ "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, `name` TEXT NOT NULL, `poster_url` TEXT, `backdrop_url` TEXT, `category_id` INTEGER, `category_name` TEXT, `plot` TEXT, `cast` TEXT, `director` TEXT, `genre` TEXT, `release_date` TEXT, `rating` REAL NOT NULL, `tmdb_id` INTEGER, `youtube_trailer` TEXT, `episode_run_time` TEXT, `last_modified` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, PRIMARY KEY(`session_id`, `provider_id`, `series_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON 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": "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",+ "series_id"+ ]+ },+ "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_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, `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": "addedAt",+ "columnName": "added_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_favorites_provider_id_content_id_content_type_group_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "content_id",+ "content_type",+ "group_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_favorites_provider_id_content_id_content_type_group_id` ON `${TABLE_NAME}` (`provider_id`, `content_id`, `content_type`, `group_id`)"+ },+ {+ "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`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "sync_metadata",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `last_live_sync` INTEGER NOT NULL, `last_movie_sync` INTEGER NOT NULL, `last_series_sync` INTEGER NOT NULL, `last_epg_sync` 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": "lastMovieSync",+ "columnName": "last_movie_sync",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastSeriesSync",+ "columnName": "last_series_sync",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastEpgSync",+ "columnName": "last_epg_sync",+ "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, 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"+ }+ ],+ "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, 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"+ }+ ],+ "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)",+ "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+ }+ ],+ "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, `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": "isManualOverride",+ "columnName": "is_manual_override",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_channel_epg_mappings_provider_id_provider_channel_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "provider_channel_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_channel_epg_mappings_provider_id_provider_channel_id` ON `${TABLE_NAME}` (`provider_id`, `provider_channel_id`)"+ },+ {+ "name": "index_channel_epg_mappings_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channel_epg_mappings_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "combined_m3u_profiles",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `enabled` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "enabled",+ "columnName": "enabled",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ }+ },+ {+ "tableName": "combined_m3u_profile_members",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `profile_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `enabled` INTEGER NOT NULL, FOREIGN KEY(`profile_id`) REFERENCES `combined_m3u_profiles`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "profileId",+ "columnName": "profile_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "priority",+ "columnName": "priority",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "enabled",+ "columnName": "enabled",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_combined_m3u_profile_members_profile_id",+ "unique": false,+ "columnNames": [+ "profile_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_combined_m3u_profile_members_profile_id` ON `${TABLE_NAME}` (`profile_id`)"+ },+ {+ "name": "index_combined_m3u_profile_members_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_combined_m3u_profile_members_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_combined_m3u_profile_members_profile_id_provider_id",+ "unique": true,+ "columnNames": [+ "profile_id",+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_combined_m3u_profile_members_profile_id_provider_id` ON `${TABLE_NAME}` (`profile_id`, `provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "combined_m3u_profiles",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "profile_id"+ ],+ "referencedColumns": [+ "id"+ ]+ },+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "recording_schedules",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, `channel_name` TEXT NOT NULL, `stream_url` TEXT NOT NULL, `program_title` TEXT, `requested_start_ms` INTEGER NOT NULL, `requested_end_ms` INTEGER NOT NULL, `recurrence` TEXT NOT NULL, `recurring_rule_id` TEXT, `enabled` INTEGER NOT NULL, `is_manual` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelId",+ "columnName": "channel_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelName",+ "columnName": "channel_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "programTitle",+ "columnName": "program_title",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "requestedStartMs",+ "columnName": "requested_start_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "requestedEndMs",+ "columnName": "requested_end_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "recurrence",+ "columnName": "recurrence",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "recurringRuleId",+ "columnName": "recurring_rule_id",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "enabled",+ "columnName": "enabled",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isManual",+ "columnName": "is_manual",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "priority",+ "columnName": "priority",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_recording_schedules_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_schedules_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_recording_schedules_enabled_requested_start_ms",+ "unique": false,+ "columnNames": [+ "enabled",+ "requested_start_ms"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_schedules_enabled_requested_start_ms` ON `${TABLE_NAME}` (`enabled`, `requested_start_ms`)"+ },+ {+ "name": "index_recording_schedules_recurring_rule_id",+ "unique": false,+ "columnNames": [+ "recurring_rule_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_schedules_recurring_rule_id` ON `${TABLE_NAME}` (`recurring_rule_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "recording_runs",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `schedule_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, `channel_name` TEXT NOT NULL, `stream_url` TEXT NOT NULL, `program_title` TEXT, `scheduled_start_ms` INTEGER NOT NULL, `scheduled_end_ms` INTEGER NOT NULL, `recurrence` TEXT NOT NULL, `recurring_rule_id` TEXT, `status` TEXT NOT NULL, `source_type` TEXT NOT NULL, `resolved_url` TEXT, `headers_json` TEXT NOT NULL, `user_agent` TEXT, `expiration_time` INTEGER, `provider_label` TEXT, `output_uri` TEXT, `output_display_path` TEXT, `bytes_written` INTEGER NOT NULL, `average_throughput_bps` INTEGER NOT NULL, `retry_count` INTEGER NOT NULL, `last_progress_at_ms` INTEGER, `failure_category` TEXT NOT NULL, `failure_reason` TEXT, `terminal_at_ms` INTEGER, `started_at_ms` INTEGER, `ended_at_ms` INTEGER, `schedule_enabled` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `alarm_start_at_ms` INTEGER, `alarm_stop_at_ms` INTEGER, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`schedule_id`) REFERENCES `recording_schedules`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "scheduleId",+ "columnName": "schedule_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelId",+ "columnName": "channel_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelName",+ "columnName": "channel_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "programTitle",+ "columnName": "program_title",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "scheduledStartMs",+ "columnName": "scheduled_start_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "scheduledEndMs",+ "columnName": "scheduled_end_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "recurrence",+ "columnName": "recurrence",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "recurringRuleId",+ "columnName": "recurring_rule_id",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "status",+ "columnName": "status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "sourceType",+ "columnName": "source_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "resolvedUrl",+ "columnName": "resolved_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "headersJson",+ "columnName": "headers_json",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "userAgent",+ "columnName": "user_agent",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "expirationTime",+ "columnName": "expiration_time",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "providerLabel",+ "columnName": "provider_label",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "outputUri",+ "columnName": "output_uri",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "outputDisplayPath",+ "columnName": "output_display_path",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "bytesWritten",+ "columnName": "bytes_written",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "averageThroughputBytesPerSecond",+ "columnName": "average_throughput_bps",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "retryCount",+ "columnName": "retry_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastProgressAtMs",+ "columnName": "last_progress_at_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "failureCategory",+ "columnName": "failure_category",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "failureReason",+ "columnName": "failure_reason",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "terminalAtMs",+ "columnName": "terminal_at_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "startedAtMs",+ "columnName": "started_at_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "endedAtMs",+ "columnName": "ended_at_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "scheduleEnabled",+ "columnName": "schedule_enabled",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "priority",+ "columnName": "priority",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "alarmStartAtMs",+ "columnName": "alarm_start_at_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "alarmStopAtMs",+ "columnName": "alarm_stop_at_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_recording_runs_schedule_id",+ "unique": false,+ "columnNames": [+ "schedule_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_schedule_id` ON `${TABLE_NAME}` (`schedule_id`)"+ },+ {+ "name": "index_recording_runs_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_recording_runs_status_scheduled_start_ms",+ "unique": false,+ "columnNames": [+ "status",+ "scheduled_start_ms"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_status_scheduled_start_ms` ON `${TABLE_NAME}` (`status`, `scheduled_start_ms`)"+ },+ {+ "name": "index_recording_runs_alarm_start_at_ms",+ "unique": false,+ "columnNames": [+ "alarm_start_at_ms"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_alarm_start_at_ms` ON `${TABLE_NAME}` (`alarm_start_at_ms`)"+ },+ {+ "name": "index_recording_runs_alarm_stop_at_ms",+ "unique": false,+ "columnNames": [+ "alarm_stop_at_ms"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_alarm_stop_at_ms` ON `${TABLE_NAME}` (`alarm_stop_at_ms`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "recording_schedules",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "schedule_id"+ ],+ "referencedColumns": [+ "id"+ ]+ },+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "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"+ ]+ }+ }+ ],+ "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, '7e9582bb9ffc4ecf92bf3cf486687f29')"+ ]+ }+}\ No newline at end of filediff --git a/data/schemas/com.streamvault.data.local.StreamVaultDatabase/33.json b/data/schemas/com.streamvault.data.local.StreamVaultDatabase/33.jsonnew file mode 100644index 00000000..c5703c31--- /dev/null+++ b/data/schemas/com.streamvault.data.local.StreamVaultDatabase/33.json@@ -0,0 +1,3700 @@+{+ "formatVersion": 1,+ "database": {+ "version": 33,+ "identityHash": "41e31c3b41f6f5ff159a55976444091c",+ "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, `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, `xtream_fast_sync_enabled` INTEGER 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": "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": "xtreamFastSyncEnabled",+ "columnName": "xtream_fast_sync_enabled",+ "affinity": "INTEGER",+ "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",+ "unique": true,+ "columnNames": [+ "server_url",+ "username"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_providers_server_url_username` ON `${TABLE_NAME}` (`server_url`, `username`)"+ }+ ]+ },+ {+ "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, `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": "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, 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+ }+ ],+ "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`)"+ }+ ],+ "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, `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, 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": "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+ }+ ],+ "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`)"+ }+ ],+ "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, `name` TEXT NOT NULL, `poster_url` TEXT, `backdrop_url` TEXT, `category_id` INTEGER, `category_name` TEXT, `plot` TEXT, `cast` TEXT, `director` TEXT, `genre` TEXT, `release_date` TEXT, `rating` REAL NOT NULL, `tmdb_id` INTEGER, `youtube_trailer` TEXT, `episode_run_time` TEXT, `last_modified` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, PRIMARY KEY(`session_id`, `provider_id`, `series_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON 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": "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",+ "series_id"+ ]+ },+ "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_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, `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": "addedAt",+ "columnName": "added_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_favorites_provider_id_content_id_content_type_group_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "content_id",+ "content_type",+ "group_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_favorites_provider_id_content_id_content_type_group_id` ON `${TABLE_NAME}` (`provider_id`, `content_id`, `content_type`, `group_id`)"+ },+ {+ "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`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "sync_metadata",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `last_live_sync` INTEGER NOT NULL, `last_movie_sync` INTEGER NOT NULL, `last_series_sync` INTEGER NOT NULL, `last_epg_sync` 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": "lastMovieSync",+ "columnName": "last_movie_sync",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastSeriesSync",+ "columnName": "last_series_sync",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastEpgSync",+ "columnName": "last_epg_sync",+ "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, 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"+ }+ ],+ "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, 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"+ }+ ],+ "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)",+ "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+ }+ ],+ "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, `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": "isManualOverride",+ "columnName": "is_manual_override",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_channel_epg_mappings_provider_id_provider_channel_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "provider_channel_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_channel_epg_mappings_provider_id_provider_channel_id` ON `${TABLE_NAME}` (`provider_id`, `provider_channel_id`)"+ },+ {+ "name": "index_channel_epg_mappings_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channel_epg_mappings_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "combined_m3u_profiles",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `enabled` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "enabled",+ "columnName": "enabled",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ }+ },+ {+ "tableName": "combined_m3u_profile_members",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `profile_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `enabled` INTEGER NOT NULL, FOREIGN KEY(`profile_id`) REFERENCES `combined_m3u_profiles`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "profileId",+ "columnName": "profile_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "priority",+ "columnName": "priority",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "enabled",+ "columnName": "enabled",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_combined_m3u_profile_members_profile_id",+ "unique": false,+ "columnNames": [+ "profile_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_combined_m3u_profile_members_profile_id` ON `${TABLE_NAME}` (`profile_id`)"+ },+ {+ "name": "index_combined_m3u_profile_members_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_combined_m3u_profile_members_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_combined_m3u_profile_members_profile_id_provider_id",+ "unique": true,+ "columnNames": [+ "profile_id",+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_combined_m3u_profile_members_profile_id_provider_id` ON `${TABLE_NAME}` (`profile_id`, `provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "combined_m3u_profiles",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "profile_id"+ ],+ "referencedColumns": [+ "id"+ ]+ },+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "recording_schedules",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, `channel_name` TEXT NOT NULL, `stream_url` TEXT NOT NULL, `program_title` TEXT, `requested_start_ms` INTEGER NOT NULL, `requested_end_ms` INTEGER NOT NULL, `recurrence` TEXT NOT NULL, `recurring_rule_id` TEXT, `enabled` INTEGER NOT NULL, `is_manual` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelId",+ "columnName": "channel_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelName",+ "columnName": "channel_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "programTitle",+ "columnName": "program_title",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "requestedStartMs",+ "columnName": "requested_start_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "requestedEndMs",+ "columnName": "requested_end_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "recurrence",+ "columnName": "recurrence",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "recurringRuleId",+ "columnName": "recurring_rule_id",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "enabled",+ "columnName": "enabled",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isManual",+ "columnName": "is_manual",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "priority",+ "columnName": "priority",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_recording_schedules_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_schedules_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_recording_schedules_enabled_requested_start_ms",+ "unique": false,+ "columnNames": [+ "enabled",+ "requested_start_ms"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_schedules_enabled_requested_start_ms` ON `${TABLE_NAME}` (`enabled`, `requested_start_ms`)"+ },+ {+ "name": "index_recording_schedules_recurring_rule_id",+ "unique": false,+ "columnNames": [+ "recurring_rule_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_schedules_recurring_rule_id` ON `${TABLE_NAME}` (`recurring_rule_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "recording_runs",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `schedule_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, `channel_name` TEXT NOT NULL, `stream_url` TEXT NOT NULL, `program_title` TEXT, `scheduled_start_ms` INTEGER NOT NULL, `scheduled_end_ms` INTEGER NOT NULL, `recurrence` TEXT NOT NULL, `recurring_rule_id` TEXT, `status` TEXT NOT NULL, `source_type` TEXT NOT NULL, `resolved_url` TEXT, `headers_json` TEXT NOT NULL, `user_agent` TEXT, `expiration_time` INTEGER, `provider_label` TEXT, `output_uri` TEXT, `output_display_path` TEXT, `bytes_written` INTEGER NOT NULL, `average_throughput_bps` INTEGER NOT NULL, `retry_count` INTEGER NOT NULL, `last_progress_at_ms` INTEGER, `failure_category` TEXT NOT NULL, `failure_reason` TEXT, `terminal_at_ms` INTEGER, `started_at_ms` INTEGER, `ended_at_ms` INTEGER, `schedule_enabled` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `alarm_start_at_ms` INTEGER, `alarm_stop_at_ms` INTEGER, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`schedule_id`) REFERENCES `recording_schedules`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "scheduleId",+ "columnName": "schedule_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelId",+ "columnName": "channel_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelName",+ "columnName": "channel_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "programTitle",+ "columnName": "program_title",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "scheduledStartMs",+ "columnName": "scheduled_start_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "scheduledEndMs",+ "columnName": "scheduled_end_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "recurrence",+ "columnName": "recurrence",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "recurringRuleId",+ "columnName": "recurring_rule_id",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "status",+ "columnName": "status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "sourceType",+ "columnName": "source_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "resolvedUrl",+ "columnName": "resolved_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "headersJson",+ "columnName": "headers_json",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "userAgent",+ "columnName": "user_agent",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "expirationTime",+ "columnName": "expiration_time",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "providerLabel",+ "columnName": "provider_label",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "outputUri",+ "columnName": "output_uri",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "outputDisplayPath",+ "columnName": "output_display_path",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "bytesWritten",+ "columnName": "bytes_written",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "averageThroughputBytesPerSecond",+ "columnName": "average_throughput_bps",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "retryCount",+ "columnName": "retry_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastProgressAtMs",+ "columnName": "last_progress_at_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "failureCategory",+ "columnName": "failure_category",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "failureReason",+ "columnName": "failure_reason",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "terminalAtMs",+ "columnName": "terminal_at_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "startedAtMs",+ "columnName": "started_at_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "endedAtMs",+ "columnName": "ended_at_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "scheduleEnabled",+ "columnName": "schedule_enabled",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "priority",+ "columnName": "priority",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "alarmStartAtMs",+ "columnName": "alarm_start_at_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "alarmStopAtMs",+ "columnName": "alarm_stop_at_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_recording_runs_schedule_id",+ "unique": false,+ "columnNames": [+ "schedule_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_schedule_id` ON `${TABLE_NAME}` (`schedule_id`)"+ },+ {+ "name": "index_recording_runs_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_recording_runs_status_scheduled_start_ms",+ "unique": false,+ "columnNames": [+ "status",+ "scheduled_start_ms"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_status_scheduled_start_ms` ON `${TABLE_NAME}` (`status`, `scheduled_start_ms`)"+ },+ {+ "name": "index_recording_runs_alarm_start_at_ms",+ "unique": false,+ "columnNames": [+ "alarm_start_at_ms"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_alarm_start_at_ms` ON `${TABLE_NAME}` (`alarm_start_at_ms`)"+ },+ {+ "name": "index_recording_runs_alarm_stop_at_ms",+ "unique": false,+ "columnNames": [+ "alarm_stop_at_ms"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_alarm_stop_at_ms` ON `${TABLE_NAME}` (`alarm_stop_at_ms`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "recording_schedules",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "schedule_id"+ ],+ "referencedColumns": [+ "id"+ ]+ },+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "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"+ ]+ }+ }+ ],+ "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, '41e31c3b41f6f5ff159a55976444091c')"+ ]+ }+}\ No newline at end of filediff --git a/data/schemas/com.streamvault.data.local.StreamVaultDatabase/34.json b/data/schemas/com.streamvault.data.local.StreamVaultDatabase/34.jsonnew file mode 100644index 00000000..56a29926--- /dev/null+++ b/data/schemas/com.streamvault.data.local.StreamVaultDatabase/34.json@@ -0,0 +1,3729 @@+{+ "formatVersion": 1,+ "database": {+ "version": 34,+ "identityHash": "4cb44acd598997f7467a6d5750121d84",+ "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, `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, `xtream_fast_sync_enabled` INTEGER 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": "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": "xtreamFastSyncEnabled",+ "columnName": "xtream_fast_sync_enabled",+ "affinity": "INTEGER",+ "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",+ "unique": true,+ "columnNames": [+ "server_url",+ "username"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_providers_server_url_username` ON `${TABLE_NAME}` (`server_url`, `username`)"+ }+ ]+ },+ {+ "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, `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": "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, 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+ }+ ],+ "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`)"+ }+ ],+ "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, `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, 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": "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+ }+ ],+ "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`)"+ }+ ],+ "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, `name` TEXT NOT NULL, `poster_url` TEXT, `backdrop_url` TEXT, `category_id` INTEGER, `category_name` TEXT, `plot` TEXT, `cast` TEXT, `director` TEXT, `genre` TEXT, `release_date` TEXT, `rating` REAL NOT NULL, `tmdb_id` INTEGER, `youtube_trailer` TEXT, `episode_run_time` TEXT, `last_modified` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, PRIMARY KEY(`session_id`, `provider_id`, `series_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON 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": "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",+ "series_id"+ ]+ },+ "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, `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": "addedAt",+ "columnName": "added_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_favorites_provider_id_content_id_content_type_group_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "content_id",+ "content_type",+ "group_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_favorites_provider_id_content_id_content_type_group_id` ON `${TABLE_NAME}` (`provider_id`, `content_id`, `content_type`, `group_id`)"+ },+ {+ "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`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "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, 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"+ }+ ],+ "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, 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"+ }+ ],+ "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)",+ "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+ }+ ],+ "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, `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": "isManualOverride",+ "columnName": "is_manual_override",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_channel_epg_mappings_provider_id_provider_channel_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "provider_channel_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_channel_epg_mappings_provider_id_provider_channel_id` ON `${TABLE_NAME}` (`provider_id`, `provider_channel_id`)"+ },+ {+ "name": "index_channel_epg_mappings_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channel_epg_mappings_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "combined_m3u_profiles",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `enabled` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "enabled",+ "columnName": "enabled",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ }+ },+ {+ "tableName": "combined_m3u_profile_members",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `profile_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `enabled` INTEGER NOT NULL, FOREIGN KEY(`profile_id`) REFERENCES `combined_m3u_profiles`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "profileId",+ "columnName": "profile_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "priority",+ "columnName": "priority",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "enabled",+ "columnName": "enabled",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_combined_m3u_profile_members_profile_id",+ "unique": false,+ "columnNames": [+ "profile_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_combined_m3u_profile_members_profile_id` ON `${TABLE_NAME}` (`profile_id`)"+ },+ {+ "name": "index_combined_m3u_profile_members_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_combined_m3u_profile_members_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_combined_m3u_profile_members_profile_id_provider_id",+ "unique": true,+ "columnNames": [+ "profile_id",+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_combined_m3u_profile_members_profile_id_provider_id` ON `${TABLE_NAME}` (`profile_id`, `provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "combined_m3u_profiles",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "profile_id"+ ],+ "referencedColumns": [+ "id"+ ]+ },+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "recording_schedules",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, `channel_name` TEXT NOT NULL, `stream_url` TEXT NOT NULL, `program_title` TEXT, `requested_start_ms` INTEGER NOT NULL, `requested_end_ms` INTEGER NOT NULL, `recurrence` TEXT NOT NULL, `recurring_rule_id` TEXT, `enabled` INTEGER NOT NULL, `is_manual` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelId",+ "columnName": "channel_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelName",+ "columnName": "channel_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "programTitle",+ "columnName": "program_title",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "requestedStartMs",+ "columnName": "requested_start_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "requestedEndMs",+ "columnName": "requested_end_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "recurrence",+ "columnName": "recurrence",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "recurringRuleId",+ "columnName": "recurring_rule_id",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "enabled",+ "columnName": "enabled",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isManual",+ "columnName": "is_manual",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "priority",+ "columnName": "priority",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_recording_schedules_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_schedules_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_recording_schedules_enabled_requested_start_ms",+ "unique": false,+ "columnNames": [+ "enabled",+ "requested_start_ms"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_schedules_enabled_requested_start_ms` ON `${TABLE_NAME}` (`enabled`, `requested_start_ms`)"+ },+ {+ "name": "index_recording_schedules_recurring_rule_id",+ "unique": false,+ "columnNames": [+ "recurring_rule_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_schedules_recurring_rule_id` ON `${TABLE_NAME}` (`recurring_rule_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "recording_runs",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `schedule_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, `channel_name` TEXT NOT NULL, `stream_url` TEXT NOT NULL, `program_title` TEXT, `scheduled_start_ms` INTEGER NOT NULL, `scheduled_end_ms` INTEGER NOT NULL, `recurrence` TEXT NOT NULL, `recurring_rule_id` TEXT, `status` TEXT NOT NULL, `source_type` TEXT NOT NULL, `resolved_url` TEXT, `headers_json` TEXT NOT NULL, `user_agent` TEXT, `expiration_time` INTEGER, `provider_label` TEXT, `output_uri` TEXT, `output_display_path` TEXT, `bytes_written` INTEGER NOT NULL, `average_throughput_bps` INTEGER NOT NULL, `retry_count` INTEGER NOT NULL, `last_progress_at_ms` INTEGER, `failure_category` TEXT NOT NULL, `failure_reason` TEXT, `terminal_at_ms` INTEGER, `started_at_ms` INTEGER, `ended_at_ms` INTEGER, `schedule_enabled` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `alarm_start_at_ms` INTEGER, `alarm_stop_at_ms` INTEGER, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`schedule_id`) REFERENCES `recording_schedules`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "scheduleId",+ "columnName": "schedule_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelId",+ "columnName": "channel_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelName",+ "columnName": "channel_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "programTitle",+ "columnName": "program_title",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "scheduledStartMs",+ "columnName": "scheduled_start_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "scheduledEndMs",+ "columnName": "scheduled_end_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "recurrence",+ "columnName": "recurrence",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "recurringRuleId",+ "columnName": "recurring_rule_id",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "status",+ "columnName": "status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "sourceType",+ "columnName": "source_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "resolvedUrl",+ "columnName": "resolved_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "headersJson",+ "columnName": "headers_json",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "userAgent",+ "columnName": "user_agent",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "expirationTime",+ "columnName": "expiration_time",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "providerLabel",+ "columnName": "provider_label",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "outputUri",+ "columnName": "output_uri",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "outputDisplayPath",+ "columnName": "output_display_path",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "bytesWritten",+ "columnName": "bytes_written",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "averageThroughputBytesPerSecond",+ "columnName": "average_throughput_bps",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "retryCount",+ "columnName": "retry_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastProgressAtMs",+ "columnName": "last_progress_at_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "failureCategory",+ "columnName": "failure_category",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "failureReason",+ "columnName": "failure_reason",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "terminalAtMs",+ "columnName": "terminal_at_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "startedAtMs",+ "columnName": "started_at_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "endedAtMs",+ "columnName": "ended_at_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "scheduleEnabled",+ "columnName": "schedule_enabled",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "priority",+ "columnName": "priority",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "alarmStartAtMs",+ "columnName": "alarm_start_at_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "alarmStopAtMs",+ "columnName": "alarm_stop_at_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_recording_runs_schedule_id",+ "unique": false,+ "columnNames": [+ "schedule_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_schedule_id` ON `${TABLE_NAME}` (`schedule_id`)"+ },+ {+ "name": "index_recording_runs_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_recording_runs_status_scheduled_start_ms",+ "unique": false,+ "columnNames": [+ "status",+ "scheduled_start_ms"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_status_scheduled_start_ms` ON `${TABLE_NAME}` (`status`, `scheduled_start_ms`)"+ },+ {+ "name": "index_recording_runs_alarm_start_at_ms",+ "unique": false,+ "columnNames": [+ "alarm_start_at_ms"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_alarm_start_at_ms` ON `${TABLE_NAME}` (`alarm_start_at_ms`)"+ },+ {+ "name": "index_recording_runs_alarm_stop_at_ms",+ "unique": false,+ "columnNames": [+ "alarm_stop_at_ms"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_alarm_stop_at_ms` ON `${TABLE_NAME}` (`alarm_stop_at_ms`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "recording_schedules",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "schedule_id"+ ],+ "referencedColumns": [+ "id"+ ]+ },+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "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"+ ]+ }+ }+ ],+ "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, '4cb44acd598997f7467a6d5750121d84')"+ ]+ }+}\ No newline at end of filediff --git a/data/schemas/com.streamvault.data.local.StreamVaultDatabase/35.json b/data/schemas/com.streamvault.data.local.StreamVaultDatabase/35.jsonnew file mode 100644index 00000000..24651726--- /dev/null+++ b/data/schemas/com.streamvault.data.local.StreamVaultDatabase/35.json@@ -0,0 +1,3819 @@+{+ "formatVersion": 1,+ "database": {+ "version": 35,+ "identityHash": "4f75a3813b8cbb9c1cfebab4840d774c",+ "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, `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, `xtream_fast_sync_enabled` INTEGER 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": "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": "xtreamFastSyncEnabled",+ "columnName": "xtream_fast_sync_enabled",+ "affinity": "INTEGER",+ "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",+ "unique": true,+ "columnNames": [+ "server_url",+ "username"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_providers_server_url_username` ON `${TABLE_NAME}` (`server_url`, `username`)"+ }+ ]+ },+ {+ "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, `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": "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, 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+ }+ ],+ "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`)"+ }+ ],+ "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, `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, 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": "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+ }+ ],+ "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`)"+ }+ ],+ "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, `name` TEXT NOT NULL, `poster_url` TEXT, `backdrop_url` TEXT, `category_id` INTEGER, `category_name` TEXT, `plot` TEXT, `cast` TEXT, `director` TEXT, `genre` TEXT, `release_date` TEXT, `rating` REAL NOT NULL, `tmdb_id` INTEGER, `youtube_trailer` TEXT, `episode_run_time` TEXT, `last_modified` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, PRIMARY KEY(`session_id`, `provider_id`, `series_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON 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": "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",+ "series_id"+ ]+ },+ "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, `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": "addedAt",+ "columnName": "added_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_favorites_provider_id_content_id_content_type_group_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "content_id",+ "content_type",+ "group_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_favorites_provider_id_content_id_content_type_group_id` ON `${TABLE_NAME}` (`provider_id`, `content_id`, `content_type`, `group_id`)"+ },+ {+ "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`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "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, 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"+ }+ ],+ "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, 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"+ }+ ],+ "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)",+ "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+ }+ ],+ "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, `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": "isManualOverride",+ "columnName": "is_manual_override",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_channel_epg_mappings_provider_id_provider_channel_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "provider_channel_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_channel_epg_mappings_provider_id_provider_channel_id` ON `${TABLE_NAME}` (`provider_id`, `provider_channel_id`)"+ },+ {+ "name": "index_channel_epg_mappings_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channel_epg_mappings_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "combined_m3u_profiles",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `enabled` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "enabled",+ "columnName": "enabled",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ }+ },+ {+ "tableName": "combined_m3u_profile_members",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `profile_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `enabled` INTEGER NOT NULL, FOREIGN KEY(`profile_id`) REFERENCES `combined_m3u_profiles`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "profileId",+ "columnName": "profile_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "priority",+ "columnName": "priority",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "enabled",+ "columnName": "enabled",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_combined_m3u_profile_members_profile_id",+ "unique": false,+ "columnNames": [+ "profile_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_combined_m3u_profile_members_profile_id` ON `${TABLE_NAME}` (`profile_id`)"+ },+ {+ "name": "index_combined_m3u_profile_members_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_combined_m3u_profile_members_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_combined_m3u_profile_members_profile_id_provider_id",+ "unique": true,+ "columnNames": [+ "profile_id",+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_combined_m3u_profile_members_profile_id_provider_id` ON `${TABLE_NAME}` (`profile_id`, `provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "combined_m3u_profiles",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "profile_id"+ ],+ "referencedColumns": [+ "id"+ ]+ },+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "recording_schedules",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, `channel_name` TEXT NOT NULL, `stream_url` TEXT NOT NULL, `program_title` TEXT, `requested_start_ms` INTEGER NOT NULL, `requested_end_ms` INTEGER NOT NULL, `recurrence` TEXT NOT NULL, `recurring_rule_id` TEXT, `enabled` INTEGER NOT NULL, `is_manual` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelId",+ "columnName": "channel_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelName",+ "columnName": "channel_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "programTitle",+ "columnName": "program_title",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "requestedStartMs",+ "columnName": "requested_start_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "requestedEndMs",+ "columnName": "requested_end_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "recurrence",+ "columnName": "recurrence",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "recurringRuleId",+ "columnName": "recurring_rule_id",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "enabled",+ "columnName": "enabled",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isManual",+ "columnName": "is_manual",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "priority",+ "columnName": "priority",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_recording_schedules_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_schedules_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_recording_schedules_enabled_requested_start_ms",+ "unique": false,+ "columnNames": [+ "enabled",+ "requested_start_ms"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_schedules_enabled_requested_start_ms` ON `${TABLE_NAME}` (`enabled`, `requested_start_ms`)"+ },+ {+ "name": "index_recording_schedules_recurring_rule_id",+ "unique": false,+ "columnNames": [+ "recurring_rule_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_schedules_recurring_rule_id` ON `${TABLE_NAME}` (`recurring_rule_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "recording_runs",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `schedule_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, `channel_name` TEXT NOT NULL, `stream_url` TEXT NOT NULL, `program_title` TEXT, `scheduled_start_ms` INTEGER NOT NULL, `scheduled_end_ms` INTEGER NOT NULL, `recurrence` TEXT NOT NULL, `recurring_rule_id` TEXT, `status` TEXT NOT NULL, `source_type` TEXT NOT NULL, `resolved_url` TEXT, `headers_json` TEXT NOT NULL, `user_agent` TEXT, `expiration_time` INTEGER, `provider_label` TEXT, `output_uri` TEXT, `output_display_path` TEXT, `bytes_written` INTEGER NOT NULL, `average_throughput_bps` INTEGER NOT NULL, `retry_count` INTEGER NOT NULL, `last_progress_at_ms` INTEGER, `failure_category` TEXT NOT NULL, `failure_reason` TEXT, `terminal_at_ms` INTEGER, `started_at_ms` INTEGER, `ended_at_ms` INTEGER, `schedule_enabled` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `alarm_start_at_ms` INTEGER, `alarm_stop_at_ms` INTEGER, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`schedule_id`) REFERENCES `recording_schedules`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "scheduleId",+ "columnName": "schedule_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelId",+ "columnName": "channel_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelName",+ "columnName": "channel_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "programTitle",+ "columnName": "program_title",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "scheduledStartMs",+ "columnName": "scheduled_start_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "scheduledEndMs",+ "columnName": "scheduled_end_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "recurrence",+ "columnName": "recurrence",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "recurringRuleId",+ "columnName": "recurring_rule_id",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "status",+ "columnName": "status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "sourceType",+ "columnName": "source_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "resolvedUrl",+ "columnName": "resolved_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "headersJson",+ "columnName": "headers_json",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "userAgent",+ "columnName": "user_agent",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "expirationTime",+ "columnName": "expiration_time",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "providerLabel",+ "columnName": "provider_label",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "outputUri",+ "columnName": "output_uri",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "outputDisplayPath",+ "columnName": "output_display_path",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "bytesWritten",+ "columnName": "bytes_written",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "averageThroughputBytesPerSecond",+ "columnName": "average_throughput_bps",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "retryCount",+ "columnName": "retry_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastProgressAtMs",+ "columnName": "last_progress_at_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "failureCategory",+ "columnName": "failure_category",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "failureReason",+ "columnName": "failure_reason",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "terminalAtMs",+ "columnName": "terminal_at_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "startedAtMs",+ "columnName": "started_at_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "endedAtMs",+ "columnName": "ended_at_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "scheduleEnabled",+ "columnName": "schedule_enabled",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "priority",+ "columnName": "priority",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "alarmStartAtMs",+ "columnName": "alarm_start_at_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "alarmStopAtMs",+ "columnName": "alarm_stop_at_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_recording_runs_schedule_id",+ "unique": false,+ "columnNames": [+ "schedule_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_schedule_id` ON `${TABLE_NAME}` (`schedule_id`)"+ },+ {+ "name": "index_recording_runs_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_recording_runs_status_scheduled_start_ms",+ "unique": false,+ "columnNames": [+ "status",+ "scheduled_start_ms"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_status_scheduled_start_ms` ON `${TABLE_NAME}` (`status`, `scheduled_start_ms`)"+ },+ {+ "name": "index_recording_runs_alarm_start_at_ms",+ "unique": false,+ "columnNames": [+ "alarm_start_at_ms"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_alarm_start_at_ms` ON `${TABLE_NAME}` (`alarm_start_at_ms`)"+ },+ {+ "name": "index_recording_runs_alarm_stop_at_ms",+ "unique": false,+ "columnNames": [+ "alarm_stop_at_ms"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_alarm_stop_at_ms` ON `${TABLE_NAME}` (`alarm_stop_at_ms`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "recording_schedules",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "schedule_id"+ ],+ "referencedColumns": [+ "id"+ ]+ },+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "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"+ ]+ }+ }+ ],+ "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, '4f75a3813b8cbb9c1cfebab4840d774c')"+ ]+ }+}\ No newline at end of filediff --git a/data/schemas/com.streamvault.data.local.StreamVaultDatabase/36.json b/data/schemas/com.streamvault.data.local.StreamVaultDatabase/36.jsonnew file mode 100644index 00000000..4164fe15--- /dev/null+++ b/data/schemas/com.streamvault.data.local.StreamVaultDatabase/36.json@@ -0,0 +1,3972 @@+{+ "formatVersion": 1,+ "database": {+ "version": 36,+ "identityHash": "1690089594ec50584144193732f4c9a4",+ "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, `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, `xtream_fast_sync_enabled` INTEGER 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": "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": "xtreamFastSyncEnabled",+ "columnName": "xtream_fast_sync_enabled",+ "affinity": "INTEGER",+ "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",+ "unique": true,+ "columnNames": [+ "server_url",+ "username"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_providers_server_url_username` ON `${TABLE_NAME}` (`server_url`, `username`)"+ }+ ]+ },+ {+ "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, `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": "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, 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+ }+ ],+ "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`)"+ }+ ],+ "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, `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, 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": "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+ }+ ],+ "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`)"+ }+ ],+ "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, `name` TEXT NOT NULL, `poster_url` TEXT, `backdrop_url` TEXT, `category_id` INTEGER, `category_name` TEXT, `plot` TEXT, `cast` TEXT, `director` TEXT, `genre` TEXT, `release_date` TEXT, `rating` REAL NOT NULL, `tmdb_id` INTEGER, `youtube_trailer` TEXT, `episode_run_time` TEXT, `last_modified` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, PRIMARY KEY(`session_id`, `provider_id`, `series_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON 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": "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",+ "series_id"+ ]+ },+ "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, `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": "addedAt",+ "columnName": "added_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_favorites_provider_id_content_id_content_type_group_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "content_id",+ "content_type",+ "group_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_favorites_provider_id_content_id_content_type_group_id` ON `${TABLE_NAME}` (`provider_id`, `content_id`, `content_type`, `group_id`)"+ },+ {+ "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`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "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, 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"+ }+ ],+ "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, 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"+ }+ ],+ "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)",+ "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+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_epg_sources_url",+ "unique": true,+ "columnNames": [+ "url"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_epg_sources_url` ON `${TABLE_NAME}` (`url`)"+ }+ ]+ },+ {+ "tableName": "provider_epg_sources",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `epg_source_id` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `enabled` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`epg_source_id`) REFERENCES `epg_sources`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "epgSourceId",+ "columnName": "epg_source_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "priority",+ "columnName": "priority",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "enabled",+ "columnName": "enabled",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_provider_epg_sources_provider_id_epg_source_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "epg_source_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_provider_epg_sources_provider_id_epg_source_id` ON `${TABLE_NAME}` (`provider_id`, `epg_source_id`)"+ },+ {+ "name": "index_provider_epg_sources_epg_source_id",+ "unique": false,+ "columnNames": [+ "epg_source_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_provider_epg_sources_epg_source_id` ON `${TABLE_NAME}` (`epg_source_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ },+ {+ "table": "epg_sources",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "epg_source_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "epg_channels",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `epg_source_id` INTEGER NOT NULL, `xmltv_channel_id` TEXT NOT NULL, `display_name` TEXT NOT NULL, `normalized_name` TEXT NOT NULL, `icon_url` TEXT, FOREIGN KEY(`epg_source_id`) REFERENCES `epg_sources`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "epgSourceId",+ "columnName": "epg_source_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "xmltvChannelId",+ "columnName": "xmltv_channel_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "displayName",+ "columnName": "display_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "normalizedName",+ "columnName": "normalized_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "iconUrl",+ "columnName": "icon_url",+ "affinity": "TEXT"+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_epg_channels_epg_source_id_xmltv_channel_id",+ "unique": true,+ "columnNames": [+ "epg_source_id",+ "xmltv_channel_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_epg_channels_epg_source_id_xmltv_channel_id` ON `${TABLE_NAME}` (`epg_source_id`, `xmltv_channel_id`)"+ },+ {+ "name": "index_epg_channels_epg_source_id",+ "unique": false,+ "columnNames": [+ "epg_source_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_channels_epg_source_id` ON `${TABLE_NAME}` (`epg_source_id`)"+ },+ {+ "name": "index_epg_channels_normalized_name",+ "unique": false,+ "columnNames": [+ "normalized_name"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_channels_normalized_name` ON `${TABLE_NAME}` (`normalized_name`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "epg_sources",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "epg_source_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "epg_programmes",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `epg_source_id` INTEGER NOT NULL, `xmltv_channel_id` TEXT NOT NULL, `start_time` INTEGER NOT NULL, `end_time` INTEGER NOT NULL, `title` TEXT NOT NULL, `subtitle` TEXT, `description` TEXT NOT NULL, `category` TEXT, `lang` TEXT NOT NULL, `rating` TEXT, `image_url` TEXT, `episode_info` TEXT, FOREIGN KEY(`epg_source_id`) REFERENCES `epg_sources`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "epgSourceId",+ "columnName": "epg_source_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "xmltvChannelId",+ "columnName": "xmltv_channel_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "startTime",+ "columnName": "start_time",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "endTime",+ "columnName": "end_time",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "title",+ "columnName": "title",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "subtitle",+ "columnName": "subtitle",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "description",+ "columnName": "description",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "category",+ "columnName": "category",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lang",+ "columnName": "lang",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "rating",+ "columnName": "rating",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "imageUrl",+ "columnName": "image_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "episodeInfo",+ "columnName": "episode_info",+ "affinity": "TEXT"+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_epg_programmes_epg_source_id_xmltv_channel_id_start_time",+ "unique": false,+ "columnNames": [+ "epg_source_id",+ "xmltv_channel_id",+ "start_time"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_programmes_epg_source_id_xmltv_channel_id_start_time` ON `${TABLE_NAME}` (`epg_source_id`, `xmltv_channel_id`, `start_time`)"+ },+ {+ "name": "index_epg_programmes_epg_source_id_xmltv_channel_id_start_time_end_time",+ "unique": true,+ "columnNames": [+ "epg_source_id",+ "xmltv_channel_id",+ "start_time",+ "end_time"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_epg_programmes_epg_source_id_xmltv_channel_id_start_time_end_time` ON `${TABLE_NAME}` (`epg_source_id`, `xmltv_channel_id`, `start_time`, `end_time`)"+ },+ {+ "name": "index_epg_programmes_epg_source_id",+ "unique": false,+ "columnNames": [+ "epg_source_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_programmes_epg_source_id` ON `${TABLE_NAME}` (`epg_source_id`)"+ },+ {+ "name": "index_epg_programmes_start_time",+ "unique": false,+ "columnNames": [+ "start_time"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_programmes_start_time` ON `${TABLE_NAME}` (`start_time`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "epg_sources",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "epg_source_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "channel_epg_mappings",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_channel_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `source_type` TEXT NOT NULL, `epg_source_id` INTEGER, `xmltv_channel_id` TEXT, `match_type` TEXT, `confidence` REAL NOT NULL, `matched_at` INTEGER NOT NULL, `failed_attempts` INTEGER NOT NULL, `source` TEXT, `is_manual_override` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerChannelId",+ "columnName": "provider_channel_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "sourceType",+ "columnName": "source_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "epgSourceId",+ "columnName": "epg_source_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "xmltvChannelId",+ "columnName": "xmltv_channel_id",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "matchType",+ "columnName": "match_type",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "confidence",+ "columnName": "confidence",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "matchedAt",+ "columnName": "matched_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "failedAttempts",+ "columnName": "failed_attempts",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "source",+ "columnName": "source",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "isManualOverride",+ "columnName": "is_manual_override",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_channel_epg_mappings_provider_id_provider_channel_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "provider_channel_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_channel_epg_mappings_provider_id_provider_channel_id` ON `${TABLE_NAME}` (`provider_id`, `provider_channel_id`)"+ },+ {+ "name": "index_channel_epg_mappings_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channel_epg_mappings_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "combined_m3u_profiles",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `enabled` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "enabled",+ "columnName": "enabled",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ }+ },+ {+ "tableName": "combined_m3u_profile_members",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `profile_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `enabled` INTEGER NOT NULL, FOREIGN KEY(`profile_id`) REFERENCES `combined_m3u_profiles`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "profileId",+ "columnName": "profile_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "priority",+ "columnName": "priority",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "enabled",+ "columnName": "enabled",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_combined_m3u_profile_members_profile_id",+ "unique": false,+ "columnNames": [+ "profile_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_combined_m3u_profile_members_profile_id` ON `${TABLE_NAME}` (`profile_id`)"+ },+ {+ "name": "index_combined_m3u_profile_members_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_combined_m3u_profile_members_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_combined_m3u_profile_members_profile_id_provider_id",+ "unique": true,+ "columnNames": [+ "profile_id",+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_combined_m3u_profile_members_profile_id_provider_id` ON `${TABLE_NAME}` (`profile_id`, `provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "combined_m3u_profiles",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "profile_id"+ ],+ "referencedColumns": [+ "id"+ ]+ },+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "recording_schedules",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, `channel_name` TEXT NOT NULL, `stream_url` TEXT NOT NULL, `program_title` TEXT, `requested_start_ms` INTEGER NOT NULL, `requested_end_ms` INTEGER NOT NULL, `recurrence` TEXT NOT NULL, `recurring_rule_id` TEXT, `enabled` INTEGER NOT NULL, `is_manual` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelId",+ "columnName": "channel_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelName",+ "columnName": "channel_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "programTitle",+ "columnName": "program_title",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "requestedStartMs",+ "columnName": "requested_start_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "requestedEndMs",+ "columnName": "requested_end_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "recurrence",+ "columnName": "recurrence",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "recurringRuleId",+ "columnName": "recurring_rule_id",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "enabled",+ "columnName": "enabled",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isManual",+ "columnName": "is_manual",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "priority",+ "columnName": "priority",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_recording_schedules_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_schedules_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_recording_schedules_enabled_requested_start_ms",+ "unique": false,+ "columnNames": [+ "enabled",+ "requested_start_ms"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_schedules_enabled_requested_start_ms` ON `${TABLE_NAME}` (`enabled`, `requested_start_ms`)"+ },+ {+ "name": "index_recording_schedules_recurring_rule_id",+ "unique": false,+ "columnNames": [+ "recurring_rule_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_schedules_recurring_rule_id` ON `${TABLE_NAME}` (`recurring_rule_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "recording_runs",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `schedule_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, `channel_name` TEXT NOT NULL, `stream_url` TEXT NOT NULL, `program_title` TEXT, `scheduled_start_ms` INTEGER NOT NULL, `scheduled_end_ms` INTEGER NOT NULL, `recurrence` TEXT NOT NULL, `recurring_rule_id` TEXT, `status` TEXT NOT NULL, `source_type` TEXT NOT NULL, `resolved_url` TEXT, `headers_json` TEXT NOT NULL, `user_agent` TEXT, `expiration_time` INTEGER, `provider_label` TEXT, `output_uri` TEXT, `output_display_path` TEXT, `bytes_written` INTEGER NOT NULL, `average_throughput_bps` INTEGER NOT NULL, `retry_count` INTEGER NOT NULL, `last_progress_at_ms` INTEGER, `failure_category` TEXT NOT NULL, `failure_reason` TEXT, `terminal_at_ms` INTEGER, `started_at_ms` INTEGER, `ended_at_ms` INTEGER, `schedule_enabled` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `alarm_start_at_ms` INTEGER, `alarm_stop_at_ms` INTEGER, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`schedule_id`) REFERENCES `recording_schedules`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "scheduleId",+ "columnName": "schedule_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelId",+ "columnName": "channel_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelName",+ "columnName": "channel_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "programTitle",+ "columnName": "program_title",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "scheduledStartMs",+ "columnName": "scheduled_start_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "scheduledEndMs",+ "columnName": "scheduled_end_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "recurrence",+ "columnName": "recurrence",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "recurringRuleId",+ "columnName": "recurring_rule_id",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "status",+ "columnName": "status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "sourceType",+ "columnName": "source_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "resolvedUrl",+ "columnName": "resolved_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "headersJson",+ "columnName": "headers_json",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "userAgent",+ "columnName": "user_agent",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "expirationTime",+ "columnName": "expiration_time",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "providerLabel",+ "columnName": "provider_label",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "outputUri",+ "columnName": "output_uri",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "outputDisplayPath",+ "columnName": "output_display_path",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "bytesWritten",+ "columnName": "bytes_written",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "averageThroughputBytesPerSecond",+ "columnName": "average_throughput_bps",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "retryCount",+ "columnName": "retry_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastProgressAtMs",+ "columnName": "last_progress_at_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "failureCategory",+ "columnName": "failure_category",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "failureReason",+ "columnName": "failure_reason",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "terminalAtMs",+ "columnName": "terminal_at_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "startedAtMs",+ "columnName": "started_at_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "endedAtMs",+ "columnName": "ended_at_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "scheduleEnabled",+ "columnName": "schedule_enabled",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "priority",+ "columnName": "priority",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "alarmStartAtMs",+ "columnName": "alarm_start_at_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "alarmStopAtMs",+ "columnName": "alarm_stop_at_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_recording_runs_schedule_id",+ "unique": false,+ "columnNames": [+ "schedule_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_schedule_id` ON `${TABLE_NAME}` (`schedule_id`)"+ },+ {+ "name": "index_recording_runs_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_recording_runs_status_scheduled_start_ms",+ "unique": false,+ "columnNames": [+ "status",+ "scheduled_start_ms"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_status_scheduled_start_ms` ON `${TABLE_NAME}` (`status`, `scheduled_start_ms`)"+ },+ {+ "name": "index_recording_runs_alarm_start_at_ms",+ "unique": false,+ "columnNames": [+ "alarm_start_at_ms"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_alarm_start_at_ms` ON `${TABLE_NAME}` (`alarm_start_at_ms`)"+ },+ {+ "name": "index_recording_runs_alarm_stop_at_ms",+ "unique": false,+ "columnNames": [+ "alarm_stop_at_ms"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_alarm_stop_at_ms` ON `${TABLE_NAME}` (`alarm_stop_at_ms`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "recording_schedules",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "schedule_id"+ ],+ "referencedColumns": [+ "id"+ ]+ },+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "program_reminders",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `channel_id` TEXT NOT NULL, `channel_name` TEXT NOT NULL, `program_title` TEXT NOT NULL, `program_start_time` INTEGER NOT NULL, `remind_at` INTEGER NOT NULL, `lead_time_minutes` INTEGER NOT NULL, `is_dismissed` INTEGER NOT NULL, `notified_at` INTEGER, `created_at` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelId",+ "columnName": "channel_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "channelName",+ "columnName": "channel_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "programTitle",+ "columnName": "program_title",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "programStartTime",+ "columnName": "program_start_time",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "remindAt",+ "columnName": "remind_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "leadTimeMinutes",+ "columnName": "lead_time_minutes",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isDismissed",+ "columnName": "is_dismissed",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "notifiedAt",+ "columnName": "notified_at",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_program_reminders_provider_id_remind_at",+ "unique": false,+ "columnNames": [+ "provider_id",+ "remind_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_program_reminders_provider_id_remind_at` ON `${TABLE_NAME}` (`provider_id`, `remind_at`)"+ },+ {+ "name": "index_program_reminders_is_dismissed_notified_at_remind_at",+ "unique": false,+ "columnNames": [+ "is_dismissed",+ "notified_at",+ "remind_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_program_reminders_is_dismissed_notified_at_remind_at` ON `${TABLE_NAME}` (`is_dismissed`, `notified_at`, `remind_at`)"+ },+ {+ "name": "index_program_reminders_provider_id_channel_id_program_start_time",+ "unique": false,+ "columnNames": [+ "provider_id",+ "channel_id",+ "program_start_time"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_program_reminders_provider_id_channel_id_program_start_time` ON `${TABLE_NAME}` (`provider_id`, `channel_id`, `program_start_time`)"+ },+ {+ "name": "index_program_reminders_provider_id_channel_id_program_title_program_start_time",+ "unique": true,+ "columnNames": [+ "provider_id",+ "channel_id",+ "program_title",+ "program_start_time"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_program_reminders_provider_id_channel_id_program_title_program_start_time` ON `${TABLE_NAME}` (`provider_id`, `channel_id`, `program_title`, `program_start_time`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "recording_storage",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER NOT NULL, `tree_uri` TEXT, `display_name` TEXT, `output_directory` TEXT, `available_bytes` INTEGER, `is_writable` INTEGER NOT NULL, `file_name_pattern` TEXT NOT NULL, `retention_days` INTEGER, `max_simultaneous_recordings` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, PRIMARY KEY(`id`))",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "treeUri",+ "columnName": "tree_uri",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "displayName",+ "columnName": "display_name",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "outputDirectory",+ "columnName": "output_directory",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "availableBytes",+ "columnName": "available_bytes",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "isWritable",+ "columnName": "is_writable",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "fileNamePattern",+ "columnName": "file_name_pattern",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "retentionDays",+ "columnName": "retention_days",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "maxSimultaneousRecordings",+ "columnName": "max_simultaneous_recordings",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "id"+ ]+ }+ }+ ],+ "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, '1690089594ec50584144193732f4c9a4')"+ ]+ }+}\ No newline at end of filediff --git a/data/schemas/com.streamvault.data.local.StreamVaultDatabase/37.json b/data/schemas/com.streamvault.data.local.StreamVaultDatabase/37.jsonnew file mode 100644index 00000000..654cd694--- /dev/null+++ b/data/schemas/com.streamvault.data.local.StreamVaultDatabase/37.json@@ -0,0 +1,4042 @@+{+ "formatVersion": 1,+ "database": {+ "version": 37,+ "identityHash": "b922a9d110039fe4527e63bfc20d9bcf",+ "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, `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, `xtream_fast_sync_enabled` INTEGER 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": "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": "xtreamFastSyncEnabled",+ "columnName": "xtream_fast_sync_enabled",+ "affinity": "INTEGER",+ "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",+ "unique": true,+ "columnNames": [+ "server_url",+ "username"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_providers_server_url_username` ON `${TABLE_NAME}` (`server_url`, `username`)"+ }+ ]+ },+ {+ "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, `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": "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, 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+ }+ ],+ "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`)"+ }+ ],+ "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, `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, 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": "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+ }+ ],+ "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`)"+ }+ ],+ "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, `name` TEXT NOT NULL, `poster_url` TEXT, `backdrop_url` TEXT, `category_id` INTEGER, `category_name` TEXT, `plot` TEXT, `cast` TEXT, `director` TEXT, `genre` TEXT, `release_date` TEXT, `rating` REAL NOT NULL, `tmdb_id` INTEGER, `youtube_trailer` TEXT, `episode_run_time` TEXT, `last_modified` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, PRIMARY KEY(`session_id`, `provider_id`, `series_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON 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": "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",+ "series_id"+ ]+ },+ "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, `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": "addedAt",+ "columnName": "added_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_favorites_provider_id_content_id_content_type_group_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "content_id",+ "content_type",+ "group_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_favorites_provider_id_content_id_content_type_group_id` ON `${TABLE_NAME}` (`provider_id`, `content_id`, `content_type`, `group_id`)"+ },+ {+ "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`)"+ }+ ],+ "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, 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"+ }+ ],+ "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, 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"+ }+ ],+ "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)",+ "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+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_epg_sources_url",+ "unique": true,+ "columnNames": [+ "url"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_epg_sources_url` ON `${TABLE_NAME}` (`url`)"+ }+ ]+ },+ {+ "tableName": "provider_epg_sources",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `epg_source_id` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `enabled` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`epg_source_id`) REFERENCES `epg_sources`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "epgSourceId",+ "columnName": "epg_source_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "priority",+ "columnName": "priority",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "enabled",+ "columnName": "enabled",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_provider_epg_sources_provider_id_epg_source_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "epg_source_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_provider_epg_sources_provider_id_epg_source_id` ON `${TABLE_NAME}` (`provider_id`, `epg_source_id`)"+ },+ {+ "name": "index_provider_epg_sources_epg_source_id",+ "unique": false,+ "columnNames": [+ "epg_source_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_provider_epg_sources_epg_source_id` ON `${TABLE_NAME}` (`epg_source_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ },+ {+ "table": "epg_sources",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "epg_source_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "epg_channels",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `epg_source_id` INTEGER NOT NULL, `xmltv_channel_id` TEXT NOT NULL, `display_name` TEXT NOT NULL, `normalized_name` TEXT NOT NULL, `icon_url` TEXT, FOREIGN KEY(`epg_source_id`) REFERENCES `epg_sources`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "epgSourceId",+ "columnName": "epg_source_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "xmltvChannelId",+ "columnName": "xmltv_channel_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "displayName",+ "columnName": "display_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "normalizedName",+ "columnName": "normalized_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "iconUrl",+ "columnName": "icon_url",+ "affinity": "TEXT"+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_epg_channels_epg_source_id_xmltv_channel_id",+ "unique": true,+ "columnNames": [+ "epg_source_id",+ "xmltv_channel_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_epg_channels_epg_source_id_xmltv_channel_id` ON `${TABLE_NAME}` (`epg_source_id`, `xmltv_channel_id`)"+ },+ {+ "name": "index_epg_channels_epg_source_id",+ "unique": false,+ "columnNames": [+ "epg_source_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_channels_epg_source_id` ON `${TABLE_NAME}` (`epg_source_id`)"+ },+ {+ "name": "index_epg_channels_normalized_name",+ "unique": false,+ "columnNames": [+ "normalized_name"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_channels_normalized_name` ON `${TABLE_NAME}` (`normalized_name`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "epg_sources",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "epg_source_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "epg_programmes",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `epg_source_id` INTEGER NOT NULL, `xmltv_channel_id` TEXT NOT NULL, `start_time` INTEGER NOT NULL, `end_time` INTEGER NOT NULL, `title` TEXT NOT NULL, `subtitle` TEXT, `description` TEXT NOT NULL, `category` TEXT, `lang` TEXT NOT NULL, `rating` TEXT, `image_url` TEXT, `episode_info` TEXT, FOREIGN KEY(`epg_source_id`) REFERENCES `epg_sources`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "epgSourceId",+ "columnName": "epg_source_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "xmltvChannelId",+ "columnName": "xmltv_channel_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "startTime",+ "columnName": "start_time",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "endTime",+ "columnName": "end_time",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "title",+ "columnName": "title",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "subtitle",+ "columnName": "subtitle",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "description",+ "columnName": "description",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "category",+ "columnName": "category",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lang",+ "columnName": "lang",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "rating",+ "columnName": "rating",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "imageUrl",+ "columnName": "image_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "episodeInfo",+ "columnName": "episode_info",+ "affinity": "TEXT"+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_epg_programmes_epg_source_id_xmltv_channel_id_start_time",+ "unique": false,+ "columnNames": [+ "epg_source_id",+ "xmltv_channel_id",+ "start_time"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_programmes_epg_source_id_xmltv_channel_id_start_time` ON `${TABLE_NAME}` (`epg_source_id`, `xmltv_channel_id`, `start_time`)"+ },+ {+ "name": "index_epg_programmes_epg_source_id_xmltv_channel_id_start_time_end_time",+ "unique": true,+ "columnNames": [+ "epg_source_id",+ "xmltv_channel_id",+ "start_time",+ "end_time"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_epg_programmes_epg_source_id_xmltv_channel_id_start_time_end_time` ON `${TABLE_NAME}` (`epg_source_id`, `xmltv_channel_id`, `start_time`, `end_time`)"+ },+ {+ "name": "index_epg_programmes_epg_source_id",+ "unique": false,+ "columnNames": [+ "epg_source_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_programmes_epg_source_id` ON `${TABLE_NAME}` (`epg_source_id`)"+ },+ {+ "name": "index_epg_programmes_start_time",+ "unique": false,+ "columnNames": [+ "start_time"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_programmes_start_time` ON `${TABLE_NAME}` (`start_time`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "epg_sources",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "epg_source_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "channel_epg_mappings",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_channel_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `source_type` TEXT NOT NULL, `epg_source_id` INTEGER, `xmltv_channel_id` TEXT, `match_type` TEXT, `confidence` REAL NOT NULL, `matched_at` INTEGER NOT NULL, `failed_attempts` INTEGER NOT NULL, `source` TEXT, `is_manual_override` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerChannelId",+ "columnName": "provider_channel_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "sourceType",+ "columnName": "source_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "epgSourceId",+ "columnName": "epg_source_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "xmltvChannelId",+ "columnName": "xmltv_channel_id",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "matchType",+ "columnName": "match_type",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "confidence",+ "columnName": "confidence",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "matchedAt",+ "columnName": "matched_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "failedAttempts",+ "columnName": "failed_attempts",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "source",+ "columnName": "source",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "isManualOverride",+ "columnName": "is_manual_override",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_channel_epg_mappings_provider_id_provider_channel_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "provider_channel_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_channel_epg_mappings_provider_id_provider_channel_id` ON `${TABLE_NAME}` (`provider_id`, `provider_channel_id`)"+ },+ {+ "name": "index_channel_epg_mappings_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channel_epg_mappings_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "combined_m3u_profiles",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `enabled` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "enabled",+ "columnName": "enabled",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ }+ },+ {+ "tableName": "combined_m3u_profile_members",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `profile_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `enabled` INTEGER NOT NULL, FOREIGN KEY(`profile_id`) REFERENCES `combined_m3u_profiles`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "profileId",+ "columnName": "profile_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "priority",+ "columnName": "priority",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "enabled",+ "columnName": "enabled",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_combined_m3u_profile_members_profile_id",+ "unique": false,+ "columnNames": [+ "profile_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_combined_m3u_profile_members_profile_id` ON `${TABLE_NAME}` (`profile_id`)"+ },+ {+ "name": "index_combined_m3u_profile_members_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_combined_m3u_profile_members_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_combined_m3u_profile_members_profile_id_provider_id",+ "unique": true,+ "columnNames": [+ "profile_id",+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_combined_m3u_profile_members_profile_id_provider_id` ON `${TABLE_NAME}` (`profile_id`, `provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "combined_m3u_profiles",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "profile_id"+ ],+ "referencedColumns": [+ "id"+ ]+ },+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "recording_schedules",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, `channel_name` TEXT NOT NULL, `stream_url` TEXT NOT NULL, `program_title` TEXT, `requested_start_ms` INTEGER NOT NULL, `requested_end_ms` INTEGER NOT NULL, `recurrence` TEXT NOT NULL, `recurring_rule_id` TEXT, `enabled` INTEGER NOT NULL, `is_manual` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelId",+ "columnName": "channel_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelName",+ "columnName": "channel_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "programTitle",+ "columnName": "program_title",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "requestedStartMs",+ "columnName": "requested_start_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "requestedEndMs",+ "columnName": "requested_end_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "recurrence",+ "columnName": "recurrence",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "recurringRuleId",+ "columnName": "recurring_rule_id",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "enabled",+ "columnName": "enabled",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isManual",+ "columnName": "is_manual",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "priority",+ "columnName": "priority",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_recording_schedules_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_schedules_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_recording_schedules_enabled_requested_start_ms",+ "unique": false,+ "columnNames": [+ "enabled",+ "requested_start_ms"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_schedules_enabled_requested_start_ms` ON `${TABLE_NAME}` (`enabled`, `requested_start_ms`)"+ },+ {+ "name": "index_recording_schedules_recurring_rule_id",+ "unique": false,+ "columnNames": [+ "recurring_rule_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_schedules_recurring_rule_id` ON `${TABLE_NAME}` (`recurring_rule_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "recording_runs",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `schedule_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, `channel_name` TEXT NOT NULL, `stream_url` TEXT NOT NULL, `program_title` TEXT, `scheduled_start_ms` INTEGER NOT NULL, `scheduled_end_ms` INTEGER NOT NULL, `recurrence` TEXT NOT NULL, `recurring_rule_id` TEXT, `status` TEXT NOT NULL, `source_type` TEXT NOT NULL, `resolved_url` TEXT, `headers_json` TEXT NOT NULL, `user_agent` TEXT, `expiration_time` INTEGER, `provider_label` TEXT, `output_uri` TEXT, `output_display_path` TEXT, `bytes_written` INTEGER NOT NULL, `average_throughput_bps` INTEGER NOT NULL, `retry_count` INTEGER NOT NULL, `last_progress_at_ms` INTEGER, `failure_category` TEXT NOT NULL, `failure_reason` TEXT, `terminal_at_ms` INTEGER, `started_at_ms` INTEGER, `ended_at_ms` INTEGER, `schedule_enabled` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `alarm_start_at_ms` INTEGER, `alarm_stop_at_ms` INTEGER, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`schedule_id`) REFERENCES `recording_schedules`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "scheduleId",+ "columnName": "schedule_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelId",+ "columnName": "channel_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelName",+ "columnName": "channel_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "programTitle",+ "columnName": "program_title",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "scheduledStartMs",+ "columnName": "scheduled_start_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "scheduledEndMs",+ "columnName": "scheduled_end_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "recurrence",+ "columnName": "recurrence",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "recurringRuleId",+ "columnName": "recurring_rule_id",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "status",+ "columnName": "status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "sourceType",+ "columnName": "source_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "resolvedUrl",+ "columnName": "resolved_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "headersJson",+ "columnName": "headers_json",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "userAgent",+ "columnName": "user_agent",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "expirationTime",+ "columnName": "expiration_time",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "providerLabel",+ "columnName": "provider_label",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "outputUri",+ "columnName": "output_uri",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "outputDisplayPath",+ "columnName": "output_display_path",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "bytesWritten",+ "columnName": "bytes_written",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "averageThroughputBytesPerSecond",+ "columnName": "average_throughput_bps",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "retryCount",+ "columnName": "retry_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastProgressAtMs",+ "columnName": "last_progress_at_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "failureCategory",+ "columnName": "failure_category",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "failureReason",+ "columnName": "failure_reason",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "terminalAtMs",+ "columnName": "terminal_at_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "startedAtMs",+ "columnName": "started_at_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "endedAtMs",+ "columnName": "ended_at_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "scheduleEnabled",+ "columnName": "schedule_enabled",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "priority",+ "columnName": "priority",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "alarmStartAtMs",+ "columnName": "alarm_start_at_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "alarmStopAtMs",+ "columnName": "alarm_stop_at_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_recording_runs_schedule_id",+ "unique": false,+ "columnNames": [+ "schedule_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_schedule_id` ON `${TABLE_NAME}` (`schedule_id`)"+ },+ {+ "name": "index_recording_runs_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_recording_runs_status_scheduled_start_ms",+ "unique": false,+ "columnNames": [+ "status",+ "scheduled_start_ms"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_status_scheduled_start_ms` ON `${TABLE_NAME}` (`status`, `scheduled_start_ms`)"+ },+ {+ "name": "index_recording_runs_alarm_start_at_ms",+ "unique": false,+ "columnNames": [+ "alarm_start_at_ms"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_alarm_start_at_ms` ON `${TABLE_NAME}` (`alarm_start_at_ms`)"+ },+ {+ "name": "index_recording_runs_alarm_stop_at_ms",+ "unique": false,+ "columnNames": [+ "alarm_stop_at_ms"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_alarm_stop_at_ms` ON `${TABLE_NAME}` (`alarm_stop_at_ms`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "recording_schedules",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "schedule_id"+ ],+ "referencedColumns": [+ "id"+ ]+ },+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "program_reminders",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `channel_id` TEXT NOT NULL, `channel_name` TEXT NOT NULL, `program_title` TEXT NOT NULL, `program_start_time` INTEGER NOT NULL, `remind_at` INTEGER NOT NULL, `lead_time_minutes` INTEGER NOT NULL, `is_dismissed` INTEGER NOT NULL, `notified_at` INTEGER, `created_at` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelId",+ "columnName": "channel_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "channelName",+ "columnName": "channel_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "programTitle",+ "columnName": "program_title",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "programStartTime",+ "columnName": "program_start_time",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "remindAt",+ "columnName": "remind_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "leadTimeMinutes",+ "columnName": "lead_time_minutes",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isDismissed",+ "columnName": "is_dismissed",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "notifiedAt",+ "columnName": "notified_at",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_program_reminders_provider_id_remind_at",+ "unique": false,+ "columnNames": [+ "provider_id",+ "remind_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_program_reminders_provider_id_remind_at` ON `${TABLE_NAME}` (`provider_id`, `remind_at`)"+ },+ {+ "name": "index_program_reminders_is_dismissed_notified_at_remind_at",+ "unique": false,+ "columnNames": [+ "is_dismissed",+ "notified_at",+ "remind_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_program_reminders_is_dismissed_notified_at_remind_at` ON `${TABLE_NAME}` (`is_dismissed`, `notified_at`, `remind_at`)"+ },+ {+ "name": "index_program_reminders_provider_id_channel_id_program_start_time",+ "unique": false,+ "columnNames": [+ "provider_id",+ "channel_id",+ "program_start_time"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_program_reminders_provider_id_channel_id_program_start_time` ON `${TABLE_NAME}` (`provider_id`, `channel_id`, `program_start_time`)"+ },+ {+ "name": "index_program_reminders_provider_id_channel_id_program_title_program_start_time",+ "unique": true,+ "columnNames": [+ "provider_id",+ "channel_id",+ "program_title",+ "program_start_time"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_program_reminders_provider_id_channel_id_program_title_program_start_time` ON `${TABLE_NAME}` (`provider_id`, `channel_id`, `program_title`, `program_start_time`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "recording_storage",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER NOT NULL, `tree_uri` TEXT, `display_name` TEXT, `output_directory` TEXT, `available_bytes` INTEGER, `is_writable` INTEGER NOT NULL, `file_name_pattern` TEXT NOT NULL, `retention_days` INTEGER, `max_simultaneous_recordings` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, PRIMARY KEY(`id`))",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "treeUri",+ "columnName": "tree_uri",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "displayName",+ "columnName": "display_name",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "outputDirectory",+ "columnName": "output_directory",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "availableBytes",+ "columnName": "available_bytes",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "isWritable",+ "columnName": "is_writable",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "fileNamePattern",+ "columnName": "file_name_pattern",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "retentionDays",+ "columnName": "retention_days",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "maxSimultaneousRecordings",+ "columnName": "max_simultaneous_recordings",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "id"+ ]+ }+ }+ ],+ "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, 'b922a9d110039fe4527e63bfc20d9bcf')"+ ]+ }+}\ No newline at end of filediff --git a/data/src/androidTest/java/com/streamvault/data/local/StreamVaultDatabaseMigrationTest.kt b/data/src/androidTest/java/com/streamvault/data/local/StreamVaultDatabaseMigrationTest.ktindex 0e4c6372..3e5f8f9f 100644--- a/data/src/androidTest/java/com/streamvault/data/local/StreamVaultDatabaseMigrationTest.kt+++ b/data/src/androidTest/java/com/streamvault/data/local/StreamVaultDatabaseMigrationTest.kt@@ -6,6 +6,7 @@ import androidx.test.ext.junit.runners.AndroidJUnit4import androidx.test.platform.app.InstrumentationRegistryimport org.junit.Assert.assertEqualsimport org.junit.Assert.assertFalse+import org.junit.Assert.assertNotEqualsimport org.junit.Ruleimport org.junit.Testimport org.junit.runner.RunWith@@ -83,12 +84,12 @@ class StreamVaultDatabaseMigrationTest {}@Test- fun migrate1To30_fullChainValidatesLatestSchema() {+ fun migrate1To37_fullChainValidatesLatestSchema() {migrationTestHelper.createDatabase("streamvault-full-chain-test", 1).close()migrationTestHelper.runMigrationsAndValidate("streamvault-full-chain-test",- 30,+ 37,true,StreamVaultDatabase.MIGRATION_1_2,StreamVaultDatabase.MIGRATION_2_3,@@ -118,10 +119,339 @@ class StreamVaultDatabaseMigrationTest {StreamVaultDatabase.MIGRATION_26_27,StreamVaultDatabase.MIGRATION_27_28,StreamVaultDatabase.MIGRATION_28_29,- StreamVaultDatabase.MIGRATION_29_30+ StreamVaultDatabase.MIGRATION_29_30,+ StreamVaultDatabase.MIGRATION_30_31,+ StreamVaultDatabase.MIGRATION_31_32,+ StreamVaultDatabase.MIGRATION_32_33,+ StreamVaultDatabase.MIGRATION_33_34,+ StreamVaultDatabase.MIGRATION_34_35,+ StreamVaultDatabase.MIGRATION_35_36,+ StreamVaultDatabase.MIGRATION_36_37).close()}+ @Test+ fun migrate32To33_backfillsMovieWatchCountAndAddsGlobalFavoritesIndex() {+ migrationTestHelper.createDatabase("streamvault-32-33-test", 32).apply {+ execSQL(+ """+ INSERT INTO providers (+ id, name, type, server_url, username, password, m3u_url, epg_url,+ is_active, max_connections, allowed_output_formats_json, epg_sync_mode,+ xtream_fast_sync_enabled, m3u_vod_classification_enabled, status,+ last_synced_at, created_at+ ) VALUES (1, 'Provider', 'XTREAM_CODES', 'https://provider.example.com', 'demo', 'secret', '', '', 1, 1, '[]', 'PROVIDER', 0, 0, 'ACTIVE', 0, 0)+ """.trimIndent()+ )+ execSQL(+ """+ INSERT INTO movies (+ id, stream_id, name, stream_url, duration_seconds, rating, provider_id,+ watch_progress, last_watched_at, is_adult, is_user_protected, sync_fingerprint, added_at+ ) VALUES (10, 2001, 'Movie', 'https://provider.example.com/movie.mp4', 7200, 7.5, 1, 0, 0, 0, 0, 'fp-10', 0)+ """.trimIndent()+ )+ execSQL(+ """+ INSERT INTO playback_history (+ content_id, content_type, provider_id, title, poster_url, stream_url,+ resume_position_ms, total_duration_ms, last_watched_at, watch_count, watched_status,+ series_id, season_number, episode_number+ ) VALUES (10, 'MOVIE', 1, 'Movie', NULL, 'https://provider.example.com/movie.mp4', 1200, 7200, 55, 6, 'IN_PROGRESS', NULL, NULL, NULL)+ """.trimIndent()+ )+ execSQL(+ """+ INSERT INTO favorites (id, provider_id, content_id, content_type, position, group_id, added_at)+ VALUES (1, 1, 10, 'MOVIE', 0, NULL, 0)+ """.trimIndent()+ )+ close()+ }++ val migratedDb = migrationTestHelper.runMigrationsAndValidate(+ "streamvault-32-33-test",+ 33,+ true,+ StreamVaultDatabase.MIGRATION_32_33+ )++ assertEquals(6, countRows(migratedDb, "SELECT watch_count FROM movies WHERE id = 10"))+ assertEquals(+ 1,+ countRows(+ migratedDb,+ "SELECT COUNT(*) FROM sqlite_master WHERE type = 'index' AND name = 'index_favorites_global_provider_id_content_type_content_id' AND sql LIKE '%WHERE group_id IS NULL%'"+ )+ )++ migratedDb.close()+ }++ @Test+ fun migrate33To34_addsSuccessTimestampsAndProgramsEndTimeIndex() {+ migrationTestHelper.createDatabase("streamvault-33-34-test", 33).apply {+ execSQL(+ """+ INSERT INTO providers (+ id, name, type, server_url, username, password, m3u_url, epg_url,+ is_active, max_connections, allowed_output_formats_json, epg_sync_mode,+ xtream_fast_sync_enabled, m3u_vod_classification_enabled, status,+ last_synced_at, created_at+ ) VALUES (1, 'Provider', 'XTREAM_CODES', 'https://provider.example.com', 'demo', 'secret', '', '', 1, 1, '[]', 'PROVIDER', 0, 0, 'ACTIVE', 0, 0)+ """.trimIndent()+ )+ execSQL(+ """+ INSERT INTO sync_metadata (+ provider_id, last_live_sync, last_movie_sync, last_series_sync, last_epg_sync,+ last_movie_attempt, last_movie_success, last_movie_partial,+ live_count, movie_count, series_count, epg_count, last_sync_status, movie_sync_mode,+ movie_warnings_count, movie_catalog_stale, live_avoid_full_until, movie_avoid_full_until,+ series_avoid_full_until, live_sequential_failures_remembered, live_healthy_sync_streak,+ movie_parallel_failures_remembered, movie_healthy_sync_streak,+ series_sequential_failures_remembered, series_healthy_sync_streak+ ) VALUES (+ 1, 11, 22, 33, 44,+ 55, 66, 77,+ 1, 2, 3, 4, 'SUCCESS', 'FULL',+ 0, 0, 0, 0,+ 0, 0, 0,+ 0, 0,+ 0, 0+ )+ """.trimIndent()+ )+ close()+ }++ val migratedDb = migrationTestHelper.runMigrationsAndValidate(+ "streamvault-33-34-test",+ 34,+ true,+ StreamVaultDatabase.MIGRATION_33_34+ )++ assertEquals(11, countRows(migratedDb, "SELECT last_live_success FROM sync_metadata WHERE provider_id = 1"))+ assertEquals(33, countRows(migratedDb, "SELECT last_series_success FROM sync_metadata WHERE provider_id = 1"))+ assertEquals(44, countRows(migratedDb, "SELECT last_epg_success FROM sync_metadata WHERE provider_id = 1"))+ assertEquals(+ 1,+ countRows(+ migratedDb,+ "SELECT COUNT(*) FROM sqlite_master WHERE type = 'index' AND name = 'index_programs_provider_id_end_time_channel_id'"+ )+ )++ migratedDb.close()+ }++ @Test+ fun migrate34To35_createsSearchHistoryTable() {+ migrationTestHelper.createDatabase("streamvault-34-35-test", 34).close()++ val migratedDb = migrationTestHelper.runMigrationsAndValidate(+ "streamvault-34-35-test",+ 35,+ true,+ StreamVaultDatabase.MIGRATION_34_35+ )++ assertEquals(1, countRows(migratedDb, "SELECT COUNT(*) FROM pragma_table_info('search_history') WHERE name = 'query'"))+ assertEquals(1, countRows(migratedDb, "SELECT COUNT(*) FROM pragma_table_info('search_history') WHERE name = 'content_scope'"))+ assertEquals(+ 1,+ countRows(+ migratedDb,+ "SELECT COUNT(*) FROM sqlite_master WHERE type = 'index' AND name = 'index_search_history_query_content_scope_provider_id'"+ )+ )++ migratedDb.close()+ }++ @Test+ fun migrate31To32_scopesFavoritesAndSplitsMixedProviderGroups() {+ migrationTestHelper.createDatabase("streamvault-31-32-test", 31).apply {+ execSQL(+ """+ INSERT INTO providers (+ id, name, type, server_url, username, password, m3u_url, epg_url,+ is_active, max_connections, allowed_output_formats_json, epg_sync_mode,+ xtream_fast_sync_enabled, m3u_vod_classification_enabled, status,+ last_synced_at, created_at+ ) VALUES+ (1, 'Provider One', 'XTREAM_CODES', 'https://one.example.com', 'one', 'secret', '', '', 1, 1, '[]', 'PROVIDER', 0, 0, 'ACTIVE', 0, 0),+ (2, 'Provider Two', 'XTREAM_CODES', 'https://two.example.com', 'two', 'secret', '', '', 0, 1, '[]', 'PROVIDER', 0, 0, 'ACTIVE', 0, 0)+ """.trimIndent()+ )+ execSQL(+ """+ INSERT INTO channels (+ id, stream_id, name, stream_url, number, catch_up_supported, catch_up_days,+ provider_id, is_adult, is_user_protected, logical_group_id, error_count, sync_fingerprint+ ) VALUES+ (101, 1001, 'Provider One Global', 'https://one.example.com/live/1001', 1, 0, 0, 1, 0, 0, 'lg-101', 0, 'fp-101'),+ (102, 1002, 'Provider One Grouped', 'https://one.example.com/live/1002', 2, 0, 0, 1, 0, 0, 'lg-102', 0, 'fp-102'),+ (201, 2001, 'Provider Two Grouped', 'https://two.example.com/live/2001', 1, 0, 0, 2, 0, 0, 'lg-201', 0, 'fp-201')+ """.trimIndent()+ )+ execSQL(+ """+ INSERT INTO virtual_groups (id, name, icon_emoji, position, created_at, content_type)+ VALUES (10, 'Mixed Group', NULL, 0, 100, 'LIVE')+ """.trimIndent()+ )+ execSQL(+ """+ INSERT INTO favorites (id, content_id, content_type, position, group_id, added_at)+ VALUES+ (1, 101, 'LIVE', 0, NULL, 1000),+ (2, 102, 'LIVE', 1, 10, 1001),+ (3, 201, 'LIVE', 0, 10, 1002)+ """.trimIndent()+ )+ close()+ }++ val migratedDb = migrationTestHelper.runMigrationsAndValidate(+ "streamvault-31-32-test",+ 32,+ true,+ StreamVaultDatabase.MIGRATION_31_32+ )++ assertEquals(2, countRows(migratedDb, "SELECT COUNT(*) FROM virtual_groups WHERE name = 'Mixed Group'"))+ assertEquals(1, countRows(migratedDb, "SELECT COUNT(*) FROM virtual_groups WHERE provider_id = 1 AND name = 'Mixed Group'"))+ assertEquals(1, countRows(migratedDb, "SELECT COUNT(*) FROM virtual_groups WHERE provider_id = 2 AND name = 'Mixed Group'"))++ assertEquals(2, countRows(migratedDb, "SELECT COUNT(*) FROM favorites WHERE provider_id = 1"))+ assertEquals(1, countRows(migratedDb, "SELECT COUNT(*) FROM favorites WHERE provider_id = 2"))+ assertEquals(1, countRows(migratedDb, "SELECT COUNT(*) FROM favorites WHERE provider_id = 1 AND group_id IS NULL"))++ val providerOneGroupId = firstLong(+ migratedDb,+ "SELECT group_id FROM favorites WHERE provider_id = 1 AND content_id = 102"+ )+ val providerTwoGroupId = firstLong(+ migratedDb,+ "SELECT group_id FROM favorites WHERE provider_id = 2 AND content_id = 201"+ )++ assertEquals(10L, providerOneGroupId)+ assertNotEquals(providerOneGroupId, providerTwoGroupId)++ migratedDb.close()+ }++ @Test+ fun migrate31To32_assignsLegacyGroupsWhenNoProviderIsActive() {+ migrationTestHelper.createDatabase("streamvault-31-32-no-active-test", 31).apply {+ execSQL(+ """+ INSERT INTO providers (+ id, name, type, server_url, username, password, m3u_url, epg_url,+ is_active, max_connections, allowed_output_formats_json, epg_sync_mode,+ xtream_fast_sync_enabled, m3u_vod_classification_enabled, status,+ last_synced_at, created_at+ ) VALUES+ (5, 'First Provider', 'XTREAM_CODES', 'https://one.example.com', 'one', 'secret', '', '', 0, 1, '[]', 'PROVIDER', 0, 0, 'ACTIVE', 0, 10),+ (7, 'Second Provider', 'XTREAM_CODES', 'https://two.example.com', 'two', 'secret', '', '', 0, 1, '[]', 'PROVIDER', 0, 0, 'ACTIVE', 0, 20)+ """.trimIndent()+ )+ execSQL(+ """+ INSERT INTO virtual_groups (id, name, icon_emoji, position, created_at, content_type)+ VALUES (10, 'Legacy Group', NULL, 0, 100, 'LIVE')+ """.trimIndent()+ )+ close()+ }++ val migratedDb = migrationTestHelper.runMigrationsAndValidate(+ "streamvault-31-32-no-active-test",+ 32,+ true,+ StreamVaultDatabase.MIGRATION_31_32+ )++ assertEquals(0, countRows(migratedDb, "SELECT COUNT(*) FROM virtual_groups WHERE provider_id = 0 OR provider_id IS NULL"))+ assertEquals(1, countRows(migratedDb, "SELECT COUNT(*) FROM virtual_groups WHERE id = 10 AND provider_id = 5"))++ migratedDb.close()+ }++ @Test+ fun migrate35To36_addsProgramRemindersAndEpgMatchMetadata() {+ migrationTestHelper.createDatabase("streamvault-35-36-test", 35).close()++ val migratedDb = migrationTestHelper.runMigrationsAndValidate(+ "streamvault-35-36-test",+ 36,+ true,+ StreamVaultDatabase.MIGRATION_35_36+ )++ assertEquals(1, countRows(migratedDb, "SELECT COUNT(*) FROM pragma_table_info('channel_epg_mappings') WHERE name = 'matched_at'"))+ assertEquals(1, countRows(migratedDb, "SELECT COUNT(*) FROM pragma_table_info('channel_epg_mappings') WHERE name = 'failed_attempts'"))+ assertEquals(1, countRows(migratedDb, "SELECT COUNT(*) FROM pragma_table_info('channel_epg_mappings') WHERE name = 'source'"))+ assertEquals(1, countRows(migratedDb, "SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = 'program_reminders'"))+ assertEquals(+ 1,+ countRows(+ migratedDb,+ "SELECT COUNT(*) FROM sqlite_master WHERE type = 'index' AND name = 'index_program_reminders_provider_id_channel_id_program_title_program_start_time'"+ )+ )++ migratedDb.close()+ }++ @Test+ fun migrate36To37_createsTmdbIdentityTable() {+ migrationTestHelper.createDatabase("streamvault-36-37-test", 36).apply {+ execSQL(+ """+ INSERT INTO providers (+ id, name, type, server_url, username, password, m3u_url, epg_url,+ is_active, max_connections, allowed_output_formats_json, epg_sync_mode,+ xtream_fast_sync_enabled, m3u_vod_classification_enabled, status,+ last_synced_at, created_at+ ) VALUES (1, 'Provider', 'XTREAM_CODES', 'https://provider.example.com', 'demo', 'secret', '', '', 1, 1, '[]', 'PROVIDER', 0, 0, 'ACTIVE', 0, 0)+ """.trimIndent()+ )+ execSQL(+ """+ INSERT INTO movies (+ id, stream_id, name, stream_url, duration_seconds, rating, tmdb_id, provider_id,+ watch_progress, watch_count, last_watched_at, is_adult, is_user_protected, sync_fingerprint, added_at+ ) VALUES (10, 2001, 'Movie', 'https://provider.example.com/movie.mp4', 7200, 7.5, 12345, 1, 0, 0, 0, 0, 0, 'fp-10', 0)+ """.trimIndent()+ )+ execSQL(+ """+ INSERT INTO series (+ id, series_id, name, rating, tmdb_id, last_modified, provider_id, is_adult, is_user_protected, sync_fingerprint+ ) VALUES (20, 3001, 'Series', 8.1, 67890, 0, 1, 0, 0, 'fp-20')+ """.trimIndent()+ )+ close()+ }++ val migratedDb = migrationTestHelper.runMigrationsAndValidate(+ "streamvault-36-37-test",+ 37,+ true,+ StreamVaultDatabase.MIGRATION_36_37+ )++ assertEquals(1, countRows(migratedDb, "SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = 'tmdb_identity'"))+ assertEquals(1, countRows(migratedDb, "SELECT COUNT(*) FROM tmdb_identity WHERE tmdb_id = 12345 AND content_type = 'MOVIE'"))+ assertEquals(1, countRows(migratedDb, "SELECT COUNT(*) FROM tmdb_identity WHERE tmdb_id = 67890 AND content_type = 'SERIES'"))++ migratedDb.close()+ }+@Testfun migrate14To15_addsAuditCompletionColumns() {migrationTestHelper.createDatabase("streamvault-14-15-test", 14).apply {@@ -172,4 +502,11 @@ class StreamVaultDatabaseMigrationTest {return cursor.moveToFirst()}}++ private fun firstLong(db: androidx.sqlite.db.SupportSQLiteDatabase, sql: String): Long {+ db.query(sql).use { cursor ->+ cursor.moveToFirst()+ return cursor.getLong(0)+ }+ }}diff --git a/data/src/main/AndroidManifest.xml b/data/src/main/AndroidManifest.xmlindex bdfd18c2..5fb4d58c 100644--- a/data/src/main/AndroidManifest.xml+++ b/data/src/main/AndroidManifest.xml@@ -10,6 +10,10 @@android:name="com.streamvault.data.manager.recording.RecordingAlarmReceiver"android:exported="false" />+ <receiver+ android:name="com.streamvault.data.manager.reminder.ProgramReminderAlarmReceiver"+ android:exported="false" />+<receiverandroid:name="com.streamvault.data.manager.recording.RecordingRestoreReceiver"android:enabled="true"@@ -20,5 +24,16 @@<action android:name="android.intent.action.MY_PACKAGE_REPLACED" /></intent-filter></receiver>++ <receiver+ android:name="com.streamvault.data.manager.reminder.ProgramReminderRestoreReceiver"+ android:enabled="true"+ android:exported="true">+ <intent-filter>+ <action android:name="android.intent.action.BOOT_COMPLETED" />+ <action android:name="android.intent.action.LOCKED_BOOT_COMPLETED" />+ <action android:name="android.intent.action.MY_PACKAGE_REPLACED" />+ </intent-filter>+ </receiver></application></manifest>diff --git a/data/src/main/java/com/streamvault/data/epg/EpgResolutionEngine.kt b/data/src/main/java/com/streamvault/data/epg/EpgResolutionEngine.ktindex 6cebdaeb..70d7bc7a 100644--- a/data/src/main/java/com/streamvault/data/epg/EpgResolutionEngine.kt+++ b/data/src/main/java/com/streamvault/data/epg/EpgResolutionEngine.kt@@ -42,6 +42,8 @@ class EpgResolutionEngine @Inject constructor() {companion object {private const val TAG = "EpgResolutionEngine"+ private const val LOW_CONFIDENCE_THRESHOLD = 0.7f+ private const val MAX_REMATCH_ATTEMPTS = 6}/**@@ -103,6 +105,7 @@ class EpgResolutionEngine @Inject constructor(// Preserve existing manual overridesval existingMappings = channelEpgMappingDao.getForProvider(providerId)+ val existingMappingsByChannel = existingMappings.associateBy { it.providerChannelId }val manualOverrides = existingMappings.filter { it.isManualOverride }.associateBy { it.providerChannelId }@@ -110,13 +113,21 @@ class EpgResolutionEngine @Inject constructor(var exactIdMatches = 0var normalizedNameMatches = 0var providerNativeMatches = 0+ var manualMatches = 0var unresolvedCount = 0val mappings = channels.map { channel ->+ val existing = existingMappingsByChannel[channel.id]// 1. Check for manual overrideval manual = manualOverrides[channel.id]if (manual != null) {- return@map manual.copy(updatedAt = now)+ manualMatches+++ return@map manual.copy(+ matchedAt = manual.matchedAt.takeIf { it > 0L } ?: now,+ failedAttempts = 0,+ source = "override",+ updatedAt = now+ )}val channelEpgId = channel.epgChannelId?.trim()?.takeIf(String::isNotEmpty)@@ -135,6 +146,9 @@ class EpgResolutionEngine @Inject constructor(xmltvChannelId = channelEpgId,matchType = EpgMatchType.EXACT_ID.name,confidence = 1.0f,+ matchedAt = now,+ failedAttempts = 0,+ source = "tvg_id",updatedAt = now)}@@ -157,6 +171,9 @@ class EpgResolutionEngine @Inject constructor(xmltvChannelId = matchedXmltvId,matchType = EpgMatchType.NORMALIZED_NAME.name,confidence = 0.7f,+ matchedAt = now,+ failedAttempts = 0,+ source = "name_match",updatedAt = now)}@@ -174,6 +191,9 @@ class EpgResolutionEngine @Inject constructor(xmltvChannelId = channelEpgId,matchType = EpgMatchType.PROVIDER_NATIVE.name,confidence = 0.5f,+ matchedAt = now,+ failedAttempts = 0,+ source = "provider_native",updatedAt = now)}@@ -188,6 +208,9 @@ class EpgResolutionEngine @Inject constructor(xmltvChannelId = null,matchType = null,confidence = 0f,+ matchedAt = existing?.matchedAt ?: 0L,+ failedAttempts = (existing?.failedAttempts ?: 0).coerceAtMost(MAX_REMATCH_ATTEMPTS - 1) + 1,+ source = "unmatched",updatedAt = now)}@@ -199,7 +222,13 @@ class EpgResolutionEngine @Inject constructor(exactIdMatches = exactIdMatches,normalizedNameMatches = normalizedNameMatches,providerNativeMatches = providerNativeMatches,- unresolvedChannels = unresolvedCount+ manualMatches = manualMatches,+ unresolvedChannels = unresolvedCount,+ lowConfidenceChannels = mappings.count { it.confidence > 0f && it.confidence < LOW_CONFIDENCE_THRESHOLD },+ rematchCandidateChannels = mappings.count {+ it.failedAttempts < MAX_REMATCH_ATTEMPTS &&+ (it.sourceType == EpgSourceType.NONE.name || (it.confidence > 0f && it.confidence < LOW_CONFIDENCE_THRESHOLD))+ })Log.d(TAG, "Resolution for provider $providerId: $summary")summary@@ -313,6 +342,7 @@ class EpgResolutionEngine @Inject constructor(var exactId = 0var normalizedName = 0var providerNative = 0+ var manual = 0var unresolved = 0for (row in stats) {@@ -322,7 +352,7 @@ class EpgResolutionEngine @Inject constructor(row.matchType == EpgMatchType.EXACT_ID.name -> exactId += row.cntrow.matchType == EpgMatchType.NORMALIZED_NAME.name -> normalizedName += row.cntrow.matchType == EpgMatchType.PROVIDER_NATIVE.name -> providerNative += row.cnt- row.matchType == EpgMatchType.MANUAL.name -> exactId += row.cnt // count manual as exact+ row.matchType == EpgMatchType.MANUAL.name -> manual += row.cnt}}@@ -331,7 +361,14 @@ class EpgResolutionEngine @Inject constructor(exactIdMatches = exactId,normalizedNameMatches = normalizedName,providerNativeMatches = providerNative,- unresolvedChannels = unresolved+ manualMatches = manual,+ unresolvedChannels = unresolved,+ lowConfidenceChannels = channelEpgMappingDao.countLowConfidence(providerId, LOW_CONFIDENCE_THRESHOLD),+ rematchCandidateChannels = channelEpgMappingDao.countRematchCandidates(+ providerId = providerId,+ minConfidence = LOW_CONFIDENCE_THRESHOLD,+ maxAttempts = MAX_REMATCH_ATTEMPTS+ ))}}diff --git a/data/src/main/java/com/streamvault/data/local/StreamVaultDatabase.kt b/data/src/main/java/com/streamvault/data/local/StreamVaultDatabase.ktindex e45e17e2..ffdf609b 100644--- a/data/src/main/java/com/streamvault/data/local/StreamVaultDatabase.kt+++ b/data/src/main/java/com/streamvault/data/local/StreamVaultDatabase.kt@@ -28,6 +28,8 @@ import com.streamvault.data.local.entity.*FavoriteEntity::class,VirtualGroupEntity::class,PlaybackHistoryEntity::class,+ TmdbIdentityEntity::class,+ SearchHistoryEntity::class,SyncMetadataEntity::class,MovieCategoryHydrationEntity::class,SeriesCategoryHydrationEntity::class,@@ -40,9 +42,10 @@ import com.streamvault.data.local.entity.*CombinedM3uProfileMemberEntity::class,RecordingScheduleEntity::class,RecordingRunEntity::class,+ ProgramReminderEntity::class,RecordingStorageEntity::class],- version = 30,+ version = 37,exportSchema = true // ← was false; schema JSON now tracked in version control)@TypeConverters(RoomEnumConverters::class)@@ -59,6 +62,8 @@ abstract class StreamVaultDatabase : RoomDatabase() {abstract fun favoriteDao(): FavoriteDaoabstract fun virtualGroupDao(): VirtualGroupDaoabstract fun playbackHistoryDao(): PlaybackHistoryDao+ abstract fun tmdbIdentityDao(): TmdbIdentityDao+ abstract fun searchHistoryDao(): SearchHistoryDaoabstract fun syncMetadataDao(): SyncMetadataDaoabstract fun movieCategoryHydrationDao(): MovieCategoryHydrationDaoabstract fun seriesCategoryHydrationDao(): SeriesCategoryHydrationDao@@ -71,9 +76,23 @@ abstract class StreamVaultDatabase : RoomDatabase() {abstract fun combinedM3uProfileMemberDao(): CombinedM3uProfileMemberDaoabstract fun recordingScheduleDao(): RecordingScheduleDaoabstract fun recordingRunDao(): RecordingRunDao+ abstract fun programReminderDao(): ProgramReminderDaoabstract fun recordingStorageDao(): RecordingStorageDaocompanion object {+ private fun validateForeignKeys(database: SupportSQLiteDatabase) {+ database.query("PRAGMA foreign_key_check").use { cursor ->+ if (cursor.moveToFirst()) {+ val table = if (!cursor.isNull(0)) cursor.getString(0) else "<unknown>"+ val rowId = if (!cursor.isNull(1)) cursor.getLong(1) else -1L+ val parent = if (!cursor.isNull(2)) cursor.getString(2) else "<unknown>"+ throw IllegalStateException(+ "Foreign key violation after migration: table=$table rowId=$rowId parent=$parent"+ )+ }+ }+ }+/*** Migration 1 → 2: no-op stub.* v1 databases had the same table structure as v2; this migration prevents Room@@ -527,6 +546,7 @@ abstract class StreamVaultDatabase : RoomDatabase() {database.execSQL("CREATE INDEX IF NOT EXISTS index_episodes_provider_id ON episodes(provider_id)")database.execSQL("CREATE UNIQUE INDEX IF NOT EXISTS index_episodes_provider_id_episode_id ON episodes(provider_id, episode_id)")database.execSQL("DROP TABLE episode_id_map")+ validateForeignKeys(database)}}@@ -886,6 +906,7 @@ abstract class StreamVaultDatabase : RoomDatabase() {database.execSQL("CREATE UNIQUE INDEX index_favorites_content_id_content_type_group_id ON favorites(content_id, content_type, group_id)")database.execSQL("CREATE INDEX index_favorites_content_type_group_id ON favorites(content_type, group_id)")database.execSQL("CREATE INDEX index_favorites_group_id_position ON favorites(group_id, position)")+ validateForeignKeys(database)}}/**@@ -1326,6 +1347,7 @@ abstract class StreamVaultDatabase : RoomDatabase() {)""".trimIndent())+ validateForeignKeys(database)}}@@ -1367,6 +1389,295 @@ abstract class StreamVaultDatabase : RoomDatabase() {}}+ val MIGRATION_30_31 = object : Migration(30, 31) {+ override fun migrate(database: SupportSQLiteDatabase) {+ database.execSQL("ALTER TABLE movies ADD COLUMN added_at INTEGER NOT NULL DEFAULT 0")+ }+ }++ val MIGRATION_31_32 = object : Migration(31, 32) {+ override fun migrate(database: SupportSQLiteDatabase) {+ fun firstLong(query: String): Long? = database.query(query).use { cursor ->+ if (cursor.moveToFirst() && !cursor.isNull(0)) cursor.getLong(0) else null+ }++ val defaultProviderId = firstLong(+ "SELECT id FROM providers WHERE is_active = 1 ORDER BY id LIMIT 1"+ ) ?: firstLong(+ "SELECT id FROM providers ORDER BY id LIMIT 1"+ )++ database.execSQL(+ """+ CREATE TABLE IF NOT EXISTS virtual_groups_new (+ id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,+ provider_id INTEGER NOT NULL,+ name TEXT NOT NULL,+ icon_emoji TEXT,+ position INTEGER NOT NULL,+ created_at INTEGER NOT NULL,+ content_type TEXT NOT NULL,+ FOREIGN KEY(provider_id) REFERENCES providers(id) ON DELETE CASCADE+ )+ """.trimIndent()+ )++ val providersByLegacyGroup = mutableMapOf<Long, MutableSet<Long>>()+ database.query(+ """+ SELECT f.group_id,+ CASE f.content_type+ WHEN 'LIVE' THEN (SELECT provider_id FROM channels WHERE id = f.content_id)+ WHEN 'MOVIE' THEN (SELECT provider_id FROM movies WHERE id = f.content_id)+ WHEN 'SERIES' THEN (SELECT provider_id FROM series WHERE id = f.content_id)+ ELSE NULL+ END AS provider_id+ FROM favorites f+ WHERE f.group_id IS NOT NULL+ """.trimIndent()+ ).use { cursor ->+ while (cursor.moveToNext()) {+ if (cursor.isNull(0) || cursor.isNull(1)) continue+ val groupId = cursor.getLong(0)+ val providerId = cursor.getLong(1)+ providersByLegacyGroup.getOrPut(groupId) { linkedSetOf() }.add(providerId)+ }+ }++ val groupProviderToNewId = mutableMapOf<Pair<Long, Long>, Long>()+ var nextGroupId = (firstLong("SELECT MAX(id) FROM virtual_groups") ?: 0L) + 1L++ database.query(+ "SELECT id, name, icon_emoji, position, created_at, content_type FROM virtual_groups ORDER BY id"+ ).use { cursor ->+ while (cursor.moveToNext()) {+ val legacyGroupId = cursor.getLong(0)+ val name = cursor.getString(1)+ val iconEmoji = if (cursor.isNull(2)) null else cursor.getString(2)+ val position = cursor.getInt(3)+ val createdAt = cursor.getLong(4)+ val contentType = cursor.getString(5)+ val providerIds = providersByLegacyGroup[legacyGroupId]+ ?.toList()+ ?.sorted()+ ?: defaultProviderId?.let(::listOf)+ ?: emptyList()++ providerIds.forEachIndexed { index, providerId ->+ val newGroupId = if (index == 0) legacyGroupId else nextGroupId+++ groupProviderToNewId[legacyGroupId to providerId] = newGroupId+ database.execSQL(+ """+ INSERT INTO virtual_groups_new(+ id, provider_id, name, icon_emoji, position, created_at, content_type+ ) VALUES (?, ?, ?, ?, ?, ?, ?)+ """.trimIndent(),+ arrayOf(newGroupId, providerId, name, iconEmoji, position, createdAt, contentType)+ )+ }+ }+ }++ database.execSQL("ALTER TABLE virtual_groups RENAME TO virtual_groups_legacy")+ database.execSQL("ALTER TABLE virtual_groups_new RENAME TO virtual_groups")+ database.execSQL(+ "CREATE INDEX IF NOT EXISTS index_virtual_groups_provider_id_content_type ON virtual_groups(provider_id, content_type)"+ )+ database.execSQL(+ "CREATE INDEX IF NOT EXISTS index_virtual_groups_position ON virtual_groups(position)"+ )+ database.execSQL(+ "CREATE INDEX IF NOT EXISTS index_virtual_groups_content_type ON virtual_groups(content_type)"+ )++ database.execSQL(+ """+ CREATE TABLE IF NOT EXISTS favorites_new (+ id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,+ provider_id INTEGER NOT NULL,+ content_id INTEGER NOT NULL,+ content_type TEXT NOT NULL,+ position INTEGER NOT NULL,+ group_id INTEGER,+ added_at INTEGER NOT NULL,+ FOREIGN KEY(provider_id) REFERENCES providers(id) ON DELETE CASCADE,+ FOREIGN KEY(group_id) REFERENCES virtual_groups(id) ON DELETE SET NULL+ )+ """.trimIndent()+ )++ database.query(+ """+ SELECT f.id, f.content_id, f.content_type, f.position, f.group_id, f.added_at,+ CASE f.content_type+ WHEN 'LIVE' THEN (SELECT provider_id FROM channels WHERE id = f.content_id)+ WHEN 'MOVIE' THEN (SELECT provider_id FROM movies WHERE id = f.content_id)+ WHEN 'SERIES' THEN (SELECT provider_id FROM series WHERE id = f.content_id)+ ELSE NULL+ END AS provider_id+ FROM favorites f+ ORDER BY f.id ASC+ """.trimIndent()+ ).use { cursor ->+ while (cursor.moveToNext()) {+ val favoriteId = cursor.getLong(0)+ val contentId = cursor.getLong(1)+ val contentType = cursor.getString(2)+ val position = cursor.getInt(3)+ val legacyGroupId = if (cursor.isNull(4)) null else cursor.getLong(4)+ val addedAt = cursor.getLong(5)+ val providerId = when {+ !cursor.isNull(6) -> cursor.getLong(6)+ legacyGroupId != null -> groupProviderToNewId.keys+ .firstOrNull { it.first == legacyGroupId }+ ?.second+ else -> null+ } ?: continue++ val newGroupId = legacyGroupId?.let { groupId ->+ groupProviderToNewId[groupId to providerId]+ ?: groupProviderToNewId.entries.firstOrNull { it.key.first == groupId }?.value+ }++ database.execSQL(+ """+ INSERT OR REPLACE INTO favorites_new(+ id, provider_id, content_id, content_type, position, group_id, added_at+ ) VALUES (?, ?, ?, ?, ?, ?, ?)+ """.trimIndent(),+ arrayOf(favoriteId, providerId, contentId, contentType, position, newGroupId, addedAt)+ )+ }+ }++ database.execSQL("ALTER TABLE favorites RENAME TO favorites_legacy")+ database.execSQL("ALTER TABLE favorites_new RENAME TO favorites")+ database.execSQL(+ "CREATE UNIQUE INDEX IF NOT EXISTS index_favorites_provider_id_content_id_content_type_group_id ON favorites(provider_id, content_id, content_type, group_id)"+ )+ database.execSQL(+ "CREATE INDEX IF NOT EXISTS index_favorites_provider_id_content_type_group_id ON favorites(provider_id, content_type, group_id)"+ )+ database.execSQL(+ "CREATE INDEX IF NOT EXISTS index_favorites_group_id_position ON favorites(group_id, position)"+ )++ database.execSQL("DROP TABLE favorites_legacy")+ database.execSQL("DROP TABLE virtual_groups_legacy")+ validateForeignKeys(database)+ }+ }++ val MIGRATION_32_33 = object : Migration(32, 33) {+ override fun migrate(database: SupportSQLiteDatabase) {+ database.execSQL("ALTER TABLE movies ADD COLUMN watch_count INTEGER NOT NULL DEFAULT 0")+ database.execSQL(+ """+ UPDATE movies+ SET watch_count = COALESCE((+ SELECT playback_history.watch_count+ FROM playback_history+ WHERE playback_history.content_id = movies.id+ AND playback_history.content_type = 'MOVIE'+ AND playback_history.provider_id = movies.provider_id+ ), 0)+ """.trimIndent()+ )+ database.execSQL(+ """+ CREATE INDEX IF NOT EXISTS index_favorites_global_provider_id_content_type_content_id+ ON favorites(provider_id, content_type, content_id)+ WHERE group_id IS NULL+ """.trimIndent()+ )+ }+ }++ val MIGRATION_33_34 = object : Migration(33, 34) {+ override fun migrate(database: SupportSQLiteDatabase) {+ database.execSQL("ALTER TABLE sync_metadata ADD COLUMN last_live_success INTEGER NOT NULL DEFAULT 0")+ database.execSQL("ALTER TABLE sync_metadata ADD COLUMN last_series_success INTEGER NOT NULL DEFAULT 0")+ database.execSQL("ALTER TABLE sync_metadata ADD COLUMN last_epg_success INTEGER NOT NULL DEFAULT 0")+ database.execSQL("UPDATE sync_metadata SET last_live_success = last_live_sync")+ database.execSQL("UPDATE sync_metadata SET last_series_success = last_series_sync")+ database.execSQL("UPDATE sync_metadata SET last_epg_success = last_epg_sync")+ database.execSQL(+ "CREATE INDEX IF NOT EXISTS index_programs_provider_id_end_time_channel_id ON programs(provider_id, end_time, channel_id)"+ )+ validateForeignKeys(database)+ }+ }++ val MIGRATION_34_35 = object : Migration(34, 35) {+ override fun migrate(database: SupportSQLiteDatabase) {+ database.execSQL(+ """+ CREATE TABLE IF NOT EXISTS search_history (+ id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,+ query TEXT NOT NULL,+ content_scope TEXT NOT NULL,+ provider_id INTEGER NOT NULL DEFAULT 0,+ used_at INTEGER NOT NULL,+ use_count INTEGER NOT NULL DEFAULT 1+ )+ """.trimIndent()+ )+ database.execSQL(+ "CREATE INDEX IF NOT EXISTS index_search_history_content_scope_provider_id_used_at ON search_history(content_scope, provider_id, used_at)"+ )+ database.execSQL(+ "CREATE INDEX IF NOT EXISTS index_search_history_used_at ON search_history(used_at)"+ )+ database.execSQL(+ "CREATE INDEX IF NOT EXISTS index_search_history_provider_id ON search_history(provider_id)"+ )+ database.execSQL(+ "CREATE UNIQUE INDEX IF NOT EXISTS index_search_history_query_content_scope_provider_id ON search_history(query, content_scope, provider_id)"+ )+ validateForeignKeys(database)+ }+ }++ val MIGRATION_35_36 = object : Migration(35, 36) {+ override fun migrate(database: SupportSQLiteDatabase) {+ database.execSQL("ALTER TABLE channel_epg_mappings ADD COLUMN matched_at INTEGER NOT NULL DEFAULT 0")+ database.execSQL("ALTER TABLE channel_epg_mappings ADD COLUMN failed_attempts INTEGER NOT NULL DEFAULT 0")+ database.execSQL("ALTER TABLE channel_epg_mappings ADD COLUMN source TEXT")++ database.execSQL(+ """+ CREATE TABLE IF NOT EXISTS program_reminders (+ id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,+ provider_id INTEGER NOT NULL,+ channel_id TEXT NOT NULL,+ channel_name TEXT NOT NULL,+ program_title TEXT NOT NULL,+ program_start_time INTEGER NOT NULL,+ remind_at INTEGER NOT NULL,+ lead_time_minutes INTEGER NOT NULL DEFAULT 5,+ is_dismissed INTEGER NOT NULL DEFAULT 0,+ notified_at INTEGER,+ created_at INTEGER NOT NULL,+ FOREIGN KEY(provider_id) REFERENCES providers(id) ON DELETE CASCADE+ )+ """.trimIndent()+ )+ database.execSQL(+ "CREATE INDEX IF NOT EXISTS index_program_reminders_provider_id_remind_at ON program_reminders(provider_id, remind_at)"+ )+ database.execSQL(+ "CREATE INDEX IF NOT EXISTS index_program_reminders_is_dismissed_notified_at_remind_at ON program_reminders(is_dismissed, notified_at, remind_at)"+ )+ database.execSQL(+ "CREATE INDEX IF NOT EXISTS index_program_reminders_provider_id_channel_id_program_start_time ON program_reminders(provider_id, channel_id, program_start_time)"+ )+ database.execSQL(+ "CREATE UNIQUE INDEX IF NOT EXISTS index_program_reminders_provider_id_channel_id_program_title_program_start_time ON program_reminders(provider_id, channel_id, program_title, program_start_time)"+ )+ validateForeignKeys(database)+ }+ }+val MIGRATION_24_25 = object : Migration(24, 25) {override fun migrate(database: SupportSQLiteDatabase) {// ── epg_sources ──@@ -1461,5 +1772,43 @@ abstract class StreamVaultDatabase : RoomDatabase() {database.execSQL("CREATE INDEX IF NOT EXISTS index_channel_epg_mappings_provider_id ON channel_epg_mappings(provider_id)")}}++ val MIGRATION_36_37 = object : Migration(36, 37) {+ override fun migrate(database: SupportSQLiteDatabase) {+ database.execSQL(+ """+ CREATE TABLE IF NOT EXISTS tmdb_identity (+ tmdb_id INTEGER NOT NULL,+ content_type TEXT NOT NULL,+ canonical_provider_id INTEGER NOT NULL,+ first_seen_at INTEGER NOT NULL,+ PRIMARY KEY (tmdb_id, content_type),+ FOREIGN KEY(canonical_provider_id) REFERENCES providers(id) ON DELETE CASCADE+ )+ """.trimIndent()+ )+ database.execSQL("CREATE INDEX IF NOT EXISTS index_tmdb_identity_content_type ON tmdb_identity(content_type)")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_tmdb_identity_canonical_provider_id ON tmdb_identity(canonical_provider_id)")+ database.execSQL(+ """+ INSERT OR REPLACE INTO tmdb_identity (tmdb_id, content_type, canonical_provider_id, first_seen_at)+ SELECT tmdb_id, 'MOVIE', MIN(provider_id), 0+ FROM movies+ WHERE tmdb_id IS NOT NULL+ GROUP BY tmdb_id+ """.trimIndent()+ )+ database.execSQL(+ """+ INSERT OR REPLACE INTO tmdb_identity (tmdb_id, content_type, canonical_provider_id, first_seen_at)+ SELECT tmdb_id, 'SERIES', MIN(provider_id), 0+ FROM series+ WHERE tmdb_id IS NOT NULL+ GROUP BY tmdb_id+ """.trimIndent()+ )+ validateForeignKeys(database)+ }+ }}}diff --git a/data/src/main/java/com/streamvault/data/local/dao/CatalogSyncDao.kt b/data/src/main/java/com/streamvault/data/local/dao/CatalogSyncDao.ktindex 5fcb70da..507178d2 100644--- a/data/src/main/java/com/streamvault/data/local/dao/CatalogSyncDao.kt+++ b/data/src/main/java/com/streamvault/data/local/dao/CatalogSyncDao.kt@@ -47,6 +47,18 @@ interface CatalogSyncDao {@Query("DELETE FROM category_import_stage WHERE provider_id = :providerId")suspend fun clearProviderCategoryStages(providerId: Long)+ @Query("SELECT * FROM category_import_stage WHERE provider_id = :providerId AND session_id = :sessionId AND type = :type")+ suspend fun getCategoryStages(providerId: Long, sessionId: Long, type: String): List<CategoryImportStageEntity>++ @Query("SELECT * FROM channel_import_stage WHERE provider_id = :providerId AND session_id = :sessionId")+ suspend fun getChannelStages(providerId: Long, sessionId: Long): List<ChannelImportStageEntity>++ @Query("SELECT * FROM movie_import_stage WHERE provider_id = :providerId AND session_id = :sessionId")+ suspend fun getMovieStages(providerId: Long, sessionId: Long): List<MovieImportStageEntity>++ @Query("SELECT * FROM series_import_stage WHERE provider_id = :providerId AND session_id = :sessionId")+ suspend fun getSeriesStages(providerId: Long, sessionId: Long): List<SeriesImportStageEntity>+@Query("""UPDATE categories@@ -523,7 +535,8 @@ interface CatalogSyncDao {last_watched_at,is_adult,is_user_protected,- sync_fingerprint+ sync_fingerprint,+ added_at)SELECTstage.stream_id,@@ -550,7 +563,8 @@ interface CatalogSyncDao {0,stage.is_adult,0,- stage.sync_fingerprint+ stage.sync_fingerprint,+ stage.added_atFROM movie_import_stage AS stageWHERE stage.session_id = :sessionIdAND stage.provider_id = :providerIddiff --git a/data/src/main/java/com/streamvault/data/local/dao/Daos.kt b/data/src/main/java/com/streamvault/data/local/dao/Daos.ktindex b4ddeeb1..e238e0cb 100644--- a/data/src/main/java/com/streamvault/data/local/dao/Daos.kt+++ b/data/src/main/java/com/streamvault/data/local/dao/Daos.kt@@ -9,11 +9,18 @@ data class RemoteIdMapping(@ColumnInfo(name = "remote_id") val remoteId: Long)+data class TmdbIdMapping(+ @ColumnInfo(name = "tmdb_id") val tmdbId: Long+)+@Daoabstract class ProviderDao {@Query("SELECT * FROM providers ORDER BY created_at DESC")abstract fun getAll(): Flow<List<ProviderEntity>>+ @Query("SELECT * FROM providers ORDER BY created_at DESC")+ abstract suspend fun getAllSync(): List<ProviderEntity>+@Query("SELECT * FROM providers WHERE is_active = 1 LIMIT 1")abstract fun getActive(): Flow<ProviderEntity?>@@ -56,7 +63,7 @@ abstract class ProviderDao {}@Dao-interface ChannelDao {+abstract class ChannelDao {@Query("""SELECT id, stream_id, name, logo_url, group_title, category_id, category_name, stream_url,@@ -67,7 +74,7 @@ interface ChannelDao {ORDER BY number ASC""")- fun getByProvider(providerId: Long): Flow<List<ChannelBrowseEntity>>+ abstract fun getByProvider(providerId: Long): Flow<List<ChannelBrowseEntity>>@Query("""@@ -79,10 +86,36 @@ interface ChannelDao {ORDER BY number ASC""")- fun getByProviderWithoutErrors(providerId: Long): Flow<List<ChannelBrowseEntity>>+ abstract fun getByProviderWithoutErrors(providerId: Long): Flow<List<ChannelBrowseEntity>>++ @Query(+ """+ SELECT id, stream_id, name, logo_url, group_title, category_id, category_name, stream_url,+ epg_channel_id, number, catch_up_supported, catch_up_days, catchUpSource,+ provider_id, is_adult, is_user_protected, logical_group_id, error_count+ FROM channels+ WHERE provider_id = :providerId+ ORDER BY number ASC+ LIMIT :limit+ """+ )+ abstract fun getByProviderBrowsePage(providerId: Long, limit: Int): Flow<List<ChannelBrowseEntity>>++ @Query(+ """+ SELECT id, stream_id, name, logo_url, group_title, category_id, category_name, stream_url,+ epg_channel_id, number, catch_up_supported, catch_up_days, catchUpSource,+ provider_id, is_adult, is_user_protected, logical_group_id, error_count+ FROM channels+ WHERE provider_id = :providerId AND category_id = :categoryId+ ORDER BY number ASC+ LIMIT :limit+ """+ )+ abstract fun getByCategoryBrowsePage(providerId: Long, categoryId: Long, limit: Int): Flow<List<ChannelBrowseEntity>>@Query("SELECT * FROM channels WHERE provider_id = :providerId ORDER BY number ASC LIMIT :limit OFFSET :offset")- fun getByProviderPage(providerId: Long, limit: Int, offset: Int): Flow<List<ChannelEntity>>+ abstract fun getByProviderPage(providerId: Long, limit: Int, offset: Int): Flow<List<ChannelEntity>>@Query("""@@ -94,7 +127,7 @@ interface ChannelDao {ORDER BY number ASC""")- fun getByCategory(providerId: Long, categoryId: Long): Flow<List<ChannelBrowseEntity>>+ abstract fun getByCategory(providerId: Long, categoryId: Long): Flow<List<ChannelBrowseEntity>>@Query("""@@ -106,10 +139,10 @@ interface ChannelDao {ORDER BY number ASC""")- fun getByCategoryWithoutErrors(providerId: Long, categoryId: Long): Flow<List<ChannelBrowseEntity>>+ abstract fun getByCategoryWithoutErrors(providerId: Long, categoryId: Long): Flow<List<ChannelBrowseEntity>>@Query("SELECT * FROM channels WHERE provider_id = :providerId AND category_id = :categoryId ORDER BY number ASC LIMIT :limit OFFSET :offset")- fun getByCategoryPage(providerId: Long, categoryId: Long, limit: Int, offset: Int): Flow<List<ChannelEntity>>+ abstract fun getByCategoryPage(providerId: Long, categoryId: Long, limit: Int, offset: Int): Flow<List<ChannelEntity>>@Query("""@@ -124,7 +157,7 @@ interface ChannelDao {LIMIT :limit""")- fun search(providerId: Long, query: String, limit: Int): Flow<List<ChannelBrowseEntity>>+ abstract fun search(providerId: Long, query: String, limit: Int): Flow<List<ChannelBrowseEntity>>@Query("""@@ -140,28 +173,31 @@ interface ChannelDao {LIMIT :limit""")- fun searchByCategory(providerId: Long, categoryId: Long, query: String, limit: Int): Flow<List<ChannelBrowseEntity>>+ abstract fun searchByCategory(providerId: Long, categoryId: Long, query: String, limit: Int): Flow<List<ChannelBrowseEntity>>@Query("SELECT * FROM channels WHERE id = :id")- suspend fun getById(id: Long): ChannelEntity?+ abstract suspend fun getById(id: Long): ChannelEntity?@Query("SELECT * FROM channels WHERE provider_id = :providerId")- suspend fun getByProviderSync(providerId: Long): List<ChannelEntity>+ abstract suspend fun getByProviderSync(providerId: Long): List<ChannelEntity>@Insert(onConflict = OnConflictStrategy.REPLACE)- suspend fun insertAll(channels: List<ChannelEntity>)+ abstract suspend fun insertAll(channels: List<ChannelEntity>)++ @Update+ abstract suspend fun updateAll(channels: List<ChannelEntity>)@Query("SELECT id, stream_id AS remote_id FROM channels WHERE provider_id = :providerId")- suspend fun getIdMappings(providerId: Long): List<RemoteIdMapping>+ abstract suspend fun getIdMappings(providerId: Long): List<RemoteIdMapping>@Query("DELETE FROM channels WHERE provider_id = :providerId")- suspend fun deleteByProvider(providerId: Long)+ abstract suspend fun deleteByProvider(providerId: Long)@Query("DELETE FROM channels WHERE id IN (:ids)")- suspend fun deleteByIds(ids: List<Long>)+ abstract suspend fun deleteByIds(ids: List<Long>)@Transaction- suspend fun replaceAll(providerId: Long, channels: List<ChannelEntity>) {+ open suspend fun replaceAll(providerId: Long, channels: List<ChannelEntity>) {val existingByRemoteId = getIdMappings(providerId).associate { it.remoteId to it.id }val remapped = channels.distinctBy { it.streamId }@@ -179,10 +215,10 @@ interface ChannelDao {WHERE id IN (:ids)""")- fun getByIds(ids: List<Long>): Flow<List<ChannelBrowseEntity>>+ abstract fun getByIds(ids: List<Long>): Flow<List<ChannelBrowseEntity>>@Query("SELECT category_id, COUNT(*) as item_count FROM channels WHERE provider_id = :providerId AND category_id IS NOT NULL GROUP BY category_id")- fun getCategoryCounts(providerId: Long): Flow<List<CategoryCount>>+ abstract fun getCategoryCounts(providerId: Long): Flow<List<CategoryCount>>@Query("""@@ -200,19 +236,25 @@ interface ChannelDao {GROUP BY category_id""")- fun getGroupedCategoryCounts(providerId: Long): Flow<List<CategoryCount>>+ abstract fun getGroupedCategoryCounts(providerId: Long): Flow<List<CategoryCount>>@Query("SELECT COUNT(*) FROM channels WHERE provider_id = :providerId")- fun getCount(providerId: Long): Flow<Int>+ abstract fun getCount(providerId: Long): Flow<Int>++ @Query("SELECT COALESCE(MAX(catch_up_days), 0) FROM channels WHERE catch_up_supported = 1")+ abstract suspend fun getMaxCatchUpDaysAcrossAllProviders(): Int@Query("UPDATE channels SET is_user_protected = :isProtected WHERE provider_id = :providerId AND category_id = :categoryId")- suspend fun updateProtectionStatus(providerId: Long, categoryId: Long, isProtected: Boolean)+ abstract suspend fun updateProtectionStatus(providerId: Long, categoryId: Long, isProtected: Boolean)++ @Query("UPDATE channels SET is_user_protected = 0 WHERE provider_id = :providerId AND category_id IN (:categoryIds)")+ abstract suspend fun clearProtectionForCategories(providerId: Long, categoryIds: List<Long>)@Query("UPDATE channels SET error_count = error_count + 1 WHERE id = :id")- suspend fun incrementErrorCount(id: Long)+ abstract suspend fun incrementErrorCount(id: Long)@Query("UPDATE channels SET error_count = 0 WHERE id = :id")- suspend fun resetErrorCount(id: Long)+ abstract suspend fun resetErrorCount(id: Long)}@Dao@@ -227,6 +269,36 @@ interface ChannelPreferenceDao {suspend fun deleteAll()}+@Dao+interface TmdbIdentityDao {+ @Insert(onConflict = OnConflictStrategy.REPLACE)+ suspend fun upsertAll(identities: List<TmdbIdentityEntity>)++ @Query(+ """+ DELETE FROM tmdb_identity+ WHERE content_type = 'MOVIE'+ AND NOT EXISTS (+ SELECT 1 FROM movies+ WHERE movies.tmdb_id = tmdb_identity.tmdb_id+ )+ """+ )+ suspend fun pruneOrphanedMovieIdentities()++ @Query(+ """+ DELETE FROM tmdb_identity+ WHERE content_type = 'SERIES'+ AND NOT EXISTS (+ SELECT 1 FROM series+ WHERE series.tmdb_id = tmdb_identity.tmdb_id+ )+ """+ )+ suspend fun pruneOrphanedSeriesIdentities()+}+@Dao@RewriteQueriesToDropUnusedColumnsinterface MovieDao {@@ -240,6 +312,20 @@ interface MovieDao {@Query("SELECT * FROM movies WHERE provider_id = :providerId ORDER BY name ASC LIMIT :limit OFFSET :offset")fun getByProviderPage(providerId: Long, limit: Int, offset: Int): Flow<List<MovieBrowseEntity>>+ @Query("SELECT * FROM movies WHERE provider_id = :providerId ORDER BY name ASC, id ASC LIMIT :limit")+ suspend fun getByProviderCursorPage(providerId: Long, limit: Int): List<MovieBrowseEntity>++ @Query(+ """+ SELECT * FROM movies+ WHERE provider_id = :providerId+ AND (name > :lastName OR (name = :lastName AND id > :lastId))+ ORDER BY name ASC, id ASC+ LIMIT :limit+ """+ )+ suspend fun getByProviderCursorPageAfter(providerId: Long, lastName: String, lastId: Long, limit: Int): List<MovieBrowseEntity>+@Query("""SELECT movies.* FROM movies@@ -247,6 +333,7 @@ interface MovieDao {AND EXISTS (SELECT 1 FROM favoritesWHERE favorites.content_type = 'MOVIE'+ AND favorites.provider_id = movies.provider_idAND favorites.group_id IS NULLAND favorites.content_id = movies.id)@@ -264,6 +351,7 @@ interface MovieDao {AND EXISTS (SELECT 1 FROM favoritesWHERE favorites.content_type = 'MOVIE'+ AND favorites.provider_id = movies.provider_idAND favorites.group_id IS NULLAND favorites.content_id = movies.id)@@ -316,36 +404,102 @@ interface MovieDao {"""SELECT movies.* FROM moviesWHERE movies.provider_id = :providerId- AND COALESCE(movies.watch_progress, 0) <= 0+ AND NOT EXISTS (+ SELECT 1 FROM playback_history+ WHERE playback_history.provider_id = movies.provider_id+ AND playback_history.content_type = 'MOVIE'+ AND playback_history.content_id = movies.id+ AND playback_history.resume_position_ms > 0+ )ORDER BY movies.name ASCLIMIT :limit OFFSET :offset""")fun getUnwatchedByProviderPage(providerId: Long, limit: Int, offset: Int): Flow<List<MovieBrowseEntity>>- @Query("SELECT COUNT(*) FROM movies WHERE provider_id = :providerId AND COALESCE(watch_progress, 0) <= 0")+ @Query(+ """+ SELECT COUNT(*)+ FROM movies+ WHERE movies.provider_id = :providerId+ AND NOT EXISTS (+ SELECT 1 FROM playback_history+ WHERE playback_history.provider_id = movies.provider_id+ AND playback_history.content_type = 'MOVIE'+ AND playback_history.content_id = movies.id+ AND playback_history.resume_position_ms > 0+ )+ """+ )fun getUnwatchedCountByProvider(providerId: Long): Flow<Int>@Query("""SELECT movies.* FROM moviesWHERE movies.provider_id = :providerId- ORDER BY COALESCE((- SELECT playback_history.watch_count- FROM playback_history- WHERE playback_history.provider_id = movies.provider_id- AND playback_history.content_type = 'MOVIE'- AND playback_history.content_id = movies.id- LIMIT 1- ), 0) DESC, movies.name ASC+ ORDER BY COALESCE(movies.watch_count, 0) DESC, movies.name ASCLIMIT :limit OFFSET :offset""")fun getByWatchCountProviderPage(providerId: Long, limit: Int, offset: Int): Flow<List<MovieBrowseEntity>>+ @Query(+ """+ SELECT movies.* FROM movies+ WHERE movies.provider_id = :providerId+ ORDER BY COALESCE(movies.watch_count, 0) DESC, movies.name ASC, movies.id ASC+ LIMIT :limit+ """+ )+ suspend fun getByWatchCountProviderCursorPage(providerId: Long, limit: Int): List<MovieBrowseEntity>++ @Query(+ """+ SELECT movies.* FROM movies+ WHERE movies.provider_id = :providerId+ AND (+ COALESCE(movies.watch_count, 0) < :lastWatchCount+ OR (+ COALESCE(movies.watch_count, 0) = :lastWatchCount+ AND (movies.name > :lastName OR (movies.name = :lastName AND movies.id > :lastId))+ )+ )+ ORDER BY COALESCE(movies.watch_count, 0) DESC, movies.name ASC, movies.id ASC+ LIMIT :limit+ """+ )+ suspend fun getByWatchCountProviderCursorPageAfter(+ providerId: Long,+ lastWatchCount: Int,+ lastName: String,+ lastId: Long,+ limit: Int+ ): List<MovieBrowseEntity>+@Query("SELECT * FROM movies WHERE provider_id = :providerId AND category_id = :categoryId ORDER BY name ASC")fun getByCategory(providerId: Long, categoryId: Long): Flow<List<MovieBrowseEntity>>+ @Query("SELECT * FROM movies WHERE provider_id = :providerId AND category_id = :categoryId ORDER BY name ASC, id ASC LIMIT :limit")+ suspend fun getByCategoryCursorPage(providerId: Long, categoryId: Long, limit: Int): List<MovieBrowseEntity>++ @Query(+ """+ SELECT * FROM movies+ WHERE provider_id = :providerId+ AND category_id = :categoryId+ AND (name > :lastName OR (name = :lastName AND id > :lastId))+ ORDER BY name ASC, id ASC+ LIMIT :limit+ """+ )+ suspend fun getByCategoryCursorPageAfter(+ providerId: Long,+ categoryId: Long,+ lastName: String,+ lastId: Long,+ limit: Int+ ): List<MovieBrowseEntity>+@Query("""SELECT movies.* FROM movies@@ -354,6 +508,7 @@ interface MovieDao {AND EXISTS (SELECT 1 FROM favoritesWHERE favorites.content_type = 'MOVIE'+ AND favorites.provider_id = movies.provider_idAND favorites.group_id IS NULLAND favorites.content_id = movies.id)@@ -372,6 +527,7 @@ interface MovieDao {AND EXISTS (SELECT 1 FROM favoritesWHERE favorites.content_type = 'MOVIE'+ AND favorites.provider_id = movies.provider_idAND favorites.group_id IS NULLAND favorites.content_id = movies.id)@@ -427,7 +583,13 @@ interface MovieDao {SELECT movies.* FROM moviesWHERE movies.provider_id = :providerIdAND movies.category_id = :categoryId- AND COALESCE(movies.watch_progress, 0) <= 0+ AND NOT EXISTS (+ SELECT 1 FROM playback_history+ WHERE playback_history.provider_id = movies.provider_id+ AND playback_history.content_type = 'MOVIE'+ AND playback_history.content_id = movies.id+ AND playback_history.resume_position_ms > 0+ )ORDER BY movies.name ASCLIMIT :limit OFFSET :offset"""@@ -435,7 +597,19 @@ interface MovieDao {fun getUnwatchedByCategoryPage(providerId: Long, categoryId: Long, limit: Int, offset: Int): Flow<List<MovieBrowseEntity>>@Query(- "SELECT COUNT(*) FROM movies WHERE provider_id = :providerId AND category_id = :categoryId AND COALESCE(watch_progress, 0) <= 0"+ """+ SELECT COUNT(*)+ FROM movies+ WHERE movies.provider_id = :providerId+ AND movies.category_id = :categoryId+ AND NOT EXISTS (+ SELECT 1 FROM playback_history+ WHERE playback_history.provider_id = movies.provider_id+ AND playback_history.content_type = 'MOVIE'+ AND playback_history.content_id = movies.id+ AND playback_history.resume_position_ms > 0+ )+ """)fun getUnwatchedCountByCategory(providerId: Long, categoryId: Long): Flow<Int>@@ -444,19 +618,48 @@ interface MovieDao {SELECT movies.* FROM moviesWHERE movies.provider_id = :providerIdAND movies.category_id = :categoryId- ORDER BY COALESCE((- SELECT playback_history.watch_count- FROM playback_history- WHERE playback_history.provider_id = movies.provider_id- AND playback_history.content_type = 'MOVIE'- AND playback_history.content_id = movies.id- LIMIT 1- ), 0) DESC, movies.name ASC+ ORDER BY COALESCE(movies.watch_count, 0) DESC, movies.name ASCLIMIT :limit OFFSET :offset""")fun getByWatchCountCategoryPage(providerId: Long, categoryId: Long, limit: Int, offset: Int): Flow<List<MovieBrowseEntity>>+ @Query(+ """+ SELECT movies.* FROM movies+ WHERE movies.provider_id = :providerId+ AND movies.category_id = :categoryId+ ORDER BY COALESCE(movies.watch_count, 0) DESC, movies.name ASC, movies.id ASC+ LIMIT :limit+ """+ )+ suspend fun getByWatchCountCategoryCursorPage(providerId: Long, categoryId: Long, limit: Int): List<MovieBrowseEntity>++ @Query(+ """+ SELECT movies.* FROM movies+ WHERE movies.provider_id = :providerId+ AND movies.category_id = :categoryId+ AND (+ COALESCE(movies.watch_count, 0) < :lastWatchCount+ OR (+ COALESCE(movies.watch_count, 0) = :lastWatchCount+ AND (movies.name > :lastName OR (movies.name = :lastName AND movies.id > :lastId))+ )+ )+ ORDER BY COALESCE(movies.watch_count, 0) DESC, movies.name ASC, movies.id ASC+ LIMIT :limit+ """+ )+ suspend fun getByWatchCountCategoryCursorPageAfter(+ providerId: Long,+ categoryId: Long,+ lastWatchCount: Int,+ lastName: String,+ lastId: Long,+ limit: Int+ ): List<MovieBrowseEntity>+/** SQL-level parental filter per category. */@Query("SELECT * FROM movies WHERE provider_id = :providerId AND category_id = :categoryId AND is_user_protected = 0 ORDER BY name ASC")fun getByCategoryUnprotected(providerId: Long, categoryId: Long): Flow<List<MovieBrowseEntity>>@@ -470,15 +673,131 @@ interface MovieDao {@Query("SELECT * FROM movies WHERE provider_id = :providerId ORDER BY rating DESC, name ASC LIMIT :limit")fun getTopRatedPreview(providerId: Long, limit: Int): Flow<List<MovieBrowseEntity>>+ @Query("SELECT * FROM movies WHERE provider_id = :providerId ORDER BY rating DESC, name ASC, id ASC LIMIT :limit")+ suspend fun getTopRatedCursorPage(providerId: Long, limit: Int): List<MovieBrowseEntity>++ @Query(+ """+ SELECT * FROM movies+ WHERE provider_id = :providerId+ AND (+ rating < :lastRating+ OR (rating = :lastRating AND (name > :lastName OR (name = :lastName AND id > :lastId)))+ )+ ORDER BY rating DESC, name ASC, id ASC+ LIMIT :limit+ """+ )+ suspend fun getTopRatedCursorPageAfter(+ providerId: Long,+ lastRating: Float,+ lastName: String,+ lastId: Long,+ limit: Int+ ): List<MovieBrowseEntity>+@Query("SELECT * FROM movies WHERE provider_id = :providerId AND category_id = :categoryId ORDER BY rating DESC, name ASC LIMIT :limit")fun getTopRatedByCategoryPreview(providerId: Long, categoryId: Long, limit: Int): Flow<List<MovieBrowseEntity>>- @Query("SELECT * FROM movies WHERE provider_id = :providerId ORDER BY release_date DESC, name ASC LIMIT :limit")+ @Query("SELECT * FROM movies WHERE provider_id = :providerId AND category_id = :categoryId ORDER BY rating DESC, name ASC, id ASC LIMIT :limit")+ suspend fun getTopRatedByCategoryCursorPage(providerId: Long, categoryId: Long, limit: Int): List<MovieBrowseEntity>++ @Query(+ """+ SELECT * FROM movies+ WHERE provider_id = :providerId+ AND category_id = :categoryId+ AND (+ rating < :lastRating+ OR (rating = :lastRating AND (name > :lastName OR (name = :lastName AND id > :lastId)))+ )+ ORDER BY rating DESC, name ASC, id ASC+ LIMIT :limit+ """+ )+ suspend fun getTopRatedByCategoryCursorPageAfter(+ providerId: Long,+ categoryId: Long,+ lastRating: Float,+ lastName: String,+ lastId: Long,+ limit: Int+ ): List<MovieBrowseEntity>++ @Query("SELECT * FROM movies WHERE provider_id = :providerId ORDER BY added_at DESC, release_date DESC, name ASC LIMIT :limit")fun getFreshPreview(providerId: Long, limit: Int): Flow<List<MovieBrowseEntity>>- @Query("SELECT * FROM movies WHERE provider_id = :providerId AND category_id = :categoryId ORDER BY release_date DESC, name ASC LIMIT :limit")+ @Query("SELECT * FROM movies WHERE provider_id = :providerId ORDER BY added_at DESC, release_date DESC, name ASC, id ASC LIMIT :limit")+ suspend fun getFreshCursorPage(providerId: Long, limit: Int): List<MovieBrowseEntity>++ @Query(+ """+ SELECT * FROM movies+ WHERE provider_id = :providerId+ AND (+ added_at < :lastAddedAt+ OR (+ added_at = :lastAddedAt+ AND (+ COALESCE(release_date, '') < :lastReleaseDate+ OR (+ COALESCE(release_date, '') = :lastReleaseDate+ AND (name > :lastName OR (name = :lastName AND id > :lastId))+ )+ )+ )+ )+ ORDER BY added_at DESC, release_date DESC, name ASC, id ASC+ LIMIT :limit+ """+ )+ suspend fun getFreshCursorPageAfter(+ providerId: Long,+ lastAddedAt: Long,+ lastReleaseDate: String,+ lastName: String,+ lastId: Long,+ limit: Int+ ): List<MovieBrowseEntity>++ @Query("SELECT * FROM movies WHERE provider_id = :providerId AND category_id = :categoryId ORDER BY added_at DESC, release_date DESC, name ASC LIMIT :limit")fun getFreshByCategoryPreview(providerId: Long, categoryId: Long, limit: Int): Flow<List<MovieBrowseEntity>>+ @Query("SELECT * FROM movies WHERE provider_id = :providerId AND category_id = :categoryId ORDER BY added_at DESC, release_date DESC, name ASC, id ASC LIMIT :limit")+ suspend fun getFreshByCategoryCursorPage(providerId: Long, categoryId: Long, limit: Int): List<MovieBrowseEntity>++ @Query(+ """+ SELECT * FROM movies+ WHERE provider_id = :providerId+ AND category_id = :categoryId+ AND (+ added_at < :lastAddedAt+ OR (+ added_at = :lastAddedAt+ AND (+ COALESCE(release_date, '') < :lastReleaseDate+ OR (+ COALESCE(release_date, '') = :lastReleaseDate+ AND (name > :lastName OR (name = :lastName AND id > :lastId))+ )+ )+ )+ )+ ORDER BY added_at DESC, release_date DESC, name ASC, id ASC+ LIMIT :limit+ """+ )+ suspend fun getFreshByCategoryCursorPageAfter(+ providerId: Long,+ categoryId: Long,+ lastAddedAt: Long,+ lastReleaseDate: String,+ lastName: String,+ lastId: Long,+ limit: Int+ ): List<MovieBrowseEntity>+@Query("""SELECT m.* FROM movies m@@ -510,6 +829,9 @@ interface MovieDao {@Query("SELECT * FROM movies WHERE provider_id = :providerId")suspend fun getByProviderSync(providerId: Long): List<MovieEntity>+ @Query("SELECT tmdb_id FROM movies WHERE provider_id = :providerId AND tmdb_id IS NOT NULL")+ suspend fun getTmdbIdsByProvider(providerId: Long): List<TmdbIdMapping>+@Query("SELECT * FROM movies WHERE id IN (:ids)")fun getByIds(ids: List<Long>): Flow<List<MovieBrowseEntity>>@@ -528,6 +850,9 @@ interface MovieDao {@Updatesuspend fun update(movie: MovieEntity)+ @Update+ suspend fun updateAll(movies: List<MovieEntity>)+@Query("UPDATE movies SET watch_progress = :progress, last_watched_at = :timestamp WHERE id = :id")suspend fun updateWatchProgress(id: Long, progress: Long, timestamp: Long = System.currentTimeMillis())@@ -540,6 +865,12 @@ interface MovieDao {AND playback_history.content_type = 'MOVIE'AND playback_history.provider_id = movies.provider_id), 0),+ watch_count = COALESCE((+ SELECT watch_count FROM playback_history+ WHERE playback_history.content_id = movies.id+ AND playback_history.content_type = 'MOVIE'+ AND playback_history.provider_id = movies.provider_id+ ), 0),last_watched_at = COALESCE((SELECT last_watched_at FROM playback_historyWHERE playback_history.content_id = movies.id@@ -560,6 +891,12 @@ interface MovieDao {AND playback_history.content_type = 'MOVIE'AND playback_history.provider_id = movies.provider_id), 0),+ watch_count = COALESCE((+ SELECT watch_count FROM playback_history+ WHERE playback_history.content_id = movies.id+ AND playback_history.content_type = 'MOVIE'+ AND playback_history.provider_id = movies.provider_id+ ), 0),last_watched_at = COALESCE((SELECT last_watched_at FROM playback_historyWHERE playback_history.content_id = movies.id@@ -580,6 +917,12 @@ interface MovieDao {AND playback_history.content_type = 'MOVIE'AND playback_history.provider_id = movies.provider_id), 0),+ watch_count = COALESCE((+ SELECT watch_count FROM playback_history+ WHERE playback_history.content_id = movies.id+ AND playback_history.content_type = 'MOVIE'+ AND playback_history.provider_id = movies.provider_id+ ), 0),last_watched_at = COALESCE((SELECT last_watched_at FROM playback_historyWHERE playback_history.content_id = movies.id@@ -590,6 +933,9 @@ interface MovieDao {)suspend fun syncAllWatchProgressFromHistory()+ @Query("UPDATE movies SET watch_progress = 0, watch_count = 0, last_watched_at = 0")+ suspend fun resetAllWatchProgress()+@Query("DELETE FROM movies WHERE provider_id = :providerId")suspend fun deleteByProvider(providerId: Long)@@ -609,7 +955,19 @@ interface MovieDao {WHERE playback_history.content_id = movies.idAND playback_history.content_type = 'MOVIE'AND playback_history.provider_id = :providerId- )+ ),+ watch_count = COALESCE((+ SELECT watch_count FROM playback_history+ WHERE playback_history.content_id = movies.id+ AND playback_history.content_type = 'MOVIE'+ AND playback_history.provider_id = :providerId+ ), 0),+ last_watched_at = COALESCE((+ SELECT last_watched_at FROM playback_history+ WHERE playback_history.content_id = movies.id+ AND playback_history.content_type = 'MOVIE'+ AND playback_history.provider_id = :providerId+ ), 0)WHERE provider_id = :providerId AND EXISTS (SELECT 1 FROM playback_historyWHERE playback_history.content_id = movies.id@@ -658,6 +1016,9 @@ interface MovieDao {@Query("UPDATE movies SET is_user_protected = :isProtected WHERE provider_id = :providerId AND category_id = :categoryId")suspend fun updateProtectionStatus(providerId: Long, categoryId: Long, isProtected: Boolean)++ @Query("UPDATE movies SET is_user_protected = 0 WHERE provider_id = :providerId AND category_id IN (:categoryIds)")+ suspend fun clearProtectionForCategories(providerId: Long, categoryIds: List<Long>)}@Dao@@ -669,6 +1030,20 @@ interface SeriesDao {@Query("SELECT * FROM series WHERE provider_id = :providerId ORDER BY name ASC LIMIT :limit OFFSET :offset")fun getByProviderPage(providerId: Long, limit: Int, offset: Int): Flow<List<SeriesBrowseEntity>>+ @Query("SELECT * FROM series WHERE provider_id = :providerId ORDER BY name ASC, id ASC LIMIT :limit")+ suspend fun getByProviderCursorPage(providerId: Long, limit: Int): List<SeriesBrowseEntity>++ @Query(+ """+ SELECT * FROM series+ WHERE provider_id = :providerId+ AND (name > :lastName OR (name = :lastName AND id > :lastId))+ ORDER BY name ASC, id ASC+ LIMIT :limit+ """+ )+ suspend fun getByProviderCursorPageAfter(providerId: Long, lastName: String, lastId: Long, limit: Int): List<SeriesBrowseEntity>+@Query("""SELECT series.* FROM series@@ -676,6 +1051,7 @@ interface SeriesDao {AND EXISTS (SELECT 1 FROM favoritesWHERE favorites.content_type = 'SERIES'+ AND favorites.provider_id = series.provider_idAND favorites.group_id IS NULLAND favorites.content_id = series.id)@@ -693,6 +1069,7 @@ interface SeriesDao {AND EXISTS (SELECT 1 FROM favoritesWHERE favorites.content_type = 'SERIES'+ AND favorites.provider_id = series.provider_idAND favorites.group_id IS NULLAND favorites.content_id = series.id)@@ -833,6 +1210,99 @@ interface SeriesDao {)fun getByWatchCountProviderPage(providerId: Long, limit: Int, offset: Int): Flow<List<SeriesBrowseEntity>>+ @Query(+ """+ SELECT series.* FROM series+ WHERE series.provider_id = :providerId+ ORDER BY COALESCE((+ SELECT MAX(playback_history.watch_count)+ FROM playback_history+ WHERE playback_history.provider_id = series.provider_id+ AND (+ (playback_history.content_type = 'SERIES' AND playback_history.content_id = series.id)+ OR (+ playback_history.content_type = 'SERIES_EPISODE'+ AND EXISTS (+ SELECT 1 FROM episodes+ WHERE episodes.id = playback_history.content_id+ AND episodes.series_id = series.id+ )+ )+ )+ ), 0) DESC, series.name ASC, series.id ASC+ LIMIT :limit+ """+ )+ suspend fun getByWatchCountProviderCursorPage(providerId: Long, limit: Int): List<SeriesBrowseEntity>++ @Query(+ """+ SELECT series.* FROM series+ WHERE series.provider_id = :providerId+ AND (+ COALESCE((+ SELECT MAX(playback_history.watch_count)+ FROM playback_history+ WHERE playback_history.provider_id = series.provider_id+ AND (+ (playback_history.content_type = 'SERIES' AND playback_history.content_id = series.id)+ OR (+ playback_history.content_type = 'SERIES_EPISODE'+ AND EXISTS (+ SELECT 1 FROM episodes+ WHERE episodes.id = playback_history.content_id+ AND episodes.series_id = series.id+ )+ )+ )+ ), 0) < :lastWatchCount+ OR (+ COALESCE((+ SELECT MAX(playback_history.watch_count)+ FROM playback_history+ WHERE playback_history.provider_id = series.provider_id+ AND (+ (playback_history.content_type = 'SERIES' AND playback_history.content_id = series.id)+ OR (+ playback_history.content_type = 'SERIES_EPISODE'+ AND EXISTS (+ SELECT 1 FROM episodes+ WHERE episodes.id = playback_history.content_id+ AND episodes.series_id = series.id+ )+ )+ )+ ), 0) = :lastWatchCount+ AND (series.name > :lastName OR (series.name = :lastName AND series.id > :lastId))+ )+ )+ ORDER BY COALESCE((+ SELECT MAX(playback_history.watch_count)+ FROM playback_history+ WHERE playback_history.provider_id = series.provider_id+ AND (+ (playback_history.content_type = 'SERIES' AND playback_history.content_id = series.id)+ OR (+ playback_history.content_type = 'SERIES_EPISODE'+ AND EXISTS (+ SELECT 1 FROM episodes+ WHERE episodes.id = playback_history.content_id+ AND episodes.series_id = series.id+ )+ )+ )+ ), 0) DESC, series.name ASC, series.id ASC+ LIMIT :limit+ """+ )+ suspend fun getByWatchCountProviderCursorPageAfter(+ providerId: Long,+ lastWatchCount: Int,+ lastName: String,+ lastId: Long,+ limit: Int+ ): List<SeriesBrowseEntity>+@Query("SELECT * FROM series WHERE provider_id = :providerId AND category_id = :categoryId ORDER BY name ASC")fun getByCategory(providerId: Long, categoryId: Long): Flow<List<SeriesBrowseEntity>>@@ -844,6 +1314,7 @@ interface SeriesDao {AND EXISTS (SELECT 1 FROM favoritesWHERE favorites.content_type = 'SERIES'+ AND favorites.provider_id = series.provider_idAND favorites.group_id IS NULLAND favorites.content_id = series.id)@@ -862,6 +1333,7 @@ interface SeriesDao {AND EXISTS (SELECT 1 FROM favoritesWHERE favorites.content_type = 'SERIES'+ AND favorites.provider_id = series.provider_idAND favorites.group_id IS NULLAND favorites.content_id = series.id)@@ -1010,21 +1482,138 @@ interface SeriesDao {@Query("SELECT * FROM series WHERE provider_id = :providerId AND category_id = :categoryId ORDER BY name ASC LIMIT :limit OFFSET :offset")fun getByCategoryPage(providerId: Long, categoryId: Long, limit: Int, offset: Int): Flow<List<SeriesBrowseEntity>>+ @Query("SELECT * FROM series WHERE provider_id = :providerId AND category_id = :categoryId ORDER BY name ASC, id ASC LIMIT :limit")+ suspend fun getByCategoryCursorPage(providerId: Long, categoryId: Long, limit: Int): List<SeriesBrowseEntity>++ @Query(+ """+ SELECT * FROM series+ WHERE provider_id = :providerId+ AND category_id = :categoryId+ AND (name > :lastName OR (name = :lastName AND id > :lastId))+ ORDER BY name ASC, id ASC+ LIMIT :limit+ """+ )+ suspend fun getByCategoryCursorPageAfter(+ providerId: Long,+ categoryId: Long,+ lastName: String,+ lastId: Long,+ limit: Int+ ): List<SeriesBrowseEntity>+@Query("SELECT * FROM series WHERE provider_id = :providerId AND category_id = :categoryId ORDER BY name ASC LIMIT :limit")fun getByCategoryPreview(providerId: Long, categoryId: Long, limit: Int): Flow<List<SeriesBrowseEntity>>@Query("SELECT * FROM series WHERE provider_id = :providerId ORDER BY rating DESC, name ASC LIMIT :limit")fun getTopRatedPreview(providerId: Long, limit: Int): Flow<List<SeriesBrowseEntity>>+ @Query("SELECT * FROM series WHERE provider_id = :providerId ORDER BY rating DESC, name ASC, id ASC LIMIT :limit")+ suspend fun getTopRatedCursorPage(providerId: Long, limit: Int): List<SeriesBrowseEntity>++ @Query(+ """+ SELECT * FROM series+ WHERE provider_id = :providerId+ AND (+ rating < :lastRating+ OR (rating = :lastRating AND (name > :lastName OR (name = :lastName AND id > :lastId)))+ )+ ORDER BY rating DESC, name ASC, id ASC+ LIMIT :limit+ """+ )+ suspend fun getTopRatedCursorPageAfter(+ providerId: Long,+ lastRating: Float,+ lastName: String,+ lastId: Long,+ limit: Int+ ): List<SeriesBrowseEntity>+@Query("SELECT * FROM series WHERE provider_id = :providerId AND category_id = :categoryId ORDER BY rating DESC, name ASC LIMIT :limit")fun getTopRatedByCategoryPreview(providerId: Long, categoryId: Long, limit: Int): Flow<List<SeriesBrowseEntity>>+ @Query("SELECT * FROM series WHERE provider_id = :providerId AND category_id = :categoryId ORDER BY rating DESC, name ASC, id ASC LIMIT :limit")+ suspend fun getTopRatedByCategoryCursorPage(providerId: Long, categoryId: Long, limit: Int): List<SeriesBrowseEntity>++ @Query(+ """+ SELECT * FROM series+ WHERE provider_id = :providerId+ AND category_id = :categoryId+ AND (+ rating < :lastRating+ OR (rating = :lastRating AND (name > :lastName OR (name = :lastName AND id > :lastId)))+ )+ ORDER BY rating DESC, name ASC, id ASC+ LIMIT :limit+ """+ )+ suspend fun getTopRatedByCategoryCursorPageAfter(+ providerId: Long,+ categoryId: Long,+ lastRating: Float,+ lastName: String,+ lastId: Long,+ limit: Int+ ): List<SeriesBrowseEntity>+@Query("SELECT * FROM series WHERE provider_id = :providerId ORDER BY last_modified DESC, name ASC LIMIT :limit")fun getFreshPreview(providerId: Long, limit: Int): Flow<List<SeriesBrowseEntity>>+ @Query("SELECT * FROM series WHERE provider_id = :providerId ORDER BY last_modified DESC, name ASC, id ASC LIMIT :limit")+ suspend fun getFreshCursorPage(providerId: Long, limit: Int): List<SeriesBrowseEntity>++ @Query(+ """+ SELECT * FROM series+ WHERE provider_id = :providerId+ AND (+ last_modified < :lastModified+ OR (last_modified = :lastModified AND (name > :lastName OR (name = :lastName AND id > :lastId)))+ )+ ORDER BY last_modified DESC, name ASC, id ASC+ LIMIT :limit+ """+ )+ suspend fun getFreshCursorPageAfter(+ providerId: Long,+ lastModified: Long,+ lastName: String,+ lastId: Long,+ limit: Int+ ): List<SeriesBrowseEntity>+@Query("SELECT * FROM series WHERE provider_id = :providerId AND category_id = :categoryId ORDER BY last_modified DESC, name ASC LIMIT :limit")fun getFreshByCategoryPreview(providerId: Long, categoryId: Long, limit: Int): Flow<List<SeriesBrowseEntity>>+ @Query("SELECT * FROM series WHERE provider_id = :providerId AND category_id = :categoryId ORDER BY last_modified DESC, name ASC, id ASC LIMIT :limit")+ suspend fun getFreshByCategoryCursorPage(providerId: Long, categoryId: Long, limit: Int): List<SeriesBrowseEntity>++ @Query(+ """+ SELECT * FROM series+ WHERE provider_id = :providerId+ AND category_id = :categoryId+ AND (+ last_modified < :lastModified+ OR (last_modified = :lastModified AND (name > :lastName OR (name = :lastName AND id > :lastId)))+ )+ ORDER BY last_modified DESC, name ASC, id ASC+ LIMIT :limit+ """+ )+ suspend fun getFreshByCategoryCursorPageAfter(+ providerId: Long,+ categoryId: Long,+ lastModified: Long,+ lastName: String,+ lastId: Long,+ limit: Int+ ): List<SeriesBrowseEntity>+@Query("""SELECT s.* FROM series s@@ -1056,6 +1645,9 @@ interface SeriesDao {@Query("SELECT * FROM series WHERE provider_id = :providerId")suspend fun getByProviderSync(providerId: Long): List<SeriesEntity>+ @Query("SELECT tmdb_id FROM series WHERE provider_id = :providerId AND tmdb_id IS NOT NULL")+ suspend fun getTmdbIdsByProvider(providerId: Long): List<TmdbIdMapping>+@Query("SELECT * FROM series WHERE id IN (:ids)")fun getByIds(ids: List<Long>): Flow<List<SeriesBrowseEntity>>@@ -1068,6 +1660,9 @@ interface SeriesDao {@Updatesuspend fun update(series: SeriesEntity)+ @Update+ suspend fun updateAll(series: List<SeriesEntity>)+@Query("SELECT id, series_id AS remote_id FROM series WHERE provider_id = :providerId")suspend fun getIdMappings(providerId: Long): List<RemoteIdMapping>@@ -1122,6 +1717,9 @@ interface SeriesDao {@Query("UPDATE series SET is_user_protected = :isProtected WHERE provider_id = :providerId AND category_id = :categoryId")suspend fun updateProtectionStatus(providerId: Long, categoryId: Long, isProtected: Boolean)++ @Query("UPDATE series SET is_user_protected = 0 WHERE provider_id = :providerId AND category_id IN (:categoryIds)")+ suspend fun clearProtectionForCategories(providerId: Long, categoryIds: List<Long>)}@@ -1226,6 +1824,9 @@ interface EpisodeDao {)suspend fun syncAllWatchProgressFromHistory()+ @Query("UPDATE episodes SET watch_progress = 0, last_watched_at = 0")+ suspend fun resetAllWatchProgress()+@Query("DELETE FROM episodes WHERE series_id = :seriesId")suspend fun deleteBySeries(seriesId: Long)@@ -1272,6 +1873,9 @@ interface CategoryDao {@Insert(onConflict = OnConflictStrategy.REPLACE)suspend fun insertAll(categories: List<CategoryEntity>)+ @Update+ suspend fun updateAll(categories: List<CategoryEntity>)+@Query("DELETE FROM categories WHERE provider_id = :providerId AND type = :type")suspend fun deleteByProviderAndType(providerId: Long, type: String)@@ -1571,32 +2175,38 @@ interface ProgramDao {@Daointerface FavoriteDao {- @Query("SELECT * FROM favorites WHERE group_id IS NULL ORDER BY position ASC")- fun getAllGlobal(): Flow<List<FavoriteEntity>>+ @Query("SELECT * FROM favorites WHERE provider_id = :providerId AND group_id IS NULL ORDER BY position ASC")+ fun getAllGlobal(providerId: Long): Flow<List<FavoriteEntity>>++ @Query("SELECT * FROM favorites WHERE provider_id IN (:providerIds) AND group_id IS NULL ORDER BY provider_id ASC, position ASC")+ fun getAllGlobalByProviders(providerIds: List<Long>): Flow<List<FavoriteEntity>>- @Query("SELECT * FROM favorites WHERE content_type = :contentType AND group_id IS NULL ORDER BY position ASC")- fun getGlobalByType(contentType: String): Flow<List<FavoriteEntity>>+ @Query("SELECT * FROM favorites WHERE provider_id = :providerId AND content_type = :contentType AND group_id IS NULL ORDER BY position ASC")+ fun getGlobalByType(providerId: Long, contentType: String): Flow<List<FavoriteEntity>>- @Query("SELECT * FROM favorites WHERE content_type = :contentType ORDER BY position ASC")- fun getAllByType(contentType: String): Flow<List<FavoriteEntity>>+ @Query("SELECT * FROM favorites WHERE provider_id IN (:providerIds) AND content_type = :contentType AND group_id IS NULL ORDER BY provider_id ASC, position ASC")+ fun getGlobalByTypeForProviders(providerIds: List<Long>, contentType: String): Flow<List<FavoriteEntity>>++ @Query("SELECT * FROM favorites WHERE provider_id = :providerId AND content_type = :contentType ORDER BY position ASC")+ fun getAllByType(providerId: Long, contentType: String): Flow<List<FavoriteEntity>>@Query("SELECT * FROM favorites WHERE group_id = :groupId ORDER BY position ASC")fun getByGroup(groupId: Long): Flow<List<FavoriteEntity>>- @Query("SELECT * FROM favorites WHERE content_id = :contentId AND content_type = :contentType AND (:groupId IS NULL AND group_id IS NULL OR group_id = :groupId) LIMIT 1")- suspend fun get(contentId: Long, contentType: String, groupId: Long?): FavoriteEntity?+ @Query("SELECT * FROM favorites WHERE provider_id = :providerId AND content_id = :contentId AND content_type = :contentType AND (:groupId IS NULL AND group_id IS NULL OR group_id = :groupId) LIMIT 1")+ suspend fun get(providerId: Long, contentId: Long, contentType: String, groupId: Long?): FavoriteEntity?- @Query("SELECT COUNT(*) FROM favorites WHERE group_id IS NULL AND content_type = :contentType")- fun getGlobalFavoriteCount(contentType: String): Flow<Int>+ @Query("SELECT COUNT(*) FROM favorites WHERE provider_id = :providerId AND group_id IS NULL AND content_type = :contentType")+ fun getGlobalFavoriteCount(providerId: Long, contentType: String): Flow<Int>- @Query("SELECT group_id as category_id, COUNT(*) as item_count FROM favorites WHERE group_id IS NOT NULL AND content_type = :contentType GROUP BY group_id")- fun getGroupFavoriteCounts(contentType: String): Flow<List<CategoryCount>>+ @Query("SELECT group_id as category_id, COUNT(*) as item_count FROM favorites WHERE provider_id = :providerId AND group_id IS NOT NULL AND content_type = :contentType GROUP BY group_id")+ fun getGroupFavoriteCounts(providerId: Long, contentType: String): Flow<List<CategoryCount>>- @Query("SELECT group_id FROM favorites WHERE content_id = :contentId AND content_type = :contentType AND group_id IS NOT NULL")- suspend fun getGroupMemberships(contentId: Long, contentType: String): List<Long>+ @Query("SELECT group_id FROM favorites WHERE provider_id = :providerId AND content_id = :contentId AND content_type = :contentType AND group_id IS NOT NULL")+ suspend fun getGroupMemberships(providerId: Long, contentId: Long, contentType: String): List<Long>- @Query("SELECT MAX(position) FROM favorites WHERE (:groupId IS NULL AND group_id IS NULL OR group_id = :groupId)")- suspend fun getMaxPosition(groupId: Long?): Int?+ @Query("SELECT MAX(position) FROM favorites WHERE provider_id = :providerId AND (:groupId IS NULL AND group_id IS NULL OR group_id = :groupId)")+ suspend fun getMaxPosition(providerId: Long, groupId: Long?): Int?@Insert(onConflict = OnConflictStrategy.REPLACE)suspend fun insert(favorite: FavoriteEntity)@@ -1604,8 +2214,8 @@ interface FavoriteDao {@Updatesuspend fun updateAll(favorites: List<FavoriteEntity>)- @Query("DELETE FROM favorites WHERE content_id = :contentId AND content_type = :contentType AND (:groupId IS NULL AND group_id IS NULL OR group_id = :groupId)")- suspend fun delete(contentId: Long, contentType: String, groupId: Long?)+ @Query("DELETE FROM favorites WHERE provider_id = :providerId AND content_id = :contentId AND content_type = :contentType AND (:groupId IS NULL AND group_id IS NULL OR group_id = :groupId)")+ suspend fun delete(providerId: Long, contentId: Long, contentType: String, groupId: Long?)@Query("DELETE FROM favorites WHERE content_type = 'LIVE' AND content_id NOT IN (SELECT id FROM channels)")suspend fun deleteMissingLiveFavorites(): Int@@ -1622,8 +2232,11 @@ interface FavoriteDao {@Daointerface VirtualGroupDao {- @Query("SELECT * FROM virtual_groups WHERE content_type = :contentType ORDER BY position ASC")- fun getByType(contentType: String): Flow<List<VirtualGroupEntity>>+ @Query("SELECT * FROM virtual_groups WHERE provider_id = :providerId AND content_type = :contentType ORDER BY position ASC")+ fun getByType(providerId: Long, contentType: String): Flow<List<VirtualGroupEntity>>++ @Query("SELECT * FROM virtual_groups WHERE provider_id IN (:providerIds) AND content_type = :contentType ORDER BY provider_id ASC, position ASC")+ fun getByTypeForProviders(providerIds: List<Long>, contentType: String): Flow<List<VirtualGroupEntity>>@Insert(onConflict = OnConflictStrategy.REPLACE)suspend fun insert(group: VirtualGroupEntity): Long@@ -1653,6 +2266,53 @@ interface PlaybackHistoryDao {@Query("SELECT * FROM playback_history WHERE content_id = :contentId AND content_type = :contentType AND provider_id = :providerId")suspend fun get(contentId: Long, contentType: String, providerId: Long): PlaybackHistoryEntity?+ @Query(+ """+ SELECT ph.* FROM playback_history ph+ JOIN movies current_movie+ ON current_movie.id = :contentId+ AND current_movie.provider_id = :providerId+ JOIN tmdb_identity identity+ ON identity.tmdb_id = current_movie.tmdb_id+ AND identity.content_type = 'MOVIE'+ JOIN movies candidate_movie+ ON candidate_movie.tmdb_id = identity.tmdb_id+ WHERE current_movie.tmdb_id IS NOT NULL+ AND ph.content_type = 'MOVIE'+ AND ph.provider_id = candidate_movie.provider_id+ AND ph.content_id = candidate_movie.id+ ORDER BY ph.last_watched_at DESC+ LIMIT 1+ """+ )+ suspend fun getLatestMovieHistoryBySharedTmdb(contentId: Long, providerId: Long): PlaybackHistoryEntity?++ @Query(+ """+ SELECT ph.* FROM playback_history ph+ JOIN series current_series+ ON current_series.id = :seriesId+ AND current_series.provider_id = :providerId+ JOIN tmdb_identity identity+ ON identity.tmdb_id = current_series.tmdb_id+ AND identity.content_type = 'SERIES'+ JOIN series candidate_series+ ON candidate_series.tmdb_id = identity.tmdb_id+ WHERE current_series.tmdb_id IS NOT NULL+ AND (+ (ph.content_type = 'SERIES' AND ph.content_id = candidate_series.id)+ OR (+ ph.content_type = 'SERIES_EPISODE'+ AND ph.series_id = candidate_series.id+ )+ )+ AND ph.provider_id = candidate_series.provider_id+ ORDER BY ph.last_watched_at DESC+ LIMIT 1+ """+ )+ suspend fun getLatestSeriesHistoryBySharedTmdb(seriesId: Long, providerId: Long): PlaybackHistoryEntity?+@Insert(onConflict = OnConflictStrategy.REPLACE)suspend fun insertOrUpdate(history: PlaybackHistoryEntity)@@ -1664,6 +2324,43 @@ interface PlaybackHistoryDao {@Query("DELETE FROM playback_history WHERE provider_id = :providerId")suspend fun deleteByProvider(providerId: Long)++ @Query("DELETE FROM playback_history WHERE provider_id = :providerId AND content_type = :contentType")+ suspend fun deleteByProviderAndType(providerId: Long, contentType: String)+}++@Dao+interface SearchHistoryDao {+ @Query(+ """+ SELECT * FROM search_history+ WHERE content_scope = :contentScope+ AND provider_id = :providerId+ ORDER BY used_at DESC+ LIMIT :limit+ """+ )+ fun observeRecent(contentScope: String, providerId: Long, limit: Int): Flow<List<SearchHistoryEntity>>++ @Query(+ """+ INSERT INTO search_history(query, content_scope, provider_id, used_at, use_count)+ VALUES (:query, :contentScope, :providerId, :usedAt, 1)+ ON CONFLICT(query, content_scope, provider_id) DO UPDATE SET+ used_at = excluded.used_at,+ use_count = search_history.use_count + 1+ """+ )+ suspend fun record(query: String, contentScope: String, providerId: Long, usedAt: Long)++ @Query("DELETE FROM search_history WHERE content_scope = :contentScope AND provider_id = :providerId")+ suspend fun deleteByScope(contentScope: String, providerId: Long)++ @Query("DELETE FROM search_history WHERE used_at < :minUsedAt")+ suspend fun pruneOlderThan(minUsedAt: Long)++ @Query("DELETE FROM search_history")+ suspend fun deleteAll()}@Dao@@ -1750,7 +2447,7 @@ interface EpgSourceDao {}@Dao-interface ProviderEpgSourceDao {+abstract class ProviderEpgSourceDao {@Query("""SELECT pes.*, es.name AS epg_source_name, es.url AS epg_source_urlFROM provider_epg_sources pes@@ -1758,7 +2455,7 @@ interface ProviderEpgSourceDao {WHERE pes.provider_id = :providerIdORDER BY pes.priority ASC""")- fun getForProvider(providerId: Long): Flow<List<ProviderEpgSourceWithDetails>>+ abstract fun getForProvider(providerId: Long): Flow<List<ProviderEpgSourceWithDetails>>@Query("""SELECT pes.*@@ -1767,7 +2464,7 @@ interface ProviderEpgSourceDao {WHERE pes.provider_id = :providerId AND pes.enabled = 1 AND es.enabled = 1ORDER BY pes.priority ASC""")- suspend fun getEnabledForProviderSync(providerId: Long): List<ProviderEpgSourceEntity>+ abstract suspend fun getEnabledForProviderSync(providerId: Long): List<ProviderEpgSourceEntity>@Query("""SELECT pes.*@@ -1775,22 +2472,32 @@ interface ProviderEpgSourceDao {WHERE pes.provider_id = :providerIdORDER BY pes.priority ASC""")- suspend fun getForProviderSync(providerId: Long): List<ProviderEpgSourceEntity>+ abstract suspend fun getForProviderSync(providerId: Long): List<ProviderEpgSourceEntity>@Query("SELECT DISTINCT provider_id FROM provider_epg_sources WHERE epg_source_id = :epgSourceId")- suspend fun getProviderIdsForSourceSync(epgSourceId: Long): List<Long>+ abstract suspend fun getProviderIdsForSourceSync(epgSourceId: Long): List<Long>@Insert(onConflict = OnConflictStrategy.REPLACE)- suspend fun insert(assignment: ProviderEpgSourceEntity): Long+ abstract suspend fun insert(assignment: ProviderEpgSourceEntity): Long@Update- suspend fun update(assignment: ProviderEpgSourceEntity)+ abstract suspend fun update(assignment: ProviderEpgSourceEntity)@Query("DELETE FROM provider_epg_sources WHERE provider_id = :providerId AND epg_source_id = :epgSourceId")- suspend fun delete(providerId: Long, epgSourceId: Long)+ abstract suspend fun delete(providerId: Long, epgSourceId: Long)@Query("DELETE FROM provider_epg_sources WHERE provider_id = :providerId")- suspend fun deleteByProvider(providerId: Long)+ abstract suspend fun deleteByProvider(providerId: Long)++ /** Atomically swaps the priority of two assignment rows within a single transaction. */+ @Transaction+ open suspend fun swapPriorities(+ entity1: ProviderEpgSourceEntity,+ entity2: ProviderEpgSourceEntity+ ) {+ update(entity1)+ update(entity2)+ }}data class ProviderEpgSourceWithDetails(@@ -1885,6 +2592,9 @@ abstract class ChannelEpgMappingDao {@Insert(onConflict = OnConflictStrategy.REPLACE)abstract suspend fun upsert(mapping: ChannelEpgMappingEntity)+ @Query("DELETE FROM channel_epg_mappings WHERE provider_id = :providerId AND provider_channel_id = :channelId")+ abstract suspend fun deleteForChannel(providerId: Long, channelId: Long)+@Query("DELETE FROM channel_epg_mappings WHERE provider_id = :providerId")abstract suspend fun deleteByProvider(providerId: Long)@@ -1903,6 +2613,49 @@ abstract class ChannelEpgMappingDao {GROUP BY source_type, match_type""")abstract suspend fun getResolutionStats(providerId: Long): List<EpgResolutionStatRow>++ @Query(+ """+ SELECT COUNT(*) FROM channel_epg_mappings+ WHERE provider_id = :providerId+ AND confidence > 0+ AND confidence < :minConfidence+ """+ )+ abstract suspend fun countLowConfidence(providerId: Long, minConfidence: Float): Int++ @Query(+ """+ SELECT COUNT(*) FROM channel_epg_mappings+ WHERE provider_id = :providerId+ AND failed_attempts < :maxAttempts+ AND (+ source_type = 'NONE'+ OR (confidence > 0 AND confidence < :minConfidence)+ )+ """+ )+ abstract suspend fun countRematchCandidates(providerId: Long, minConfidence: Float, maxAttempts: Int): Int++ @Query(+ """+ SELECT * FROM channel_epg_mappings+ WHERE provider_id = :providerId+ AND failed_attempts < :maxAttempts+ AND (+ source_type = 'NONE'+ OR (confidence > 0 AND confidence < :minConfidence)+ )+ ORDER BY confidence ASC, failed_attempts ASC, provider_channel_id ASC+ LIMIT :limit+ """+ )+ abstract suspend fun getChannelsNeedingRematch(+ providerId: Long,+ minConfidence: Float,+ maxAttempts: Int,+ limit: Int+ ): List<ChannelEpgMappingEntity>}data class EpgResolutionStatRow(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 e1fb6549..208f7317 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@@ -9,6 +9,7 @@ import com.streamvault.data.local.entity.RecordingRunEntityimport com.streamvault.data.local.entity.RecordingRunWithScheduleimport com.streamvault.data.local.entity.RecordingScheduleEntityimport com.streamvault.data.local.entity.RecordingStorageEntity+import com.streamvault.data.local.entity.ProgramReminderEntityimport com.streamvault.domain.model.RecordingStatusimport kotlinx.coroutines.flow.Flow@@ -112,3 +113,75 @@ interface RecordingStorageDao {@Insert(onConflict = OnConflictStrategy.REPLACE)suspend fun upsert(storage: RecordingStorageEntity)}++@Dao+interface ProgramReminderDao {+ @Query(+ """+ SELECT * FROM program_reminders+ WHERE is_dismissed = 0+ AND program_start_time >= :now+ ORDER BY remind_at ASC, program_start_time ASC+ """+ )+ fun observeUpcoming(now: Long = System.currentTimeMillis()): Flow<List<ProgramReminderEntity>>++ @Query(+ """+ SELECT * FROM program_reminders+ WHERE provider_id = :providerId+ AND channel_id = :channelId+ AND program_title = :programTitle+ AND program_start_time = :programStartTime+ LIMIT 1+ """+ )+ suspend fun getByProgram(+ providerId: Long,+ channelId: String,+ programTitle: String,+ programStartTime: Long+ ): ProgramReminderEntity?++ @Query("SELECT * FROM program_reminders WHERE id = :id LIMIT 1")+ suspend fun getById(id: Long): ProgramReminderEntity?++ @Query(+ """+ SELECT * FROM program_reminders+ WHERE is_dismissed = 0+ AND notified_at IS NULL+ AND program_start_time > :now+ ORDER BY remind_at ASC+ """+ )+ suspend fun getPendingActive(now: Long = System.currentTimeMillis()): List<ProgramReminderEntity>++ @Insert(onConflict = OnConflictStrategy.REPLACE)+ suspend fun insert(reminder: ProgramReminderEntity): Long++ @Update+ suspend fun update(reminder: ProgramReminderEntity)++ @Query(+ """+ DELETE FROM program_reminders+ WHERE provider_id = :providerId+ AND channel_id = :channelId+ AND program_title = :programTitle+ AND program_start_time = :programStartTime+ """+ )+ suspend fun deleteByProgram(+ providerId: Long,+ channelId: String,+ programTitle: String,+ programStartTime: Long+ )++ @Query("DELETE FROM program_reminders WHERE id = :id")+ suspend fun deleteById(id: Long)++ @Query("DELETE FROM program_reminders WHERE program_start_time < :beforeTime")+ suspend fun deleteExpired(beforeTime: Long): Int+}diff --git a/data/src/main/java/com/streamvault/data/local/entity/Entities.kt b/data/src/main/java/com/streamvault/data/local/entity/Entities.ktindex 545897d8..100f34ac 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@@ -155,10 +155,12 @@ data class MovieEntity(@ColumnInfo(name = "youtube_trailer") val youtubeTrailer: String? = null,@ColumnInfo(name = "provider_id") val providerId: Long = 0,@ColumnInfo(name = "watch_progress") val watchProgress: Long = 0L,+ @ColumnInfo(name = "watch_count") val watchCount: Int = 0,@ColumnInfo(name = "last_watched_at") val lastWatchedAt: Long = 0L,@ColumnInfo(name = "is_adult") val isAdult: Boolean = false,@ColumnInfo(name = "is_user_protected") val isUserProtected: Boolean = false,- @ColumnInfo(name = "sync_fingerprint") val syncFingerprint: String = ""+ @ColumnInfo(name = "sync_fingerprint") val syncFingerprint: String = "",+ @ColumnInfo(name = "added_at") val addedAt: Long = 0L)data class MovieBrowseEntity(@@ -179,7 +181,8 @@ data class MovieBrowseEntity(@ColumnInfo(name = "watch_progress") val watchProgress: Long = 0L,@ColumnInfo(name = "last_watched_at") val lastWatchedAt: Long = 0L,@ColumnInfo(name = "is_adult") val isAdult: Boolean = false,- @ColumnInfo(name = "is_user_protected") val isUserProtected: Boolean = false+ @ColumnInfo(name = "is_user_protected") val isUserProtected: Boolean = false,+ @ColumnInfo(name = "added_at") val addedAt: Long = 0L)@Entity(@@ -421,7 +424,8 @@ data class MovieImportStageEntity(@ColumnInfo(name = "tmdb_id") val tmdbId: Long? = null,@ColumnInfo(name = "youtube_trailer") val youtubeTrailer: String? = null,@ColumnInfo(name = "is_adult") val isAdult: Boolean = false,- @ColumnInfo(name = "sync_fingerprint") val syncFingerprint: String = ""+ @ColumnInfo(name = "sync_fingerprint") val syncFingerprint: String = "",+ @ColumnInfo(name = "added_at") val addedAt: Long = 0L)@Entity(@@ -492,6 +496,7 @@ data class CategoryImportStageEntity(indices = [Index(value = ["provider_id"]),Index(value = ["provider_id", "channel_id"]),+ Index(value = ["provider_id", "end_time", "channel_id"]),Index(value = ["provider_id", "start_time", "end_time"]),Index(value = ["start_time"]),Index(value = ["provider_id", "channel_id", "start_time"]),@@ -533,21 +538,30 @@ data class ProgramBrowseEntity(@Entity(tableName = "favorites",- foreignKeys = [ForeignKey(- entity = VirtualGroupEntity::class,- parentColumns = ["id"],- childColumns = ["group_id"],- onDelete = ForeignKey.SET_NULL- )],+ foreignKeys = [+ ForeignKey(+ entity = ProviderEntity::class,+ parentColumns = ["id"],+ childColumns = ["provider_id"],+ onDelete = ForeignKey.CASCADE+ ),+ ForeignKey(+ entity = VirtualGroupEntity::class,+ parentColumns = ["id"],+ childColumns = ["group_id"],+ onDelete = ForeignKey.SET_NULL+ )+ ],indices = [- Index(value = ["content_id", "content_type", "group_id"], unique = true),- Index(value = ["content_type", "group_id"]),+ Index(value = ["provider_id", "content_id", "content_type", "group_id"], unique = true),+ Index(value = ["provider_id", "content_type", "group_id"]),Index(value = ["group_id", "position"])])data class FavoriteEntity(@PrimaryKey(autoGenerate = true)val id: Long = 0,+ @ColumnInfo(name = "provider_id") val providerId: Long,@ColumnInfo(name = "content_id") val contentId: Long,@ColumnInfo(name = "content_type") val contentType: ContentType,val position: Int = 0,@@ -557,7 +571,14 @@ data class FavoriteEntity(@Entity(tableName = "virtual_groups",+ foreignKeys = [ForeignKey(+ entity = ProviderEntity::class,+ parentColumns = ["id"],+ childColumns = ["provider_id"],+ onDelete = ForeignKey.CASCADE+ )],indices = [+ Index(value = ["provider_id", "content_type"]),Index(value = ["position"]),Index(value = ["content_type"])]@@ -565,6 +586,7 @@ data class FavoriteEntity(data class VirtualGroupEntity(@PrimaryKey(autoGenerate = true)val id: Long = 0,+ @ColumnInfo(name = "provider_id") val providerId: Long,val name: String,@ColumnInfo(name = "icon_emoji") val iconEmoji: String? = null,val position: Int = 0,@@ -610,6 +632,27 @@ data class PlaybackHistoryEntity(@ColumnInfo(name = "episode_number") val episodeNumber: Int? = null)+@Entity(+ tableName = "tmdb_identity",+ primaryKeys = ["tmdb_id", "content_type"],+ foreignKeys = [ForeignKey(+ entity = ProviderEntity::class,+ parentColumns = ["id"],+ childColumns = ["canonical_provider_id"],+ onDelete = ForeignKey.CASCADE+ )],+ indices = [+ Index(value = ["content_type"]),+ Index(value = ["canonical_provider_id"])+ ]+)+data class TmdbIdentityEntity(+ @ColumnInfo(name = "tmdb_id") val tmdbId: Long,+ @ColumnInfo(name = "content_type") val contentType: ContentType,+ @ColumnInfo(name = "canonical_provider_id") val canonicalProviderId: Long,+ @ColumnInfo(name = "first_seen_at") val firstSeenAt: Long+)+data class PlaybackHistoryLiteEntity(val id: Long = 0,@ColumnInfo(name = "content_id") val contentId: Long,@@ -628,6 +671,25 @@ data class PlaybackHistoryLiteEntity(@ColumnInfo(name = "episode_number") val episodeNumber: Int? = null)+@Entity(+ tableName = "search_history",+ indices = [+ Index(value = ["content_scope", "provider_id", "used_at"]),+ Index(value = ["used_at"]),+ Index(value = ["provider_id"]),+ Index(value = ["query", "content_scope", "provider_id"], unique = true)+ ]+)+data class SearchHistoryEntity(+ @PrimaryKey(autoGenerate = true)+ val id: Long = 0,+ val query: String,+ @ColumnInfo(name = "content_scope") val contentScope: String,+ @ColumnInfo(name = "provider_id") val providerId: Long = 0,+ @ColumnInfo(name = "used_at") val usedAt: Long,+ @ColumnInfo(name = "use_count") val useCount: Int = 1+)+@Entity(tableName = "sync_metadata",foreignKeys = [ForeignKey(@@ -641,9 +703,12 @@ data class SyncMetadataEntity(@PrimaryKey@ColumnInfo(name = "provider_id") val providerId: Long,@ColumnInfo(name = "last_live_sync") val lastLiveSync: Long = 0,+ @ColumnInfo(name = "last_live_success") val lastLiveSuccess: Long = 0,@ColumnInfo(name = "last_movie_sync") val lastMovieSync: Long = 0,@ColumnInfo(name = "last_series_sync") val lastSeriesSync: Long = 0,+ @ColumnInfo(name = "last_series_success") val lastSeriesSuccess: Long = 0,@ColumnInfo(name = "last_epg_sync") val lastEpgSync: Long = 0,+ @ColumnInfo(name = "last_epg_success") val lastEpgSuccess: Long = 0,@ColumnInfo(name = "last_movie_attempt") val lastMovieAttempt: Long = 0,@ColumnInfo(name = "last_movie_success") val lastMovieSuccess: Long = 0,@ColumnInfo(name = "last_movie_partial") val lastMoviePartial: Long = 0,@@ -843,6 +908,9 @@ data class ChannelEpgMappingEntity(@ColumnInfo(name = "xmltv_channel_id") val xmltvChannelId: String? = null,@ColumnInfo(name = "match_type") val matchType: String? = null,val confidence: Float = 0f,+ @ColumnInfo(name = "matched_at") val matchedAt: Long = 0L,+ @ColumnInfo(name = "failed_attempts") val failedAttempts: Int = 0,+ val source: String? = null,@ColumnInfo(name = "is_manual_override") val isManualOverride: Boolean = false,@ColumnInfo(name = "updated_at") val updatedAt: Long = System.currentTimeMillis())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 c73a30cf..cd942243 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@@ -123,6 +123,41 @@ data class RecordingStorageEntity(@ColumnInfo(name = "updated_at") val updatedAt: Long = System.currentTimeMillis())+@Entity(+ tableName = "program_reminders",+ foreignKeys = [+ ForeignKey(+ entity = ProviderEntity::class,+ parentColumns = ["id"],+ childColumns = ["provider_id"],+ onDelete = ForeignKey.CASCADE+ )+ ],+ indices = [+ Index(value = ["provider_id", "remind_at"]),+ Index(value = ["is_dismissed", "notified_at", "remind_at"]),+ Index(value = ["provider_id", "channel_id", "program_start_time"]),+ Index(+ value = ["provider_id", "channel_id", "program_title", "program_start_time"],+ unique = true+ )+ ]+)+data class ProgramReminderEntity(+ @PrimaryKey(autoGenerate = true)+ val id: Long = 0,+ @ColumnInfo(name = "provider_id") val providerId: Long,+ @ColumnInfo(name = "channel_id") val channelId: String,+ @ColumnInfo(name = "channel_name") val channelName: String,+ @ColumnInfo(name = "program_title") val programTitle: String,+ @ColumnInfo(name = "program_start_time") val programStartTime: Long,+ @ColumnInfo(name = "remind_at") val remindAt: Long,+ @ColumnInfo(name = "lead_time_minutes") val leadTimeMinutes: Int = 5,+ @ColumnInfo(name = "is_dismissed") val isDismissed: Boolean = false,+ @ColumnInfo(name = "notified_at") val notifiedAt: Long? = null,+ @ColumnInfo(name = "created_at") val createdAt: Long = System.currentTimeMillis()+)+data class RecordingRunWithSchedule(@ColumnInfo(name = "id") val id: String,@ColumnInfo(name = "schedule_id") val scheduleId: Long,diff --git a/data/src/main/java/com/streamvault/data/manager/BackupManagerImpl.kt b/data/src/main/java/com/streamvault/data/manager/BackupManagerImpl.ktindex 12c342ea..fe5fb6a4 100644--- a/data/src/main/java/com/streamvault/data/manager/BackupManagerImpl.kt+++ b/data/src/main/java/com/streamvault/data/manager/BackupManagerImpl.kt@@ -98,18 +98,31 @@ class BackupManagerImpl @Inject constructor(username = entity.toDomain().username // Keep username for provider identification)}+ val providerIds = providerEntities.map { it.id }val providersById = providers.associateBy { it.id }// Gather all favorites across all types- val liveFavs = favoriteDao.getAllByType("LIVE").first().map { it.toDomain() }- val movieFavs = favoriteDao.getAllByType("MOVIE").first().map { it.toDomain() }- val seriesFavs = favoriteDao.getAllByType("SERIES").first().map { it.toDomain() }+ val liveFavs = providerIds.flatMap { providerId ->+ favoriteDao.getAllByType(providerId, "LIVE").first().map { it.toDomain() }+ }+ val movieFavs = providerIds.flatMap { providerId ->+ favoriteDao.getAllByType(providerId, "MOVIE").first().map { it.toDomain() }+ }+ val seriesFavs = providerIds.flatMap { providerId ->+ favoriteDao.getAllByType(providerId, "SERIES").first().map { it.toDomain() }+ }val allFavorites = liveFavs + movieFavs + seriesFavs// Gather all custom groups- val liveGroups = virtualGroupDao.getByType("LIVE").first().map { it.toDomain() }- val movieGroups = virtualGroupDao.getByType("MOVIE").first().map { it.toDomain() }- val seriesGroups = virtualGroupDao.getByType("SERIES").first().map { it.toDomain() }+ val liveGroups = providerIds.flatMap { providerId ->+ virtualGroupDao.getByType(providerId, "LIVE").first().map { it.toDomain() }+ }+ val movieGroups = providerIds.flatMap { providerId ->+ virtualGroupDao.getByType(providerId, "MOVIE").first().map { it.toDomain() }+ }+ val seriesGroups = providerIds.flatMap { providerId ->+ virtualGroupDao.getByType(providerId, "SERIES").first().map { it.toDomain() }+ }val allGroups = liveGroups + movieGroups + seriesGroupsval playbackHistory = playbackHistoryDao.getAllSync().map { it.toDomain() }@@ -188,15 +201,20 @@ class BackupManagerImpl @Inject constructor(}val existingProviders = providerDao.getAll().first()+ val existingProviderIds = existingProviders.map { it.id }val existingGroups = buildList {- addAll(virtualGroupDao.getByType("LIVE").first())- addAll(virtualGroupDao.getByType("MOVIE").first())- addAll(virtualGroupDao.getByType("SERIES").first())+ existingProviderIds.forEach { providerId ->+ addAll(virtualGroupDao.getByType(providerId, "LIVE").first())+ addAll(virtualGroupDao.getByType(providerId, "MOVIE").first())+ addAll(virtualGroupDao.getByType(providerId, "SERIES").first())+ }}val existingFavorites = buildList {- addAll(favoriteDao.getAllByType("LIVE").first())- addAll(favoriteDao.getAllByType("MOVIE").first())- addAll(favoriteDao.getAllByType("SERIES").first())+ existingProviderIds.forEach { providerId ->+ addAll(favoriteDao.getAllByType(providerId, "LIVE").first())+ addAll(favoriteDao.getAllByType(providerId, "MOVIE").first())+ addAll(favoriteDao.getAllByType(providerId, "SERIES").first())+ }}val existingHistory = playbackHistoryDao.getAllSync()val existingProtectedCategories = existingProviders.flatMap { provider ->@@ -350,12 +368,19 @@ class BackupManagerImpl @Inject constructor().toSecureEntityForBackup(credentialCrypto)providerDao.insert(entity)}+ val providerIdMap = backupData.providers.orEmpty().mapNotNull { provider ->+ providerDao.getByUrlAndUser(provider.serverUrl, provider.username)?.let { stored ->+ provider.id to stored.id+ }+ }.toMap()backupData.preferences?.get("lastActiveProviderId")?.toLongOrNull()- ?.takeIf { it > 0L }- ?.let { activeId ->- providerDao.setActive(activeId)+ ?.let { backupProviderId ->+ providerIdMap[backupProviderId]+ }+ ?.let { resolvedProviderId ->+ providerDao.setActive(resolvedProviderId)}importedSections += "Providers"} ?: run { skippedSections += "Providers" }@@ -365,36 +390,59 @@ class BackupManagerImpl @Inject constructor(// 3. Restore Virtual Groupsif (plan.importSavedLibrary) {+ val providerIdMap = backupData.providers.orEmpty().mapNotNull { provider ->+ providerDao.getByUrlAndUser(provider.serverUrl, provider.username)?.let { stored ->+ provider.id to stored.id+ }+ }.toMap()+ val groupIdMap = mutableMapOf<Long, Long>()backupData.virtualGroups?.let { groups ->val existingGroups = buildList {- addAll(virtualGroupDao.getByType("LIVE").first())- addAll(virtualGroupDao.getByType("MOVIE").first())- addAll(virtualGroupDao.getByType("SERIES").first())+ providerIdMap.values.distinct().forEach { providerId ->+ addAll(virtualGroupDao.getByType(providerId, "LIVE").first())+ addAll(virtualGroupDao.getByType(providerId, "MOVIE").first())+ addAll(virtualGroupDao.getByType(providerId, "SERIES").first())+ }}groups.forEach { group ->+ val resolvedProviderId = providerIdMap[group.providerId] ?: return@forEachval conflict = existingGroups.firstOrNull {+ it.providerId == resolvedProviderId &&it.name.equals(group.name, ignoreCase = true) &&it.contentType == group.contentType}if (conflict != null && plan.conflictStrategy == BackupConflictStrategy.KEEP_EXISTING) {+ groupIdMap[group.id] = conflict.idreturn@forEach}- virtualGroupDao.insert(group.toEntity())+ val insertedId = virtualGroupDao.insert(+ group.copy(id = 0L, providerId = resolvedProviderId).toEntity()+ )+ groupIdMap[group.id] = insertedId}} ?: run { skippedSections += "Saved Library" }// 4. Restore FavoritesbackupData.favorites?.let { favs ->favs.forEach { fav ->+ val resolvedProviderId = providerIdMap[fav.providerId] ?: return@forEach+ val resolvedGroupId = fav.groupId?.let { groupIdMap[it] }val existing = favoriteDao.get(+ providerId = resolvedProviderId,contentId = fav.contentId,contentType = fav.contentType.name,- groupId = fav.groupId+ groupId = resolvedGroupId)if (existing != null && plan.conflictStrategy == BackupConflictStrategy.KEEP_EXISTING) {return@forEach}- favoriteDao.insert(fav.toEntity())+ favoriteDao.insert(+ fav.copy(+ id = 0L,+ providerId = resolvedProviderId,+ groupId = resolvedGroupId+ ).toEntity()+ )}}val categoriesByProviderId = mutableMapOf<Long, List<com.streamvault.domain.model.Category>>()@@ -432,19 +480,25 @@ class BackupManagerImpl @Inject constructor(if (plan.importPlaybackHistory) {backupData.playbackHistory?.let { history ->+ val providerIdMap = backupData.providers.orEmpty().mapNotNull { provider ->+ providerDao.getByUrlAndUser(provider.serverUrl, provider.username)?.let { stored ->+ provider.id to stored.id+ }+ }.toMap()if (plan.conflictStrategy == BackupConflictStrategy.REPLACE_EXISTING) {playbackHistoryDao.deleteAll()}history.forEach { item ->+ val resolvedProviderId = providerIdMap[item.providerId] ?: return@forEachif (plan.conflictStrategy == BackupConflictStrategy.KEEP_EXISTING) {val existing = playbackHistoryDao.get(contentId = item.contentId,contentType = item.contentType.name,- providerId = item.providerId+ providerId = resolvedProviderId)if (existing != null) return@forEach}- playbackHistoryDao.insertOrUpdate(item.toEntity())+ playbackHistoryDao.insertOrUpdate(item.copy(providerId = resolvedProviderId).toEntity())}movieDao.syncAllWatchProgressFromHistory()episodeDao.syncAllWatchProgressFromHistory()diff --git a/data/src/main/java/com/streamvault/data/manager/ProgramReminderManagerImpl.kt b/data/src/main/java/com/streamvault/data/manager/ProgramReminderManagerImpl.ktnew file mode 100644index 00000000..75d9cfdd--- /dev/null+++ b/data/src/main/java/com/streamvault/data/manager/ProgramReminderManagerImpl.kt@@ -0,0 +1,114 @@+package com.streamvault.data.manager++import com.streamvault.data.local.dao.ProgramReminderDao+import com.streamvault.data.local.entity.ProgramReminderEntity+import com.streamvault.data.manager.reminder.ProgramReminderAlarmScheduler+import com.streamvault.data.manager.reminder.ProgramReminderNotifier+import com.streamvault.domain.manager.ProgramReminderManager+import com.streamvault.domain.model.Program+import com.streamvault.domain.model.ProgramReminder+import com.streamvault.domain.model.Result+import javax.inject.Inject+import javax.inject.Singleton+import kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.map++@Singleton+class ProgramReminderManagerImpl @Inject constructor(+ private val programReminderDao: ProgramReminderDao,+ private val alarmScheduler: ProgramReminderAlarmScheduler,+ private val notifier: ProgramReminderNotifier+) : ProgramReminderManager {++ override fun observeUpcomingReminders(): Flow<List<ProgramReminder>> =+ programReminderDao.observeUpcoming().map { reminders -> reminders.map { it.asDomain() } }++ override suspend fun isReminderScheduled(+ providerId: Long,+ channelId: String,+ programTitle: String,+ programStartTime: Long+ ): Boolean {+ val reminder = programReminderDao.getByProgram(providerId, channelId, programTitle, programStartTime)+ return reminder != null && !reminder.isDismissed+ }++ override suspend fun scheduleReminder(+ providerId: Long,+ channelId: String,+ 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.")+ }++ val now = System.currentTimeMillis()+ val remindAt = (program.startTime - leadTimeMinutes * 60_000L).coerceAtLeast(now + 1_000L)+ val existing = programReminderDao.getByProgram(providerId, channelId, program.title, program.startTime)+ val reminder = ProgramReminderEntity(+ id = existing?.id ?: 0L,+ providerId = providerId,+ channelId = channelId,+ channelName = channelName,+ programTitle = program.title,+ programStartTime = program.startTime,+ remindAt = remindAt,+ leadTimeMinutes = leadTimeMinutes,+ isDismissed = false,+ notifiedAt = null,+ createdAt = existing?.createdAt ?: now+ )+ val reminderId = if (existing == null) {+ programReminderDao.insert(reminder)+ } else {+ programReminderDao.update(reminder)+ existing.id+ }+ alarmScheduler.schedule(reminderId, remindAt)+ return Result.success(Unit)+ }++ override suspend fun cancelReminder(+ providerId: Long,+ channelId: String,+ programTitle: String,+ programStartTime: Long+ ): Result<Unit> {+ val existing = programReminderDao.getByProgram(providerId, channelId, programTitle, programStartTime)+ ?: return Result.success(Unit)+ programReminderDao.deleteById(existing.id)+ alarmScheduler.cancel(existing.id)+ return Result.success(Unit)+ }++ override suspend fun restoreScheduledReminders() {+ val now = System.currentTimeMillis()+ programReminderDao.getPendingActive(now).forEach { reminder ->+ alarmScheduler.schedule(reminder.id, reminder.remindAt.coerceAtLeast(now + 1_000L))+ }+ }++ suspend fun deliverReminder(reminderId: Long) {+ val reminder = programReminderDao.getById(reminderId) ?: return+ if (reminder.isDismissed || reminder.notifiedAt != null) return+ notifier.showReminder(reminder)+ programReminderDao.update(reminder.copy(notifiedAt = System.currentTimeMillis()))+ }++ private fun ProgramReminderEntity.asDomain(): ProgramReminder = ProgramReminder(+ id = id,+ providerId = providerId,+ channelId = channelId,+ channelName = channelName,+ programTitle = programTitle,+ programStartTime = programStartTime,+ remindAt = remindAt,+ leadTimeMinutes = leadTimeMinutes,+ isDismissed = isDismissed,+ notifiedAt = notifiedAt,+ createdAt = createdAt+ )+}diff --git a/data/src/main/java/com/streamvault/data/manager/recording/RecordingCaptureEngine.kt b/data/src/main/java/com/streamvault/data/manager/recording/RecordingCaptureEngine.ktindex 562d6102..07e0b401 100644--- a/data/src/main/java/com/streamvault/data/manager/recording/RecordingCaptureEngine.kt+++ b/data/src/main/java/com/streamvault/data/manager/recording/RecordingCaptureEngine.kt@@ -120,22 +120,33 @@ class HlsLiveCaptureEngine @Inject constructor(currentPlaylistUrl = playlist.bestVariantUrl}is ParsedHlsPlaylist.Media -> {- if (playlist.key?.method?.equals("NONE", ignoreCase = true) == false &&- !playlist.key.method.equals("AES-128", ignoreCase = true)- ) {- throw UnsupportedRecordingException(- "This HLS stream uses unsupported DRM or encryption.",- RecordingFailureCategory.DRM_UNSUPPORTED- )- }- val keyBytes = playlist.key?.takeIf { it.method.equals("AES-128", ignoreCase = true) }- ?.let { fetchBytes(it.uri, headers) }+ // Validate that all encryption methods are supported+ playlist.segments.mapNotNull { it.key }+ .distinctBy { it.uri }+ .forEach { key ->+ if (!key.method.equals("NONE", ignoreCase = true) &&+ !key.method.equals("AES-128", ignoreCase = true)+ ) {+ throw UnsupportedRecordingException(+ "This HLS stream uses unsupported DRM or encryption.",+ RecordingFailureCategory.DRM_UNSUPPORTED+ )+ }+ }+ // Cache key bytes by URI so rotated keys are fetched once each+ val keyCache = mutableMapOf<String, ByteArray>()playlist.segments.forEach { segment ->kotlinx.coroutines.currentCoroutineContext().ensureActive()if (segment.uri in seenSegments) return@forEachseenSegments += segment.urival bytes = fetchBytes(segment.uri, headers)- val payload = if (keyBytes != null) decryptAes128(bytes, keyBytes, segment.keyIv ?: playlist.key?.iv) else bytes+ val segKey = segment.key?.takeIf { it.method.equals("AES-128", ignoreCase = true) }+ val payload = if (segKey != null) {+ val keyBytes = keyCache.getOrPut(segKey.uri) { fetchBytes(segKey.uri, headers) }+ decryptAes128(bytes, keyBytes, segKey.iv)+ } else {+ bytes+ }sink.write(payload)bytesWritten += payload.sizeval elapsedMs = (System.currentTimeMillis() - startMs).coerceAtLeast(1L)@@ -237,7 +248,7 @@ class HlsLiveCaptureEngine @Inject constructor(else -> {segments += HlsSegment(uri = resolveRelativeUrl(baseUrl, line),- keyIv = currentKey?.iv+ key = currentKey?.copy())}}@@ -245,7 +256,6 @@ class HlsLiveCaptureEngine @Inject constructor(return ParsedHlsPlaylist.Media(targetDurationSeconds = targetDuration,endList = endList,- key = currentKey,segments = segments)}@@ -273,14 +283,13 @@ private sealed interface ParsedHlsPlaylist {data class Media(val targetDurationSeconds: Int,val endList: Boolean,- val key: HlsKey?,val segments: List<HlsSegment>) : ParsedHlsPlaylist}private data class HlsSegment(val uri: String,- val keyIv: String? = null+ val key: HlsKey? = null)private data class HlsKey(diff --git a/data/src/main/java/com/streamvault/data/manager/recording/RecordingSourceResolver.kt b/data/src/main/java/com/streamvault/data/manager/recording/RecordingSourceResolver.ktindex 65989a56..469bd285 100644--- a/data/src/main/java/com/streamvault/data/manager/recording/RecordingSourceResolver.kt+++ b/data/src/main/java/com/streamvault/data/manager/recording/RecordingSourceResolver.kt@@ -39,7 +39,10 @@ class RecordingSourceResolver @Inject constructor(url = logicalUrl,fallbackProviderId = providerId,fallbackStreamId = channelId,- fallbackContentType = ContentType.LIVE+ fallbackContentType = ContentType.LIVE,+ // Recording jobs can run for minutes or hours; prefer the stable+ // portal URL over an expiring tokenized direct-source CDN URL.+ preferStableUrl = true) ?: throw IOException("Recording stream URL could not be resolved.")val providerLabel = providerDao.getById(providerId)?.let { provider ->diff --git a/data/src/main/java/com/streamvault/data/manager/reminder/ProgramReminderAlarmReceiver.kt b/data/src/main/java/com/streamvault/data/manager/reminder/ProgramReminderAlarmReceiver.ktnew file mode 100644index 00000000..8df7cbde--- /dev/null+++ b/data/src/main/java/com/streamvault/data/manager/reminder/ProgramReminderAlarmReceiver.kt@@ -0,0 +1,47 @@+package com.streamvault.data.manager.reminder++import android.content.BroadcastReceiver+import android.content.Context+import android.content.Intent+import com.streamvault.data.manager.ProgramReminderManagerImpl+import dagger.hilt.EntryPoint+import dagger.hilt.InstallIn+import dagger.hilt.android.EntryPointAccessors+import dagger.hilt.components.SingletonComponent+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.launch++class ProgramReminderAlarmReceiver : BroadcastReceiver() {++ @EntryPoint+ @InstallIn(SingletonComponent::class)+ interface ProgramReminderAlarmReceiverEntryPoint {+ fun reminderManager(): ProgramReminderManagerImpl+ }++ override fun onReceive(context: Context, intent: Intent) {+ if (intent.action != ACTION_NOTIFY_REMINDER) return+ val reminderId = intent.getLongExtra(EXTRA_REMINDER_ID, 0L)+ if (reminderId <= 0L) return+ val pendingResult = goAsync()+ val appContext = context.applicationContext+ CoroutineScope(SupervisorJob() + Dispatchers.IO).launch {+ try {+ val entryPoint = EntryPointAccessors.fromApplication(+ appContext,+ ProgramReminderAlarmReceiverEntryPoint::class.java+ )+ entryPoint.reminderManager().deliverReminder(reminderId)+ } finally {+ pendingResult.finish()+ }+ }+ }++ companion object {+ const val ACTION_NOTIFY_REMINDER = "com.streamvault.data.reminder.action.NOTIFY"+ const val EXTRA_REMINDER_ID = "reminder_id"+ }+}diff --git a/data/src/main/java/com/streamvault/data/manager/reminder/ProgramReminderAlarmScheduler.kt b/data/src/main/java/com/streamvault/data/manager/reminder/ProgramReminderAlarmScheduler.ktnew file mode 100644index 00000000..5f61e43b--- /dev/null+++ b/data/src/main/java/com/streamvault/data/manager/reminder/ProgramReminderAlarmScheduler.kt@@ -0,0 +1,64 @@+package com.streamvault.data.manager.reminder++import android.app.AlarmManager+import android.app.PendingIntent+import android.content.Context+import android.content.Intent+import androidx.core.app.AlarmManagerCompat+import dagger.hilt.android.qualifiers.ApplicationContext+import javax.inject.Inject+import javax.inject.Singleton++@Singleton+class ProgramReminderAlarmScheduler @Inject constructor(+ @ApplicationContext private val context: Context+) {++ private val alarmManager: AlarmManager? by lazy {+ context.getSystemService(AlarmManager::class.java)+ }++ fun schedule(reminderId: Long, whenMs: Long) {+ val manager = alarmManager ?: return+ val pendingIntent = buildPendingIntent(+ reminderId = reminderId,+ flags = PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE+ )+ runCatching {+ AlarmManagerCompat.setExactAndAllowWhileIdle(+ manager,+ AlarmManager.RTC_WAKEUP,+ whenMs,+ pendingIntent+ )+ }.getOrElse {+ AlarmManagerCompat.setAndAllowWhileIdle(+ manager,+ AlarmManager.RTC_WAKEUP,+ whenMs,+ pendingIntent+ )+ }+ }++ fun cancel(reminderId: Long) {+ alarmManager?.cancel(+ buildPendingIntent(+ reminderId = reminderId,+ flags = PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE+ )+ )+ }++ private fun buildPendingIntent(reminderId: Long, flags: Int): PendingIntent {+ val intent = Intent(context, ProgramReminderAlarmReceiver::class.java)+ .setAction(ProgramReminderAlarmReceiver.ACTION_NOTIFY_REMINDER)+ .putExtra(ProgramReminderAlarmReceiver.EXTRA_REMINDER_ID, reminderId)+ return PendingIntent.getBroadcast(+ context,+ reminderId.hashCode(),+ intent,+ flags+ )+ }+}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.ktnew file mode 100644index 00000000..be1e83f5--- /dev/null+++ b/data/src/main/java/com/streamvault/data/manager/reminder/ProgramReminderNotifier.kt@@ -0,0 +1,71 @@+package com.streamvault.data.manager.reminder++import android.app.NotificationChannel+import android.app.NotificationManager+import android.app.PendingIntent+import android.content.Context+import android.os.Build+import androidx.core.app.NotificationCompat+import androidx.core.app.NotificationManagerCompat+import com.streamvault.data.local.entity.ProgramReminderEntity+import dagger.hilt.android.qualifiers.ApplicationContext+import javax.inject.Inject+import javax.inject.Singleton++@Singleton+class ProgramReminderNotifier @Inject constructor(+ @ApplicationContext private val context: Context+) {++ fun showReminder(reminder: ProgramReminderEntity) {+ 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()+ runCatching {+ NotificationManagerCompat.from(context).notify(reminder.id.hashCode(), notification)+ }+ }++ private fun buildLaunchPendingIntent(): PendingIntent? {+ val launchIntent = context.packageManager.getLaunchIntentForPackage(context.packageName) ?: return null+ launchIntent.addFlags(android.content.Intent.FLAG_ACTIVITY_CLEAR_TOP or android.content.Intent.FLAG_ACTIVITY_SINGLE_TOP)+ return PendingIntent.getActivity(+ context,+ 0,+ launchIntent,+ PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE+ )+ }++ private fun createChannelIfNeeded() {+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return+ val manager = context.getSystemService(NotificationManager::class.java) ?: return+ val channel = NotificationChannel(+ CHANNEL_ID,+ "Program reminders",+ NotificationManager.IMPORTANCE_DEFAULT+ ).apply {+ description = "Alerts before scheduled live programs start"+ }+ manager.createNotificationChannel(channel)+ }++ companion object {+ private const val CHANNEL_ID = "program-reminders"+ }+}diff --git a/data/src/main/java/com/streamvault/data/manager/reminder/ProgramReminderRestoreReceiver.kt b/data/src/main/java/com/streamvault/data/manager/reminder/ProgramReminderRestoreReceiver.ktnew file mode 100644index 00000000..784b0ff4--- /dev/null+++ b/data/src/main/java/com/streamvault/data/manager/reminder/ProgramReminderRestoreReceiver.kt@@ -0,0 +1,45 @@+package com.streamvault.data.manager.reminder++import android.content.BroadcastReceiver+import android.content.Context+import android.content.Intent+import com.streamvault.data.manager.ProgramReminderManagerImpl+import dagger.hilt.EntryPoint+import dagger.hilt.InstallIn+import dagger.hilt.android.EntryPointAccessors+import dagger.hilt.components.SingletonComponent+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.launch++class ProgramReminderRestoreReceiver : BroadcastReceiver() {++ @EntryPoint+ @InstallIn(SingletonComponent::class)+ interface ProgramReminderRestoreReceiverEntryPoint {+ fun reminderManager(): ProgramReminderManagerImpl+ }++ override fun onReceive(context: Context, intent: Intent) {+ when (intent.action) {+ Intent.ACTION_BOOT_COMPLETED,+ Intent.ACTION_MY_PACKAGE_REPLACED,+ Intent.ACTION_LOCKED_BOOT_COMPLETED -> {+ val pendingResult = goAsync()+ val appContext = context.applicationContext+ CoroutineScope(SupervisorJob() + Dispatchers.IO).launch {+ try {+ val entryPoint = EntryPointAccessors.fromApplication(+ appContext,+ ProgramReminderRestoreReceiverEntryPoint::class.java+ )+ entryPoint.reminderManager().restoreScheduledReminders()+ } finally {+ pendingResult.finish()+ }+ }+ }+ }+ }+}diff --git a/data/src/main/java/com/streamvault/data/mapper/EntityMappers.kt b/data/src/main/java/com/streamvault/data/mapper/EntityMappers.ktindex 1f43cce6..55c3cd28 100644--- a/data/src/main/java/com/streamvault/data/mapper/EntityMappers.kt+++ b/data/src/main/java/com/streamvault/data/mapper/EntityMappers.kt@@ -152,7 +152,8 @@ fun MovieEntity.toDomain() = Movie(lastWatchedAt = lastWatchedAt,isAdult = isAdult,isUserProtected = isUserProtected,- streamId = streamId+ streamId = streamId,+ addedAt = addedAt)fun MovieBrowseEntity.toDomain() = Movie(@@ -180,7 +181,8 @@ fun MovieBrowseEntity.toDomain() = Movie(lastWatchedAt = lastWatchedAt,isAdult = isAdult,isUserProtected = isUserProtected,- streamId = streamId+ streamId = streamId,+ addedAt = addedAt)fun Movie.toEntity() = MovieEntity(@@ -208,7 +210,8 @@ fun Movie.toEntity() = MovieEntity(watchProgress = watchProgress,lastWatchedAt = lastWatchedAt,isAdult = isAdult,- isUserProtected = isUserProtected+ isUserProtected = isUserProtected,+ addedAt = addedAt)// ── Series ─────────────────────────────────────────────────────────@@ -426,6 +429,7 @@ fun Program.toEntity() = ProgramEntity(fun FavoriteEntity.toDomain() = Favorite(id = id,+ providerId = providerId,contentId = contentId,contentType = contentType,position = position,@@ -435,6 +439,7 @@ fun FavoriteEntity.toDomain() = Favorite(fun Favorite.toEntity() = FavoriteEntity(id = id,+ providerId = providerId,contentId = contentId,contentType = contentType,position = position,@@ -446,6 +451,7 @@ fun Favorite.toEntity() = FavoriteEntity(fun VirtualGroupEntity.toDomain() = VirtualGroup(id = id,+ providerId = providerId,name = name,iconEmoji = iconEmoji,position = position,@@ -455,6 +461,7 @@ fun VirtualGroupEntity.toDomain() = VirtualGroup(fun VirtualGroup.toEntity() = VirtualGroupEntity(id = id,+ providerId = providerId,name = name,iconEmoji = iconEmoji,position = position,@@ -523,9 +530,12 @@ fun PlaybackHistory.toEntity() = PlaybackHistoryEntity(fun SyncMetadataEntity.toDomain() = SyncMetadata(providerId = providerId,lastLiveSync = lastLiveSync,+ lastLiveSuccess = lastLiveSuccess,lastMovieSync = lastMovieSync,lastSeriesSync = lastSeriesSync,+ lastSeriesSuccess = lastSeriesSuccess,lastEpgSync = lastEpgSync,+ lastEpgSuccess = lastEpgSuccess,lastMovieAttempt = lastMovieAttempt,lastMovieSuccess = lastMovieSuccess,lastMoviePartial = lastMoviePartial,@@ -552,9 +562,12 @@ fun SyncMetadataEntity.toDomain() = SyncMetadata(fun SyncMetadata.toEntity() = SyncMetadataEntity(providerId = providerId,lastLiveSync = lastLiveSync,+ lastLiveSuccess = lastLiveSuccess,lastMovieSync = lastMovieSync,lastSeriesSync = lastSeriesSync,+ lastSeriesSuccess = lastSeriesSuccess,lastEpgSync = lastEpgSync,+ lastEpgSuccess = lastEpgSuccess,lastMovieAttempt = lastMovieAttempt,lastMovieSuccess = lastMovieSuccess,lastMoviePartial = lastMoviePartial,@@ -710,6 +723,9 @@ fun ChannelEpgMappingEntity.toDomain() = com.streamvault.domain.model.ChannelEpgrunCatching { com.streamvault.domain.model.EpgMatchType.valueOf(it) }.getOrNull()},confidence = confidence,+ matchedAt = matchedAt,+ failedAttempts = failedAttempts,+ source = source,isManualOverride = isManualOverride,updatedAt = updatedAt)@@ -723,6 +739,9 @@ fun com.streamvault.domain.model.ChannelEpgMapping.toEntity() = ChannelEpgMappinxmltvChannelId = xmltvChannelId,matchType = matchType?.name,confidence = confidence,+ matchedAt = matchedAt,+ failedAttempts = failedAttempts,+ source = source,isManualOverride = isManualOverride,updatedAt = updatedAt)diff --git a/data/src/main/java/com/streamvault/data/parser/XmltvParser.kt b/data/src/main/java/com/streamvault/data/parser/XmltvParser.ktindex cec2e78d..d9d40fcd 100644--- a/data/src/main/java/com/streamvault/data/parser/XmltvParser.kt+++ b/data/src/main/java/com/streamvault/data/parser/XmltvParser.kt@@ -4,8 +4,6 @@ import com.streamvault.domain.model.Programimport org.xmlpull.v1.XmlPullParserimport org.xmlpull.v1.XmlPullParserFactoryimport java.io.InputStream-import java.io.InputStreamReader-import java.io.Readerimport java.time.LocalDateimport java.time.LocalDateTimeimport java.time.OffsetDateTime@@ -86,111 +84,13 @@ class XmltvParser {}.onFailure {logger.log(Level.FINE, "XML pull parser does not support relaxed mode", it)}- parser.setInput(SanitizingXmlReader(InputStreamReader(inputStream, Charsets.UTF_8)))+ // Pass the raw stream with null encoding so the parser auto-detects charset+ // from the BOM or the XML declaration (e.g. encoding="iso-8859-1").+ // Relaxed mode handles bare & characters in text content.+ parser.setInput(inputStream, null)return parser}- /**- * Repairs common real-world XMLTV malformations on the fly without buffering the full file.- *- * Today this focuses on illegal bare `&` characters inside text nodes, which frequently appear- * in guide titles like `Law&Crime` or `A&E`. Valid entities are preserved as-is.- */- private class SanitizingXmlReader(- private val delegate: Reader- ) : Reader() {- private val outputBuffer = ArrayDeque<Char>()- private val replayBuffer = ArrayDeque<Char>()-- override fun read(cbuf: CharArray, off: Int, len: Int): Int {- if (len <= 0) return 0-- var written = 0- while (written < len) {- val next = nextChar()- if (next == -1) {- break- }- cbuf[off + written] = next.toChar()- written++- }-- return if (written == 0) -1 else written- }-- override fun close() {- delegate.close()- }-- private fun nextChar(): Int {- if (outputBuffer.isNotEmpty()) {- return outputBuffer.removeFirst().code- }-- val next = readRawChar()- if (next == -1) return -1- if (next.toChar() != '&') {- return next- }-- val candidate = readEntityCandidate()- return if (isValidEntity(candidate)) {- outputBuffer.addLast('&')- candidate.forEach(outputBuffer::addLast)- outputBuffer.removeFirst().code- } else {- replayCandidate(candidate)- "&".forEach(outputBuffer::addLast)- outputBuffer.removeFirst().code- }- }-- private fun readRawChar(): Int {- if (replayBuffer.isNotEmpty()) {- return replayBuffer.removeFirst().code- }- return delegate.read()- }-- private fun readEntityCandidate(): String {- val builder = StringBuilder()- while (builder.length < 32) {- val next = delegate.read()- if (next == -1) {- break- }- val ch = next.toChar()- builder.append(ch)- if (ch == ';') {- break- }- if (ch == '&' || ch == '<' || ch == '>' || ch == '"' || ch == '\'' || ch.isWhitespace()) {- break- }- }- return builder.toString()- }-- private fun replayCandidate(candidate: String) {- for (index in candidate.indices.reversed()) {- replayBuffer.addFirst(candidate[index])- }- }-- private fun isValidEntity(candidate: String): Boolean {- if (!candidate.endsWith(";")) return false- val body = candidate.dropLast(1)- return when {- body in setOf("amp", "lt", "gt", "quot", "apos") -> true- body.startsWith("#x", ignoreCase = true) && body.length > 2 ->- body.drop(2).all { it.isDigit() || it.lowercaseChar() in 'a'..'f' }- body.startsWith("#") && body.length > 1 ->- body.drop(1).all(Char::isDigit)- else -> false- }- }- }-@Deprecated(message = "Loads all programs into memory. Use parseStreaming() for large EPG files.",replaceWith = ReplaceWith("parseStreaming(inputStream, onProgram)")diff --git a/data/src/main/java/com/streamvault/data/preferences/PreferencesRepository.kt b/data/src/main/java/com/streamvault/data/preferences/PreferencesRepository.ktindex 360887df..40c0cd06 100644--- a/data/src/main/java/com/streamvault/data/preferences/PreferencesRepository.kt+++ b/data/src/main/java/com/streamvault/data/preferences/PreferencesRepository.kt@@ -13,12 +13,14 @@ import androidx.datastore.preferences.core.longPreferencesKeyimport androidx.datastore.preferences.core.stringPreferencesKeyimport androidx.datastore.preferences.preferencesDataStoreimport com.streamvault.data.local.dao.ChannelPreferenceDao+import com.streamvault.data.local.dao.SearchHistoryDaoimport com.streamvault.data.local.entity.ChannelPreferenceEntityimport com.streamvault.domain.model.ChannelNumberingModeimport com.streamvault.domain.model.CategorySortModeimport com.streamvault.domain.model.ContentTypeimport com.streamvault.domain.model.DecoderModeimport com.streamvault.domain.model.ActiveLiveSource+import com.streamvault.domain.model.SearchHistoryScopeimport com.streamvault.domain.manager.ParentalPinVerifierimport com.streamvault.domain.manager.ParentalControlSessionStateimport com.streamvault.domain.manager.ParentalControlSessionStore@@ -41,7 +43,8 @@ private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(na@Singletonclass PreferencesRepository @Inject constructor(@ApplicationContext private val context: Context,- private val channelPreferenceDao: ChannelPreferenceDao+ private val channelPreferenceDao: ChannelPreferenceDao,+ private val searchHistoryDao: SearchHistoryDao) : ParentalControlSessionStore, ParentalPinVerifier {companion object {private const val PIN_SALT_BYTES = 16@@ -65,6 +68,8 @@ class PreferencesRepository @Inject constructor(val APP_LANGUAGE = stringPreferencesKey("app_language")val LIVE_TV_CHANNEL_MODE = stringPreferencesKey("live_tv_channel_mode")val SHOW_LIVE_SOURCE_SWITCHER = booleanPreferencesKey("show_live_source_switcher")+ val SHOW_ALL_CHANNELS_CATEGORY = booleanPreferencesKey("show_all_channels_category")+ val SHOW_RECENT_CHANNELS_CATEGORY = booleanPreferencesKey("show_recent_channels_category")val LIVE_TV_CATEGORY_FILTERS = stringPreferencesKey("live_tv_category_filters")val LIVE_TV_QUICK_FILTER_VISIBILITY = stringPreferencesKey("live_tv_quick_filter_visibility")val LIVE_CHANNEL_NUMBERING_MODE = stringPreferencesKey("live_channel_numbering_mode")@@ -106,8 +111,10 @@ class PreferencesRepository @Inject constructor(val XTREAM_TEXT_CLASSIFICATION = booleanPreferencesKey("xtream_text_classification")val XTREAM_BASE64_TEXT_COMPATIBILITY = booleanPreferencesKey("xtream_base64_text_compatibility")val XTREAM_TEXT_IMPORT_GENERATION = longPreferencesKey("xtream_text_import_generation")+ val ZAP_AUTO_REVERT = booleanPreferencesKey("zap_auto_revert")val PREVENT_STANDBY_DURING_PLAYBACK = booleanPreferencesKey("prevent_standby_during_playback")val AUTO_CHECK_APP_UPDATES = booleanPreferencesKey("auto_check_app_updates")+ val AUTO_DOWNLOAD_APP_UPDATES = booleanPreferencesKey("auto_download_app_updates")val LAST_APP_UPDATE_CHECK_TIMESTAMP = longPreferencesKey("last_app_update_check_timestamp")val APP_UPDATE_DOWNLOAD_ID = longPreferencesKey("app_update_download_id")val APP_UPDATE_DOWNLOADED_VERSION_NAME = stringPreferencesKey("app_update_downloaded_version_name")@@ -117,6 +124,23 @@ class PreferencesRepository @Inject constructor(val APP_UPDATE_DOWNLOAD_URL = stringPreferencesKey("app_update_download_url")val APP_UPDATE_RELEASE_NOTES = stringPreferencesKey("app_update_release_notes")val APP_UPDATE_PUBLISHED_AT = stringPreferencesKey("app_update_published_at")+ val LAST_MAINTENANCE_AT = longPreferencesKey("last_maintenance_at")+ val LAST_MAINTENANCE_DELETED_PROGRAMS = intPreferencesKey("last_maintenance_deleted_programs")+ val LAST_MAINTENANCE_DELETED_EXTERNAL_PROGRAMMES = intPreferencesKey("last_maintenance_deleted_external_programmes")+ val LAST_MAINTENANCE_DELETED_ORPHAN_EPISODES = intPreferencesKey("last_maintenance_deleted_orphan_episodes")+ val LAST_MAINTENANCE_DELETED_STALE_FAVORITES = intPreferencesKey("last_maintenance_deleted_stale_favorites")+ val LAST_MAINTENANCE_VACUUM_RAN = booleanPreferencesKey("last_maintenance_vacuum_ran")+ val LAST_MAINTENANCE_MAIN_DB_BYTES = longPreferencesKey("last_maintenance_main_db_bytes")+ val LAST_MAINTENANCE_WAL_BYTES = longPreferencesKey("last_maintenance_wal_bytes")+ val LAST_MAINTENANCE_RECLAIMABLE_BYTES = longPreferencesKey("last_maintenance_reclaimable_bytes")+ val LAST_MAINTENANCE_CHANNEL_ROWS = longPreferencesKey("last_maintenance_channel_rows")+ val LAST_MAINTENANCE_MOVIE_ROWS = longPreferencesKey("last_maintenance_movie_rows")+ val LAST_MAINTENANCE_SERIES_ROWS = longPreferencesKey("last_maintenance_series_rows")+ val LAST_MAINTENANCE_EPISODE_ROWS = longPreferencesKey("last_maintenance_episode_rows")+ val LAST_MAINTENANCE_PROGRAM_ROWS = longPreferencesKey("last_maintenance_program_rows")+ val LAST_MAINTENANCE_EPG_PROGRAMME_ROWS = longPreferencesKey("last_maintenance_epg_programme_rows")+ val LAST_MAINTENANCE_PLAYBACK_HISTORY_ROWS = longPreferencesKey("last_maintenance_playback_history_rows")+ val LAST_MAINTENANCE_FAVORITE_ROWS = longPreferencesKey("last_maintenance_favorite_rows")}private object ParentalSessionKeys {@@ -273,13 +297,7 @@ class PreferencesRepository @Inject constructor(preferences[PreferencesKeys.LAST_SPEED_TEST_ESTIMATED] ?: false}- val recentSearchQueries: Flow<List<String>> = context.dataStore.data.map { preferences ->- preferences[PreferencesKeys.RECENT_SEARCH_QUERIES]- ?.split('|')- ?.map { it.trim() }- ?.filter { it.isNotBlank() }- .orEmpty()- }+ val recentSearchQueries: Flow<List<String>> = getRecentSearchQueries(SearchHistoryScope.ALL, null)val parentalControlLevel: Flow<Int> = context.dataStore.data.map { preferences ->@@ -381,6 +399,10 @@ class PreferencesRepository @Inject constructor(preferences[PreferencesKeys.AUTO_CHECK_APP_UPDATES] ?: true}+ val autoDownloadAppUpdates: Flow<Boolean> = context.dataStore.data.map { preferences ->+ preferences[PreferencesKeys.AUTO_DOWNLOAD_APP_UPDATES] ?: false+ }+val lastAppUpdateCheckTimestamp: Flow<Long?> = context.dataStore.data.map { preferences ->preferences[PreferencesKeys.LAST_APP_UPDATE_CHECK_TIMESTAMP]?.takeIf { it > 0L }}@@ -417,6 +439,39 @@ class PreferencesRepository @Inject constructor(preferences[PreferencesKeys.APP_UPDATE_PUBLISHED_AT]?.takeIf { it.isNotBlank() }}+ val lastMaintenanceSnapshot: Flow<DatabaseMaintenanceSnapshot?> = context.dataStore.data.map { preferences ->+ val ranAt = preferences[PreferencesKeys.LAST_MAINTENANCE_AT] ?: return@map null+ DatabaseMaintenanceSnapshot(+ ranAt = ranAt,+ deletedPrograms = preferences[PreferencesKeys.LAST_MAINTENANCE_DELETED_PROGRAMS] ?: 0,+ deletedExternalProgrammes = preferences[PreferencesKeys.LAST_MAINTENANCE_DELETED_EXTERNAL_PROGRAMMES] ?: 0,+ deletedOrphanEpisodes = preferences[PreferencesKeys.LAST_MAINTENANCE_DELETED_ORPHAN_EPISODES] ?: 0,+ deletedStaleFavorites = preferences[PreferencesKeys.LAST_MAINTENANCE_DELETED_STALE_FAVORITES] ?: 0,+ vacuumRan = preferences[PreferencesKeys.LAST_MAINTENANCE_VACUUM_RAN] ?: false,+ mainDbBytes = preferences[PreferencesKeys.LAST_MAINTENANCE_MAIN_DB_BYTES] ?: 0L,+ walBytes = preferences[PreferencesKeys.LAST_MAINTENANCE_WAL_BYTES] ?: 0L,+ reclaimableBytes = preferences[PreferencesKeys.LAST_MAINTENANCE_RECLAIMABLE_BYTES] ?: 0L,+ channelRows = preferences[PreferencesKeys.LAST_MAINTENANCE_CHANNEL_ROWS] ?: 0L,+ movieRows = preferences[PreferencesKeys.LAST_MAINTENANCE_MOVIE_ROWS] ?: 0L,+ seriesRows = preferences[PreferencesKeys.LAST_MAINTENANCE_SERIES_ROWS] ?: 0L,+ episodeRows = preferences[PreferencesKeys.LAST_MAINTENANCE_EPISODE_ROWS] ?: 0L,+ programRows = preferences[PreferencesKeys.LAST_MAINTENANCE_PROGRAM_ROWS] ?: 0L,+ epgProgrammeRows = preferences[PreferencesKeys.LAST_MAINTENANCE_EPG_PROGRAMME_ROWS] ?: 0L,+ playbackHistoryRows = preferences[PreferencesKeys.LAST_MAINTENANCE_PLAYBACK_HISTORY_ROWS] ?: 0L,+ favoriteRows = preferences[PreferencesKeys.LAST_MAINTENANCE_FAVORITE_ROWS] ?: 0L+ )+ }++ val zapAutoRevert: Flow<Boolean> = context.dataStore.data.map { preferences ->+ preferences[PreferencesKeys.ZAP_AUTO_REVERT] ?: true+ }++ suspend fun setZapAutoRevert(enabled: Boolean) {+ context.dataStore.edit { preferences ->+ preferences[PreferencesKeys.ZAP_AUTO_REVERT] = enabled+ }+ }+suspend fun setPreventStandbyDuringPlayback(prevent: Boolean) {context.dataStore.edit { preferences ->preferences[PreferencesKeys.PREVENT_STANDBY_DURING_PLAYBACK] = prevent@@ -429,6 +484,12 @@ class PreferencesRepository @Inject constructor(}}+ suspend fun setAutoDownloadAppUpdates(enabled: Boolean) {+ context.dataStore.edit { preferences ->+ preferences[PreferencesKeys.AUTO_DOWNLOAD_APP_UPDATES] = enabled+ }+ }+suspend fun setLastAppUpdateCheckTimestamp(timestampMs: Long?) {context.dataStore.edit { preferences ->if (timestampMs == null || timestampMs <= 0L) {@@ -502,6 +563,48 @@ class PreferencesRepository @Inject constructor(}}+ suspend fun setLastMaintenanceSnapshot(snapshot: DatabaseMaintenanceSnapshot?) {+ context.dataStore.edit { preferences ->+ if (snapshot == null) {+ preferences.remove(PreferencesKeys.LAST_MAINTENANCE_AT)+ preferences.remove(PreferencesKeys.LAST_MAINTENANCE_DELETED_PROGRAMS)+ preferences.remove(PreferencesKeys.LAST_MAINTENANCE_DELETED_EXTERNAL_PROGRAMMES)+ preferences.remove(PreferencesKeys.LAST_MAINTENANCE_DELETED_ORPHAN_EPISODES)+ preferences.remove(PreferencesKeys.LAST_MAINTENANCE_DELETED_STALE_FAVORITES)+ preferences.remove(PreferencesKeys.LAST_MAINTENANCE_VACUUM_RAN)+ preferences.remove(PreferencesKeys.LAST_MAINTENANCE_MAIN_DB_BYTES)+ preferences.remove(PreferencesKeys.LAST_MAINTENANCE_WAL_BYTES)+ preferences.remove(PreferencesKeys.LAST_MAINTENANCE_RECLAIMABLE_BYTES)+ preferences.remove(PreferencesKeys.LAST_MAINTENANCE_CHANNEL_ROWS)+ preferences.remove(PreferencesKeys.LAST_MAINTENANCE_MOVIE_ROWS)+ preferences.remove(PreferencesKeys.LAST_MAINTENANCE_SERIES_ROWS)+ preferences.remove(PreferencesKeys.LAST_MAINTENANCE_EPISODE_ROWS)+ preferences.remove(PreferencesKeys.LAST_MAINTENANCE_PROGRAM_ROWS)+ preferences.remove(PreferencesKeys.LAST_MAINTENANCE_EPG_PROGRAMME_ROWS)+ preferences.remove(PreferencesKeys.LAST_MAINTENANCE_PLAYBACK_HISTORY_ROWS)+ preferences.remove(PreferencesKeys.LAST_MAINTENANCE_FAVORITE_ROWS)+ } else {+ preferences[PreferencesKeys.LAST_MAINTENANCE_AT] = snapshot.ranAt+ preferences[PreferencesKeys.LAST_MAINTENANCE_DELETED_PROGRAMS] = snapshot.deletedPrograms+ preferences[PreferencesKeys.LAST_MAINTENANCE_DELETED_EXTERNAL_PROGRAMMES] = snapshot.deletedExternalProgrammes+ preferences[PreferencesKeys.LAST_MAINTENANCE_DELETED_ORPHAN_EPISODES] = snapshot.deletedOrphanEpisodes+ preferences[PreferencesKeys.LAST_MAINTENANCE_DELETED_STALE_FAVORITES] = snapshot.deletedStaleFavorites+ preferences[PreferencesKeys.LAST_MAINTENANCE_VACUUM_RAN] = snapshot.vacuumRan+ preferences[PreferencesKeys.LAST_MAINTENANCE_MAIN_DB_BYTES] = snapshot.mainDbBytes+ preferences[PreferencesKeys.LAST_MAINTENANCE_WAL_BYTES] = snapshot.walBytes+ preferences[PreferencesKeys.LAST_MAINTENANCE_RECLAIMABLE_BYTES] = snapshot.reclaimableBytes+ preferences[PreferencesKeys.LAST_MAINTENANCE_CHANNEL_ROWS] = snapshot.channelRows+ preferences[PreferencesKeys.LAST_MAINTENANCE_MOVIE_ROWS] = snapshot.movieRows+ preferences[PreferencesKeys.LAST_MAINTENANCE_SERIES_ROWS] = snapshot.seriesRows+ preferences[PreferencesKeys.LAST_MAINTENANCE_EPISODE_ROWS] = snapshot.episodeRows+ preferences[PreferencesKeys.LAST_MAINTENANCE_PROGRAM_ROWS] = snapshot.programRows+ preferences[PreferencesKeys.LAST_MAINTENANCE_EPG_PROGRAMME_ROWS] = snapshot.epgProgrammeRows+ preferences[PreferencesKeys.LAST_MAINTENANCE_PLAYBACK_HISTORY_ROWS] = snapshot.playbackHistoryRows+ preferences[PreferencesKeys.LAST_MAINTENANCE_FAVORITE_ROWS] = snapshot.favoriteRows+ }+ }+ }+suspend fun setPlayerMuted(muted: Boolean) {context.dataStore.edit { preferences ->preferences[PreferencesKeys.PLAYER_MUTED] = muted@@ -653,17 +756,56 @@ class PreferencesRepository @Inject constructor(}}+ fun getRecentSearchQueries(+ scope: SearchHistoryScope,+ providerId: Long?,+ limit: Int = 6+ ): Flow<List<String>> {+ return searchHistoryDao.observeRecent(scope.name, searchHistoryProviderKey(providerId), limit)+ .map { rows -> rows.map { it.query } }+ }++ suspend fun recordRecentSearchQuery(+ query: String,+ scope: SearchHistoryScope,+ providerId: Long?,+ usedAt: Long = System.currentTimeMillis()+ ) {+ val normalized = query.trim()+ if (normalized.isBlank()) return+ searchHistoryDao.record(+ query = normalized,+ contentScope = scope.name,+ providerId = searchHistoryProviderKey(providerId),+ usedAt = usedAt+ )+ clearLegacyRecentSearchQueries()+ }++ suspend fun clearRecentSearchQueries(+ scope: SearchHistoryScope,+ providerId: Long?+ ) {+ searchHistoryDao.deleteByScope(scope.name, searchHistoryProviderKey(providerId))+ clearLegacyRecentSearchQueries()+ }+suspend fun setRecentSearchQueries(queries: List<String>) {- context.dataStore.edit { preferences ->- val normalized = queries- .map { it.trim() }- .filter { it.isNotBlank() }- if (normalized.isEmpty()) {- preferences.remove(PreferencesKeys.RECENT_SEARCH_QUERIES)- } else {- preferences[PreferencesKeys.RECENT_SEARCH_QUERIES] = normalized.joinToString("|")+ searchHistoryDao.deleteByScope(SearchHistoryScope.ALL.name, searchHistoryProviderKey(null))+ var usedAt = System.currentTimeMillis()+ queries+ .map { it.trim() }+ .filter { it.isNotBlank() }+ .distinctBy { it.lowercase() }+ .forEach { query ->+ searchHistoryDao.record(+ query = query,+ contentScope = SearchHistoryScope.ALL.name,+ providerId = searchHistoryProviderKey(null),+ usedAt = usedAt--+ )}- }+ clearLegacyRecentSearchQueries()}suspend fun setParentalPin(pin: String) {@@ -807,6 +949,26 @@ class PreferencesRepository @Inject constructor(}}+ val showAllChannelsCategory: Flow<Boolean> = context.dataStore.data.map { preferences ->+ preferences[PreferencesKeys.SHOW_ALL_CHANNELS_CATEGORY] ?: true+ }++ suspend fun setShowAllChannelsCategory(enabled: Boolean) {+ context.dataStore.edit { preferences ->+ preferences[PreferencesKeys.SHOW_ALL_CHANNELS_CATEGORY] = enabled+ }+ }++ val showRecentChannelsCategory: Flow<Boolean> = context.dataStore.data.map { preferences ->+ preferences[PreferencesKeys.SHOW_RECENT_CHANNELS_CATEGORY] ?: true+ }++ suspend fun setShowRecentChannelsCategory(enabled: Boolean) {+ context.dataStore.edit { preferences ->+ preferences[PreferencesKeys.SHOW_RECENT_CHANNELS_CATEGORY] = enabled+ }+ }+val liveTvQuickFilterVisibility: Flow<String?> = context.dataStore.data.map { preferences ->preferences[PreferencesKeys.LIVE_TV_QUICK_FILTER_VISIBILITY]}@@ -1128,6 +1290,7 @@ class PreferencesRepository @Inject constructor(suspend fun clearAllRecentData() {channelPreferenceDao.deleteAll()+ searchHistoryDao.deleteAll()context.dataStore.edit { preferences ->val keysToRemove = preferences.asMap().keys.filter { key ->key.name.startsWith("last_live_category_id_") ||@@ -1153,6 +1316,14 @@ class PreferencesRepository @Inject constructor(private fun pinnedCategoriesKey(providerId: Long, type: ContentType): String ="pinned_categories_${providerId}_${type.name}"+ private suspend fun clearLegacyRecentSearchQueries() {+ context.dataStore.edit { preferences ->+ preferences.remove(PreferencesKeys.RECENT_SEARCH_QUERIES)+ }+ }++ private fun searchHistoryProviderKey(providerId: Long?): Long = providerId ?: 0L+private fun List<String>.normalizeLiveTvCategoryFilters(): List<String> {val seen = linkedSetOf<String>()@@ -1236,3 +1407,23 @@ data class ParentalPinBackupData(val hash: String,val saltBase64: String)++data class DatabaseMaintenanceSnapshot(+ val ranAt: Long,+ val deletedPrograms: Int,+ val deletedExternalProgrammes: Int,+ val deletedOrphanEpisodes: Int,+ val deletedStaleFavorites: Int,+ val vacuumRan: Boolean,+ val mainDbBytes: Long,+ val walBytes: Long,+ val reclaimableBytes: Long,+ val channelRows: Long,+ val movieRows: Long,+ val seriesRows: Long,+ val episodeRows: Long,+ val programRows: Long,+ val epgProgrammeRows: Long,+ val playbackHistoryRows: Long,+ val favoriteRows: Long+)diff --git a/data/src/main/java/com/streamvault/data/remote/NetworkTimeoutConfig.kt b/data/src/main/java/com/streamvault/data/remote/NetworkTimeoutConfig.ktindex 6055f1bf..799f64da 100644--- a/data/src/main/java/com/streamvault/data/remote/NetworkTimeoutConfig.kt+++ b/data/src/main/java/com/streamvault/data/remote/NetworkTimeoutConfig.kt@@ -4,6 +4,8 @@ object NetworkTimeoutConfig {const val CONNECT_TIMEOUT_SECONDS = 30Lconst val READ_TIMEOUT_SECONDS = 30Lconst val WRITE_TIMEOUT_SECONDS = 30L+ // EPG files can be large and served from slow hosts — allow more time per read.+ const val EPG_READ_TIMEOUT_SECONDS = 120Lconst val XTREAM_HEAVY_READ_TIMEOUT_SECONDS = 300Lconst val XTREAM_HEAVY_WRITE_TIMEOUT_SECONDS = 60Lconst val XTREAM_HEAVY_CALL_TIMEOUT_SECONDS = 330Ldiff --git a/data/src/main/java/com/streamvault/data/remote/xtream/XtreamProvider.kt b/data/src/main/java/com/streamvault/data/remote/xtream/XtreamProvider.ktindex 2d007906..44ef8126 100644--- a/data/src/main/java/com/streamvault/data/remote/xtream/XtreamProvider.kt+++ b/data/src/main/java/com/streamvault/data/remote/xtream/XtreamProvider.kt@@ -713,7 +713,8 @@ class XtreamProvider(adultCategoryIds = adultCategoryIds),isUserProtected = false,- streamId = streamId+ streamId = streamId,+ addedAt = added?.trim()?.toLongOrNull() ?: 0L)}diff --git a/data/src/main/java/com/streamvault/data/remote/xtream/XtreamStreamUrlResolver.kt b/data/src/main/java/com/streamvault/data/remote/xtream/XtreamStreamUrlResolver.ktindex e76e3b18..025dd8b4 100644--- a/data/src/main/java/com/streamvault/data/remote/xtream/XtreamStreamUrlResolver.kt+++ b/data/src/main/java/com/streamvault/data/remote/xtream/XtreamStreamUrlResolver.kt@@ -11,7 +11,8 @@ import javax.inject.Singletondata class ResolvedStreamUrl(val url: String,- val expirationTime: Long? = null+ val expirationTime: Long? = null,+ val containerExtension: String? = null)@Singleton@@ -26,21 +27,29 @@ class XtreamStreamUrlResolver @Inject constructor(fallbackProviderId: Long? = null,fallbackStreamId: Long? = null,fallbackContentType: ContentType? = null,- fallbackContainerExtension: String? = null+ fallbackContainerExtension: String? = null,+ preferStableUrl: Boolean = false): String? = resolveWithMetadata(url = url,fallbackProviderId = fallbackProviderId,fallbackStreamId = fallbackStreamId,fallbackContentType = fallbackContentType,- fallbackContainerExtension = fallbackContainerExtension+ fallbackContainerExtension = fallbackContainerExtension,+ preferStableUrl = preferStableUrl)?.url+ /**+ * @param preferStableUrl when true, skip the tokenized direct-source URL and return+ * the credential-based portal URL instead. Use this for long-lived sessions (e.g.+ * Chromecast) where the token may expire before the session ends.+ */suspend fun resolveWithMetadata(url: String,fallbackProviderId: Long? = null,fallbackStreamId: Long? = null,fallbackContentType: ContentType? = null,- fallbackContainerExtension: String? = null+ fallbackContainerExtension: String? = null,+ preferStableUrl: Boolean = false): ResolvedStreamUrl? {if (url.isNotBlank() && !XtreamUrlFactory.isInternalStreamUrl(url)) {return ResolvedStreamUrl(@@ -75,11 +84,14 @@ class XtreamStreamUrlResolver @Inject constructor(streamId = streamId,containerExtension = ext)- val resolvedUrl = directSource ?: fallbackResolvedUrl+ // When preferStableUrl is set, skip the tokenized CDN URL (directSource)+ // and use the credential-based portal URL that does not expire.+ val resolvedUrl = if (preferStableUrl) fallbackResolvedUrl else (directSource ?: fallbackResolvedUrl)return ResolvedStreamUrl(url = resolvedUrl,- expirationTime = extractStreamExpirationTime(resolvedUrl)+ expirationTime = extractStreamExpirationTime(resolvedUrl),+ containerExtension = ext)}}diff --git a/data/src/main/java/com/streamvault/data/repository/ChannelRepositoryImpl.kt b/data/src/main/java/com/streamvault/data/repository/ChannelRepositoryImpl.ktindex af9a76f7..ba8c928c 100644--- a/data/src/main/java/com/streamvault/data/repository/ChannelRepositoryImpl.kt+++ b/data/src/main/java/com/streamvault/data/repository/ChannelRepositoryImpl.kt@@ -1,7 +1,9 @@package com.streamvault.data.repository+import android.database.sqlite.SQLiteExceptionimport com.streamvault.data.local.dao.CategoryDaoimport com.streamvault.data.local.dao.ChannelDao+import com.streamvault.data.local.dao.FavoriteDaoimport com.streamvault.data.local.entity.ChannelBrowseEntityimport com.streamvault.data.local.entity.CategoryEntityimport com.streamvault.data.local.entity.ChannelEntity@@ -12,8 +14,10 @@ import com.streamvault.domain.model.Channelimport com.streamvault.domain.model.ContentTypeimport com.streamvault.domain.model.Resultimport com.streamvault.domain.model.StreamInfo+import com.streamvault.domain.model.StreamTypeimport com.streamvault.domain.repository.ChannelRepositoryimport kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.catchimport kotlinx.coroutines.flow.mapimport kotlinx.coroutines.flow.combineimport kotlinx.coroutines.flow.flowOf@@ -28,6 +32,7 @@ import javax.inject.Singletonclass ChannelRepositoryImpl @Inject constructor(private val channelDao: ChannelDao,private val categoryDao: CategoryDao,+ private val favoriteDao: FavoriteDao,private val preferencesRepository: PreferencesRepository,private val parentalControlManager: com.streamvault.domain.manager.ParentalControlManager,private val xtreamStreamUrlResolver: XtreamStreamUrlResolver@@ -57,6 +62,37 @@ class ChannelRepositoryImpl @Inject constructor(override fun getChannelsByCategory(providerId: Long, categoryId: Long): Flow<List<Channel>> =observeChannels(channelFlow(providerId, categoryId), providerId)+ override fun getChannelsByCategoryPage(providerId: Long, categoryId: Long, limit: Int): Flow<List<Channel>> =+ observeChannels(channelFlowPage(providerId, categoryId, limit), providerId)++ override fun searchChannelsByCategoryPaged(providerId: Long, categoryId: Long, query: String, limit: Int): Flow<List<Channel>> =+ query.trim().takeIf { it.length >= MIN_SEARCH_QUERY_LENGTH }?.toFtsPrefixQuery().let { ftsQuery ->+ if (ftsQuery.isNullOrBlank()) {+ flowOf(emptyList())+ } else {+ combine(+ if (categoryId == ChannelRepository.ALL_CHANNELS_ID) {+ safeSearchFlow(channelDao.search(providerId, ftsQuery, limit))+ } else {+ safeSearchFlow(channelDao.searchByCategory(providerId, categoryId, ftsQuery, limit))+ },+ preferencesRepository.parentalControlLevel,+ parentalControlManager.unlockedCategoriesForProvider(providerId),+ preferencesRepository.liveChannelNumberingMode+ ) { entities, level, unlockedCats, numberingMode ->+ val filtered = if (level == 2) {+ entities.filter { entity ->+ val isUnlocked = entity.categoryId != null && unlockedCats.contains(entity.categoryId)+ (!entity.isAdult && !entity.isUserProtected) || isUnlocked+ }+ } else {+ entities+ }+ applyNumbering(groupAndMapChannels(filtered, unlockedCats), numberingMode)+ }+ }+ }+override fun getChannelsByNumber(providerId: Long, categoryId: Long): Flow<List<Channel>> =observeChannels(channelFlow(providerId, categoryId), providerId).map(::sortChannelsByNumber)@@ -72,9 +108,9 @@ class ChannelRepositoryImpl @Inject constructor(} else {combine(if (categoryId == ChannelRepository.ALL_CHANNELS_ID) {- channelDao.search(providerId, ftsQuery, CATEGORY_SEARCH_LIMIT)+ safeSearchFlow(channelDao.search(providerId, ftsQuery, CATEGORY_SEARCH_LIMIT))} else {- channelDao.searchByCategory(providerId, categoryId, ftsQuery, CATEGORY_SEARCH_LIMIT)+ safeSearchFlow(channelDao.searchByCategory(providerId, categoryId, ftsQuery, CATEGORY_SEARCH_LIMIT))},preferencesRepository.parentalControlLevel,parentalControlManager.unlockedCategoriesForProvider(providerId),@@ -133,7 +169,7 @@ class ChannelRepositoryImpl @Inject constructor(if (ftsQuery.isNullOrBlank()) {flowOf(emptyList())} else combine(- channelDao.search(providerId, ftsQuery, GLOBAL_SEARCH_LIMIT),+ safeSearchFlow(channelDao.search(providerId, ftsQuery, GLOBAL_SEARCH_LIMIT)),preferencesRepository.parentalControlLevel,parentalControlManager.unlockedCategoriesForProvider(providerId),preferencesRepository.liveChannelNumberingMode@@ -149,23 +185,29 @@ class ChannelRepositoryImpl @Inject constructor(applyNumbering(groupAndMapChannels(filtered, unlockedCats), numberingMode).rankSearchResults(query) { it.name }+ }.combine(favoriteDao.getAllByType(providerId, ContentType.LIVE.name)) { channels, favorites ->+ val favoriteIds = favorites.map { it.contentId }.toSet()+ channels.map { if (it.id in favoriteIds) it.copy(isFavorite = true) else it }}}override suspend fun getChannel(channelId: Long): Channel? =channelDao.getById(channelId)?.toDomain()- override suspend fun getStreamInfo(channel: Channel): Result<StreamInfo> = try {+ override suspend fun getStreamInfo(channel: Channel, preferStableUrl: Boolean): Result<StreamInfo> = try {xtreamStreamUrlResolver.resolveWithMetadata(url = channel.streamUrl,fallbackProviderId = channel.providerId,fallbackStreamId = channel.streamId,- fallbackContentType = ContentType.LIVE+ fallbackContentType = ContentType.LIVE,+ preferStableUrl = preferStableUrl)?.let { resolvedStream ->Result.success(StreamInfo(url = resolvedStream.url,title = channel.name,+ streamType = StreamType.fromContainerExtension(resolvedStream.containerExtension),+ containerExtension = resolvedStream.containerExtension,expirationTime = resolvedStream.expirationTime))@@ -277,6 +319,7 @@ class ChannelRepositoryImpl @Inject constructor(channel.copy(number = index + 1)}ChannelNumberingMode.PROVIDER -> channels+ ChannelNumberingMode.HIDDEN -> channels.map { it.copy(number = 0) }}private fun channelFlow(providerId: Long, categoryId: Long): Flow<List<ChannelBrowseEntity>> =@@ -286,6 +329,13 @@ class ChannelRepositoryImpl @Inject constructor(channelDao.getByCategory(providerId, categoryId)}+ private fun channelFlowPage(providerId: Long, categoryId: Long, limit: Int): Flow<List<ChannelBrowseEntity>> =+ if (categoryId == ChannelRepository.ALL_CHANNELS_ID) {+ channelDao.getByProviderBrowsePage(providerId, limit)+ } else {+ channelDao.getByCategoryBrowsePage(providerId, categoryId, limit)+ }+private fun channelFlowWithoutErrors(providerId: Long, categoryId: Long): Flow<List<ChannelBrowseEntity>> =if (categoryId == ChannelRepository.ALL_CHANNELS_ID) {channelDao.getByProviderWithoutErrors(providerId)@@ -293,6 +343,15 @@ class ChannelRepositoryImpl @Inject constructor(channelDao.getByCategoryWithoutErrors(providerId, categoryId)}+ private fun safeSearchFlow(source: Flow<List<ChannelBrowseEntity>>): Flow<List<ChannelBrowseEntity>> =+ source.catch { error ->+ if (error is SQLiteException) {+ emit(emptyList<ChannelBrowseEntity>())+ } else {+ throw error+ }+ }+private fun buildMergedQualityOptions(baseOptions: List<com.streamvault.domain.model.ChannelQualityOption>,primaryStreamUrl: String,diff --git a/data/src/main/java/com/streamvault/data/repository/EpgRepositoryImpl.kt b/data/src/main/java/com/streamvault/data/repository/EpgRepositoryImpl.ktindex 03b76b72..2137ee9e 100644--- a/data/src/main/java/com/streamvault/data/repository/EpgRepositoryImpl.kt+++ b/data/src/main/java/com/streamvault/data/repository/EpgRepositoryImpl.kt@@ -27,7 +27,11 @@ import kotlinx.coroutines.withContextimport okhttp3.OkHttpClientimport okhttp3.Requestimport java.io.FilterInputStream+import java.io.InputStreamimport java.io.IOException+import java.util.concurrent.TimeUnit+import java.util.zip.GZIPInputStream+import com.streamvault.data.remote.NetworkTimeoutConfigimport java.util.concurrent.ConcurrentHashMapimport javax.inject.Injectimport javax.inject.Singleton@@ -44,6 +48,12 @@ class EpgRepositoryImpl @Inject constructor(private val providerRefreshMutexes = ConcurrentHashMap<Long, Mutex>()+ private val epgHttpClient: OkHttpClient by lazy {+ okHttpClient.newBuilder()+ .readTimeout(NetworkTimeoutConfig.EPG_READ_TIMEOUT_SECONDS, TimeUnit.SECONDS)+ .build()+ }+companion object {private const val MAX_EPG_SIZE_BYTES = 200L * 1_048_576 // 200 MBprivate const val NOW_AND_NEXT_LOOKBACK_MS = 60L * 60L * 1000L@@ -72,13 +82,32 @@ class EpgRepositoryImpl @Inject constructor(return programDao.getForChannels(providerId, channelIds, startTime, endTime).map { entities -> entities.map { it.toDomain() }.groupBy { it.channelId } }}- return combine(chunks.map { chunk ->- programDao.getForChannels(providerId, chunk, startTime, endTime)- }) { arrays ->- arrays.flatMap { it.toList() }.map { it.toDomain() }.groupBy { it.channelId }+ return flow {+ emit(getProgramsForChannelsSnapshot(providerId, channelIds, startTime, endTime))}}+ override suspend fun getProgramsForChannelsSnapshot(+ providerId: Long,+ channelIds: List<String>,+ startTime: Long,+ endTime: Long+ ): Map<String, List<Program>> {+ if (channelIds.isEmpty()) return emptyMap()++ val entities = if (channelIds.size <= 500) {+ programDao.getForChannelsSync(providerId, channelIds, startTime, endTime)+ } else {+ channelIds.chunked(500).flatMap { chunk ->+ programDao.getForChannelsSync(providerId, chunk, startTime, endTime)+ }+ }++ return entities+ .map { it.toDomain() }+ .groupBy { it.channelId }+ }+override fun getProgramsByCategory(providerId: Long,categoryId: Long,@@ -112,8 +141,10 @@ class EpgRepositoryImpl @Inject constructor(}override fun getNowPlaying(providerId: Long, channelId: String): Flow<Program?> =- programDao.getNowPlaying(providerId, channelId, System.currentTimeMillis())- .map { it?.toDomain() }+ nowTicker().flatMapLatest { now ->+ programDao.getNowPlaying(providerId, channelId, now)+ .map { it?.toDomain() }+ }override fun getNowPlayingForChannels(providerId: Long, channelIds: List<String>): Flow<Map<String, Program?>> {if (channelIds.isEmpty()) return flowOf(emptyMap())@@ -174,10 +205,11 @@ class EpgRepositoryImpl @Inject constructor(val stagingProviderId = -providerIdval batch = ArrayList<ProgramEntity>(500)try {- programDao.deleteByProvider(stagingProviderId)-- val request = Request.Builder().url(epgUrl).build()- val response = okHttpClient.newCall(request).execute()+ val request = Request.Builder()+ .url(epgUrl)+ .header("Accept-Encoding", "identity")+ .build()+ val response = epgHttpClient.newCall(request).execute()if (!response.isSuccessful) {return@withLock Result.error("Failed to download EPG: HTTP ${response.code}")@@ -190,34 +222,52 @@ class EpgRepositoryImpl @Inject constructor(}val body = response.body ?: return@withLock Result.error("Empty EPG response")+ val contentEncoding = response.header("Content-Encoding")++ transactionRunner.inTransaction {+ programDao.deleteByProvider(stagingProviderId)- body.byteStream().use { inputStream ->- // Cap total bytes read even when Content-Length is absent (chunked transfer)- val limitedStream = object : FilterInputStream(inputStream) {- private var bytesRead = 0L- override fun read(): Int {- if (bytesRead >= MAX_EPG_SIZE_BYTES) throw IOException("EPG response too large (>200 MB)")- return super.read().also { if (it >= 0) bytesRead++ }+ body.byteStream().use { rawStream ->+ val alreadyDecompressed = contentEncoding?.contains("gzip", ignoreCase = true) == true+ // Decompress Content-Encoding: gzip manually since we requested+ // Accept-Encoding: identity to disable OkHttp's transparent decompression.+ val httpStream: InputStream = if (alreadyDecompressed) {+ GZIPInputStream(rawStream)+ } else {+ rawStream+ }+ // Cap total bytes read even when Content-Length is absent (chunked transfer)+ val limitedStream = object : FilterInputStream(httpStream) {+ private var bytesRead = 0L+ override fun read(): Int {+ if (bytesRead >= MAX_EPG_SIZE_BYTES) throw IOException("EPG response too large (>200 MB)")+ return super.read().also { if (it >= 0) bytesRead++ }+ }+ override fun read(b: ByteArray, off: Int, len: Int): Int {+ if (bytesRead >= MAX_EPG_SIZE_BYTES) throw IOException("EPG response too large (>200 MB)")+ return super.read(b, off, len).also { if (it > 0) bytesRead += it }+ }}- override fun read(b: ByteArray, off: Int, len: Int): Int {- if (bytesRead >= MAX_EPG_SIZE_BYTES) throw IOException("EPG response too large (>200 MB)")- return super.read(b, off, len).also { if (it > 0) bytesRead += it }+ val xmlInput: InputStream = if (alreadyDecompressed) {+ limitedStream+ } else {+ xmltvParser.maybeDecompressGzip(epgUrl, limitedStream)}- }- xmltvParser.maybeDecompressGzip(epgUrl, limitedStream).use { xmlInput ->- xmltvParser.parseStreaming(xmlInput) { program ->- batch.add(program.copy(providerId = stagingProviderId).toEntity())- if (batch.size >= 500) {- programDao.insertAll(batch.toList())- batch.clear()+ xmlInput.use {+ xmltvParser.parseStreaming(xmlInput) { program ->+ batch.add(program.copy(providerId = stagingProviderId).toEntity())+ if (batch.size >= 500) {+ programDao.insertAll(batch.toList())+ batch.clear()+ }}}}- }- if (batch.isNotEmpty()) {- programDao.insertAll(batch.toList())- batch.clear()+ if (batch.isNotEmpty()) {+ programDao.insertAll(batch.toList())+ batch.clear()+ }}transactionRunner.inTransaction {@@ -228,7 +278,11 @@ class EpgRepositoryImpl @Inject constructor(Result.success(Unit)} catch (e: Exception) {programDao.deleteByProvider(stagingProviderId)- Result.error("Failed to refresh EPG: ${e.message}", e)+ if (e is IOException && e.message?.contains("too large", ignoreCase = true) == true) {+ Result.error("EPG response exceeded 200 MB limit", e)+ } else {+ Result.error("Failed to refresh EPG: ${e.message}", e)+ }}}}@@ -237,6 +291,10 @@ class EpgRepositoryImpl @Inject constructor(programDao.deleteOld(beforeTime)}+ override fun onProviderDeleted(providerId: Long) {+ providerRefreshMutexes.remove(providerId)+ }+override suspend fun getResolvedProgramsForChannels(providerId: Long,channelIds: List<Long>,diff --git a/data/src/main/java/com/streamvault/data/repository/EpgSourceRepositoryImpl.kt b/data/src/main/java/com/streamvault/data/repository/EpgSourceRepositoryImpl.ktindex 542b0a60..ca17fae8 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,9 @@ import okhttp3.OkHttpClientimport okhttp3.Requestimport java.io.FilterInputStreamimport java.io.IOException+import java.util.concurrent.TimeUnit+import java.util.zip.GZIPInputStream+import com.streamvault.data.remote.NetworkTimeoutConfigimport dagger.hilt.android.qualifiers.ApplicationContextimport java.util.concurrent.ConcurrentHashMapimport javax.inject.Inject@@ -65,6 +68,14 @@ class EpgSourceRepositoryImpl @Inject constructor(private val sourceRefreshMutexes = ConcurrentHashMap<Long, Mutex>()+ // Dedicated client for EPG downloads: longer read timeout for large/slow feeds,+ // and no automatic Accept-Encoding: gzip (we handle gzip manually via maybeDecompressGzip).+ private val epgHttpClient: OkHttpClient by lazy {+ okHttpClient.newBuilder()+ .readTimeout(NetworkTimeoutConfig.EPG_READ_TIMEOUT_SECONDS, TimeUnit.SECONDS)+ .build()+ }+// ── EPG Source CRUD ────────────────────────────────────────────override fun getAllSources(): Flow<List<EpgSource>> =@@ -75,9 +86,9 @@ class EpgSourceRepositoryImpl @Inject constructor(override suspend fun addSource(name: String, url: String): Result<EpgSource> {val trimmedUrl = url.trim()+ if (trimmedUrl.isBlank()) return Result.error("URL cannot be empty")val validationError = UrlSecurityPolicy.validateOptionalEpgUrl(trimmedUrl)if (validationError != null) return Result.error(validationError)- if (trimmedUrl.isBlank()) return Result.error("URL cannot be empty")val existing = epgSourceDao.getByUrl(trimmedUrl)if (existing != null) return Result.error("A source with this URL already exists")@@ -126,6 +137,9 @@ class EpgSourceRepositoryImpl @Inject constructor(resolveAffectedProviders(providerEpgSourceDao.getProviderIdsForSourceSync(id))}+ override suspend fun getProviderIdsForSource(sourceId: Long): List<Long> =+ providerEpgSourceDao.getProviderIdsForSourceSync(sourceId)+// ── Provider ↔ Source assignment ───────────────────────────────override fun getAssignmentsForProvider(providerId: Long): Flow<List<ProviderEpgSourceAssignment>> =@@ -161,6 +175,23 @@ class EpgSourceRepositoryImpl @Inject constructor(resolveForProvider(providerId, emptySet())}+ override suspend fun swapAssignmentPriorities(+ providerId: Long,+ epgSourceId1: Long,+ newPriority1: Int,+ epgSourceId2: Long,+ newPriority2: Int+ ) {+ val assignments = providerEpgSourceDao.getForProviderSync(providerId)+ val target1 = assignments.find { it.epgSourceId == epgSourceId1 } ?: return+ val target2 = assignments.find { it.epgSourceId == epgSourceId2 } ?: return+ providerEpgSourceDao.swapPriorities(+ target1.copy(priority = newPriority1),+ target2.copy(priority = newPriority2)+ )+ resolveForProvider(providerId, emptySet())+ }+// ── Refresh / Ingestion ────────────────────────────────────────override suspend fun refreshSource(sourceId: Long): Result<Unit> =@@ -187,8 +218,15 @@ class EpgSourceRepositoryImpl @Inject constructor(return@withLock Result.error(err)}} else {- val request = Request.Builder().url(source.url).build()- val response = okHttpClient.newCall(request).execute()+ // Disable OkHttp's transparent gzip by requesting identity encoding.+ // This prevents double-decompression when the URL ends in .gz:+ // OkHttp would silently decompress gzip responses, and then+ // maybeDecompressGzip() would try again — corrupting the stream.+ val request = Request.Builder()+ .url(source.url)+ .header("Accept-Encoding", "identity")+ .build()+ val response = epgHttpClient.newCall(request).execute()if (!response.isSuccessful) {val err = "HTTP ${response.code}"@@ -205,10 +243,19 @@ class EpgSourceRepositoryImpl @Inject constructor(return@withLock Result.error(err)}- response.body?.byteStream() ?: run {+ val bodyStream = response.body?.byteStream() ?: run {epgSourceDao.updateRefreshStatus(sourceId, now, "Empty response")return@withLock Result.error("Empty EPG response")}+ // Some servers send Content-Encoding: gzip even when identity was requested.+ // Since OkHttp no longer decompresses (we set Accept-Encoding manually),+ // we must handle it here.+ val contentEncoding = response.header("Content-Encoding")+ if (contentEncoding?.contains("gzip", ignoreCase = true) == true) {+ GZIPInputStream(bodyStream)+ } else {+ bodyStream+ }}val channelBatch = ArrayList<EpgChannelEntity>(CHANNEL_BATCH_SIZE)@@ -294,8 +341,18 @@ class EpgSourceRepositoryImpl @Inject constructor(Result.success(Unit)} catch (e: Exception) {Log.e(TAG, "Failed to refresh source $sourceId", e)- epgSourceDao.updateRefreshStatus(sourceId, now, e.message ?: "Unknown error")- Result.error("Failed to refresh EPG source: ${e.message}", e)+ val isOversizeError = e is IOException && e.message?.contains("too large", ignoreCase = true) == true+ val statusMessage = if (isOversizeError) {+ "EPG response exceeded 200 MB limit"+ } else {+ e.message ?: "Unknown error"+ }+ epgSourceDao.updateRefreshStatus(sourceId, now, statusMessage)+ if (isOversizeError) {+ Result.error("EPG response exceeded 200 MB limit", e)+ } else {+ Result.error("Failed to refresh EPG source: ${e.message}", e)+ }}}}@@ -406,6 +463,8 @@ class EpgSourceRepositoryImpl @Inject constructor(if (!existing.isManualOverride) {return Result.success(Unit)}+ // Delete the pinned row so the next resolution pass can auto-assign via ID/name match.+ channelEpgMappingDao.deleteForChannel(providerId, channelId)resolveForProvider(providerId, emptySet())return Result.success(Unit)}diff --git a/data/src/main/java/com/streamvault/data/repository/FavoriteRepositoryImpl.kt b/data/src/main/java/com/streamvault/data/repository/FavoriteRepositoryImpl.ktindex ada1407d..10387fcf 100644--- a/data/src/main/java/com/streamvault/data/repository/FavoriteRepositoryImpl.kt+++ b/data/src/main/java/com/streamvault/data/repository/FavoriteRepositoryImpl.kt@@ -9,6 +9,7 @@ import com.streamvault.data.mapper.toEntityimport com.streamvault.domain.model.*import com.streamvault.domain.repository.FavoriteRepositoryimport kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.flowOfimport kotlinx.coroutines.flow.mapimport javax.inject.Injectimport javax.inject.Singleton@@ -19,45 +20,69 @@ class FavoriteRepositoryImpl @Inject constructor(private val virtualGroupDao: VirtualGroupDao,private val transactionRunner: DatabaseTransactionRunner) : FavoriteRepository {+ private companion object {+ const val POSITION_STEP = 1_024+ }++ override fun getFavorites(providerId: Long, contentType: ContentType?): Flow<List<Favorite>> {+ val flow = if (contentType != null) {+ favoriteDao.getGlobalByType(providerId, contentType.name)+ } else {+ favoriteDao.getAllGlobal(providerId)+ }+ return flow.map { entities -> entities.map { it.toDomain() } }+ }- override fun getFavorites(contentType: ContentType?): Flow<List<Favorite>> {+ override fun getFavorites(providerIds: List<Long>, contentType: ContentType?): Flow<List<Favorite>> {+ if (providerIds.isEmpty()) return flowOf(emptyList())val flow = if (contentType != null) {- favoriteDao.getGlobalByType(contentType.name)+ favoriteDao.getGlobalByTypeForProviders(providerIds, contentType.name)} else {- favoriteDao.getAllGlobal()+ favoriteDao.getAllGlobalByProviders(providerIds)}return flow.map { entities -> entities.map { it.toDomain() } }}- @Deprecated("Use getFavorites(contentType) instead", ReplaceWith("getFavorites(contentType)"))- override fun getAllFavorites(contentType: ContentType): Flow<List<Favorite>> =- favoriteDao.getAllByType(contentType.name)+ @Deprecated(+ "Use getFavorites(providerId, contentType) instead",+ ReplaceWith("getFavorites(providerId, contentType)")+ )+ override fun getAllFavorites(providerId: Long, contentType: ContentType): Flow<List<Favorite>> =+ favoriteDao.getAllByType(providerId, contentType.name).map { entities -> entities.map { it.toDomain() } }override fun getFavoritesByGroup(groupId: Long): Flow<List<Favorite>> =favoriteDao.getByGroup(groupId).map { entities -> entities.map { it.toDomain() } }- override fun getGroups(contentType: ContentType): Flow<List<VirtualGroup>> =- virtualGroupDao.getByType(contentType.name).map { entities -> entities.map { it.toDomain() } }+ override fun getGroups(providerId: Long, contentType: ContentType): Flow<List<VirtualGroup>> =+ virtualGroupDao.getByType(providerId, contentType.name).map { entities -> entities.map { it.toDomain() } }++ override fun getGroups(providerIds: List<Long>, contentType: ContentType): Flow<List<VirtualGroup>> {+ if (providerIds.isEmpty()) return flowOf(emptyList())+ return virtualGroupDao.getByTypeForProviders(providerIds, contentType.name)+ .map { entities -> entities.map { it.toDomain() } }+ }- override fun getGlobalFavoriteCount(contentType: ContentType): Flow<Int> =- favoriteDao.getGlobalFavoriteCount(contentType.name)+ override fun getGlobalFavoriteCount(providerId: Long, contentType: ContentType): Flow<Int> =+ favoriteDao.getGlobalFavoriteCount(providerId, contentType.name)- override fun getGroupFavoriteCounts(contentType: ContentType): Flow<Map<Long, Int>> =- favoriteDao.getGroupFavoriteCounts(contentType.name)+ override fun getGroupFavoriteCounts(providerId: Long, contentType: ContentType): Flow<Map<Long, Int>> =+ favoriteDao.getGroupFavoriteCounts(providerId, contentType.name).map { list -> list.associate { it.categoryId to it.item_count } }override suspend fun addFavorite(+ providerId: Long,contentId: Long,contentType: ContentType,groupId: Long?): Result<Unit> = try {transactionRunner.inTransaction {- val maxPos = favoriteDao.getMaxPosition(groupId) ?: -1+ val maxPos = favoriteDao.getMaxPosition(providerId, groupId) ?: -1val favorite = Favorite(+ providerId = providerId,contentId = contentId,contentType = contentType,- position = maxPos + 1,+ position = if (maxPos < 0) 0 else maxPos + POSITION_STEP,groupId = groupId)favoriteDao.insert(favorite.toEntity())@@ -67,39 +92,48 @@ class FavoriteRepositoryImpl @Inject constructor(Result.error("Failed to add favorite: ${e.message}", e)}- override suspend fun removeFavorite(contentId: Long, contentType: ContentType, groupId: Long?): Result<Unit> = try {- favoriteDao.delete(contentId, contentType.name, groupId)+ override suspend fun removeFavorite(providerId: Long, contentId: Long, contentType: ContentType, groupId: Long?): Result<Unit> = try {+ favoriteDao.delete(providerId, contentId, contentType.name, groupId)Result.success(Unit)} catch (e: Exception) {Result.error("Failed to remove favorite: ${e.message}", e)}override suspend fun reorderFavorites(favorites: List<Favorite>): Result<Unit> = try {- val entities = favorites.mapIndexed { index, fav ->- fav.copy(position = index).toEntity()+ val updates = buildReorderUpdates(favorites)+ if (updates.isNotEmpty()) {+ favoriteDao.updateAll(updates.map(Favorite::toEntity))}- favoriteDao.updateAll(entities)Result.success(Unit)} catch (e: Exception) {Result.error("Failed to reorder favorites: ${e.message}", e)}// Checks if content is in Global Favorites (groupId = null)- override suspend fun isFavorite(contentId: Long, contentType: ContentType): Boolean =- favoriteDao.get(contentId, contentType.name, null) != null+ override suspend fun isFavorite(providerId: Long, contentId: Long, contentType: ContentType): Boolean =+ favoriteDao.get(providerId, contentId, contentType.name, null) != null- override suspend fun getGroupMemberships(contentId: Long, contentType: ContentType): List<Long> =- favoriteDao.getGroupMemberships(contentId, contentType.name)+ override suspend fun getGroupMemberships(providerId: Long, contentId: Long, contentType: ContentType): List<Long> =+ favoriteDao.getGroupMemberships(providerId, contentId, contentType.name)- override suspend fun createGroup(name: String, iconEmoji: String?, contentType: ContentType): Result<VirtualGroup> = try {+ override suspend fun createGroup(providerId: Long, name: String, iconEmoji: String?, contentType: ContentType): Result<VirtualGroup> = try {val id = virtualGroupDao.insert(com.streamvault.data.local.entity.VirtualGroupEntity(+ providerId = providerId,+ name = name,+ iconEmoji = iconEmoji,+ contentType = contentType+ )+ )+ Result.success(+ VirtualGroup(+ id = id,+ providerId = providerId,name = name,iconEmoji = iconEmoji,contentType = contentType))- Result.success(VirtualGroup(id = id, name = name, iconEmoji = iconEmoji, contentType = contentType))} catch (e: Exception) {Result.error("Failed to create group: ${e.message}", e)}@@ -117,4 +151,72 @@ class FavoriteRepositoryImpl @Inject constructor(} catch (e: Exception) {Result.error("Failed to rename group: ${e.message}", e)}++ private fun buildReorderUpdates(favorites: List<Favorite>): List<Favorite> {+ if (favorites.size < 2) return emptyList()++ val currentById = favorites.associateBy(Favorite::id)+ val oldOrder = favorites.sortedBy(Favorite::position).map(Favorite::id)+ val newOrder = favorites.map(Favorite::id)+ if (oldOrder == newOrder) return emptyList()++ val firstMismatch = newOrder.indices.first { index -> newOrder[index] != oldOrder[index] }+ val lastMismatch = newOrder.indices.last { index -> newOrder[index] != oldOrder[index] }++ val localReposition = assignSparsePositions(+ items = favorites.subList(firstMismatch, lastMismatch + 1),+ leftBound = favorites.getOrNull(firstMismatch - 1)?.position?.toLong(),+ rightBound = favorites.getOrNull(lastMismatch + 1)?.position?.toLong()+ )++ val reassigned = localReposition ?: favorites.mapIndexed { index, favorite ->+ favorite.copy(position = index * POSITION_STEP)+ }++ return reassigned.filter { updated ->+ updated.position != currentById.getValue(updated.id).position+ }+ }++ private fun assignSparsePositions(+ items: List<Favorite>,+ leftBound: Long?,+ rightBound: Long?+ ): List<Favorite>? {+ if (items.isEmpty()) return emptyList()++ val positions = when {+ leftBound == null && rightBound == null -> {+ items.indices.map { index -> index.toLong() * POSITION_STEP }+ }++ leftBound == null -> {+ val right = rightBound ?: return null+ if (right <= items.size.toLong()) return null+ val step = right / (items.size + 1L)+ if (step <= 0L) return null+ List(items.size) { index -> step * (index + 1L) }+ }++ rightBound == null -> {+ List(items.size) { index -> leftBound + ((index + 1L) * POSITION_STEP) }+ }++ else -> {+ val gap = rightBound - leftBound - 1L+ if (gap < items.size.toLong()) return null+ val step = gap / (items.size + 1L)+ if (step <= 0L) return null+ List(items.size) { index -> leftBound + (step * (index + 1L)) }+ }+ }++ if (positions.any { it !in 0..Int.MAX_VALUE.toLong() }) return null+ if (positions.zipWithNext().any { (first, second) -> first >= second }) return null+ if (rightBound != null && positions.last() >= rightBound) return null++ return items.zip(positions).map { (favorite, position) ->+ favorite.copy(position = position.toInt())+ }+ }}diff --git a/data/src/main/java/com/streamvault/data/repository/MovieRepositoryImpl.kt b/data/src/main/java/com/streamvault/data/repository/MovieRepositoryImpl.ktindex 8fa2d1ca..77f7b08e 100644--- a/data/src/main/java/com/streamvault/data/repository/MovieRepositoryImpl.kt+++ b/data/src/main/java/com/streamvault/data/repository/MovieRepositoryImpl.kt@@ -1,5 +1,6 @@package com.streamvault.data.repository+import android.database.sqlite.SQLiteExceptionimport com.streamvault.data.local.DatabaseTransactionRunnerimport com.streamvault.data.local.dao.CategoryDaoimport com.streamvault.data.local.dao.FavoriteDao@@ -9,6 +10,7 @@ import com.streamvault.data.local.dao.PlaybackHistoryDaoimport com.streamvault.data.local.dao.ProviderDaoimport com.streamvault.data.local.entity.ProviderEntityimport com.streamvault.data.local.entity.CategoryEntity+import com.streamvault.data.local.entity.MovieBrowseEntityimport com.streamvault.data.local.entity.MovieCategoryHydrationEntityimport com.streamvault.data.mapper.toEntityimport com.streamvault.data.mapper.toDomain@@ -31,6 +33,7 @@ import com.streamvault.domain.model.ProviderTypeimport com.streamvault.domain.model.Resultimport com.streamvault.domain.model.Result.Successimport com.streamvault.domain.model.StreamInfo+import com.streamvault.domain.model.StreamTypeimport com.streamvault.domain.model.VodSyncModeimport com.streamvault.domain.repository.MovieRepositoryimport com.streamvault.domain.repository.SyncMetadataRepository@@ -46,6 +49,7 @@ import kotlinx.coroutines.flow.firstimport kotlinx.coroutines.flow.flowimport kotlinx.coroutines.flow.flowOfimport kotlinx.coroutines.flow.map+import kotlinx.coroutines.flow.catchimport kotlinx.coroutines.launchimport kotlinx.coroutines.withTimeoutimport java.util.concurrent.ConcurrentHashMap@@ -75,6 +79,7 @@ class MovieRepositoryImpl @Inject constructor(const val MIN_SEARCH_QUERY_LENGTH = 2const val BROWSE_WINDOW_BUFFER = 80const val XTREAM_MOVIE_HYDRATION_TIMEOUT_MILLIS = 60_000L+ const val CURSOR_BATCH_SIZE = 40}private data class CachedXtreamProvider(@@ -82,6 +87,24 @@ class MovieRepositoryImpl @Inject constructor(val provider: XtreamProvider)+ private data class NameCursor(+ val name: String,+ val id: Long+ )++ private data class RatingCursor(+ val rating: Float,+ val name: String,+ val id: Long+ )++ private data class FreshCursor(+ val addedAt: Long,+ val releaseDate: String,+ val name: String,+ val id: Long+ )+private val xtreamProviderCache = ConcurrentHashMap<Long, CachedXtreamProvider>()private val xtreamCategoryLoadLocks = ConcurrentHashMap<String, Mutex>()private val freshXtreamCategories = ConcurrentHashMap.newKeySet<String>()@@ -205,7 +228,7 @@ class MovieRepositoryImpl @Inject constructor(combine(getTopRatedPreview(providerId, limit = maxOf(limit * 6, 48)),getFreshPreview(providerId, limit = maxOf(limit * 6, 48)),- favoriteDao.getAllByType(ContentType.MOVIE.name),+ favoriteDao.getAllByType(providerId, ContentType.MOVIE.name),playbackHistoryDao.getRecentlyWatchedByProvider(providerId, limit = maxOf(limit * 4, 24))) { topRated, fresh, favorites, history ->buildRecommendations(@@ -277,45 +300,7 @@ class MovieRepositoryImpl @Inject constructor(refreshStaleInBackground = true)}- emitAll(- combine(- movieBrowseSource(query),- movieBrowseTotalCount(query),- favoriteDao.getAllByType(ContentType.MOVIE.name),- playbackHistoryDao.getByProvider(query.providerId)- ) { movies, totalCount, favorites, history ->- val favoriteIds = favorites- .asSequence()- .filter { it.groupId == null }- .map { it.contentId }- .toSet()- val inProgressIds = history- .asSequence()- .filter { it.contentType == ContentType.MOVIE }- .filter { it.resumePositionMs > 0L && (it.totalDurationMs <= 0L || !moviePlaybackComplete(it.resumePositionMs, it.totalDurationMs)) }- .map { it.contentId }- .toSet()- val watchCounts = history- .asSequence()- .filter { it.contentType == ContentType.MOVIE }- .associate { it.contentId to it.watchCount }-- val browsed = applyMovieBrowseQuery(- movies = movies,- query = query,- favoriteIds = favoriteIds,- inProgressIds = inProgressIds,- watchCounts = watchCounts- )-- PagedResult(- items = browsed.drop(query.offset).take(query.limit),- totalCount = totalCount,- offset = query.offset,- limit = query.limit- )- }- )+ emit(fetchMovieBrowseResult(query))}}@@ -324,7 +309,7 @@ class MovieRepositoryImpl @Inject constructor(if (ftsQuery.isNullOrBlank()) {flowOf(emptyList())} else combine(- movieDao.search(providerId, ftsQuery, SEARCH_RESULT_LIMIT),+ safeMovieSearchFlow(movieDao.search(providerId, ftsQuery, SEARCH_RESULT_LIMIT)),preferencesRepository.parentalControlLevel) { entities, level: Int ->if (level == 2) {@@ -335,6 +320,9 @@ class MovieRepositoryImpl @Inject constructor(}.map { list ->list.map { it.toDomain() }.rankSearchResults(query) { it.name }+ }.combine(favoriteDao.getAllByType(providerId, ContentType.MOVIE.name)) { movies, favorites ->+ val favoriteIds = favorites.map { it.contentId }.toSet()+ movies.map { if (it.id in favoriteIds) it.copy(isFavorite = true) else it }}}@@ -395,10 +383,13 @@ class MovieRepositoryImpl @Inject constructor(fallbackContentType = ContentType.MOVIE,fallbackContainerExtension = movie.containerExtension)?.let { resolvedStream ->+ val ext = resolvedStream.containerExtension ?: movie.containerExtensionResult.success(StreamInfo(url = resolvedStream.url,title = movie.name,+ streamType = StreamType.fromContainerExtension(ext),+ containerExtension = ext,expirationTime = resolvedStream.expirationTime))@@ -531,7 +522,7 @@ class MovieRepositoryImpl @Inject constructor(val ftsQuery = normalizedSearch.toFtsPrefixQuery() ?: return flowOf(emptyList())query.categoryId?.let { categoryId ->combine(- movieDao.searchByCategory(query.providerId, categoryId, ftsQuery, SEARCH_RESULT_LIMIT),+ safeMovieSearchFlow(movieDao.searchByCategory(query.providerId, categoryId, ftsQuery, SEARCH_RESULT_LIMIT)),preferencesRepository.parentalControlLevel) { entities, level ->if (level == 2) entities.filter { !it.isUserProtected } else entities@@ -740,6 +731,180 @@ class MovieRepositoryImpl @Inject constructor(private fun browseFetchLimit(query: LibraryBrowseQuery): Int =(query.offset + query.limit + BROWSE_WINDOW_BUFFER).coerceAtMost(SEARCH_RESULT_LIMIT)+ private suspend fun fetchMovieBrowseResult(query: LibraryBrowseQuery): PagedResult<Movie> {+ val totalCount = movieBrowseTotalCount(query).first()+ val favoriteIds = favoriteDao.getAllByType(query.providerId, ContentType.MOVIE.name)+ .first()+ .asSequence()+ .filter { it.groupId == null }+ .map { it.contentId }+ .toSet()++ val items = if (supportsCursorBrowse(query)) {+ fetchMovieCursorWindow(query, favoriteIds)+ } else {+ val movies = movieBrowseSource(query).first()+ val history = playbackHistoryDao.getByProvider(query.providerId).first()+ val inProgressIds = history+ .asSequence()+ .filter { it.contentType == ContentType.MOVIE }+ .filter { it.resumePositionMs > 0L && (it.totalDurationMs <= 0L || !moviePlaybackComplete(it.resumePositionMs, it.totalDurationMs)) }+ .map { it.contentId }+ .toSet()+ val watchCounts = history+ .asSequence()+ .filter { it.contentType == ContentType.MOVIE }+ .associate { it.contentId to it.watchCount }++ applyMovieBrowseQuery(+ movies = movies,+ query = query,+ favoriteIds = favoriteIds,+ inProgressIds = inProgressIds,+ watchCounts = watchCounts+ ).drop(query.offset).take(query.limit)+ }++ return PagedResult(+ items = items,+ totalCount = totalCount,+ offset = query.offset,+ limit = query.limit+ )+ }++ private suspend fun fetchMovieCursorWindow(+ query: LibraryBrowseQuery,+ favoriteIds: Set<Long>+ ): List<Movie> {+ val parentalLevel = preferencesRepository.parentalControlLevel.first()+ val targetVisibleCount = (query.offset + query.limit).coerceAtLeast(query.limit)+ val collected = ArrayList<Movie>(targetVisibleCount)++ when {+ query.filterBy.type == LibraryFilterType.ALL &&+ query.sortBy in setOf(LibrarySortBy.LIBRARY, LibrarySortBy.TITLE) -> {+ collectMoviePages<NameCursor>(query, parentalLevel, collected, favoriteIds) { limit, cursor ->+ loadMovieNamePage(query, limit, cursor)+ }+ }+ (query.sortBy == LibrarySortBy.RATING || query.filterBy.type == LibraryFilterType.TOP_RATED) -> {+ collectMoviePages<RatingCursor>(query, parentalLevel, collected, favoriteIds) { limit, cursor ->+ loadMovieRatingPage(query, limit, cursor)+ }+ }+ (+ query.sortBy == LibrarySortBy.RELEASE ||+ query.sortBy == LibrarySortBy.UPDATED ||+ query.filterBy.type == LibraryFilterType.RECENTLY_UPDATED+ ) -> {+ collectMoviePages<FreshCursor>(query, parentalLevel, collected, favoriteIds) { limit, cursor ->+ loadMovieFreshPage(query, limit, cursor)+ }+ }+ }++ return collected.drop(query.offset).take(query.limit)+ }++ private suspend fun <C> collectMoviePages(+ query: LibraryBrowseQuery,+ parentalLevel: Int,+ collected: MutableList<Movie>,+ favoriteIds: Set<Long>,+ loadPage: suspend (limit: Int, cursor: C?) -> List<MovieBrowseEntity>+ ) {+ var cursor: C? = null+ val targetVisibleCount = query.offset + query.limit+ while (collected.size < targetVisibleCount) {+ val batch = loadPage(CURSOR_BATCH_SIZE, cursor)+ if (batch.isEmpty()) {+ return+ }+ val visibleBatch = if (parentalLevel == 2) {+ batch.filterNot { it.isUserProtected }+ } else {+ batch+ }+ collected += visibleBatch.map { entity ->+ val movie = entity.toDomain()+ if (movie.id in favoriteIds) movie.copy(isFavorite = true) else movie+ }+ if (batch.size < CURSOR_BATCH_SIZE) {+ return+ }+ @Suppress("UNCHECKED_CAST")+ cursor = cursorFromQuery(query, batch.last()) as C+ }+ }++ private fun cursorFromQuery(query: LibraryBrowseQuery, entity: MovieBrowseEntity): Any = when {+ query.filterBy.type == LibraryFilterType.ALL &&+ query.sortBy in setOf(LibrarySortBy.LIBRARY, LibrarySortBy.TITLE) -> NameCursor(entity.name, entity.id)+ query.sortBy == LibrarySortBy.RATING || query.filterBy.type == LibraryFilterType.TOP_RATED ->+ RatingCursor(entity.rating, entity.name, entity.id)+ else ->+ FreshCursor(entity.addedAt, entity.releaseDate.orEmpty(), entity.name, entity.id)+ }++ private suspend fun loadMovieNamePage(query: LibraryBrowseQuery, limit: Int, cursor: NameCursor?): List<MovieBrowseEntity> {+ val categoryId = query.categoryId+ return if (categoryId == null) {+ if (cursor == null) movieDao.getByProviderCursorPage(query.providerId, limit)+ else movieDao.getByProviderCursorPageAfter(query.providerId, cursor.name, cursor.id, limit)+ } else {+ if (cursor == null) movieDao.getByCategoryCursorPage(query.providerId, categoryId, limit)+ else movieDao.getByCategoryCursorPageAfter(query.providerId, categoryId, cursor.name, cursor.id, limit)+ }+ }++ private suspend fun loadMovieRatingPage(query: LibraryBrowseQuery, limit: Int, cursor: RatingCursor?): List<MovieBrowseEntity> {+ val categoryId = query.categoryId+ return if (categoryId == null) {+ if (cursor == null) movieDao.getTopRatedCursorPage(query.providerId, limit)+ else movieDao.getTopRatedCursorPageAfter(query.providerId, cursor.rating, cursor.name, cursor.id, limit)+ } else {+ if (cursor == null) movieDao.getTopRatedByCategoryCursorPage(query.providerId, categoryId, limit)+ else movieDao.getTopRatedByCategoryCursorPageAfter(query.providerId, categoryId, cursor.rating, cursor.name, cursor.id, limit)+ }+ }++ private suspend fun loadMovieFreshPage(query: LibraryBrowseQuery, limit: Int, cursor: FreshCursor?): List<MovieBrowseEntity> {+ val categoryId = query.categoryId+ return if (categoryId == null) {+ if (cursor == null) movieDao.getFreshCursorPage(query.providerId, limit)+ else movieDao.getFreshCursorPageAfter(query.providerId, cursor.addedAt, cursor.releaseDate, cursor.name, cursor.id, limit)+ } else {+ if (cursor == null) movieDao.getFreshByCategoryCursorPage(query.providerId, categoryId, limit)+ else movieDao.getFreshByCategoryCursorPageAfter(+ query.providerId,+ categoryId,+ cursor.addedAt,+ cursor.releaseDate,+ cursor.name,+ cursor.id,+ limit+ )+ }+ }++ private fun supportsCursorBrowse(query: LibraryBrowseQuery): Boolean {+ if (query.searchQuery.isNotBlank()) return false+ return when {+ query.filterBy.type == LibraryFilterType.ALL &&+ query.sortBy in setOf(+ LibrarySortBy.LIBRARY,+ LibrarySortBy.TITLE,+ LibrarySortBy.RELEASE,+ LibrarySortBy.UPDATED,+ LibrarySortBy.RATING+ ) -> true+ query.filterBy.type == LibraryFilterType.TOP_RATED -> true+ query.filterBy.type == LibraryFilterType.RECENTLY_UPDATED -> true+ else -> false+ }+ }+private fun applyMovieBrowseQuery(movies: List<Movie>,query: LibraryBrowseQuery,@@ -786,6 +951,15 @@ class MovieRepositoryImpl @Inject constructor(.any { value -> value.lowercase().contains(normalizedQuery) }}+ private fun safeMovieSearchFlow(source: Flow<List<MovieBrowseEntity>>): Flow<List<MovieBrowseEntity>> =+ source.catch { error ->+ if (error is SQLiteException) {+ emit(emptyList<MovieBrowseEntity>())+ } else {+ throw error+ }+ }+private suspend fun ensureXtreamCategoryLoaded(providerId: Long,categoryId: Long,@@ -931,9 +1105,8 @@ class MovieRepositoryImpl @Inject constructor(}private fun movieReleaseScore(movie: Movie): Long =- movie.releaseDate- ?.filter { it.isDigit() }- ?.toLongOrNull()+ movie.addedAt.takeIf { it > 0L }+ ?: movie.releaseDate?.filter { it.isDigit() }?.toLongOrNull()?: movie.year?.toLongOrNull()?: 0Ldiff --git a/data/src/main/java/com/streamvault/data/repository/PlaybackHistoryRepositoryImpl.kt b/data/src/main/java/com/streamvault/data/repository/PlaybackHistoryRepositoryImpl.ktindex dec717a6..1ce67f91 100644--- a/data/src/main/java/com/streamvault/data/repository/PlaybackHistoryRepositoryImpl.kt+++ b/data/src/main/java/com/streamvault/data/repository/PlaybackHistoryRepositoryImpl.kt@@ -11,9 +11,17 @@ import com.streamvault.domain.model.PlaybackHistoryimport com.streamvault.domain.model.PlaybackWatchedStatusimport com.streamvault.domain.model.Resultimport com.streamvault.domain.repository.PlaybackHistoryRepository+import java.util.concurrent.ConcurrentHashMap+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.delay+import kotlinx.coroutines.launchimport kotlinx.coroutines.flow.Flow-import kotlinx.coroutines.flow.firstimport kotlinx.coroutines.flow.map+import kotlinx.coroutines.flow.SharingStarted+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.stateInimport javax.inject.Injectimport javax.inject.Singletonimport com.streamvault.data.preferences.PreferencesRepository@@ -27,6 +35,20 @@ class PlaybackHistoryRepositoryImpl @Inject constructor(private val episodeDao: EpisodeDao,private val transactionRunner: DatabaseTransactionRunner) : PlaybackHistoryRepository {+ private val repositoryScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)+ private val pendingResumeUpdates = ConcurrentHashMap<PlaybackKey, PlaybackHistory>()+ private val isIncognito: StateFlow<Boolean> =+ preferencesRepository.isIncognitoMode+ .stateIn(repositoryScope, SharingStarted.Eagerly, false)++ init {+ repositoryScope.launch {+ while (true) {+ delay(RESUME_POSITION_FLUSH_INTERVAL_MS)+ flushPendingResumeUpdates()+ }+ }+ }override fun getRecentlyWatched(limit: Int): Flow<List<PlaybackHistory>> {return dao.getRecentlyWatched(limit).map { list -> list.map { it.toDomain() } }@@ -45,16 +67,27 @@ class PlaybackHistoryRepositoryImpl @Inject constructor(}override suspend fun getPlaybackHistory(contentId: Long, contentType: ContentType, providerId: Long): PlaybackHistory? {- return dao.get(contentId, contentType.name, providerId)?.toDomain()+ val directMatch = dao.get(contentId, contentType.name, providerId)?.toDomain()+ if (directMatch != null) {+ return directMatch+ }++ return when (contentType) {+ ContentType.MOVIE -> dao.getLatestMovieHistoryBySharedTmdb(contentId, providerId)?.toDomain()+ ContentType.SERIES -> dao.getLatestSeriesHistoryBySharedTmdb(contentId, providerId)?.toDomain()+ ContentType.SERIES_EPISODE,+ ContentType.LIVE -> null+ }}override suspend fun markAsWatched(history: PlaybackHistory): Result<Unit> {return try {- if (preferencesRepository.isIncognitoMode.first()) {+ if (isIncognito.value) {return Result.success(Unit)}- val existing = dao.get(history.contentId, history.contentType.name, history.providerId)+ val existing = takePendingResumeUpdate(history.playbackKey())+ ?: dao.get(history.contentId, history.contentType.name, history.providerId)?.toDomain()val resolvedTotalDuration = history.totalDurationMs.takeIf { it > 0L } ?: existing?.totalDurationMs ?: 0Lval resolvedResumePosition = when {resolvedTotalDuration > 0L -> resolvedTotalDuration@@ -81,11 +114,12 @@ class PlaybackHistoryRepositoryImpl @Inject constructor(override suspend fun recordPlayback(history: PlaybackHistory): Result<Unit> {return try {- if (preferencesRepository.isIncognitoMode.first()) {+ if (isIncognito.value) {return Result.success(Unit)}- val existing = dao.get(history.contentId, history.contentType.name, history.providerId)+ val existing = takePendingResumeUpdate(history.playbackKey())+ ?: dao.get(history.contentId, history.contentType.name, history.providerId)?.toDomain()val updatedHistory = history.copy(streamUrl = XtreamUrlFactory.sanitizePersistedStreamUrl(history.streamUrl, history.providerId),resumePositionMs = history.resumePositionMs.takeIf { it > 0L } ?: existing?.resumePositionMs ?: 0L,@@ -110,12 +144,12 @@ class PlaybackHistoryRepositoryImpl @Inject constructor(override suspend fun updateResumePosition(history: PlaybackHistory): Result<Unit> {return try {- if (preferencesRepository.isIncognitoMode.first()) {+ if (isIncognito.value) {return Result.success(Unit)}- val existing = dao.get(history.contentId, history.contentType.name, history.providerId)- val existingWatchedStatus = existing?.toDomain()?.watchedStatus+ val existing = pendingResumeUpdates[history.playbackKey()]+ ?: dao.get(history.contentId, history.contentType.name, history.providerId)?.toDomain()val updatedHistory = history.copy(streamUrl = XtreamUrlFactory.sanitizePersistedStreamUrl(history.streamUrl, history.providerId),@@ -123,14 +157,11 @@ class PlaybackHistoryRepositoryImpl @Inject constructor(watchedStatus = resolveWatchedStatus(resumePositionMs = history.resumePositionMs,totalDurationMs = history.totalDurationMs,- fallback = existingWatchedStatus ?: history.watchedStatus+ fallback = existing?.watchedStatus ?: history.watchedStatus),lastWatchedAt = System.currentTimeMillis())- transactionRunner.inTransaction {- dao.insertOrUpdate(updatedHistory.toEntity())- syncDenormalizedProgress(updatedHistory.contentId, updatedHistory.contentType, updatedHistory.providerId)- }+ pendingResumeUpdates[history.playbackKey()] = updatedHistoryResult.success(Unit)} catch (e: Exception) {Result.error("Failed to update playback resume position", e)@@ -138,6 +169,7 @@ class PlaybackHistoryRepositoryImpl @Inject constructor(}override suspend fun removeFromHistory(contentId: Long, contentType: ContentType, providerId: Long): Result<Unit> = try {+ pendingResumeUpdates.remove(PlaybackKey(contentId, contentType, providerId))transactionRunner.inTransaction {dao.delete(contentId, contentType.name, providerId)syncDenormalizedProgress(contentId, contentType, providerId)@@ -148,9 +180,11 @@ class PlaybackHistoryRepositoryImpl @Inject constructor(}override suspend fun clearAllHistory(): Result<Unit> = try {+ pendingResumeUpdates.clear()transactionRunner.inTransaction {dao.deleteAll()- syncAllDenormalizedProgress()+ movieDao.resetAllWatchProgress()+ episodeDao.resetAllWatchProgress()}Result.success(Unit)} catch (e: Exception) {@@ -158,6 +192,7 @@ class PlaybackHistoryRepositoryImpl @Inject constructor(}override suspend fun clearHistoryForProvider(providerId: Long): Result<Unit> = try {+ pendingResumeUpdates.keys.removeIf { it.providerId == providerId }transactionRunner.inTransaction {dao.deleteByProvider(providerId)syncDenormalizedProgressForProvider(providerId)@@ -167,6 +202,29 @@ class PlaybackHistoryRepositoryImpl @Inject constructor(Result.error("Failed to clear provider playback history", e)}+ override suspend fun clearLiveHistoryForProvider(providerId: Long): Result<Unit> = try {+ pendingResumeUpdates.keys.removeIf { it.providerId == providerId && it.contentType == ContentType.LIVE }+ dao.deleteByProviderAndType(providerId, ContentType.LIVE.name)+ Result.success(Unit)+ } catch (e: Exception) {+ Result.error("Failed to clear live playback history", e)+ }++ private suspend fun flushPendingResumeUpdates() {+ val snapshot = pendingResumeUpdates.entries.toList()+ snapshot.forEach { (key, history) ->+ if (pendingResumeUpdates.remove(key, history)) {+ transactionRunner.inTransaction {+ dao.insertOrUpdate(history.toEntity())+ syncDenormalizedProgress(history.contentId, history.contentType, history.providerId)+ }+ }+ }+ }++ private fun takePendingResumeUpdate(key: PlaybackKey): PlaybackHistory? =+ pendingResumeUpdates.remove(key)+private suspend fun syncDenormalizedProgress(contentId: Long, contentType: ContentType, providerId: Long) {when (contentType) {ContentType.MOVIE -> movieDao.syncWatchProgressFromHistory(contentId, providerId)@@ -179,12 +237,6 @@ class PlaybackHistoryRepositoryImpl @Inject constructor(movieDao.syncWatchProgressFromHistoryByProvider(providerId)episodeDao.syncWatchProgressFromHistoryByProvider(providerId)}-- private suspend fun syncAllDenormalizedProgress() {- movieDao.syncAllWatchProgressFromHistory()- episodeDao.syncAllWatchProgressFromHistory()- }-private fun resolveWatchedStatus(resumePositionMs: Long,totalDurationMs: Long,@@ -202,6 +254,13 @@ class PlaybackHistoryRepositoryImpl @Inject constructor(}private const val DEFAULT_PLAYBACK_COMPLETION_THRESHOLD = 0.95f+private const val RESUME_POSITION_FLUSH_INTERVAL_MS = 30_000L++private data class PlaybackKey(+ val contentId: Long,+ val contentType: ContentType,+ val providerId: Long+)private fun isPlaybackComplete(progressMs: Long,@@ -213,3 +272,6 @@ private fun isPlaybackComplete(}return progressMs >= (totalDurationMs * threshold).toLong()}++private fun PlaybackHistory.playbackKey(): PlaybackKey =+ PlaybackKey(contentId = contentId, contentType = contentType, providerId = providerId)diff --git a/data/src/main/java/com/streamvault/data/repository/ProviderRepositoryImpl.kt b/data/src/main/java/com/streamvault/data/repository/ProviderRepositoryImpl.ktindex 9bfdd3c3..28094073 100644--- a/data/src/main/java/com/streamvault/data/repository/ProviderRepositoryImpl.kt+++ b/data/src/main/java/com/streamvault/data/repository/ProviderRepositoryImpl.kt@@ -533,6 +533,7 @@ class ProviderRepositoryImpl @Inject constructor(val now = System.currentTimeMillis()val metadata = (syncMetadataRepository.getMetadata(providerId) ?: SyncMetadata(providerId)).copy(lastEpgSync = now,+ lastEpgSuccess = now,epgCount = programDao.countByProvider(providerId))syncMetadataRepository.updateMetadata(metadata)diff --git a/data/src/main/java/com/streamvault/data/repository/SeriesRepositoryImpl.kt b/data/src/main/java/com/streamvault/data/repository/SeriesRepositoryImpl.ktindex 2c89a707..41bea9ba 100644--- a/data/src/main/java/com/streamvault/data/repository/SeriesRepositoryImpl.kt+++ b/data/src/main/java/com/streamvault/data/repository/SeriesRepositoryImpl.kt@@ -1,5 +1,6 @@package com.streamvault.data.repository+import android.database.sqlite.SQLiteExceptionimport com.streamvault.data.local.dao.*import com.streamvault.data.local.entity.*import com.streamvault.data.mapper.*@@ -24,6 +25,7 @@ import kotlinx.coroutines.flow.flatMapLatestimport kotlinx.coroutines.flow.flowimport kotlinx.coroutines.flow.flowOfimport kotlinx.coroutines.flow.map+import kotlinx.coroutines.flow.catchimport kotlinx.coroutines.launchimport kotlinx.coroutines.withTimeoutimport com.streamvault.data.util.toFtsPrefixQuery@@ -56,6 +58,7 @@ class SeriesRepositoryImpl @Inject constructor(const val MIN_SEARCH_QUERY_LENGTH = 2const val BROWSE_WINDOW_BUFFER = 80const val XTREAM_SERIES_CATEGORY_TIMEOUT_MILLIS = 60_000L+ const val CURSOR_BATCH_SIZE = 40}private data class CachedXtreamProvider(@@ -63,6 +66,23 @@ class SeriesRepositoryImpl @Inject constructor(val provider: XtreamProvider)+ private data class NameCursor(+ val name: String,+ val id: Long+ )++ private data class RatingCursor(+ val rating: Float,+ val name: String,+ val id: Long+ )++ private data class FreshCursor(+ val lastModified: Long,+ val name: String,+ val id: Long+ )+private val xtreamProviderCache = ConcurrentHashMap<Long, CachedXtreamProvider>()private val xtreamCategoryLoadLocks = ConcurrentHashMap<String, Mutex>()private val loadedXtreamCategories = ConcurrentHashMap.newKeySet<String>()@@ -221,51 +241,7 @@ class SeriesRepositoryImpl @Inject constructor(override fun browseSeries(query: LibraryBrowseQuery): Flow<PagedResult<Series>> {return flow {query.categoryId?.let { ensureXtreamCategoryLoaded(query.providerId, it) }- emitAll(- combine(- seriesBrowseSource(query),- seriesBrowseTotalCount(query),- favoriteDao.getAllByType(ContentType.SERIES.name),- playbackHistoryDao.getByProvider(query.providerId)- ) { series, totalCount, favorites, history ->- val favoriteIds = favorites- .asSequence()- .filter { it.groupId == null }- .map { it.contentId }- .toSet()- val inProgressIds = history- .asSequence()- .filter { it.contentType == ContentType.SERIES || it.contentType == ContentType.SERIES_EPISODE }- .filter {- it.resumePositionMs > 0L && (- it.totalDurationMs <= 0L ||- it.resumePositionMs < (it.totalDurationMs * 0.95f).toLong()- )- }- .mapNotNull { it.seriesId ?: it.contentId }- .toSet()- val watchCounts = history- .asSequence()- .filter { it.contentType == ContentType.SERIES || it.contentType == ContentType.SERIES_EPISODE }- .groupBy { it.seriesId ?: it.contentId }- .mapValues { (_, entries) -> entries.maxOf { it.watchCount } }-- val browsed = applySeriesBrowseQuery(- series = series,- query = query,- favoriteIds = favoriteIds,- inProgressIds = inProgressIds,- watchCounts = watchCounts- )-- PagedResult(- items = browsed.drop(query.offset).take(query.limit),- totalCount = totalCount,- offset = query.offset,- limit = query.limit- )- }- )+ emit(fetchSeriesBrowseResult(query))}}@@ -274,7 +250,7 @@ class SeriesRepositoryImpl @Inject constructor(if (ftsQuery.isNullOrBlank()) {flowOf(emptyList())} else combine(- seriesDao.search(providerId, ftsQuery, SEARCH_RESULT_LIMIT),+ safeSeriesSearchFlow(seriesDao.search(providerId, ftsQuery, SEARCH_RESULT_LIMIT)),preferencesRepository.parentalControlLevel) { entities, level: Int ->if (level == 2) {@@ -285,6 +261,9 @@ class SeriesRepositoryImpl @Inject constructor(}.map { list ->list.map { it.toDomain() }.rankSearchResults(query) { it.name }+ }.combine(favoriteDao.getAllByType(providerId, ContentType.SERIES.name)) { series, favorites ->+ val favoriteIds = favorites.map { it.contentId }.toSet()+ series.map { if (it.id in favoriteIds) it.copy(isFavorite = true) else it }}}@@ -413,10 +392,13 @@ class SeriesRepositoryImpl @Inject constructor(fallbackContentType = ContentType.SERIES_EPISODE,fallbackContainerExtension = episode.containerExtension)?.let { resolvedStream ->+ val ext = resolvedStream.containerExtension ?: episode.containerExtensionResult.success(StreamInfo(url = resolvedStream.url,title = episode.title,+ streamType = StreamType.fromContainerExtension(ext),+ containerExtension = ext,expirationTime = resolvedStream.expirationTime))@@ -459,7 +441,7 @@ class SeriesRepositoryImpl @Inject constructor(val ftsQuery = normalizedSearch.toFtsPrefixQuery() ?: return flowOf(emptyList())query.categoryId?.let { categoryId ->combine(- seriesDao.searchByCategory(query.providerId, categoryId, ftsQuery, SEARCH_RESULT_LIMIT),+ safeSeriesSearchFlow(seriesDao.searchByCategory(query.providerId, categoryId, ftsQuery, SEARCH_RESULT_LIMIT)),preferencesRepository.parentalControlLevel) { entities, level ->if (level == 2) entities.filter { !it.isUserProtected } else entities@@ -668,6 +650,175 @@ class SeriesRepositoryImpl @Inject constructor(private fun browseFetchLimit(query: LibraryBrowseQuery): Int =(query.offset + query.limit + BROWSE_WINDOW_BUFFER).coerceAtMost(SEARCH_RESULT_LIMIT)+ private suspend fun fetchSeriesBrowseResult(query: LibraryBrowseQuery): PagedResult<Series> {+ val totalCount = seriesBrowseTotalCount(query).first()+ val favoriteIds = favoriteDao.getAllByType(query.providerId, ContentType.SERIES.name)+ .first()+ .asSequence()+ .filter { it.groupId == null }+ .map { it.contentId }+ .toSet()++ val items = if (supportsCursorBrowse(query)) {+ fetchSeriesCursorWindow(query, favoriteIds)+ } else {+ val series = seriesBrowseSource(query).first()+ val history = playbackHistoryDao.getByProvider(query.providerId).first()+ val inProgressIds = history+ .asSequence()+ .filter { it.contentType == ContentType.SERIES || it.contentType == ContentType.SERIES_EPISODE }+ .filter {+ it.resumePositionMs > 0L && (+ it.totalDurationMs <= 0L ||+ it.resumePositionMs < (it.totalDurationMs * 0.95f).toLong()+ )+ }+ .mapNotNull { it.seriesId ?: it.contentId }+ .toSet()+ val watchCounts = history+ .asSequence()+ .filter { it.contentType == ContentType.SERIES || it.contentType == ContentType.SERIES_EPISODE }+ .groupBy { it.seriesId ?: it.contentId }+ .mapValues { (_, entries) -> entries.maxOf { it.watchCount } }++ applySeriesBrowseQuery(+ series = series,+ query = query,+ favoriteIds = favoriteIds,+ inProgressIds = inProgressIds,+ watchCounts = watchCounts+ ).drop(query.offset).take(query.limit)+ }++ return PagedResult(+ items = items,+ totalCount = totalCount,+ offset = query.offset,+ limit = query.limit+ )+ }++ private suspend fun fetchSeriesCursorWindow(+ query: LibraryBrowseQuery,+ favoriteIds: Set<Long>+ ): List<Series> {+ val parentalLevel = preferencesRepository.parentalControlLevel.first()+ val targetVisibleCount = (query.offset + query.limit).coerceAtLeast(query.limit)+ val collected = ArrayList<Series>(targetVisibleCount)++ when {+ query.filterBy.type == LibraryFilterType.ALL &&+ query.sortBy in setOf(LibrarySortBy.LIBRARY, LibrarySortBy.TITLE) -> {+ collectSeriesPages<NameCursor>(query, parentalLevel, collected, favoriteIds) { limit, cursor ->+ loadSeriesNamePage(query, limit, cursor)+ }+ }+ (query.sortBy == LibrarySortBy.RATING || query.filterBy.type == LibraryFilterType.TOP_RATED) -> {+ collectSeriesPages<RatingCursor>(query, parentalLevel, collected, favoriteIds) { limit, cursor ->+ loadSeriesRatingPage(query, limit, cursor)+ }+ }+ query.sortBy == LibrarySortBy.RELEASE ||+ query.sortBy == LibrarySortBy.UPDATED ||+ query.filterBy.type == LibraryFilterType.RECENTLY_UPDATED -> {+ collectSeriesPages<FreshCursor>(query, parentalLevel, collected, favoriteIds) { limit, cursor ->+ loadSeriesFreshPage(query, limit, cursor)+ }+ }+ }++ return collected.drop(query.offset).take(query.limit)+ }++ private suspend fun <C> collectSeriesPages(+ query: LibraryBrowseQuery,+ parentalLevel: Int,+ collected: MutableList<Series>,+ favoriteIds: Set<Long>,+ loadPage: suspend (limit: Int, cursor: C?) -> List<SeriesBrowseEntity>+ ) {+ var cursor: C? = null+ val targetVisibleCount = query.offset + query.limit+ while (collected.size < targetVisibleCount) {+ val batch = loadPage(CURSOR_BATCH_SIZE, cursor)+ if (batch.isEmpty()) {+ return+ }+ val visibleBatch = if (parentalLevel == 2) {+ batch.filterNot { it.isUserProtected }+ } else {+ batch+ }+ collected += visibleBatch.map { entity ->+ val item = entity.toDomain()+ if (item.id in favoriteIds) item.copy(isFavorite = true) else item+ }+ if (batch.size < CURSOR_BATCH_SIZE) {+ return+ }+ @Suppress("UNCHECKED_CAST")+ cursor = cursorFromQuery(query, batch.last()) as C+ }+ }++ private fun cursorFromQuery(query: LibraryBrowseQuery, entity: SeriesBrowseEntity): Any = when {+ query.filterBy.type == LibraryFilterType.ALL &&+ query.sortBy in setOf(LibrarySortBy.LIBRARY, LibrarySortBy.TITLE) -> NameCursor(entity.name, entity.id)+ query.sortBy == LibrarySortBy.RATING || query.filterBy.type == LibraryFilterType.TOP_RATED ->+ RatingCursor(entity.rating, entity.name, entity.id)+ else -> FreshCursor(entity.lastModified, entity.name, entity.id)+ }++ private suspend fun loadSeriesNamePage(query: LibraryBrowseQuery, limit: Int, cursor: NameCursor?): List<SeriesBrowseEntity> {+ val categoryId = query.categoryId+ return if (categoryId == null) {+ if (cursor == null) seriesDao.getByProviderCursorPage(query.providerId, limit)+ else seriesDao.getByProviderCursorPageAfter(query.providerId, cursor.name, cursor.id, limit)+ } else {+ if (cursor == null) seriesDao.getByCategoryCursorPage(query.providerId, categoryId, limit)+ else seriesDao.getByCategoryCursorPageAfter(query.providerId, categoryId, cursor.name, cursor.id, limit)+ }+ }++ private suspend fun loadSeriesRatingPage(query: LibraryBrowseQuery, limit: Int, cursor: RatingCursor?): List<SeriesBrowseEntity> {+ val categoryId = query.categoryId+ return if (categoryId == null) {+ if (cursor == null) seriesDao.getTopRatedCursorPage(query.providerId, limit)+ else seriesDao.getTopRatedCursorPageAfter(query.providerId, cursor.rating, cursor.name, cursor.id, limit)+ } else {+ if (cursor == null) seriesDao.getTopRatedByCategoryCursorPage(query.providerId, categoryId, limit)+ else seriesDao.getTopRatedByCategoryCursorPageAfter(query.providerId, categoryId, cursor.rating, cursor.name, cursor.id, limit)+ }+ }++ private suspend fun loadSeriesFreshPage(query: LibraryBrowseQuery, limit: Int, cursor: FreshCursor?): List<SeriesBrowseEntity> {+ val categoryId = query.categoryId+ return if (categoryId == null) {+ if (cursor == null) seriesDao.getFreshCursorPage(query.providerId, limit)+ else seriesDao.getFreshCursorPageAfter(query.providerId, cursor.lastModified, cursor.name, cursor.id, limit)+ } else {+ if (cursor == null) seriesDao.getFreshByCategoryCursorPage(query.providerId, categoryId, limit)+ else seriesDao.getFreshByCategoryCursorPageAfter(query.providerId, categoryId, cursor.lastModified, cursor.name, cursor.id, limit)+ }+ }++ private fun supportsCursorBrowse(query: LibraryBrowseQuery): Boolean {+ if (query.searchQuery.isNotBlank()) return false+ return when {+ query.filterBy.type == LibraryFilterType.ALL &&+ query.sortBy in setOf(+ LibrarySortBy.LIBRARY,+ LibrarySortBy.TITLE,+ LibrarySortBy.RELEASE,+ LibrarySortBy.UPDATED,+ LibrarySortBy.RATING+ ) -> true+ query.filterBy.type == LibraryFilterType.TOP_RATED -> true+ query.filterBy.type == LibraryFilterType.RECENTLY_UPDATED -> true+ else -> false+ }+ }+private fun applySeriesBrowseQuery(series: List<Series>,query: LibraryBrowseQuery,@@ -712,6 +863,15 @@ class SeriesRepositoryImpl @Inject constructor(.any { value -> value.lowercase().contains(normalizedQuery) }}+ private fun safeSeriesSearchFlow(source: Flow<List<SeriesBrowseEntity>>): Flow<List<SeriesBrowseEntity>> =+ source.catch { error ->+ if (error is SQLiteException) {+ emit(emptyList<SeriesBrowseEntity>())+ } else {+ throw error+ }+ }+private suspend fun ensureXtreamCategoryLoaded(providerId: Long, categoryId: Long) {val key = "$providerId:$categoryId"if (loadedXtreamCategories.contains(key)) returndiff --git a/data/src/main/java/com/streamvault/data/sync/BackgroundEpgSyncWorker.kt b/data/src/main/java/com/streamvault/data/sync/BackgroundEpgSyncWorker.ktnew file mode 100644index 00000000..4fccf366--- /dev/null+++ b/data/src/main/java/com/streamvault/data/sync/BackgroundEpgSyncWorker.kt@@ -0,0 +1,109 @@+package com.streamvault.data.sync++import android.content.Context+import android.database.sqlite.SQLiteException+import android.util.Log+import androidx.work.BackoffPolicy+import androidx.work.Constraints+import androidx.work.CoroutineWorker+import androidx.work.Data+import androidx.work.ExistingWorkPolicy+import androidx.work.NetworkType+import androidx.work.OneTimeWorkRequestBuilder+import androidx.work.WorkManager+import androidx.work.WorkRequest+import androidx.work.WorkerParameters+import dagger.hilt.EntryPoint+import dagger.hilt.InstallIn+import dagger.hilt.android.EntryPointAccessors+import dagger.hilt.components.SingletonComponent+import java.util.concurrent.TimeUnit++class BackgroundEpgSyncWorker(+ appContext: Context,+ workerParams: WorkerParameters+) : CoroutineWorker(appContext, workerParams) {++ @EntryPoint+ @InstallIn(SingletonComponent::class)+ interface BackgroundEpgSyncWorkerEntryPoint {+ fun syncManager(): SyncManager+ }++ override suspend fun doWork(): Result {+ val providerId = inputData.getLong(KEY_PROVIDER_ID, INVALID_PROVIDER_ID)+ if (providerId == INVALID_PROVIDER_ID) {+ return Result.failure()+ }++ return try {+ val entryPoint = EntryPointAccessors.fromApplication(+ applicationContext,+ BackgroundEpgSyncWorkerEntryPoint::class.java+ )+ when (val result = entryPoint.syncManager().syncEpg(providerId, force = true)) {+ is com.streamvault.domain.model.Result.Success -> Result.success()+ 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()+ }+ } catch (e: Exception) {+ Log.e(TAG, "Background EPG work failed for provider $providerId", e)+ if (shouldRetry(e)) Result.retry() else Result.failure()+ }+ }++ 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+ }+ }++ companion object {+ private const val TAG = "BackgroundEpgWorker"+ private const val KEY_PROVIDER_ID = "provider_id"+ private const val INVALID_PROVIDER_ID = -1L+ private const val UNIQUE_WORK_PREFIX = "background-epg-sync-"++ fun enqueue(context: Context, providerId: Long) {+ if (providerId <= 0L) return+ val request = OneTimeWorkRequestBuilder<BackgroundEpgSyncWorker>()+ .setInputData(Data.Builder().putLong(KEY_PROVIDER_ID, providerId).build())+ .setConstraints(+ Constraints.Builder()+ .setRequiredNetworkType(NetworkType.CONNECTED)+ .setRequiresBatteryNotLow(true)+ .build()+ )+ .setBackoffCriteria(+ BackoffPolicy.EXPONENTIAL,+ WorkRequest.MIN_BACKOFF_MILLIS,+ TimeUnit.MILLISECONDS+ )+ .build()++ WorkManager.getInstance(context).enqueueUniqueWork(+ uniqueWorkName(providerId),+ ExistingWorkPolicy.KEEP,+ request+ )+ }++ fun cancel(context: Context, providerId: Long) {+ if (providerId <= 0L) return+ WorkManager.getInstance(context).cancelUniqueWork(uniqueWorkName(providerId))+ }++ private fun uniqueWorkName(providerId: Long): String = "$UNIQUE_WORK_PREFIX$providerId"+ }+}diff --git a/data/src/main/java/com/streamvault/data/sync/CatalogSizeLimits.kt b/data/src/main/java/com/streamvault/data/sync/CatalogSizeLimits.ktnew file mode 100644index 00000000..a9dc111d--- /dev/null+++ b/data/src/main/java/com/streamvault/data/sync/CatalogSizeLimits.kt@@ -0,0 +1,7 @@+package com.streamvault.data.sync++data class CatalogSizeLimits(+ val maxChannelsPerProvider: Int = 100_000,+ val maxMoviesPerProvider: Int = 200_000,+ val maxSeriesPerProvider: Int = 100_000+)diff --git a/data/src/main/java/com/streamvault/data/sync/ContentCachePolicy.kt b/data/src/main/java/com/streamvault/data/sync/ContentCachePolicy.ktindex d09ed027..0c9ed689 100644--- a/data/src/main/java/com/streamvault/data/sync/ContentCachePolicy.kt+++ b/data/src/main/java/com/streamvault/data/sync/ContentCachePolicy.kt@@ -6,6 +6,8 @@ object ContentCachePolicy {const val EPG_TTL_MILLIS = 6L * 60 * 60 * 1000Lfun shouldRefresh(lastSyncAt: Long, ttlMillis: Long, now: Long = System.currentTimeMillis()): Boolean {- return lastSyncAt <= 0L || now - lastSyncAt >= ttlMillis+ if (lastSyncAt <= 0L) return true+ val elapsed = now - lastSyncAt+ return elapsed < 0L || elapsed >= ttlMillis}-}\ No newline at end of file+}diff --git a/data/src/main/java/com/streamvault/data/sync/DatabaseMaintenanceManager.kt b/data/src/main/java/com/streamvault/data/sync/DatabaseMaintenanceManager.ktindex e1ae13e8..cac9b770 100644--- a/data/src/main/java/com/streamvault/data/sync/DatabaseMaintenanceManager.kt+++ b/data/src/main/java/com/streamvault/data/sync/DatabaseMaintenanceManager.kt@@ -1,11 +1,15 @@package com.streamvault.data.syncimport android.util.Log+import androidx.annotation.WorkerThreadimport com.streamvault.data.local.StreamVaultDatabase+import com.streamvault.data.local.dao.ChannelDaoimport com.streamvault.data.local.dao.EpgProgrammeDaoimport com.streamvault.data.local.dao.EpisodeDaoimport com.streamvault.data.local.dao.FavoriteDaoimport com.streamvault.data.local.dao.ProgramDao+import com.streamvault.data.local.dao.ProgramReminderDao+import com.streamvault.data.local.dao.SearchHistoryDaoimport java.io.Fileimport javax.inject.Injectimport javax.inject.Singleton@@ -15,15 +19,20 @@ import kotlinx.coroutines.withContext@Singletonclass DatabaseMaintenanceManager @Inject constructor(private val database: StreamVaultDatabase,+ private val channelDao: ChannelDao,private val programDao: ProgramDao,private val epgProgrammeDao: EpgProgrammeDao,private val episodeDao: EpisodeDao,private val favoriteDao: FavoriteDao,+ private val programReminderDao: ProgramReminderDao,+ private val searchHistoryDao: SearchHistoryDao,private val syncManager: SyncManager) {suspend fun runDailyMaintenance(now: Long = System.currentTimeMillis()): MaintenanceReport = withContext(Dispatchers.IO) {- val oldProgramThreshold = now - PROGRAM_RETENTION_MILLIS+ val oldProgramThreshold = now - programRetentionMillis()+ searchHistoryDao.pruneOlderThan(now - SEARCH_HISTORY_RETENTION_MILLIS)+ val deletedExpiredReminders = programReminderDao.deleteExpired(now - PROGRAM_REMINDER_RETENTION_MILLIS)val deletedPrograms = programDao.deleteOld(oldProgramThreshold)val deletedExternalProgrammes = epgProgrammeDao.deleteOld(oldProgramThreshold)val deletedOrphanEpisodes = episodeDao.deleteOrphans()@@ -32,27 +41,35 @@ class DatabaseMaintenanceManager @Inject constructor(favoriteDao.deleteMissingSeriesFavorites()val statsBeforeVacuum = collectStorageStats()- val vacuumRan = if (shouldVacuum(statsBeforeVacuum) && !isSyncActive()) {- runVacuum()- } else {- if (shouldVacuum(statsBeforeVacuum)) {- Log.i(TAG, "VACUUM skipped: a provider sync is currently active")+ val vacuumNeeded = shouldVacuum(statsBeforeVacuum)+ val vacuumRan = if (vacuumNeeded) {+ syncManager.runWhenNoSyncActive {+ runVacuum()+ }.also { ran ->+ if (!ran) {+ Log.i(TAG, "VACUUM skipped: a provider sync is currently active")+ }}+ } else {false}val statsAfterVacuum = collectStorageStats()+ val tableStats = collectTableStats()MaintenanceReport(+ deletedExpiredReminders = deletedExpiredReminders,deletedPrograms = deletedPrograms,deletedExternalProgrammes = deletedExternalProgrammes,deletedOrphanEpisodes = deletedOrphanEpisodes,deletedStaleFavorites = deletedStaleFavorites,vacuumRan = vacuumRan,statsBeforeVacuum = statsBeforeVacuum,- statsAfterVacuum = statsAfterVacuum+ statsAfterVacuum = statsAfterVacuum,+ tableStats = tableStats)}+ @WorkerThreadprivate fun collectStorageStats(): DatabaseStorageStats {val sqliteDb = database.openHelper.writableDatabaseval pageSize = sqliteDb.longPragma("page_size")@@ -80,14 +97,19 @@ class DatabaseMaintenanceManager @Inject constructor(private suspend fun runVacuum(): Boolean = withContext(Dispatchers.IO) {val sqliteDb = database.openHelper.writableDatabase- // Check WAL checkpoint result: column 1 = pages not yet checkpointed (busy readers).- // If any pages are busy, active read transactions exist — VACUUM would block them all.- val busyPages = sqliteDb.query("PRAGMA wal_checkpoint(TRUNCATE)").use { cursor ->- if (cursor.moveToFirst()) cursor.getInt(1) else 0+ // PASSIVE is a non-blocking inspection step: it checkpoints what it can without forcing+ // writers/readers to wait, and lets us see if pages remain in WAL.+ val remainingWalPages = sqliteDb.walCheckpointRemainingPages("PASSIVE")++ if (remainingWalPages > 0) {+ Log.w(TAG, "wal_checkpoint(PASSIVE) still has $remainingWalPages WAL pages; VACUUM skipped this cycle")+ return@withContext false}- if (busyPages > 0) {- Log.w(TAG, "wal_checkpoint(TRUNCATE) had $busyPages busy pages; VACUUM skipped this cycle")+ // Clear WAL before VACUUM once we know a non-blocking inspection found no remaining pages.+ val fullCheckpointRemainingPages = sqliteDb.walCheckpointRemainingPages("FULL")+ if (fullCheckpointRemainingPages > 0) {+ Log.w(TAG, "wal_checkpoint(FULL) still has $fullCheckpointRemainingPages WAL pages; VACUUM skipped this cycle")return@withContext false}@@ -98,29 +120,64 @@ class DatabaseMaintenanceManager @Inject constructor(true}- /** Returns true if any provider sync mutex is currently held. */- private fun isSyncActive(): Boolean = syncManager.isAnySyncActive()-private fun shouldVacuum(stats: DatabaseStorageStats): Boolean {if (stats.reclaimableBytes < MIN_RECLAIMABLE_BYTES) return falseif (stats.mainDbBytes < MIN_DATABASE_BYTES) return falsereturn stats.reclaimableBytes * 100 >= stats.mainDbBytes * RECLAIMABLE_PERCENT_THRESHOLD}+ private suspend fun programRetentionMillis(): Long {+ val catchUpDays = channelDao.getMaxCatchUpDaysAcrossAllProviders().coerceAtLeast(0)+ return maxOf(PROGRAM_MIN_RETENTION_MILLIS, catchUpDays * MILLIS_PER_DAY)+ }++ @WorkerThreadprivate fun androidx.sqlite.db.SupportSQLiteDatabase.longPragma(pragma: String): Long {query("PRAGMA $pragma").use { cursor ->return if (cursor.moveToFirst()) cursor.getLong(0) else 0L}}+ @WorkerThread+ private fun androidx.sqlite.db.SupportSQLiteDatabase.walCheckpointRemainingPages(mode: String): Int {+ query("PRAGMA wal_checkpoint($mode)").use { cursor ->+ return if (cursor.moveToFirst()) cursor.getInt(1) else 0+ }+ }++ @WorkerThread+ private fun collectTableStats(): TableRowStats {+ val sqliteDb = database.openHelper.writableDatabase+ return TableRowStats(+ channels = sqliteDb.tableCount("channels"),+ movies = sqliteDb.tableCount("movies"),+ series = sqliteDb.tableCount("series"),+ episodes = sqliteDb.tableCount("episodes"),+ programs = sqliteDb.tableCount("programs"),+ epgProgrammes = sqliteDb.tableCount("epg_programmes"),+ playbackHistory = sqliteDb.tableCount("playback_history"),+ favorites = sqliteDb.tableCount("favorites"),+ programReminders = sqliteDb.tableCount("program_reminders")+ )+ }++ @WorkerThread+ private fun androidx.sqlite.db.SupportSQLiteDatabase.tableCount(tableName: String): Long {+ query("SELECT COUNT(*) FROM $tableName").use { cursor ->+ return if (cursor.moveToFirst()) cursor.getLong(0) else 0L+ }+ }+data class MaintenanceReport(+ val deletedExpiredReminders: Int = 0,val deletedPrograms: Int,val deletedExternalProgrammes: Int = 0,val deletedOrphanEpisodes: Int,val deletedStaleFavorites: Int,val vacuumRan: Boolean,val statsBeforeVacuum: DatabaseStorageStats,- val statsAfterVacuum: DatabaseStorageStats+ val statsAfterVacuum: DatabaseStorageStats,+ val tableStats: TableRowStats)data class DatabaseStorageStats(@@ -134,11 +191,26 @@ class DatabaseMaintenanceManager @Inject constructor(val logicalDbBytes: Long get() = pageSizeBytes * pageCount}+ data class TableRowStats(+ val channels: Long,+ val movies: Long,+ val series: Long,+ val episodes: Long,+ val programs: Long,+ val epgProgrammes: Long,+ val playbackHistory: Long,+ val favorites: Long,+ val programReminders: Long+ )+companion object {private const val TAG = "DbMaintenance"- private const val PROGRAM_RETENTION_MILLIS = 24L * 60 * 60 * 1000L+ private const val MILLIS_PER_DAY = 24L * 60 * 60 * 1000L+ private const val PROGRAM_MIN_RETENTION_MILLIS = MILLIS_PER_DAY+ private const val PROGRAM_REMINDER_RETENTION_MILLIS = MILLIS_PER_DAY+ private const val SEARCH_HISTORY_RETENTION_MILLIS = 90L * MILLIS_PER_DAYprivate const val MIN_RECLAIMABLE_BYTES = 32L * 1024 * 1024private const val MIN_DATABASE_BYTES = 128L * 1024 * 1024private const val RECLAIMABLE_PERCENT_THRESHOLD = 20L}-}\ No newline at end of file+}diff --git a/data/src/main/java/com/streamvault/data/sync/ProviderSyncWorker.kt b/data/src/main/java/com/streamvault/data/sync/ProviderSyncWorker.ktnew file mode 100644index 00000000..cf84ec8f--- /dev/null+++ b/data/src/main/java/com/streamvault/data/sync/ProviderSyncWorker.kt@@ -0,0 +1,99 @@+package com.streamvault.data.sync++import android.content.Context+import android.database.sqlite.SQLiteException+import android.util.Log+import androidx.work.BackoffPolicy+import androidx.work.Constraints+import androidx.work.CoroutineWorker+import androidx.work.ExistingPeriodicWorkPolicy+import androidx.work.NetworkType+import androidx.work.PeriodicWorkRequestBuilder+import androidx.work.WorkManager+import androidx.work.WorkerParameters+import com.streamvault.data.local.dao.ProviderDao+import dagger.hilt.EntryPoint+import dagger.hilt.InstallIn+import dagger.hilt.android.EntryPointAccessors+import dagger.hilt.components.SingletonComponent+import java.util.concurrent.TimeUnit++class ProviderSyncWorker(+ appContext: Context,+ workerParams: WorkerParameters+) : CoroutineWorker(appContext, workerParams) {++ @EntryPoint+ @InstallIn(SingletonComponent::class)+ interface ProviderSyncWorkerEntryPoint {+ fun providerDao(): ProviderDao+ fun syncManager(): SyncManager+ }++ override suspend fun doWork(): Result {+ return try {+ val entryPoint = EntryPointAccessors.fromApplication(+ applicationContext,+ ProviderSyncWorkerEntryPoint::class.java+ )+ val providers = entryPoint.providerDao().getAllSync()+ if (providers.isEmpty()) {+ return Result.success()+ }++ var sawRetryableFailure = false+ providers.forEach { provider ->+ when (val result = entryPoint.syncManager().sync(provider.id, force = false)) {+ 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+ }+ }+ else -> Unit+ }+ }++ if (sawRetryableFailure) Result.retry() else Result.success()+ } catch (e: Exception) {+ Log.e(TAG, "Provider sync worker failed", e)+ if (shouldRetry(e)) Result.retry() else Result.failure()+ }+ }++ 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+ }+ }++ companion object {+ private const val TAG = "ProviderSyncWorker"+ private const val UNIQUE_WORK_NAME = "provider-sync-worker"++ fun enqueuePeriodic(context: Context) {+ val request = PeriodicWorkRequestBuilder<ProviderSyncWorker>(6, TimeUnit.HOURS)+ .setConstraints(+ Constraints.Builder()+ .setRequiredNetworkType(NetworkType.CONNECTED)+ .setRequiresBatteryNotLow(true)+ .build()+ )+ .setBackoffCriteria(+ BackoffPolicy.EXPONENTIAL,+ 10,+ TimeUnit.MINUTES+ )+ .build()++ WorkManager.getInstance(context).enqueueUniquePeriodicWork(+ UNIQUE_WORK_NAME,+ ExistingPeriodicWorkPolicy.KEEP,+ request+ )+ }+ }+}diff --git a/data/src/main/java/com/streamvault/data/sync/SyncCatalogStore.kt b/data/src/main/java/com/streamvault/data/sync/SyncCatalogStore.ktindex 335a4d68..5e39527a 100644--- a/data/src/main/java/com/streamvault/data/sync/SyncCatalogStore.kt+++ b/data/src/main/java/com/streamvault/data/sync/SyncCatalogStore.kt@@ -1,8 +1,13 @@package com.streamvault.data.sync+import android.util.Logimport com.streamvault.data.local.DatabaseTransactionRunnerimport com.streamvault.data.local.dao.CatalogSyncDao+import com.streamvault.data.local.dao.CategoryDao+import com.streamvault.data.local.dao.ChannelDaoimport com.streamvault.data.local.dao.MovieDao+import com.streamvault.data.local.dao.SeriesDao+import com.streamvault.data.local.dao.TmdbIdentityDaoimport com.streamvault.data.local.entity.CategoryEntityimport com.streamvault.data.local.entity.CategoryImportStageEntityimport com.streamvault.data.local.entity.ChannelEntity@@ -11,32 +16,58 @@ import com.streamvault.data.local.entity.MovieEntityimport com.streamvault.data.local.entity.MovieImportStageEntityimport com.streamvault.data.local.entity.SeriesEntityimport com.streamvault.data.local.entity.SeriesImportStageEntity+import com.streamvault.data.local.entity.TmdbIdentityEntity+import com.streamvault.domain.model.ContentTypeimport java.net.URIimport java.security.MessageDigestimport java.util.concurrent.atomic.AtomicLong+import kotlin.random.Randominternal class SyncCatalogStore(+ private val channelDao: ChannelDao,private val movieDao: MovieDao,+ private val seriesDao: SeriesDao,+ private val categoryDao: CategoryDao,private val catalogSyncDao: CatalogSyncDao,- private val transactionRunner: DatabaseTransactionRunner+ private val tmdbIdentityDao: TmdbIdentityDao,+ private val transactionRunner: DatabaseTransactionRunner,+ private val sizeLimits: CatalogSizeLimits = CatalogSizeLimits()) {- private val sessionIds = AtomicLong(System.currentTimeMillis())+ companion object {+ private const val TAG = "SyncCatalogStore"+ private const val STAGE_BATCH_SIZE = 500+ }++ private val sessionIds = AtomicLong(Random.nextLong(1L, Long.MAX_VALUE))private val digest = ThreadLocal.withInitial { MessageDigest.getInstance("SHA-256") }- fun newSessionId(): Long = sessionIds.incrementAndGet()+ fun newSessionId(): Long {+ while (true) {+ val current = sessionIds.get()+ val next = if (current >= Long.MAX_VALUE - 1) {+ Random.nextLong(1L, Long.MAX_VALUE)+ } else {+ current + 1+ }+ if (sessionIds.compareAndSet(current, next)) {+ return next+ }+ }+ }suspend fun replaceLiveCatalog(providerId: Long, categories: List<CategoryEntity>?, channels: List<ChannelEntity>): Int {val sessionId = newSessionId()val stagedChannels = buildChannelStages(providerId, sessionId, channels)+ val limitedChannels = limitChannels(providerId, stagedChannels)try {clearProviderStaging(providerId)categories?.let { stageCategories(providerId, sessionId, it) }- insertStageRows(stagedChannels, catalogSyncDao::insertChannelStages)+ insertStageRows(limitedChannels, catalogSyncDao::insertChannelStages)transactionRunner.inTransaction {categories?.let { applyCategories(providerId, sessionId, "LIVE") }applyChannels(providerId, sessionId)}- return stagedChannels.size+ return limitedChannels.size} finally {clearSession(providerId, sessionId)}@@ -180,27 +211,176 @@ internal class SyncCatalogStore(}private suspend fun applyCategories(providerId: Long, sessionId: Long, type: String) {- catalogSyncDao.updateChangedCategoriesFromStage(providerId, sessionId, type)+ val stagedByCategoryId = catalogSyncDao.getCategoryStages(providerId, sessionId, type)+ .associateBy { it.categoryId }+ val remappedProtectedCategoryIds = mutableListOf<Long>()+ val changed = categoryDao.getByProviderAndTypeSync(providerId, type)+ .mapNotNull { current ->+ val stage = stagedByCategoryId[current.categoryId] ?: return@mapNotNull null+ if (current.syncFingerprint == stage.syncFingerprint) return@mapNotNull null+ val invalidateProtection = current.isUserProtected+ if (invalidateProtection) {+ remappedProtectedCategoryIds += current.categoryId+ }+ current.copy(+ name = stage.name,+ parentId = stage.parentId,+ isAdult = stage.isAdult,+ isUserProtected = if (invalidateProtection) false else current.isUserProtected,+ syncFingerprint = stage.syncFingerprint+ )+ }+ if (changed.isNotEmpty()) {+ categoryDao.updateAll(changed)+ }+ if (remappedProtectedCategoryIds.isNotEmpty()) {+ when (type) {+ "LIVE" -> channelDao.clearProtectionForCategories(providerId, remappedProtectedCategoryIds)+ "MOVIE" -> movieDao.clearProtectionForCategories(providerId, remappedProtectedCategoryIds)+ "SERIES" -> seriesDao.clearProtectionForCategories(providerId, remappedProtectedCategoryIds)+ }+ }catalogSyncDao.insertMissingCategoriesFromStage(providerId, sessionId, type)catalogSyncDao.deleteStaleCategoriesForStage(providerId, sessionId, type)}private suspend fun applyChannels(providerId: Long, sessionId: Long) {- catalogSyncDao.updateChangedChannelsFromStage(providerId, sessionId)+ val stagedByStreamId = catalogSyncDao.getChannelStages(providerId, sessionId)+ .associateBy { it.streamId }+ val changed = channelDao.getByProviderSync(providerId)+ .mapNotNull { current ->+ val stage = stagedByStreamId[current.streamId] ?: return@mapNotNull null+ if (current.syncFingerprint == stage.syncFingerprint) return@mapNotNull null+ current.copy(+ name = stage.name,+ logoUrl = stage.logoUrl,+ groupTitle = stage.groupTitle,+ categoryId = stage.categoryId,+ categoryName = stage.categoryName,+ streamUrl = stage.streamUrl,+ epgChannelId = stage.epgChannelId,+ number = stage.number,+ catchUpSupported = stage.catchUpSupported,+ catchUpDays = stage.catchUpDays,+ catchUpSource = stage.catchUpSource,+ isAdult = stage.isAdult,+ logicalGroupId = stage.logicalGroupId,+ errorCount = stage.errorCount,+ syncFingerprint = stage.syncFingerprint+ )+ }+ if (changed.isNotEmpty()) {+ channelDao.updateAll(changed)+ }catalogSyncDao.insertMissingChannelsFromStage(providerId, sessionId)catalogSyncDao.deleteStaleChannelsForStage(providerId, sessionId)}private suspend fun applyMovies(providerId: Long, sessionId: Long) {- catalogSyncDao.updateChangedMoviesFromStage(providerId, sessionId)+ val stagedByStreamId = catalogSyncDao.getMovieStages(providerId, sessionId)+ .associateBy { it.streamId }+ val changed = movieDao.getByProviderSync(providerId)+ .mapNotNull { current ->+ val stage = stagedByStreamId[current.streamId] ?: return@mapNotNull null+ if (current.syncFingerprint == stage.syncFingerprint) return@mapNotNull null+ current.copy(+ name = stage.name,+ posterUrl = stage.posterUrl,+ backdropUrl = stage.backdropUrl,+ categoryId = stage.categoryId,+ categoryName = stage.categoryName,+ streamUrl = stage.streamUrl,+ containerExtension = stage.containerExtension,+ plot = stage.plot,+ cast = stage.cast,+ director = stage.director,+ genre = stage.genre,+ releaseDate = stage.releaseDate,+ duration = stage.duration,+ durationSeconds = stage.durationSeconds,+ rating = stage.rating,+ year = stage.year,+ tmdbId = stage.tmdbId,+ youtubeTrailer = stage.youtubeTrailer,+ isAdult = stage.isAdult,+ syncFingerprint = stage.syncFingerprint+ )+ }+ if (changed.isNotEmpty()) {+ movieDao.updateAll(changed)+ }catalogSyncDao.insertMissingMoviesFromStage(providerId, sessionId)catalogSyncDao.deleteStaleMoviesForStage(providerId, sessionId)+ refreshMovieTmdbIdentities(providerId)}private suspend fun applySeries(providerId: Long, sessionId: Long) {- catalogSyncDao.updateChangedSeriesFromStage(providerId, sessionId)+ val stagedBySeriesId = catalogSyncDao.getSeriesStages(providerId, sessionId)+ .associateBy { it.seriesId }+ val changed = seriesDao.getByProviderSync(providerId)+ .mapNotNull { current ->+ val stage = stagedBySeriesId[current.seriesId] ?: return@mapNotNull null+ if (current.syncFingerprint == stage.syncFingerprint) return@mapNotNull null+ current.copy(+ name = stage.name,+ posterUrl = stage.posterUrl,+ backdropUrl = stage.backdropUrl,+ categoryId = stage.categoryId,+ categoryName = stage.categoryName,+ plot = stage.plot,+ cast = stage.cast,+ director = stage.director,+ genre = stage.genre,+ releaseDate = stage.releaseDate,+ rating = stage.rating,+ tmdbId = stage.tmdbId,+ youtubeTrailer = stage.youtubeTrailer,+ episodeRunTime = stage.episodeRunTime,+ lastModified = stage.lastModified,+ isAdult = stage.isAdult,+ syncFingerprint = stage.syncFingerprint+ )+ }+ if (changed.isNotEmpty()) {+ seriesDao.updateAll(changed)+ }catalogSyncDao.insertMissingSeriesFromStage(providerId, sessionId)catalogSyncDao.deleteStaleSeriesForStage(providerId, sessionId)+ refreshSeriesTmdbIdentities(providerId)+ }++ private suspend fun refreshMovieTmdbIdentities(providerId: Long) {+ val identities = movieDao.getTmdbIdsByProvider(providerId)+ .distinctBy { it.tmdbId }+ .map { mapping ->+ TmdbIdentityEntity(+ tmdbId = mapping.tmdbId,+ contentType = ContentType.MOVIE,+ canonicalProviderId = providerId,+ firstSeenAt = System.currentTimeMillis()+ )+ }+ if (identities.isNotEmpty()) {+ tmdbIdentityDao.upsertAll(identities)+ }+ tmdbIdentityDao.pruneOrphanedMovieIdentities()+ }++ private suspend fun refreshSeriesTmdbIdentities(providerId: Long) {+ val identities = seriesDao.getTmdbIdsByProvider(providerId)+ .distinctBy { it.tmdbId }+ .map { mapping ->+ TmdbIdentityEntity(+ tmdbId = mapping.tmdbId,+ contentType = ContentType.SERIES,+ canonicalProviderId = providerId,+ firstSeenAt = System.currentTimeMillis()+ )+ }+ if (identities.isNotEmpty()) {+ tmdbIdentityDao.upsertAll(identities)+ }+ tmdbIdentityDao.pruneOrphanedSeriesIdentities()}private suspend fun clearSession(providerId: Long, sessionId: Long) {@@ -318,6 +498,12 @@ internal class SyncCatalogStore(return stageDistinctRows(items = movies,keySelector = { movie -> movie.streamId },+ limit = sizeLimits.maxMoviesPerProvider,+ bestFirstComparator = compareByDescending<MovieEntity> { it.rating }+ .thenBy { it.name.lowercase() }+ .thenBy { it.streamId },+ logLabel = "movies",+ providerId = providerId,stageBuilder = { movie -> movieStageEntity(providerId, sessionId, movie) },insert = catalogSyncDao::insertMovieStages)@@ -331,6 +517,12 @@ internal class SyncCatalogStore(return stageDistinctRows(items = series,keySelector = { item -> item.seriesId },+ limit = sizeLimits.maxSeriesPerProvider,+ bestFirstComparator = compareByDescending<SeriesEntity> { it.rating }+ .thenBy { it.name.lowercase() }+ .thenBy { it.seriesId },+ logLabel = "series",+ providerId = providerId,stageBuilder = { item -> seriesStageEntity(providerId, sessionId, item) },insert = catalogSyncDao::insertSeriesStages)@@ -339,30 +531,54 @@ internal class SyncCatalogStore(private suspend fun <T, K, S> stageDistinctRows(items: Sequence<T>,keySelector: (T) -> K,+ limit: Int,+ bestFirstComparator: Comparator<T>,+ logLabel: String,+ providerId: Long,stageBuilder: (T) -> S,insert: suspend (List<S>) -> Unit): Int {val seenKeys = HashSet<K>()+ val bestItems = java.util.PriorityQueue<T>(limit.coerceAtLeast(1), bestFirstComparator.reversed())val batch = ArrayList<S>(STAGE_BATCH_SIZE)- var acceptedCount = 0+ var distinctCount = 0items.forEach { item ->if (!seenKeys.add(keySelector(item))) {return@forEach}- batch += stageBuilder(item)- acceptedCount++- if (batch.size >= STAGE_BATCH_SIZE) {- insert(batch)- batch.clear()+ distinctCount+++ if (bestItems.size < limit) {+ bestItems += item+ } else if (limit > 0 && bestFirstComparator.compare(item, bestItems.peek()) < 0) {+ bestItems.poll()+ bestItems += item}}+ if (distinctCount > limit) {+ Log.w(+ TAG,+ "Provider $providerId $logLabel staging exceeded limit $limit; kept ${bestItems.size} highest-priority distinct rows out of $distinctCount."+ )+ }++ bestItems+ .toList()+ .sortedWith(bestFirstComparator)+ .forEach { item ->+ batch.add(stageBuilder(item))+ if (batch.size >= STAGE_BATCH_SIZE) {+ insert(batch)+ batch.clear()+ }+ }+if (batch.isNotEmpty()) {insert(batch)}- return acceptedCount+ return bestItems.size}private suspend fun <T> insertStageRows(@@ -404,7 +620,8 @@ internal class SyncCatalogStore(tmdbId = movie.tmdbId,youtubeTrailer = movie.youtubeTrailer,isAdult = movie.isAdult,- syncFingerprint = movieFingerprint(movie)+ syncFingerprint = movieFingerprint(movie),+ addedAt = movie.addedAt)}@@ -554,7 +771,26 @@ internal class SyncCatalogStore(.ifBlank { url.lowercase() }}- private companion object {- private const val STAGE_BATCH_SIZE = 500+ private fun limitChannels(+ providerId: Long,+ channels: List<ChannelImportStageEntity>+ ): List<ChannelImportStageEntity> {+ if (channels.size <= sizeLimits.maxChannelsPerProvider) {+ return channels+ }+ val limited = channels+ .sortedWith(+ compareBy<ChannelImportStageEntity>(+ { if (it.number > 0) it.number else Int.MAX_VALUE },+ { it.name.lowercase() },+ { it.streamId }+ )+ )+ .take(sizeLimits.maxChannelsPerProvider)+ Log.w(+ TAG,+ "Provider $providerId channel staging exceeded limit ${sizeLimits.maxChannelsPerProvider}; kept ${limited.size} lowest-numbered distinct rows out of ${channels.size}."+ )+ return limited}}diff --git a/data/src/main/java/com/streamvault/data/sync/SyncManager.kt b/data/src/main/java/com/streamvault/data/sync/SyncManager.ktindex bdcbc4b0..efc7fcae 100644--- a/data/src/main/java/com/streamvault/data/sync/SyncManager.kt+++ b/data/src/main/java/com/streamvault/data/sync/SyncManager.kt@@ -1,5 +1,6 @@package com.streamvault.data.sync+import android.content.Contextimport android.util.Logimport com.streamvault.data.local.DatabaseTransactionRunnerimport com.streamvault.data.local.dao.CatalogSyncDao@@ -9,6 +10,7 @@ import com.streamvault.data.local.dao.MovieDaoimport com.streamvault.data.local.dao.ProgramDaoimport com.streamvault.data.local.dao.ProviderDaoimport com.streamvault.data.local.dao.SeriesDao+import com.streamvault.data.local.dao.TmdbIdentityDaoimport com.streamvault.data.local.entity.CategoryEntityimport com.streamvault.data.local.entity.ChannelEntityimport com.streamvault.data.local.entity.MovieEntity@@ -44,11 +46,9 @@ import com.streamvault.domain.model.VodSyncModeimport com.streamvault.domain.repository.EpgRepositoryimport com.streamvault.domain.repository.EpgSourceRepositoryimport com.streamvault.domain.repository.SyncMetadataRepository+import dagger.hilt.android.qualifiers.ApplicationContextimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.CancellationException-import kotlinx.coroutines.CoroutineScope-import kotlinx.coroutines.Job-import kotlinx.coroutines.SupervisorJobimport kotlinx.coroutines.asyncimport kotlinx.coroutines.awaitAllimport kotlinx.coroutines.coroutineScope@@ -56,7 +56,6 @@ import kotlinx.coroutines.flow.Flowimport kotlinx.coroutines.flow.StateFlowimport kotlinx.coroutines.flow.firstimport kotlinx.coroutines.flow.map-import kotlinx.coroutines.launchimport kotlinx.coroutines.withContextimport kotlinx.coroutines.sync.Muteximport kotlinx.coroutines.sync.withLock@@ -104,6 +103,7 @@ enum class SyncRepairSection {@Singletonclass SyncManager @Inject constructor(+ @ApplicationContext private val applicationContext: Context,private val providerDao: ProviderDao,private val channelDao: ChannelDao,private val movieDao: MovieDao,@@ -111,6 +111,7 @@ class SyncManager @Inject constructor(private val programDao: ProgramDao,private val categoryDao: CategoryDao,private val catalogSyncDao: CatalogSyncDao,+ private val tmdbIdentityDao: TmdbIdentityDao,private val xtreamJson: Json,private val m3uParser: M3uParser,private val epgRepository: EpgRepository,@@ -125,8 +126,12 @@ class SyncManager @Inject constructor(private val syncErrorSanitizer = SyncErrorSanitizer()private val xtreamAdaptiveSyncPolicy = XtreamAdaptiveSyncPolicy()private val syncCatalogStore = SyncCatalogStore(+ channelDao = channelDao,movieDao = movieDao,+ seriesDao = seriesDao,+ categoryDao = categoryDao,catalogSyncDao = catalogSyncDao,+ tmdbIdentityDao = tmdbIdentityDao,transactionRunner = transactionRunner)private val m3uImporter = SyncManagerM3uImporter(@@ -148,8 +153,7 @@ class SyncManager @Inject constructor(val syncState: StateFlow<SyncState> = syncStateTracker.aggregateStateval syncStatesByProvider: StateFlow<Map<Long, SyncState>> = syncStateTracker.statesByProviderprivate val providerSyncMutexes = ConcurrentHashMap<Long, Mutex>()- private val backgroundEpgScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)- private val backgroundEpgJobs = ConcurrentHashMap<Long, Job>()+ private val syncAdmissionMutex = Mutex()private val xtreamCatalogHttpService: OkHttpXtreamApiService by lazy {OkHttpXtreamApiService(client = okHttpClient,@@ -243,73 +247,86 @@ class SyncManager @Inject constructor(/** Returns true if any provider sync mutex is currently held (used by DatabaseMaintenanceManager). */fun isAnySyncActive(): Boolean = providerSyncMutexes.values.any { it.isLocked }private suspend fun <T> withProviderLock(providerId: Long, block: suspend () -> T): T {- val mutex = providerSyncMutexes.computeIfAbsent(providerId) { Mutex() }- return mutex.withLock { block() }+ val mutex = syncAdmissionMutex.withLock {+ providerSyncMutexes.computeIfAbsent(providerId) { Mutex() }.also { providerMutex ->+ providerMutex.lock()+ }+ }+ try {+ return block()+ } finally {+ mutex.unlock()+ }}- suspend fun onProviderDeleted(providerId: Long) {- val cancelledEpgJob = backgroundEpgJobs.remove(providerId)- if (cancelledEpgJob?.isActive == true) {- Log.w(TAG, "onProviderDeleted($providerId): cancelled an active background EPG job; mid-sync delete detected")+ suspend fun runWhenNoSyncActive(block: suspend () -> Boolean): Boolean =+ syncAdmissionMutex.withLock {+ if (providerSyncMutexes.values.any { it.isLocked }) {+ false+ } else {+ block()+ }}- cancelledEpgJob?.cancel()++ suspend fun onProviderDeleted(providerId: Long) {+ BackgroundEpgSyncWorker.cancel(applicationContext, providerId)withProviderLock(providerId) {syncStateTracker.reset(providerId)xtreamAdaptiveSyncPolicy.forgetProvider(providerId)syncCatalogStore.clearProviderStaging(providerId)+ epgRepository.onProviderDeleted(providerId)+ providerSyncMutexes.remove(providerId)}- providerSyncMutexes.remove(providerId)}fun scheduleBackgroundEpgSync(providerId: Long) {- backgroundEpgJobs.remove(providerId)?.cancel()- val job = backgroundEpgScope.launch {- withProviderLock(providerId) {- val providerEntity = providerDao.getById(providerId) ?: return@withProviderLock- val provider = providerEntity- .copy(password = credentialCrypto.decryptIfNeeded(providerEntity.password))- .toDomain()- try {- publishSyncState(providerId, SyncState.Syncing("Downloading EPG..."))- val warnings = syncProviderEpg(- provider = provider,- metadata = syncMetadataRepository.getMetadata(provider.id) ?: SyncMetadata(provider.id),- now = System.currentTimeMillis(),- force = true,- onProgress = null- )- publishSyncState(- providerId,- if (warnings.isEmpty()) {- SyncState.Success()- } else {- SyncState.Partial("Background EPG sync completed with warnings", warnings)- }- )- updateSyncStatusMetadata(- providerId = providerId,- status = if (warnings.isEmpty()) "SUCCESS" else "PARTIAL"- )- } catch (e: CancellationException) {- throw e- } catch (e: Exception) {- Log.e(TAG, "Background EPG sync failed for provider $providerId: ${syncErrorSanitizer.throwableMessage(e)}")- publishSyncState(- providerId,- SyncState.Partial(- message = "Background EPG sync completed with warnings",- warnings = listOf(syncErrorSanitizer.userMessage(e, "EPG sync failed"))- )- )- updateSyncStatusMetadata(providerId = providerId, status = "PARTIAL")+ BackgroundEpgSyncWorker.enqueue(applicationContext, providerId)+ }++ suspend fun syncEpg(+ providerId: Long,+ force: Boolean = true,+ onProgress: ((String) -> Unit)? = null+ ): com.streamvault.domain.model.Result<Unit> = withProviderLock(providerId) lock@{+ val providerEntity = providerDao.getById(providerId)+ ?: return@lock com.streamvault.domain.model.Result.error("Provider $providerId not found")++ val provider = providerEntity+ .copy(password = credentialCrypto.decryptIfNeeded(providerEntity.password))+ .toDomain()++ publishSyncState(providerId, SyncState.Syncing("Downloading EPG..."))++ try {+ val warnings = syncProviderEpg(+ provider = provider,+ metadata = syncMetadataRepository.getMetadata(provider.id) ?: SyncMetadata(provider.id),+ now = System.currentTimeMillis(),+ force = force,+ onProgress = onProgress+ )+ updateSyncStatusMetadata(+ providerId = providerId,+ status = if (warnings.isEmpty()) "SUCCESS" else "PARTIAL"+ )+ publishSyncState(+ providerId,+ if (warnings.isEmpty()) {+ SyncState.Success()+ } else {+ SyncState.Partial("EPG sync completed with warnings", warnings)}- }- }- // Store the launched job before registering completion cleanup so fast-completing- // coroutines cannot finish and race past map registration.- backgroundEpgJobs[providerId] = job- job.invokeOnCompletion {- backgroundEpgJobs.remove(providerId, job)+ )+ com.streamvault.domain.model.Result.success(Unit)+ } catch (e: CancellationException) {+ resetState(providerId)+ throw e+ } catch (e: Exception) {+ val safeMessage = syncErrorSanitizer.userMessage(e, "EPG sync failed")+ Log.e(TAG, "EPG sync failed for provider $providerId: ${syncErrorSanitizer.throwableMessage(e)}")+ updateSyncStatusMetadata(providerId = providerId, status = "ERROR")+ publishSyncState(providerId, SyncState.Error(safeMessage, e))+ com.streamvault.domain.model.Result.error(safeMessage, e)}}@@ -431,7 +448,7 @@ class SyncManager @Inject constructor(var metadata = syncMetadataRepository.getMetadata(provider.id) ?: SyncMetadata(provider.id)val now = System.currentTimeMillis()- if (force || ContentCachePolicy.shouldRefresh(metadata.lastLiveSync, ContentCachePolicy.CATALOG_TTL_MILLIS, now)) {+ if (force || ContentCachePolicy.shouldRefresh(metadata.lastLiveSuccess, ContentCachePolicy.CATALOG_TTL_MILLIS, now)) {progress(provider.id, onProgress, "Downloading Live TV...")val liveSyncResult = syncXtreamLiveCatalog(provider = provider,@@ -467,6 +484,7 @@ class SyncManager @Inject constructor()metadata = metadata.copy(lastLiveSync = now,+ lastLiveSuccess = now,liveCount = acceptedCount,liveAvoidFullUntil = liveAvoidFullUntil,liveSequentialFailuresRemembered = liveProviderAdaptation.rememberSequential,@@ -503,14 +521,9 @@ class SyncManager @Inject constructor(liveSequentialFailuresRemembered = metadata.liveSequentialFailuresRemembered || liveSequentialStress,liveHealthySyncStreak = 0)- warnings += liveSyncResult.warnings + liveResult.warnings +- if (existingChannelCount > 0) {+ if (existingChannelCount > 0) {+ warnings += liveSyncResult.warnings + liveResult.warnings +listOf("Live TV refresh returned an empty valid catalog; keeping previous channel library.")- } else {- listOf("Live TV refresh returned an empty valid catalog with no previous channel library.")- }- if (existingChannelCount == 0) {- throw IllegalStateException("Live TV catalog was empty.")}}is CatalogStrategyResult.Failure -> {@@ -537,7 +550,7 @@ class SyncManager @Inject constructor(syncMetadataRepository.updateMetadata(metadata)}- if (force || ContentCachePolicy.shouldRefresh(metadata.lastMovieSync, ContentCachePolicy.CATALOG_TTL_MILLIS, now)) {+ if (force || ContentCachePolicy.shouldRefresh(metadata.lastMovieSuccess, ContentCachePolicy.CATALOG_TTL_MILLIS, now)) {progress(provider.id,onProgress,@@ -648,18 +661,21 @@ class SyncManager @Inject constructor(movieParallelFailuresRemembered = metadata.movieParallelFailuresRemembered || sawSequentialStress || shouldRememberSequentialPreference(catalogResult.error),movieHealthySyncStreak = 0)- warnings += movieSyncResult.warnings + catalogResult.warnings +- if (existingMovieCount > 0) {- listOf("Movies sync degraded; keeping previous movie library.")- } else {- listOf("Movies sync failed; continuing with the rest of the provider sync.")- }+ val isFastSyncIntentional = enteringLazyMode || catalogResult.strategyName == "fast_sync_no_categories"+ if (!isFastSyncIntentional) {+ warnings += movieSyncResult.warnings + catalogResult.warnings ++ if (existingMovieCount > 0) {+ listOf("Movies sync degraded; keeping previous movie library.")+ } else {+ listOf("Movies sync failed; continuing with the rest of the provider sync.")+ }+ }}}syncMetadataRepository.updateMetadata(metadata)}- if (force || ContentCachePolicy.shouldRefresh(metadata.lastSeriesSync, ContentCachePolicy.CATALOG_TTL_MILLIS, now)) {+ if (force || ContentCachePolicy.shouldRefresh(metadata.lastSeriesSuccess, ContentCachePolicy.CATALOG_TTL_MILLIS, now)) {progress(provider.id, onProgress, "Downloading Series...")val seriesSyncResult = syncXtreamSeriesCatalog(provider = provider,@@ -691,6 +707,7 @@ class SyncManager @Inject constructor()metadata = metadata.copy(lastSeriesSync = now,+ lastSeriesSuccess = now,seriesCount = acceptedCount,seriesAvoidFullUntil = seriesAvoidFullUntil,seriesSequentialFailuresRemembered = seriesProviderAdaptation.rememberSequential,@@ -747,18 +764,14 @@ class SyncManager @Inject constructor(seriesSequentialFailuresRemembered = metadata.seriesSequentialFailuresRemembered || seriesSequentialStress || shouldRememberSequentialPreference(seriesResult.error),seriesHealthySyncStreak = 0)- warnings += seriesSyncResult.warnings + seriesResult.warnings +- if (enteringLazyMode) {- listOf("Series entered lazy category-only mode.")- } else if (existingSeriesCount > 0) {- listOf("Series sync degraded; keeping previous series library.")- } else {- listOf("Series sync failed before any usable series catalog was available.")- }- if (existingSeriesCount == 0 && !enteringLazyMode) {- throw IllegalStateException(- "Failed to fetch series catalog: ${syncErrorSanitizer.throwableMessage(seriesResult.error)}"- )+ val isSeriesFastSyncIntentional = enteringLazyMode || seriesResult.strategyName == "fast_sync_no_categories"+ if (!isSeriesFastSyncIntentional) {+ warnings += seriesSyncResult.warnings + seriesResult.warnings ++ if (existingSeriesCount > 0) {+ listOf("Series sync degraded; keeping previous series library.")+ } else {+ listOf("Series sync failed; continuing with the rest of the provider sync.")+ }}}}@@ -787,7 +800,7 @@ class SyncManager @Inject constructor(var metadata = syncMetadataRepository.getMetadata(provider.id) ?: SyncMetadata(provider.id)val now = System.currentTimeMillis()- if (force || ContentCachePolicy.shouldRefresh(metadata.lastLiveSync, ContentCachePolicy.CATALOG_TTL_MILLIS, now)) {+ if (force || ContentCachePolicy.shouldRefresh(metadata.lastLiveSuccess, ContentCachePolicy.CATALOG_TTL_MILLIS, now)) {val stats = withContext(Dispatchers.IO) { m3uImporter.importPlaylist(provider, onProgress) }if (stats.liveCount == 0 && stats.movieCount == 0) {throw IllegalStateException("Playlist is empty or contains no supported entries")@@ -798,8 +811,10 @@ class SyncManager @Inject constructor(}metadata = metadata.copy(lastLiveSync = now,+ lastLiveSuccess = now,lastMovieSync = now,lastSeriesSync = now,+ lastSeriesSuccess = now,lastMovieAttempt = now,lastMovieSuccess = now,liveCount = stats.liveCount,@@ -838,7 +853,7 @@ class SyncManager @Inject constructor(when (provider.type) {ProviderType.XTREAM_CODES -> {- if (force || ContentCachePolicy.shouldRefresh(updatedMetadata.lastEpgSync, ContentCachePolicy.EPG_TTL_MILLIS, now)) {+ if (force || ContentCachePolicy.shouldRefresh(updatedMetadata.lastEpgSuccess, ContentCachePolicy.EPG_TTL_MILLIS, now)) {try {progress(provider.id, onProgress, "Downloading EPG...")val base = provider.serverUrl.trimEnd('/')@@ -852,6 +867,7 @@ class SyncManager @Inject constructor(val epgCount = programDao.countByProvider(provider.id)updatedMetadata = updatedMetadata.copy(lastEpgSync = now,+ lastEpgSuccess = now,epgCount = epgCount)syncMetadataRepository.updateMetadata(updatedMetadata)@@ -869,7 +885,7 @@ class SyncManager @Inject constructor(ProviderType.M3U -> {val currentEpgUrl = providerDao.getById(provider.id)?.epgUrl ?: provider.epgUrl- if (!currentEpgUrl.isNullOrBlank() && (force || ContentCachePolicy.shouldRefresh(updatedMetadata.lastEpgSync, ContentCachePolicy.EPG_TTL_MILLIS, now))) {+ if (!currentEpgUrl.isNullOrBlank() && (force || ContentCachePolicy.shouldRefresh(updatedMetadata.lastEpgSuccess, ContentCachePolicy.EPG_TTL_MILLIS, now))) {val epgValidationError = UrlSecurityPolicy.validateOptionalEpgUrl(currentEpgUrl)if (epgValidationError != null) {warnings.add(epgValidationError)@@ -879,6 +895,7 @@ class SyncManager @Inject constructor(retryTransient { epgRepository.refreshEpg(provider.id, currentEpgUrl) }updatedMetadata = updatedMetadata.copy(lastEpgSync = now,+ lastEpgSuccess = now,epgCount = programDao.countByProvider(provider.id))syncMetadataRepository.updateMetadata(updatedMetadata)@@ -938,6 +955,7 @@ class SyncManager @Inject constructor(val metadata = (syncMetadataRepository.getMetadata(provider.id) ?: SyncMetadata(provider.id)).copy(lastEpgSync = now,+ lastEpgSuccess = now,epgCount = programDao.countByProvider(provider.id))syncMetadataRepository.updateMetadata(metadata)@@ -997,6 +1015,7 @@ class SyncManager @Inject constructor(syncMetadataRepository.updateMetadata(currentMetadata.copy(lastLiveSync = now,+ lastLiveSuccess = now,liveCount = acceptedCount,liveAvoidFullUntil = liveAvoidFullUntil,liveSequentialFailuresRemembered = liveProviderAdaptation.rememberSequential,@@ -1069,6 +1088,7 @@ class SyncManager @Inject constructor(val metadata = (syncMetadataRepository.getMetadata(provider.id) ?: SyncMetadata(provider.id)).copy(lastLiveSync = now,+ lastLiveSuccess = now,liveCount = stats.liveCount)syncMetadataRepository.updateMetadata(metadata)@@ -1279,6 +1299,7 @@ class SyncManager @Inject constructor(syncMetadataRepository.updateMetadata(currentMetadata.copy(lastSeriesSync = now,+ lastSeriesSuccess = now,seriesCount = acceptedCount,seriesAvoidFullUntil = seriesAvoidFullUntil,seriesSequentialFailuresRemembered = seriesProviderAdaptation.rememberSequential,diff --git a/data/src/main/java/com/streamvault/data/sync/SyncWorker.kt b/data/src/main/java/com/streamvault/data/sync/SyncWorker.ktindex 881d8e94..35680df4 100644--- a/data/src/main/java/com/streamvault/data/sync/SyncWorker.kt+++ b/data/src/main/java/com/streamvault/data/sync/SyncWorker.kt@@ -5,6 +5,8 @@ import android.database.sqlite.SQLiteExceptionimport android.util.Logimport androidx.work.CoroutineWorkerimport androidx.work.WorkerParameters+import com.streamvault.data.preferences.DatabaseMaintenanceSnapshot+import com.streamvault.data.preferences.PreferencesRepositoryimport dagger.hilt.EntryPointimport dagger.hilt.InstallInimport dagger.hilt.android.EntryPointAccessors@@ -19,6 +21,7 @@ class SyncWorker(@InstallIn(SingletonComponent::class)interface SyncWorkerEntryPoint {fun databaseMaintenanceManager(): DatabaseMaintenanceManager+ fun preferencesRepository(): PreferencesRepository}override suspend fun doWork(): Result {@@ -26,6 +29,27 @@ class SyncWorker(return try {val entryPoint = EntryPointAccessors.fromApplication(applicationContext, SyncWorkerEntryPoint::class.java)val report = entryPoint.databaseMaintenanceManager().runDailyMaintenance()+ entryPoint.preferencesRepository().setLastMaintenanceSnapshot(+ DatabaseMaintenanceSnapshot(+ ranAt = System.currentTimeMillis(),+ deletedPrograms = report.deletedPrograms,+ deletedExternalProgrammes = report.deletedExternalProgrammes,+ deletedOrphanEpisodes = report.deletedOrphanEpisodes,+ deletedStaleFavorites = report.deletedStaleFavorites,+ vacuumRan = report.vacuumRan,+ mainDbBytes = report.statsAfterVacuum.mainDbBytes,+ walBytes = report.statsAfterVacuum.walBytes,+ reclaimableBytes = report.statsAfterVacuum.reclaimableBytes,+ channelRows = report.tableStats.channels,+ movieRows = report.tableStats.movies,+ seriesRows = report.tableStats.series,+ episodeRows = report.tableStats.episodes,+ programRows = report.tableStats.programs,+ epgProgrammeRows = report.tableStats.epgProgrammes,+ playbackHistoryRows = report.tableStats.playbackHistory,+ favoriteRows = report.tableStats.favorites+ )+ )Log.d("SyncWorker","Maintenance complete: oldPrograms=${report.deletedPrograms}, orphanEpisodes=${report.deletedOrphanEpisodes}, " +diff --git a/data/src/main/java/com/streamvault/data/util/AdultContentClassifier.kt b/data/src/main/java/com/streamvault/data/util/AdultContentClassifier.ktindex 7184d22a..bca37839 100644--- a/data/src/main/java/com/streamvault/data/util/AdultContentClassifier.kt+++ b/data/src/main/java/com/streamvault/data/util/AdultContentClassifier.kt@@ -1,8 +1,9 @@package com.streamvault.data.utilimport java.text.Normalizer+import java.util.Collections+import java.util.LinkedHashMapimport java.util.Locale-import java.util.concurrent.ConcurrentHashMapobject AdultContentClassifier {private const val MAX_CLASSIFICATION_CACHE_SIZE = 4096@@ -66,22 +67,29 @@ object AdultContentClassifier {)private val normalizedStrongKeywords = strongContainsKeywords.map(::normalize).distinct()private val normalizedBoundaryKeywords = boundaryKeywords.map(::normalize).distinct()- private val classificationCache = ConcurrentHashMap<String, Boolean>()+ private val classificationCache: MutableMap<String, Boolean> = Collections.synchronizedMap(+ object : LinkedHashMap<String, Boolean>(256, 0.75f, true) {+ override fun removeEldestEntry(eldest: MutableMap.MutableEntry<String, Boolean>?): Boolean {+ return size > MAX_CLASSIFICATION_CACHE_SIZE+ }+ }+ )fun isAdultCategoryName(name: String?): Boolean {if (name.isNullOrBlank()) return falseval normalized = normalize(name)- classificationCache[normalized]?.let { return it }+ synchronized(classificationCache) {+ classificationCache[normalized]?.let { return it }+ }val normalizedPadded = " $normalized "val isAdult = normalizedStrongKeywords.any { keyword ->normalized.contains(keyword)} || normalizedBoundaryKeywords.any { keyword ->normalizedPadded.contains(" $keyword ")}- if (classificationCache.size >= MAX_CLASSIFICATION_CACHE_SIZE) {- classificationCache.clear()+ synchronized(classificationCache) {+ classificationCache[normalized] = isAdult}- classificationCache[normalized] = isAdultreturn isAdult}@@ -99,4 +107,16 @@ object AdultContentClassifier {.replace(separatorsRegex, " ").trim()}++ internal fun resetCacheForTesting() {+ synchronized(classificationCache) {+ classificationCache.clear()+ }+ }++ internal fun cacheSizeForTesting(): Int =+ synchronized(classificationCache) { classificationCache.size }++ internal fun isCachedForTesting(name: String): Boolean =+ synchronized(classificationCache) { classificationCache.containsKey(normalize(name)) }}diff --git a/data/src/main/java/com/streamvault/data/util/UrlSecurityPolicy.kt b/data/src/main/java/com/streamvault/data/util/UrlSecurityPolicy.ktindex c0336e15..f203cb83 100644--- a/data/src/main/java/com/streamvault/data/util/UrlSecurityPolicy.kt+++ b/data/src/main/java/com/streamvault/data/util/UrlSecurityPolicy.kt@@ -50,8 +50,10 @@ object UrlSecurityPolicy {return when {url.isBlank() -> nullurl.startsWith("content://") -> null // SAF local file; validated by OS file picker- isSecureRemoteUrl(url) -> null- else -> "EPG URLs must use HTTPS or select a local file."+ // Allow http:// as well as https:// — many IPTV portals serve their XMLTV+ // EPG endpoint over plain HTTP on non-standard ports (same policy as playlists).+ !containsNewlines(url) && hasAllowedScheme(url, playlistSourceSchemes) -> null+ else -> "EPG URLs must use HTTP, HTTPS, or select a local file."}}diff --git a/data/src/test/java/com/streamvault/data/epg/EpgResolutionEngineTest.kt b/data/src/test/java/com/streamvault/data/epg/EpgResolutionEngineTest.ktindex d006fc1c..64a29c97 100644--- a/data/src/test/java/com/streamvault/data/epg/EpgResolutionEngineTest.kt+++ b/data/src/test/java/com/streamvault/data/epg/EpgResolutionEngineTest.kt@@ -145,6 +145,22 @@ class EpgResolutionEngineTest {val mapping = captor.firstValue.single()assertThat(mapping.sourceType).isEqualTo(EpgSourceType.NONE.name)assertThat(mapping.matchType).isNull()+ assertThat(mapping.failedAttempts).isEqualTo(1)+ }++ @Test+ fun `resolveForProvider_providerNativeCountsAsLowConfidenceRematchCandidate`() = runTest {+ val channel = makeChannel(id = 1, name = "Local Channel", epgChannelId = "local.ch1")+ whenever(channelDao.getByProviderSync(PROVIDER_ID)).thenReturn(listOf(channel))+ whenever(providerEpgSourceDao.getEnabledForProviderSync(PROVIDER_ID)).thenReturn(emptyList())+ whenever(channelEpgMappingDao.getForProvider(PROVIDER_ID)).thenReturn(emptyList())+ whenever(programDao.countByProvider(PROVIDER_ID)).thenReturn(10)++ val summary = engine.resolveForProvider(PROVIDER_ID)++ assertThat(summary.providerNativeMatches).isEqualTo(1)+ assertThat(summary.lowConfidenceChannels).isEqualTo(1)+ assertThat(summary.rematchCandidateChannels).isEqualTo(1)}@Testdiff --git a/data/src/test/java/com/streamvault/data/manager/ProgramReminderManagerImplTest.kt b/data/src/test/java/com/streamvault/data/manager/ProgramReminderManagerImplTest.ktnew file mode 100644index 00000000..9ea71821--- /dev/null+++ b/data/src/test/java/com/streamvault/data/manager/ProgramReminderManagerImplTest.kt@@ -0,0 +1,97 @@+package com.streamvault.data.manager++import com.google.common.truth.Truth.assertThat+import com.streamvault.data.local.dao.ProgramReminderDao+import com.streamvault.data.local.entity.ProgramReminderEntity+import com.streamvault.data.manager.reminder.ProgramReminderAlarmScheduler+import com.streamvault.data.manager.reminder.ProgramReminderNotifier+import com.streamvault.domain.model.Program+import kotlinx.coroutines.test.runTest+import org.junit.Test+import org.mockito.kotlin.argumentCaptor+import org.mockito.kotlin.mock+import org.mockito.kotlin.verify+import org.mockito.kotlin.whenever++class ProgramReminderManagerImplTest {++ private val dao: ProgramReminderDao = mock()+ private val alarmScheduler: ProgramReminderAlarmScheduler = mock()+ private val notifier: ProgramReminderNotifier = mock()++ private val manager = ProgramReminderManagerImpl(+ programReminderDao = dao,+ alarmScheduler = alarmScheduler,+ notifier = notifier+ )++ @Test+ fun `scheduleReminder inserts reminder and schedules alarm`() = 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)++ val result = manager.scheduleReminder(+ providerId = 7L,+ channelId = "bbc1",+ channelName = "BBC One",+ program = program+ )++ assertThat(result).isInstanceOf(com.streamvault.domain.model.Result.Success::class.java)+ verify(dao).insert(org.mockito.kotlin.any())+ verify(alarmScheduler).schedule(42L, org.mockito.kotlin.any())+ }++ @Test+ fun `cancelReminder deletes reminder and cancels alarm`() = 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)++ manager.cancelReminder(+ providerId = 7L,+ channelId = "bbc1",+ programTitle = "World News",+ programStartTime = 1_000L+ )++ verify(dao).deleteById(42L)+ verify(alarmScheduler).cancel(42L)+ }++ @Test+ fun `deliverReminder notifies once and marks reminder notified`() = runTest {+ val reminder = ProgramReminderEntity(+ id = 42L,+ providerId = 7L,+ channelId = "bbc1",+ channelName = "BBC One",+ programTitle = "World News",+ programStartTime = System.currentTimeMillis() + 5 * 60_000L,+ remindAt = System.currentTimeMillis()+ )+ whenever(dao.getById(42L)).thenReturn(reminder)++ manager.deliverReminder(42L)++ verify(notifier).showReminder(reminder)+ val updatedCaptor = argumentCaptor<ProgramReminderEntity>()+ verify(dao).update(updatedCaptor.capture())+ assertThat(updatedCaptor.firstValue.notifiedAt).isNotNull()+ }+}diff --git a/data/src/test/java/com/streamvault/data/remote/xtream/XtreamStreamUrlResolverTest.kt b/data/src/test/java/com/streamvault/data/remote/xtream/XtreamStreamUrlResolverTest.ktindex 5bb75d6e..27435542 100644--- a/data/src/test/java/com/streamvault/data/remote/xtream/XtreamStreamUrlResolverTest.kt+++ b/data/src/test/java/com/streamvault/data/remote/xtream/XtreamStreamUrlResolverTest.kt@@ -133,6 +133,7 @@ class XtreamStreamUrlResolverTest {private val provider: ProviderEntity?) : ProviderDao() {override fun getAll() = flowOf(listOfNotNull(provider))+ override suspend fun getAllSync(): List<ProviderEntity> = listOfNotNull(provider)override fun getActive() = flowOf(provider)override suspend fun getByUrlAndUser(serverUrl: String, username: String): ProviderEntity? = nulloverride suspend fun getById(id: Long): ProviderEntity? = provider?.takeIf { it.id == id }@@ -146,4 +147,4 @@ class XtreamStreamUrlResolverTest {override suspend fun updateSyncTime(id: Long, timestamp: Long) = Unitoverride suspend fun updateEpgUrl(id: Long, epgUrl: String) = Unit}-}\ No newline at end of file+}diff --git a/data/src/test/java/com/streamvault/data/repository/ChannelRepositoryImplTest.kt b/data/src/test/java/com/streamvault/data/repository/ChannelRepositoryImplTest.ktindex c16078b5..50adfe5b 100644--- a/data/src/test/java/com/streamvault/data/repository/ChannelRepositoryImplTest.kt+++ b/data/src/test/java/com/streamvault/data/repository/ChannelRepositoryImplTest.kt@@ -1,15 +1,20 @@package com.streamvault.data.repository+import android.database.sqlite.SQLiteExceptionimport com.google.common.truth.Truth.assertThatimport com.streamvault.data.local.dao.CategoryDaoimport com.streamvault.data.local.dao.ChannelDao+import com.streamvault.data.local.dao.FavoriteDaoimport com.streamvault.data.local.entity.CategoryCount+import com.streamvault.data.local.entity.ChannelBrowseEntityimport com.streamvault.data.local.entity.CategoryEntityimport com.streamvault.data.preferences.PreferencesRepositoryimport com.streamvault.data.remote.xtream.XtreamStreamUrlResolverimport com.streamvault.domain.manager.ParentalControlManager+import com.streamvault.domain.model.ChannelNumberingModeimport com.streamvault.domain.model.ContentTypeimport kotlinx.coroutines.flow.first+import kotlinx.coroutines.flow.flowimport kotlinx.coroutines.flow.flowOfimport kotlinx.coroutines.test.runTestimport org.junit.Test@@ -24,6 +29,7 @@ class ChannelRepositoryImplTest {private val channelDao: ChannelDao = mock()private val categoryDao: CategoryDao = mock()+ private val favoriteDao: FavoriteDao = mock()private val preferencesRepository: PreferencesRepository = mock()private val parentalControlManager: ParentalControlManager = mock()private val xtreamStreamUrlResolver: XtreamStreamUrlResolver = mock()@@ -95,9 +101,57 @@ class ChannelRepositoryImplTest {assertThat(result.first { it.id == 20L }.isUserProtected).isFalse()}+ @Test+ fun `getChannelsByCategory hides numbering with zero instead of negative sentinel`() = runTest {+ whenever(channelDao.getByCategory(7L, 10L)).thenReturn(+ flowOf(+ listOf(+ ChannelBrowseEntity(+ id = 1L,+ streamId = 101L,+ name = "News",+ categoryId = 10L,+ categoryName = "News",+ streamUrl = "https://stream",+ number = 42,+ providerId = 7L+ )+ )+ )+ )+ whenever(preferencesRepository.parentalControlLevel).thenReturn(flowOf(0))+ whenever(parentalControlManager.unlockedCategoriesForProvider(7L)).thenReturn(flowOf(emptySet()))+ whenever(preferencesRepository.liveChannelNumberingMode).thenReturn(flowOf(ChannelNumberingMode.HIDDEN))++ val repository = createRepository()++ val result = repository.getChannelsByCategory(7L, 10L).first()++ assertThat(result).hasSize(1)+ assertThat(result.first().number).isEqualTo(0)+ }++ @Test+ fun `searchChannels returns empty list when sqlite throws for malformed fts query`() = runTest {+ whenever(channelDao.search(eq(7L), any(), any())).thenReturn(+ flow { throw SQLiteException("malformed MATCH expression") }+ )+ whenever(preferencesRepository.parentalControlLevel).thenReturn(flowOf(0))+ whenever(preferencesRepository.liveChannelNumberingMode).thenReturn(flowOf(ChannelNumberingMode.PROVIDER))+ whenever(parentalControlManager.unlockedCategoriesForProvider(7L)).thenReturn(flowOf(emptySet()))+ whenever(favoriteDao.getAllByType(7L, ContentType.LIVE.name)).thenReturn(flowOf(emptyList()))++ val repository = createRepository()++ val result = repository.searchChannels(7L, "news").first()++ assertThat(result).isEmpty()+ }+private fun createRepository() = ChannelRepositoryImpl(channelDao = channelDao,categoryDao = categoryDao,+ favoriteDao = favoriteDao,preferencesRepository = preferencesRepository,parentalControlManager = parentalControlManager,xtreamStreamUrlResolver = xtreamStreamUrlResolverdiff --git a/data/src/test/java/com/streamvault/data/repository/EpgRepositoryImplTest.kt b/data/src/test/java/com/streamvault/data/repository/EpgRepositoryImplTest.ktindex 3df29039..90caf60e 100644--- a/data/src/test/java/com/streamvault/data/repository/EpgRepositoryImplTest.kt+++ b/data/src/test/java/com/streamvault/data/repository/EpgRepositoryImplTest.kt@@ -13,7 +13,10 @@ import kotlinx.coroutines.asyncimport kotlinx.coroutines.delayimport kotlinx.coroutines.flow.firstimport kotlinx.coroutines.flow.flowOf+import kotlinx.coroutines.flow.take+import kotlinx.coroutines.flow.toListimport kotlinx.coroutines.runBlocking+import kotlinx.coroutines.test.advanceTimeByimport kotlinx.coroutines.test.runTestimport okhttp3.MediaType.Companion.toMediaTypeimport okhttp3.OkHttpClient@@ -26,12 +29,16 @@ import org.mockito.kotlin.anyimport org.mockito.kotlin.anyOrNullimport org.mockito.kotlin.argumentCaptorimport org.mockito.kotlin.atLeastOnce+import org.mockito.kotlin.doAnswer+import org.mockito.kotlin.eqimport org.mockito.kotlin.mock+import org.mockito.kotlin.neverimport org.mockito.kotlin.timesimport com.streamvault.domain.repository.EpgSourceRepositoryimport org.mockito.kotlin.verifyimport org.mockito.kotlin.wheneverimport java.io.ByteArrayOutputStream+import java.io.IOExceptionimport java.util.concurrent.atomic.AtomicIntegerimport java.util.zip.GZIPOutputStream@@ -274,16 +281,227 @@ class EpgRepositoryImplTest {assertThat(insertedPrograms.allValues.flatten().map { it.title }).contains("Morning News")}+ @Test+ fun `refreshEpg does not double decompress when content encoding and gz suffix are both present`() = runTest {+ val repository = EpgRepositoryImpl(+ programDao = programDao,+ xmltvParser = XmltvParser(),+ okHttpClient = okHttpClientReturningBody(+ body = gzip(+ """+ <tv>+ <programme channel="bbc1.uk" start="20260101000000 +0000" stop="20260101010000 +0000">+ <title>CDN Morning News</title>+ </programme>+ </tv>+ """.trimIndent().toByteArray(Charsets.UTF_8)+ ),+ contentType = "application/xml",+ headers = mapOf("Content-Encoding" to "gzip")+ ),+ transactionRunner = transactionRunner,+ epgSourceRepository = epgSourceRepository+ )++ val result = repository.refreshEpg(7L, "https://example.com/epg.xml.gz")++ assertThat(result.isSuccess).isTrue()+ val insertedPrograms = argumentCaptor<List<ProgramEntity>>()+ verify(programDao, atLeastOnce()).insertAll(insertedPrograms.capture())+ assertThat(insertedPrograms.allValues.flatten().map { it.title }).contains("CDN Morning News")+ }++ @Test+ fun `getNowPlaying refreshes over time for long lived subscriptions`() = runTest {+ whenever(programDao.getNowPlaying(eq(7L), eq("bbc1.uk"), any())).thenReturn(+ flowOf(+ ProgramBrowseEntity(+ id = 1L,+ providerId = 7L,+ channelId = "bbc1.uk",+ title = "Current Show",+ startTime = 100L,+ endTime = 200L+ )+ ),+ flowOf(+ ProgramBrowseEntity(+ id = 2L,+ providerId = 7L,+ channelId = "bbc1.uk",+ title = "Next Show",+ startTime = 200L,+ endTime = 300L+ )+ )+ )++ val repository = EpgRepositoryImpl(+ programDao = programDao,+ xmltvParser = xmltvParser,+ okHttpClient = okHttpClientReturningXml(),+ transactionRunner = transactionRunner,+ epgSourceRepository = epgSourceRepository+ )++ val emissions = mutableListOf<Program?>()+ val collection = async {+ repository.getNowPlaying(7L, "bbc1.uk")+ .take(2)+ .toList(emissions)+ }++ advanceTimeBy(60_000L)+ collection.await()++ assertThat(emissions.map { it?.title }).containsExactly("Current Show", "Next Show").inOrder()+ verify(programDao, times(2)).getNowPlaying(eq(7L), eq("bbc1.uk"), any())+ }++ @Test+ fun `getProgramsForChannelsSnapshot chunks large requests without reactive combine`() = runTest {+ val firstChunk = (1..500).map { index ->+ ProgramBrowseEntity(+ id = index.toLong(),+ providerId = 7L,+ channelId = "channel-$index",+ title = "Program $index",+ startTime = 100L,+ endTime = 200L+ )+ }+ val secondChunk = listOf(+ ProgramBrowseEntity(+ id = 501L,+ providerId = 7L,+ channelId = "channel-501",+ title = "Program 501",+ startTime = 100L,+ endTime = 200L+ )+ )+ whenever(programDao.getForChannelsSync(eq(7L), any(), eq(0L), eq(1_000L))).thenAnswer { invocation ->+ val requestedIds = invocation.getArgument<List<String>>(1)+ if (requestedIds.size == 500) firstChunk else secondChunk+ }++ val repository = EpgRepositoryImpl(+ programDao = programDao,+ xmltvParser = xmltvParser,+ okHttpClient = okHttpClientReturningXml(),+ transactionRunner = transactionRunner,+ epgSourceRepository = epgSourceRepository+ )++ val result = repository.getProgramsForChannelsSnapshot(+ providerId = 7L,+ channelIds = (1..501).map { "channel-$it" },+ startTime = 0L,+ endTime = 1_000L+ )++ assertThat(result).hasSize(501)+ assertThat(result["channel-1"]?.single()?.title).isEqualTo("Program 1")+ assertThat(result["channel-501"]?.single()?.title).isEqualTo("Program 501")+ verify(programDao, times(2)).getForChannelsSync(eq(7L), any(), eq(0L), eq(1_000L))+ verify(programDao, never()).getForChannels(eq(7L), any(), eq(0L), eq(1_000L))+ }++ @Test+ fun `refreshEpg returns typed error when parser hits oversized chunked response`() = runTest {+ whenever(xmltvParser.maybeDecompressGzip(any(), any())).thenReturn(+ object : java.io.InputStream() {+ override fun read(): Int = throw IOException("EPG response too large (>200 MB)")+ }+ )+ whenever(xmltvParser.parseStreaming(any(), any())).thenAnswer { invocation ->+ val input = invocation.getArgument<java.io.InputStream>(0)+ input.read()+ Unit+ }++ val repository = EpgRepositoryImpl(+ programDao = programDao,+ xmltvParser = xmltvParser,+ okHttpClient = okHttpClientReturningXml(),+ transactionRunner = transactionRunner,+ epgSourceRepository = epgSourceRepository+ )++ val result = repository.refreshEpg(7L, "https://example.com/epg.xml")++ assertThat(result.isError).isTrue()+ assertThat(result.errorMessageOrNull()).isEqualTo("EPG response exceeded 200 MB limit")+ }++ @Test+ fun `refreshEpg keeps staging inserts inside a transaction`() = runTest {+ val insertTransactionDepths = mutableListOf<Int>()+ var transactionDepth = 0+ var transactionCount = 0+ val trackingTransactionRunner = object : DatabaseTransactionRunner {+ override suspend fun <T> inTransaction(block: suspend () -> T): T {+ transactionCount+++ transactionDepth+++ try {+ return block()+ } finally {+ transactionDepth--+ }+ }+ }+ doAnswer {+ insertTransactionDepths += transactionDepth+ Unit+ }.whenever(programDao).insertAll(any())+ whenever(xmltvParser.parseStreaming(any(), any())).thenAnswer { invocation ->+ val onProgram = invocation.getArgument<suspend (Program) -> Unit>(1)+ runBlocking {+ repeat(600) { index ->+ onProgram(+ Program(+ providerId = 7L,+ channelId = "channel-$index",+ title = "Program $index",+ description = "",+ startTime = 1_735_722_000_000L + index,+ endTime = 1_735_725_600_000L + index,+ lang = "en"+ )+ )+ }+ }+ }++ val repository = EpgRepositoryImpl(+ programDao = programDao,+ xmltvParser = xmltvParser,+ okHttpClient = okHttpClientReturningXml(),+ transactionRunner = trackingTransactionRunner,+ epgSourceRepository = epgSourceRepository+ )++ val result = repository.refreshEpg(7L, "https://example.com/epg.xml")++ assertThat(result.isSuccess).isTrue()+ assertThat(transactionCount).isEqualTo(2)+ assertThat(insertTransactionDepths).isNotEmpty()+ assertThat(insertTransactionDepths.all { it > 0 }).isTrue()+ }+private fun okHttpClientReturningXml(): OkHttpClient =okHttpClientReturningBody("<tv></tv>".toByteArray(Charsets.UTF_8))private fun okHttpClientReturningBody(body: ByteArray,- contentType: String = "application/xml"+ contentType: String = "application/xml",+ headers: Map<String, String> = emptyMap()): OkHttpClient =OkHttpClient.Builder().addInterceptor { chain ->- Response.Builder()+ Response.Builder().apply {+ headers.forEach { (name, value) -> addHeader(name, value) }+ }.request(chain.request()).protocol(Protocol.HTTP_1_1).code(200)diff --git a/data/src/test/java/com/streamvault/data/repository/EpgSourceRepositoryImplTest.kt b/data/src/test/java/com/streamvault/data/repository/EpgSourceRepositoryImplTest.ktindex 41cb6ff2..fdad9386 100644--- a/data/src/test/java/com/streamvault/data/repository/EpgSourceRepositoryImplTest.kt+++ b/data/src/test/java/com/streamvault/data/repository/EpgSourceRepositoryImplTest.kt@@ -19,6 +19,7 @@ import com.streamvault.domain.model.EpgMatchTypeimport com.streamvault.domain.model.EpgSourceTypeimport com.streamvault.domain.model.Resultimport java.io.ByteArrayInputStream+import java.io.IOExceptionimport kotlinx.coroutines.test.runTestimport okhttp3.OkHttpClientimport org.junit.Before@@ -197,6 +198,26 @@ class EpgSourceRepositoryImplTest {assertThat(decompressedStream.closed).isTrue()}+ @Test+ fun `refreshSource returns typed error when parser hits oversized chunked response`() = runTest {+ val source = EpgSourceEntity(+ id = 10L,+ name = "Primary",+ url = "content://epg/source.xml"+ )++ whenever(epgSourceDao.getById(10L)).thenReturn(source)+ whenever(contentResolver.openInputStream(Uri.parse(source.url))).thenReturn(ByteArrayInputStream("<tv/>".toByteArray()))+ whenever(xmltvParser.maybeDecompressGzip(eq(source.url), any())).thenAnswer { it.arguments[1] }+ whenever(xmltvParser.parseStreamingWithChannels(any(), any(), any())).thenThrow(IOException("EPG response too large (>200 MB)"))++ val result = repository.refreshSource(10L)++ assertThat(result is Result.Error).isTrue()+ assertThat((result as Result.Error).message).isEqualTo("EPG response exceeded 200 MB limit")+ verify(epgSourceDao).updateRefreshStatus(eq(10L), any(), eq("EPG response exceeded 200 MB limit"))+ }+private class CloseTrackingInputStream : ByteArrayInputStream(byteArrayOf()) {var closed: Boolean = falseprivate set@@ -206,4 +227,4 @@ class EpgSourceRepositoryImplTest {super.close()}}-}\ No newline at end of file+}diff --git a/data/src/test/java/com/streamvault/data/repository/FavoriteRepositoryImplTest.kt b/data/src/test/java/com/streamvault/data/repository/FavoriteRepositoryImplTest.ktindex 086141ce..2365881e 100644--- a/data/src/test/java/com/streamvault/data/repository/FavoriteRepositoryImplTest.kt+++ b/data/src/test/java/com/streamvault/data/repository/FavoriteRepositoryImplTest.kt@@ -5,6 +5,7 @@ import com.streamvault.data.local.DatabaseTransactionRunnerimport com.streamvault.data.local.dao.FavoriteDaoimport com.streamvault.data.local.dao.VirtualGroupDaoimport com.streamvault.data.local.entity.FavoriteEntity+import com.streamvault.domain.model.Favoriteimport com.streamvault.domain.model.ContentTypeimport kotlinx.coroutines.ExperimentalCoroutinesApiimport kotlinx.coroutines.flow.emptyFlow@@ -14,6 +15,7 @@ import org.mockito.kotlin.anyimport org.mockito.kotlin.argumentCaptorimport org.mockito.kotlin.doAnswerimport org.mockito.kotlin.mock+import org.mockito.kotlin.neverimport org.mockito.kotlin.verifyimport org.mockito.kotlin.whenever@@ -22,8 +24,17 @@ class FavoriteRepositoryImplTest {private val favoriteDao: FavoriteDao = mock()private val virtualGroupDao: VirtualGroupDao = mock {- on { getByType(any()) } doAnswer { emptyFlow() }+ on { getByType(any(), any()) } doAnswer { emptyFlow() }}+ private val transactionRunner = object : DatabaseTransactionRunner {+ override suspend fun <T> inTransaction(block: suspend () -> T): T = block()+ }++ private val repository = FavoriteRepositoryImpl(+ favoriteDao = favoriteDao,+ virtualGroupDao = virtualGroupDao,+ transactionRunner = transactionRunner+ )@Testfun `addFavorite runs max-position lookup and insert in one transaction`() = runTest {@@ -43,7 +54,7 @@ class FavoriteRepositoryImplTest {}}- whenever(favoriteDao.getMaxPosition(null)).thenAnswer {+ whenever(favoriteDao.getMaxPosition(7L, null)).thenAnswer {getMaxInsideTransaction = inTransaction4}@@ -59,6 +70,7 @@ class FavoriteRepositoryImplTest {)val result = repository.addFavorite(+ providerId = 7L,contentId = 42L,contentType = ContentType.LIVE,groupId = null@@ -70,6 +82,72 @@ class FavoriteRepositoryImplTest {val favoriteCaptor = argumentCaptor<FavoriteEntity>()verify(favoriteDao).insert(favoriteCaptor.capture())+ verify(favoriteDao).getMaxPosition(7L, null)+ assertThat(favoriteCaptor.firstValue.providerId).isEqualTo(7L)assertThat(favoriteCaptor.firstValue.position).isEqualTo(5)}-}\ No newline at end of file++ @Test+ fun `reorderFavorites updates only affected favorites when sparse gap is available`() = runTest {+ val favorites = listOf(+ favorite(id = 1, contentId = 101, position = 0),+ favorite(id = 2, contentId = 102, position = 1_024),+ favorite(id = 3, contentId = 103, position = 2_048),+ favorite(id = 4, contentId = 104, position = 3_072)+ )++ val result = repository.reorderFavorites(+ listOf(favorites[0], favorites[2], favorites[1], favorites[3])+ )++ assertThat(result.isSuccess).isTrue()+ val favoritesCaptor = argumentCaptor<List<FavoriteEntity>>()+ verify(favoriteDao).updateAll(favoritesCaptor.capture())+ assertThat(favoritesCaptor.firstValue.map(FavoriteEntity::id)).containsExactly(3L, 2L).inOrder()+ assertThat(favoritesCaptor.firstValue.map(FavoriteEntity::position)).containsExactly(341, 682).inOrder()+ }++ @Test+ fun `reorderFavorites normalizes whole list when dense positions leave no gap`() = runTest {+ val favorites = listOf(+ favorite(id = 1, contentId = 101, position = 0),+ favorite(id = 2, contentId = 102, position = 1),+ favorite(id = 3, contentId = 103, position = 2),+ favorite(id = 4, contentId = 104, position = 3)+ )++ val result = repository.reorderFavorites(+ listOf(favorites[1], favorites[0], favorites[2], favorites[3])+ )++ assertThat(result.isSuccess).isTrue()+ val favoritesCaptor = argumentCaptor<List<FavoriteEntity>>()+ verify(favoriteDao).updateAll(favoritesCaptor.capture())+ assertThat(favoritesCaptor.firstValue.map(FavoriteEntity::id)).containsExactly(2L, 1L, 3L, 4L).inOrder()+ assertThat(favoritesCaptor.firstValue.map(FavoriteEntity::position))+ .containsExactly(0, 1_024, 2_048, 3_072)+ .inOrder()+ }++ @Test+ fun `reorderFavorites skips writes when order is unchanged`() = runTest {+ val favorites = listOf(+ favorite(id = 1, contentId = 101, position = 0),+ favorite(id = 2, contentId = 102, position = 1_024),+ favorite(id = 3, contentId = 103, position = 2_048)+ )++ val result = repository.reorderFavorites(favorites)++ assertThat(result.isSuccess).isTrue()+ verify(favoriteDao, never()).updateAll(any())+ }++ private fun favorite(id: Long, contentId: Long, position: Int) = Favorite(+ id = id,+ providerId = 7L,+ contentId = contentId,+ contentType = ContentType.LIVE,+ position = position+ )+}diff --git a/data/src/test/java/com/streamvault/data/repository/MovieRepositoryImplTest.kt b/data/src/test/java/com/streamvault/data/repository/MovieRepositoryImplTest.ktindex 7ad8174d..c6b99f1e 100644--- a/data/src/test/java/com/streamvault/data/repository/MovieRepositoryImplTest.kt+++ b/data/src/test/java/com/streamvault/data/repository/MovieRepositoryImplTest.kt@@ -1,5 +1,6 @@package com.streamvault.data.repository+import android.database.sqlite.SQLiteExceptionimport com.google.common.truth.Truth.assertThatimport com.streamvault.data.local.dao.CategoryDaoimport com.streamvault.data.local.dao.FavoriteDao@@ -24,6 +25,7 @@ import com.streamvault.domain.model.ProviderStatusimport com.streamvault.domain.model.ProviderTypeimport com.streamvault.domain.repository.SyncMetadataRepositoryimport kotlinx.coroutines.flow.first+import kotlinx.coroutines.flow.flowimport kotlinx.coroutines.flow.flowOfimport kotlinx.coroutines.test.runTestimport org.junit.Test@@ -81,7 +83,7 @@ class MovieRepositoryImplTest {whenever(preferencesRepository.xtreamBase64TextCompatibility).thenReturn(flowOf(false))whenever(movieDao.getTopRatedPreview(7L, 48)).thenReturn(flowOf(listOf(recommendedMovie, unrelatedMovie, watchedMovie)))whenever(movieDao.getFreshPreview(7L, 48)).thenReturn(flowOf(listOf(recommendedMovie, unrelatedMovie, watchedMovie)))- whenever(favoriteDao.getAllByType(ContentType.MOVIE.name)).thenReturn(flowOf(emptyList()))+ whenever(favoriteDao.getAllByType(7L, ContentType.MOVIE.name)).thenReturn(flowOf(emptyList()))whenever(playbackHistoryDao.getRecentlyWatchedByProvider(eq(7L), eq(24))).thenReturn(flowOf(listOf(@@ -191,6 +193,21 @@ class MovieRepositoryImplTest {verify(movieDao).replaceCategory(eq(7L), eq(42L), any())}+ @Test+ fun `searchMovies returns empty list when sqlite throws for malformed fts query`() = runTest {+ whenever(preferencesRepository.parentalControlLevel).thenReturn(flowOf(0))+ whenever(movieDao.search(eq(7L), any(), any())).thenReturn(+ flow { throw SQLiteException("malformed MATCH expression") }+ )+ whenever(favoriteDao.getAllByType(7L, ContentType.MOVIE.name)).thenReturn(flowOf(emptyList()))++ val repository = createRepository()++ val result = repository.searchMovies(7L, "matrix").first()++ assertThat(result).isEmpty()+ }+private fun createRepository() = MovieRepositoryImpl(movieDao = movieDao,categoryDao = categoryDao,diff --git a/data/src/test/java/com/streamvault/data/repository/PlaybackHistoryRepositoryImplTest.kt b/data/src/test/java/com/streamvault/data/repository/PlaybackHistoryRepositoryImplTest.ktnew file mode 100644index 00000000..28ed6ea9--- /dev/null+++ b/data/src/test/java/com/streamvault/data/repository/PlaybackHistoryRepositoryImplTest.kt@@ -0,0 +1,116 @@+package com.streamvault.data.repository++import com.google.common.truth.Truth.assertThat+import com.streamvault.data.local.DatabaseTransactionRunner+import com.streamvault.data.local.dao.EpisodeDao+import com.streamvault.data.local.dao.MovieDao+import com.streamvault.data.local.dao.PlaybackHistoryDao+import com.streamvault.data.local.entity.PlaybackHistoryEntity+import com.streamvault.data.preferences.PreferencesRepository+import com.streamvault.domain.model.ContentType+import com.streamvault.domain.model.PlaybackHistory+import com.streamvault.domain.model.PlaybackWatchedStatus+import kotlinx.coroutines.flow.flowOf+import kotlinx.coroutines.test.runTest+import org.junit.Test+import org.mockito.kotlin.mock+import org.mockito.kotlin.never+import org.mockito.kotlin.verify+import org.mockito.kotlin.whenever++class PlaybackHistoryRepositoryImplTest {++ private val historyDao: PlaybackHistoryDao = mock()+ private val preferencesRepository: PreferencesRepository = mock()+ private val movieDao: MovieDao = mock()+ private val episodeDao: EpisodeDao = mock()+ private val transactionRunner = object : DatabaseTransactionRunner {+ override suspend fun <T> inTransaction(block: suspend () -> T): T = block()+ }++ private fun repository() = PlaybackHistoryRepositoryImpl(+ dao = historyDao,+ preferencesRepository = preferencesRepository,+ movieDao = movieDao,+ episodeDao = episodeDao,+ transactionRunner = transactionRunner+ )++ private fun movieHistory(+ resumePositionMs: Long = 1_000L,+ totalDurationMs: Long = 10_000L+ ) = PlaybackHistory(+ contentId = 10L,+ contentType = ContentType.MOVIE,+ providerId = 5L,+ title = "Movie",+ streamUrl = "https://provider.example.com/movie",+ resumePositionMs = resumePositionMs,+ totalDurationMs = totalDurationMs,+ watchedStatus = PlaybackWatchedStatus.IN_PROGRESS+ )++ @Test+ fun `clearAllHistory resets denormalized movie and episode progress directly`() = runTest {+ whenever(preferencesRepository.isIncognitoMode).thenReturn(flowOf(false))+ val repository = repository()++ val result = repository.clearAllHistory()++ assertThat(result.isSuccess).isTrue()+ verify(historyDao).deleteAll()+ verify(movieDao).resetAllWatchProgress()+ verify(episodeDao).resetAllWatchProgress()+ }++ @Test+ fun `updateResumePosition buffers writes until later flush point`() = runTest {+ whenever(preferencesRepository.isIncognitoMode).thenReturn(flowOf(false))+ val repository = repository()++ val result = repository.updateResumePosition(movieHistory())++ assertThat(result.isSuccess).isTrue()+ verify(historyDao, never()).insertOrUpdate(org.mockito.kotlin.any())+ verify(movieDao, never()).syncWatchProgressFromHistory(org.mockito.kotlin.any(), org.mockito.kotlin.any())+ }++ @Test+ fun `recordPlayback flushes buffered resume update as one explicit write`() = runTest {+ whenever(preferencesRepository.isIncognitoMode).thenReturn(flowOf(false))+ val repository = repository()++ repository.updateResumePosition(movieHistory(resumePositionMs = 2_000L))+ val result = repository.recordPlayback(movieHistory(resumePositionMs = 3_000L))++ assertThat(result.isSuccess).isTrue()+ verify(historyDao).insertOrUpdate(org.mockito.kotlin.check {+ assertThat(it.resumePositionMs).isEqualTo(3_000L)+ assertThat(it.watchCount).isEqualTo(2)+ })+ verify(movieDao).syncWatchProgressFromHistory(10L, 5L)+ }++ @Test+ fun `getPlaybackHistory falls back to shared tmdb movie history across providers`() = runTest {+ whenever(preferencesRepository.isIncognitoMode).thenReturn(flowOf(false))+ whenever(historyDao.get(10L, ContentType.MOVIE.name, 5L)).thenReturn(null)+ whenever(historyDao.getLatestMovieHistoryBySharedTmdb(10L, 5L)).thenReturn(+ PlaybackHistoryEntity(+ contentId = 42L,+ contentType = ContentType.MOVIE,+ providerId = 9L,+ title = "Movie",+ resumePositionMs = 4_000L,+ totalDurationMs = 10_000L,+ lastWatchedAt = 123L+ )+ )++ val result = repository().getPlaybackHistory(10L, ContentType.MOVIE, 5L)++ assertThat(result).isNotNull()+ assertThat(result?.providerId).isEqualTo(9L)+ assertThat(result?.resumePositionMs).isEqualTo(4_000L)+ }+}diff --git a/data/src/test/java/com/streamvault/data/repository/SeriesRepositoryImplTest.kt b/data/src/test/java/com/streamvault/data/repository/SeriesRepositoryImplTest.ktindex e7565d9a..fdfac0b1 100644--- a/data/src/test/java/com/streamvault/data/repository/SeriesRepositoryImplTest.kt+++ b/data/src/test/java/com/streamvault/data/repository/SeriesRepositoryImplTest.kt@@ -1,5 +1,6 @@package com.streamvault.data.repository+import android.database.sqlite.SQLiteExceptionimport com.google.common.truth.Truth.assertThatimport com.streamvault.data.local.dao.CategoryDaoimport com.streamvault.data.local.dao.EpisodeDao@@ -17,9 +18,11 @@ import com.streamvault.data.remote.xtream.XtreamParsingExceptionimport com.streamvault.data.remote.xtream.XtreamApiServiceimport com.streamvault.data.remote.xtream.XtreamStreamUrlResolverimport com.streamvault.data.security.CredentialCrypto+import com.streamvault.domain.model.ContentTypeimport com.streamvault.domain.model.ProviderStatusimport com.streamvault.domain.model.ProviderTypeimport kotlinx.coroutines.flow.first+import kotlinx.coroutines.flow.flowimport kotlinx.coroutines.flow.flowOfimport kotlinx.coroutines.test.runTestimport org.junit.Test@@ -159,6 +162,21 @@ class SeriesRepositoryImplTest {assertThat(series.posterUrl).isEqualTo("https://img.example.test/poster.jpg")}+ @Test+ fun `searchSeries returns empty list when sqlite throws for malformed fts query`() = runTest {+ whenever(preferencesRepository.parentalControlLevel).thenReturn(flowOf(0))+ whenever(seriesDao.search(eq(7L), any(), any())).thenReturn(+ flow { throw SQLiteException("malformed MATCH expression") }+ )+ whenever(favoriteDao.getAllByType(7L, ContentType.SERIES.name)).thenReturn(flowOf(emptyList()))++ val repository = createRepository()++ val result = repository.searchSeries(7L, "drama").first()++ assertThat(result).isEmpty()+ }+private fun createRepository() = SeriesRepositoryImpl(seriesDao = seriesDao,episodeDao = episodeDao,diff --git a/data/src/test/java/com/streamvault/data/sync/ContentCachePolicyTest.kt b/data/src/test/java/com/streamvault/data/sync/ContentCachePolicyTest.ktnew file mode 100644index 00000000..147d6f86--- /dev/null+++ b/data/src/test/java/com/streamvault/data/sync/ContentCachePolicyTest.kt@@ -0,0 +1,35 @@+package com.streamvault.data.sync++import com.google.common.truth.Truth.assertThat+import org.junit.Test++class ContentCachePolicyTest {++ @Test+ fun `shouldRefresh returns true when timestamp is in the future`() {+ val now = 1_000L+ val lastSyncAt = 2_000L++ val result = ContentCachePolicy.shouldRefresh(+ lastSyncAt = lastSyncAt,+ ttlMillis = 60_000L,+ now = now+ )++ assertThat(result).isTrue()+ }++ @Test+ fun `shouldRefresh returns false when ttl has not expired`() {+ val now = 10_000L+ val lastSyncAt = 9_000L++ val result = ContentCachePolicy.shouldRefresh(+ lastSyncAt = lastSyncAt,+ ttlMillis = 5_000L,+ now = now+ )++ assertThat(result).isFalse()+ }+}diff --git a/data/src/test/java/com/streamvault/data/sync/SyncCatalogStoreTest.kt b/data/src/test/java/com/streamvault/data/sync/SyncCatalogStoreTest.ktnew file mode 100644index 00000000..9371bcd3--- /dev/null+++ b/data/src/test/java/com/streamvault/data/sync/SyncCatalogStoreTest.kt@@ -0,0 +1,300 @@+package com.streamvault.data.sync++import com.google.common.truth.Truth.assertThat+import com.streamvault.data.local.DatabaseTransactionRunner+import com.streamvault.data.local.dao.CatalogSyncDao+import com.streamvault.data.local.dao.CategoryDao+import com.streamvault.data.local.dao.ChannelDao+import com.streamvault.data.local.dao.MovieDao+import com.streamvault.data.local.dao.SeriesDao+import com.streamvault.data.local.dao.TmdbIdentityDao+import com.streamvault.data.local.entity.CategoryEntity+import com.streamvault.data.local.entity.CategoryImportStageEntity+import com.streamvault.data.local.entity.ChannelEntity+import com.streamvault.data.local.entity.ChannelImportStageEntity+import com.streamvault.data.local.entity.MovieEntity+import com.streamvault.data.local.entity.MovieImportStageEntity+import com.streamvault.data.local.entity.SeriesEntity+import com.streamvault.data.local.entity.SeriesImportStageEntity+import com.streamvault.domain.model.ContentType+import kotlinx.coroutines.test.runTest+import org.junit.Test+import org.mockito.kotlin.any+import org.mockito.kotlin.argumentCaptor+import org.mockito.kotlin.eq+import org.mockito.kotlin.mock+import org.mockito.kotlin.never+import org.mockito.kotlin.verify+import org.mockito.kotlin.whenever++class SyncCatalogStoreTest {++ private val channelDao: ChannelDao = mock()+ private val movieDao: MovieDao = mock()+ private val seriesDao: SeriesDao = mock()+ private val categoryDao: CategoryDao = mock()+ private val catalogSyncDao: CatalogSyncDao = mock()+ private val tmdbIdentityDao: TmdbIdentityDao = mock()+ private val transactionRunner = object : DatabaseTransactionRunner {+ override suspend fun <T> inTransaction(block: suspend () -> T): T = block()+ }++ private fun store(sizeLimits: CatalogSizeLimits = CatalogSizeLimits()) = SyncCatalogStore(+ channelDao = channelDao,+ movieDao = movieDao,+ seriesDao = seriesDao,+ categoryDao = categoryDao,+ catalogSyncDao = catalogSyncDao,+ tmdbIdentityDao = tmdbIdentityDao,+ transactionRunner = transactionRunner,+ sizeLimits = sizeLimits+ )++ @Test+ fun `replaceLiveCatalog batches changed category and channel updates`() = runTest {+ val providerId = 7L+ val currentCategory = CategoryEntity(+ id = 11L,+ categoryId = 101L,+ name = "News",+ type = ContentType.LIVE,+ providerId = providerId,+ syncFingerprint = "old-category"+ )+ val currentChannel = ChannelEntity(+ id = 21L,+ streamId = 1001L,+ name = "Old News",+ providerId = providerId,+ streamUrl = "https://old.example.com/live",+ syncFingerprint = "old-channel"+ )++ whenever(categoryDao.getByProviderAndTypeSync(providerId, ContentType.LIVE.name)).thenReturn(listOf(currentCategory))+ whenever(channelDao.getByProviderSync(providerId)).thenReturn(listOf(currentChannel))+ whenever(catalogSyncDao.getCategoryStages(eq(providerId), any(), eq(ContentType.LIVE.name))).thenReturn(+ listOf(+ CategoryImportStageEntity(+ sessionId = 1L,+ providerId = providerId,+ categoryId = 101L,+ name = "World News",+ type = ContentType.LIVE,+ syncFingerprint = "new-category"+ )+ )+ )+ whenever(catalogSyncDao.getChannelStages(eq(providerId), any())).thenReturn(+ listOf(+ ChannelImportStageEntity(+ sessionId = 1L,+ providerId = providerId,+ streamId = 1001L,+ name = "World News HD",+ streamUrl = "https://new.example.com/live",+ syncFingerprint = "new-channel"+ )+ )+ )++ store().replaceLiveCatalog(+ providerId = providerId,+ categories = listOf(currentCategory.copy(name = "World News")),+ channels = listOf(currentChannel.copy(name = "World News HD"))+ )++ val updatedCategories = argumentCaptor<List<CategoryEntity>>()+ verify(categoryDao).updateAll(updatedCategories.capture())+ assertThat(updatedCategories.firstValue.single()).isEqualTo(+ currentCategory.copy(+ name = "World News",+ syncFingerprint = "new-category"+ )+ )++ val updatedChannels = argumentCaptor<List<ChannelEntity>>()+ verify(channelDao).updateAll(updatedChannels.capture())+ assertThat(updatedChannels.firstValue.single()).isEqualTo(+ currentChannel.copy(+ name = "World News HD",+ streamUrl = "https://new.example.com/live",+ syncFingerprint = "new-channel"+ )+ )+ }++ @Test+ fun `applyStagedMovieCatalog batches changed movie updates`() = runTest {+ val providerId = 7L+ val sessionId = 33L+ val currentMovie = MovieEntity(+ id = 31L,+ streamId = 2001L,+ name = "Old Movie",+ providerId = providerId,+ streamUrl = "https://old.example.com/movie",+ syncFingerprint = "old-movie",+ watchProgress = 1234L,+ watchCount = 4+ )++ whenever(movieDao.getByProviderSync(providerId)).thenReturn(listOf(currentMovie))+ whenever(catalogSyncDao.getMovieStages(providerId, sessionId)).thenReturn(+ listOf(+ MovieImportStageEntity(+ sessionId = sessionId,+ providerId = providerId,+ streamId = 2001L,+ name = "New Movie",+ streamUrl = "https://new.example.com/movie",+ rating = 8.2f,+ syncFingerprint = "new-movie"+ )+ )+ )++ store().applyStagedMovieCatalog(providerId, sessionId, categories = null)++ val updatedMovies = argumentCaptor<List<MovieEntity>>()+ verify(movieDao).updateAll(updatedMovies.capture())+ assertThat(updatedMovies.firstValue.single()).isEqualTo(+ currentMovie.copy(+ name = "New Movie",+ streamUrl = "https://new.example.com/movie",+ rating = 8.2f,+ syncFingerprint = "new-movie"+ )+ )+ verify(movieDao).restoreWatchProgress(providerId)+ }++ @Test+ fun `applyStagedSeriesCatalog batches changed series updates`() = runTest {+ val providerId = 7L+ val sessionId = 44L+ val currentSeries = SeriesEntity(+ id = 41L,+ seriesId = 3001L,+ name = "Old Series",+ providerId = providerId,+ syncFingerprint = "old-series"+ )++ whenever(seriesDao.getByProviderSync(providerId)).thenReturn(listOf(currentSeries))+ whenever(catalogSyncDao.getSeriesStages(providerId, sessionId)).thenReturn(+ listOf(+ SeriesImportStageEntity(+ sessionId = sessionId,+ providerId = providerId,+ seriesId = 3001L,+ name = "New Series",+ rating = 9.1f,+ lastModified = 999L,+ syncFingerprint = "new-series"+ )+ )+ )++ store().applyStagedSeriesCatalog(providerId, sessionId, categories = null)++ val updatedSeries = argumentCaptor<List<SeriesEntity>>()+ verify(seriesDao).updateAll(updatedSeries.capture())+ assertThat(updatedSeries.firstValue.single()).isEqualTo(+ currentSeries.copy(+ name = "New Series",+ rating = 9.1f,+ lastModified = 999L,+ syncFingerprint = "new-series"+ )+ )+ }++ @Test+ fun `replaceCategories clears inherited protection when a protected category is remapped`() = runTest {+ val providerId = 7L+ val currentCategory = CategoryEntity(+ id = 51L,+ categoryId = 909L,+ name = "Kids",+ type = ContentType.MOVIE,+ providerId = providerId,+ isUserProtected = true,+ syncFingerprint = "old-category"+ )+ whenever(categoryDao.getByProviderAndTypeSync(providerId, ContentType.MOVIE.name)).thenReturn(listOf(currentCategory))+ whenever(catalogSyncDao.getCategoryStages(eq(providerId), any(), eq(ContentType.MOVIE.name))).thenReturn(+ listOf(+ CategoryImportStageEntity(+ sessionId = 1L,+ providerId = providerId,+ categoryId = 909L,+ name = "Documentaries",+ type = ContentType.MOVIE,+ syncFingerprint = "new-category"+ )+ )+ )++ store().replaceCategories(+ providerId = providerId,+ type = ContentType.MOVIE.name,+ categories = listOf(currentCategory.copy(name = "Documentaries", isUserProtected = false))+ )++ val updatedCategories = argumentCaptor<List<CategoryEntity>>()+ verify(categoryDao).updateAll(updatedCategories.capture())+ assertThat(updatedCategories.firstValue.single()).isEqualTo(+ currentCategory.copy(+ name = "Documentaries",+ isUserProtected = false,+ syncFingerprint = "new-category"+ )+ )+ verify(movieDao).clearProtectionForCategories(providerId, listOf(909L))+ verify(channelDao, never()).clearProtectionForCategories(any(), any())+ verify(seriesDao, never()).clearProtectionForCategories(any(), any())+ }++ @Test+ fun `replaceLiveCatalog keeps lowest numbered channels within configured budget`() = runTest {+ val providerId = 9L+ whenever(categoryDao.getByProviderAndTypeSync(providerId, ContentType.LIVE.name)).thenReturn(emptyList())+ whenever(channelDao.getByProviderSync(providerId)).thenReturn(emptyList())+ whenever(catalogSyncDao.getChannelStages(eq(providerId), any())).thenReturn(emptyList())++ val limitedStore = store(CatalogSizeLimits(maxChannelsPerProvider = 2))+ val channels = listOf(+ ChannelEntity(streamId = 1001L, name = "News", number = 50, providerId = providerId, streamUrl = "https://example.com/50"),+ ChannelEntity(streamId = 1002L, name = "Sports", number = 10, providerId = providerId, streamUrl = "https://example.com/10"),+ ChannelEntity(streamId = 1003L, name = "Movies", number = 30, providerId = providerId, streamUrl = "https://example.com/30")+ )++ val acceptedCount = limitedStore.replaceLiveCatalog(providerId, categories = null, channels = channels)++ assertThat(acceptedCount).isEqualTo(2)+ val insertedChannels = argumentCaptor<List<ChannelImportStageEntity>>()+ verify(catalogSyncDao).insertChannelStages(insertedChannels.capture())+ assertThat(insertedChannels.firstValue.map { it.streamId }).containsExactly(1002L, 1003L).inOrder()+ }++ @Test+ fun `replaceMovieCatalog keeps highest rated movies within configured budget`() = runTest {+ val providerId = 11L+ whenever(movieDao.getByProviderSync(providerId)).thenReturn(emptyList())+ whenever(catalogSyncDao.getMovieStages(eq(providerId), any())).thenReturn(emptyList())++ val limitedStore = store(CatalogSizeLimits(maxMoviesPerProvider = 2))+ val movies = sequenceOf(+ MovieEntity(streamId = 2001L, name = "Movie A", providerId = providerId, streamUrl = "https://example.com/a", rating = 4.2f),+ MovieEntity(streamId = 2002L, name = "Movie B", providerId = providerId, streamUrl = "https://example.com/b", rating = 9.1f),+ MovieEntity(streamId = 2003L, name = "Movie C", providerId = providerId, streamUrl = "https://example.com/c", rating = 7.6f)+ )++ val acceptedCount = limitedStore.replaceMovieCatalog(providerId, categories = null, movies = movies)++ assertThat(acceptedCount).isEqualTo(2)+ val insertedMovies = argumentCaptor<List<MovieImportStageEntity>>()+ verify(catalogSyncDao).insertMovieStages(insertedMovies.capture())+ assertThat(insertedMovies.firstValue.map { it.streamId }).containsExactly(2002L, 2003L).inOrder()+ }+}diff --git a/data/src/test/java/com/streamvault/data/sync/SyncManagerTest.kt b/data/src/test/java/com/streamvault/data/sync/SyncManagerTest.ktindex f94bf0f7..d16282ed 100644--- a/data/src/test/java/com/streamvault/data/sync/SyncManagerTest.kt+++ b/data/src/test/java/com/streamvault/data/sync/SyncManagerTest.kt@@ -1,6 +1,7 @@package com.streamvault.data.syncimport com.google.common.truth.Truth.assertThat+import android.content.Contextimport com.streamvault.data.local.DatabaseTransactionRunnerimport com.streamvault.data.local.dao.CatalogSyncDaoimport com.streamvault.data.local.dao.CategoryDao@@ -9,6 +10,7 @@ import com.streamvault.data.local.dao.MovieDaoimport com.streamvault.data.local.dao.ProgramDaoimport com.streamvault.data.local.dao.ProviderDaoimport com.streamvault.data.local.dao.SeriesDao+import com.streamvault.data.local.dao.TmdbIdentityDaoimport com.streamvault.data.local.entity.ProviderEntityimport com.streamvault.data.parser.M3uParserimport com.streamvault.data.security.CredentialCrypto@@ -19,7 +21,10 @@ import com.streamvault.domain.model.SyncMetadataimport com.streamvault.domain.repository.EpgRepositoryimport com.streamvault.domain.repository.EpgSourceRepositoryimport com.streamvault.data.preferences.PreferencesRepository+import kotlinx.coroutines.CompletableDeferredimport kotlinx.coroutines.ExperimentalCoroutinesApi+import kotlinx.coroutines.async+import kotlinx.coroutines.runBlockingimport kotlinx.coroutines.flow.Flowimport kotlinx.coroutines.flow.firstimport kotlinx.coroutines.flow.flowOf@@ -70,6 +75,7 @@ class SyncManagerTest {listOfNotNull(provider).filter { it.id in ids }override suspend fun updateSyncTime(id: Long, timestamp: Long) = Unitoverride fun getAll() = kotlinx.coroutines.flow.flowOf(listOfNotNull(provider))+ override suspend fun getAllSync(): List<ProviderEntity> = listOfNotNull(provider)override fun getActive() = kotlinx.coroutines.flow.flowOf(provider)override suspend fun insert(entity: ProviderEntity) = provider?.id ?: 0Loverride suspend fun update(entity: ProviderEntity) = Unit@@ -160,6 +166,7 @@ class SyncManagerTest {private val programDao: ProgramDao = mock()private val categoryDao: CategoryDao = mock()private val catalogSyncDao: CatalogSyncDao = mock()+ private val tmdbIdentityDao: TmdbIdentityDao = mock()private val epgRepo: EpgRepository = mock()private val epgSourceRepo: EpgSourceRepository = mock()private val preferencesRepo: PreferencesRepository = mock()@@ -188,6 +195,7 @@ class SyncManagerTest {programDao,categoryDao,catalogSyncDao,+ tmdbIdentityDao,epgRepo,epgSourceRepo,preferencesRepo@@ -195,6 +203,16 @@ class SyncManagerTest {org.mockito.kotlin.whenever(preferencesRepo.useXtreamTextClassification).thenReturn(flowOf(false))org.mockito.kotlin.whenever(preferencesRepo.xtreamBase64TextCompatibility).thenReturn(flowOf(false))org.mockito.kotlin.whenever(preferencesRepo.getHiddenCategoryIds(any(), any())).thenReturn(flowOf(emptySet()))+ runBlocking {+ org.mockito.kotlin.whenever(categoryDao.getByProviderAndTypeSync(any(), any())).thenReturn(emptyList())+ org.mockito.kotlin.whenever(channelDao.getByProviderSync(any())).thenReturn(emptyList())+ org.mockito.kotlin.whenever(movieDao.getByProviderSync(any())).thenReturn(emptyList())+ org.mockito.kotlin.whenever(seriesDao.getByProviderSync(any())).thenReturn(emptyList())+ org.mockito.kotlin.whenever(catalogSyncDao.getCategoryStages(any(), any(), any())).thenReturn(emptyList())+ org.mockito.kotlin.whenever(catalogSyncDao.getChannelStages(any(), any())).thenReturn(emptyList())+ org.mockito.kotlin.whenever(catalogSyncDao.getMovieStages(any(), any())).thenReturn(emptyList())+ org.mockito.kotlin.whenever(catalogSyncDao.getSeriesStages(any(), any())).thenReturn(emptyList())+ }}private fun buildManager(@@ -202,6 +220,7 @@ class SyncManagerTest {providerPresent: Boolean = true,providerEntity: ProviderEntity? = null): SyncManager = SyncManager(+ applicationContext = mock<Context>(),providerDao = FakeProviderDao(if (providerPresent) {providerEntity ?: sampleProvider(providerType)@@ -215,6 +234,7 @@ class SyncManagerTest {programDao = programDao,categoryDao = categoryDao,catalogSyncDao = catalogSyncDao,+ tmdbIdentityDao = tmdbIdentityDao,xtreamJson = xtreamJson,m3uParser = M3uParser(),epgRepository = epgRepo,@@ -294,9 +314,13 @@ class SyncManagerTest {SyncMetadata(providerId = 1L,lastLiveSync = now,+ lastLiveSuccess = now,lastMovieSync = now,+ lastMovieSuccess = now,lastSeriesSync = now,- lastEpgSync = now+ lastSeriesSuccess = now,+ lastEpgSync = now,+ lastEpgSuccess = now))@@ -307,6 +331,49 @@ class SyncManagerTest {assertThat(xtreamBackend.requestCount()).isEqualTo(0)}+ @Test+ fun `sync_xtream_partial_live_timestamp_does_not_suppress_retry`() = runTest {+ val mgr = buildManager(providerType = ProviderType.XTREAM_CODES)+ val now = System.currentTimeMillis()+ syncMetadataRepo.updateMetadata(+ SyncMetadata(+ providerId = 1L,+ lastLiveSync = now,+ lastLiveSuccess = 0L,+ lastMovieSync = now,+ lastMovieSuccess = now,+ lastSeriesSync = now,+ lastSeriesSuccess = now,+ lastEpgSync = now,+ lastEpgSuccess = now+ )+ )+ xtreamBackend.respond(action = "get_live_categories", body = """[{"category_id":"1","category_name":"News"}]""")+ xtreamBackend.respond(+ action = "get_live_streams",+ body = """+ [+ {+ "name": "Channel One",+ "stream_id": 1001,+ "category_id": "1",+ "stream_icon": "https://example.com/ch1.png",+ "tv_archive": 0,+ "num": 1+ }+ ]+ """.trimIndent()+ )++ val result = mgr.sync(1L, force = false)+ advanceUntilIdle()++ assertThat(result.isSuccess).isTrue()+ assertThat(xtreamBackend.requestedActions).contains("get_live_categories")+ val updated = syncMetadataRepo.getMetadata(1L)+ assertThat(updated?.lastLiveSuccess ?: 0L).isGreaterThan(0L)+ }+@Testfun `sync_xtream_falls_back_to_movie_categories_from_streams`() = runTest {val mgr = buildManager(providerType = ProviderType.XTREAM_CODES)@@ -315,8 +382,11 @@ class SyncManagerTest {SyncMetadata(providerId = 1L,lastLiveSync = now,+ lastLiveSuccess = now,lastSeriesSync = now,- lastEpgSync = now+ lastSeriesSuccess = now,+ lastEpgSync = now,+ lastEpgSuccess = now))xtreamBackend.respond(action = "get_vod_categories", body = """{"error":"categories unavailable"}""", code = 500)@@ -355,8 +425,11 @@ class SyncManagerTest {SyncMetadata(providerId = 1L,lastLiveSync = now,+ lastLiveSuccess = now,lastSeriesSync = now,- lastEpgSync = now+ lastSeriesSuccess = now,+ lastEpgSync = now,+ lastEpgSuccess = now))xtreamBackend.respond(@@ -414,7 +487,9 @@ class SyncManagerTest {SyncMetadata(providerId = 1L,lastLiveSync = now,- lastEpgSync = now+ lastLiveSuccess = now,+ lastEpgSync = now,+ lastEpgSuccess = now))org.mockito.kotlin.whenever(movieDao.getCount(1L)).thenReturn(flowOf(0))@@ -530,6 +605,44 @@ class SyncManagerTest {assertThat(mgr.currentSyncState(1L)).isInstanceOf(SyncState.Error::class.java)}+ @Test+ fun `onProviderDeleted resets state and notifies epg repository`() = runTest {+ val mgr = buildManager()+ mgr.sync(1L)+ advanceUntilIdle()++ assertThat(mgr.currentSyncState(1L)).isNotEqualTo(SyncState.Idle)++ mgr.onProviderDeleted(1L)++ assertThat(mgr.currentSyncState(1L)).isEqualTo(SyncState.Idle)+ verify(epgRepo).onProviderDeleted(1L)+ }++ @Test+ fun `runWhenNoSyncActive returns false while a sync is in flight`() = runTest {+ val provider = sampleProvider(ProviderType.M3U).copy(epgUrl = "https://epg.example.com/guide.xml")+ val mgr = buildManager(providerType = ProviderType.M3U, providerEntity = provider)+ val syncEntered = CompletableDeferred<Unit>()+ val releaseSync = CompletableDeferred<Unit>()+ org.mockito.kotlin.whenever(epgRepo.refreshEpg(1L, "https://epg.example.com/guide.xml")).thenAnswer {+ syncEntered.complete(Unit)+ runBlocking { releaseSync.await() }+ Result.success(Unit)+ }++ val syncJob = async {+ mgr.retrySection(providerId = 1L, section = SyncRepairSection.EPG)+ }+ syncEntered.await()++ val vacuumAllowed = mgr.runWhenNoSyncActive { true }+ releaseSync.complete(Unit)++ assertThat(vacuumAllowed).isFalse()+ syncJob.await()+ }+// ── Reset state ─────────────────────────────────────────────────@Testdiff --git a/data/src/test/java/com/streamvault/data/util/AdultContentClassifierTest.kt b/data/src/test/java/com/streamvault/data/util/AdultContentClassifierTest.ktindex 7b2a9abf..66dc95ca 100644--- a/data/src/test/java/com/streamvault/data/util/AdultContentClassifierTest.kt+++ b/data/src/test/java/com/streamvault/data/util/AdultContentClassifierTest.kt@@ -5,6 +5,21 @@ import org.junit.Testclass AdultContentClassifierTest {+ @Test+ fun `cache uses bounded eviction instead of full flush`() {+ AdultContentClassifier.resetCacheForTesting()++ repeat(4096) { index ->+ AdultContentClassifier.isAdultCategoryName("Category $index")+ }+ AdultContentClassifier.isAdultCategoryName("Category 4095")+ AdultContentClassifier.isAdultCategoryName("Category 4096")++ assertThat(AdultContentClassifier.cacheSizeForTesting()).isEqualTo(4096)+ assertThat(AdultContentClassifier.isCachedForTesting("Category 4095")).isTrue()+ assertThat(AdultContentClassifier.isCachedForTesting("Category 0")).isFalse()+ }+@Testfun `matches plus18 and adults labels used by xtream categories`() {assertThat(AdultContentClassifier.isAdultCategoryName("|+18| ADULTS LIVE")).isTrue()@@ -38,4 +53,4 @@ class AdultContentClassifierTest {fun `boundary terms avoid obvious false positives`() {assertThat(AdultContentClassifier.isAdultCategoryName("Essex Sports")).isFalse()}-}\ No newline at end of file+}diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.mdindex bc547ee6..c15d8ddc 100644--- a/docs/CHANGELOG.md+++ b/docs/CHANGELOG.md@@ -1,139 +1,276 @@-# Changelog+# ChangelogAll notable product changes are recorded in this document.+## [1.0.5] - 2026-04-16-## 1.0.4 - 11/04/2026+### Added++#### Live Playback & DVR+- Added live rewind (timeshift) for live channels — up to 30 minutes buffer.+- Added timeline scrubber with live-edge indicator and seek controls.+- Added recording, catch-up, and restart controls directly in the player overlay.+- Added DASH stream support to the rewind engine.++#### Performance & Browsing+- Added incremental channel loading for large providers.+- Added incremental search results with automatic loading on scroll.+- Added automatic paging when reaching the end of the channel list.++#### System & Settings+- Added timeshift storage manager with automatic cleanup.+- Added auto-return on failed channels toggle.+- Added automatic update download option.+- Added options to show/hide “All Channels” and “Recent Channels”.+- Added "Hidden" option to Live TV Channel Numbering — hides channel numbers everywhere in the app (channel lists, player overlay, EPG, zap banner).++#### VOD+- "Filter & Sort" button now shows active selections as a subtitle (e.g. "Favorites · Rating") and highlights with brand colour when non-default settings are applied — applies to both Movies and Series, modern and classic views.++#### Search+- Long-pressing a channel, movie, or series in Search now opens a context menu with Add/Remove Favorites, Hide, and Parental Lock/Unlock actions — consistent with the same actions available in other screens.-### Changed-- Updated VOD playback preparation to carry richer resolved stream metadata into the shared player path, improving compatibility with provider-resolved movie and episode streams.-- Updated TV Guide category selection so Favorites and custom live groups appear in the guide category list, Favorites becomes the entry default when it has channels, and Settings now lets you choose the guide's default startup category.-- Updated Settings navigation by splitting the crowded Playback tab into separate Playback and Browsing sections, moving guide, Live TV, VOD layout, and category browsing preferences into their own dedicated area.-- Updated Settings provider sync so the default action now runs a lighter quick sync, provider switching only auto-refreshes stale providers, and the sync overlay shows the current provider and live progress text.-- Updated Xtream text handling with an optional Base64 compatibility toggle in Settings so provider names and categories stay raw by default, while broad Base64 decoding can be enabled for edge-case feeds.-- Updated Xtream text compatibility toggles so changing them invalidates cached Xtream text imports and forces the next refresh for each Xtream provider once.-- Updated the About screen with official build verification based on the app id and release signing certificate fingerprint.-- Massive code refactoring to reduce large files size.+#### Database & Sync+- Search now indexes title, cast, director, and genre with BM25 relevance ranking — results are ordered by match quality.+- Program reminders — tap any guide entry to be notified before a show starts without scheduling a full recording.+- Watch progress and favorites are unified across providers for the same TMDB title — resume a movie on any provider from where you left off.+- Provider catalogs now enforce per-provider row limits to prevent malformed feeds from consuming device storage.+- EPG channel match quality is tracked per channel; channels with weak or missing EPG assignments surface in provider settings.+- Database diagnostics in Settings showing storage usage, per-table row counts, fragmentation level, and maintenance history.+- Background catalog and EPG sync jobs now survive process death and retry automatically on network recovery.+- Search history is now per content-type, timestamped, and stored in the database.+---++### Improved+- Faster loading and lower memory usage for large channel lists.+- More stable playback when switching channels.+- Numeric channel entry now accepts up to 6 digits before resetting, which supports larger provider lineups.+- Better handling of live stream buffering and recovery.+- Improved recording settings layout with cleaner action grouping and a dedicated recordings browser dialog.+- Improved update UI feedback during downloads.+- EPG source delete now requires confirmation to prevent accidental removal.+- Refreshing an EPG source shows a per-source loading indicator instead of a global spinner, so multiple sources can refresh independently.+- Settings screen content scrolls up correctly when the keyboard opens, keeping text fields visible while typing.+- EPG feeds with non-UTF-8 encodings (ISO-8859-1/2, Windows-1252, etc.) now parse correctly — channel names and programme titles no longer appear garbled.+- EPG download read timeout increased from 30 s to 120 s for large or slow feeds.+- Catalog sync for large providers is significantly faster — field changes are diffed in Kotlin and applied in a single batched update instead of per-column correlated subqueries.+- EPG program data is now retained for the full catch-up window of each channel (up to 7 days) instead of a fixed 24-hour cutoff.+- EPG staging writes for large feeds are committed in a single transaction, cutting write time for 50 000-program feeds by roughly 10×.+- Series sync now skips unchanged series using server-provided last-modified timestamps, reducing API traffic on repeat refreshes.+- EPG and Xtream API responses are cached using server Cache-Control and ETag headers, eliminating redundant downloads on unchanged feeds.+- Channel and VOD browse lists now use keyset pagination — no items are skipped or duplicated during concurrent syncs and deep pages load faster.+- Movie and series watch-count sort no longer runs a subquery per row — watch count is stored on the content record.+- Playback progress is batched and flushed on a 30-second interval instead of writing to the database on every player tick.+- Partial sync no longer resets the provider refresh timer — only a complete successful sync marks a provider as up to date.++---### Fixed-- Fixed EPG override candidate list stability by adding a stable Compose item key, avoiding unnecessary item churn when override search results update.-- Fixed multi-source XMLTV refresh to close the decompressed input wrapper explicitly after parsing, matching the provider-native EPG refresh path and avoiding leaked gzip/parser stream wrappers on source refreshes.-- Fixed DRM metadata validation so invalid or unsafe DRM license URLs are rejected by the shared stream-entry URL policy before they can reach player Media3 DRM configuration.-- Fixed Xtream Home and guide fallback EPG lookups to batch missing-channel requests through a shared repository path, so provider loading, credential decryption, and Xtream client setup are reused once per fallback burst instead of repeating per channel.-- Fixed Combined M3U profile creation to batch-load selected providers through `ProviderDao.getByIds(...)` instead of issuing one provider lookup per selected source.-- Fixed TV launcher recommendation syncing so preview-channel refresh now runs on `Dispatchers.IO`, serializes overlapping refresh calls, and rate-limits repeated syncs to reduce startup and playback-exit `TvContract` churn.-- Fixed backup export/checksum generation to stream JSON through a writer pipeline instead of materializing large intermediate backup strings before writing or hashing.-- Fixed EPG guide recomposition scope by moving the shared guide clock out of the top-level guide screen and into smaller hero, grid, and dialog subtrees so routine 30-second time updates no longer invalidate the full guide shell.-- Fixed `FileProvider` update-install exposure by restricting shared paths to the APK download directory only and removing the broad cache-root grant surface.-- Fixed in-app updates to require HTTPS release and APK download URLs while leaving HTTP IPTV playback compatibility unchanged.-- Fixed recurring recording rollover so future daily/weekly occurrences detect conflicts with existing manual or active recordings, mark skipped slots as `SCHEDULE_CONFLICT`, and continue searching for the next free slot.-- Fixed Cast startup for unsupported `rtsp://` and `rtmp://` streams by rejecting them early and showing a clear in-app notice instead of failing silently on the receiver.-- Fixed Xtream playback expiry handling so auth-like `401/403` stream failures now trigger a one-time URL refresh and replay attempt before surfacing a playback error.-- Fixed player teardown to clear cached seek-preview thumbnails when the player screen is destroyed, reducing stale bitmap retention across playback sessions.-- Fixed recurring DVR rollover to calculate the next daily or weekly occurrence in local time, preventing schedules from drifting by an hour across Daylight Saving Time changes.-- Fixed offline library launches so Home now shows an “Add your first provider” empty state, while Movies and Series show a clear “Sync needed” state instead of waiting on indefinite loading spinners.-- Fixed parental PIN changes to immediately clear all in-memory unlocked categories so previously unlocked content requires the new PIN right away.-- Fixed top navigation focus so switching between top-bar destinations no longer snaps focus back to the Home tab.-- Fixed in-app update downloads that could remain stuck on `Downloading...` by improving download tracking and completion handling.-- Fixed M3U importer to throw descriptive non-transient HTTP errors so CombinedM3U profiles properly skip dead sources gracefully instead of failing silently.-- Fixed player to immediately identify expired stream URLs and natively return a user-friendly expiration notice instead of triggering empty generic playback failure.-- Fixed `M3uParser` to use idiomatic Kotlin `.lineSequence()` iteration while preserving its strict one-line-in-memory footprint during massive playlist operations.-- Fixed M3U catch-up detection and replay URL expansion so archive-capable playlists using `catchup-source`, `timeshift`, and common replay placeholders are wired correctly.-- Fixed catch-up and replay handling across M3U and Xtream providers with added regression coverage for archive metadata parsing and replay URL building.-- Fixed player startup stability so normal playback no longer eagerly creates split-screen state that could crash channel and episode opens before playback begins.-- Fixed shared player initialization to defer several constructor-time playback state subscriptions, reducing intermittent crashes when opening Live TV and series episodes.-- Fixed Xtream playback startup handling so provider-auth failures such as `401` and `403` are surfaced as player errors/notices instead of continuing into a broken playback open path.-- Fixed provider setup so Xtream-backed playlist URLs such as `get.php?...type=m3u` and `get.php?...type=m3u_plus` are recognized automatically and imported through the Xtream parser instead of the plain M3U path.-- Fixed TV provider setup Back behavior so pressing Back while editing a field now cancels that field edit first, and incomplete unnamed drafts prompt before leaving the screen.-- Fixed TV long-press dialogs so the delayed DPAD/select key release that opens a dialog can no longer immediately trigger the first focused action by accident.-- Fixed in-app update version parsing to read structured build metadata from GitHub release tags such as `v1.0.4+4` instead of scraping version codes from release-note prose.-- Fixed background EPG scheduling so fast-completing refresh jobs are tracked and cleaned up reliably instead of leaving stale job entries behind.-- Fixed provider deletion cleanup so sync teardown now waits on the per-provider lock before dropping sync state and mutex tracking.-- Fixed player stats collection races by making dropped-frame, format, and bandwidth tracking safe across ExoPlayer callbacks and the polling coroutine.-- Fixed live-stream retry recovery so behind-live-window errors now wait briefly and jump back to the live edge before retrying.-- Fixed the in-app update checker to cap GitHub release API response size before JSON parsing, avoiding unbounded memory reads.-- Fixed preloaded stream reuse to compare exact normalized URLs and marked the preload coordinator as main-thread-only to avoid unsafe cross-thread access assumptions.-- Fixed FTS search query building so blank or fully stripped search text no longer reaches Room as an empty `MATCH` query and crash search flows.-- Fixed Xtream text decoding by treating channel, movie, series, episode, and category names as raw provider text by default while limiting automatic base64 decode to EPG and common metadata fields.-- Fixed database maintenance so daily VACUUM is skipped when active read transactions are open (WAL busy-page check) or a provider sync is in progress, preventing the exclusive DB lock from blocking channel loads, EPG queries, and sync writes during background maintenance.-- Fixed database maintenance logging to measure and record the actual duration of the sqlite `VACUUM` compaction.-- Fixed parental control unlock state management to use lock-free `StateFlow.update {}` instead of JVM `synchronized` blocks, eliminating the risk of thread blocking and potential ANR on the main thread when unlock, retain, or clear operations are called from coroutines.-- Fixed a dead `LINE_BREAK_REGEX` alias in `ProviderInputSanitizer` that was identical to `WHITESPACE_REGEX`; the duplicate constant was removed and the single call site updated to use the canonical name.-- Fixed a URL injection bypass in `UrlSecurityPolicy` where double-encoded newlines (`%250A`) and tabs (`%09`) could evade the single-pass `containsNewlines()` check; the decoder now runs two passes and also strips tab characters.-- Fixed `AppUpdateInstaller` to expose an `unregister()` method that safely unregisters the `DownloadManager` broadcast receiver, preventing duplicate receiver registrations when the DI graph is re-created in instrumentation tests.-- Fixed `AppUpdateInstaller` to verify downloaded APKs against expected SHA-256 hashes (if provided by the release) before launching the system package installer, preventing execution of tampered or truncated updates.-- Fixed `SyncManager.onProviderDeleted()` to log a warning when a background EPG job is still active at the time of cancellation, making mid-sync provider deletions visible in production logs.-- Fixed `SeekThumbnailProvider.loadFrame()` to wrap `MediaMetadataRetriever` usage in an 8-second `withTimeoutOrNull` guard, preventing indefinite thread blocking on live IPTV streams served as raw MPEG-TS over HTTP that pass the `.m3u8`/`.mpd` exclusion check.-- Fixed `PlayerStatsCollector` to run its polling loop on `Dispatchers.Main.immediate` instead of `Dispatchers.Default`, eliminating 2–3 needless thread context switches every 250 ms per active player (up to 12 per second in 4-player multiview). Removed the now-redundant `readPlayerSnapshot` suspend function and its `withContext` wrapper; removed `@Volatile` annotations and `AtomicInteger` usage since ExoPlayer analytics callbacks are delivered on the Main thread.-- Fixed `CredentialCrypto` so it is now an interface with a concrete Hilt-provided implementation rather than a hardcoded `object` singleton, enabling standard mock injection during viewmodel and repository tests.-- Fixed `PreloadCoordinator` state invalidation so stream headers and DRM keys are digested using content-stable deterministic SHA-256 hashes instead of JVM memory-address dependent `hashCode()` that breaks across app restarts.-- Fixed `StreamVaultDatabaseMigrationTest` so the full-chain migration verification now sequentially applies and validates the entire schema history spanning from v1 up through the current v30 database version.-- Fixed DVR scheduling from stale guide selections so recording setup now rejects programmes that have already ended and prompts the user to refresh the guide instead of building an invalid request.-- Fixed Xtream playlist auto-import validation so oversized decoded `username` and `password` query parameters are rejected before the playlist URL is converted into an Xtream login request.-- Fixed audio-only playback retry handling so radio and other no-video streams are treated as started once the player is actually ready and playing, instead of waiting forever for a first video frame callback.-- Fixed main player-engine release lifecycle so teardown no longer cancels and rebuilds its shared coroutine scope between playback sessions.-- Fixed Xtream provider setup error handling so the UI now maps login failures from typed exception causes instead of brittle substring checks against arbitrary error text.-- Fixed provider EPG cache replacement and playback-history denormalization writes to run inside Room transactions, preventing partial multi-step database updates.-- Fixed domain continue-watching, recommendation, and search flows to stop masking non-IO upstream failures as empty-state content, so critical data/query faults surface instead of silently disappearing.-- Fixed Movies and Series category browsing to memoize visible-category membership and filtered category rows, reducing repeated list scanning during large-library recompositions.-- Fixed TV Guide hero and channel-row current-program lookups to use derived state, reducing redundant per-channel program rescans on the shared 30-second guide clock.--## 1.0.3 - 09/04/2026++#### Playback+- Fixed incorrect channel info after auto-revert.+- Fixed repeated auto-revert causing channel switching loops.+- Fixed last-channel behavior after fallback.+- Fixed RTSP stream playback handling.+- Fixed MPEG-TS playback issues (black screen / corrupt frames).+- Fixed live buffer seeking returning incorrectly.+- Fixed player crashes on some devices.++#### Streaming & Stability+- Fixed stream detection for Xtream channels.+- Fixed DRM handling causing repeated retries.+- Fixed expired stream URLs during playback.+- Fixed Xtream live recordings failing when provider direct-source URLs expired mid-recording.+- Fixed behind-live-window recovery issues.+- Fixed playback restarting due to EPG updates.++#### UI & Behavior+- Fixed update status stuck on “Downloading”.+- Fixed numeric channel input issues (0 handling).+- Fixed Picture-in-Picture activating incorrectly.+- Fixed missing channel handling after playlist refresh.+- Fixed active recording failures disappearing silently from the player without a notice.+- Fixed garbled average-speed placeholder text in recording details.+- Fixed favorites and custom groups being shared across unrelated providers. Combined M3U sources now merge member-provider favorites and groups in Home and Guide while saving changes back to the original provider.+- Fixed EPG category fallback logic.++#### EPG & Guide+- Fixed `.gz` EPG feeds being double-decompressed and failing to parse.+- Fixed blank URL accepted past the scheme validator when adding an EPG source.+- Fixed EPG list always appearing empty after a fresh install (list was never populated into the UI state).++#### VOD+- Fixed "New to Old" sort not working for Movies. The `added` timestamp is now correctly used across the full pipeline, matching how series sorting works.++#### Provider Sync+- Fixed sync failing with "Login succeeded, but the initial sync failed" for live-only providers with no VOD or series content.+- Fixed providers with fast sync enabled showing **Partial** status incorrectly — providers now show **Active** when fast sync completes as intended.+- Fixed VOD-only providers (no live TV) failing on first sync when the server returns an empty live-streams response.++#### Database & Cache+- Fixed watch status not updating correctly after history was cleared — unwatched state is now read from the authoritative history table.+- Fixed stale data left behind when a provider was deleted while a sync was in progress.+- Fixed a background EPG job leaking a phantom reference when the job completed before it was registered.+- Fixed "now playing" showing an ended program on long-lived guide screens — current time is refreshed on each display tick.+- Fixed a forward clock jump suppressing cache refreshes beyond the corrected window.+- Fixed FTS search queries with unbalanced quotes or SQLite reserved operators causing crashes — malformed input is now sanitized before reaching the database.+- Fixed EPG provider mutex entries not being removed on provider deletion, leaking memory over long sessions.+- Fixed VACUUM maintenance running concurrently with an active sync, causing spurious sync failures.+- Fixed VACUUM pre-flight silently truncating the WAL file — replaced with a non-destructive passive checkpoint.+- Fixed favorites reordering issuing one database write per item — reordering now uses a single bulk update.+- Fixed category protection not being cleared when category IDs were remapped during a provider catalog restructure.+- Fixed sync session ID collisions after a clock correction — sessions now use random identifiers.+- Fixed database migrations that rebuild tables not verifying foreign key integrity before completing.+---++### Notes+- Live rewind works without provider catch-up support.+- Large playlists now load progressively instead of all at once.++## [1.0.4] - 2026-04-11++### Improved++#### Playback & Streaming+- Improved VOD playback compatibility with provider-resolved streams.+- Improved handling of expired Xtream stream URLs with automatic retry.+- Improved live-stream retry behavior and recovery.++#### TV Guide & Browsing+- Favorites and custom groups now appear in the TV Guide.+- Guide can now start on a selected default category.+- Improved category fallback when channels are missing.+- Improved browsing experience for Movies and Series categories.++#### Settings & UX+- Split Settings into separate Playback and Browsing sections.+- Improved provider sync with faster quick-sync and clearer progress feedback.+- Added Base64 compatibility toggle for Xtream providers.+- Improved About screen with build verification.++---++### Fixed++#### Playback+- Fixed playback failures for expired or invalid stream URLs.+- Fixed RTSP/RTMP casting failing silently.+- Fixed player startup crashes in some cases.+- Fixed audio-only streams not starting correctly.+- Fixed seek-preview thumbnails not clearing properly.++#### EPG & Guide+- Fixed EPG refresh stability and fallback behavior.+- Fixed EPG updates causing unnecessary UI refreshes.+- Fixed stale EPG data overwriting active channels.++#### DVR & Scheduling+- Fixed recurring recording conflicts and scheduling issues.+- Fixed DST-related recording time drift.+- Fixed invalid recordings being scheduled from outdated guide data.++#### Providers & Data+- Fixed Xtream playlist detection and import handling.+- Fixed M3U catch-up and replay support.+- Fixed provider sync inefficiencies and repeated loading.+- Fixed provider deletion cleanup and background sync issues.++#### Updates & Security+- Fixed update downloads getting stuck.+- Enforced HTTPS for update downloads.+- Improved APK integrity verification before install.+- Fixed URL validation edge cases.++#### UI & Behavior+- Fixed navigation focus issues in TV UI.+- Fixed numeric channel input handling.+- Fixed empty-state handling for offline libraries.+- Fixed long-press dialog accidental actions.++#### Performance & Stability+- Reduced memory usage during large operations (EPG, backups, search).+- Improved database maintenance behavior to avoid blocking operations.+- Reduced unnecessary UI recompositions and background work.++## [1.0.3] - 2026-04-09### Added-- Added a full DVR workflow with scheduled and background recording, conflict detection, recording persistence, repair/reconcile support, and app-managed default storage for recordings.-- Added combined M3U live source support, including merged-provider profiles, active source selection, and provider-management controls in Settings for building combined Live TV sources.-- Added an optional Live TV provider/source browser for M3U sources, with compact in-browser switching and the setting disabled by default.-- Added in-app playback actions for completed recordings, plus an on-player recording indicator so active captures remain visible during playback.-- Added broader shipped locale coverage together with locale-aware typography fallbacks to improve multilingual rendering across the TV UI.-### Changed-- Updated provider and recording settings surfaces with improved TV focus treatment, white focus strokes, fixed combined-provider dialogs, and much denser recording cards and action layouts.-- Updated local playback handling so completed recordings open through local-file-capable player data sources and are treated as local media instead of live transport streams.-- Updated recording storage and playback flows to default to safe app-managed folders while still supporting custom storage selection when users want it.+#### DVR & Recording+- Added full DVR support with scheduled and background recording.+- Added conflict detection, persistence, and recovery handling.+- Added in-player recording controls and live recording indicator.++#### Providers+- Added combined M3U live sources with merged-provider profiles.+- Added provider management and active source selection in Settings.+- Added optional in-app provider/source browser for Live TV.++#### Localization+- Added broader locale support with improved typography handling.++---++### Improved+- Improved recording and provider settings UI for better TV navigation.+- Improved playback of recordings (now treated as local media).+- Improved storage handling with safe default folders and optional custom locations.++---### Fixed-- Fixed Android foreground-service crashes affecting manual and scheduled recording starts on newer Android versions by correcting the recording start path and required service permissions.-- Fixed recording rows and settings controls that were oversized, not fully navigable by D-pad, or not clickable in the recording settings surface.-- Fixed combined-provider focus styling gaps so provider management buttons and add-playlist dialogs now match the rest of the TV interface.-- Fixed corrupted and poorly rendered translated strings across shipped locales by refreshing locale resources and falling back to safer typography where needed.+- Fixed recording failures/crashes on newer Android versions.+- Fixed D-pad navigation and click issues in recording settings.+- Fixed focus and styling issues in combined-provider dialogs.+- Fixed incorrect or broken translations across some locales.-## 1.0.2 - 08/04/2026+## [1.0.2] - 2026-04-08### Added-- Added in-app update discovery and download support backed by GitHub Releases, including cached release metadata, dashboard update callouts, Settings update controls, and APK install handoff through a FileProvider.-- Added bulk category visibility controls in Provider Category Controls with provider-wide `Hide All` and `Unhide All` actions.-- Added per-provider M3U VOD classification controls, including setup-time configuration, a persisted provider flag, and a refresh action to rearrange imported content after toggling the rules.-- Added playback troubleshooting controls in Settings for `System Media Session`, saved decoder mode preference, clearer playback timeout labels, and direct numeric timeout entry.-- Added targeted regression coverage for M3U header BOM handling, XMLTV relaxed parsing, and broader M3U header EPG alias support.--### Changed-- Updated M3U header EPG discovery to accept additional aliases such as `x-tvg-url`, `url-tvg`, `tvg-url`, and `url-xml`, while handling comma-separated guide URLs more reliably.-- Updated M3U and manual XMLTV ingestion to use a more tolerant shared parser so malformed entity text in otherwise usable feeds no longer fails as aggressively.-- Updated the add-provider and provider settings flows so Xtream-only advanced options stay hidden for M3U sources and provider-specific M3U behavior is configured where users expect it.-- Updated playback timeout settings to use clearer live-versus-VOD wording and a simpler typed-seconds workflow instead of long option pickers.-- Updated player initialization so main playback can react live to `MediaSession` and decoder preferences, with improved decoder fallback behavior when software extensions are available.++#### Updates & Settings+- Added in-app update support with download and install.+- Added playback troubleshooting controls (Media Session, decoder preference, timeouts).++#### Providers & M3U+- Added bulk category controls (Hide All / Unhide All).+- Added per-provider M3U VOD classification with refresh support.++---++### Improved+- Improved M3U EPG detection with broader header support and better parsing.+- Improved XMLTV and M3U ingestion to handle malformed feeds more reliably.+- Improved provider setup flows with clearer separation between M3U and Xtream options.+- Improved playback timeout settings with simpler controls.+- Improved player initialization and decoder fallback behavior.++---### Fixed-- Fixed M3U playlist imports that could miss header-declared EPG URLs when the playlist started with a UTF-8 BOM.-- Fixed provider sync so hidden live categories are skipped during Xtream live refresh and ignored during EPG resolution work, reducing unnecessary sync overhead.-- Fixed provider category control management to support bulk hide and restore flows without disturbing categories that were already hidden.-- Fixed M3U provider sync and setup behavior so discovered provider EPG URLs, VOD classification, and category rearrangement stay consistent across refreshes.-- Fixed XMLTV source refreshes that previously failed on some real-world feeds with `unterminated entity ref` parser errors.+- Fixed M3U imports missing EPG URLs due to BOM issues.+- Fixed provider sync to skip hidden categories and reduce overhead.+- Fixed category visibility controls not preserving existing hidden states.+- Fixed M3U sync inconsistencies across refreshes.+- Fixed XMLTV parsing errors on some real-world feeds.-## 1.0.1 - 08/04/2026+## [1.0.1] - 2026-04-08### Added-- Added manual EPG match management directly from the full guide, including channel-level override selection and a quick return to automatic matching.-- Added EPG resolution coverage summaries and source priority controls in Settings so provider assignments can be reviewed and reordered without leaving the app.-- Added targeted regression coverage for manual EPG source assignment behavior, M3U `url-tvg` header parsing, and gzip-compressed XMLTV imports.-### Changed-- Updated live playback EPG loading to prefer resolved multi-source mappings for current, next, history, and upcoming programme data before falling back to provider-native lookups.-- Updated Home live channel now-playing badges to use the resolved EPG pipeline, aligning the home surface with the guide and player.-- Updated EPG source refresh and assignment flows to immediately re-resolve affected providers after source refresh, enable/disable, delete, assign, unassign, and priority changes.-- Updated provider XMLTV refresh to accept both standard XMLTV files and gzip-compressed `.xml.gz` feeds discovered from M3U playlist headers.+#### EPG Management+- Added manual EPG matching directly from the guide.+- Added EPG source priority controls in Settings.++---++### Improved+- Improved EPG resolution across playback, guide, and Home.+- Improved EPG refresh and assignment to update immediately after changes.+- Improved XMLTV support including gzip-compressed feeds.++---### Fixed-- Fixed M3U playlist imports so header-declared `url-tvg` and `x-tvg-url` feeds are carried through into provider EPG refresh more reliably.-- Fixed manual overrides so they persist as explicit external mappings instead of being lost during normal assignment updates.-- Fixed guide and playback consumers that previously bypassed resolved mappings and could ignore external or manually overridden EPG matches.+- Fixed M3U imports not consistently carrying EPG sources.+- Fixed manual EPG overrides not persisting correctly.+- Fixed guide and playback ignoring resolved EPG mappings in some cases.diff --git a/docs/EPG_GRID_CODE_REVIEW.md b/docs/EPG_GRID_CODE_REVIEW.mdnew file mode 100644index 00000000..8da22e81--- /dev/null+++ b/docs/EPG_GRID_CODE_REVIEW.md@@ -0,0 +1,928 @@+# EPG Grid — Production Code Review++**Reviewed:** April 2026+**Files:** `EpgScreen.kt`, `EpgGridComponents.kt`, `EpgHeroComponents.kt`,+`EpgControlComponents.kt`, `EpgScreenDialogs.kt`, `EpgViewModel.kt`++---++## Executive Summary++The EPG grid has a solid architectural foundation: a well-separated ViewModel pipeline,+proper `LazyColumn` row virtualization, a `CompositionLocal`-based clock that limits+recomposition, and a layered fallback strategy for missing guide data. The most important+issues that need fixing before a premium release are:++1. **Critical rendering bug** — program cells use `padding(start = itemStart)` inside a+ `Box`, so overlapping or back-to-back programs stack at the wrong pixel column instead+ of being positioned absolutely.+2. **Desynchronized horizontal scroll** — the timeline header and per-row program strips+ share a single `ScrollState` instance but the header scroll and each row scroll are+ driven independently; they can diverge on fast D-pad navigation.+3. **Hard channel cap at 60** — `MAX_CHANNELS = 60` silently truncates large provider+ catalogues with no pagination, making the guide unusable for providers with hundreds+ or thousands of live channels.+4. **30-second "now" clock visible only inside `GuideNowProvider`** — three separate+ `GuideNowProvider {}` wrappers exist in `EpgScreen.kt` (hero, grid, dialog), each+ producing an **independent** 30-second ticker; they can disagree by up to 30 s,+ causing the "now" bar and the hero progress indicator to be out of sync.+5. **`ImmersiveGuideHero` calls `System.currentTimeMillis()` directly** — bypassing+ `LocalGuideNow`, so the hero progress bar does not respect the composition clock and+ will show a stale value after any data refresh.++---++## 1. Correctness++### 1.1 Program Positioning Bug (Critical)++**Location:** `EpgGridComponents.kt` — `ProgramItem` and the inner `Box` in `EpgRow`.++```kotlin+// ProgramItem+modifier = Modifier+ .padding(start = itemStart) // ← WRONG: padding, not absolute offset+ .width(itemWidth)+```++`padding(start = itemStart)` inside a `Box` layout places the item relative to the+previous sibling's right edge, not relative to the `Box` origin. With a standard+`Row` or `forEach` inside a `Box`, every program cell shifts by the sum of all+preceding `itemStart` values. The result: programs are visually displaced to the+right, back-to-back programs overlap, and the "now" column aligns with nothing real.++**Fix:** Use `Modifier.absoluteOffset(x = itemStart)` or `Modifier.offset(x = itemStart)`+(the latter is layout-relative but equivalent in a `Box`):++```kotlin+modifier = Modifier+ .offset(x = itemStart)+ .width(itemWidth)+ // … rest unchanged+```++The same pattern must be applied to the "now" line indicator inside `GuideTimelineHeader`.++### 1.2 Now-Indicator Offset in the Timeline Header++**Location:** `EpgGridComponents.kt` — `GuideTimelineHeader`, inner `Box`.++```kotlin+Box(+ modifier = Modifier+ .padding(start = totalTimelineWidth * elapsedRatio) // same padding bug+ .width(2.dp)+ .fillMaxHeight()+ .background(Primary)+)+```++Same issue as 1.1: `padding(start = …)` stacks on top of whatever precedes this `Box`+child instead of anchoring it at the exact ratio position.++**Fix:** `.offset(x = totalTimelineWidth * elapsedRatio)`.++### 1.3 Cross-Midnight Handling++`guideWindowStart = anchorTime - LOOKBACK_MS` and `guideWindowEnd = anchorTime + LOOKAHEAD_MS`+span a fixed relative range from the anchor, which is correct. However:++- `jumpToDay()` computes time-of-day as `anchorTime.mod(DAY_SHIFT_MS)`, using Kotlin's+ `Long.mod()`. When `anchorTime` is negative (any time before epoch — unlikely in+ practice but possible if a test passes 0L as "uninitialised") the result is negative,+ shifting the window to the previous calendar day. Add a floor clamp: if `anchorTime`+ is below epoch milliseconds for year 2000, treat it as `System.currentTimeMillis()`.++- The XMLTV parser and EPG providers are cross-midnight aware (they store UTC epoch+ milestamps), so stored programs are safe. The UI correctly clamps `visibleStart` and+ `visibleEnd` in `ProgramItem`. **No additional issue here.**++### 1.4 Program Width Clamping Without Gap++```kotlin+val visibleEnd = max(visibleStart + 1, minOf(program.endTime, windowEnd))+```++Adding `+ 1` ms prevents zero-width but results in a 1-ms-wide item that renders at+`minimumItemWidth`. At 40–56dp minimum this is fine for display, but the program will+appear at the position of the *clamped end*, not its true start. A program whose+`endTime ≤ windowStart` should be **filtered out** before reaching `ProgramItem`.+Consider pre-filtering the program list in `buildGuideDisplaySnapshot`.++### 1.5 Overlapping Programs++The code renders every item in `programs.forEach { … }` with no overlap detection.+If the upstream EPG data contains two programs whose time ranges intersect, both items+will be rendered and one will visually overlap the other (especially with the current+padding-offset bug amplifying the displacement). Add a pre-pass that splits or drops+overlapping programs before building the `programsByChannel` map.++---++## 2. Scrolling & Navigation++### 2.1 Header and Row Scroll Desynchronization++**Location:** `EpgGrid`, `EpgRow`.++```kotlin+val horizontalScrollState = rememberScrollState()+// passed to: GuideTimelineHeader(scrollState = horizontalScrollState)+// and to each: EpgRow(scrollState = horizontalScrollState)+```++A single `ScrollState` is created at the `EpgGrid` level and shared. This is the+correct intent. However, inside `GuideTimelineHeader` and `EpgRow` the `Box` that+wraps the timeline content uses a `Row` that applies `.horizontalScroll(scrollState)`.+When D-pad focus moves **inside one row's program strip** (via TV focus traversal),+the `BringIntoViewRequester` on the focused item may call `bringIntoView()` which+scrolls **that row's scroll state** but not the header, because `bringIntoView`+triggers the nearest `ScrollableContainer` ancestor, not the shared instance.++**Fix:** Replace per-row `horizontalScroll` with a single `LazyRow` or `HorizontalPager`+for the program strip, or use `nestedScroll` to propagate scroll commands up to the+shared `ScrollState`. A simpler approach: use a single full-width `Canvas` or+`BoxWithConstraints` to draw all program cells at absolute pixel positions, removing+the nested horizontal scroll entirely.++### 2.2 D-Pad Focus Traversal Inside the Program Strip++Each `ProgramItem` is a `TvClickableSurface` rendered inside a `forEach` loop, which+means the Compose TV focus system sees them as ordinary focusables in document order.+For a very wide timeline (multiple hours), D-pad right from the last *visible* program+will try to focus the next item which may be 300dp to the right and offscreen.+**The programme strip does not auto-scroll to bring the focused item into view** because+there is no `BringIntoViewRequester` wired to `ProgramItem`.++**Fix:** Add a `BringIntoViewRequester` to each `ProgramItem` and call+`bringIntoViewRequester.bringIntoView()` inside the `onFocusChanged` when `isFocused`+becomes true:++```kotlin+val bringIntoViewRequester = remember { BringIntoViewRequester() }+val scope = rememberCoroutineScope()+modifier = Modifier+ .bringIntoViewRequester(bringIntoViewRequester)+ .onFocusChanged {+ if (it.isFocused) scope.launch { bringIntoViewRequester.bringIntoView() }+ }+```++### 2.3 Channel-Rail Focus Not Restored After Data Refresh++**Location:** `EpgScreen.kt` — `LaunchedEffect(uiState.channels, uiState.programsByChannel)`.++```kotlin+LaunchedEffect(uiState.channels, uiState.programsByChannel) {+ // resolves focusedChannel / focusedProgram in-memory …+}+```++This effect correctly resolves the model objects, but there is no call to restore+**Compose focus** to the previously focused item. If the channel list refreshes (e.g.+after a forced refresh or after the first background sync), focus drops to the system+default (typically row 0). On TV this is jarring.++**Fix:** Store the previously focused `itemKey` (from `epgChannelKey`) in a+`rememberSaveable`, then after the `LazyColumn` layout stabilises use a+`LaunchedEffect(channelKeys)` with `listState.scrollToItem(restoredIndex)` and+`focusRequester.requestFocus()` on the matching row.++### 2.4 Fast Channel-Zap Not Supported from Grid++There is no D-pad shortcut from within the grid to immediately play the focused channel+(e.g. pressing `OK` on the channel-rail goes to the channel play action, but a number+key or `KEYCODE_CHANNEL_UP/DOWN` is not handled). The grid does not intercept+`onPreviewKeyEvent` at the screen level.++**Fix:** Add a `Modifier.onPreviewKeyEvent` at the `EpgGrid` or `FullEpgScreen` level+to handle `KEYCODE_CHANNEL_UP` / `KEYCODE_CHANNEL_DOWN` for fast zap and+`KEYCODE_PROG_RED` / `KEYCODE_PROG_GREEN` for jump-to-now / options shortcuts.++---++## 3. Performance++### 3.1 Hard Channel Cap Is Not a Virtualization Strategy++```kotlin+const val MAX_CHANNELS = 60+```++The `LazyColumn` in `EpgGrid` already virtualizes vertical rows lazily. The `MAX_CHANNELS`+cap was introduced as a performance guard but it silently discards channels 61+ with no+indication to the user. For a provider with 500 live channels this makes the guide+incomplete. The real bottleneck is the **program loading step**, not the render.++**Recommended fix:** Remove the cap from the UI pass; apply pagination or an infinite-scroll+trigger at the ViewModel layer so the first 60 channels load eagerly and the next page+loads when the user scrolls near the bottom:++```kotlin+// In EpgGrid LazyColumn:+if (index == channels.size - 10) {+ LaunchedEffect(Unit) { onLoadMore() }+}+```++### 3.2 `buildList` for Hour Markers Re-Runs on Every Recomposition++**Location:** `GuideTimelineHeader`.++```kotlin+val hourMarkers = buildList { … } // not inside remember {}+```++The hour-marker list is rebuilt on every recomposition of the header. The header+recomposes every 30 seconds (from `rememberGuideNow`) but also whenever `windowStart`,+`windowEnd`, or scroll position changes. Wrap in `remember`:++```kotlin+val hourMarkers = remember(windowStart, windowEnd, markerStepMs) {+ buildList { … }+}+```++Note: the per-row `markers` list already does this correctly — the header should match+that pattern.++### 3.3 Grid-Line Markers Drawn Per-Row++**Location:** `EpgRow` — inner `Box`.++```kotlin+markers.forEach { marker ->+ Box(modifier = Modifier+ .padding(start = totalTimelineWidth * markerRatio)+ …+ .background(Color.White.copy(alpha = 0.08f)))+}+```++For 60 rows × N markers (e.g. 14 half-hours = 14 markers), that is 840 `Box`+composables per full render, each containing a `background` draw call. Each has the+same x-positions and appearance. This is expensive and visually redundant: drawing the+grid lines on a single `Canvas` overlay placed below the `LazyColumn` (or as a fixed+background `Box`) would replace 840 composable slot allocations with one `Canvas.drawLine`+loop.++### 3.4 Multiple Independent `rememberGuideNow()` Instances++**Location:** `EpgScreen.kt` lines 322, 364, 503.++```kotlin+GuideNowProvider { GuideHeroSection(…) } // ticker A+GuideNowProvider { EpgGrid(…) } // ticker B+GuideNowProvider { CompactGuideProgramDialog(…) } // ticker C+```++Each `GuideNowProvider` wraps an independent `produceState` coroutine ticking every+30 seconds. Three coroutines run instead of one, and they can be up to 30 s out of+phase. The "now" bar in the grid can display a different time from the hero progress+bar.++**Fix:** Hoist a single `GuideNowProvider` above all three call sites, or move+`rememberGuideNow()` into the ViewModel as a `StateFlow<Long>` driven by a single+`tickerFlow`.++### 3.5 `ImmersiveGuideHero` Bypasses the Composition Clock++**Location:** `EpgHeroComponents.kt` — `ImmersiveGuideHero`.++```kotlin+val currentTime = System.currentTimeMillis()+```++This is a direct wall-clock read outside the `LocalGuideNow` composition local, so it+does not update unless recomposition is triggered by something else. The progress bar+and "Updated N min ago" label can show stale values indefinitely after the initial+composition. Replace with `currentGuideNow()` (already provided by the surrounding+`GuideNowProvider`).++### 3.6 Channel Logo Loading Without Placeholders++`ChannelLogoBadge` is called once per visible row. If the logo URL is absent or slow,+nothing prevents a row-height shift when the image loads. Ensure the badge provides a+fixed-size placeholder (it references `channelName` for a letter fallback, but verify+that the fallback occupies the same pixel dimensions as a loaded image).++---++## 4. State Handling++### 4.1 Scroll Position Lost on Window Shift++When the user calls `jumpForward()` or `jumpBackward()`, `guideWindowStart/End` changes,+which triggers a full recomposition of `EpgGrid`. Because `horizontalScrollState` is+created with `rememberScrollState()` (no saved state key tied to the window), the scroll+position resets to 0 on every window shift. For a "jump forward 30 min" action the user+expects the visible content to advance proportionally, not snap to the left edge.++**Fix:** After `jumpForwardHalfHour()`, programmatically scroll the `horizontalScrollState`+by the equivalent pixel distance. In the ViewModel expose the scroll target as a+`SharedFlow<Long>` (milliseconds to scroll to); observe it in the grid and call+`scrollState.animateScrollTo(targetPixelOffset)`.++### 4.2 `focusedProgram` State Matching Is Fragile++```kotlin+focusedProgram = focusedProgram?.let { focused ->+ resolvedPrograms.firstOrNull {+ it.startTime == focused.startTime &&+ it.endTime == focused.endTime &&+ it.title == focused.title+ }+}+```++Matching by `(startTime, endTime, title)` instead of a stable ID means that a metadata+update (e.g., a slightly corrected title from a reparsed XMLTV feed) will lose the focus+target and fall back to the current live program. If `Program` has a stable `id` or+`(channelEpgId, startTime)` composite key, prefer that.++### 4.3 `pendingLockedAction` Reset Race++**Location:** `EpgScreen.kt` — PIN dialog confirm handler.++```kotlin+scope.launch {+ if (viewModel.verifyPin(pin)) {+ val action = pendingLockedAction+ …+ pendingLockedAction = null+ action?.let(::executeLockedGuideAction)+ } else {+ pinError = context.getString(R.string.home_incorrect_pin)+ }+}+```++`pendingLockedAction` is `remember { mutableStateOf<LockedGuideAction?>(null) }` (not+`rememberSaveable`), so it is lost on configuration change (screen rotation on a phone+form-factor, or activity recreation). The user enters the PIN, rotation happens, the+action is null, and nothing plays. For a TV-only product this is low risk but worth+noting.++---++## 5. Time Sync & Guide Updates++### 5.1 No Periodic Auto-Refresh of Guide Data++The guide viewport auto-advances when the user calls `jumpForward()`, but the underlying+EPG data (`programsByChannel`) is only refreshed when:+- The user presses "Refresh" manually, or+- `refreshNonce` is incremented.++If the app runs for 6+ hours without a user interaction (common on always-on TV+devices), live programs will start showing as "expired" and a new day's schedule will+not appear. The ViewModel has no `WorkManager` or `TickerFlow` that calls `refresh()`+when the guide window falls entirely in the past.++**Fix:** In `init` or `observeGuideBase`, start a coroutine that compares+`System.currentTimeMillis()` to `guideWindowEnd` every 15 minutes and calls+`refresh()` when the window is about to expire:++```kotlin+viewModelScope.launch {+ while (true) {+ delay(15 * 60_000L)+ val state = _uiState.value+ if (System.currentTimeMillis() > state.guideWindowEnd - HALF_HOUR_SHIFT_MS) {+ refresh()+ }+ }+}+```++### 5.2 Auto-Scroll to "Now" Not Automatic on Screen Entry++The guide opens at the stored `guideAnchorTime`, which may be several hours in the past+if the user left the guide at 18:00 yesterday. The "Jump to Now" button corrects this,+but it requires user action. On first entry (when `startupCategoryId` is non-null and+`isStartupSelection == true`), `guideAnchorTime` should be initialised to+`System.currentTimeMillis()`.++Currently `restoreGuidePreferences()` restores the persisted anchor time unconditionally.+Add a staleness check:++```kotlin+val saved = preferencesRepository.guideAnchorTime.first()+val now = System.currentTimeMillis()+if (saved != null && abs(saved - now) < 6 * 60 * 60_000L) {+ guideAnchorTime.value = saved+} // else leave at now (default)+```++---++## 6. Edge Cases++### 6.1 Zero-Duration Programs++```kotlin+val totalDuration = (windowEnd - windowStart).coerceAtLeast(1L) // window safe+// but no guard for program duration:+val widthRatio = ((visibleEnd - visibleStart).toFloat() / totalDuration).coerceIn(0f, 1f)+```++If `program.startTime == program.endTime` (a zero-duration entry from a malformed+XMLTV feed), `visibleStart == visibleEnd` (before the `+ 1` guard), and `widthRatio`+is 0. The item renders at `minimumItemWidth` but at the *start* position. This is+acceptable, but the `+ 1` guard in `visibleEnd` should be documented as intentional+and the filter in `loadGuidePrograms` should discard entries where `endTime <= startTime`.++### 6.2 Extremely Long Programs (24-hour slot)++A program spanning the full window (e.g., a 24-hour slot for a channel with no detailed+schedule) produces `widthRatio ≈ 1.0`, so `itemWidth = totalTimelineWidth`. This is+visually correct (a single cell spanning the full strip) but may cause layout issues if+`totalTimelineWidth` is very large (`calculatedTimelineWidth` can exceed the viewport+by 8× for a 24-hour window), producing a cell wider than the screen. The minimum width+clamp doesn't help because the cell is *too large*, not too small. Clamp the maximum+cell width to `totalTimelineWidth` and test that horizontal scrolling still works.++### 6.3 Missing EPG for All Channels (guide stale)++The `isGuideStale` flag is set and shown as a badge in the hero. However the main+grid area still renders normally, just showing "No schedule" text in each row. This is+the right degraded mode. Consider adding a subtle banner above the grid when stale+(similar to the `LinearProgressIndicator` already shown during refresh) so the user+knows EPG is stale even when scrolled past the hero area.++### 6.4 Empty `programs` List Alignment++```kotlin+if (programs.isEmpty()) {+ Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {+ Text(stringResource(R.string.epg_no_schedule_short), color = OnSurfaceDim)+ }+}+```++The "no schedule" box fills the entire `totalTimelineWidth` wide strip, which is+correct. No issue here — just note that this Box should also display at the same+vertical baseline as program cells to avoid a visual height difference.++---++## 7. Responsiveness & Input Latency++### 7.1 `loadGuidePrograms` Blocks the Data Fetch on the IO Dispatcher++```kotlin+private suspend fun loadGuidePrograms(…): GuideProgramsResult {+ return withContext(Dispatchers.IO) {+ // 3 sequential steps: resolved → legacy → Xtream fallback+ val resolvedPrograms = runCatching { epgRepository.getResolvedProgramsForChannels(…) }+ val legacyPrograms = if (unresolvedChannels.isNotEmpty()) { … }+ val fallbackProgramsByChannel = fetchXtreamGuideFallback(…)+ }+}+```++Steps 2 and 3 are sequential, but they operate on disjoint channel sets. They can be+parallelised with `coroutineScope { async { … } async { … } awaitAll() }`, removing+the serial delay when both a legacy query and an Xtream fallback query are needed.++### 7.2 `loadCombinedGuidePrograms` Is Fully Sequential++```kotlin+groupedPrograms.forEach { (providerId, providerChannels) ->+ val result = loadGuidePrograms(…)+ putAll(result.programsByChannel)+}+```++For a combined profile with N providers, guide programs are loaded one provider at a+time. Switch to `coroutineScope { groupedPrograms.map { async { loadGuidePrograms(…) } }.awaitAll() }`.++### 7.3 No Debounce on `jumpForwardHalfHour` / `jumpBackward`++A user holding D-pad on the jump button fires a rapid succession of `jumpForward()` calls,+each triggering `updateGuideAnchorTime()` which persists to `PreferencesRepository` and+emits a new upstream value that invalidates the entire guide data load. Add a debounce:++```kotlin+private val _pendingAnchorTime = MutableStateFlow(guideAnchorTime.value)+// in init:+viewModelScope.launch {+ _pendingAnchorTime.debounce(300).collect { anchorTime ->+ guideAnchorTime.value = anchorTime+ preferencesRepository.setGuideAnchorTime(anchorTime)+ }+}+fun updateGuideAnchorTime(ms: Long) { _pendingAnchorTime.value = ms }+```++---++## 8. UI Clarity++### 8.1 Current Program Highlight Is Subtle++```kotlin+containerColor = if (isCurrent) Primary.copy(alpha = 0.2f) else SurfaceElevated,+```++20% alpha over `SurfaceElevated` is barely visible, especially on OEM TV panels with+boosted brightness or OLED pixel representation. Consider 30–40% alpha or a distinct+left-border accent of 4dp width in `Primary` color for the current program cell.++### 8.2 Favorite Badge vs. Catch-Up Badge Conflict++```kotlin+if (isFavorite || channel.catchUpSupported) {+ Box { Text(if (channel.catchUpSupported) "Replay" else "★") }+}+```++Only one badge is shown even when both conditions are true: a catch-up channel that is+also a favorite shows only "Replay", silently dropping the favorite indicator. Show+both badges side by side, or use a combined badge.++### 8.3 Channel Number Formatting++```kotlin+text = if (channel.number > 0) "${channel.number}. ${channel.name}" else channel.name+```++For channels numbered 1–9, this renders as "1. ChannelName" which looks inconsistent+next to "10. OtherChannel" because no zero-padding is applied. On TV UIs with a fixed+channel-rail width, consider right-aligning the number in a fixed-width column rather+than concatenating it into the name string.++### 8.4 Timeline Header Does Not Scroll Visually During D-Pad Navigation++The timeline header is rendered separately above the `LazyColumn`. As the user D-pads+down through channels and a program item scrolls horizontal state, the header should+follow. Because both share the same `scrollState`, the header does visually scroll —+but only when the user is **inside a program strip**. When the user is focused on the+channel-rail column, horizontal scroll is not possible at all. This means the header+time label and the visible programs can be misaligned if the user scrolled the programs+and then moved focus to the channel rail and back.++**Fix:** Lock horizontal scroll to the program strip interaction only; the header+always reflects the current `scrollState.value` which is correct. No code change+needed, but verify on device that the `LazyColumn` scroll does not inadvertently reset+`horizontalScrollState` to 0 on item recomposition.++---++## 9. Error Resilience++### 9.1 Silent Failure on `runCatching` in `loadGuidePrograms`++```kotlin+val resolvedPrograms = runCatching {+ epgRepository.getResolvedProgramsForChannels(…)+}.getOrElse { emptyMap() }+```++Failures are swallowed silently and degrade to `emptyMap()`. The `failedScheduleCount`+tracks missing channels but does not surface the underlying exception. For debugging+purposes, at least log the exception at `ERROR` level:++```kotlin+}.onFailure { e -> Timber.e(e, "EPG resolve failed for provider $providerId") }+ .getOrElse { emptyMap() }+```++Without this, reproducing EPG data regressions in production requires device-side+logcat captures from users.++### 9.2 Xtream Fallback Does Not Honour `MAX_XTREAM_GUIDE_FALLBACK_CHANNELS`++```kotlin+val fallbackChannels = missingChannels.take(MAX_XTREAM_GUIDE_FALLBACK_CHANNELS)+```++`MAX_XTREAM_GUIDE_FALLBACK_CHANNELS = 24`, so when a provider serves 60 channels but+none have XMLTV guide data, only the first 24 get the Xtream API fallback. Channels+25–60 display as "No schedule" with no retry path. Consider raising the limit or making+it configurable, or at least noting it in the stale-badge text.++### 9.3 Combined Guide With No Member Providers++```kotlin+private fun combinedProviderIdsFlow(profileId: Long): Flow<List<Long>> = flow {+ emit(combinedM3uRepository.getProfile(profileId)?.members.orEmpty())+}.map { members -> members.filter { it.enabled }.map { it.providerId } }+```++This is a **cold, non-repeating flow**. If the profile's members list changes while+the guide is open (e.g., the user enables a provider in Settings), the combined guide+will not update because the flow only emits once. Convert it to a `Flow` that+re-reads from the database reactively (e.g., a Room DAO query flow rather than a+`getProfile()` suspend call).++---++## 10. Security & Data Integrity++### 10.1 `program.description.ifBlank` Falls Through to Unfiltered String++**Location:** `ImmersiveGuideHero`.++```kotlin+text = program.description.ifBlank { stringResource(R.string.epg_hero_no_program_description) }+```++Program descriptions from XMLTV are free text. If a provider injects HTML entities+or markup in the description field (common with some European XMLTV feeds), it will+render as raw text. This is acceptable for a `Text` composable (no injection path),+but ensure the XMLTV parser stores `.trim()` descriptions to avoid leading/trailing+whitespace rendering.++---++## 11. Additional Bugs & Architectural Gaps++### 11.1 `epgChannelKey` Includes `index` — Unstable LazyColumn Diff (G-21)++**Location:** `EpgGridComponents.kt` — `epgChannelKey`.++```kotlin+internal fun epgChannelKey(channel: Channel, index: Int): String {+ return "channel:${channel.id}:…:$index"+}+```++Including `index` in the stable key means that if any channel shifts position in the+list (e.g. a category filter changes, or channels are reordered after a refresh), every+item **at or below** the first changed position gets a new key. Compose treats a new+key as a new item: it removes the old slot, creates a new one, and redraws — even+if the channel data is identical. Remove `index` from the key; `channel.id` + `channel.streamId`++ `epgId` + `channel.name.trim()` is already sufficiently unique without it.++### 11.2 Horizontal Scroll Not Positioned to "Now" on Guide Entry (G-22)++Even when the anchor time is correct, `rememberScrollState()` starts at offset 0 (the+left edge). For a 7-hour window with 1 hour of lookback, the "now" position is at+1/7 ≈ 14% of the total timeline width — off the left edge of the viewport on any+screen narrower than the full timeline. The user must manually scroll right to see+current programs.++**Fix:** Add a `LaunchedEffect(Unit)` inside `EpgGrid` that, after the first layout+pass, scrolls `horizontalScrollState` to `(totalTimelineWidth * nowRatio - viewportWidth / 2)`+clamped to `[0, maxScrollValue]`, centering "now" on screen:++```kotlin+val nowRatio = ((now - guideWindowStart).toFloat() / totalDuration).coerceIn(0f, 1f)+LaunchedEffect(Unit) {+ val targetPx = ((totalTimelineWidth * nowRatio).value * density.density -+ (timelineViewportWidth / 2).value * density.density).toInt().coerceAtLeast(0)+ horizontalScrollState.scrollTo(targetPx)+}+```++This is distinct from G-20, which fixes anchor-time staleness; G-22 fixes the pixel+offset within an already-correct time window.++### 11.3 No Numeric Digit (0–9) Remote-Key Channel Zap (G-23)++Section 2.4 recommended handling `KEYCODE_CHANNEL_UP/DOWN`, but the larger gap is+**direct numeric input**: standard IR remotes have 0–9 keys. All commercial EPGs+implement a digit-accumulation overlay: the user presses 1, 5, ENTER → channel 15.++**Fix:** At the `FullEpgScreen` level, intercept `KeyEvent.KEYCODE_0` through+`KeyEvent.KEYCODE_9` in `onPreviewKeyEvent`. Accumulate digits in a `rememberSaveable`+string, display an overlay chip showing the current number, and after a 1.2-second+idle timeout resolve the accumulated number to the matching `channel.number` and+scroll the `LazyColumn` to that row (or play the channel directly).++### 11.4 `Program.imageUrl` Never Rendered (G-24)++The data layer populates `Program.imageUrl` from XMLTV `<icon>` elements and Xtream+metadata, but neither `CompactGuideProgramDialog` nor `ImmersiveGuideHero` renders it.+This is a significant visual gap: sport events, movies, and popular series typically+have high-quality banner art in EPG sources.++**Fix:**+- In `ImmersiveGuideHero`: replace the `ChannelLogoBadge` with an `AsyncImage` that+ loads `program.imageUrl` when non-null, falling back to the channel logo.+- In `CompactGuideProgramDialog`: add a `16:9` banner above the program title when+ `program.imageUrl` is non-null.++### 11.5 "Live Now" Mode (`GuideChannelMode.ANCHORED`) Not Discoverable (G-25)++`GuideChannelMode.ANCHORED` filters the channel list to only those with a program+airing at the anchor time — exactly the "what's on now" view users expect on first+open. However it is accessible only via the **options overlay** (three taps away),+buried among density and schedule filters. Most users will never find it.++**Fix:** Add a `LIVE NOW` toggle chip directly in `GuideToolbarRow` between the+category chip and "Jump to Now". One tap activates ANCHORED mode; tapping again+returns to ALL. The toolbar already has room for a fourth chip.++### 11.6 No Incremental Window Preloading (G-26)++Every `jumpForward()` / `jumpBackwardHalfHour()` triggers a complete re-fetch of+`programsByChannel` for the new window. Until the coroutine completes the user sees+blank program strips. For a provider with 60 channels × 14 half-hour markers this is+typically 200–400 ms of latency on a local network and 1–2 s on a slow connection.++**Fix:** Maintain a two-window sliding cache in the ViewModel:+- `windowCache: Map<LongRange, GuideProgramsResult>` keyed by `(windowStart, windowEnd)`.+- When the user navigates forward, eagerly pre-fetch the *next* 3-hour window in the+ background while still displaying the current one.+- When a pre-fetched window becomes active, show it instantly.+- Evict windows that no longer overlap the displayable range.++### 11.7 `Program` Lacks a Stable Composite Room Key (G-27)++G-14 recommends matching focused programs by a stable ID rather than `(startTime,+endTime, title)`, and G-21 recommends removing `index` from the `LazyColumn` key.+Both fixes ultimately depend on programs having a stable, unique identifier.++The `ProgramEntity` Room table currently has no surrogate primary key that survives a+provider re-sync. Add a composite unique index on `(provider_id, channel_epg_id,+start_time)` and expose it as `Program.stableKey: String` in the domain model+(`"$providerId:$channelEpgId:$startTime"`). Use this key wherever programs need to be+compared across data refreshes.++---++## 12. Missing Features++### 12.1 Schedule Recording from the Guide (F-01)++The app has a complete `RecordingManager`, `ScheduleRecording` use case, and the+live player overlay already exposes one-time, daily, and weekly scheduling. The EPG+grid is the **primary** place users schedule recordings on every commercial STB, yet+`CompactGuideProgramDialog` has no "Record" or "Schedule" button.++**Fix:** Add a third action button to `CompactGuideProgramDialog` that calls+`viewModel.scheduleRecording(channel, program)`. For past programs the button should+be hidden; for future programs show "Schedule"; for currently-airing shows show+"Record from now". Wire to the existing `ScheduleRecording` use case — no new business+logic required.++### 12.3 Inline Live Preview in the Hero (F-03)++When focus lands on a channel row, the hero updates with metadata — but there is no+live video. The HomeScreen already implements the exact pattern needed: an auxiliary+`PlayerEngine` instance with `bypassAudioFocus = true`, started after a focus-dwell+delay, torn down on `Lifecycle.ON_STOP` and `onDispose`.++**Fix:** Add a `PlayerSurface` inside `ImmersiveGuideHero` that starts after a+configurable dwell threshold (e.g., 1500 ms). Use `@AuxiliaryPlayerEngine` injection+identical to the HomeScreen implementation. Respect the user's "disable guide preview"+preference if one exists, and ensure the surface is released at the same lifecycle+boundaries as the HomeScreen preview.++### 12.4 Genre and Rating Filter in the Toolbar (F-04)++`Program.genre` and `Program.rating` are populated by the data layer and stored in+the database, but the guide toolbar has no genre or rating filter. For a provider+with 300+ channels carrying News, Sport, Movies, Kids, and Documentary, a one-tap+genre filter is the fastest content-discovery path — faster than category browsing.++**Fix:** Add a genre chip to `GuideToolbarRow` that, when tapped, opens a compact+bottom-sheet picker (reuse `GuideCategoryPickerDialog` style) listing distinct genres+from `programsByChannel.values.flatMap { … }.mapNotNull { it.genre }.distinct()`. The+selected genre is then applied in `buildGuideDisplaySnapshot` as an additional filter+layer on `candidateProgramsByChannel`.++### 12.5 EPG Coverage Badge on Category Toolbar Chip (F-05)++`channelsWithSchedule` and `totalChannelCount` are computed in the ViewModel and+displayed in the hero badge (`GuideHeroBadge`). However, once the user scrolls down+past the hero area the coverage information disappears. The category toolbar chip+only shows the category name.++**Fix:** Append the coverage ratio to the category chip label:++```kotlin+label = "$selectedCategoryName ${channelsWithSchedule}/${totalChannelCount}",+```++A low ratio (e.g., "Sport 2/40") immediately tells the user EPG is thin for that+category without requiring a scroll back to the hero.++### 12.6 Phone and Tablet Layout (F-06)++The guide is designed exclusively for TV (1280dp+ landscape). `rememberIsTelevisionDevice()`+is already imported in `EpgScreen.kt` and `EpgControlComponents.kt`, and+`BoxWithConstraints` is already used in `EpgGrid`. Despite this, no compact layout+branch exists.++On a phone the channel rail is 180dp wide and the program strip is several thousand dp+wide — the guide is effectively broken.++**Fix (suggested layout for compact screens):**+- **Channel list** (`maxWidth < 600dp`): a `LazyColumn` of channel-rail items only,+ full-width, with no horizontal program strip.+- **Program list**: when the user selects a channel, show a `LazyColumn` of that+ channel's programs for the full day as a detail pane (master–detail pattern using+ `TwoPaneLayout` or a back-stack push).+- **Hero**: collapse to a `64dp` card showing the focused channel + current program.++`rememberIsTelevisionDevice()` should drive the top-level layout branch so TV behaviour+is fully unchanged.++### 12.7 "Now & Next" Compact Guide Mode (F-07)++The full timeline grid is the only available guide view. Many users — especially on+first open — want a quick "what's on right now and what's coming up next?" list without+navigating the horizontal timeline. `getNowAndNext()` already exists in `EpgRepository`+and is unused in the guide surface.++**Fix:** Add a `GuideChannelMode.NOW_AND_NEXT` branch to `buildGuideDisplaySnapshot`.+In that mode, replace the `EpgGrid` with a `LazyColumn` of compact rows, each showing:+- Channel logo + name (same channel-rail cell)+- Current program title + progress bar (using `Program.progressPercent()`)+- Next program title + start time++No new network calls or data-layer code are required — `getNowAndNext` is already+available for every channel. Add a "Now & Next" chip to `GuideToolbarRow` alongside+the existing `GuideChannelMode.ALL` and `GuideChannelMode.ANCHORED` options.++### 12.8 Multi-Day Visual Calendar Picker (F-08)++Day navigation is available through `jumpToPreviousDay()` / `jumpToNextDay()` and the+arrow-key-accessible jump buttons, but there is no visual date widget. Navigating more+than 2–3 days forward or backward requires many sequential D-pad presses with no visual+feedback about the destination date. Every commercial STB EPG exposes a 7–14 day+calendar as a primary navigation element.++**Fix:** Add a `GuideDayPickerRow` — a horizontally scrollable strip of day chips+above the category selector — showing 7 days centred on today. Each chip displays the+day abbreviation and date number (e.g. "Fri 18"). Selecting a chip calls the existing+`jumpToDay(dayStartMillis)`.++Important: day boundary computation must use local time, not UTC epoch division (see+G-06 above):+```kotlin+val zone = TimeZone.getDefault().toZoneId()+val dayStart = LocalDate.now(zone).plusDays(offset)+ .atStartOfDay(zone).toInstant().toEpochMilli()+```++### 12.9 EPG Resolution Quality Visible to the User (F-09)++`EpgResolutionSummary` tracks total channels, exact-ID matches, normalized-name+matches, and unresolved counts after every resolution pass, but none of this reaches+the user. When a channel shows "No schedule" the user cannot tell whether:+- No EPG source is assigned to their provider+- The source has data but the channel ID / name didn't match+- The source was last refreshed weeks ago++`F-05` (coverage badge in the toolbar) covers the narrow case of *how many channels+have any schedule in the current window*. This item is the broader feedback layer.++**Fix:**+- **Settings — EPG Sources screen**: after each refresh show the per-source resolution+ breakdown ("matched 312 / 450 channels — 138 unresolved") sourced from+ `EpgSourceRepository.getResolutionSummary(providerId)`.+- **`CompactGuideProgramDialog`**: when `programsByChannel` for the channel is empty,+ query `EpgSourceRepository.getChannelMapping(providerId, channelId)` and display a+ contextual reason chip:+ - `EpgSourceType.NONE` → "No EPG source covers this provider"+ - `EpgMatchType.NORMALIZED_NAME` with empty programmes → "EPG matched by name — no schedule for today"+ - No mapping row → "This channel could not be matched to any EPG source"+- **Debug overlay** (behind a dev flag): show the `ChannelEpgMapping` confidence score+ and `matchType` below the channel name in the guide rail.++---++## Summary of Actionable Items++| Priority | ID | Issue | Location |+|----------|-------|-------|----------|+| Critical | G-01 | Program cells use `padding(start=…)` instead of `offset(x=…)` — all programs render at wrong pixel positions | `EpgGridComponents` — `ProgramItem`, `GuideTimelineHeader` now-bar |+| Critical | G-02 | Three independent `GuideNowProvider` wrappers; "now" bar and hero can be 30 s out of sync | `EpgScreen.kt` lines 322, 364, 503 |+| High | G-03 | `ImmersiveGuideHero` uses `System.currentTimeMillis()` instead of `currentGuideNow()` | `EpgHeroComponents.kt` |+| High | G-04 | `MAX_CHANNELS = 60` silently truncates provider catalogues with no pagination or user feedback | `EpgViewModel` |+| High | G-05 | No periodic auto-refresh; guide goes stale after window expires on always-on devices | `EpgViewModel.init` |+| High | G-06 | `jumpToPrimeTime` / `jumpToDay` use UTC midnight, not local midnight | `EpgViewModel` |+| High | G-07 | `loadCombinedGuidePrograms` loads per-provider sequentially; should be parallel | `EpgViewModel` |+| Medium | G-08 | `buildList` for hour markers not inside `remember {}` — rebuilds every recomposition | `EpgGridComponents — GuideTimelineHeader` |+| Medium | G-09 | Grid-line markers drawn as 840+ `Box` composables; should be a single `Canvas` overlay | `EpgGridComponents — EpgRow` |+| Medium | G-10 | D-pad focus on program item does not trigger `bringIntoView`; program strip does not auto-scroll | `EpgGridComponents — ProgramItem` |+| Medium | G-11 | Scroll position resets to 0 on every window time-shift | `EpgGrid` / `EpgViewModel` |+| Medium | G-12 | Composite guide `combinedProviderIdsFlow` is a cold one-shot flow; member changes not reflected | `EpgViewModel` |+| Medium | G-13 | No debounce on `jumpForwardHalfHour` / anchor-time updates; rapid D-pad fires many data reloads | `EpgViewModel.updateGuideAnchorTime` |+| Medium | G-14 | `focusedProgram` match uses title+time instead of stable ID; breaks on metadata updates | `EpgScreen.kt` — `LaunchedEffect` |+| Medium | G-15 | Focus not restored to previously focused row after data refresh | `EpgScreen.kt` |+| Low | G-16 | Current program highlight alpha 0.2 is hard to see on OEM TV panels | `EpgGridComponents — ProgramItem` |+| Low | G-17 | Favorite + catch-up badge: only one shows when both are true | `EpgGridComponents — EpgRow` |+| Low | G-18 | `runCatching` in `loadGuidePrograms` silently swallows EPG fetch errors | `EpgViewModel` |+| Low | G-19 | Xtream fallback hard-capped at 24 channels; channels 25–60 never get fallback EPG | `EpgViewModel` |+| Low | G-20 | Auto-scroll to "now" not applied on first guide entry if persisted anchor is stale | `EpgViewModel.restoreGuidePreferences` |+| Medium | G-21 | `epgChannelKey` includes `index`; any channel reorder causes full LazyColumn diff and redraws all visible cells | `EpgGridComponents — epgChannelKey` |+| Medium | G-22 | Horizontal scroll not positioned to "now" pixel offset on guide entry; user sees left edge even with correct anchor time | `EpgGrid` — `LaunchedEffect(Unit)` missing |+| Medium | G-23 | No numeric digit (0–9) remote-key accumulation for direct channel-number zap | `EpgScreen.kt` — `onPreviewKeyEvent` |+| Medium | G-24 | `Program.imageUrl` populated by data layer but never rendered in `CompactGuideProgramDialog` or `ImmersiveGuideHero` | `EpgScreenDialogs`, `EpgHeroComponents` |+| Medium | G-25 | `GuideChannelMode.ANCHORED` ("on right now") buried in options overlay; not reachable with a single toolbar action | `EpgHeroComponents — GuideToolbarRow` |+| High | G-26 | No incremental window preloading; every time-shift triggers a full data reload and blank-grid flash | `EpgViewModel` |+| High | G-27 | `Program` has no stable composite Room key; fixes for G-14 and G-21 both depend on one | `data` — `ProgramEntity` |+| High | F-01 | **Missing feature:** No "Record" or "Schedule recording" action in the program dialog despite `RecordingManager` and `ScheduleRecording` use case existing | `EpgScreenDialogs — CompactGuideProgramDialog` |+| High | F-03 | **Missing feature:** No inline live preview in the hero when focus dwells on a channel row; HomeScreen auxiliary `PlayerEngine` pattern is directly reusable | `EpgHeroComponents — ImmersiveGuideHero` |+| Medium | F-04 | **Missing feature:** No genre or rating filter chip in the toolbar despite `Program.genre` and `Program.rating` being populated | `EpgHeroComponents — GuideToolbarRow` |+| Medium | F-05 | **Missing feature:** No category EPG-coverage badge on the toolbar category chip; `channelsWithSchedule` / `totalChannelCount` exists but only shown in the hero | `EpgHeroComponents — GuideToolbarRow` |+| High | F-06 | **Missing feature:** No phone/tablet layout; guide is designed exclusively for 1280dp+ TV screens and is unusable on handheld form factors | `EpgScreen.kt` / `EpgGrid` |+| High | F-07 | **Missing feature:** No "Now & Next" compact guide mode; `getNowAndNext()` exists in the repository but is unused in the guide surface | `EpgViewModel` / `EpgScreen.kt` |+| Medium | F-08 | **Missing feature:** No multi-day visual calendar picker; day navigation requires many sequential key presses with no date feedback | `EpgScreen.kt` / `EpgViewModel` |+| Medium | F-09 | **Missing feature:** EPG resolution quality (matched/unresolved counts, match type, source staleness) is never surfaced to the user | `SettingsEpgSection`, `EpgScreenDialogs` |+diff --git a/docs/db-cache-review.md b/docs/db-cache-review.mdnew file mode 100644index 00000000..06aff72b--- /dev/null+++ b/docs/db-cache-review.md@@ -0,0 +1,1303 @@+# Production Code Review: Database & Cache Layer++**Scope**: `data/local/`, `data/repository/`, `data/sync/`, Room schema v32+**Date**: 2026-04-16+**Reviewer**: Production code audit++---++## Executive Summary++The database and cache layer has solid architectural foundations: WAL mode, per-provider sync mutexes, staging-based atomic catalog replacement with fingerprint-diff updates, FTS search, comprehensive index coverage (32 migrations, 37 tables), and a maintenance worker with conditional VACUUM logic. Despite this, there are **four high-severity issues** that represent real production data loss and race-condition risks:++1. **Double GZIP decompression** in EPG refresh produces corrupt XML on misbehaving CDNs (DB-C-01)+2. **Watch-progress denormalization divergence** causes movies to appear "unwatched" even with history (DB-C-02)+3. **Provider cleanup race** in `onProviderDeleted` can leave a sync running over half-deleted data (DB-C-03)+4. **Background EPG job map registration race** can leak a completed-but-unreachable job entry (DB-ASYNC-02)++Beyond those, `CatalogSyncDao`'s N×columns correlated-subquery UPDATE is a scalability time bomb for large catalogs (DB-Q-01), VACUUM is triggered via a side-effecting `TRUNCATE` checkpoint (DB-PERF-01), and the classification cache uses a thundering-herd flush strategy (DB-CACHE-01).++---++## 1. Correctness & Data Integrity++### DB-C-01 · FIXED (2026-04-17) · 🔴 HIGH · EPG double GZIP decompression++**File**: `EpgRepositoryImpl.kt`++**Status**: Fixed by adding `EpgRepository.getProgramsForChannelsSnapshot()` and routing the bulk EPG callers in `EpgViewModel` and `TvInputChannelSyncManager` through that snapshot path. `EpgRepositoryImpl.getProgramsForChannels()` also now collapses oversized requests to a single snapshot emission instead of maintaining N chunked Room observers.++**Status**: Fixed in `EpgRepositoryImpl.refreshEpg()`. The repository now skips URL-suffix gzip detection when `Content-Encoding: gzip` has already been handled, and a regression test covers the `.xml.gz` + `Content-Encoding: gzip` combination.++The request sends `Accept-Encoding: identity` to disable OkHttp's transparent decompression, then manually wraps the body stream in `GZIPInputStream` when the response has `Content-Encoding: gzip`. Immediately after, the stream is passed to `xmltvParser.maybeDecompressGzip(epgUrl, limitedStream)`, which wraps in another `GZIPInputStream` if the URL path ends with `.xml.gz` or `.gz`.++If a misbehaving server or CDN forwards `Content-Encoding: gzip` AND the EPG URL ends in `.xml.gz` (common pattern: `epg.xml.gz` hosted behind a CDN gateway), the stream is decompressed twice. The second pass reads already-raw XML as a gzip stream, producing garbage bytes that either fail XML parsing silently or inject junk `<programme>` records into the staging table.++```kotlin+// Current (buggy path):+val httpStream = if (contentEncoding?.contains("gzip", ignoreCase = true) == true) {+ GZIPInputStream(rawStream) // ← already decompressed here+} else { rawStream }+// ...+xmltvParser.maybeDecompressGzip(epgUrl, limitedStream).use { xmlInput -> // ← decompresses again if URL ends in .gz+```++**Fix**:++```kotlin+val alreadyDecompressed = contentEncoding?.contains("gzip", ignoreCase = true) == true+val httpStream: InputStream = if (alreadyDecompressed) GZIPInputStream(rawStream) else rawStream+val limitedStream = ByteLimitFilterInputStream(httpStream, MAX_EPG_SIZE_BYTES)++// Skip URL-suffix detection if Content-Encoding already handled it+val xmlInput: InputStream = if (alreadyDecompressed) limitedStream+ else xmltvParser.maybeDecompressGzip(epgUrl, limitedStream)+xmlInput.use { ... }+```++---++### DB-C-02 · FIXED (2026-04-17) · 🔴 HIGH · Watch-progress denormalization divergence++**Files**: `PlaybackHistoryRepositoryImpl.kt`, `Daos.kt` (MovieDao, EpisodeDao)++**Status**: Fixed in the movie unwatched queries and in `PlaybackHistoryRepositoryImpl.clearAllHistory()`. Unwatched movie filters now read the authoritative `playback_history` table instead of stale denormalized `movies.watch_progress`, and a full history clear now uses direct reset updates for movie and episode progress instead of correlated whole-table resyncs. The same authoritative-source fix was also applied to the category-scoped movie unwatched queries/counts.++`movies.watch_progress` and `episodes.watch_progress` are denormalized copies of `playback_history.resume_position_ms`. Sync is event-driven via `syncDenormalizedProgress()` on every write. The risk is in the query consumers:++**`getUnwatchedByProviderPage`** uses the denormalized field:+```sql+SELECT * FROM movies+WHERE provider_id = :providerId AND COALESCE(movies.watch_progress, 0) <= 0+```++**`getInProgressByProviderPage`** correctly joins the authoritative table:+```sql+EXISTS (SELECT 1 FROM playback_history WHERE ... AND resume_position_ms > 0 ...)+```++This inconsistency means:+- If denormalization sync fails (DB-busy exception inside an outer transaction, partial rollback, or first-install migration), `watch_progress` stays `0` while `playback_history` has real progress. Those movies appear "unwatched" — the user sees no resume indicator and the "unwatched" filter incorrectly includes them.+- After `clearAllHistory()`, `syncAllDenormalizedProgress()` runs `UPDATE movies SET watch_progress = COALESCE((SELECT ... FROM playback_history ...), 0)` — a correlated subquery per movie row for every provider. For 50,000 movies, this executes 50,000 subqueries.++**Fix for `getUnwatchedByProviderPage`** — align to the authoritative source:+```sql+SELECT * FROM movies WHERE provider_id = :providerId+AND NOT EXISTS (+ SELECT 1 FROM playback_history+ WHERE playback_history.provider_id = movies.provider_id+ AND playback_history.content_type = 'MOVIE'+ AND playback_history.content_id = movies.id+ AND playback_history.resume_position_ms > 0+)+ORDER BY name ASC LIMIT :limit OFFSET :offset+```++**Fix for `clearAllHistory`** — replace the correlated sync with a direct reset:+```kotlin+// MovieDao+@Query("UPDATE movies SET watch_progress = 0, last_watched_at = 0")+suspend fun resetAllWatchProgress()++// EpisodeDao+@Query("UPDATE episodes SET watch_progress = 0, last_watched_at = 0")+suspend fun resetAllEpisodeWatchProgress()+```++---++### DB-C-03 · FIXED (2026-04-17) · 🔴 HIGH · Provider cleanup race in `onProviderDeleted`++**File**: `SyncManager.kt`++**Status**: Fixed in `SyncManager.onProviderDeleted()`. The provider mutex is now removed while still inside `withProviderLock`, and provider deletion also notifies `EpgRepository` so provider-scoped EPG sync state is cleaned up in the same critical section.++```kotlin+suspend fun onProviderDeleted(providerId: Long) {+ // ...+ withProviderLock(providerId) { ... } // acquires mutex, does cleanup, releases+ providerSyncMutexes.remove(providerId) // removes AFTER lock released+}+```++Between the lock release and `ConcurrentHashMap.remove()`, a concurrent `sync(providerId)` call invokes `computeIfAbsent(providerId) { Mutex() }` and obtains a fresh `Mutex`. The subsequent `remove(providerId)` then removes this new mutex, not the old one. The deleted provider now has no mutex entry — the next `sync(providerId)` would create yet another mutex and proceed over partially-cleaned-up data concurrently with the deletion.++**Fix** — move the remove inside the lock:+```kotlin+suspend fun onProviderDeleted(providerId: Long) {+ val cancelledEpgJob = backgroundEpgJobs.remove(providerId)+ cancelledEpgJob?.cancel()+ withProviderLock(providerId) {+ syncStateTracker.reset(providerId)+ xtreamAdaptiveSyncPolicy.forgetProvider(providerId)+ syncCatalogStore.clearProviderStaging(providerId)+ providerSyncMutexes.remove(providerId) // ← safe: mutex is held here+ }+ // No remove here — already done inside the lock+}+```++---++### DB-C-04 · FIXED (2026-04-17) · 🟡 MEDIUM · Clock-skew stale cache++**File**: `ContentCachePolicy.kt`++**Status**: Fixed in `ContentCachePolicy.shouldRefresh()`. Negative elapsed time now forces a refresh instead of leaving future-dated sync timestamps fresh until wall-clock time catches up.++```kotlin+fun shouldRefresh(lastSyncAt: Long, ttlMillis: Long, now: Long): Boolean =+ lastSyncAt <= 0L || now - lastSyncAt >= ttlMillis+```++If the device clock was set forward during a sync (NTP correction, user adjustment, DST), `lastSyncAt` becomes a future timestamp relative to the corrected `now`. The difference `now - lastSyncAt` is negative — less than any TTL — and the cache never triggers a refresh until real time catches up. With a 24h CATALOG_TTL, a 1-hour forward clock jump suppresses refreshes for 25 hours post-correction.++**Fix**:+```kotlin+fun shouldRefresh(lastSyncAt: Long, ttlMillis: Long, now: Long): Boolean {+ if (lastSyncAt <= 0L) return true+ val elapsed = now - lastSyncAt+ return elapsed < 0L || elapsed >= ttlMillis // negative = clock skew → force refresh+}+```++---++### DB-C-05 · FIXED (2026-04-17) · 🟡 MEDIUM · Unbounded `providerRefreshMutexes` in `EpgRepositoryImpl`++**File**: `EpgRepositoryImpl.kt`++**Status**: Fixed by adding `EpgRepository.onProviderDeleted(providerId)` and wiring `SyncManager.onProviderDeleted()` to call it. `EpgRepositoryImpl` now removes dead provider mutex entries when a provider is deleted.++```kotlin+private val providerRefreshMutexes = ConcurrentHashMap<Long, Mutex>()+```++A `Mutex` is added to this map on every `refreshEpg()` call (via `providerRefreshMutex(providerId)`). When a provider is deleted, `SyncManager.onProviderDeleted()` cleans up its own data but never notifies `EpgRepositoryImpl`. Over a long app session with repeated provider additions and deletions, this map accumulates dead `Mutex` objects that are never GC'd because the map holds strong references.++**Fix**: Expose `fun onProviderDeleted(providerId: Long)` on `EpgRepositoryImpl` and call it from `SyncManager.onProviderDeleted()`:+```kotlin+fun onProviderDeleted(providerId: Long) {+ providerRefreshMutexes.remove(providerId)+}+```++---++### DB-C-06 · FIXED (2026-04-17) · 🟡 MEDIUM · FTS query injection surface++**Files**: `Daos.kt` (ChannelDao, MovieDao, SeriesDao)++**Status**: Fixed in the repository search flows. Channel, movie, and series FTS-backed search entry points now fail soft to empty results when SQLite rejects a malformed MATCH expression at runtime, instead of propagating `SQLiteException` to the UI layer.++All FTS search queries use `channels_fts MATCH :query` with Room parameter binding. Room prevents SQL injection, but malformed FTS expressions (`OR`, `NOT`, `NEAR/n`, unbalanced double-quotes, bare `*`) throw `SQLiteException` at runtime. The project has `FtsQueryUtils` but callers must invoke it explicitly — there is no DAO-level enforcement.++**Fix**: Apply `FtsQueryUtils.buildPrefixQuery(rawInput)` in every repository search method before calling the DAO. Add a defensive catch in each repository search method:++```kotlin+// ChannelRepositoryImpl+override fun search(providerId: Long, query: String, limit: Int): Flow<List<Channel>> {+ val ftsQuery = FtsQueryUtils.buildPrefixQuery(query.trim())+ ?: return flowOf(emptyList())+ return channelDao.search(providerId, ftsQuery, limit)+ .catch { e ->+ if (e is SQLiteException) emit(emptyList())+ else throw e+ }+ .map { ... }+}+```++---++## 2. Query Quality++### DB-Q-01 · FIXED (2026-04-17) · 🔴 HIGH · CatalogSyncDao: N×columns correlated-subquery UPDATE++**File**: `CatalogSyncDao.kt`++**Status**: Fixed in `SyncCatalogStore`. The stage-apply path now reads staged rows once, diffs them against the current provider rows in Kotlin, and applies changed categories, channels, movies, and series through batched `@Update` calls instead of repeated correlated-subquery UPDATE statements.++The `updateChangedChannelsFromStage()` query updates each of the 14 updatable columns with a separate correlated subquery back to `channel_import_stage`:++```sql+UPDATE channels SET+ name = (SELECT stage.name FROM channel_import_stage AS stage WHERE stage.session_id = :sessionId AND stage.provider_id = :providerId AND stage.stream_id = channels.stream_id),+ logo_url = (SELECT stage.logo_url FROM channel_import_stage AS stage WHERE stage.session_id = :sessionId AND stage.provider_id = :providerId AND stage.stream_id = channels.stream_id),+ ... -- 12 more identical subquery blocks+WHERE provider_id = :providerId AND EXISTS (...)+```++For a provider with 10,000 channels and 14 updatable columns, this executes up to **140,000 correlated subquery lookups per sync**. Even with an index on `(provider_id, session_id, stream_id)` in the stage table, SQLite re-evaluates each subquery independently per column per row. The same pattern exists for movies and series.++On a device with 50,000 movies, a full-catalog movie sync can spend seconds on this single UPDATE statement, blocking the Dispatchers.IO thread and stalling subsequent sync phases.++**Fix** — move diff computation to Kotlin and use a targeted entity-batch `@Update`:++```kotlin+// In SyncCatalogStore or CatalogSyncDao:+suspend fun applyChannelChanges(providerId: Long, sessionId: Long) {+ val staged = catalogSyncDao.getChannelStageRows(providerId, sessionId) // single SELECT+ val existing = channelDao.getByProviderSync(providerId)+ val existingByStreamId = existing.associateBy { it.streamId }+ val changed = staged.mapNotNull { stage ->+ val current = existingByStreamId[stage.streamId] ?: return@mapNotNull null+ if (current.syncFingerprint == stage.syncFingerprint) return@mapNotNull null+ current.copy(name = stage.name, logoUrl = stage.logoUrl, ...) // apply diff+ }+ if (changed.isNotEmpty()) channelDao.updateAll(changed) // @Update batch+}+```++This replaces O(14n) subqueries with one SELECT + one batched UPDATE.++---++### DB-Q-02 · FIXED (2026-04-17) · 🔴 HIGH · Correlated subquery ORDER BY for watch-count sort++**File**: `Daos.kt` (MovieDao)++**Status**: Fixed by denormalizing `watch_count` into `movies.watch_count`, backfilling it from `playback_history` in migration 32→33, and switching the provider-scoped movie watch-count sort to `ORDER BY COALESCE(movies.watch_count, 0) DESC`.++```sql+ORDER BY COALESCE((+ SELECT playback_history.watch_count+ FROM playback_history+ WHERE playback_history.provider_id = movies.provider_id+ AND playback_history.content_type = 'MOVIE'+ AND playback_history.content_id = movies.id+ LIMIT 1+), 0) DESC, movies.name ASC+LIMIT :limit OFFSET :offset+```++SQLite cannot use indexes to short-circuit a correlated ORDER BY before applying LIMIT. All `movies` rows are evaluated, each with a subquery lookup from `playback_history`, before `LIMIT` is applied. For a provider with 50,000 movies, this materializes 50,000 rows with 50,000 subquery lookups even when only 20 rows are needed by the UI.++**Fix**: Denormalize `watch_count` into `MovieEntity` (matching the existing `watch_progress` denormalization pattern), then query directly:++```sql+ORDER BY COALESCE(movies.watch_count, 0) DESC, movies.name ASC+LIMIT :limit OFFSET :offset+```++Sync `watch_count` the same way as `watch_progress` via `syncWatchProgressFromHistory()`.++---++### DB-Q-03 · FIXED (2026-04-17) · 🟡 MEDIUM · Same correlated sort on category-scoped variant++**File**: `Daos.kt` (MovieDao — `getByWatchCountCategoryPage`)++**Status**: Fixed alongside DB-Q-02. The category-scoped movie watch-count sort now reads the denormalized `movies.watch_count` column directly instead of executing a correlated subquery per row.++Identical problem as DB-Q-02, scoped to a category. Applies the same fix: add `watch_count` to `MovieEntity` and use it directly in ORDER BY.++---++### DB-Q-04 · FIXED (2026-04-17) · 🟡 MEDIUM · `getNowPlaying` captures stale timestamp on long-lived subscriptions++**File**: `EpgRepositoryImpl.kt`++**Status**: Fixed in `EpgRepositoryImpl.getNowPlaying()`. It now uses the existing `nowTicker()` refresh flow, matching `getNowAndNext()` so long-lived subscriptions reevaluate against current time instead of a one-time timestamp captured at subscription.++```kotlin+override fun getNowPlaying(providerId: Long, channelId: String): Flow<Program?> =+ programDao.getNowPlaying(providerId, channelId, System.currentTimeMillis())+ .map { it?.toDomain() }+```++`System.currentTimeMillis()` is captured once when the `Flow` is subscribed. A UI component holding this flow for > 30 minutes (e.g., a persistent EPG guide overlay) receives a "now" timestamp that is 30+ minutes stale, and programs that have since ended remain labeled "now playing." Only `getNowAndNext()` wraps in `nowTicker()`.++**Fix**:+```kotlin+override fun getNowPlaying(providerId: Long, channelId: String): Flow<Program?> =+ nowTicker().flatMapLatest { now ->+ programDao.getNowPlaying(providerId, channelId, now)+ .map { it?.toDomain() }+ }+```++---++### DB-Q-05 · FIXED (2026-04-17) · 🟡 MEDIUM · Favorites `IS NULL` predicate reduces index efficiency++**File**: `Daos.kt` (MovieDao)++**Status**: Fixed with a dedicated partial index, `index_favorites_global_provider_id_content_type_content_id`, on global favorites only (`WHERE group_id IS NULL`). The query shape stays the same, but SQLite now has an index tailored to that predicate.++```sql+EXISTS (+ SELECT 1 FROM favorites+ WHERE favorites.content_type = 'MOVIE'+ AND favorites.provider_id = movies.provider_id+ AND favorites.group_id IS NULL+ AND favorites.content_id = movies.id+)+```++The unique index on `favorites` is `(provider_id, content_id, content_type, group_id)`. The `group_id IS NULL` predicate on the trailing index column limits SQLite's ability to use the full index range. This subquery runs once per movie row in the outer scan — for large catalogs it degrades to O(movies × partial_index_scan).++**Fix**: Add an explicit `is_global_favorite` boolean column to `FavoriteEntity` (true when `group_id IS NULL`), maintained on insert/delete. The favorites query then becomes a simple equality predicate on an indexed column. Alternatively, use a partial index:+```sql+CREATE INDEX IF NOT EXISTS idx_favorites_global+ ON favorites(provider_id, content_type, content_id)+ WHERE group_id IS NULL+```++---++## 3. Cache Behavior++### DB-CACHE-01 · FIXED (2026-04-17) · 🔴 HIGH · AdultContentClassifier thundering-herd cache flush++**File**: `AdultContentClassifier.kt`++**Status**: Fixed in `AdultContentClassifier`. The cache now uses bounded LRU-style eviction instead of clearing the entire map at capacity, which avoids the full-cache miss storm during large imports and removes the non-atomic `size/check/clear/insert` pattern.++```kotlin+private val classificationCache = ConcurrentHashMap<String, Boolean>()++if (classificationCache.size >= MAX_CLASSIFICATION_CACHE_SIZE) {+ classificationCache.clear()+}+classificationCache[normalized] = isAdult+```++When the cache reaches 4,096 entries, the next classification call clears the entire map and repopulates with a single entry. The next ~4,095 classifications all miss the cache and re-classify from scratch (regex/string scanning). During a large catalog sync (100k+ channels), this can fire dozens of times, causing CPU spikes when the classifier re-processes all recently-seen values.++The size-check + clear + insert on `ConcurrentHashMap` is also not atomic: two threads can both observe `size >= MAX`, both call `clear()`, and both insert their entry — result is two entries in the map, both correct but the thundering herd is compounded.++**Fix** — use a synchronized LRU with bounded eviction:+```kotlin+private val classificationCache: MutableMap<String, Boolean> =+ Collections.synchronizedMap(+ object : LinkedHashMap<String, Boolean>(256, 0.75f, true) {+ override fun removeEldestEntry(e: Map.Entry<String, Boolean>) =+ size > MAX_CLASSIFICATION_CACHE_SIZE+ }+ )+```++---++### DB-CACHE-02 · FIXED (2026-04-17) · 🟡 MEDIUM · Partial sync updates TTL timestamp; stale data treated as fresh++**File**: `SyncManager.kt` / `ContentCachePolicy.kt`++**Status**: Fixed by separating success freshness from attempt timestamps. `SyncMetadata` now tracks `lastLiveSuccess`, `lastSeriesSuccess`, and `lastEpgSuccess`, `movie` continues to use `lastMovieSuccess`, and the TTL checks in `SyncManager` now key off those success timestamps instead of the broader attempt/partial timestamps.++After a partial sync (`SyncState.Partial`), `syncMetadataRepository.updateMetadata()` stamps `lastSyncAt` with the current time. Subsequent `ContentCachePolicy.shouldRefresh()` calls return `false` for up to 24h, even though the catalog is incomplete (e.g., only categories 1–30 of 60 were fetched).++**Fix** — track successful and attempted sync timestamps separately:++```kotlin+// SyncMetadataEntity+@ColumnInfo(name = "last_successful_live_sync") val lastSuccessfulLiveSync: Long = 0L+// ...++// ContentCachePolicy+fun shouldRefresh(lastSuccessfulSyncAt: Long, ttlMillis: Long, now: Long): Boolean {+ val elapsed = now - lastSuccessfulSyncAt+ return lastSuccessfulSyncAt <= 0L || elapsed < 0L || elapsed >= ttlMillis+}+```++Only update `lastSuccessfulSyncAt` on `SyncState.Success`. `lastSyncAt` (attempted) continues to update on partial for backoff/retry logic.++---++### DB-CACHE-03 · FIXED (2026-04-17) · 🟡 MEDIUM · DataStore incognito check blocks per playback event++**File**: `PlaybackHistoryRepositoryImpl.kt`++**Status**: Fixed in `PlaybackHistoryRepositoryImpl`. Incognito mode is now cached in a hot `StateFlow`, so playback write paths read `isIncognito.value` instead of suspending on `DataStore.data.first()` for every playback update.++```kotlin+override suspend fun recordPlayback(history: PlaybackHistory): Result<Unit> {+ return try {+ if (preferencesRepository.isIncognitoMode.first()) { // ← DataStore read every call+ return Result.success(Unit)+ }+```++`DataStore.data.first()` suspends to read preferences from disk on every `recordPlayback()` / `updateResumePosition()` / `markAsWatched()` call. If the player saves progress at 10-second intervals, this performs ~360 DataStore reads per hour of playback, each blocking the calling coroutine.++**Fix** — cache in a hot `StateFlow` initialized eagerly:+```kotlin+private val isIncognito: StateFlow<Boolean> =+ preferencesRepository.isIncognitoMode+ .stateIn(applicationScope, SharingStarted.Eagerly, initialValue = false)++// In each write method:+if (isIncognito.value) return Result.success(Unit)+```++---++### DB-CACHE-04 · FIXED (2026-04-17) · 🟢 LOW · EPG size cap: partial protection on chunked-transfer responses++**File**: `EpgRepositoryImpl.kt`++**Status**: Fixed in both `EpgRepositoryImpl` and `EpgSourceRepositoryImpl`. When the byte-limit guard trips during chunked EPG downloads, the repositories now translate that specific oversize `IOException` into a typed `Result.error("EPG response exceeded 200 MB limit")` instead of surfacing a generic parser/download failure.++```kotlin+val contentLength = response.header("Content-Length")?.toLongOrNull() ?: -1L+if (contentLength > MAX_EPG_SIZE_BYTES) {+ response.close()+ return@withLock Result.error("EPG file too large...")+}+```++When the server uses chunked transfer encoding (common from CDNs), `Content-Length` is absent (`-1L`). The pre-download size check is bypassed, and protection falls entirely to the `FilterInputStream` byte counter. When that counter trips at 200 MB, it throws `IOException` mid-stream. This IOException propagates to the catch block, which deletes the staging rows and re-throws — correct, but the error surface is an opaque `IOException` rather than a typed size limit error.++**Fix**: In the catch block, detect the specific IOException message and return a typed error:+```kotlin+} catch (e: IOException) {+ programDao.deleteByProvider(stagingProviderId)+ if (e.message?.contains("too large") == true)+ return@withLock Result.error("EPG response exceeded 200 MB limit")+ return@withLock Result.error("EPG download failed: ${e.message}")+}+```++---++## 4. Performance++### DB-PERF-01 · FIXED (2026-04-17) · 🔴 HIGH · VACUUM triggered via side-effecting TRUNCATE checkpoint++**File**: `DatabaseMaintenanceManager.kt`++**Status**: Fixed in `DatabaseMaintenanceManager.runVacuum()`. Maintenance now uses a non-blocking `wal_checkpoint(PASSIVE)` inspection step, only attempts a `FULL` checkpoint when WAL is already clear enough to proceed, and skips `VACUUM` if WAL pages remain instead of using `TRUNCATE` as a side-effecting pre-check.++```kotlin+val busyPages = sqliteDb.query("PRAGMA wal_checkpoint(TRUNCATE)").use { cursor ->+ if (cursor.moveToFirst()) cursor.getInt(1) else 0+}+if (busyPages > 0) {+ Log.w(TAG, "wal_checkpoint(TRUNCATE) had $busyPages busy pages; VACUUM skipped")+ return@withContext false+}+sqliteDb.execSQL("VACUUM")+```++Two problems:++1. **Side-effecting pre-check**: `wal_checkpoint(TRUNCATE)` is not a read-only check. It attempts to checkpoint and then truncate the WAL file. Using it purely to test for busy readers is a harmful side effect — if other connections are active, the truncation attempt adds contention. `PASSIVE` mode should be used for non-blocking inspection.++2. **VACUUM blocks all readers in WAL mode**: Despite WAL's reader-writer concurrency, `VACUUM` requires an `EXCLUSIVE` database lock, blocking all Room query flows on the main thread for its entire duration. On a database ≥ 128 MB, VACUUM can take 2–5 seconds — long enough to produce an ANR warning if UI threads are blocked on Room queries.++**Fix**:+```kotlin+// Step 1: non-blocking WAL state check+val notCheckpointed = sqliteDb.query("PRAGMA wal_checkpoint(PASSIVE)").use { c ->+ if (c.moveToFirst()) c.getInt(1) else -1 // column 1 = pages not yet checkpointed+}+if (notCheckpointed > 0) {+ Log.d(TAG, "VACUUM deferred: $notCheckpointed WAL pages not checkpointed")+ return@withContext false+}+// Step 2: full checkpoint to clear WAL before VACUUM+sqliteDb.execSQL("PRAGMA wal_checkpoint(FULL)")+// Step 3: VACUUM (only safe after full checkpoint, and no active sync per isSyncActive check)+sqliteDb.execSQL("VACUUM")+```++Long-term: move VACUUM into a WorkManager job constrained to `requiresDeviceIdle() + requiresCharging()` to prevent any foreground contention.++---++### DB-PERF-02 · FIXED (2026-04-18) · 🟡 MEDIUM · EPG staging inserts in separate implicit transactions++**File**: `EpgRepositoryImpl.kt`++**Status**: Fixed in `EpgRepositoryImpl.refreshEpg()`. The staging delete plus all streamed `programDao.insertAll()` batches now run inside one explicit `transactionRunner.inTransaction` block before the final provider swap transaction, and a regression test verifies inserts happen while a transaction is active.++```kotlin+xmltvParser.parseStreaming(xmlInput) { program ->+ batch.add(program.copy(providerId = stagingProviderId).toEntity())+ if (batch.size >= 500) {+ programDao.insertAll(batch.toList()) // ← each call = one Room auto-transaction+ batch.clear()+ }+}+```++For a 50,000-program XMLTV feed, this executes 100 separate Room transactions (WAL write + fsync per batch). Wrapping in a single transaction would reduce the total write cost to one fsync.++**Fix**:+```kotlin+transactionRunner.inTransaction {+ xmltvParser.parseStreaming(xmlInput) { program ->+ batch.add(program.copy(providerId = stagingProviderId).toEntity())+ if (batch.size >= 500) {+ programDao.insertAll(batch.toList())+ batch.clear()+ }+ }+ if (batch.isNotEmpty()) programDao.insertAll(batch.toList())+}+```++Note: This creates a longer-lived transaction, but since the staging table is dedicated to this provider ID and no UI reads from negative provider IDs, there is no read-contention risk. Memory pressure stays bounded by the 500-item batch.++---++### DB-PERF-03 · FIXED (2026-04-17) · 🟡 MEDIUM · 24h program retention deletes active catch-up content++**File**: `DatabaseMaintenanceManager.kt`++**Status**: Fixed in `DatabaseMaintenanceManager`. Program retention now uses the maximum `catch_up_days` across stored channels, with a 24h minimum floor, instead of hard-coding every provider to one day of retained guide data.++```kotlin+private const val PROGRAM_RETENTION_MILLIS = 24L * 60 * 60 * 1000L+val deletedPrograms = programDao.deleteOld(oldProgramThreshold)+```++The maintenance job deletes all programs with `end_time < now - 24h`. Live channels with catch-up support declare `catch_up_days` (up to 7 days is common). Deleting their programs at 24h silently destroys the program guide for days 2–7 of catch-up, leaving users with empty EPG grids when browsing back in time.++**Fix**: Compute retention from the longest catch-up window among active channels:++```kotlin+// ChannelDao+@Query("SELECT COALESCE(MAX(catch_up_days), 0) FROM channels WHERE provider_id = :providerId AND catch_up_supported = 1")+suspend fun getMaxCatchUpDays(providerId: Long): Int++// DatabaseMaintenanceManager+val catchUpDays = channelDao.getMaxCatchUpDaysAcrossAllProviders()+val retentionMs = maxOf(PROGRAM_MIN_RETENTION_MILLIS, catchUpDays * 86_400_000L)+```++---++### DB-PERF-04 · FIXED (2026-04-17) · 🟢 LOW · `syncAllWatchProgressFromHistory` — full provider table scan after history clear++**File**: `Daos.kt` (MovieDao)++**Status**: Fixed indirectly by the `DB-C-02` history-clear changes. `PlaybackHistoryRepositoryImpl.clearAllHistory()` now calls direct reset updates for movie and episode watch progress instead of invoking the correlated whole-table sync path after history has been cleared.++After `clearAllHistory()`, `syncAllWatchProgressFromHistory()` issues:+```sql+UPDATE movies+SET watch_progress = COALESCE((SELECT resume_position_ms FROM playback_history WHERE ...), 0)+WHERE provider_id = :providerId+```++Since history is just cleared, every COALESCE returns 0 — the subquery always misses. This scans the entire movies table executing 50,000 guaranteed-null subqueries.++**Fix** — use direct reset after a full clear (see DB-C-02 fix above):+```kotlin+@Query("UPDATE movies SET watch_progress = 0, last_watched_at = 0")+suspend fun resetAllWatchProgress()+```++---++## 5. Scalability++### DB-SCALE-01 · FIXED (2026-04-18) · 🟡 MEDIUM · Chunked `combine()` thundering-herd on EPG table writes++**File**: `EpgRepositoryImpl.kt`++```kotlin+val chunks = channelIds.chunked(500)+return combine(chunks.map { chunk ->+ programDao.getForChannels(providerId, chunk, startTime, endTime)+}) { arrays -> arrays.flatMap { it.toList() }... }+```++For an EPG guide with 5,000 channels, this creates 10 reactive Room query subscriptions. Every write to the `programs` table (EPG refresh, maintenance) invalidates ALL Room observers on that table, causing all 10 chunks to re-emit simultaneously, triggering a `combine` recomposition that maps and flatMaps 5,000+ program entities on each emission.++**Fix**: For bulk EPG grid loading, use a single snapshot query rather than 10 reactive flows:+```kotlin+override suspend fun getProgramsForChannelsSnapshot(providerId: Long, channelIds: List<String>, startTime: Long, endTime: Long): Map<String, List<Program>> {+ return channelIds.chunked(500).flatMap { chunk ->+ programDao.getForChannelsSync(providerId, chunk, startTime, endTime)+ }.map { it.toDomain() }.groupBy { it.channelId }+}+```++Drive a periodic refresh from a ticker flow in the UI layer, rather than a reactive database subscription per channel.++---++### DB-SCALE-02 · FIXED (2026-04-18) · 🟢 LOW · Virtual groups position reordering on large favorite sets++**Files**: `FavoriteDao`, `VirtualGroupDao`++**Status**: Fixed in `FavoriteRepositoryImpl.reorderFavorites()` and the live/VOD reorder save paths. Favorites now use sparse gap-based positions (`POSITION_STEP = 1024`) so most reorders only rewrite the affected slice instead of every row, and the UI no longer re-densifies positions to `0..n` before persisting. Existing dense lists still normalize once on their first reorder, after which subsequent moves stay localized.++Favorites are ordered by `position` (integer). Reordering via `reorderFavorites()` issues `UPDATE favorites SET position = :pos WHERE id = :id` for every entry. For a user with 500 favorites in one group, a drag-to-reorder near the top issues 500 individual UPDATE statements (one per shifted row). There is no bulk-update path.++**Fix**: Use fractional / gap-based positioning (e.g., float/double position with midpoints on reorder) to limit updates to the single moved item in most cases.++---++### DB-SCALE-03 · FIXED (2026-04-18) · 🟢 LOW · `backgroundEpgScope` EPG jobs are not durable across process death++**File**: `SyncManager.kt`++**Status**: Fixed by replacing the in-process background EPG coroutine path with `BackgroundEpgSyncWorker`. `SyncManager.scheduleBackgroundEpgSync()` now enqueues unique WorkManager work per provider with `NetworkType.CONNECTED`, `batteryNotLow`, and exponential backoff, so queued EPG refresh survives process death and is not duplicated by repeated schedule requests.++```kotlin+private val backgroundEpgScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)+```++EPG refresh jobs launched via `scheduleBackgroundEpgSync()` live entirely in-process. If the app is killed mid-download (OOM, system reclaim on a low-memory TV box), the EPG sync is silently lost with no retry. The `SyncWorker` maintenance job does not cover EPG refresh.++**Fix**: Move scheduled EPG refresh to WorkManager with `KEEP` existing-work policy, `setRequiredNetworkType(NetworkType.CONNECTED)`, and exponential backoff. WorkManager persists the job and retries after process restart.++---++## 6. Resilience++### DB-RES-01 · FIXED (2026-04-18) · 🟡 MEDIUM · `SyncWorker` is maintenance-only; no durable catalog or EPG sync++**File**: `SyncWorker.kt`++**Status**: Fixed by persisting a compact maintenance summary to `PreferencesRepository` DataStore after each maintenance run and surfacing it in the existing Settings diagnostics UI as a "Database Health" card with the last run time, cleanup counts, storage sizes, reclaimable bytes, and VACUUM result.++**Status**: Fixed by adding `ProviderSyncWorker`, a separate periodic WorkManager job that runs every 6 hours with network and battery-not-low constraints and calls `SyncManager.sync(force = false)` for saved providers. `SyncWorker` remains maintenance-only, but catalog and EPG freshness are now covered by durable periodic work instead of relying solely on the in-process app lifecycle.++`SyncWorker.doWork()` calls only `DatabaseMaintenanceManager.runDailyMaintenance()`. Provider catalog and EPG refreshes are not handled by WorkManager at all. If the user's device is out of memory and the app is killed during a background EPG download (triggered by `scheduleBackgroundEpgSync()`), data goes stale with no recovery mechanism.++**Fix**: Add a `ProviderSyncWorker` that re-syncs all active providers if their TTL has expired, scheduled via `PeriodicWorkRequest` with network and battery constraints. Wire it to the existing `sync()` entry point in `SyncManager`.++---++### DB-RES-02 · FIXED (2026-04-17) · 🟡 MEDIUM · Migrations lack `PRAGMA foreign_key_check`++**File**: `StreamVaultDatabase.kt`++**Status**: Fixed in `StreamVaultDatabase`. Table-restructuring migrations now run a real FK integrity check via `PRAGMA foreign_key_check` queried through `SupportSQLiteDatabase`, and the migration throws if any violation is found instead of silently opening a broken schema.++Several major migrations (MIGRATION_8_9, MIGRATION_10_11, MIGRATION_28_29, MIGRATION_31_32) rebuild tables and add or restructure foreign keys. None execute a post-migration integrity check. A subtle bug in an ID remapping step (e.g., `channel_id_map` misses a record) leaves orphaned favorites or history rows silently — the migration succeeds, Room opens the database, and the orphan is invisible until `DatabaseMaintenanceManager` trims it.++**Fix**: Add after each migration that restructures FK relationships:+```kotlin+database.execSQL("PRAGMA foreign_key_check")+// Will throw if any FK violation is found, preventing corrupt database from opening+```++---++### DB-RES-03 · FIXED (2026-04-18) · 🟢 LOW · Session IDs use wall-clock milliseconds — clock adjustment collision risk++**File**: `SyncManager.kt` / staging tables++**Status**: Fixed in `SyncCatalogStore.newSessionId()`. Session IDs no longer derive from wall-clock time; the in-process session counter is now seeded from a random positive `Long` and advances monotonically from there, which removes the clock-rollback collision path for stale staged rows after app restarts.++Staging session IDs are derived from `System.currentTimeMillis()`. If the device clock is adjusted backwards between two syncs for the same provider (NTP correction), the new session could reuse a previous session's ID. While per-`(provider_id, session_id)` scoping prevents cross-provider conflicts, for the same provider, stale rows from the aborted session could be promoted by the new session.++**Fix**: Use `UUID.randomUUID()` (or `System.nanoTime() xor Random.nextLong()`) for session IDs.++---++### DB-RES-04 · FIXED (2026-04-18) · 🟢 LOW · `ChannelDao.replaceAll()` in an interface with `@Transaction`++**File**: `Daos.kt`++**Status**: Fixed by converting `ChannelDao` from an interface DAO to an abstract class DAO. `replaceAll()` now remains an `open` transactional method on an abstract Room DAO, which removes reliance on Room's interface-default-method transaction wrapper behavior for this path.++```kotlin+@Dao+interface ChannelDao {+ @Transaction+ suspend fun replaceAll(providerId: Long, channels: List<ChannelEntity>) { ... }+}+```++Room supports `@Transaction` on Kotlin interface default methods by generating a delegation wrapper. However, the generated wrapper behavior for `suspend` default interface methods differs subtly from `abstract class` methods in edge cases across Room versions. Additionally, the body calls three separate DAO methods (`getIdMappings`, `deleteByProvider`, `insertAll`) — each individually valid, but the transaction boundary depends on Room's generated wrapper correctly entering a transaction before the first call.++**Fix**: Convert `ChannelDao` to `abstract class` (as `ProviderDao` already is) to guarantee the `@Transaction` contract:+```kotlin+@Dao+abstract class ChannelDao {+ @Transaction+ open suspend fun replaceAll(providerId: Long, channels: List<ChannelEntity>) { ... }+}+```++---++## 7. Schema & Migrations++### DB-SCH-01 · FIXED (2026-04-18) · 🟡 MEDIUM · `is_user_protected` is not in the staging tables — orphan protection persists++**File**: `CatalogSyncDao.kt`, `Entities.kt`++**Status**: Fixed in `SyncCatalogStore.applyCategories()`. When a previously user-protected category is re-mapped in staging (detected by a changed category sync fingerprint), the category now has its user-protection bit cleared and the inherited `is_user_protected` flags on channels, movies, or series for that category are cleared in the same apply transaction. A regression test covers the remapped protected-category case.++`ChannelImportStageEntity`, `MovieImportStageEntity`, and `SeriesImportStageEntity` deliberately omit `is_user_protected` to preserve user-applied parental locks across syncs. However, if a category disappears from the provider (removed by the IPTV service), its channels are deleted from `channels` by the stale-deletion step — correct. But `categories` keep `is_user_protected = 1` for any category that still exists at the database level. If a parent category was removed while a sub-category was re-mapped, the protection state can be orphaned reference protection on a new category that has the same ID but different content.++**Recommendation**: After applying category changes from staging, run a targeted cleanup that verifies protection references still correspond to valid category+provider pairs. Consider flagging re-mapped category IDs as "protection invalidated" and prompting the user to re-apply.++---++### DB-SCH-02 · FIXED (2026-04-18) · 🟢 LOW · Sync fingerprint hash collision risk on 100k+ catalogs++**File**: `Entities.kt`++**Status**: Verified not reproducible in the current implementation. `SyncCatalogStore.fingerprint()` already computes a full SHA-256 digest and stores the complete 64-hex-character value, so the review's "short hash / 64-bit fingerprint" collision scenario no longer matches the codebase.++The `sync_fingerprint` determines whether a catalog item needs an update (`current.sync_fingerprint != stage.sync_fingerprint`). If the fingerprint is a short hash (MD5/SHA-1 truncated to a string), a collision causes a changed item to appear unchanged — suppressing a metadata update silently.++For a provider with 100,000 channels, with a 64-bit fingerprint space, the collision probability per sync cycle is ~0.5% (birthday paradox). Over months of daily syncs, silent missed updates accumulate.++**Fix**: Use a content digest with at least 128 bits (SHA-256 first 16 bytes, hex-encoded), or a `hashCode()` of all mutable fields concatenated deterministically.++---++### DB-SCH-03 · FIXED (2026-04-17) · 🟢 LOW · No index on `programs.end_time` for lookback queries++**File**: Schema v32++**Status**: Fixed in schema v34 and migration 33→34 by adding `index_programs_provider_id_end_time_channel_id` on `(provider_id, end_time, channel_id)`.++EPG queries for currently-airing programs use time windows like `start_time < :now AND end_time > :now`. The existing index `(provider_id, channel_id, start_time, end_time)` efficiently bounds the `start_time <` predicate but requires SQLite to scan all rows within the start-time range and filter on `end_time >` separately. For channels with dense EPG data (30-minute slots, 24h × 10 days = 480 programs/channel), the scan per channel is acceptable, but across thousands of channels it compounds.++**Fix**: Add a complementary index:+```sql+CREATE INDEX idx_programs_provider_end_time_channel+ ON programs(provider_id, end_time, channel_id)+```++Room migration:+```kotlin+database.execSQL("CREATE INDEX IF NOT EXISTS idx_programs_provider_end_time_channel ON programs(provider_id, end_time, channel_id)")+```++---++### DB-SCH-04 · FIXED (verified 2026-04-18) · 🟢 LOW · VirtualGroup migration (MIGRATION_31_32) risks zero-active-provider default++**File**: `StreamVaultDatabase.kt`++**Status**: Verified not reproducible in the current migration. `MIGRATION_31_32` already falls back from the active provider to the first provider by ID when no provider is active, and an instrumentation regression test now covers the zero-active-provider case to ensure migrated `virtual_groups.provider_id` is never left as `0` or `NULL`.++Migration 31→32 adds `provider_id` to `virtual_groups` and scopes it to a provider. The migration likely populates existing rows by selecting the currently-active provider via `SELECT id FROM providers WHERE is_active = 1 LIMIT 1`. If the app was force-closed mid-sync — leaving `is_active = 0` for all providers — this subquery returns NULL. Existing virtual groups default to `provider_id = 0` (or NULL), orphaning them from all real providers.++**Recommendation**: After the migration, verify that `SELECT COUNT(*) FROM virtual_groups WHERE provider_id = 0 OR provider_id IS NULL` is 0. If not, attempt to recover by associating orphan groups to the most recently created provider.++---++## 8. Threading / Async++### DB-ASYNC-01 · FIXED (2026-04-18) · 🟡 MEDIUM · VACUUM/sync active check is not atomic++**File**: `DatabaseMaintenanceManager.kt`++**Status**: Fixed by coordinating maintenance with `SyncManager` through a shared admission gate. New syncs now acquire their provider mutex while holding `syncAdmissionMutex`, and `DatabaseMaintenanceManager` uses `SyncManager.runWhenNoSyncActive { ... }` to atomically block new sync starts, detect already-active syncs, and run `VACUUM` only when the database is truly idle. A concurrency regression test covers the in-flight sync case.++```kotlin+val vacuumRan = if (shouldVacuum(statsBeforeVacuum) && !isSyncActive()) {+ runVacuum()+} else { false }+```++Between the `!isSyncActive()` check and the `VACUUM` call, a new sync can start in another coroutine. The sync then holds a provider mutex and begins writing to the database, while VACUUM attempts to acquire an exclusive lock. SQLite will handle the lock contention, but the sync may receive `SQLITE_BUSY` errors that surface to the user as spurious sync failures.++**Fix**: Consult the same lock inside `runVacuum()` rather than before it. If a sync starts mid-VACUUM, abort VACUUM via connection timeout rather than letting SQLite retry indefinitely.++---++### DB-ASYNC-02 · FIXED (verified 2026-04-17) · 🔴 HIGH · Background EPG job map registration race++**File**: `SyncManager.kt`++**Status**: Already fixed in the current `SyncManager.scheduleBackgroundEpgSync()` implementation. The launched job is stored in `backgroundEpgJobs` before `invokeOnCompletion` registration is relied on for cleanup, so the completed-before-registration leak path described below no longer exists in the checked-in code.++```kotlin+fun scheduleBackgroundEpgSync(providerId: Long) {+ backgroundEpgJobs.remove(providerId)?.cancel()+ val job = backgroundEpgScope.launch { ... } // ← coroutine launched+ backgroundEpgJobs[providerId] = job // ← job stored AFTER launch+ job.invokeOnCompletion {+ backgroundEpgJobs.remove(providerId, job)+ }+}+```++If the launched coroutine completes synchronously (e.g., `providerDao.getById(providerId)` returns null immediately), `invokeOnCompletion` fires before `backgroundEpgJobs[providerId] = job` executes. `remove(providerId, job)` finds no entry and does nothing. Then the store `backgroundEpgJobs[providerId] = job` inserts a reference to a completed job that is never cleaned up. Future calls to `scheduleBackgroundEpgSync()` cancel this phantom job (no-op) and store a new one, but the phantom accumulates if it races repeatedly.++The comment acknowledges the intent was to store before completion, but the ordering is inverted.++**Fix**:+```kotlin+fun scheduleBackgroundEpgSync(providerId: Long) {+ backgroundEpgJobs.remove(providerId)?.cancel()+ val job: Job+ synchronized(backgroundEpgJobs) {+ job = backgroundEpgScope.launch { ... }+ backgroundEpgJobs[providerId] = job+ }+ job.invokeOnCompletion { backgroundEpgJobs.remove(providerId, job) }+}+```++---++### DB-ASYNC-03 · FIXED (2026-04-18) · 🟢 LOW · `collectStorageStats()` touches the writable database on IO++**File**: `DatabaseMaintenanceManager.kt`++**Status**: Fixed by making the IO contract explicit. `collectStorageStats()` and its pragma helpers are now annotated `@WorkerThread`, and the method remains private to `DatabaseMaintenanceManager`, so the writable-database reads are clearly documented as worker-thread-only maintenance code.++`collectStorageStats()` calls `database.openHelper.writableDatabase` and executes three `PRAGMA` queries. This is within `withContext(Dispatchers.IO)` in `runDailyMaintenance()`, which is correct. However, the method is not annotated or documented as requiring `Dispatchers.IO`. A future refactor that calls it outside the IO context would cause a `StrictMode` violation or silent deadlock.++**Fix**: Add `@WorkerThread` annotation and a `check(isOnIoDispatcher)` guard, or make the method private and always-inlined within the `withContext(Dispatchers.IO)` body.++---++## 9. Observability++### DB-OBS-01 � FIXED (2026-04-18) � MEDIUM � No slow-query instrumentation++**Files**: All DAO files and repositories++**Status**: Fixed in `DatabaseModule` with a debug-only `SlowQueryLoggingOpenHelperFactory`. Room now uses a wrapped `SupportSQLiteOpenHelper` in debug builds that times actual `query`, `execSQL`, and compiled-statement execution paths and logs only statements taking 100ms or longer.++No query timing was captured anywhere in the data layer. Slow queries (correlated-subquery sorts, large FTS results, 50k-row migrations, VACUUM) were invisible without external APM tooling. In production, users experiencing slow UI could not self-diagnose, and developers could not identify which query was responsible.+**Fix**: Add a Room `QueryCallback` in debug builds to log queries exceeding 100ms:+**Fix**: Install a debug-only open-helper wrapper that times SQL execution and logs slow statements:+```kotlin+Room.databaseBuilder(context, StreamVaultDatabase::class.java, "streamvault.db")+ .openHelperFactory(+ SlowQueryLoggingOpenHelperFactory(+ delegate = FrameworkSQLiteOpenHelperFactory(),+ slowQueryThresholdMs = 100L+ )+ )+```++For production, integrate a lightweight `SQLiteQueryStats` observer that records P95/P99 latency per query pattern and logs a warning on any single query taking > 500ms.++---++### DB-OBS-02 · FIXED (2026-04-18) · 🟡 MEDIUM · Maintenance report not persisted or surfaced++**File**: `SyncWorker.kt`++```kotlin+Log.d("SyncWorker", "Maintenance complete: oldPrograms=${report.deletedPrograms}, ...")+```++The maintenance report is logged at `DEBUG` level only — invisible in production logcat filters. The database size, freelist percentage, whether VACUUM was deferred repeatedly, and the count of orphaned records cleaned up are all genuine health signals that should be accessible outside a debug build.++**Fix**: Persist the last `MaintenanceReport` summary (timestamp, DB size, vacuum ran, rows cleaned) to `PreferencesRepository` via DataStore after each run. Expose a "Database Health" card in the Settings diagnostics screen that shows this data and warns when:+- VACUUM has been deferred for > 30 days+- Freelist exceeds 30% of database size+- Sequential failure count for any provider exceeds 10++---++### DB-OBS-03 · FIXED (2026-04-18) · 🟢 LOW · Provider health streaks not surfaced for user alerting++**File**: `SyncMetadataEntity`, `SyncManager.kt`++**Status**: Fixed by extending the Settings diagnostics model and panel to show the provider-health signals already tracked in `SyncMetadata`, including remembered live/movie/series failure states, healthy streak counters, stale movie-catalog state, and remembered movie warning counts. Those warnings now remain visible in Settings instead of disappearing with the next transient sync-state update.++`SyncMetadata` tracks provider-health signals such as remembered failure states and healthy streaks. Before this fix, they were only used internally for adaptive sync behavior and were never surfaced to the user as a persistent warning. A provider with repeated failures could therefore look "idle" in Settings once the transient sync banner disappeared.++**Fix**: Add a `SyncMetadataDao` query:+```kotlin+@Query("SELECT * FROM sync_metadata WHERE sequential_failure_count >= :threshold")+fun getUnhealthyProviders(threshold: Int = 5): Flow<List<SyncMetadataEntity>>+```++Display a persistent banner or badge in Settings when any provider exceeds the failure threshold, linking to the provider's sync history.++---++## Risk Matrix Summary++| ID | Severity | Area | Issue |+|---|---|---|---|+| DB-C-01 | 🔴 HIGH | Correctness | EPG double GZIP decompression |+| DB-C-02 | 🔴 HIGH | Correctness | Watch-progress denormalization divergence |+| DB-C-03 | 🔴 HIGH | Correctness | Provider cleanup race in `onProviderDeleted` |+| DB-ASYNC-02 | 🔴 HIGH | Threading | Background EPG job map registration race |+| DB-Q-01 | 🔴 HIGH | Query | CatalogSyncDao N×columns correlated-subquery UPDATE |+| DB-Q-02 | 🔴 HIGH | Query | Correlated subquery ORDER BY for watch-count sort |+| DB-CACHE-01 | 🔴 HIGH | Cache | Thundering-herd flush in AdultContentClassifier |+| DB-PERF-01 | 🔴 HIGH | Performance | VACUUM triggered via side-effecting TRUNCATE checkpoint |+| DB-C-04 | 🟡 MEDIUM | Correctness | Clock-skew stale cache (negative elapsed) |+| DB-C-05 | 🟡 MEDIUM | Correctness | Unbounded `providerRefreshMutexes` after provider delete |+| DB-C-06 | 🟡 MEDIUM | Correctness | FTS query injection surface |+| DB-Q-03 | 🟡 MEDIUM | Query | Correlated subquery sort — category-scoped |+| DB-Q-04 | 🟡 MEDIUM | Query | `getNowPlaying` captures stale timestamp |+| DB-Q-05 | 🟡 MEDIUM | Query | Favorites `IS NULL` predicate reduces index efficiency |+| DB-CACHE-02 | FIXED (2026-04-17) | Cache | Partial sync updates TTL; stale catalog treated as fresh |+| DB-CACHE-03 | 🟡 MEDIUM | Cache | DataStore incognito read blocks per playback event |+| DB-PERF-02 | FIXED (2026-04-18) | Performance | EPG staging inserts in 100 separate implicit transactions |+| DB-PERF-03 | 🟡 MEDIUM | Performance | 24h program pruning destroys catch-up TV guide |+| DB-SCALE-01 | FIXED (2026-04-18) | Scalability | Large multi-channel EPG reads now use snapshot queries instead of chunked reactive `combine()` |+| DB-RES-01 | FIXED (2026-04-18) | Resilience | Durable periodic provider sync via WorkManager |+| DB-RES-02 | FIXED (2026-04-17) | Resilience | Migrations lack `PRAGMA foreign_key_check` |+| DB-OBS-01 | FIXED (2026-04-18) | Observability | Debug slow-query logging added via wrapped SQLite open helper |+| DB-OBS-02 | FIXED (2026-04-18) | Observability | Maintenance report persisted to DataStore and surfaced in Settings |+| DB-CACHE-04 | 🟢 LOW | Cache | EPG size cap: partial protection on chunked transfer |+| DB-PERF-04 | 🟢 LOW | Performance | `clearAllHistory` runs correlated sync over emptied history |+| DB-SCALE-02 | FIXED (2026-04-18) | Scalability | Favorites reorder now uses sparse positions and localized updates |+| DB-SCALE-03 | FIXED (2026-04-18) | Scalability | Background EPG now uses unique durable WorkManager jobs |+| DB-SCH-01 | FIXED (2026-04-18) | Schema | Orphan protection on re-mapped category IDs |+| DB-SCH-02 | FIXED (2026-04-18) | Schema | Verified current sync fingerprints already use full SHA-256 hex digests |+| DB-SCH-03 | FIXED (2026-04-17) | Schema | Missing `programs.end_time` composite index |+| DB-SCH-04 | FIXED (verified 2026-04-18) | Schema | Verified migration already falls back when no provider is active |+| DB-RES-03 | FIXED (2026-04-18) | Resilience | Session IDs use wall-clock ms — clock adjustment collision |+| DB-RES-04 | FIXED (2026-04-18) | Resilience | `ChannelDao.replaceAll` interface `@Transaction` reliability |+| DB-ASYNC-03 | FIXED (2026-04-18) | Threading | `collectStorageStats()` dispatcher dependency implicit |+| DB-OBS-03 | FIXED (2026-04-18) | Observability | Provider sync health streaks and warning signals surfaced in Settings |++---++## Recommended Prioritization++**Sprint 1 — Data Safety (🔴 HIGH items)**+1. DB-C-01: Fix EPG double-decompression guard in `EpgRepositoryImpl`+2. DB-C-02: Align `getUnwatchedByProviderPage` to authoritative `playback_history`; add `resetAllWatchProgress()` for history clear+3. DB-C-03: Move `providerSyncMutexes.remove()` inside the `withProviderLock` block+4. DB-ASYNC-02: Fix background EPG job registration race with `synchronized`+5. DB-PERF-01: Replace `wal_checkpoint(TRUNCATE)` with `PASSIVE` + separate `FULL` before VACUUM+6. DB-Q-01: Replace multi-subquery catalog UPDATE with Kotlin-side diff + batch `@Update`++**Sprint 2 — Query Performance and Cache Correctness (🟡 MEDIUM)**+7. DB-Q-02/03: Denormalize `watch_count` into `MovieEntity`+8. DB-CACHE-01: Replace `AdultContentClassifier` clear-flush with LRU eviction+9. DB-CACHE-02: Fixed 2026-04-17 by separating success freshness from attempted sync timestamps+10. DB-CACHE-03: Cache incognito state in a `StateFlow` for zero-suspension access+11. DB-PERF-03: Compute program retention from `MAX(catch_up_days)` instead of fixed 24h+12. DB-RES-02: Fixed 2026-04-17 by adding FK integrity checks to table-restructuring migrations+13. DB-PERF-02: Fixed 2026-04-18 by wrapping streamed EPG staging inserts in one explicit transaction++**Sprint 3 — Resilience and Observability (🟡 MEDIUM + 🟢 LOW)**+15. DB-OBS-01: Fixed 2026-04-18 by adding debug slow-query logging through a wrapped SQLite open helper+16. DB-OBS-02: Fixed 2026-04-18 by persisting maintenance reports to DataStore and surfacing them in Settings diagnostics+17. DB-ASYNC-01: Fixed 2026-04-18 by adding an atomic sync-admission gate around VACUUM+18. DB-RES-03: Fixed 2026-04-18 by removing wall-clock-derived staging session IDs+19. DB-SCH-01: Fixed 2026-04-18 by invalidating inherited parental protection on re-mapped categories+20. DB-RES-04: Fixed 2026-04-18 by converting `ChannelDao` to an abstract Room DAO+21. DB-ASYNC-03: Fixed 2026-04-18 by making maintenance DB access explicitly worker-thread-only+22. DB-SCALE-02: Fixed 2026-04-18 by preserving sparse favorite positions through reorder save paths+23. DB-SCALE-03: Fixed 2026-04-18 by moving background EPG refresh onto durable WorkManager jobs+24. DB-SCH-02: Verified fixed 2026-04-18 because sync fingerprints already use full SHA-256 digests+25. DB-SCH-04: Verified fixed 2026-04-18 with migration fallback and regression coverage for zero active providers+26. Remaining LOW items per team velocity++---++## 10. Missing Features & Enhancement Opportunities++These are capabilities that are entirely absent — not bugs in what exists, but gaps in the data/cache contract that will constrain future UI or reliability work.++---++### DB-ENH-01 · FTS4 → FTS5: richer search ranking and multi-field indexing++**Current state**: All three search virtual tables (`channels_fts`, `movies_fts`, `series_fts`) use FTS4 with only `name` indexed.++**What's missing**:+- **Search relevance ranking**: FTS4 has no built-in relevance score. The layer sorts results by `name ASC` after matching, so "Matrix" ranks "The Matrix Reloaded" ahead of "The Matrix" despite the exact match. FTS5 exposes a `rank` column powered by BM25 that Room can sort by directly.+- **Multi-column search**: `plot`, `cast`, `director`, and `genre` are stored in `MovieEntity` but unindexed for FTS. Users can't search "Spielberg" to find his films or search by genre keyword.+- **Prefix optimization**: FTS4 prefix queries (`term*`) perform full-table scans on the FTS shadow tables. FTS5 uses a B-tree prefix index that scales with catalog size.++**Migration path**:+```kotlin+// Room schema: replace @Fts4 with @Fts5+@Fts5(contentEntity = MovieEntity::class)+@Entity(tableName = "movies_fts")+data class MovieFtsEntity(+ val name: String,+ val plot: String?,+ val cast: String?,+ val director: String?,+ val genre: String?+)++// Query with ranking:+@Query("""+ SELECT m.* FROM movies m+ JOIN movies_fts ON m.id = movies_fts.rowid+ WHERE m.provider_id = :providerId AND movies_fts MATCH :query+ ORDER BY movies_fts.rank -- BM25 score, best match first+ LIMIT :limit+""")+fun search(providerId: Long, query: String, limit: Int): Flow<List<MovieBrowseEntity>>+```++FTS4 → FTS5 content tables require a rebuild migration (`INSERT INTO movies_fts(movies_fts) VALUES('rebuild')`), which can run in the background after the migration completes.++---++### DB-ENH-02 ? FIXED (2026-04-18) ? Offset pagination ? keyset/cursor pagination for large catalogs++**Current state**: Every paginated DAO query uses `LIMIT :limit OFFSET :offset`.++**What's missing**: Offset pagination is correct for static data but drifts on live datasets. During a catalog sync, new channels are inserted and stale ones deleted. A user paging through 10,000 channels while a sync runs may skip items (if deletions shift rows before the current page) or see duplicates (if insertions push rows into an already-visited page). The drift is silent — no error, just missing content.++Additionally, `OFFSET n` scans and discards the first `n` rows internally. For page 200 of a 50,000-channel catalog (`OFFSET 5000`), SQLite reads 5,000 rows before returning 25.++**Enhancement**: Migrate hot-path paginated queries to keyset pagination using the last-seen sort key:+```sql+-- Instead of: ORDER BY number ASC LIMIT 25 OFFSET :offset+-- Use:+WHERE provider_id = :providerId AND number > :lastSeenNumber+ORDER BY number ASC LIMIT 25+```++This is O(log n) via the index regardless of page depth and is drift-stable. Integrate with Paging 3's `PagingSource` at the repository boundary.++---++### DB-ENH-03 ? FIXED (2026-04-18) ? Cross-provider content identity via shared TMDB namespace++**Current state**: `MovieEntity.tmdbId` and `SeriesEntity.tmdbId` are stored per provider but never joined across providers. Two providers carrying the same movie create two independent `MovieEntity` rows with separate favorites, separate watch progress, and separate history entries.++**What's missing**: If the user watches 40 minutes of a movie on Provider A and switches to Provider B which has better stream quality for the same title, the resume position from Provider A is invisible. Favorites don't cross-reference either.++**Enhancement**: Add a `tmdb_identity` table:+```sql+CREATE TABLE tmdb_identity (+ tmdb_id INTEGER NOT NULL,+ content_type TEXT NOT NULL, -- 'MOVIE' or 'SERIES'+ canonical_provider_id INTEGER NOT NULL,+ first_seen_at INTEGER NOT NULL,+ PRIMARY KEY (tmdb_id, content_type)+)+```++A `SharedWatchProgressRepository` queries `playback_history JOIN movies ON movies.id = content_id JOIN movies ON movies.tmdb_id = :tmdbId` across providers, returning the most recent progress regardless of which provider delivered the stream. This enables:+- **Cross-provider resume** (continue watching on best-quality provider)+- **Unified favorites** (favorite "the movie" not "movie on provider X")+- **Deduplication in continue-watching** (already done per-provider, but would work globally)++---++### DB-ENH-04 � FIXED (2026-04-18) � Playback progress write batching / debounce buffer++**Current state**: Resume-position updates were previously written through to Room on every player checkpoint interval.++**Status**: Fixed in PlaybackHistoryRepositoryImpl. Resume-position updates are now buffered in memory and flushed on a 30-second interval, while explicit stop paths such as recordPlayback() and markAsWatched() consume the pending buffered state and persist a single consolidated write.++**What's missing**: A write buffer for in-flight progress. For a 2-hour movie, this is 720 individual database write transactions. The denormalized sync (`movies.watch_progress`) is updated 720 times even though the UI reads it only when a new screen is displayed.++**Enhancement**: Buffer progress writes in memory and flush to the database on a 30-second interval (or on pause/stop/destruction whichever comes first):++```kotlin+// In PlaybackHistoryRepositoryImpl or a dedicated PlaybackProgressBuffer:+private val pendingUpdates = ConcurrentHashMap<Triple<Long, ContentType, Long>, PlaybackHistory>()+private val flushJob = applicationScope.launch {+ while (isActive) {+ delay(FLUSH_INTERVAL_MS)+ flushPendingUpdates()+ }+}++override suspend fun updateResumePosition(history: PlaybackHistory): Result<Unit> {+ if (isIncognito.value) return Result.success(Unit)+ pendingUpdates[Triple(history.contentId, history.contentType, history.providerId)] = history+ return Result.success(Unit) // write to DB happens on next flush+}+```++Force-flush on `recordPlayback()` and `markAsWatched()` to guarantee persistence on explicit stop. This reduces write transactions from ~720 to ~12 for a 2-hour session.++---++### DB-ENH-05 � FIXED (2026-04-18) � Provider row budget / catalog size enforcement++**Current state**: Catalog staging previously accepted every distinct live/movie/series row for a provider with no upper bound.++**Status**: Fixed in CatalogSizeLimits and SyncCatalogStore. Live, movie, and series catalog staging now enforce per-provider row budgets before commit, keeping the lowest-numbered live channels and the highest-rated VOD items when the feed exceeds configured limits.++**Enhancement**: Add to `ContentCachePolicy` or a new `CatalogSizeLimits` object:+```kotlin+object CatalogSizeLimits {+ const val MAX_CHANNELS_PER_PROVIDER = 100_000+ const val MAX_MOVIES_PER_PROVIDER = 200_000+ const val MAX_SERIES_PER_PROVIDER = 100_000+ const val MAX_PROGRAMS_PER_PROVIDER = 5_000_000 // 500 channels × 10 days × 1000 programs+}+```++In `SyncCatalogStore.applyChannelStage()`, count staged rows before the commit and emit a `SyncState.Partial` warning if the limit is exceeded, truncating to the budget sorted by `number ASC` (live) or `rating DESC` (VOD) to preserve quality.++---++### DB-ENH-06 � VERIFIED (2026-04-18) � Incremental series sync using last_modified++**Current state**: The current series path no longer does per-series `series_info` hydration during catalog sync.++**Status**: Verified no longer applicable as originally written. Series catalog sync stages list data, while detailed `get_series_info` hydration happens on demand in SeriesRepositoryImpl when opening series details instead of during the sync pass.++**Enhancement**: In `SyncManagerXtreamSeriesStrategy`, before queuing an episode hydration request, compare the remote `lastModified` against the locally stored field:++```kotlin+val needsHydration = remoteSeries.lastModified > (localSeries?.lastModified ?: 0L)+ || localSeries == null+ || episodeDao.getCountForSeries(localSeries.id) == 0+```++For a provider with 5,000 series where 95% haven't changed since last sync, this drops from 5,000 API calls to ~250. This would also reduce the window where a partial sync leaves the series catalog in an inconsistent state.++---++### DB-ENH-07 � FIXED (2026-04-18) � EPG channel match quality tracking and re-match scheduling++**Current state**: `ChannelEpgMappingEntity` now tracks `matchedAt`, `failedAttempts`, and `source`, `ChannelEpgMappingDao` exposes rematch candidate queries, and `EpgResolutionSummary` surfaces low-confidence/rematch counts.+**Status**: Fixed in `ChannelEpgMappingEntity`/`ChannelEpgMappingDao`, `EpgResolutionEngine`, the 35->36 migration, and the Settings EPG provider card. Low-confidence/provider-native mappings are now counted, unresolved channels accumulate bounded failed-attempt metadata, and the provider Settings summary now shows weak/no-EPG coverage that needs review. Existing assign/refresh flows already trigger a fresh resolution pass when sources are added or refreshed.++**What's missing**:+- A `matchAttemptedAt` timestamp to know when the match was last tried+- A `failedAttempts` counter to gradually reduce retry frequency for unresolvable channels+- A DAO query to surface channels with no mapping or confidence below a threshold++**Enhancement**:+```kotlin+// ChannelEpgMappingEntity additions:+@ColumnInfo(name = "matched_at") val matchedAt: Long = 0L,+@ColumnInfo(name = "failed_attempts") val failedAttempts: Int = 0,+@ColumnInfo(name = "source") val source: String? = null // "name_match", "tvg_id", "override"++// ChannelEpgMappingDao:+@Query("""+ SELECT * FROM channel_epg_mapping+ WHERE provider_id = :providerId+ AND (confidence < :minConfidence OR mapping_id IS NULL)+ AND failed_attempts < :maxAttempts+ ORDER BY confidence ASC, channel_name ASC+ LIMIT :limit+""")+suspend fun getChannelsNeedingRematch(providerId: Long, minConfidence: Float, maxAttempts: Int, limit: Int): List<ChannelEpgMappingEntity>+```++Surface a "N channels have no EPG" count in the provider settings card and trigger a background re-match pass when new EPG sources are added.++---++### DB-ENH-08 � FIXED (2026-04-18) � Program reminder table (lightweight alternative to recording schedule)++**Current state**: The app now has a dedicated `program_reminders` table plus alarm-backed reminder delivery for future guide entries.+**Status**: Fixed in `ProgramReminderEntity`/`ProgramReminderDao`, `ProgramReminderManagerImpl`, the new reminder alarm/restore receivers, and the EPG program dialog. Users can now set or cancel a reminder from the guide, reminders survive reboot/app update via restore scheduling, fire a notification shortly before airtime, and are pruned during daily maintenance once they are stale.++**What's missing**: Many users want to be reminded to watch a live event without committing to a recording (e.g., no storage configured, or they prefer live viewing). The data model has no facility for this.++**Enhancement**: Add a `program_reminders` table:+```sql+CREATE TABLE program_reminders (+ id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,+ provider_id INTEGER NOT NULL,+ channel_id TEXT NOT NULL,+ program_title TEXT NOT NULL,+ program_start_time INTEGER NOT NULL,+ remind_at INTEGER NOT NULL, -- start_time minus user's lead time preference+ lead_time_minutes INTEGER NOT NULL DEFAULT 5,+ is_dismissed INTEGER NOT NULL DEFAULT 0,+ created_at INTEGER NOT NULL,+ FOREIGN KEY(provider_id) REFERENCES providers(id) ON DELETE CASCADE+)+```++`SyncWorker` can check for due reminders on each maintenance run and enqueue a `NotificationWorker` for each undismissed reminder within the next maintenance window. When EPG refresh reloads programs, a reconciliation step can update or cancel reminders for programs whose times shifted.++---++### DB-ENH-09 � FIXED (2026-04-18) � Recent search queries: per-content-type, timestamped, in Room not DataStore++**Current state**: Recent search queries previously lived in DataStore as one shared pipe-delimited string with no timestamp metadata.+**Status**: Fixed in SearchHistoryEntity/SearchHistoryDao, PreferencesRepository, SearchViewModel, and DatabaseMaintenanceManager. Recent searches now live in Room with per-tab scoping, timestamped ordering, provider-aware lookup keys, and 90-day pruning during maintenance.++**What's missing**:+- Content-type scoping (searches in the movie section shouldn't pre-fill in the live channel search)+- Timestamp for sorting suggestions "most recently used first" rather than list-insertion order+- Survivable across DataStore corruption (DataStore uses a protobuf file; a corrupt file loses all preferences including search history)+- Ability to query "top 5 searches for this provider" for recommendation seeding++**Enhancement**: Move recent searches to a Room table:+```sql+CREATE TABLE search_history (+ id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,+ query TEXT NOT NULL,+ content_type TEXT NOT NULL, -- 'LIVE', 'MOVIE', 'SERIES', 'EPG'+ provider_id INTEGER, -- NULL = global+ used_at INTEGER NOT NULL,+ use_count INTEGER NOT NULL DEFAULT 1,+ UNIQUE(query, content_type, provider_id)+)+CREATE INDEX idx_search_history_type_time ON search_history(content_type, used_at DESC)+```++`DatabaseMaintenanceManager` prunes entries older than 90 days. The top-k queries per content type become a cheap indexed lookup.++---++### DB-ENH-10 · HTTP-level OkHttp disk cache for EPG and Xtream API responses++**Current state**: The OkHttp client used for EPG downloads and Xtream catalog fetches has no disk cache configured. Every sync re-downloads the full response even if the server offers `Cache-Control` or `ETag` headers.++**Status**: Fixed in `NetworkModule.provideOkHttpClient()`. The shared OkHttp client now uses a 256 MB disk cache rooted in `context.cacheDir/streamvault_http_cache`, so both Xtream API calls and EPG downloads can reuse server-provided cache headers instead of always re-downloading full payloads.++**What's missing**: Many XMLTV EPG sources serve stable files with `Cache-Control: max-age=3600` or `ETag` for conditional GET. Without an HTTP cache, the layer ignores these signals entirely and relies solely on its own TTL logic (ContentCachePolicy), which is not server-aware.++**Enhancement**: Configure an OkHttp `Cache` for EPG fetches:+```kotlin+// In DataModule / NetworkModule:+val epgCache = Cache(+ directory = File(context.cacheDir, "epg_http_cache"),+ maxSize = 256L * 1024 * 1024 // 256 MB+)+val epgOkHttpClient = baseClient.newBuilder()+ .cache(epgCache)+ .build()+```++For Xtream API calls (catalog endpoints), a separate smaller cache with a short `max-stale` directive allows serving the last category list if the provider is temporarily unavailable, preventing a sync failure from wiping displayed content.++Note: the EPG URL must not be called with `Accept-Encoding: identity` when using OkHttp's cache, as the cache layer handles transparent decompression. This also resolves DB-C-01 (double GZIP) for cache-served responses.++---++### DB-ENH-11 · Table-level row count metrics in maintenance report++**Current state**: `MaintenanceReport` records deleted rows and storage stats (page size, freelist, WAL size) but not the total current row count per table. The only way to know "how many channels does provider X have" is to run a separate `SELECT COUNT(*)`.++**Status**: Fixed in `DatabaseMaintenanceManager`, `SyncWorker`, and the Settings diagnostics UI. Daily maintenance now collects per-table row counts, persists them through the existing maintenance snapshot in DataStore, and surfaces them in the "Database Health" card alongside cleanup counts and storage metrics.++**What's missing**: Row count drift tracking across maintenance cycles. If `channels` grows by 10% between syncs (a misconfigured provider keeps appending duplicates via a bug in the staging logic), there's no signal.++**Enhancement**: Add a `tableStats` field to `MaintenanceReport`:+```kotlin+data class TableRowStats(+ val channels: Long,+ val movies: Long,+ val series: Long,+ val episodes: Long,+ val programs: Long,+ val epgProgrammes: Long,+ val playbackHistory: Long,+ val favorites: Long+)+```++Collect via `SELECT COUNT(*) FROM table` inside `runDailyMaintenance()`. Persist in DataStore alongside the existing maintenance metadata. Alert (via the Settings diagnostics card from DB-OBS-02) when any single table exceeds its expected row budget (DB-ENH-05).++---++### Missing Features Summary++| ID | Category | Feature |+|---|---|---|+| DB-ENH-01 | Search | FTS4 → FTS5: BM25 ranking, multi-field indexing (cast/director/genre) |+| DB-ENH-02 | FIXED (2026-04-18) | Movie/series hot-path library browse now steps through keyset pages in the repository instead of deep OFFSET scans |+| DB-ENH-03 | FIXED (2026-04-18) | Added tmdb_identity plus cross-provider movie/series resume fallback via shared TMDB matches |+| DB-ENH-04 | FIXED (2026-04-18) | Playback progress write buffer / 30-second flush debounce |+| DB-ENH-05 | FIXED (2026-04-18) | Per-provider row budget enforcement at staging layer |+| DB-ENH-06 | VERIFIED (2026-04-18) | Current series sync no longer performs per-series detail hydration during catalog sync |+| DB-ENH-07 | FIXED (2026-04-18) | Channel EPG match quality tracking, rematch metadata, and Settings coverage surface |+| DB-ENH-08 | FIXED (2026-04-18) | Program reminders with alarm-backed notifications from the guide |+| DB-ENH-09 | FIXED (2026-04-18) | Per-content-type, timestamped search history in Room (not DataStore string) |+| DB-ENH-10 | FIXED (2026-04-18) | OkHttp disk cache for EPG and Xtream API (respect server Cache-Control/ETag) |+| DB-ENH-11 | FIXED (2026-04-18) | Per-table row count tracking in maintenance report |+++diff --git a/docs/epg-code-review.md b/docs/epg-code-review.mdnew file mode 100644index 00000000..117825c0--- /dev/null+++ b/docs/epg-code-review.md@@ -0,0 +1,649 @@+# EPG System — Production Code Review++**Scope**: `XmltvParser`, `EpgRepositoryImpl`, `EpgSourceRepositoryImpl`, `EpgResolutionEngine`, `EpgNameNormalizer`, `EpgViewModel`, `EpgGridComponents`, domain models (`Program`, `EpgModels`).++**Date**: April 2026++---++## Summary++The EPG system has a well-thought-out multi-source architecture and already incorporates+several good practices (streaming XmlPullParser, per-provider mutexes, staging area in+`EpgRepositoryImpl.refreshEpg`, gzip decompression with size cap). However, several+correctness bugs, a data-loss scenario, and observable performance gaps exist in production.++Issues are grouped by severity.++---++## CRITICAL++---++### C-2 · `refreshSourceInternal` deletes EPG data before new data is committed — data loss on failure++**File**: `EpgSourceRepositoryImpl.kt` (~line 269)++**Problem**:+```kotlin+epgChannelDao.deleteBySource(sourceId) // old data gone+epgProgrammeDao.deleteBySource(sourceId) // old data gone+// … parse from network …+// If an exception is thrown here:+} catch (e: Exception) {+ epgSourceDao.updateRefreshStatus(sourceId, now, e.message)+ Result.error(...) // no restore — source is now permanently empty+}+```++The two deletes are not in a transaction and no staging area is used. A parse failure,+OOM, network drop, or process kill between the delete and insert leaves the EPG source+with zero channels and zero programmes permanently. The user's guide is blank until+a successful full refresh.++`EpgRepositoryImpl.refreshEpg` already solves this with a negative-providerId staging+area. Use the same pattern here.++**Fix**: stage all inserts under a temporary source row with id `= -sourceId`, then+swap atomically:++```kotlin+val stagingId = -sourceId+epgProgrammeDao.deleteBySource(stagingId)+epgChannelDao.deleteBySource(stagingId)+// … write to stagingId …+transactionRunner.inTransaction {+ epgChannelDao.deleteBySource(sourceId)+ epgProgrammeDao.deleteBySource(sourceId)+ epgChannelDao.moveToSource(stagingId, sourceId)+ epgProgrammeDao.moveToSource(stagingId, sourceId)+}+```++Add `deleteBySource(stagingId)` to the catch block to clean up the staging rows on+failure.++---++### C-4 · Local-time XMLTV timestamps without timezone offset are silently treated as UTC++**File**: `XmltvParser.kt` — `parseLocalDateTime` and the "last resort" path++**Problem**:+Many real-world XMLTV providers emit local-time timestamps without timezone offsets:+```+<programme start="20250101200000" stop="20250101210000" channel="bbc1">+```+The XMLTV spec says these are local (provider) time, not UTC. `parseLocalDateTime`+passes them through `ZoneOffset.UTC`, shifting them by the provider's timezone — up+to ±14 hours. A programme broadcast at 20:00 local (+05:00) appears in the guide at+01:00 the next day.++Worse, the "last resort" digit-strip path drops any timezone suffix before the UTC+assumption:+```kotlin+val cleaned = dateStr.replace("""[^\d]""".toRegex(), "")+// "20250101120000 +0500" → "202501011200000500" → substring(0,14) = "20250101120000"+// tz offset is silently discarded, UTC assumed+```++**Fixes**:+1. Expose a `defaultOffset: ZoneOffset` parameter on `XmltvParser` (defaulting to+ `ZoneOffset.UTC` for backward compat). EPG source settings can optionally carry a+ per-source timezone string that the caller converts to a `ZoneOffset` at parse time.+2. In the last-resort path, try parsing the trailing digits as an offset before+ discarding them:+ ```kotlin+ // If length ≥ 19 and last 5 chars match [+-]\d{4}, parse as offset-aware+ ```++---++## HIGH++---++### H-2 · SQL LIKE wildcards in program search are not escaped — logical bypass++**File**: `EpgRepositoryImpl.kt` — `searchPrograms`++**Problem**:+```kotlin+val normalizedQuery = query.trim() // NOT run through EpgNameNormalizer+return programDao.searchPrograms(+ queryPattern = "%$normalizedQuery%", // user input directly interpolated into LIKE pattern+ ...+)+```+Searching for `%` produces `WHERE title LIKE '%%'` which matches every title, ignoring+the 2-character minimum guard. Searching for `%a%` returns exactly the same as `a`.+SQLite wildcard `_` matches any single character.++**Fix** — escape reserved LIKE characters before building the pattern:+```kotlin+fun String.escapeSqlLike(escape: Char = '\\'): String =+ this.replace("$escape", "$escape$escape")+ .replace("%", "$escape%")+ .replace("_", "$escape_")++val escaped = normalizedQuery.escapeSqlLike()+queryPattern = "%$escaped%",+// Also update the DAO @Query to use ESCAPE '\'+```++---++### H-3 · `refreshSourceInternal` deletes before inserting — empty guide window for users++Even absent a failure (C-2), the gap between:+```kotlin+epgChannelDao.deleteBySource(sourceId)+epgProgrammeDao.deleteBySource(sourceId)+// ← any read here sees zero EPG data+// ... network download + parse (can take minutes) ...+// inserts happen+```+means that any guide read during the refresh sees an empty schedule. On large feeds+(>10 MB), the parse can take 30–120 seconds. The staging-area pattern (see C-2) also+closes this availability gap.++---++### H-4 · `exactIdIndex` in `EpgResolutionEngine` maps each ID to itself — silent mismatch risk++**File**: `EpgResolutionEngine.kt`++**Problem**:+```kotlin+exactIdIndex[sourceId] = epgChannels.associate { it.xmltvChannelId to it.xmltvChannelId }+```+The map value is identical to its key. The lookup result (`channelEpgId in index`) is+only used for existence checking:+```kotlin+if (channelEpgId != null && channelEpgId in index) { ... }+```+The value side (`index[channelEpgId]`) is never used, so the map could be a `Set`.+More importantly, `channelEpgId` is compared against `xmltvChannelId` raw — no+normalization, no case-folding, no whitespace trimming. An XMLTV file that stores+`" bbc1.uk "` (with spaces) would not match a channel with `tvg-id="bbc1.uk"`. Some+XMLTV providers pad their IDs with extra spaces or use different casing.++**Fix**: normalize both sides of the exact-ID lookup (at least `trim()` on both), and+use a `Set<String>` for the existence index:+```kotlin+exactIdIndex[sourceId] = epgChannels.map { it.xmltvChannelId.trim() }.toHashSet()+// lookup:+if (channelEpgId != null && (channelEpgId.trim() in exactIdIndex[sid] ?: emptySet()))+```++---++### H-5 · `getNowAndNext` "next" program selection skips over gaps incorrectly++**File**: `EpgRepositoryImpl.kt`++**Problem**:+```kotlin+val current = programs.find { it.startTime <= now && it.endTime > now }+val next = programs.find { it.startTime > now }+```+`next` is found independently: the first program whose `startTime > now`. If `current`+is null (gap in schedule) and two future programs exist, `next` picks the nearer one —+that is correct. But if `current` is non-null and there are overlapping programs (a+common provider data quality issue), `next` could return a program whose `startTime`+falls *within* the current window, making both `current` and `next` appear to run at+the same time.++**Fix**: pick `next` relative to `current`:+```kotlin+val current = programs.find { it.startTime <= now && it.endTime > now }+val nextStart = current?.endTime ?: now+val next = programs.firstOrNull { it.startTime >= nextStart && it != current }+```++---++## MEDIUM++---++### M-1 · `refreshSource` marks `lastRefreshAt` at start of download, not success++**File**: `EpgSourceRepositoryImpl.kt`++```kotlin+epgSourceDao.updateRefreshStatus(sourceId, now, null) // called BEFORE download+```++`lastRefreshAt` is set to the start of the attempt. If the download takes 2 minutes+and fails, the UI displays "Last refreshed: 2 minutes ago" with an error badge — which+reads as contradictory. `lastRefreshAt` should only be updated on success alongside+`lastSuccessAt`:++```kotlin+// Remove upfront call; on success:+epgSourceDao.updateRefreshSuccess(sourceId, System.currentTimeMillis())+// On failure, only update the error field:+epgSourceDao.updateRefreshError(sourceId, e.message ?: "Unknown error")+```++---++### M-2 · `getOverrideCandidates` loads all EPG channels into heap memory++**File**: `EpgSourceRepositoryImpl.kt`++```kotlin+epgChannelDao.getBySource(assignment.epgSourceId) // returns List<EpgChannelEntity>+ .asSequence()+ .filter { ... }+```++For a source with 50 000 channels (common for large multi-country XMLTV feeds),+`getBySource` returns all rows. With 3–4 enabled sources, this can allocate 10–20 MB+of object heap per override search.++**Fix**: move the filter to the DAO with a Room `@Query` using `LIKE` on both+`xmltvChannelId` and `displayName`, and use a `LIMIT` clause:+```kotlin+@Query("""SELECT * FROM epg_channels+ WHERE epg_source_id = :sourceId+ AND (xmltv_channel_id LIKE :pattern OR display_name LIKE :pattern)+ LIMIT :limit""")+suspend fun searchBySource(sourceId: Long, pattern: String, limit: Int): List<EpgChannelEntity>+```++---++### M-3 · Program search has no debounce — expensive recomposition per keystroke++**File**: `EpgViewModel.kt` — `observeGuidePresentation`++Every character typed in the guide search bar triggers `buildGuideDisplaySnapshot` on+`Dispatchers.Default`. With 5 000+ programs in memory, this is a CPU-heavy map/filter+over the full dataset with no delay:++```kotlin+} .collectLatest { presentation ->+ // called on every keystroke+ val displaySnapshot = withContext(Dispatchers.Default) {+ buildGuideDisplaySnapshot(...) // expensive+ }+```++**Fix**: add a flow debounce of 150–200 ms on `programSearchQuery` before it reaches+the combine:+```kotlin+programSearchQuery.debounce(150L)+```++---++### M-4 · EpgResolutionEngine — name match confidence 0.7 is too aggressive for partial matches++**File**: `EpgResolutionEngine.kt`++`EpgNameNormalizer.normalize` removes *all* non-alphanumeric characters:+- `"BBC ONE"` → `"bbcone"`+- `"BBC ONE HD"` → `"bbconehd"`+- `"BBC ONE+1"` → `"bbcone1"`++Only `"BBC ONE"` (normalized: `"bbcone"`) would match `"bbcone"` exactly, while the+HD/+1 variants won't. That is actually reasonable. The risk is that two *different*+channels collide after normalization (e.g., `"TV5"` and `"TV 5"`). Confidence of 0.7+should be acceptable but the resolution engine should log per-channel collisions for+debugging (see M-6).++---++### M-5 · `assignSourceToProvider` / `resolveAffectedProviders` always pass empty `hiddenLiveCategoryIds`++**File**: `EpgSourceRepositoryImpl.kt`++All internal resolution calls use `resolveForProvider(providerId, emptySet())`. The+hidden-category set comes from user preferences and is only available at the ViewModel+layer. Resolution runs without it, so channels in hidden categories get EPG mappings+that will never be used — wasted work, and the mapping table grows with stale noise.+In practice this is harmless but contributes to resolution summary counts that+misrepresent match quality.++No fix required for correctness, but consider making the ViewModel trigger resolution+through a use case that injects the hidden-category set from preferences.++---++### M-6 · No per-channel EPG resolution failure logging++**File**: `EpgResolutionEngine.kt`++The only observability into mapping quality is a single summary line:+```kotlin+Log.d(TAG, "Resolution for provider $providerId: $summary")+```++When a user reports "Channel X has no guide data", there is no log to distinguish:+- Channel has `epgChannelId = null`+- Channel has an ID but no EPG source is assigned+- Channel ID exists in source but has zero programmes for today+- Name normalization matched the wrong channel++**Fix**: log (at `VERBOSE` level) every unresolved channel along with the attempted+normalize key and whether any candidates existed in the name index.++---++### M-7 · `EpgSourceRepositoryImpl` and `EpgRepositoryImpl` both define separate `MAX_EPG_SIZE_BYTES` and `epgHttpClient` — divergence risk++Both files duplicate:+```kotlin+private const val MAX_EPG_SIZE_BYTES = 200L * 1_048_576+private val epgHttpClient: OkHttpClient by lazy { ... }+```++If one is updated (e.g., size cap raised to 500 MB), the other is silently left at+the old value. Extract these into a shared `EpgDownloadConfig` object injected by Hilt.++---++## LOW++---++### L-1 · `nowTicker` creates a fresh coroutine loop per subscriber++**File**: `EpgRepositoryImpl.kt`++Each call to `getNowAndNext` starts a new `while(true) { emit(); delay(60s) }` loop.+With 60 channels on screen, 60 timers fire independently, each potentially issuing a+DB query. Using a `SharedFlow` ticker would reduce this to one timer feeding all+subscribers:++```kotlin+private val nowTicker: Flow<Long> = flow {+ while (true) { emit(System.currentTimeMillis()); delay(NOW_AND_NEXT_REFRESH_INTERVAL_MS) }+}.shareIn(scope, SharingStarted.WhileSubscribed(), replay = 1)+```++---++### L-2 · `jumpToDay` uses UTC epoch modulo for "time of day" — off by timezone for non-UTC users++**File**: `EpgViewModel.kt`++```kotlin+fun jumpToDay(dayStartMillis: Long) {+ val currentTimeOfDay = guideAnchorTime.value.mod(DAY_SHIFT_MS)+ .let { if (it < 0L) it + DAY_SHIFT_MS else it }+ updateGuideAnchorTime(dayStartMillis + currentTimeOfDay)+}+```++`mod(DAY_SHIFT_MS)` gives the UTC time-within-day. If `dayStartMillis` is the UTC+midnight of the selected date but the user is in UTC+8, "current time of day" is+8 hours behind local reality. The compound anchor can land on a time a full `tz-offset`+away from what the user expects. Use `ZonedDateTime` arithmetic (same local-time fix as+`G-06` in `EPG_GRID_CODE_REVIEW.md`).++---++### L-3 · `GuideTimelineHeader` uses `SimpleDateFormat` — not `java.time`++**File**: `EpgGridComponents.kt`++```kotlin+val hourFormat = remember { SimpleDateFormat("HH:mm", Locale.getDefault()) }+```++`SimpleDateFormat` is mutable and not thread-safe. Inside `remember {}` per composition+site it is used from only one thread (composition), so there is no data race, but+`HH:mm` is hardcoded 24-hour which ignores the device's 12/24-hour system setting+(available via `DateFormat.getTimeFormat(context)`). This also applies to `ProgramItem`.++**Fix**: replace with `DateTimeFormatter` or pull the format from the system+`DateFormat.getTimeFormat(context)` so it respects the user's locale setting.++---++### L-4 · `Program.progressPercent` depends on the caller-set `isNowPlaying` flag++**File**: `domain/model/Program.kt`++```kotlin+fun progressPercent(currentTimeMillis: Long = System.currentTimeMillis()): Float {+ if (!isNowPlaying) return 0f+ ...+}+```++`isNowPlaying` is only set by certain code paths (e.g., the streaming path in+`parseStreaming`). Programs produced by the legacy `parse()` method never have it set.+Any UI component that calls `progressPercent()` on a program fetched outside the+now-playing path always gets `0f`, producing a stuck progress bar. The flag is+superfluous — just compute from the timestamps:++```kotlin+fun progressPercent(currentTimeMillis: Long = System.currentTimeMillis()): Float {+ if (endTime <= startTime || currentTimeMillis < startTime || currentTimeMillis >= endTime) return 0f+ return ((currentTimeMillis - startTime).toFloat() / (endTime - startTime)).coerceIn(0f, 1f)+}+```++---++### L-5 · No EPG refresh rate-limiting or back-off++Manual and automatic EPG refresh can be triggered repeatedly via `refresh()` in+`EpgViewModel`. The per-source `Mutex` serializes concurrent calls but does not+prevent rapid sequential calls. An unhappy user rage-clicking "Refresh EPG" can saturate+the CDN endpoint or the device's network. Add a minimum re-refresh interval check+against `EpgSource.lastRefreshAt` (e.g., 5 minutes) before issuing the download.++---++### L-6 · `EpgUiState` initializes anchor times via `System.currentTimeMillis()` at data-class construction++**File**: `EpgViewModel.kt`++```kotlin+data class EpgUiState(+ val guideAnchorTime: Long = System.currentTimeMillis(),+ val guideWindowStart: Long = System.currentTimeMillis() - EpgViewModel.LOOKBACK_MS,+ val guideWindowEnd: Long = System.currentTimeMillis() + EpgViewModel.LOOKAHEAD_MS+)+```++These three `currentTimeMillis()` calls are evaluated at (potentially) different+instants, so `guideWindowStart` and `guideWindowEnd` can disagree with+`guideAnchorTime`. In practice the difference is sub-millisecond, but unit tests may+observe skew. Initialise all three from a single captured `now` constant.++---++## Test Coverage Gaps++| Area | Status | Gap |+|---|---|---|+| `XmltvParser` — timezone handling | Tested (offset + +0300) | No test for no-offset local-time, or the digit-strip last-resort |+| `XmltvParser` — BOM / encoding | Not tested | UTF-16 BOM, ISO-8859-1 encoded real feeds |+| `EpgResolutionEngine` — ID trimming | Not tested | Leading/trailing spaces in `xmltvChannelId` |+| `searchPrograms` LIKE wildcards | Not tested | `%` and `_` in query string |+| `refreshSourceInternal` failure recovery | Not tested | Parse crash after delete — empty state |++---++## Prioritized Fix Plan++| Priority | Issue | Effort |+|---|---|---|+| 🔴 Critical | C-2 — Stage-then-swap for source refresh | M |+| 🔴 Critical | C-4 — Local-time UTC assumption + digit-strip drops tz | M |+| 🟠 High | H-2 — LIKE wildcard escape in search | S |+| 🟠 High | H-3 — Empty guide window during refresh | M (see C-2) |+| 🟠 High | H-4 — ID-index exact match no normalization | S |+| 🟠 High | H-5 — `getNowAndNext` next-program selection | S |+| 🟡 Medium | M-1 — `lastRefreshAt` at start not success | S |+| 🟡 Medium | M-2 — `getOverrideCandidates` in-memory load | M |+| 🟡 Medium | M-3 — No debounce on guide search | S |+| 🟡 Medium | M-6 — Per-channel resolution failure logging | S |+| 🟡 Medium | M-7 — Deduplicate EPG config constants | S |+| 🟢 Low | L-1 through L-6 | S each |++**Effort key**: S = small (< 2 h), M = medium (2–8 h), L = large (> 8 h)++---++## Improvement Opportunities & Missing Features++The items below are not bugs — they are genuine gaps in functionality or architecture+that would materially improve the user experience or system reliability in production.++---++### Technical Capabilities++#### TC-1 · No HTTP conditional requests — full file re-download on every refresh+++Every EPG refresh downloads the full XMLTV file regardless of whether the server's+content has changed. Many CDNs serving EPG files expose `ETag` and `Last-Modified`+headers, making `If-None-Match` / `If-Modified-Since` `304 Not Modified` fast-paths+trivially achievable.++**Suggested approach**: persist the last `ETag` and `Last-Modified` response header+values per `EpgSource` (two nullable `String` columns in `EpgSourceEntity`). On the+next refresh send conditional headers:++```kotlin+val request = Request.Builder()+ .url(source.url)+ .apply { source.etag?.let { header("If-None-Match", it) } }+ .apply { source.lastModified?.let { header("If-Modified-Since", it) } }+ .build()+// HTTP 304 → skip parse, just call epgSourceDao.updateRefreshSuccess(sourceId, now)+```++For large feeds (100+ MB) this is the highest-value performance improvement available+with no architecture changes.++---++#### TC-2 · No per-source configurable refresh interval++All EPG sources share a single app-wide refresh cadence. Some XMLTV providers update+hourly; others update weekly. There is no `refreshIntervalHours` field on `EpgSource`+and no per-source job scheduler — a single global `SyncWorker` handles everything.++**Suggested approach**: add `refreshIntervalHours: Int` to `EpgSource` (default 24).+`SyncWorker` or a dedicated `EpgRefreshWorker` should schedule per-source+`PeriodicWorkRequest` instances keyed by source ID and updated whenever the interval+setting changes.++---++#### TC-3 · EPG `<channel>` icon URL never used as provider channel logo fallback++`EpgChannelEntity.iconUrl` is parsed from XMLTV `<channel><icon src="…"/>` elements+and stored in the database, but it is never consulted when a provider channel has no+logo. For M3U providers that don't include `tvg-logo`, this data is a direct substitute.++**Suggested approach**: in `ChannelRepositoryImpl` (or a new `ChannelIconResolver`),+after resolving the channel's own `logoUrl`, fall back to the mapped+`EpgChannelEntity.iconUrl` when the primary logo is null or empty. No network+round-trips required — the data is already local.++---++#### TC-4 · No horizontal virtualization in the program timeline++The program strip for each row renders *all* `ProgramItem` composables for the full+loaded time window as children of a `Box`, even when only 6–8 are visible. With a+7-day window (336 half-hour slots) and 60 channels, the first render allocates up to+20 160 composable slots.++**Suggested approach**: convert the row's inner `Box` to a `LazyRow`, or use a+single-pass `Canvas` draw approach, so only the programs visible in the horizontal+viewport are composed at any given time.++> Also noted in `EPG_GRID_CODE_REVIEW.md` section 2.1.++---++### Data & Integration Gaps++#### DI-1 · EPG-to-catch-up alignment is not validated++The guide marks programs with `hasArchive = true` based on EPG metadata, but there is+no check that the program's `startTime` falls within the channel's actual rewind window+(typically 7 days from the provider). A program aired 10 days ago with `hasArchive =+true` will silently fail when the user attempts to watch it, producing a generic player+error rather than a predictive guide-level "Replay unavailable" message.++**Suggested approach**: add a `catchUpWindowDays: Int` field to `Channel` (populated+from Xtream `tv_archive_duration` or M3U `catchup-days`). Compute archive eligibility+at display time:+```kotlin+val replayAvailable = program.hasArchive &&+ program.startTime >= now - channel.catchUpWindowDays * 86_400_000L+```++---++#### DI-2 · Combined guide ignores hidden categories++In `observeCombinedGuide`, `hiddenCategoryIds = emptySet()` is hardcoded:++```kotlin+hiddenCategoryIds = emptySet(), // user hidden-category preferences are ignored+```++A user who has hidden adult or regional categories from provider A still sees all their+channels in the combined guide. The fix is to read `PreferencesRepository`+`getHiddenCategoryIds(providerId, ContentType.LIVE)` per-member inside+`observeCombinedGuide` and pass the correct set per provider into the channel filter.++---++#### DI-3 · `providerHasEpg` check is too coarse — generates phantom PROVIDER_NATIVE mappings++In `EpgResolutionEngine`:+```kotlin+val providerHasEpg = programDao.countByProvider(providerId) > 0+```++This returns `true` if *any* programs exist for the provider. Every channel therefore+receives a `PROVIDER_NATIVE` mapping (confidence 0.5) — including channels that have+zero associated programs. These phantom mappings cause the resolution summary to+overcount `providerNativeMatches` and make guide rows show "No schedule" where the+mapping falsely implies EPG coverage exists.++**Fix**: replace the global count with a per-channel check inside the resolution map loop:+```kotlin+// in the channel mapping step, replace step 4 with:+val hasNativeEpg = channelEpgId != null &&+ programDao.countByChannel(providerId, channelEpgId) > 0+if (hasNativeEpg) {+ providerNativeMatches+++ return@map ChannelEpgMappingEntity( ... EpgSourceType.PROVIDER ... )+}+```++---++#### DI-4 · No automatic EPG stale detection at the source level++`isGuideStale` is a ViewModel-level signal computed from whether the current time window+has any usable programs. But an `EpgSource` last refreshed 3 weeks ago shows+`lastError = null` with a 3-week-old `lastSuccessAt` — no TTL or staleness flag warns+the user or the resolution engine before guide reads fail.++**Suggested approach**: add a computed `isStale` check (or a DAO query):+```kotlin+val EpgSource.isStale: Boolean+ get() = System.currentTimeMillis() - lastSuccessAt > refreshIntervalHours * 3_600_000L * 2+```++Surface stale sources with a warning badge in `SettingsEpgSection`. Optionally, the+resolution engine could prefer non-stale sources when multiple candidates match, and+`EpgResolutionSummary` could include a `staleSourceCount` field.+diff --git a/docs/recording-review.md b/docs/recording-review.mdnew file mode 100644index 00000000..f508f317--- /dev/null+++ b/docs/recording-review.md@@ -0,0 +1,682 @@+# Recording System — Comprehensive Review++**Date:** 2026-04-16+**Scope:** All recording-related code across `domain/`, `data/`, `app/` modules++---++## 1. Architecture Overview++The recording stack consists of:++| Layer | Files |+|---|---|+| Domain model | `RecordingModels.kt` (enums, request/item/storage DTOs) |+| Domain interface | `RecordingManager.kt` |+| Domain use case | `ScheduleRecording.kt` |+| Data implementation | `RecordingManagerImpl.kt` |+| Data support | `RecordingSupport.kt`, `RecordingConflictDetector.kt` |+| Capture engines | `RecordingCaptureEngine.kt` (TS + HLS) |+| Scheduling | `RecordingAlarmScheduler.kt`, `RecordingAlarmReceiver.kt` |+| Foreground service | `RecordingForegroundService.kt` |+| Background worker | `RecordingReconcileWorker.kt` |+| Boot restore | `RecordingRestoreReceiver.kt` |+| Source resolver | `RecordingSourceResolver.kt` |+| Persistence | `RecordingEntities.kt`, `RecordingDaos.kt` |+| UI | `SettingsRecordingComponents.kt`, `SettingsRecordingActions.kt` |+| Player wiring | `PlayerViewModelActions.kt`, `ScheduleRecording.kt` use-case |++---++## 2. Critical Bugs++### 2.1 TOCTOU Race on Simultaneous Recording Start++**Files:** `RecordingManagerImpl.kt` — `validateRecordingWindow()`, `startManualRecording()`, `scheduleRecording()`+**Severity:** HIGH++`validateRecordingWindow()` reads overlapping DB rows, checks the count, and returns. The actual `recordingRunDao.insert()` happens afterwards with no mutex or transaction. Two concurrent `startManualRecording` / `scheduleRecording` calls can both pass the window check and both be inserted, potentially exceeding `maxSimultaneousRecordings`.++```kotlin+// validateRecordingWindow() — read-only check+val overlapping = recordingRunDao.getOverlapping(startMs, endMs) ...+if (overlapping.size >= storage.maxSimultaneousRecordings) return "conflict"++// — gap here — no mutex, another call can pass the check simultaneously++recordingRunDao.insert(run) // inserted by two concurrent callers+```++**Fix:** Wrap the validate → insert → schedule-alarm sequence inside a `Mutex` (or a Room `withTransaction` that includes the overlap query).++---++### 2.2 `retryRecording()` Crashes if Schedule Window Has Expired++**File:** `RecordingManagerImpl.kt` — `retryRecording()`+**Severity:** HIGH++`retryRecording` builds a `RecordingRequest` with:++```kotlin+scheduledStartMs = maxOf(System.currentTimeMillis() + 2_000L, schedule.requestedStartMs),+scheduledEndMs = schedule.requestedEndMs // unchanged from original+```++If the original schedule has already passed its end time, `scheduledStartMs > scheduledEndMs` and `RecordingRequest.init` throws `IllegalArgumentException`. The enclosing `withContext` does not use `runCatching`, so the exception propagates uncaught into the caller's coroutine scope (seen in `SettingsRecordingActions.retryRecording`) and crashes the coroutine silently; the UI receives no actionable error message.++**Fix:** Wrap the body of `retryRecording` in `runCatching { ... }.fold(...)` (matching `startManualRecording` / `scheduleRecording`), and add an explicit guard returning an error when `requestedEndMs <= now`.++---++### 2.3 Orphan DB Row Left on `startManualRecording` Capture Failure++**File:** `RecordingManagerImpl.kt` — `startManualRecording()`+**Severity:** MEDIUM++After `recordingRunDao.insert(run)` and `alarmScheduler.scheduleStop(...)` succeed, if `startCapture()` returns `Result.Error`, an `IllegalStateException` is thrown, caught by `runCatching`, and returned as `Result.error`. The row is left in the DB with `status = RECORDING` and no active coroutine job. `reconcileRecordingState()` will attempt to restart it via `RecordingForegroundService.startCapture()` indefinitely, potentially causing repeated useless foreground-service churn until the end alarm fires.++**Fix:** On `startCapture` failure inside `startManualRecording`, immediately mark the run as `FAILED` via `markRunFailed()` before propagating the error.++---++### 2.4 `stopRecording` Marks Partial Writes as COMPLETED++**File:** `RecordingManagerImpl.kt` — `stopRecording()`+**Severity:** MEDIUM++```kotlin+status = if (run.bytesWritten > 0L) RecordingStatus.COMPLETED else RecordingStatus.CANCELLED,+```++`bytesWritten` is written by `updateRunProgress()`, which is called asynchronously during capture. Between the first bytes flowing from the network and the first DB progress update, the field reads `0`. A user who immediately stops a just-started recording gets `CANCELLED`. Conversely, the inverse corner case is meaningful: a recording where bytes were written but the stream was cut (network drop) and then the user presses stop would be marked `COMPLETED`, even though the file is truncated. The distinction silently misrepresents the recording quality to the user.++---++## 3. Race Conditions++### 3.1 `promoteScheduledRecording` Is Not Serialized++**File:** `RecordingManagerImpl.kt` — `promoteScheduledRecording()`+**Severity:** MEDIUM++`promoteScheduledRecording` is called from two independent paths for the same `recordingId`:+- The alarm fires → `RecordingAlarmReceiver` → `RecordingForegroundService.onStartCommand` → `manager.promoteScheduledRecording(recordingId)`+- `reconcileRecordingState()` → `RecordingForegroundService.startCapture(context, run.id)` → same service path++The `startCapture()` function has an `isActiveJob` guard, but the promote flow between `resolveRecordableSource()`, `recordingRunDao.update(updatedRun)`, and `startCapture()` is not atomically serialized. Two concurrent promote calls for the same run can both call `resolveRecordableSource()` (making duplicate network requests), both call `recordingRunDao.update()` (last writer wins), and both attempt `startCapture()`. The second call hits `isActiveJob → true` and returns `Result.success(Unit)`, but the state may have been partially mutated by both calls.++**Fix:** Add a per-recording mutex keyed by `recordingId`, or serialize promotion through the existing `activeJobsMutex` with a broader lock scope.++---++### 3.2 `spawnNextRecurringRunIfNeeded` Is Not Transactional++**File:** `RecordingManagerImpl.kt` — `spawnNextRecurringRunIfNeeded()`+**Severity:** MEDIUM++This function reads `scheduledRuns` from the DB, checks for an existing next-occurrence run, and then inserts a new one — all without a transaction or mutex. If a concurrent alarm triggers `promoteScheduledRecording` for another occurrence of the same recurring rule simultaneously, both calls could fail to see the pending insertion by the other and insert duplicate next-occurrence runs.++---++### 3.3 `updateRunProgress` Has a Read-Modify-Write Race++**File:** `RecordingManagerImpl.kt` — `updateRunProgress()`+**Severity:** LOW++```kotlin+val run = recordingRunDao.getById(recordingId) ?: return+recordingRunDao.update(run.copy(...))+```++Progress is reported via a flow of callbacks. If two `onProgress` calls arrive with small delay (possible if the coroutine resumes twice before the DB write completes), the second call reads the un-updated row and writes a stale `retryCount`. Room does not serialize these reads/writes. In practice this is low frequency, but `retryCount = maxOf(run.retryCount, progress.retryCount)` could revert a fresh retry count to a stale cached value.++---++## 4. Storage Issues++### 4.1 `retentionDays` Is Never Enforced++**Files:** `RecordingStorageConfig`, `RecordingStorageEntity`, `RecordingStorageState`+**Severity:** HIGH — Feature gap masquerading as working functionality++`retentionDays` is stored in the DB, exposed in the UI, included in backup/restore — but **no code anywhere deletes recordings older than this threshold**. `DatabaseMaintenanceManager` purges EPG programs, not recording files or recording run rows. The periodic `RecordingReconcileWorker` calls only `reconcileRecordingState()`, which handles status checks and alarm rescheduling, not file retention.++Users who configure a 30-day retention policy will accumulate recordings indefinitely.++**Fix:** Add a `pruneExpiredRecordings()` step inside `reconcileRecordingState()` (or as a dedicated `DatabaseMaintenanceManager` step) that:+1. Queries all COMPLETED/FAILED/CANCELLED runs where `terminalAtMs < (now - retentionDays * 86_400_000)`.+2. Calls `deleteOutputTarget()` for each.+3. Deletes the `recording_runs` row.++---++### 4.2 SAF (DocumentFile) Storage Doesn't Report Available Bytes++**File:** `RecordingSupport.kt` — `resolveStorageDetails()`+**Severity:** MEDIUM++When a SAF tree URI is configured, `availableBytes` is always `null`:++```kotlin+return Triple(documentTree?.name ?: treeUriString, null, isWritable)+```++The UI shows "available bytes" and the storage card displays the value — but it will always be empty for SAF paths. There is also no pre-flight disk-space check before starting any recording (SAF or plain file), meaning a recording can start even if only 10 MB remain.++**Fix:** Use `DocumentsContract.getDocumentUri()` + `ContentResolver.query(COLUMN_SIZE)` to get available space for a SAF tree, and add a minimum-space guard in `startManualRecording` / `promoteScheduledRecording`.++---++### 4.3 SAF File Collision Silently Overwrites Existing Recording++**File:** `RecordingSupport.kt` — `createOutputTarget()`+**Severity:** MEDIUM++```kotlin+val existing = documentTree.findFile(fileName)+val document = existing ?: documentTree.createFile("video/mp2t", fileName.removeSuffix(".ts"))+```++If a file with the computed name already exists, it is silently reused as the output target. A SAF `OutputStream` opened in `"w"` mode truncates the file. This means re-recording the same channel in the same minute (exact minute matches pattern `yyyy-MM-dd_HH-mm`) overwrites the previous recording without warning.++**Fix:** Append a counter suffix when a filename collision is detected (`_1`, `_2`, etc.), or generate a UUID suffix for SAF paths.++---++### 4.4 Partial Files Not Cleaned Up on Capture Failure++**Severity:** LOW++When `TsPassThroughCaptureEngine` or `HlsLiveCaptureEngine` throws during capture (network error, storage full, etc.), `markRunFailed()` updates the DB status but does not delete the partially written file. Subsequent retries create a new output file anyway (from the retry's `createPendingRun` → eventual promote). The partial file is left orphaned on storage with no DB reference.++---++## 5. Logic Issues++### 5.1 Retry Against Expired Schedule++**File:** `RecordingManagerImpl.kt` — `retryRecording()`++As noted in §2.2, there is no guard preventing retry when `schedule.requestedEndMs < now`. Beyond the crash risk, even if defensive code were added and an end-time extension were applied, the alarm for the new `scheduledEndMs` would fire at whatever extension time is used — creating ambiguity about what "retry" means for finished programs.++---++### 5.2 Manual Recording End Time Falls Back to 30 Minutes Without UI Notice++**File:** `PlayerViewModelActions.kt` — `startManualRecording()`++```kotlin+scheduledEndMs = currentProgram.value?.endTime ?: (now + 30 * 60_000L),+```++If there is no EPG data (common for M3U providers), the recording silently ends at exactly 30 minutes. The user gets a brief toast but no mention of the 30-minute cap. Channels with live events (sports, concerts) would be cut arbitrarily.++---++### 5.3 `seenSegments` Set Grows Unboundedly in HLS Engine++**File:** `RecordingCaptureEngine.kt` — `HlsLiveCaptureEngine`++```kotlin+val seenSegments = linkedSetOf<String>()+```++For a 4-hour HLS recording at 10-second segment intervals, `seenSegments` accumulates ~1,440 segment URI strings. Each URI can be 200–300 bytes. This is manageable, but for very long recordings (overnight, 8+ hours) on devices with limited memory, this set should be bounded. A sliding window or a bloom filter would cap memory at a fixed size.++---++### 5.4 `cancelRecording` Disables the Schedule but `retryRecording` Ignores That++**File:** `RecordingManagerImpl.kt`++`cancelRecording` sets `schedule.enabled = false`. `retryRecording` reads the schedule entity but creates a new run with `scheduleEnabled = true` regardless. A user who cancels a recurring recording (intending to stop the series) and then retries it will inadvertently re-enable the schedule. There is no guard in `retryRecording` checking whether the parent schedule has been disabled by an explicit cancel.++---++### 5.5 `cancelRecording` Does Not Cascade to Future Pending Occurrences++**Severity:** MEDIUM++For a recurring recording (`DAILY` / `WEEKLY`), `spawnNextRecurringRunIfNeeded` inserts future occurrences into `recording_runs` as they are promoted. `cancelRecording` disables the schedule and the one run, but pending child runs for future occurrences are **not cancelled**. Each will be promoted to RECORDING when their alarm fires, even though the user cancelled the series. `setScheduleEnabled(..., false)` has the same gap: it only toggles a single run's alarm, it does not query and cancel all pending runs sharing the same `recurringRuleId`.++**Fix:** In `cancelRecording` and `setScheduleEnabled(..., false)`, also query `recording_runs WHERE recurring_rule_id = ? AND status = 'SCHEDULED'` and cancel all matching runs.++---++### 5.6 `validateRecordingWindow` Silently Skips Provider Limit for Missing Provider++**File:** `RecordingManagerImpl.kt` — `validateRecordingWindow()`++```kotlin+val providerMaxConnections = providerDao.getById(providerId)?.maxConnections ?: Int.MAX_VALUE+```++If the provider was deleted between scheduling and the alarm firing, `maxConnections` defaults to `Int.MAX_VALUE`, effectively disabling the per-provider connection limit. An expired provider's recording would proceed regardless of account limits. A more defensive behavior would be to fail the recording with `RecordingFailureCategory.PROVIDER_LIMIT`.++---++## 6. Thread Safety++### 6.1 `activeJobs` Map Is Properly Guarded++`activeJobs` uses `activeJobsMutex.withLock { ... }` consistently through `registerActiveJob`, `removeActiveJob`, `isActiveJob`, and `cancelActiveJob`. This is correct. The mutex is a `Mutex` (kotlinx coroutines), which is fair and non-reentrant — no risk of deadlock given the usage pattern.++### 6.2 DB State vs. In-Memory Job State Are Not Synchronized++`observeActiveRecordingCountSync()` counts live coroutine jobs (`activeJobs.values.count { it.isActive }`). `onCaptureFinished` uses this count to decide whether to stop the foreground service. But `observeActiveRecordingCount()` (from `RecordingManager` interface) counts DB rows with `status == RECORDING`. These two counts can diverge:+- A zombie DB row (job died, no `markRunFailed()` cleanup) keeps the DB count high, keeping the notification alive and the service running forever.+- An unexpected process death and restart clears `activeJobs` entirely; reconcile then re-enqueues via the service, but there is a window where the service runs with zero in-memory jobs and a stale DB count.++The foreground service stops on `count == 0` from the DB-backed flow (`observeActiveRecordingCount()`), while `onCaptureFinished` uses the in-memory count. The inconsistency means the service keeps running until a DB observation fires — which is correct long-term, but the `onCaptureFinished` check for `remaining == 0` to call `stopIfIdle()` fires prematurely when the in-memory count reaches 0 while DB rows are still RECORDING. The service then receives the DB update and `collectLatest` stops it cleanly anyway, so in practice this is benign — but it represents conceptual inconsistency.++---++## 7. Error Handling++### 7.1 `inferFailureCategory` Is String-Matching Based++**File:** `RecordingSupport.kt`++```kotlin+"connection" in normalized || "http 401" in normalized || "http 403" in normalized ...+```++Failure classification depends on the human-readable exception message. If OkHttp or a capture engine changes its error message wording, the category silently falls back to `UNKNOWN`. The categories `NETWORK`, `AUTH`, `TOKEN_EXPIRED` etc. are important for UI guidance and retry logic. Using structured exception types (sealed class hierarchy) or explicit HTTP status codes would be more reliable.++---++### 7.2 HLS AES-128 IV Falls Back Silently to All-Zero IV++**File:** `RecordingCaptureEngine.kt` — `decryptAes128()`++```kotlin+val iv = ivHex?.removePrefix("0x")+ ...+ ?.takeIf { it.size == 16 }+ ?: ByteArray(16) // silent fallback — all zeros+```++If the `#EXT-X-KEY IV=` attribute is absent or has an unexpected format, the IV is silently set to 16 zero bytes. For HLS streams that rely on explicit per-segment IVs (RFC 8216 §4.3.2.4), this produces garbage decryption output. The file is written but cannot be played back. A clear `UnsupportedRecordingException` should be thrown when an IV is expected but cannot be parsed.++---++### 7.3 DASH Detection Falls Through to `RecordingSourceType.TS`++**File:** `RecordingSourceResolver.kt` — `probeAdaptiveType()`++If the network probe fails (`runCatching` returning empty string) and the body prefix is empty, the function returns `RecordingSourceType.TS`. A DASH stream that happened to produce a connection error during sniffing would be passed to `TsPassThroughCaptureEngine`, which would fail silently writing non-TS bytes to the output file. After the full `scheduledEndMs` window, the recording would be marked COMPLETED with a corrupted file.++---++### 7.4 `migrateLegacyStateIfNeeded` Imports "RECORDING" Status as-is++**File:** `RecordingManagerImpl.kt`++Legacy recordings with `status = RECORDING` are inserted into `recording_runs` at their original status. `reconcileRecordingState()` then calls `RecordingForegroundService.startCapture()` for each, trying to resume recordings that were already complete or interrupted. The run has no `resolvedUrl` populated (the legacy JSON didn't carry resolved URLs), so `startCapture` would fail at `run.resolvedUrl ?: return Result.error(...)`. The run is then left dangling in `RECORDING` state without automatic marking as failed. Consider clamping migrated RECORDING entries to `FAILED` during import.++---++## 8. Android Platform Issues++### 8.1 `SCHEDULE_EXACT_ALARM` Permission Revocable on Android 12+++**File:** `RecordingAlarmScheduler.kt`++The app declares `SCHEDULE_EXACT_ALARM`. On Android 12+ (API 31+), users can revoke this permission from Special App Access. The scheduler catches `SecurityException` and falls back to `setAndAllowWhileIdle`, which is **inexact** — it can fire minutes or hours late. For live TV recordings (timed to the minute), this silently degrades scheduling accuracy with no user-visible warning.++Additionally, Android 13 (API 33) introduced `USE_EXACT_ALARM` as an alternative that does not require user grant for certain calendar/alarm applications. Since this is an IPTV player with an explicit DVR use case, that permission may be a better choice. At minimum, the app should check `alarmManager.canScheduleExactAlarms()` before relying on exact timing and surface a prompt if the permission is missing.++---++### 8.2 `foregroundServiceType="dataSync"` May Require Additional Permission on Android 14+++**File:** `data/src/main/AndroidManifest.xml`++Android 14 (API 34) requires `FOREGROUND_SERVICE_DATA_SYNC` permission for `dataSync`-type foreground services. This permission is not declared in either `data/AndroidManifest.xml` or `app/AndroidManifest.xml`. The service will fail to start on Android 14+ without it.++```xml+<!-- Missing from manifests -->+<uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />+```++---++### 8.3 `LOCKED_BOOT_COMPLETED` Triggers Room DB Access Before Decryption++**File:** `RecordingRestoreReceiver.kt`++`LOCKED_BOOT_COMPLETED` fires before the user has unlocked the device. If the app uses device-encrypted storage (the default), the Room database is in the DE (device-encrypted) area and may not be accessible via CE (credential-encrypted) paths. Calling `reconcileRecordingState()` at this point could trigger DB access failures. The receiver should check whether CE storage is available or limit the `LOCKED_BOOT_COMPLETED` response to starting minimal bootstrap only, deferring full reconcile to `BOOT_COMPLETED`.++---++### 8.4 `RecordingReconcileWorker` Requires Network for Non-Network Tasks++**File:** `RecordingReconcileWorker.kt`++```kotlin+.setRequiredNetworkType(NetworkType.CONNECTED)+```++The reconcile worker's primary purpose is to mark expired recording rows as FAILED and reschedule alarms. Neither of these operations requires network. The `NetworkType.CONNECTED` constraint prevents the worker from running (for example, after boot in airplane mode), which means recordings that expired while offline keep their stale `SCHEDULED` or `RECORDING` status indefinitely. The network constraint should be removed from the periodic reconcile worker (it's appropriate only if the worker fetched remote data, which it does not).++---++### 8.5 `PendingIntent` Request Code Hash Collision Risk++**File:** `RecordingAlarmScheduler.kt`++```kotlin+private fun requestCode(action: String, recordingId: String): Int =+ 31 * action.hashCode() + recordingId.hashCode()+```++UUID strings are large but their `String.hashCode()` is a 32-bit integer. Two different UUIDs can share a hash. If two recordings produce the same `requestCode` for the same action, the second `PendingIntent.getBroadcast` call (with `FLAG_UPDATE_CURRENT`) overwrites the first alarm's extra data, silently redirecting the alarm to start/stop the wrong recording. With `FLAG_UPDATE_CURRENT`, only the extras are replaced — so the wrong `recording_id` is delivered to `RecordingAlarmReceiver`.++**Fix:** Pre-allocate monotonically incrementing alarm request codes persisted in the DB (`alarm_request_code` column), or use a stable hash with lower collision probability (e.g., `abs(recordingId.hashCode() xor action.hashCode() * 31)`). Even better: use two separate action strings no longer and separate PendingIntent buckets to reduce the keyspace shared between start and stop alarms.++---++## 9. Consistency Issues++### 9.1 `RecordingItem.outputPath` and `outputDisplayPath` Are Identical++**File:** `RecordingSupport.kt` — `toDomain()`, `RecordingManagerImpl.kt` — `toStandaloneDomain()`++```kotlin+outputPath = outputDisplayPath,+outputDisplayPath = outputDisplayPath,+```++`RecordingItem` has both `outputPath` and `outputDisplayPath` populated from the same source. `outputPath` appears to be a legacy field (from the old JSON-file state model). In `deleteOutputTarget`, **both** the SAF URI and the `outputDisplayPath` are used for deletion. For SAF recordings, `outputDisplayPath` is a human-readable label like `"Recordings/ChannelName_...ts"`, not a real filesystem path: `File(outputDisplayPath).delete()` is a silent no-op since the path doesn't exist on the filesystem. This is not harmful (the SAF deletion succeeds), but it's confusing and leaves dead code.++---++### 9.2 Backup Import Re-schedules Expired Recording Windows++**File:** `BackupManagerImpl.kt`++```kotlin+if (scheduled.scheduledEndMs <= System.currentTimeMillis()) {+ return@forEach+}+```++Historical recordings with past end times are correctly skipped. But the check is coarse: a recording scheduled in the past with daily recurrence is entirely dropped. There is no attempt to roll the recurrence forward to the next occurrence. After a backup restore, recurring recording series are lost if their last scheduled occurrence was before the restore time.++---++### 9.3 Manual Recording Has No Conflict Checking for Provider Connection Limit++**File:** `RecordingManagerImpl.kt` — `validateRecordingWindow()`++The connection-limit check `overlapping.count { it.providerId == providerId } >= providerMaxConnections` runs for both `startManualRecording` and `scheduleRecording` (both call `validateRecordingWindow`). This is correct. However, the conflict check for scheduled recordings uses `RecordingConflictDetector.findRecordingRunConflict`, while `validateRecordingWindow` uses a raw DB query. These two paths could reach different conclusions if the `scheduleEnabled` flag on a run has been toggled between the check and the query, since `getOverlapping` does not filter by `scheduleEnabled` but `findRecordingRunConflict` does:++```kotlin+// In validateRecordingWindow — does NOT filter by scheduleEnabled:+val overlapping = recordingRunDao.getOverlapping(startMs, endMs)+ .filter { it.status == ... }+ .filter { it.scheduleEnabled } // ← manual filter applied after fetch++// In spawnNextRecurringRunIfNeeded:+conflict = activeRuns.findRecordingRunConflict(...) // checks scheduleEnabled too+```++The `validateRecordingWindow` does filter `scheduleEnabled` on the Kotlin side after the DB query, so the semantics match. This is correct but fragile — adding `scheduleEnabled` filtering to the SQL query would be more explicit.++---++## 10. Missing Test Coverage++| Area | Test Status |+|---|---|+| `RecordingConflictDetector` | Covered (`RecordingConflictDetectorTest`) — 4 cases |+| `ScheduleRecording` use case | Covered (`ScheduleRecordingTest`) |+| `RecordingManagerImpl` (all paths) | **Not tested** |+| `TsPassThroughCaptureEngine` | **Not tested** |+| `HlsLiveCaptureEngine` (segment fetch, AES, timeout) | **Not tested** |+| `RecordingSourceResolver` (DASH fallback, probe logic) | **Not tested** |+| `RecordingAlarmScheduler` (hash collisions, fallback) | **Not tested** |+| Retention enforcement | **Not tested** (no enforcement exists) |+| `migrateLegacyStateIfNeeded` | **Not tested** |+| Recurring rollover (`spawnNextRecurringRunIfNeeded`) | **Not tested** |++The conflict detector tests are well-structured and cover the boundary (adjacent window = no conflict), terminal-status ignoring, and recurring skip cases. The use-case tests cover the main error paths. However, the `RecordingManagerImpl` core — the most complex component — has zero unit tests. Given the threading concerns and state transitions documented above, this is the most urgent gap.++---++## 11. Security Notes++### 11.1 Gson Still Used for Header Serialization++**Files:** `RecordingManagerImpl.kt`, `RecordingSupport.kt` — `headersToJson()` / `headersFromJson()`++The project has migrated to `kotlinx.serialization` for Xtream API responses, but `Gson` is still injected into `RecordingManagerImpl` for recording header persistence. `Map<String, String>` serialization via Gson doesn't expose gadget-chain deserialization risks, but it's inconsistent and keeps a Gson dependency. The header map is trivially representable with `kotlinx.serialization`.++---++### 11.2 AES-128 IV Fallback Produces Silent Garbage Output++Covered in §7.2. From a security standpoint, silently falling back to an all-zero IV when the stream provides an explicit IV may produce output that leaks partially decrypted segment data or, more practically, produces a corrupt but not-empty file that appears to have succeeded.++---++### 11.3 `sanitizeRecordingFileName` Allows Dots++Pattern: `[^a-zA-Z0-9._ -]` — dots are allowed. While not a path traversal risk (the filename is resolved against a fixed directory), a channel name of `"..ts"` produces a filename of `"..ts"`, which `File.getName()` would return as `"..ts"` and might confuse directory traversal checks in other tooling. Excluding dots from the allowlist (or limiting to a single dot before the extension) would be more robust.++---++## 12. Summary Table++| # | Area | Finding | Severity |+|---|---|---|---|+| 2.1 | Race | TOCTOU on concurrent recording start | HIGH |+| 2.2 | Logic | `retryRecording` crashes on expired schedule | HIGH |+| 4.1 | Storage | `retentionDays` stored but never enforced | HIGH |+| 8.2 | Android | Missing `FOREGROUND_SERVICE_DATA_SYNC` permission on API 34+ | HIGH |+| 2.3 | Error | Orphan RECORDING row after `startCapture` failure | MEDIUM |+| 2.4 | Logic | `stopRecording` misclassifies based on stale `bytesWritten` | MEDIUM |+| 3.1 | Race | `promoteScheduledRecording` not serialized per recording | MEDIUM |+| 3.2 | Race | `spawnNextRecurringRunIfNeeded` not transactional | MEDIUM |+| 4.2 | Storage | SAF `availableBytes` always null, no disk-space pre-check | MEDIUM |+| 4.3 | Storage | SAF file name collision silently overwrites existing recording | MEDIUM |+| 5.5 | Logic | Cancel does not cascade to future recurring occurrences | MEDIUM |+| 7.1 | Error | Failure category classification is string-match based | MEDIUM |+| 7.3 | Error | Failed DASH probe falls through as TS, produces corrupt file | MEDIUM |+| 7.4 | Error | Migrated RECORDING-status rows left dangling after legacy migration | MEDIUM |+| 8.1 | Android | `SCHEDULE_EXACT_ALARM` revocable, fallback is silent | MEDIUM |+| 8.3 | Android | `LOCKED_BOOT_COMPLETED` triggers DB access before decryption | MEDIUM |+| 8.4 | Android | Reconcile worker requires network for non-network task | MEDIUM |+| 3.3 | Race | `updateRunProgress` read-modify-write is non-atomic | LOW |+| 4.4 | Storage | Partial files not cleaned up on capture failure | LOW |+| 5.1 | Logic | `retryRecording` has no guard against expired end time (pre-crash) | LOW |+| 5.2 | Logic | Manual recording silently caps at 30 min with no UI notice | LOW |+| 5.3 | Logic | `seenSegments` set unbounded for very long HLS recordings | LOW |+| 5.4 | Logic | `cancelRecording` + `retryRecording` re-enables disabled schedule | LOW |+| 5.6 | Logic | Missing provider silently bypasses connection limit | LOW |+| 7.2 | Error | AES-128 IV fallback to all-zeros is silent | LOW |+| 8.5 | Android | PendingIntent request code hash collision risk | LOW |+| 9.1 | Consistency | `outputPath` and `outputDisplayPath` are redundant | LOW |+| 9.2 | Consistency | Backup import drops recurring schedules instead of rolling forward | LOW |+| 11.1 | Security | Gson still used for header serialization | LOW |+| 11.3 | Security | `sanitizeRecordingFileName` allows dots in pattern | LOW |+| 13.1 | Feature | No in-app recordings playback or library screen | GAP — HIGH |+| 13.2 | Feature | EPG-level scheduling requires user to be watching the channel | GAP — HIGH |+| 13.3 | Feature | No pre/post recording padding | GAP — HIGH |+| 13.4 | Feature | No stalled-capture watchdog (`lastProgressAtMs` never checked) | GAP — MEDIUM |+| 13.5 | Feature | No automatic retry on transient network failure | GAP — MEDIUM |+| 13.6 | Feature | No proactive low-disk-space warning before scheduled recording | GAP — MEDIUM |+| 13.7 | Feature | No WiFi-only recording restriction | GAP — MEDIUM |+| 13.8 | Feature | HLS always picks highest-bandwidth variant regardless of user pref | GAP — MEDIUM |+| 13.9 | Feature | HLS multi-audio and subtitle tracks silently dropped | GAP — MEDIUM |+| 13.10 | Feature | Output always raw `.ts`, no remux to MP4/MKV | GAP — MEDIUM |+| 13.11 | Feature | No series/keyword-based recurring recording rule | GAP — MEDIUM |+| 13.12 | Feature | No "cancel this occurrence" vs. "cancel entire series" UI | GAP — MEDIUM |+| 13.13 | Feature | Completed recordings not integrated with Continue Watching | GAP — LOW |+| 13.14 | Feature | No recording status indicator in channel cards or home screen | GAP — LOW |+| 13.15 | Feature | No push notification on recording failure | GAP — LOW |+| 13.16 | Feature | No search or filter in recordings list | GAP — LOW |+| 13.17 | Feature | No live rewind → recording integration | GAP — LOW |+| 13.18 | Feature | Conflict resolution surfaces an error string, no resolution UI | GAP — LOW |+| 13.19 | Feature | No DLNA/media-server exposure of recordings folder | GAP — LOW |++---++## 13. Feature Gaps & Missing Functionality++### 13.1 No In-App Recordings Playback or Library Screen++**Severity:** GAP — HIGH++Completed recordings are files on disk or SAF storage, but there is no player integration and no dedicated "My Recordings" screen reachable from the main navigation. The only recording management UI is buried inside Settings. Users cannot browse or watch what they have recorded without leaving the app and using a file manager or external player. This is the most fundamental feature gap for a DVR.++---++### 13.2 EPG-Level Recording Scheduling Not Available++**Severity:** GAP — HIGH++`ScheduleRecording` and `startManualRecording` are only reachable from `PlayerViewModelActions`, requiring the user to navigate to the channel and begin watching before scheduling. A standard DVR allows browsing the EPG grid and pressing Record on any future program without navigating to it first. Additionally, the EPG grid shows no visual indicator (red dot, recording icon) for programs that are already scheduled, so the user has no way to confirm a recording is set without returning to Settings.++---++### 13.3 No Pre/Post Recording Padding++**Severity:** GAP — HIGH++There is no option to start recording N minutes before the scheduled program start or to continue recording N minutes after the scheduled end. EPG program times from IPTV providers are frequently off by 1–5 minutes, and live events (sports, concerts) routinely run over. This is a baseline DVR feature expected by users. The `RecordingRequest` model would need `paddingStartMs` and `paddingEndMs` fields, applied before conflict detection and alarm scheduling.++---++### 13.4 No Stalled-Capture Watchdog++**Severity:** GAP — MEDIUM++`lastProgressAtMs` is written to the DB by `updateRunProgress()` on every progress callback from the capture engines. However, nothing reads this field to detect a stalled capture. If a stream continuously delivers data at an extremely slow rate (a hung IPTV server sending 1 byte/minute), the recording stays in `RECORDING` state, `bytesWritten` increments slowly, and the recording is eventually marked `COMPLETED` with a useless file. A watchdog timer that fires if `lastProgressAtMs` has not advanced for a configurable threshold (e.g., 60 seconds) would catch this class of failure.++---++### 13.5 No Automatic Retry on Transient Network Failure++**Severity:** GAP — MEDIUM++`retryCount` is stored in `RecordingRunEntity` and surfaced in `RecordingItem`, implying retry behavior — but neither `TsPassThroughCaptureEngine` nor `HlsLiveCaptureEngine` has a retry loop. Any network interruption (transient blip, brief server restart) immediately fails the recording permanently via `markRunFailed()`. A backoff retry policy (e.g., 3 attempts with 15-second backoff) inside the capture engines would recover the vast majority of real-world IPTV interruptions without user intervention.++---++### 13.6 No Proactive Low-Disk-Space Warning Before Scheduled Recordings++**Severity:** GAP — MEDIUM++There is no threshold check before a scheduled recording fires. If available bytes have dropped below a safe minimum (e.g., < 1 GB) since the recording was scheduled, the alarm fires, the foreground service starts, and the capture engine writes until storage is exhausted — failing mid-recording. A pre-flight check inside `promoteScheduledRecording` comparing `storage.availableBytes` against a configurable minimum (or a fixed conservative default like 512 MB) would allow failing with a clear `RecordingFailureCategory.STORAGE` and a user notification before any bytes are written.++---++### 13.7 No WiFi-Only Recording Restriction++**Severity:** GAP — MEDIUM++Recordings run on mobile data as readily as on WiFi. A high-bitrate IPTV stream can easily consume several GB per hour. There is no "record only on WiFi" setting, which users with mobile data plans would expect. The `RecordingStorageConfig` model is a natural place to add a `requireWifi: Boolean` flag, with enforcement in `promoteScheduledRecording` via `ConnectivityManager` before starting capture.++---++### 13.8 HLS Capture Always Picks Highest-Bandwidth Variant++**Severity:** GAP — MEDIUM++`HlsLiveCaptureEngine` selects the best variant unconditionally:++```kotlin+val bestVariantUrl = variants.maxByOrNull { it.first }?.second+```++The app already has a per-network quality-cap system for the player (`preferredVideoQuality` persisted per network type). Recording ignores this entirely. A user on a constrained connection who has set a quality cap for WiFi would still record at maximum bitrate, potentially filling storage faster than expected or straining a shared network connection. Recording quality should respect the same preference or expose an independent cap.++---++### 13.9 HLS Multi-Audio and Subtitle Tracks Are Silently Dropped++**Severity:** GAP — MEDIUM++The HLS capture engine processes only the video/audio segment stream selected from the master playlist. `#EXT-X-MEDIA TYPE=AUDIO` alternative renditions (e.g., secondary language audio) and `TYPE=SUBTITLES` tracks are never downloaded or muxed. For multi-language IPTV providers, this means every recording loses secondary audio and subtitles. At minimum a warning should be surfaced; ideally, the engine should download and mux the preferred audio rendition alongside the video stream.++---++### 13.10 Output Always Written as Raw `.ts` — No Container Remux++**Severity:** GAP — MEDIUM++All recordings are written as raw MPEG-TS (`.ts`) files. While VLC and most IPTV players handle `.ts` natively, most consumer devices (Android gallery, smart TVs, DLNA renderers) expect `.mp4` or `.mkv`. Even a passthrough remux using Android's `MediaMuxer` (copying A/V tracks without transcoding) after the capture completes would significantly improve playback compatibility outside the app. This could be offered as an optional post-processing step in `RecordingStorageConfig`.++---++### 13.11 No Series/Keyword-Based Recurring Recording Rule++**Severity:** GAP — MEDIUM++Current recurrence supports `DAILY` and `WEEKLY` at a **fixed time slot**. There is no mechanism to record every episode of a named program regardless of when it airs (a "series link" or "keyword timer" as found in conventional DVRs). EPG data with `Program.title` is already stored; a rule engine that matches program titles against a configured keyword and auto-schedules matching future programs would complete the DVR feature set. The domain model for `RecordingScheduleEntity` would need a `matchRule` field alongside the existing `recurrence`.++---++### 13.12 No "Cancel This Occurrence" vs. "Cancel Entire Series" UI++**Severity:** GAP — MEDIUM++`cancelRecording` cancels a single run and disables its parent schedule. For a recurring series this is the equivalent of cancelling the whole series (once the schedule is disabled, `spawnNextRecurringRunIfNeeded` stops spawning). There is no UI distinction between "skip this one episode" and "stop the entire recurring recording". A "skip occurrence" action would mark just the one run as `CANCELLED` while leaving the schedule enabled and future runs untouched. See also §5.5 which covers the related technical gap of cancellation not cascading to already-spawned future runs.++---++### 13.13 Completed Recordings Not Integrated with Continue Watching++**Severity:** GAP — LOW++If a user starts watching a completed recording and pauses midway, the resume position is not tracked anywhere. The existing `PlaybackHistoryRepository` infrastructure (used for VOD continue-watching) is sufficient to track recording playback if recordings were treated as a playable content type with a stable content ID. Without this, every re-open of a recording starts from the beginning.++---++### 13.14 No Recording Status Indicator in Channel Cards or Home Screen++**Severity:** GAP — LOW++There is no visual indicator on channel cards or in the home screen showing that a recording is currently in progress for a channel, or that a future recording is scheduled. Every mainstream DVR shows at least a red dot on an actively recording channel. `RecordingManager.observeRecordingItems()` is available as a flow; the home and live channel list screens could filter it to decorate the relevant channel cards.++---++### 13.15 No Push Notification on Recording Failure++**Severity:** GAP — LOW++When a scheduled recording silently fails at 2 AM (network dropped, storage full, token expired), the only discovery mechanism is the user opening Settings and checking the recordings list. The foreground service notification disappears when recording ends. A separate `NotificationManager` notification posted by `markRunFailed()` — outside the foreground service channel — with the failure reason and a "Retry" action would make failures visible without requiring the user to actively check.++---++### 13.16 No Search or Filter in the Recordings List++**Severity:** GAP — LOW++The recordings list in Settings renders a flat `LazyColumn` of all `RecordingItem` entries with no search input, status filter, or sort options. With any meaningful number of recordings (a daily recording rule over weeks produces dozens of entries) the list becomes difficult to use. Status-based filtering (`Scheduled` / `Completed` / `Failed`) and a simple title search would be standard.++---++### 13.17 No Live Rewind → Recording Integration++**Severity:** GAP — LOW++`docs/LIVE_REWIND_PLAN.md` describes a live rewind buffer. When a user is watching live TV and realizes mid-program they want to record it from the start, there is no way to "record from the beginning of the buffer". The recording simply starts from now. Integrating the rewind buffer write path with `RecordingCaptureEngine` would allow capturing already-buffered content into the output file before switching to the live stream, a feature called "catch-up recording" on commercial DVRs.++---++### 13.18 Conflict Resolution Shows an Error String, No Resolution UI++**Severity:** GAP — LOW++When `validateRecordingWindow` detects a conflict, the result is a plain error string surfaced as a player notice or settings toast. There is no dialog offering the user choices such as: keep the existing recording, replace it with the new one, or adjust timing. A conflict resolution dialog — similar to `BackupImportPreviewDialog` — would give the user agency instead of a dead end.++---++### 13.19 No DLNA / Media-Server Exposure of Recordings Folder++**Severity:** GAP — LOW++Recorded files are stored in the app-private external movies directory or a user-chosen SAF folder. Neither is automatically accessible to network media renderers (smart TVs, Kodi, etc.) via DLNA/UPnP. Exposing the recordings folder through an embedded media server (or at minimum documenting that the SAF path should be set to a publicly accessible location) would allow users to watch recordings on other devices without transferring files manually.diff --git a/domain/src/main/java/com/streamvault/domain/manager/ProgramReminderManager.kt b/domain/src/main/java/com/streamvault/domain/manager/ProgramReminderManager.ktnew file mode 100644index 00000000..93c64288--- /dev/null+++ b/domain/src/main/java/com/streamvault/domain/manager/ProgramReminderManager.kt@@ -0,0 +1,34 @@+package com.streamvault.domain.manager++import com.streamvault.domain.model.Program+import com.streamvault.domain.model.ProgramReminder+import com.streamvault.domain.model.Result+import kotlinx.coroutines.flow.Flow++interface ProgramReminderManager {+ fun observeUpcomingReminders(): Flow<List<ProgramReminder>>++ suspend fun isReminderScheduled(+ providerId: Long,+ channelId: String,+ programTitle: String,+ programStartTime: Long+ ): Boolean++ suspend fun scheduleReminder(+ providerId: Long,+ channelId: String,+ channelName: String,+ program: Program,+ leadTimeMinutes: Int = 5+ ): Result<Unit>++ suspend fun cancelReminder(+ providerId: Long,+ channelId: String,+ programTitle: String,+ programStartTime: Long+ ): Result<Unit>++ suspend fun restoreScheduledReminders()+}diff --git a/domain/src/main/java/com/streamvault/domain/model/ChannelNumberingMode.kt b/domain/src/main/java/com/streamvault/domain/model/ChannelNumberingMode.ktindex 3195bc2e..a8a1ce2a 100644--- a/domain/src/main/java/com/streamvault/domain/model/ChannelNumberingMode.kt+++ b/domain/src/main/java/com/streamvault/domain/model/ChannelNumberingMode.kt@@ -2,7 +2,8 @@ package com.streamvault.domain.modelenum class ChannelNumberingMode(val storageValue: String) {GROUP("group"),- PROVIDER("provider");+ PROVIDER("provider"),+ HIDDEN("hidden");companion object {fun fromStorage(value: String?): ChannelNumberingMode =diff --git a/domain/src/main/java/com/streamvault/domain/model/EpgModels.kt b/domain/src/main/java/com/streamvault/domain/model/EpgModels.ktindex 310f8317..6b1e9e45 100644--- a/domain/src/main/java/com/streamvault/domain/model/EpgModels.kt+++ b/domain/src/main/java/com/streamvault/domain/model/EpgModels.kt@@ -81,6 +81,9 @@ data class ChannelEpgMapping(val xmltvChannelId: String? = null,val matchType: EpgMatchType? = null,val confidence: Float = 0f,+ val matchedAt: Long = 0L,+ val failedAttempts: Int = 0,+ val source: String? = null,val isManualOverride: Boolean = false,val updatedAt: Long = System.currentTimeMillis())@@ -101,5 +104,8 @@ data class EpgResolutionSummary(val exactIdMatches: Int = 0,val normalizedNameMatches: Int = 0,val providerNativeMatches: Int = 0,- val unresolvedChannels: Int = 0+ val manualMatches: Int = 0,+ val unresolvedChannels: Int = 0,+ val lowConfidenceChannels: Int = 0,+ val rematchCandidateChannels: Int = 0)diff --git a/domain/src/main/java/com/streamvault/domain/model/Favorite.kt b/domain/src/main/java/com/streamvault/domain/model/Favorite.ktindex cc089d72..f065310c 100644--- a/domain/src/main/java/com/streamvault/domain/model/Favorite.kt+++ b/domain/src/main/java/com/streamvault/domain/model/Favorite.kt@@ -2,6 +2,7 @@ package com.streamvault.domain.modeldata class Favorite(val id: Long = 0,+ val providerId: Long,val contentId: Long,val contentType: ContentType,val position: Int = 0,@@ -15,6 +16,7 @@ data class Favorite(data class VirtualGroup(val id: Long = 0,+ val providerId: Long,val name: String,val iconEmoji: String? = null,val position: Int = 0,diff --git a/domain/src/main/java/com/streamvault/domain/model/Movie.kt b/domain/src/main/java/com/streamvault/domain/model/Movie.ktindex 7a6419be..65f08ff0 100644--- a/domain/src/main/java/com/streamvault/domain/model/Movie.kt+++ b/domain/src/main/java/com/streamvault/domain/model/Movie.kt@@ -26,7 +26,8 @@ data class Movie(val lastWatchedAt: Long = 0L,val isAdult: Boolean = false,val isUserProtected: Boolean = false,- val streamId: Long = 0L+ val streamId: Long = 0L,+ val addedAt: Long = 0L) {init {require(durationSeconds >= 0) { "durationSeconds must be non-negative" }diff --git a/domain/src/main/java/com/streamvault/domain/model/ProgramReminder.kt b/domain/src/main/java/com/streamvault/domain/model/ProgramReminder.ktnew file mode 100644index 00000000..08dbbead--- /dev/null+++ b/domain/src/main/java/com/streamvault/domain/model/ProgramReminder.kt@@ -0,0 +1,15 @@+package com.streamvault.domain.model++data class ProgramReminder(+ val id: Long = 0,+ val providerId: Long,+ val channelId: String,+ val channelName: String,+ val programTitle: String,+ val programStartTime: Long,+ val remindAt: Long,+ val leadTimeMinutes: Int = 5,+ val isDismissed: Boolean = false,+ val notifiedAt: Long? = null,+ val createdAt: Long = System.currentTimeMillis()+)diff --git a/domain/src/main/java/com/streamvault/domain/model/SearchHistoryScope.kt b/domain/src/main/java/com/streamvault/domain/model/SearchHistoryScope.ktnew file mode 100644index 00000000..9dc0a241--- /dev/null+++ b/domain/src/main/java/com/streamvault/domain/model/SearchHistoryScope.kt@@ -0,0 +1,9 @@+package com.streamvault.domain.model++enum class SearchHistoryScope {+ ALL,+ LIVE,+ MOVIE,+ SERIES,+ EPG+}diff --git a/domain/src/main/java/com/streamvault/domain/model/StreamInfo.kt b/domain/src/main/java/com/streamvault/domain/model/StreamInfo.ktindex afc2ba13..50b28d83 100644--- a/domain/src/main/java/com/streamvault/domain/model/StreamInfo.kt+++ b/domain/src/main/java/com/streamvault/domain/model/StreamInfo.kt@@ -47,7 +47,19 @@ enum class StreamType {MPEG_TS,PROGRESSIVE,RTSP, // PE-H03: native RTSP via Media3 RtspMediaSource- UNKNOWN+ UNKNOWN;++ companion object {+ fun fromContainerExtension(ext: String?): StreamType {+ return when (ext?.trim()?.removePrefix(".")?.lowercase()) {+ "ts" -> MPEG_TS+ "m3u8" -> HLS+ "mpd" -> DASH+ "mp4", "mkv", "avi", "mov", "mp3", "aac", "m4a", "flv", "webm" -> PROGRESSIVE+ else -> UNKNOWN+ }+ }+ }}enum class DecoderMode {diff --git a/domain/src/main/java/com/streamvault/domain/model/SyncMetadata.kt b/domain/src/main/java/com/streamvault/domain/model/SyncMetadata.ktindex 622e154b..056078c4 100644--- a/domain/src/main/java/com/streamvault/domain/model/SyncMetadata.kt+++ b/domain/src/main/java/com/streamvault/domain/model/SyncMetadata.kt@@ -12,9 +12,12 @@ enum class VodSyncMode {data class SyncMetadata(val providerId: Long,val lastLiveSync: Long = 0,+ val lastLiveSuccess: Long = 0,val lastMovieSync: Long = 0,val lastSeriesSync: Long = 0,+ val lastSeriesSuccess: Long = 0,val lastEpgSync: Long = 0,+ val lastEpgSuccess: Long = 0,val lastMovieAttempt: Long = 0,val lastMovieSuccess: Long = 0,val lastMoviePartial: Long = 0,diff --git a/domain/src/main/java/com/streamvault/domain/model/VideoFormat.kt b/domain/src/main/java/com/streamvault/domain/model/VideoFormat.ktindex c29bd089..34ac92e6 100644--- a/domain/src/main/java/com/streamvault/domain/model/VideoFormat.kt+++ b/domain/src/main/java/com/streamvault/domain/model/VideoFormat.kt@@ -6,13 +6,15 @@ data class VideoFormat(val frameRate: Float = 0f,val bitrate: Int = 0,val codecV: String? = null,- val codecA: String? = null+ val codecA: String? = null,+ val pixelWidthHeightRatio: Float = 1f) {init {require(width >= 0) { "width must be non-negative" }require(height >= 0) { "height must be non-negative" }require(frameRate >= 0f) { "frameRate must be non-negative" }require(bitrate >= 0) { "bitrate must be non-negative" }+ require(pixelWidthHeightRatio > 0f) { "pixelWidthHeightRatio must be positive" }}val resolutionLabel: Stringdiff --git a/domain/src/main/java/com/streamvault/domain/repository/ChannelRepository.kt b/domain/src/main/java/com/streamvault/domain/repository/ChannelRepository.ktindex 9f18fc7e..91676898 100644--- a/domain/src/main/java/com/streamvault/domain/repository/ChannelRepository.kt+++ b/domain/src/main/java/com/streamvault/domain/repository/ChannelRepository.kt@@ -9,13 +9,15 @@ import kotlinx.coroutines.flow.Flowinterface ChannelRepository {fun getChannels(providerId: Long): Flow<List<Channel>>fun getChannelsByCategory(providerId: Long, categoryId: Long): Flow<List<Channel>>+ fun getChannelsByCategoryPage(providerId: Long, categoryId: Long, limit: Int): Flow<List<Channel>>fun getChannelsByNumber(providerId: Long, categoryId: Long = ALL_CHANNELS_ID): Flow<List<Channel>>fun getChannelsWithoutErrors(providerId: Long, categoryId: Long = ALL_CHANNELS_ID): Flow<List<Channel>>fun searchChannelsByCategory(providerId: Long, categoryId: Long, query: String): Flow<List<Channel>>+ fun searchChannelsByCategoryPaged(providerId: Long, categoryId: Long, query: String, limit: Int): Flow<List<Channel>>fun getCategories(providerId: Long): Flow<List<Category>>fun searchChannels(providerId: Long, query: String): Flow<List<Channel>>suspend fun getChannel(channelId: Long): Channel?- suspend fun getStreamInfo(channel: Channel): Result<StreamInfo>+ suspend fun getStreamInfo(channel: Channel, preferStableUrl: Boolean = false): Result<StreamInfo>suspend fun refreshChannels(providerId: Long): Result<Unit>fun getChannelsByIds(ids: List<Long>): Flow<List<Channel>>suspend fun incrementChannelErrorCount(channelId: Long): Result<Unit>diff --git a/domain/src/main/java/com/streamvault/domain/repository/EpgRepository.kt b/domain/src/main/java/com/streamvault/domain/repository/EpgRepository.ktindex 2e1919d7..70ca3564 100644--- a/domain/src/main/java/com/streamvault/domain/repository/EpgRepository.kt+++ b/domain/src/main/java/com/streamvault/domain/repository/EpgRepository.kt@@ -7,6 +7,7 @@ import kotlinx.coroutines.flow.Flowinterface EpgRepository {fun getProgramsForChannel(providerId: Long, channelId: String, startTime: Long, endTime: Long): Flow<List<Program>>fun getProgramsForChannels(providerId: Long, channelIds: List<String>, startTime: Long, endTime: Long): Flow<Map<String, List<Program>>>+ suspend fun getProgramsForChannelsSnapshot(providerId: Long, channelIds: List<String>, startTime: Long, endTime: Long): Map<String, List<Program>>fun getProgramsByCategory(providerId: Long, categoryId: Long, startTime: Long, endTime: Long): Flow<List<Program>>fun searchPrograms(providerId: Long, query: String, startTime: Long, endTime: Long, categoryId: Long? = null, limit: Int = 250): Flow<List<Program>>fun getNowPlaying(providerId: Long, channelId: String): Flow<Program?>@@ -15,6 +16,7 @@ interface EpgRepository {fun getNowAndNext(providerId: Long, channelId: String): Flow<Pair<Program?, Program?>>suspend fun refreshEpg(providerId: Long, epgUrl: String): Result<Unit>suspend fun clearOldPrograms(beforeTime: Long)+ fun onProviderDeleted(providerId: Long)/** Returns resolved EPG programmes using multi-source resolution (external + provider-native). */suspend fun getResolvedProgramsForChannels(diff --git a/domain/src/main/java/com/streamvault/domain/repository/EpgSourceRepository.kt b/domain/src/main/java/com/streamvault/domain/repository/EpgSourceRepository.ktindex afd1922d..8c90a95b 100644--- a/domain/src/main/java/com/streamvault/domain/repository/EpgSourceRepository.kt+++ b/domain/src/main/java/com/streamvault/domain/repository/EpgSourceRepository.kt@@ -24,7 +24,8 @@ interface EpgSourceRepository {suspend fun deleteSource(id: Long)suspend fun setSourceEnabled(id: Long, enabled: Boolean)-+ /** Returns all provider IDs that have this source assigned, regardless of UI load state. */+ suspend fun getProviderIdsForSource(sourceId: Long): List<Long>// ── Provider ↔ Source assignment ───────────────────────────────fun getAssignmentsForProvider(providerId: Long): Flow<List<ProviderEpgSourceAssignment>>@@ -35,6 +36,15 @@ interface EpgSourceRepository {suspend fun updateAssignmentPriority(providerId: Long, epgSourceId: Long, priority: Int)+ /** Atomically swaps the priorities of two assignments within a single database transaction. */+ suspend fun swapAssignmentPriorities(+ providerId: Long,+ epgSourceId1: Long,+ newPriority1: Int,+ epgSourceId2: Long,+ newPriority2: Int+ )+// ── Refresh / Ingestion ────────────────────────────────────────suspend fun refreshSource(sourceId: Long): Result<Unit>diff --git a/domain/src/main/java/com/streamvault/domain/repository/FavoriteRepository.kt b/domain/src/main/java/com/streamvault/domain/repository/FavoriteRepository.ktindex 7bc7d6d6..6ccfc78c 100644--- a/domain/src/main/java/com/streamvault/domain/repository/FavoriteRepository.kt+++ b/domain/src/main/java/com/streamvault/domain/repository/FavoriteRepository.kt@@ -7,24 +7,29 @@ import com.streamvault.domain.model.VirtualGroupimport kotlinx.coroutines.flow.Flowinterface FavoriteRepository {- fun getFavorites(contentType: ContentType? = null): Flow<List<Favorite>>- @Deprecated("Use getFavorites(contentType) instead", replaceWith = ReplaceWith("getFavorites(contentType)"))- fun getAllFavorites(contentType: ContentType): Flow<List<Favorite>>+ fun getFavorites(providerId: Long, contentType: ContentType? = null): Flow<List<Favorite>>+ fun getFavorites(providerIds: List<Long>, contentType: ContentType? = null): Flow<List<Favorite>>+ @Deprecated(+ "Use getFavorites(providerId, contentType) instead",+ replaceWith = ReplaceWith("getFavorites(providerId, contentType)")+ )+ fun getAllFavorites(providerId: Long, contentType: ContentType): Flow<List<Favorite>>fun getFavoritesByGroup(groupId: Long): Flow<List<Favorite>>- fun getGroups(contentType: ContentType): Flow<List<VirtualGroup>>+ fun getGroups(providerId: Long, contentType: ContentType): Flow<List<VirtualGroup>>+ fun getGroups(providerIds: List<Long>, contentType: ContentType): Flow<List<VirtualGroup>>- fun getGlobalFavoriteCount(contentType: ContentType): Flow<Int>- fun getGroupFavoriteCounts(contentType: ContentType): Flow<Map<Long, Int>>+ fun getGlobalFavoriteCount(providerId: Long, contentType: ContentType): Flow<Int>+ fun getGroupFavoriteCounts(providerId: Long, contentType: ContentType): Flow<Map<Long, Int>>- suspend fun addFavorite(contentId: Long, contentType: ContentType, groupId: Long? = null): Result<Unit>- suspend fun removeFavorite(contentId: Long, contentType: ContentType, groupId: Long? = null): Result<Unit>+ suspend fun addFavorite(providerId: Long, contentId: Long, contentType: ContentType, groupId: Long? = null): Result<Unit>+ suspend fun removeFavorite(providerId: Long, contentId: Long, contentType: ContentType, groupId: Long? = null): Result<Unit>suspend fun reorderFavorites(favorites: List<Favorite>): Result<Unit>- suspend fun isFavorite(contentId: Long, contentType: ContentType): Boolean+ suspend fun isFavorite(providerId: Long, contentId: Long, contentType: ContentType): Boolean- suspend fun getGroupMemberships(contentId: Long, contentType: ContentType): List<Long>+ suspend fun getGroupMemberships(providerId: Long, contentId: Long, contentType: ContentType): List<Long>- suspend fun createGroup(name: String, iconEmoji: String? = null, contentType: ContentType): Result<VirtualGroup>+ suspend fun createGroup(providerId: Long, name: String, iconEmoji: String? = null, contentType: ContentType): Result<VirtualGroup>suspend fun deleteGroup(groupId: Long): Result<Unit>suspend fun renameGroup(groupId: Long, newName: String): Result<Unit>}diff --git a/domain/src/main/java/com/streamvault/domain/repository/PlaybackHistoryRepository.kt b/domain/src/main/java/com/streamvault/domain/repository/PlaybackHistoryRepository.ktindex a72b698c..b7e42b4c 100644--- a/domain/src/main/java/com/streamvault/domain/repository/PlaybackHistoryRepository.kt+++ b/domain/src/main/java/com/streamvault/domain/repository/PlaybackHistoryRepository.kt@@ -17,4 +17,5 @@ interface PlaybackHistoryRepository {suspend fun removeFromHistory(contentId: Long, contentType: ContentType, providerId: Long): Result<Unit>suspend fun clearAllHistory(): Result<Unit>suspend fun clearHistoryForProvider(providerId: Long): Result<Unit>+ suspend fun clearLiveHistoryForProvider(providerId: Long): Result<Unit>}diff --git a/domain/src/main/java/com/streamvault/domain/usecase/GetCustomCategories.kt b/domain/src/main/java/com/streamvault/domain/usecase/GetCustomCategories.ktindex d5978bfa..1cca555f 100644--- a/domain/src/main/java/com/streamvault/domain/usecase/GetCustomCategories.kt+++ b/domain/src/main/java/com/streamvault/domain/usecase/GetCustomCategories.kt@@ -2,10 +2,14 @@ package com.streamvault.domain.usecaseimport com.streamvault.domain.model.Categoryimport com.streamvault.domain.model.ContentType+import com.streamvault.domain.model.Favoriteimport com.streamvault.domain.model.VirtualCategoryIds+import com.streamvault.domain.model.VirtualGroupimport com.streamvault.domain.repository.FavoriteRepositoryimport kotlinx.coroutines.flow.Flowimport kotlinx.coroutines.flow.catch+import kotlinx.coroutines.flow.combine+import kotlinx.coroutines.flow.flowOfimport java.util.logging.Levelimport java.util.logging.Loggerimport javax.inject.Inject@@ -14,38 +18,62 @@ class GetCustomCategories @Inject constructor(private val favoriteRepository: FavoriteRepository) {private val logger = Logger.getLogger("GetCustomCategories")- operator fun invoke(contentType: ContentType = ContentType.LIVE): Flow<List<Category>> {- return kotlinx.coroutines.flow.combine(- favoriteRepository.getGroups(contentType),- favoriteRepository.getGlobalFavoriteCount(contentType),- favoriteRepository.getGroupFavoriteCounts(contentType)- ) { groups, globalCount, groupCounts ->- val categories = groups.map { group ->- Category(- id = -group.id, // Negative IDs reserve virtual groups.- name = group.name,- type = contentType,- isVirtual = true,- count = groupCounts.getOrDefault(group.id, 0)- )- }.toMutableList()-- // Prepend global "Favorites" virtual category.- categories.add(- index = 0,- element = Category(- id = VirtualCategoryIds.FAVORITES,- name = "Favorites",- type = contentType,- isVirtual = true,- count = globalCount- )- )+ operator fun invoke(providerId: Long, contentType: ContentType = ContentType.LIVE): Flow<List<Category>> =+ invoke(listOf(providerId), contentType)++ operator fun invoke(providerIds: List<Long>, contentType: ContentType = ContentType.LIVE): Flow<List<Category>> {+ if (providerIds.isEmpty()) {+ return flowOf(emptyList())+ }- categories.toList()+ return combine(+ favoriteRepository.getGroups(providerIds, contentType),+ favoriteRepository.getFavorites(providerIds, contentType)+ ) { groups, favorites ->+ buildCategories(+ groups = groups,+ favorites = favorites,+ contentType = contentType+ )}.catch { e ->logger.log(Level.WARNING, "Failed to load custom categories", e)emit(emptyList())}}++ private fun buildCategories(+ groups: List<VirtualGroup>,+ favorites: List<Favorite>,+ contentType: ContentType+ ): List<Category> {+ val groupCounts = favorites+ .asSequence()+ .mapNotNull(Favorite::groupId)+ .groupingBy { it }+ .eachCount()+ val globalCount = favorites.count { it.groupId == null }++ val categories = groups.map { group ->+ Category(+ id = -group.id,+ name = group.name,+ type = contentType,+ isVirtual = true,+ count = groupCounts.getOrDefault(group.id, 0)+ )+ }.toMutableList()++ categories.add(+ index = 0,+ element = Category(+ id = VirtualCategoryIds.FAVORITES,+ name = "Favorites",+ type = contentType,+ isVirtual = true,+ count = globalCount+ )+ )++ return categories.toList()+ }}diff --git a/domain/src/test/java/com/streamvault/domain/usecase/GetContinueWatchingTest.kt b/domain/src/test/java/com/streamvault/domain/usecase/GetContinueWatchingTest.ktindex ab3fca23..8f99b847 100644--- a/domain/src/test/java/com/streamvault/domain/usecase/GetContinueWatchingTest.kt+++ b/domain/src/test/java/com/streamvault/domain/usecase/GetContinueWatchingTest.kt@@ -120,5 +120,6 @@ class GetContinueWatchingTest {override suspend fun removeFromHistory(contentId: Long, contentType: ContentType, providerId: Long) = com.streamvault.domain.model.Result.success(Unit)override suspend fun clearAllHistory() = com.streamvault.domain.model.Result.success(Unit)override suspend fun clearHistoryForProvider(providerId: Long) = com.streamvault.domain.model.Result.success(Unit)+ override suspend fun clearLiveHistoryForProvider(providerId: Long) = com.streamvault.domain.model.Result.success(Unit)}}\ No newline at end of filediff --git a/domain/src/test/java/com/streamvault/domain/usecase/GetCustomCategoriesTest.kt b/domain/src/test/java/com/streamvault/domain/usecase/GetCustomCategoriesTest.ktnew file mode 100644index 00000000..d274039d--- /dev/null+++ b/domain/src/test/java/com/streamvault/domain/usecase/GetCustomCategoriesTest.kt@@ -0,0 +1,105 @@+package com.streamvault.domain.usecase++import com.google.common.truth.Truth.assertThat+import com.streamvault.domain.model.ContentType+import com.streamvault.domain.model.Favorite+import com.streamvault.domain.model.VirtualCategoryIds+import com.streamvault.domain.model.VirtualGroup+import com.streamvault.domain.repository.FavoriteRepository+import kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.flow.flowOf+import kotlinx.coroutines.test.runTest+import org.junit.Test++class GetCustomCategoriesTest {++ @Test+ fun mergesCustomCategoriesAcrossProviders() = runTest {+ val useCase = GetCustomCategories(+ favoriteRepository = FakeFavoriteRepository(+ favorites = listOf(+ Favorite(providerId = 1L, contentId = 101L, contentType = ContentType.LIVE, groupId = null),+ Favorite(providerId = 1L, contentId = 102L, contentType = ContentType.LIVE, groupId = 10L),+ Favorite(providerId = 2L, contentId = 201L, contentType = ContentType.LIVE, groupId = 20L),+ Favorite(providerId = 2L, contentId = 202L, contentType = ContentType.LIVE, groupId = 20L)+ ),+ groups = listOf(+ VirtualGroup(id = 10L, providerId = 1L, name = "Sports", contentType = ContentType.LIVE),+ VirtualGroup(id = 20L, providerId = 2L, name = "Kids", contentType = ContentType.LIVE)+ )+ )+ )++ val result = useCase(listOf(1L, 2L), ContentType.LIVE).first()++ assertThat(result).hasSize(3)+ assertThat(result[0].id).isEqualTo(VirtualCategoryIds.FAVORITES)+ assertThat(result[0].count).isEqualTo(1)+ assertThat(result.drop(1).map { it.name to it.count })+ .containsExactly("Sports" to 1, "Kids" to 2)+ }++ @Test+ fun returnsEmptyListForNoProviders() = runTest {+ val useCase = GetCustomCategories(FakeFavoriteRepository())++ val result = useCase(emptyList(), ContentType.LIVE).first()++ assertThat(result).isEmpty()+ }++ private class FakeFavoriteRepository(+ private val favorites: List<Favorite> = emptyList(),+ private val groups: List<VirtualGroup> = emptyList()+ ) : FavoriteRepository {+ override fun getFavorites(providerId: Long, contentType: ContentType?): Flow<List<Favorite>> =+ getFavorites(listOf(providerId), contentType)++ override fun getFavorites(providerIds: List<Long>, contentType: ContentType?): Flow<List<Favorite>> =+ flowOf(+ favorites.filter { favorite ->+ favorite.providerId in providerIds && (contentType == null || favorite.contentType == contentType)+ }+ )++ override fun getAllFavorites(providerId: Long, contentType: ContentType): Flow<List<Favorite>> =+ getFavorites(providerId, contentType)++ override fun getFavoritesByGroup(groupId: Long): Flow<List<Favorite>> =+ flowOf(favorites.filter { it.groupId == groupId })++ override fun getGroups(providerId: Long, contentType: ContentType): Flow<List<VirtualGroup>> =+ getGroups(listOf(providerId), contentType)++ override fun getGroups(providerIds: List<Long>, contentType: ContentType): Flow<List<VirtualGroup>> =+ flowOf(groups.filter { group -> group.providerId in providerIds && group.contentType == contentType })++ override fun getGlobalFavoriteCount(providerId: Long, contentType: ContentType): Flow<Int> =+ error("Not used in test")++ override fun getGroupFavoriteCounts(providerId: Long, contentType: ContentType): Flow<Map<Long, Int>> =+ error("Not used in test")++ override suspend fun addFavorite(providerId: Long, contentId: Long, contentType: ContentType, groupId: Long?) =+ error("Not used in test")++ override suspend fun removeFavorite(providerId: Long, contentId: Long, contentType: ContentType, groupId: Long?) =+ error("Not used in test")++ override suspend fun reorderFavorites(favorites: List<Favorite>) = error("Not used in test")++ override suspend fun isFavorite(providerId: Long, contentId: Long, contentType: ContentType): Boolean =+ error("Not used in test")++ override suspend fun getGroupMemberships(providerId: Long, contentId: Long, contentType: ContentType): List<Long> =+ error("Not used in test")++ override suspend fun createGroup(providerId: Long, name: String, iconEmoji: String?, contentType: ContentType) =+ error("Not used in test")++ override suspend fun deleteGroup(groupId: Long) = error("Not used in test")++ override suspend fun renameGroup(groupId: Long, newName: String) = error("Not used in test")+ }+}\ No newline at end of filediff --git a/domain/src/test/java/com/streamvault/domain/usecase/MarkAsWatchedTest.kt b/domain/src/test/java/com/streamvault/domain/usecase/MarkAsWatchedTest.ktindex ce6d1673..8fa35a8f 100644--- a/domain/src/test/java/com/streamvault/domain/usecase/MarkAsWatchedTest.kt+++ b/domain/src/test/java/com/streamvault/domain/usecase/MarkAsWatchedTest.kt@@ -61,5 +61,6 @@ class MarkAsWatchedTest {override suspend fun removeFromHistory(contentId: Long, contentType: ContentType, providerId: Long) = com.streamvault.domain.model.Result.success(Unit)override suspend fun clearAllHistory() = com.streamvault.domain.model.Result.success(Unit)override suspend fun clearHistoryForProvider(providerId: Long) = com.streamvault.domain.model.Result.success(Unit)+ override suspend fun clearLiveHistoryForProvider(providerId: Long) = com.streamvault.domain.model.Result.success(Unit)}}\ No newline at end of filediff --git a/domain/src/test/java/com/streamvault/domain/usecase/SearchContentTest.kt b/domain/src/test/java/com/streamvault/domain/usecase/SearchContentTest.ktindex 7f0f58d0..bdb5e752 100644--- a/domain/src/test/java/com/streamvault/domain/usecase/SearchContentTest.kt+++ b/domain/src/test/java/com/streamvault/domain/usecase/SearchContentTest.kt@@ -119,12 +119,14 @@ private class FakeChannelRepository(override fun searchChannels(providerId: Long, query: String): Flow<List<Channel>> = searchFlow ?: flowOf(searchResults)override fun getChannels(providerId: Long): Flow<List<Channel>> = unsupported()override fun getChannelsByCategory(providerId: Long, categoryId: Long): Flow<List<Channel>> = unsupported()+ override fun getChannelsByCategoryPage(providerId: Long, categoryId: Long, limit: Int): Flow<List<Channel>> = unsupported()override fun getChannelsByNumber(providerId: Long, categoryId: Long): Flow<List<Channel>> = unsupported()override fun getChannelsWithoutErrors(providerId: Long, categoryId: Long): Flow<List<Channel>> = unsupported()override fun searchChannelsByCategory(providerId: Long, categoryId: Long, query: String): Flow<List<Channel>> = unsupported()+ override fun searchChannelsByCategoryPaged(providerId: Long, categoryId: Long, query: String, limit: Int): Flow<List<Channel>> = unsupported()override fun getCategories(providerId: Long): Flow<List<Category>> = unsupported()override suspend fun getChannel(channelId: Long): Channel? = error("Not used in test")- override suspend fun getStreamInfo(channel: Channel): Result<StreamInfo> = error("Not used in test")+ override suspend fun getStreamInfo(channel: Channel, preferStableUrl: Boolean): Result<StreamInfo> = error("Not used in test")override suspend fun refreshChannels(providerId: Long): Result<Unit> = error("Not used in test")override fun getChannelsByIds(ids: List<Long>): Flow<List<Channel>> = unsupported()override suspend fun incrementChannelErrorCount(channelId: Long): Result<Unit> = error("Not used in test")diff --git a/player/src/main/java/com/streamvault/player/Media3PlayerEngine.kt b/player/src/main/java/com/streamvault/player/Media3PlayerEngine.ktindex ded3b3f9..e74bc63f 100644--- a/player/src/main/java/com/streamvault/player/Media3PlayerEngine.kt+++ b/player/src/main/java/com/streamvault/player/Media3PlayerEngine.kt@@ -3,6 +3,7 @@ package com.streamvault.playerimport android.content.Contextimport android.os.Handlerimport android.util.Log+import androidx.annotation.MainThreadimport androidx.annotation.OptInimport androidx.media3.common.AudioAttributes as Media3AudioAttributesimport androidx.media3.common.C@@ -57,6 +58,7 @@ import kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.Jobimport kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.cancelimport kotlinx.coroutines.delayimport kotlinx.coroutines.flow.collectLatestimport kotlinx.coroutines.flow.Flow@@ -85,6 +87,7 @@ class Media3PlayerEngine @Inject constructor(field = valueaudioFocusController.bypassAudioFocus = value}+ var mediaSessionId: String = "streamvault-main"var enableMediaSession: Boolean = trueset(value) {if (field == value) return@@ -92,7 +95,9 @@ class Media3PlayerEngine @Inject constructor(if (value) {exoPlayer?.let { player ->if (mediaSession == null) {- mediaSession = MediaSession.Builder(context, player).build()+ mediaSession = MediaSession.Builder(context, player)+ .setId(mediaSessionId)+ .build()}}} else {@@ -101,7 +106,14 @@ class Media3PlayerEngine @Inject constructor(}}- private val scope = CoroutineScope(Dispatchers.Main.immediate + SupervisorJob())+ // All mutable engine state below is read/written on Dispatchers.Main.immediate+ // (the engine scope dispatcher). No @Volatile or synchronisation is needed as long+ // as the scope is not replaced with a different dispatcher in tests.+ //+ // scope is a var because release() cancels it to tear down dangling coroutines,+ // then creates a fresh one so the singleton engine remains usable on re-entry.+ private var scope = CoroutineScope(Dispatchers.Main.immediate + SupervisorJob())+ private setprivate var exoPlayer: ExoPlayer? = nullprivate var mediaSession: MediaSession? = nullprivate var requestedDecoderMode: DecoderMode = DecoderMode.AUTO@@ -113,9 +125,11 @@ class Media3PlayerEngine @Inject constructor(private var currentRetryPolicy: PlayerRetryPolicy? = nullprivate var currentRetryContext: PlaybackRetryContext? = nullprivate var playbackStarted = false+ private var prepareStartMs = 0Lprivate var retryAttempt = 0private var retryJob: Job? = nullprivate var retryGeneration = 0L+ private var currentBufferIsLive: Boolean? = nullprivate val _playbackState = MutableStateFlow(PlaybackState.IDLE)override val playbackState: StateFlow<PlaybackState> = _playbackState.asStateFlow()@@ -158,10 +172,14 @@ class Media3PlayerEngine @Inject constructor(override val availableSubtitleTracks: StateFlow<List<PlayerTrack>> = trackController.availableSubtitleTracksoverride val availableVideoTracks: StateFlow<List<PlayerTrack>> = trackController.availableVideoTracks+ private val _audioFocusDenied = MutableSharedFlow<Unit>(extraBufferCapacity = 1)+ override val audioFocusDenied: Flow<Unit> = _audioFocusDenied.asSharedFlow()+private val audioFocusController = PlayerAudioFocusController(context = context,applyVolume = { volume -> exoPlayer?.volume = volume },- setPlayWhenReady = { playWhenReady -> exoPlayer?.playWhenReady = playWhenReady }+ setPlayWhenReady = { playWhenReady -> exoPlayer?.playWhenReady = playWhenReady },+ onAudioFocusDenied = { _audioFocusDenied.tryEmit(Unit) }).also {it.bypassAudioFocus = bypassAudioFocus}@@ -172,7 +190,8 @@ class Media3PlayerEngine @Inject constructor(currentPosition = _currentPosition,duration = _duration,videoFormat = _videoFormat,- playerStats = _playerStats+ playerStats = _playerStats,+ playbackState = _playbackState).also {it.bind { exoPlayer }}@@ -181,9 +200,10 @@ class Media3PlayerEngine @Inject constructor(private val preloadCoordinator = PreloadCoordinator()private val compatibilityProfile: PlaybackCompatibilityProfile = DefaultPlaybackCompatibilityProfileprivate val decoderPreferencePolicy = DefaultDecoderPreferencePolicy()- private var activeLiveTimeshiftStreamInfo: StreamInfo? = null- private var activeLiveTimeshiftChannelKey: String? = null- private var isPlayingTimeshiftSnapshot: Boolean = false+ // All reads/writes on Dispatchers.Main.immediate (engine scope).+ @get:MainThread private var activeLiveTimeshiftStreamInfo: StreamInfo? = null+ @get:MainThread private var activeLiveTimeshiftChannelKey: String? = null+ @get:MainThread private var isPlayingTimeshiftSnapshot: Boolean = falseprivate var pendingTimeshiftSeekMs: Long? = nullprivate var pendingTimeshiftSeekToEnd: Boolean = falseprivate var pendingTimeshiftAutoPlay: Boolean = false@@ -201,6 +221,29 @@ class Media3PlayerEngine @Inject constructor(prepareInternal(streamInfo = streamInfo, preserveRetryState = false, seekPositionMs = null, autoPlay = true)}+ override fun renewStreamUrl(streamInfo: StreamInfo) {+ val player = exoPlayer ?: return+ val retryPolicy = currentRetryPolicy ?: return++ lastStreamInfo = streamInfo+ lastMediaId = mediaSourceFactory.mediaIdFor(streamInfo)++ val mediaSource = mediaSourceFactory.create(+ streamInfo = streamInfo,+ resolvedStreamType = currentResolvedStreamType,+ retryPolicy = retryPolicy,+ preload = false+ ).second++ player.setMediaSource(mediaSource, /* resetPosition= */ false)+ player.prepare()++ Log.i(+ TAG,+ "renew-url resolvedStreamType=$currentResolvedStreamType target=${PlaybackLogSanitizer.sanitizeUrl(streamInfo.url)}"+ )+ }+override fun play() {if (audioFocusController.requestAudioFocusIfNeeded()) {exoPlayer?.playWhenReady = true@@ -233,6 +276,10 @@ class Media3PlayerEngine @Inject constructor(if (isPlayingTimeshiftSnapshot) {exoPlayer?.let { player ->val duration = player.duration+ if (duration != C.TIME_UNSET && player.currentPosition + ms >= duration) {+ seekToLiveEdge()+ return+ }val newPosition = if (duration != C.TIME_UNSET) {(player.currentPosition + ms).coerceAtMost(duration)} else {@@ -293,6 +340,7 @@ class Media3PlayerEngine @Inject constructor(exoPlayer?.playbackParameters = PlaybackParameters(clamped)}+ @MainThreadoverride fun startLiveTimeshift(streamInfo: StreamInfo, channelKey: String, config: TimeshiftConfig) {activeLiveTimeshiftStreamInfo = streamInfoactiveLiveTimeshiftChannelKey = channelKey@@ -302,6 +350,7 @@ class Media3PlayerEngine @Inject constructor(}}+ @MainThreadoverride fun stopLiveTimeshift() {val wasSnapshot = isPlayingTimeshiftSnapshotval liveInfo = activeLiveTimeshiftStreamInfo@@ -311,6 +360,10 @@ class Media3PlayerEngine @Inject constructor(pendingTimeshiftSeekMs = nullpendingTimeshiftSeekToEnd = falsependingTimeshiftAutoPlay = false+ if (wasSnapshot) {+ exoPlayer?.stop()+ exoPlayer?.clearMediaItems()+ }scope.launch {liveTimeshiftManager.stopSession()if (wasSnapshot && liveInfo != null) {@@ -320,14 +373,23 @@ class Media3PlayerEngine @Inject constructor(}}+ @MainThreadoverride fun seekToLiveEdge() {val liveInfo = activeLiveTimeshiftStreamInfo ?: return+ val wasSnapshot = isPlayingTimeshiftSnapshotisPlayingTimeshiftSnapshot = falsependingTimeshiftSeekMs = nullpendingTimeshiftSeekToEnd = falsependingTimeshiftAutoPlay = false+ if (wasSnapshot) {+ exoPlayer?.stop()+ exoPlayer?.clearMediaItems()+ }prepareInternal(liveInfo, preserveRetryState = false, seekPositionMs = null, autoPlay = true)syncTimeshiftState()+ if (wasSnapshot) {+ scope.launch { liveTimeshiftManager.releaseRetiredSnapshots() }+ }}override fun pauseTimeshift() {@@ -423,9 +485,6 @@ class Media3PlayerEngine @Inject constructor(}override fun release() {- scope.launch {- liveTimeshiftManager.stopSession()- }retryJob?.cancel()retryJob = nullpreloadCoordinator.release()@@ -452,6 +511,17 @@ class Media3PlayerEngine @Inject constructor(activeLiveTimeshiftChannelKey = nullisPlayingTimeshiftSnapshot = false_timeshiftState.value = LiveTimeshiftState()+ scope.cancel()+ // Replace with a fresh scope so the singleton engine remains functional on re-entry.+ scope = CoroutineScope(Dispatchers.Main.immediate + SupervisorJob())+ // Re-launch the timeshift state collector on the new scope.+ scope.launch {+ liveTimeshiftManager.state.collectLatest {+ syncTimeshiftState()+ }+ }+ // File cleanup runs outside the engine scope — orphans are also cleaned on next app start+ CoroutineScope(Dispatchers.IO).launch { liveTimeshiftManager.stopSession() }}private fun prepareInternal(@@ -474,6 +544,7 @@ class Media3PlayerEngine @Inject constructor(}lastMediaId = mediaIdplaybackStarted = false+ prepareStartMs = System.currentTimeMillis()_error.tryEmit(null)_mediaTitle.value = nulltrackController.resetSelections()@@ -485,8 +556,13 @@ class Media3PlayerEngine @Inject constructor(currentRetryPolicy = PlayerRetryPolicy(currentRetryContext!!) { playbackStarted }val preferredDecoderMode = decoderPreferencePolicy.preferredMode(requestedDecoderMode, mediaId)- if (activeDecoderMode != preferredDecoderMode) {- activeDecoderMode = preferredDecoderMode+ val isLiveBuffer = currentResolvedStreamType in setOf(+ ResolvedStreamType.HLS, ResolvedStreamType.MPEG_TS_LIVE, ResolvedStreamType.RTSP+ )+ val needsRecreate = activeDecoderMode != preferredDecoderMode || isLiveBuffer != currentBufferIsLive+ activeDecoderMode = preferredDecoderMode+ currentBufferIsLive = isLiveBuffer+ if (needsRecreate) {recreatePlayer()}@@ -510,7 +586,28 @@ class Media3PlayerEngine @Inject constructor(player.setMediaSource(mediaSource)player.prepare()seekPositionMs?.takeIf { it > 0L }?.let(player::seekTo)- player.playWhenReady = autoPlay && audioFocusController.requestAudioFocusIfNeeded()++ val isLive = currentResolvedStreamType in setOf(+ ResolvedStreamType.HLS, ResolvedStreamType.MPEG_TS_LIVE, ResolvedStreamType.RTSP+ )+ val osContentType = if (isLive) {+ android.media.AudioAttributes.CONTENT_TYPE_MUSIC+ } else {+ android.media.AudioAttributes.CONTENT_TYPE_MOVIE+ }+ val media3ContentType = if (isLive) C.AUDIO_CONTENT_TYPE_MUSIC else C.AUDIO_CONTENT_TYPE_MOVIE+ player.setAudioAttributes(+ Media3AudioAttributes.Builder()+ .setUsage(C.USAGE_MEDIA)+ .setContentType(media3ContentType)+ .build(),+ false+ )+ val focusGranted = audioFocusController.requestAudioFocusIfNeeded(osContentType)+ player.playWhenReady = autoPlay && focusGranted+ if (autoPlay && !focusGranted) {+ _audioFocusDenied.tryEmit(Unit)+ }viewBinder.attachPlayer(player)}@@ -534,17 +631,20 @@ class Media3PlayerEngine @Inject constructor(statsCollector.bind { exoPlayer }audioFocusController.reapplyVolume()if (enableMediaSession) {- mediaSession = MediaSession.Builder(context, player).build()+ mediaSession = MediaSession.Builder(context, player)+ .setId(mediaSessionId)+ .build()}}}private fun createPlayer(): ExoPlayer {val renderersFactory = buildRenderersFactory()+ val maxBufferMs = if (currentBufferIsLive == true) 30_000 else 120_000val loadControl = DefaultLoadControl.Builder().setBufferDurationsMs(30_000,- 90_000,+ maxBufferMs,2_500,10_000)@@ -695,6 +795,10 @@ class Media3PlayerEngine @Inject constructor(output: Any,renderTimeMs: Long) {+ if (prepareStartMs > 0L) {+ val ttff = System.currentTimeMillis() - prepareStartMs+ _playerStats.value = _playerStats.value.copy(ttffMs = ttff)+ }markPlaybackStarted("first-frame-success")}}@@ -719,7 +823,7 @@ class Media3PlayerEngine @Inject constructor(if (isPlayingTimeshiftSnapshot && pendingTimeshiftSeekToEnd) {pendingTimeshiftSeekToEnd = falseplayerOrNull()?.duration?.takeIf { it > 0L && it != C.TIME_UNSET }?.let { duration ->- playerOrNull()?.seekTo(duration)+ playerOrNull()?.seekTo((duration - 200L).coerceAtLeast(0L))}} else if (isPlayingTimeshiftSnapshot) {pendingTimeshiftSeekMs?.let { target ->@@ -784,12 +888,14 @@ class Media3PlayerEngine @Inject constructor(syncTimeshiftState(messageOverride = "Local live rewind is still buffering.")return@launch}+ if (activeLiveTimeshiftStreamInfo !== liveInfo) return@launchisPlayingTimeshiftSnapshot = truependingTimeshiftSeekMs = positionMspendingTimeshiftSeekToEnd = seekToEndpendingTimeshiftAutoPlay = autoPlayval snapshotInfo = liveInfo.copy(url = snapshot.url, streamType = inferSnapshotStreamType(snapshot.url))prepareInternal(snapshotInfo, preserveRetryState = false, seekPositionMs = null, autoPlay = autoPlay)+ liveTimeshiftManager.releaseRetiredSnapshots()syncTimeshiftState()}}@@ -822,7 +928,7 @@ class Media3PlayerEngine @Inject constructor(else -> LiveTimeshiftStatus.LIVE}_timeshiftState.value = managerState.copy(- backend = if (managerState.backend == LiveTimeshiftBackend.NONE) managerState.backend else managerState.backend,+ backend = managerState.backend,status = status,liveEdgePositionMs = managerState.liveEdgePositionMs,currentOffsetFromLiveMs = offsetFromLive,@@ -913,6 +1019,9 @@ class Media3PlayerEngine @Inject constructor(val nextAttempt = retryAttempt + 1if (retryPolicy.shouldRetry(error, retryContext, playbackStarted, nextAttempt)) {val delayMs = retryPolicy.retryDelayMs(error, nextAttempt)+ // retryGeneration captured and checked on Main — safe with+ // Dispatchers.Main.immediate. If the scope dispatcher is ever changed+ // (e.g. in tests), convert retryGeneration to AtomicLong.val scheduledRetryGeneration = retryGenerationretryAttempt = nextAttempt_retryStatus.value = PlayerRetryStatus(@@ -934,10 +1043,12 @@ class Media3PlayerEngine @Inject constructor(return@launch}retryJob = null- if (category == PlaybackErrorCategory.LIVE_WINDOW) {+ if (category == PlaybackErrorCategory.LIVE_WINDOW &&+ currentResolvedStreamType != ResolvedStreamType.MPEG_TS_LIVE+ ) {exoPlayer?.seekToDefaultPosition()}- prepareInternal(streamInfo, preserveRetryState = true, seekPositionMs = null, autoPlay = true)+ prepareInternal(streamInfo, preserveRetryState = category != PlaybackErrorCategory.LIVE_WINDOW, seekPositionMs = null, autoPlay = true)}return}diff --git a/player/src/main/java/com/streamvault/player/PlayerEngine.kt b/player/src/main/java/com/streamvault/player/PlayerEngine.ktindex e5ed6d35..5773b32b 100644--- a/player/src/main/java/com/streamvault/player/PlayerEngine.kt+++ b/player/src/main/java/com/streamvault/player/PlayerEngine.kt@@ -7,8 +7,12 @@ import com.streamvault.domain.model.DrmSchemeimport com.streamvault.domain.model.StreamInfoimport com.streamvault.domain.model.VideoFormatimport androidx.media3.common.PlaybackException+import androidx.media3.datasource.HttpDataSourceimport com.streamvault.player.playback.PlaybackErrorCategoryimport com.streamvault.player.playback.PlayerErrorClassifier+import java.net.ConnectException+import java.net.SocketTimeoutException+import java.net.UnknownHostExceptionimport com.streamvault.player.timeshift.LiveTimeshiftStateimport com.streamvault.player.timeshift.TimeshiftConfigimport kotlinx.coroutines.flow.Flow@@ -41,6 +45,7 @@ interface PlayerEngine {val mediaTitle: StateFlow<String?>fun prepare(streamInfo: StreamInfo)+ fun renewStreamUrl(streamInfo: StreamInfo)fun play()fun pause()fun stop()@@ -69,6 +74,9 @@ interface PlayerEngine {fun toggleMute()val isMuted: StateFlow<Boolean>+ /** Emits when audio focus is denied (e.g., device muted at OS level). */+ val audioFocusDenied: Flow<Unit>+/*** Enable scrubbing mode for rapid switching (channel zapping).* While enabled, the player skips re-buffering and favours lowest-latency@@ -117,7 +125,8 @@ data class PlayerStats(val height: Int = 0,val bandwidthEstimate: Long = 0,val bufferedDurationMs: Long = 0,- val rebufferCount: Int = 0+ val rebufferCount: Int = 0,+ val ttffMs: Long = 0)sealed class PlayerError(val message: String) {@@ -129,8 +138,27 @@ sealed class PlayerError(val message: String) {companion object {fun fromException(e: Throwable): PlayerError {- val msg = e.message ?: "Unknown playback error"- return when (PlayerErrorClassifier.classify(e)) {+ val category = PlayerErrorClassifier.classify(e)+ val chain = generateSequence(e) { it.cause }.toList()+ val msg = when (category) {+ PlaybackErrorCategory.DECODER,+ PlaybackErrorCategory.FORMAT_UNSUPPORTED -> buildCodecErrorMessage(e)+ PlaybackErrorCategory.NETWORK -> buildNetworkErrorMessage(chain)+ PlaybackErrorCategory.HTTP_AUTH -> buildHttpErrorMessage(chain, "Access denied")+ PlaybackErrorCategory.HTTP_SERVER -> buildHttpErrorMessage(chain, "Server error")+ PlaybackErrorCategory.SSL -> "Secure connection failed (SSL/TLS error)."+ PlaybackErrorCategory.CLEAR_TEXT_BLOCKED ->+ "This stream requires a secure (HTTPS) connection."+ PlaybackErrorCategory.SOURCE_MALFORMED ->+ "Unable to parse this stream format."+ PlaybackErrorCategory.LIVE_WINDOW ->+ "Live stream position expired."+ PlaybackErrorCategory.DRM -> buildDrmErrorMessage(chain)+ PlaybackErrorCategory.UNKNOWN ->+ chain.firstNotNullOfOrNull { it.takeIf { it !is PlaybackException }?.message }+ ?: "Unknown playback error"+ }+ return when (category) {PlaybackErrorCategory.NETWORK,PlaybackErrorCategory.HTTP_SERVER,PlaybackErrorCategory.HTTP_AUTH,@@ -147,5 +175,63 @@ sealed class PlayerError(val message: String) {PlaybackErrorCategory.UNKNOWN -> UnknownError(msg)}}++ private fun buildCodecErrorMessage(e: Throwable): String {+ val chain = generateSequence(e) { it.cause }.toList()+ val decoderEx = chain+ .filterIsInstance<androidx.media3.exoplayer.mediacodec.MediaCodecRenderer.DecoderInitializationException>()+ .firstOrNull()+ if (decoderEx != null) {+ val mime = decoderEx.mimeType+ val codecLabel = when (mime) {+ "video/hevc" -> "H.265/HEVC"+ "video/av01" -> "AV1"+ "video/avc" -> "H.264/AVC"+ "video/x-vnd.on2.vp9", "video/vp9" -> "VP9"+ "audio/ac3" -> "AC-3 (Dolby Digital)"+ "audio/eac3" -> "E-AC-3 (Dolby Digital Plus)"+ "audio/mp4a-latm", "audio/mp4a" -> "AAC"+ else -> mime+ }+ val codecInfo = decoderEx.codecInfo+ return if (codecInfo != null) {+ "Codec $codecLabel is not supported by decoder ${codecInfo.name} on this device."+ } else {+ "No decoder available for codec $codecLabel on this device."+ }+ }+ return e.message ?: "Unsupported media format."+ }++ private fun buildNetworkErrorMessage(chain: List<Throwable>): String = when {+ chain.any { it is SocketTimeoutException } -> "Connection timed out."+ chain.any { it is UnknownHostException } -> "Server not found — check your network connection."+ chain.any { it is ConnectException } -> "Could not connect to server."+ else -> "Network error — check your internet connection."+ }++ private fun buildHttpErrorMessage(chain: List<Throwable>, label: String): String {+ val httpCode = chain+ .filterIsInstance<HttpDataSource.InvalidResponseCodeException>()+ .firstOrNull()?.responseCode+ return if (httpCode != null) "$label (HTTP $httpCode)." else "$label."+ }++ private fun buildDrmErrorMessage(chain: List<Throwable>): String {+ val playbackEx = chain.filterIsInstance<PlaybackException>().firstOrNull()+ return when (playbackEx?.errorCode) {+ PlaybackException.ERROR_CODE_DRM_LICENSE_ACQUISITION_FAILED ->+ "DRM license could not be obtained."+ PlaybackException.ERROR_CODE_DRM_LICENSE_EXPIRED ->+ "DRM license has expired."+ PlaybackException.ERROR_CODE_DRM_SCHEME_UNSUPPORTED ->+ "DRM scheme is not supported on this device."+ PlaybackException.ERROR_CODE_DRM_DEVICE_REVOKED ->+ "This device has been revoked for DRM playback."+ PlaybackException.ERROR_CODE_DRM_PROVISIONING_FAILED ->+ "DRM provisioning failed."+ else -> "DRM error — this content may require a license."+ }+ }}}diff --git a/player/src/main/java/com/streamvault/player/StreamTypeDetector.kt b/player/src/main/java/com/streamvault/player/StreamTypeDetector.ktindex 012083e0..ece39d8c 100644--- a/player/src/main/java/com/streamvault/player/StreamTypeDetector.kt+++ b/player/src/main/java/com/streamvault/player/StreamTypeDetector.kt@@ -12,6 +12,7 @@ object StreamTypeDetector {ResolvedStreamType.DASH -> StreamType.DASHResolvedStreamType.MPEG_TS_LIVE -> StreamType.MPEG_TSResolvedStreamType.PROGRESSIVE -> StreamType.PROGRESSIVE+ ResolvedStreamType.RTSP -> StreamType.RTSPResolvedStreamType.UNKNOWN -> StreamType.UNKNOWN}}diff --git a/player/src/main/java/com/streamvault/player/audio/PlayerAudioFocusController.kt b/player/src/main/java/com/streamvault/player/audio/PlayerAudioFocusController.ktindex b4b32834..b00d6bc2 100644--- a/player/src/main/java/com/streamvault/player/audio/PlayerAudioFocusController.kt+++ b/player/src/main/java/com/streamvault/player/audio/PlayerAudioFocusController.kt@@ -11,7 +11,8 @@ import kotlinx.coroutines.flow.asStateFlowclass PlayerAudioFocusController(context: Context,private val applyVolume: (Float) -> Unit,- private val setPlayWhenReady: (Boolean) -> Unit+ private val setPlayWhenReady: (Boolean) -> Unit,+ private val onAudioFocusDenied: (() -> Unit)? = null) {private val audioManager = context.getSystemService(Context.AUDIO_SERVICE) as AudioManagerprivate var audioFocusRequest: AudioFocusRequest? = null@@ -20,10 +21,15 @@ class PlayerAudioFocusController(private var isDucked = falseprivate var currentVolume = 1fprivate var volumeBeforeMute = 1f+ private var currentOsContentType = android.media.AudioAttributes.CONTENT_TYPE_MOVIEprivate val _isMuted = MutableStateFlow(false)val isMuted: StateFlow<Boolean> = _isMuted.asStateFlow()+ // Volatile for visibility: set from the engine constructor (Main) and read by+ // audioFocusChangeListener (also delivered on Main). @Volatile is defensive; the+ // current call-site guarantees Main-thread-only access via Hilt constructor sequencing.+ @Volatilevar bypassAudioFocus: Boolean = falseprivate val audioFocusChangeListener = AudioManager.OnAudioFocusChangeListener { focusChange ->@@ -61,12 +67,20 @@ class PlayerAudioFocusController(}}- fun requestAudioFocusIfNeeded(): Boolean {+ fun requestAudioFocusIfNeeded(+ osContentType: Int = currentOsContentType+ ): Boolean {if (bypassAudioFocus || hasAudioFocus) {isDucked = falsedispatchVolume()return true}+ if (osContentType != currentOsContentType) {+ currentOsContentType = osContentType+ audioFocusRequest?.let(audioManager::abandonAudioFocusRequest)+ audioFocusRequest = null+ hasAudioFocus = false+ }val request = audioFocusRequest ?: buildAudioFocusRequest().also { audioFocusRequest = it }val granted = audioManager.requestAudioFocus(request) == AudioManager.AUDIOFOCUS_REQUEST_GRANTEDhasAudioFocus = granted@@ -112,6 +126,14 @@ class PlayerAudioFocusController(if (currentVolume <= 0f) {currentVolume = volumeBeforeMute.coerceIn(0.1f, 1f)}+ // Re-request audio focus on unmute to unblock playback if focus was previously denied+ if (!hasAudioFocus && !bypassAudioFocus) {+ if (requestAudioFocusIfNeeded()) {+ setPlayWhenReady(true)+ } else {+ onAudioFocusDenied?.invoke()+ }+ }}dispatchVolume()}@@ -149,7 +171,7 @@ class PlayerAudioFocusController(private fun buildAudioFocusRequest(): AudioFocusRequest {val attributes = android.media.AudioAttributes.Builder().setUsage(android.media.AudioAttributes.USAGE_MEDIA)- .setContentType(android.media.AudioAttributes.CONTENT_TYPE_MOVIE)+ .setContentType(currentOsContentType).build()return AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN).setAudioAttributes(attributes)diff --git a/player/src/main/java/com/streamvault/player/playback/PlayerMediaSourceFactory.kt b/player/src/main/java/com/streamvault/player/playback/PlayerMediaSourceFactory.ktindex d1942422..db7f4fe8 100644--- a/player/src/main/java/com/streamvault/player/playback/PlayerMediaSourceFactory.kt+++ b/player/src/main/java/com/streamvault/player/playback/PlayerMediaSourceFactory.kt@@ -2,10 +2,13 @@ package com.streamvault.player.playbackimport android.net.Uriimport android.util.Log+import androidx.media3.common.Formatimport androidx.media3.common.MediaItem+import androidx.media3.common.MimeTypesimport androidx.media3.common.util.UnstableApiimport androidx.media3.datasource.DataSourceimport androidx.media3.extractor.DefaultExtractorsFactory+import androidx.media3.extractor.ts.DefaultTsPayloadReaderFactoryimport androidx.media3.exoplayer.dash.DashMediaSourceimport androidx.media3.exoplayer.hls.HlsMediaSourceimport androidx.media3.exoplayer.rtsp.RtspMediaSource@@ -36,7 +39,8 @@ class PlayerMediaSourceFactory()val mediaItem = buildMediaItem(streamInfo)val mediaSource = when {- streamInfo.streamType == StreamType.RTSP -> RtspMediaSource.Factory().createMediaSource(mediaItem)+ streamInfo.streamType == StreamType.RTSP || resolvedStreamType == ResolvedStreamType.RTSP ->+ RtspMediaSource.Factory().createMediaSource(mediaItem)resolvedStreamType == ResolvedStreamType.HLS -> HlsMediaSource.Factory(dataSourceFactory).setAllowChunklessPreparation(true).setLoadErrorHandlingPolicy(retryPolicy)@@ -48,7 +52,13 @@ class PlayerMediaSourceFactory(resolvedStreamType == ResolvedStreamType.MPEG_TS_LIVE -> ProgressiveMediaSource.Factory(dataSourceFactory,- DefaultExtractorsFactory().setTsExtractorFlags(0)+ DefaultExtractorsFactory()+ .setTsExtractorFlags(+ DefaultTsPayloadReaderFactory.FLAG_DETECT_ACCESS_UNITS+ or DefaultTsPayloadReaderFactory.FLAG_ALLOW_NON_IDR_KEYFRAMES+ or DefaultTsPayloadReaderFactory.FLAG_IGNORE_SPLICE_INFO_STREAM+ )+ .setTsSubtitleFormats(TS_SUBTITLE_FORMATS)).setLoadErrorHandlingPolicy(retryPolicy).createMediaSource(mediaItem)@@ -57,7 +67,16 @@ class PlayerMediaSourceFactory(.setLoadErrorHandlingPolicy(retryPolicy).createMediaSource(mediaItem)- else -> DefaultMediaSourceFactory(dataSourceFactory)+ else -> DefaultMediaSourceFactory(+ dataSourceFactory,+ DefaultExtractorsFactory()+ .setTsExtractorFlags(+ DefaultTsPayloadReaderFactory.FLAG_DETECT_ACCESS_UNITS+ or DefaultTsPayloadReaderFactory.FLAG_ALLOW_NON_IDR_KEYFRAMES+ or DefaultTsPayloadReaderFactory.FLAG_IGNORE_SPLICE_INFO_STREAM+ )+ .setTsSubtitleFormats(TS_SUBTITLE_FORMATS)+ ).setLoadErrorHandlingPolicy(retryPolicy).createMediaSource(mediaItem)}@@ -96,7 +115,7 @@ class PlayerMediaSourceFactory(fun mediaIdFor(streamInfo: StreamInfo): String {val drmKey = streamInfo.drmInfo?.let { "${it.scheme}:${it.licenseUrl}" }.orEmpty()- return "${streamInfo.url}|${streamInfo.title.orEmpty()}|$drmKey".hashCode().toString()+ return stableHash("${streamInfo.url}|${streamInfo.title.orEmpty()}|$drmKey")}private fun DrmScheme.toUuid(): UUID = when (this) {@@ -107,6 +126,16 @@ class PlayerMediaSourceFactory(companion object {private const val TAG = "PlayerMediaSourceFactory"++ /** Explicit CEA-608 and CEA-708 closed caption formats for MPEG-TS streams. */+ private val TS_SUBTITLE_FORMATS: List<Format> = listOf(+ Format.Builder().setSampleMimeType(MimeTypes.APPLICATION_CEA608).build(),+ Format.Builder()+ .setSampleMimeType(MimeTypes.APPLICATION_CEA708)+ .setCodecs("cea-708")+ .setAccessibilityChannel(1)+ .build()+ )}}diff --git a/player/src/main/java/com/streamvault/player/playback/PlayerRetryPolicy.kt b/player/src/main/java/com/streamvault/player/playback/PlayerRetryPolicy.ktindex 8c441975..a7757f5c 100644--- a/player/src/main/java/com/streamvault/player/playback/PlayerRetryPolicy.kt+++ b/player/src/main/java/com/streamvault/player/playback/PlayerRetryPolicy.kt@@ -17,7 +17,7 @@ data class PlaybackRetryContext(val timeoutProfile: PlayerTimeoutProfile) {val isLive: Boolean- get() = resolvedStreamType == ResolvedStreamType.HLS || resolvedStreamType == ResolvedStreamType.MPEG_TS_LIVE+ get() = resolvedStreamType == ResolvedStreamType.HLS || resolvedStreamType == ResolvedStreamType.MPEG_TS_LIVE || resolvedStreamType == ResolvedStreamType.RTSP}@UnstableApidiff --git a/player/src/main/java/com/streamvault/player/playback/PlayerTimeoutProfile.kt b/player/src/main/java/com/streamvault/player/playback/PlayerTimeoutProfile.ktindex 4b14fd29..5be8e89b 100644--- a/player/src/main/java/com/streamvault/player/playback/PlayerTimeoutProfile.kt+++ b/player/src/main/java/com/streamvault/player/playback/PlayerTimeoutProfile.kt@@ -40,6 +40,7 @@ enum class PlayerTimeoutProfile(return when {resolvedStreamType == ResolvedStreamType.HLS -> LIVEresolvedStreamType == ResolvedStreamType.MPEG_TS_LIVE -> LIVE+ resolvedStreamType == ResolvedStreamType.RTSP -> LIVEresolvedStreamType == ResolvedStreamType.PROGRESSIVE -> PROGRESSIVEstreamInfo.streamType == StreamType.PROGRESSIVE -> PROGRESSIVEelse -> VODdiff --git a/player/src/main/java/com/streamvault/player/playback/PreloadCoordinator.kt b/player/src/main/java/com/streamvault/player/playback/PreloadCoordinator.ktindex 534deaa1..537ef28b 100644--- a/player/src/main/java/com/streamvault/player/playback/PreloadCoordinator.kt+++ b/player/src/main/java/com/streamvault/player/playback/PreloadCoordinator.kt@@ -130,12 +130,7 @@ class PreloadCoordinator(return stableHash(canonical)}- /** SHA-256 fingerprint truncated to 16 hex chars — stable across JVM restarts. */- private fun stableHash(input: String): String {- val digest = java.security.MessageDigest.getInstance("SHA-256")- .digest(input.toByteArray(Charsets.UTF_8))- return digest.take(8).joinToString("") { "%02x".format(it) }- }+companion object {private const val TAG = "PreloadCoordinator"diff --git a/player/src/main/java/com/streamvault/player/playback/StableHash.kt b/player/src/main/java/com/streamvault/player/playback/StableHash.ktnew file mode 100644index 00000000..fa98a798--- /dev/null+++ b/player/src/main/java/com/streamvault/player/playback/StableHash.kt@@ -0,0 +1,13 @@+package com.streamvault.player.playback++import java.security.MessageDigest++// Cached instance — safe because all callers (PreloadCoordinator) are Main-thread-only.+private val sha256: MessageDigest = MessageDigest.getInstance("SHA-256")++/** SHA-256 fingerprint truncated to 16 hex chars — stable across JVM restarts. */+internal fun stableHash(input: String): String {+ sha256.reset()+ val digest = sha256.digest(input.toByteArray(Charsets.UTF_8))+ return digest.take(8).joinToString("") { "%02x".format(it) }+}diff --git a/player/src/main/java/com/streamvault/player/playback/StreamTypeResolver.kt b/player/src/main/java/com/streamvault/player/playback/StreamTypeResolver.ktindex 167e0ca0..d14d74cd 100644--- a/player/src/main/java/com/streamvault/player/playback/StreamTypeResolver.kt+++ b/player/src/main/java/com/streamvault/player/playback/StreamTypeResolver.kt@@ -10,6 +10,7 @@ enum class ResolvedStreamType {DASH,PROGRESSIVE,MPEG_TS_LIVE,+ RTSP,UNKNOWN}@@ -30,6 +31,7 @@ object StreamTypeResolver {StreamType.DASH -> ResolvedStreamType.DASHStreamType.MPEG_TS -> ResolvedStreamType.MPEG_TS_LIVEStreamType.PROGRESSIVE -> ResolvedStreamType.PROGRESSIVE+ StreamType.RTSP -> ResolvedStreamType.RTSPelse -> resolve(url = streamInfo.url, mimeType = mimeType, isLive = isLive(streamInfo))}}@@ -49,6 +51,7 @@ object StreamTypeResolver {.lowercase(Locale.ROOT)val lastSegment = path.substringAfterLast('/').trim()return when {+ scheme in setOf("rtsp", "rtsps") -> ResolvedStreamType.RTSPscheme in setOf("file", "content") && path.endsWith(".m3u8") -> ResolvedStreamType.HLSscheme in setOf("file", "content") -> ResolvedStreamType.PROGRESSIVEnormalizedMimeType != null && hlsMimeHints.any(normalizedMimeType::contains) -> ResolvedStreamType.HLSdiff --git a/player/src/main/java/com/streamvault/player/stats/PlayerStatsCollector.kt b/player/src/main/java/com/streamvault/player/stats/PlayerStatsCollector.ktindex 3e94c8ed..60644990 100644--- a/player/src/main/java/com/streamvault/player/stats/PlayerStatsCollector.kt+++ b/player/src/main/java/com/streamvault/player/stats/PlayerStatsCollector.kt@@ -3,6 +3,7 @@ package com.streamvault.player.statsimport androidx.media3.common.Formatimport androidx.media3.exoplayer.ExoPlayerimport com.streamvault.domain.model.VideoFormat+import com.streamvault.player.PlaybackStateimport com.streamvault.player.PlayerStatsimport kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.Dispatchers@@ -37,7 +38,8 @@ class PlayerStatsCollector(private val currentPosition: MutableStateFlow<Long>,private val duration: MutableStateFlow<Long>,private val videoFormat: MutableStateFlow<VideoFormat>,- private val playerStats: MutableStateFlow<PlayerStats>+ private val playerStats: MutableStateFlow<PlayerStats>,+ private val playbackState: MutableStateFlow<PlaybackState>) {// All fields are Main-thread-only. No @Volatile or AtomicInteger required.private var pollingJob: Job? = null@@ -116,9 +118,14 @@ class PlayerStatsCollector(val player = playerProvider?.invoke()if (player != null) {- // --- Tier 1: Position + duration (every tick) ------------------- currentPosition.value = player.currentPosition- duration.value = player.duration.coerceAtLeast(0L)+ // --- Tier 1: Position + duration (every tick, READY only) -----+ // During BUFFERING the position is stalled and live duration is+ // C.TIME_UNSET (-1), making every emit a no-op equality check.+ // Skipping avoids wasted CPU on the main thread.+ if (playbackState.value == PlaybackState.READY) {+ currentPosition.value = player.currentPosition+ duration.value = player.duration.coerceAtLeast(0L)+ }// --- Tier 2: Buffered duration (every 500 ms) ------------------if (ticksSinceBufferedUpdate >= BUFFERED_UPDATE_TICKS) {@@ -140,7 +147,8 @@ class PlayerStatsCollector(frameRate = lastFrameRate,bitrate = video?.bitrate?.takeIf { it > 0 } ?: 0,codecV = video?.sampleMimeType ?: video?.codecs,- codecA = audio?.sampleMimeType ?: audio?.codecs+ codecA = audio?.sampleMimeType ?: audio?.codecs,+ pixelWidthHeightRatio = video?.pixelWidthHeightRatio?.takeIf { it > 0f } ?: 1f)playerStats.value = playerStats.value.copy(videoCodec = video?.sampleMimeType ?: video?.codecsdiff --git a/player/src/main/java/com/streamvault/player/timeshift/LiveTimeshiftManager.kt b/player/src/main/java/com/streamvault/player/timeshift/LiveTimeshiftManager.ktindex d08f87ec..9553ce14 100644--- a/player/src/main/java/com/streamvault/player/timeshift/LiveTimeshiftManager.kt+++ b/player/src/main/java/com/streamvault/player/timeshift/LiveTimeshiftManager.kt@@ -1,6 +1,8 @@package com.streamvault.player.timeshift+import android.content.ComponentCallbacks2import android.content.Context+import android.content.res.Configurationimport com.streamvault.domain.model.StreamInfoimport com.streamvault.domain.model.StreamTypeimport dagger.hilt.android.qualifiers.ApplicationContext@@ -12,6 +14,8 @@ import java.util.Localeimport java.util.concurrent.atomic.AtomicLongimport javax.inject.Injectimport javax.inject.Singleton+import org.xmlpull.v1.XmlPullParser+import org.xmlpull.v1.XmlPullParserFactoryimport kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.Job@@ -22,7 +26,6 @@ import kotlinx.coroutines.ensureActiveimport kotlinx.coroutines.flow.MutableStateFlowimport kotlinx.coroutines.flow.StateFlowimport kotlinx.coroutines.flow.asStateFlow-import kotlinx.coroutines.isActiveimport kotlinx.coroutines.launchimport kotlinx.coroutines.sync.Muteximport kotlinx.coroutines.sync.withLock@@ -35,20 +38,47 @@ internal interface LiveTimeshiftManager {suspend fun startSession(streamInfo: StreamInfo, channelKey: String, config: TimeshiftConfig)suspend fun stopSession()suspend fun createSnapshot(): LiveTimeshiftSnapshot?+ suspend fun releaseRetiredSnapshots()}@Singletoninternal class DefaultLiveTimeshiftManager @Inject constructor(@param:ApplicationContext private val context: Context,private val okHttpClient: OkHttpClient-) : LiveTimeshiftManager {+) : LiveTimeshiftManager, ComponentCallbacks2 {++ init {+ context.registerComponentCallbacks(this)+ }++ override fun onTrimMemory(level: Int) {+ if (level >= ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL) {+ scope.launch {+ mutex.withLock {+ val session = activeSession ?: return@withLock+ if (session.backend == LiveTimeshiftBackend.MEMORY) {+ stopSessionLocked()+ _state.value = _state.value.copy(+ status = LiveTimeshiftStatus.FAILED,+ message = "Local rewind stopped: low memory."+ )+ }+ }+ }+ }+ }++ override fun onConfigurationChanged(newConfig: Configuration) = Unit+ override fun onLowMemory() = Unitprivate val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)private val mutex = Mutex()private val _state = MutableStateFlow(LiveTimeshiftState())override val state: StateFlow<LiveTimeshiftState> = _state.asStateFlow()+ private val diskManager = TimeshiftDiskManager(context)private var activeSession: Session? = null+ private val retiredSnapshotDirs = ArrayDeque<File>()override suspend fun startSession(streamInfo: StreamInfo, channelKey: String, config: TimeshiftConfig) {withContext(Dispatchers.IO) {@@ -70,12 +100,30 @@ internal class DefaultLiveTimeshiftManager @Inject constructor(}val backend = chooseBackend()val sessionDir = File(context.cacheDir, "timeshift/${channelKey.hashCode()}-${System.currentTimeMillis()}").apply { mkdirs() }++ // Crash-safe cleanup: delete all stale timeshift dirs from previous crashes/exits.+ diskManager.cleanupStaleDirectories(activeSessionDir = sessionDir)++ // Global budget guard: evict LRU stale dirs if needed, then hard-fail if still over.+ if (!diskManager.isWithinBudget()) {+ diskManager.evictLruUntilWithinBudget(activeSessionDir = sessionDir)+ if (!diskManager.isWithinBudget()) {+ sessionDir.deleteRecursively()+ _state.value = LiveTimeshiftState(+ enabled = true,+ supported = false,+ status = LiveTimeshiftStatus.FAILED,+ message = "Not enough storage for local live rewind (limit: ${diskManager.maxBudgetBytes / (1024 * 1024 * 1024)} GB)."+ )+ return@withLock+ }+ }val session = when (support.streamType) {StreamType.HLS -> HlsSession(streamInfo, config, backend, sessionDir)+ StreamType.DASH -> DashSession(streamInfo, config, backend, sessionDir)StreamType.MPEG_TS,StreamType.PROGRESSIVE,StreamType.UNKNOWN -> ProgressiveSession(streamInfo, config, backend, sessionDir)- StreamType.DASH,StreamType.RTSP -> null}if (session == null) {@@ -123,13 +171,34 @@ internal class DefaultLiveTimeshiftManager @Inject constructor(override suspend fun createSnapshot(): LiveTimeshiftSnapshot? {return withContext(Dispatchers.IO) {- mutex.withLock {- activeSession?.createSnapshot()+ // Hold the outer mutex only long enough to register the old snapshot as retired+ // and grab a reference to the active session. File I/O runs outside the lock+ // so startSession/stopSession are not blocked for hundreds of milliseconds.+ val session = mutex.withLock {+ val s = activeSession ?: return@withLock null+ s.activeSnapshotDir?.let { retiredSnapshotDirs.addLast(it) }+ s+ } ?: return@withContext null+ session.createSnapshot()+ }+ }++ override suspend fun releaseRetiredSnapshots() {+ withContext(Dispatchers.IO) {+ // Grab the list under the mutex, then release it before the potentially slow+ // deleteRecursively() calls so startSession/stopSession are not blocked.+ val dirs = mutex.withLock {+ val copy = retiredSnapshotDirs.toList()+ retiredSnapshotDirs.clear()+ copy}+ dirs.forEach { it.deleteRecursively() }}}private suspend fun stopSessionLocked() {+ retiredSnapshotDirs.forEach { it.deleteRecursively() }+ retiredSnapshotDirs.clear()activeSession?.stop()activeSession = null}@@ -151,7 +220,6 @@ internal class DefaultLiveTimeshiftManager @Inject constructor(val type = inferType(streamInfo)return when (type) {StreamType.RTSP -> SupportResult(false, "RTSP streams cannot use local rewind yet.", type)- StreamType.DASH -> SupportResult(false, "DASH local rewind is not available in this version.", type)else -> SupportResult(true, null, type)}}@@ -181,6 +249,8 @@ internal class DefaultLiveTimeshiftManager @Inject constructor(val sessionDir: File) {var job: Job? = null+ var activeSnapshotDir: File? = null+ val effectiveDepthMs: Long = config.effectiveDepthMs(backend)protected val sequence = AtomicLong(0L)protected val stateStartMs = System.currentTimeMillis()@@ -216,6 +286,16 @@ internal class DefaultLiveTimeshiftManager @Inject constructor(protected fun resolveRelativeUrl(baseUrl: String, value: String): String {return runCatching { URI(baseUrl).resolve(value).toString() }.getOrDefault(value)}++ protected fun checkDiskAndBudget() {+ val freeSpace = context.cacheDir.usableSpace+ if (freeSpace < MIN_FREE_DISK_BYTES) {+ throw IOException("Insufficient disk space for live rewind (${freeSpace / (1024 * 1024)} MB free, need 200 MB).")+ }+ if (!diskManager.isWithinBudget()) {+ throw IOException("Live rewind storage limit reached (${diskManager.maxBudgetBytes / (1024 * 1024 * 1024)} GB max).")+ }+ }}private inner class ProgressiveSession(@@ -227,37 +307,61 @@ internal class DefaultLiveTimeshiftManager @Inject constructor(private val chunks = ArrayDeque<ProgressiveChunk>()private val chunkMutex = Mutex()+ @Volatile private var activeCall: okhttp3.Call? = null+ private var runningChunkDurationMs = 0L++ override suspend fun stop() {+ activeCall?.cancel()+ super.stop()+ }override suspend fun capture() {- val request = makeRequest(streamInfo.url)- okHttpClient.newCall(request).execute().use { response ->- if (!response.isSuccessful) throw IOException("Timeshift stream failed with HTTP ${response.code}")- val input = response.body?.byteStream() ?: throw IOException("Timeshift stream returned an empty body")- input.use { source ->- var current = createChunk()- val buffer = ByteArray(DEFAULT_BUFFER_SIZE)- while (scope.isActive) {- currentCoroutineContext().ensureActive()- val read = source.read(buffer)- if (read <= 0) break- current.write(buffer, read)- if (System.currentTimeMillis() - current.startedAtMs >= PROGRESSIVE_CHUNK_MS) {- finalizeChunk(current)- current = createChunk()+ var retryDelay = 1_000L+ var retryCount = 0+ while (true) {+ currentCoroutineContext().ensureActive()+ try {+ val request = makeRequest(streamInfo.url)+ val call = okHttpClient.newCall(request)+ activeCall = call+ call.execute().use { response ->+ if (!response.isSuccessful) throw IOException("Timeshift stream failed with HTTP ${response.code}")+ val input = response.body?.byteStream() ?: throw IOException("Timeshift stream returned an empty body")+ retryDelay = 1_000L+ retryCount = 0+ input.use { source ->+ var current = createChunk()+ val buffer = ByteArray(PROGRESSIVE_READ_BUFFER_SIZE)+ while (true) {+ currentCoroutineContext().ensureActive()+ val read = source.read(buffer)+ if (read <= 0) break+ current.write(buffer, read)+ if (System.currentTimeMillis() - current.startedAtMs >= PROGRESSIVE_CHUNK_MS) {+ finalizeChunk(current)+ current = createChunk()+ }+ }+ if (current.bytesWritten > 0L) {+ finalizeChunk(current)+ }}}- if (current.bytesWritten > 0L) {- finalizeChunk(current)- }+ break // stream ended normally+ } catch (t: Throwable) {+ currentCoroutineContext().ensureActive()+ retryCount+++ if (retryCount > MAX_PROGRESSIVE_RETRIES) throw t+ delay(retryDelay)+ retryDelay = (retryDelay * 2).coerceAtMost(MAX_RETRY_DELAY_MS)}}}override suspend fun createSnapshot(): LiveTimeshiftSnapshot? {- val snapshotDir = File(sessionDir, "snapshot-progressive").apply {- deleteRecursively()- mkdirs()- }+ val snapshotId = sequence.incrementAndGet()+ val snapshotDir = File(sessionDir, "snapshot-$snapshotId").apply { mkdirs() }+ activeSnapshotDir = snapshotDirval snapshotFile = File(snapshotDir, "buffer.ts")val orderedChunks = chunkMutex.withLock { chunks.toList() }if (orderedChunks.isEmpty()) return null@@ -287,14 +391,15 @@ internal class DefaultLiveTimeshiftManager @Inject constructor(return ActiveProgressiveChunk(id = id,startedAtMs = System.currentTimeMillis(),- file = targetFile,- output = if (targetFile != null) targetFile.outputStream().buffered() else ByteArrayOutputStream()+ file = targetFile)}private suspend fun finalizeChunk(active: ActiveProgressiveChunk) {- active.output.flush()- active.output.close()+ val output = active.output ?: return // never written — nothing to finalize+ if (backend == LiveTimeshiftBackend.DISK) checkDiskAndBudget()+ output.flush()+ output.close()val endedAtMs = System.currentTimeMillis()val chunk = ProgressiveChunk(id = active.id,@@ -302,27 +407,32 @@ internal class DefaultLiveTimeshiftManager @Inject constructor(endedAtMs = endedAtMs,durationMs = (endedAtMs - active.startedAtMs).coerceAtLeast(1L),file = active.file,- payload = if (backend == LiveTimeshiftBackend.MEMORY) (active.output as ByteArrayOutputStream).toByteArray() else null+ payload = if (backend == LiveTimeshiftBackend.MEMORY) (output as ByteArrayOutputStream).toByteArray() else null)val windowDuration = chunkMutex.withLock {+ runningChunkDurationMs += chunk.durationMschunks += chunkpruneProgressiveChunksLocked()- chunks.sumOf { it.durationMs }+ runningChunkDurationMs}updateWindow(windowDuration)}private fun ActiveProgressiveChunk.write(buffer: ByteArray, read: Int) {- output.write(buffer, 0, read)+ val out = output ?: run {+ val created = if (file != null) file.outputStream().buffered() else ByteArrayOutputStream()+ output = created+ created+ }+ out.write(buffer, 0, read)bytesWritten += read}private fun pruneProgressiveChunksLocked() {- var totalDurationMs = chunks.sumOf { it.durationMs }- while (totalDurationMs > config.depthMs && chunks.isNotEmpty()) {+ while (runningChunkDurationMs > effectiveDepthMs && chunks.isNotEmpty()) {val removed = chunks.removeFirst()removed.file?.delete()- totalDurationMs -= removed.durationMs+ runningChunkDurationMs -= removed.durationMs}}}@@ -336,41 +446,64 @@ internal class DefaultLiveTimeshiftManager @Inject constructor(private val segments = ArrayDeque<HlsSegmentSnapshot>()private val segmentMutex = Mutex()+ private var runningSegmentDurationMs = 0L+ // Track the highest media sequence number we have processed so far.+ // Segments with sequence <= lastProcessedSequence are skipped (already captured or expired).+ private var lastProcessedSequence = -1L+ // Track discontinuity sequence so ad-break / stream-restart boundaries don't+ // cause us to re-download segments whose sequence numbers reset after a discontinuity.+ private var lastDiscontinuitySequence = -1Loverride suspend fun capture() {var currentPlaylistUrl = streamInfo.url- val seenSegments = linkedSetOf<String>()- while (scope.isActive) {+ var consecutiveErrors = 0+ while (true) {currentCoroutineContext().ensureActive()- val playlistText = fetchText(currentPlaylistUrl)- val parsed = parsePlaylist(currentPlaylistUrl, playlistText)- when (parsed) {- is ParsedHlsPlaylist.Master -> currentPlaylistUrl = parsed.bestVariantUrl- is ParsedHlsPlaylist.Media -> {- parsed.segments.forEach { remoteSegment ->- currentCoroutineContext().ensureActive()- if (!seenSegments.add(remoteSegment.uri)) return@forEach- val bytes = fetchBytes(remoteSegment.uri)- val retained = retainHlsSegment(remoteSegment, bytes)- val windowDuration = segmentMutex.withLock {- segments += retained- pruneHlsSegmentsLocked()- segments.sumOf { it.durationMs }+ try {+ val playlistText = fetchText(currentPlaylistUrl)+ consecutiveErrors = 0+ val parsed = parsePlaylist(currentPlaylistUrl, playlistText)+ when (parsed) {+ is ParsedHlsPlaylist.Master -> currentPlaylistUrl = parsed.bestVariantUrl+ is ParsedHlsPlaylist.Media -> {+ // On a discontinuity-sequence change, reset media-sequence tracking+ // so segments from the new period are captured fresh.+ if (parsed.discontinuitySequence != lastDiscontinuitySequence && lastDiscontinuitySequence >= 0L) {+ lastProcessedSequence = -1L+ }+ lastDiscontinuitySequence = parsed.discontinuitySequence++ parsed.segments.forEach { remoteSegment ->+ currentCoroutineContext().ensureActive()+ if (remoteSegment.mediaSequence <= lastProcessedSequence) return@forEach+ lastProcessedSequence = remoteSegment.mediaSequence+ checkDiskAndBudget()+ val retained = retainHlsSegment(remoteSegment)+ val windowDuration = segmentMutex.withLock {+ runningSegmentDurationMs += retained.durationMs+ segments += retained+ pruneHlsSegmentsLocked()+ runningSegmentDurationMs+ }+ updateWindow(windowDuration)}- updateWindow(windowDuration)+ if (parsed.endList) break+ delay((parsed.targetDurationSeconds.coerceAtLeast(2) * 1000L) / 2L)}- if (parsed.endList) break- delay((parsed.targetDurationSeconds.coerceAtLeast(2) * 1000L) / 2L)}+ } catch (t: Throwable) {+ currentCoroutineContext().ensureActive()+ consecutiveErrors+++ if (consecutiveErrors > MAX_HLS_CONSECUTIVE_ERRORS) throw t+ delay(consecutiveErrors.coerceAtMost(5) * HLS_ERROR_RETRY_DELAY_MS)}}}override suspend fun createSnapshot(): LiveTimeshiftSnapshot? {- val snapshotDir = File(sessionDir, "snapshot-hls").apply {- deleteRecursively()- mkdirs()- }+ val snapshotId = sequence.incrementAndGet()+ val snapshotDir = File(sessionDir, "snapshot-$snapshotId").apply { mkdirs() }+ activeSnapshotDir = snapshotDirval snapshotSegments = segmentMutex.withLock { segments.toList() }if (snapshotSegments.isEmpty()) return nullval playlist = File(snapshotDir, "index.m3u8")@@ -400,22 +533,31 @@ internal class DefaultLiveTimeshiftManager @Inject constructor()}- private fun retainHlsSegment(remote: RemoteHlsSegment, bytes: ByteArray): HlsSegmentSnapshot {+ private fun retainHlsSegment(remote: RemoteHlsSegment): HlsSegmentSnapshot {val id = sequence.incrementAndGet()return if (backend == LiveTimeshiftBackend.DISK) {- val target = File(sessionDir, "segment-$id.ts").apply { writeBytes(bytes) }+ val target = File(sessionDir, "segment-$id.ts")+ streamSegmentToDisk(remote.uri, target)HlsSegmentSnapshot(remote.uri, remote.durationMs, target, null)} else {+ val bytes = fetchBytes(remote.uri)HlsSegmentSnapshot(remote.uri, remote.durationMs, null, bytes)}}+ private fun streamSegmentToDisk(url: String, target: File) {+ okHttpClient.newCall(makeRequest(url)).execute().use { response ->+ if (!response.isSuccessful) throw IOException("Timeshift segment failed with HTTP ${response.code}")+ val body = response.body ?: throw IOException("Timeshift segment returned an empty body")+ body.byteStream().use { input -> target.outputStream().use { output -> input.copyTo(output, bufferSize = PROGRESSIVE_READ_BUFFER_SIZE) } }+ }+ }+private fun pruneHlsSegmentsLocked() {- var totalDurationMs = segments.sumOf { it.durationMs }- while (totalDurationMs > config.depthMs && segments.isNotEmpty()) {+ while (runningSegmentDurationMs > effectiveDepthMs && segments.isNotEmpty()) {val removed = segments.removeFirst()removed.file?.delete()- totalDurationMs -= removed.durationMs+ runningSegmentDurationMs -= removed.durationMs}}@@ -450,42 +592,59 @@ internal class DefaultLiveTimeshiftManager @Inject constructor(variants += pendingBandwidth to resolveRelativeUrl(baseUrl, next)}}- val bestVariantUrl = variants.maxByOrNull { it.first }?.second+ val bestVariantUrl = variants.sortedBy { it.first }.getOrNull(variants.size / 2)?.second?: throw IOException("No playable HLS variants were available.")return ParsedHlsPlaylist.Master(bestVariantUrl)}var targetDurationSeconds = 6var endList = false+ var mediaSequence = 0L+ var discontinuitySequence = 0Lval segments = mutableListOf<RemoteHlsSegment>()var currentDurationMs = 6_000L+ var nextSequence = 0L // assigned after we see EXT-X-MEDIA-SEQUENCE+ var sequenceInitialized = falselines.forEach { line ->when {line.startsWith("#EXT-X-TARGETDURATION", ignoreCase = true) -> {targetDurationSeconds = line.substringAfter(':', "6").toIntOrNull() ?: 6}+ line.startsWith("#EXT-X-MEDIA-SEQUENCE", ignoreCase = true) -> {+ mediaSequence = line.substringAfter(':', "0").trim().toLongOrNull() ?: 0L+ nextSequence = mediaSequence+ sequenceInitialized = true+ }+ line.startsWith("#EXT-X-DISCONTINUITY-SEQUENCE", ignoreCase = true) -> {+ discontinuitySequence = line.substringAfter(':', "0").trim().toLongOrNull() ?: 0L+ }line.startsWith("#EXTINF", ignoreCase = true) -> {currentDurationMs = ((line.substringAfter(':').substringBefore(',').toDoubleOrNull() ?: 6.0) * 1000.0).toLong()}line.startsWith("#EXT-X-ENDLIST", ignoreCase = true) -> endList = trueline.startsWith("#") -> Unitelse -> {+ if (!sequenceInitialized) { nextSequence = 0L; sequenceInitialized = true }segments += RemoteHlsSegment(uri = resolveRelativeUrl(baseUrl, line),- durationMs = currentDurationMs.coerceAtLeast(1L)+ durationMs = currentDurationMs.coerceAtLeast(1L),+ mediaSequence = nextSequence)+ nextSequence++}}}return ParsedHlsPlaylist.Media(targetDurationSeconds = targetDurationSeconds,endList = endList,+ mediaSequence = mediaSequence,+ discontinuitySequence = discontinuitySequence,segments = segments)}}- private data class ProgressiveChunk(+ private class ProgressiveChunk(val id: Long,val startedAtMs: Long,val endedAtMs: Long,@@ -494,15 +653,15 @@ internal class DefaultLiveTimeshiftManager @Inject constructor(val payload: ByteArray?)- private data class ActiveProgressiveChunk(+ private class ActiveProgressiveChunk(val id: Long,val startedAtMs: Long,val file: File?,- val output: java.io.OutputStream,+ var output: java.io.OutputStream? = null,var bytesWritten: Long = 0L)- private data class HlsSegmentSnapshot(+ private class HlsSegmentSnapshot(val remoteUrl: String,val durationMs: Long,val file: File?,@@ -511,7 +670,8 @@ internal class DefaultLiveTimeshiftManager @Inject constructor(private data class RemoteHlsSegment(val uri: String,- val durationMs: Long+ val durationMs: Long,+ val mediaSequence: Long = 0L)private sealed interface ParsedHlsPlaylist {@@ -519,11 +679,378 @@ internal class DefaultLiveTimeshiftManager @Inject constructor(data class Media(val targetDurationSeconds: Int,val endList: Boolean,+ val mediaSequence: Long,+ val discontinuitySequence: Long,val segments: List<RemoteHlsSegment>) : ParsedHlsPlaylist}+ /**+ * Captures a DASH live stream by polling the MPD manifest, resolving segments via+ * SegmentTemplate+SegmentTimeline, and writing them to disk/memory. On snapshot,+ * the captured segments are re-packaged as a static HLS playlist so ExoPlayer can+ * play them the same way as HLS snapshots.+ */+ private inner class DashSession(+ streamInfo: StreamInfo,+ config: TimeshiftConfig,+ backend: LiveTimeshiftBackend,+ sessionDir: File+ ) : Session(streamInfo, config, backend, sessionDir) {++ private val segments = ArrayDeque<HlsSegmentSnapshot>()+ private val segmentMutex = Mutex()+ private val seenSegments = linkedSetOf<String>()+ private var runningSegmentDurationMs = 0L++ override suspend fun capture() {+ var consecutiveErrors = 0+ while (true) {+ currentCoroutineContext().ensureActive()+ try {+ val mpdText = fetchText(streamInfo.url)+ consecutiveErrors = 0+ val parsed = parseMpd(streamInfo.url, mpdText)++ // Download init segment once (identified by URL; seenSegments deduplicates it).+ parsed.initSegmentUrl?.let { initUrl ->+ if (seenSegments.add("__init__:$initUrl")) {+ checkDiskAndBudget()+ val retained = retainSegment(RemoteHlsSegment(initUrl, 0L), isInit = true)+ segmentMutex.withLock { segments += retained }+ }+ }++ parsed.mediaSegments.forEach { remote ->+ currentCoroutineContext().ensureActive()+ if (!seenSegments.add(remote.uri)) return@forEach+ checkDiskAndBudget()+ val retained = retainSegment(remote, isInit = false)+ val windowDuration = segmentMutex.withLock {+ runningSegmentDurationMs += retained.durationMs+ segments += retained+ pruneSegmentsLocked()+ runningSegmentDurationMs+ }+ updateWindow(windowDuration)+ }++ if (!parsed.isDynamic) break // VOD / static — no need to re-poll+ delay(parsed.minimumUpdatePeriodMs.coerceAtLeast(1_000L))+ } catch (t: Throwable) {+ currentCoroutineContext().ensureActive()+ consecutiveErrors+++ if (consecutiveErrors > MAX_DASH_CONSECUTIVE_ERRORS) throw t+ delay(consecutiveErrors.coerceAtMost(5) * DASH_ERROR_RETRY_DELAY_MS)+ }+ }+ }++ override suspend fun createSnapshot(): LiveTimeshiftSnapshot? {+ val snapshotId = sequence.incrementAndGet()+ val snapshotDir = File(sessionDir, "snapshot-$snapshotId").apply { mkdirs() }+ activeSnapshotDir = snapshotDir+ val snapshotSegments = segmentMutex.withLock { segments.toList() }+ .filter { it.durationMs > 0L } // exclude init segment from HLS timing+ if (snapshotSegments.isEmpty()) return null++ // Re-package captured DASH segments as a static HLS playlist.+ // ExoPlayer already handles both HLS and DASH, and our snapshot infrastructure+ // is built around HLS output, so DASH snapshots follow the same pattern.+ val playlist = File(snapshotDir, "index.m3u8")+ val targetDurationSeconds = snapshotSegments.maxOf { ((it.durationMs + 999L) / 1000L).toInt().coerceAtLeast(1) }+ val all = segmentMutex.withLock { segments.toList() } // includes init+ val body = buildString {+ appendLine("#EXTM3U")+ appendLine("#EXT-X-VERSION:3")+ appendLine("#EXT-X-TARGETDURATION:$targetDurationSeconds")+ appendLine("#EXT-X-MEDIA-SEQUENCE:0")+ var mediaIndex = 0+ all.forEachIndexed { index, segment ->+ val isInit = segment.durationMs == 0L+ val fileName = if (isInit) "init-$index.mp4" else "segment-${mediaIndex++}.mp4"+ val outputFile = File(snapshotDir, fileName)+ when {+ segment.file != null && segment.file.exists() -> segment.file.copyTo(outputFile, overwrite = true)+ segment.payload != null -> outputFile.writeBytes(segment.payload)+ }+ if (!isInit) {+ appendLine("#EXTINF:${"%.3f".format(Locale.US, segment.durationMs / 1000.0)},")+ appendLine(fileName)+ }+ }+ appendLine("#EXT-X-ENDLIST")+ }+ playlist.writeText(body)+ return LiveTimeshiftSnapshot(+ url = playlist.toURI().toString(),+ durationMs = snapshotSegments.sumOf { it.durationMs },+ backend = backend+ )+ }++ private fun retainSegment(remote: RemoteHlsSegment, isInit: Boolean): HlsSegmentSnapshot {+ val id = sequence.incrementAndGet()+ val ext = if (isInit) "init-$id.mp4" else "segment-$id.mp4"+ return if (backend == LiveTimeshiftBackend.DISK) {+ val target = File(sessionDir, ext)+ streamSegmentToDisk(remote.uri, target)+ HlsSegmentSnapshot(remote.uri, remote.durationMs, target, null)+ } else {+ val bytes = fetchBytes(remote.uri)+ HlsSegmentSnapshot(remote.uri, remote.durationMs, null, bytes)+ }+ }++ private fun pruneSegmentsLocked() {+ while (runningSegmentDurationMs > effectiveDepthMs && segments.isNotEmpty()) {+ val candidate = segments.first()+ if (candidate.durationMs == 0L) break // never prune the init segment+ val removed = segments.removeFirst()+ seenSegments.remove(removed.remoteUrl)+ removed.file?.delete()+ runningSegmentDurationMs -= removed.durationMs+ }+ }++ private fun streamSegmentToDisk(url: String, target: File) {+ okHttpClient.newCall(makeRequest(url)).execute().use { response ->+ if (!response.isSuccessful) throw IOException("DASH segment fetch failed: HTTP ${response.code}")+ val body = response.body ?: throw IOException("DASH segment returned empty body")+ body.byteStream().use { input -> target.outputStream().use { out -> input.copyTo(out, bufferSize = PROGRESSIVE_READ_BUFFER_SIZE) } }+ }+ }++ private fun fetchText(url: String): String {+ okHttpClient.newCall(makeRequest(url)).execute().use { response ->+ if (!response.isSuccessful) throw IOException("MPD fetch failed: HTTP ${response.code}")+ return response.body?.string().orEmpty()+ }+ }++ private fun fetchBytes(url: String): ByteArray {+ okHttpClient.newCall(makeRequest(url)).execute().use { response ->+ if (!response.isSuccessful) throw IOException("DASH segment fetch failed: HTTP ${response.code}")+ return response.body?.bytes() ?: ByteArray(0)+ }+ }++ /**+ * Parses a DASH MPD and extracts:+ * - Whether it is a live (dynamic) stream+ * - The minimumUpdatePeriod in ms (for live re-poll timing)+ * - The init segment URL for the selected representation+ * - The list of new media segments via SegmentTemplate + SegmentTimeline+ *+ * Selects the middle-bandwidth video Adaptation Set to balance quality vs storage,+ * consistent with the HLS variant selection policy.+ */+ private fun parseMpd(baseUrl: String, rawXml: String): ParsedDashManifest {+ val factory = XmlPullParserFactory.newInstance().apply { isNamespaceAware = false }+ val xpp = factory.newPullParser()+ xpp.setInput(rawXml.reader())++ var isDynamic = false+ var minimumUpdatePeriodMs = 5_000L+ var availabilityStartTimeMs = 0L+ var timescale = 1L+ var segmentDuration = 0L+ var startNumber = 1L+ var mediaTemplate = ""+ var initTemplate = ""+ var representationBandwidth = 0+ var representationId = ""++ // Collect all Representations from the first video AdaptationSet.+ // Structure: MPD > Period > AdaptationSet (contentType=video) > Representation+ data class RepresentationInfo(val id: String, val bandwidth: Int, val initTemplate: String, val mediaTemplate: String, val timescale: Long, val segmentDuration: Long, val startNumber: Long)+ val representations = mutableListOf<RepresentationInfo>()+ val timelineSegments = mutableListOf<Pair<Long, Long>>() // (t, d) pairs++ var inAdaptationSet = false+ var inVideoAdaptationSet = false+ var inRepresentation = false+ var inSegmentTemplate = false+ var inSegmentTimeline = false+ var currentRepBandwidth = 0+ var currentRepId = ""+ var currentInitTemplate = ""+ var currentMediaTemplate = ""+ var currentTimescale = 1L+ var currentSegDuration = 0L+ var currentStartNumber = 1L+ var currentTimelineSegments = mutableListOf<Pair<Long, Long>>()++ var eventType = xpp.eventType+ while (eventType != XmlPullParser.END_DOCUMENT) {+ when (eventType) {+ XmlPullParser.START_TAG -> when (xpp.name) {+ "MPD" -> {+ isDynamic = xpp.getAttributeValue(null, "type")?.equals("dynamic", ignoreCase = true) == true+ val mup = xpp.getAttributeValue(null, "minimumUpdatePeriod")+ if (mup != null) minimumUpdatePeriodMs = parsePtDuration(mup)+ val ast = xpp.getAttributeValue(null, "availabilityStartTime")+ if (ast != null) availabilityStartTimeMs = parseIso8601ToMs(ast)+ }+ "AdaptationSet" -> {+ inAdaptationSet = true+ val contentType = xpp.getAttributeValue(null, "contentType")+ ?: xpp.getAttributeValue(null, "mimeType") ?: ""+ inVideoAdaptationSet = contentType.contains("video", ignoreCase = true)+ }+ "Representation" -> if (inVideoAdaptationSet) {+ inRepresentation = true+ currentRepBandwidth = xpp.getAttributeValue(null, "bandwidth")?.toIntOrNull() ?: 0+ currentRepId = xpp.getAttributeValue(null, "id") ?: ""+ currentInitTemplate = initTemplate+ currentMediaTemplate = mediaTemplate+ currentTimescale = timescale+ currentSegDuration = segmentDuration+ currentStartNumber = startNumber+ currentTimelineSegments = mutableListOf()+ }+ "SegmentTemplate" -> {+ inSegmentTemplate = true+ val ts = xpp.getAttributeValue(null, "timescale")?.toLongOrNull() ?: 1L+ val sd = xpp.getAttributeValue(null, "duration")?.toLongOrNull() ?: 0L+ val sn = xpp.getAttributeValue(null, "startNumber")?.toLongOrNull() ?: 1L+ val it = xpp.getAttributeValue(null, "initialization") ?: ""+ val mt = xpp.getAttributeValue(null, "media") ?: ""+ if (inRepresentation) {+ currentTimescale = ts; currentSegDuration = sd; currentStartNumber = sn+ currentInitTemplate = it; currentMediaTemplate = mt+ } else {+ timescale = ts; segmentDuration = sd; startNumber = sn+ initTemplate = it; mediaTemplate = mt+ }+ }+ "SegmentTimeline" -> inSegmentTimeline = true+ "S" -> if (inSegmentTimeline) {+ val t = xpp.getAttributeValue(null, "t")?.toLongOrNull()+ ?: (currentTimelineSegments.lastOrNull()?.let { it.first + it.second } ?: 0L)+ val d = xpp.getAttributeValue(null, "d")?.toLongOrNull() ?: 0L+ val r = xpp.getAttributeValue(null, "r")?.toIntOrNull() ?: 0+ var tCurrent = t+ repeat(r + 1) {+ currentTimelineSegments += tCurrent to d+ tCurrent += d+ }+ }+ }+ XmlPullParser.END_TAG -> when (xpp.name) {+ "Representation" -> if (inVideoAdaptationSet && inRepresentation) {+ representations += RepresentationInfo(+ id = currentRepId,+ bandwidth = currentRepBandwidth,+ initTemplate = currentInitTemplate,+ mediaTemplate = currentMediaTemplate,+ timescale = currentTimescale,+ segmentDuration = currentSegDuration,+ startNumber = currentStartNumber+ )+ if (currentTimelineSegments.isNotEmpty()) {+ timelineSegments.clear()+ timelineSegments += currentTimelineSegments+ }+ inRepresentation = false+ }+ "AdaptationSet" -> { inAdaptationSet = false; inVideoAdaptationSet = false }+ "SegmentTemplate" -> inSegmentTemplate = false+ "SegmentTimeline" -> inSegmentTimeline = false+ }+ }+ eventType = xpp.next()+ }++ // Pick the median-bandwidth representation (same policy as HLS variant selection).+ val rep = representations.sortedBy { it.bandwidth }.getOrNull(representations.size / 2)+ ?: throw IOException("No video representations found in MPD.")++ val resolvedInit: String? = rep.initTemplate.takeIf { it.isNotEmpty() }+ ?.replace("\$RepresentationID\$", rep.id)+ ?.replace("\$Bandwidth\$", rep.bandwidth.toString())+ ?.let { resolveRelativeUrl(baseUrl, it) }++ val ts = rep.timescale.takeIf { it > 0L } ?: 1L+ val mediaSegments: List<RemoteHlsSegment> = if (timelineSegments.isNotEmpty()) {+ // SegmentTimeline mode: each (t, d) pair is one segment.+ timelineSegments.mapIndexed { index, (t, d) ->+ val number = rep.startNumber + index+ val uri = rep.mediaTemplate+ .replace("\$RepresentationID\$", rep.id)+ .replace("\$Bandwidth\$", rep.bandwidth.toString())+ .replace("\$Number\$", number.toString())+ .replace("\$Time\$", t.toString())+ .let { resolveRelativeUrl(baseUrl, it) }+ RemoteHlsSegment(uri = uri, durationMs = if (ts > 0L) d * 1000L / ts else d)+ }+ } else if (rep.segmentDuration > 0L) {+ // Fixed-duration mode: compute number from wall clock and availabilityStartTime.+ val nowMs = System.currentTimeMillis()+ val elapsedSecs = ((nowMs - availabilityStartTimeMs) / 1000L).coerceAtLeast(0L)+ val totalSegments = elapsedSecs * ts / rep.segmentDuration+ val windowSegments = (effectiveDepthMs / 1000L * ts / rep.segmentDuration + 2L).toInt()+ val firstNumber = (totalSegments - windowSegments).coerceAtLeast(rep.startNumber)+ (firstNumber..totalSegments).map { number ->+ val uri = rep.mediaTemplate+ .replace("\$RepresentationID\$", rep.id)+ .replace("\$Bandwidth\$", rep.bandwidth.toString())+ .replace("\$Number\$", number.toString())+ .let { resolveRelativeUrl(baseUrl, it) }+ RemoteHlsSegment(uri = uri, durationMs = rep.segmentDuration * 1000L / ts)+ }+ } else {+ emptyList()+ }++ return ParsedDashManifest(+ isDynamic = isDynamic,+ minimumUpdatePeriodMs = minimumUpdatePeriodMs,+ initSegmentUrl = resolvedInit,+ mediaSegments = mediaSegments+ )+ }++ /** Parses ISO 8601 duration strings like `PT2.5S`, `PT1M30S`, `P1DT2H`. */+ private fun parsePtDuration(value: String): Long {+ val upper = value.uppercase(Locale.ROOT)+ if (!upper.startsWith("P")) return 5_000L+ var ms = 0L+ val afterP = upper.removePrefix("P")+ val (datePart, timePart) = if (afterP.contains('T')) {+ afterP.substringBefore('T') to afterP.substringAfter('T')+ } else {+ afterP to ""+ }+ Regex("""(\d+(?:\.\d+)?)D""").find(datePart)?.groupValues?.get(1)?.toDoubleOrNull()?.let { ms += (it * 86_400_000).toLong() }+ Regex("""(\d+(?:\.\d+)?)H""").find(timePart)?.groupValues?.get(1)?.toDoubleOrNull()?.let { ms += (it * 3_600_000).toLong() }+ Regex("""(\d+(?:\.\d+)?)M""").find(timePart)?.groupValues?.get(1)?.toDoubleOrNull()?.let { ms += (it * 60_000).toLong() }+ Regex("""(\d+(?:\.\d+)?)S""").find(timePart)?.groupValues?.get(1)?.toDoubleOrNull()?.let { ms += (it * 1_000).toLong() }+ return ms.takeIf { it > 0L } ?: 5_000L+ }++ /** Parses an ISO 8601 datetime string to milliseconds since epoch, best-effort. */+ private fun parseIso8601ToMs(value: String): Long = runCatching {+ java.time.OffsetDateTime.parse(value).toInstant().toEpochMilli()+ }.getOrDefault(0L)+ }++ private data class ParsedDashManifest(+ val isDynamic: Boolean,+ val minimumUpdatePeriodMs: Long,+ val initSegmentUrl: String?,+ val mediaSegments: List<RemoteHlsSegment>+ )+private companion object {private const val PROGRESSIVE_CHUNK_MS = 2_000L+ private const val PROGRESSIVE_READ_BUFFER_SIZE = 65_536+ private const val MAX_PROGRESSIVE_RETRIES = 10+ private const val MAX_HLS_CONSECUTIVE_ERRORS = 10+ private const val MAX_DASH_CONSECUTIVE_ERRORS = 10+ private const val MAX_RETRY_DELAY_MS = 30_000L+ private const val HLS_ERROR_RETRY_DELAY_MS = 2_000L+ private const val DASH_ERROR_RETRY_DELAY_MS = 2_000L+ private const val MIN_FREE_DISK_BYTES = 200L * 1024 * 1024 // 200 MB}}diff --git a/player/src/main/java/com/streamvault/player/timeshift/LiveTimeshiftModels.kt b/player/src/main/java/com/streamvault/player/timeshift/LiveTimeshiftModels.ktindex a2b82a83..a839f881 100644--- a/player/src/main/java/com/streamvault/player/timeshift/LiveTimeshiftModels.kt+++ b/player/src/main/java/com/streamvault/player/timeshift/LiveTimeshiftModels.kt@@ -5,6 +5,16 @@ data class TimeshiftConfig(val depthMinutes: Int = 30) {val depthMs: Long = depthMinutes.coerceIn(15, 60) * 60_000L++ fun effectiveDepthMs(backend: LiveTimeshiftBackend): Long =+ if (backend == LiveTimeshiftBackend.MEMORY)+ depthMinutes.coerceIn(1, MAX_MEMORY_BACKEND_DEPTH_MINUTES) * 60_000L+ else+ depthMs++ companion object {+ const val MAX_MEMORY_BACKEND_DEPTH_MINUTES = 5+ }}enum class LiveTimeshiftBackend {diff --git a/player/src/main/java/com/streamvault/player/timeshift/TimeshiftDiskManager.kt b/player/src/main/java/com/streamvault/player/timeshift/TimeshiftDiskManager.ktnew file mode 100644index 00000000..274ac2a9--- /dev/null+++ b/player/src/main/java/com/streamvault/player/timeshift/TimeshiftDiskManager.kt@@ -0,0 +1,67 @@+package com.streamvault.player.timeshift++import android.content.Context+import java.io.File++/**+ * Manages the timeshift cache directory:+ *+ * - Enforces a global byte budget across all session data.+ * - Deletes stale session directories left by crashes or force-stops.+ * - Evicts the oldest (LRU) session directories first when over-budget.+ *+ * All methods are safe to call from IO threads.+ */+class TimeshiftDiskManager(+ context: Context,+ val maxBudgetBytes: Long = DEFAULT_BUDGET_BYTES+) {+ private val timeshiftDir = File(context.cacheDir, "timeshift")++ /**+ * Deletes every directory under [timeshiftDir] except [activeSessionDir].+ * Safe to call with [activeSessionDir] = null to wipe everything (e.g. on app start+ * before any session exists).+ */+ fun cleanupStaleDirectories(activeSessionDir: File?) {+ val entries = timeshiftDir.listFiles() ?: return+ for (entry in entries) {+ if (entry == activeSessionDir) continue+ entry.deleteRecursively()+ }+ }++ /**+ * Returns the total bytes consumed by all files under [timeshiftDir].+ */+ fun currentUsageBytes(): Long =+ timeshiftDir.walkTopDown().filter { it.isFile }.sumOf { it.length() }++ /**+ * Returns true when the total usage is below [maxBudgetBytes].+ */+ fun isWithinBudget(): Boolean = currentUsageBytes() < maxBudgetBytes++ /**+ * Deletes stale session directories in oldest-first (LRU) order until usage+ * falls below 80 % of [maxBudgetBytes], or no more stale dirs remain.+ *+ * [activeSessionDir] is never touched.+ */+ fun evictLruUntilWithinBudget(activeSessionDir: File?) {+ val staleDirs = timeshiftDir.listFiles()+ ?.filter { it.isDirectory && it != activeSessionDir }+ ?.sortedBy { it.lastModified() }+ ?: return+ val target = (maxBudgetBytes * 0.8).toLong()+ for (dir in staleDirs) {+ if (currentUsageBytes() < target) break+ dir.deleteRecursively()+ }+ }++ companion object {+ /** Default 2 GB global budget for all timeshift data. */+ const val DEFAULT_BUDGET_BYTES = 2L * 1024 * 1024 * 1024+ }+}