Skip to content

StreamVault is a TV-first free IPTV player for Android TV built with Kotlin, Jetpack Compose, Room, Hilt, and Media3.

EPG guide, phone icon mipmap densities, partial phone touch support, screen-on during playback, UX fixes

David Nashash77f52ac3baf2
diff --git a/app/src/main/java/com/streamvault/app/di/DatabaseModule.kt b/app/src/main/java/com/streamvault/app/di/DatabaseModule.kt
index 5e5cb41b..44ef7e92 100644
--- a/app/src/main/java/com/streamvault/app/di/DatabaseModule.kt
+++ b/app/src/main/java/com/streamvault/app/di/DatabaseModule.kt
@@ -48,7 +48,8 @@ object DatabaseModule {
StreamVaultDatabase.MIGRATION_20_21,
StreamVaultDatabase.MIGRATION_21_22,
StreamVaultDatabase.MIGRATION_22_23,
- StreamVaultDatabase.MIGRATION_23_24
+ StreamVaultDatabase.MIGRATION_23_24,
+ StreamVaultDatabase.MIGRATION_24_25
)
// NOTE: fallbackToDestructiveMigration() intentionally removed.
// All future schema changes MUST add a corresponding Migration in StreamVaultDatabase.
@@ -68,4 +69,9 @@ object DatabaseModule {
@Provides fun providePlaybackHistoryDao(db: StreamVaultDatabase): PlaybackHistoryDao = db.playbackHistoryDao()
@Provides fun provideSyncMetadataDao(db: StreamVaultDatabase): SyncMetadataDao = db.syncMetadataDao()
@Provides fun provideMovieCategoryHydrationDao(db: StreamVaultDatabase): MovieCategoryHydrationDao = db.movieCategoryHydrationDao()
+ @Provides fun provideEpgSourceDao(db: StreamVaultDatabase): EpgSourceDao = db.epgSourceDao()
+ @Provides fun provideProviderEpgSourceDao(db: StreamVaultDatabase): ProviderEpgSourceDao = db.providerEpgSourceDao()
+ @Provides fun provideEpgChannelDao(db: StreamVaultDatabase): EpgChannelDao = db.epgChannelDao()
+ @Provides fun provideEpgProgrammeDao(db: StreamVaultDatabase): EpgProgrammeDao = db.epgProgrammeDao()
+ @Provides fun provideChannelEpgMappingDao(db: StreamVaultDatabase): ChannelEpgMappingDao = db.channelEpgMappingDao()
}
diff --git a/app/src/main/java/com/streamvault/app/di/RepositoryModule.kt b/app/src/main/java/com/streamvault/app/di/RepositoryModule.kt
index ed512d6d..91f8cd5a 100644
--- a/app/src/main/java/com/streamvault/app/di/RepositoryModule.kt
+++ b/app/src/main/java/com/streamvault/app/di/RepositoryModule.kt
@@ -37,6 +37,9 @@ abstract class RepositoryModule {
@Binds @Singleton
abstract fun bindEpgRepository(impl: EpgRepositoryImpl): EpgRepository
+ @Binds @Singleton
+ abstract fun bindEpgSourceRepository(impl: EpgSourceRepositoryImpl): EpgSourceRepository
+
@Binds @Singleton
abstract fun bindFavoriteRepository(impl: FavoriteRepositoryImpl): FavoriteRepository
diff --git a/app/src/main/java/com/streamvault/app/ui/components/Cards.kt b/app/src/main/java/com/streamvault/app/ui/components/Cards.kt
index bc6fa8d6..b18e09f8 100644
--- a/app/src/main/java/com/streamvault/app/ui/components/Cards.kt
+++ b/app/src/main/java/com/streamvault/app/ui/components/Cards.kt
@@ -132,6 +132,7 @@ fun FocusableCard(
.height(height)
.mouseClickable(
focusRequester = focusRequester,
+ onLongClick = onLongClick,
onClick = {
sounds.playSelect()
onClick()
@@ -333,7 +334,9 @@ fun MovieCard(
isLocked: Boolean = false,
watchProgress: Float = 0f,
isReorderMode: Boolean = false,
- isDragging: Boolean = false
+ isDragging: Boolean = false,
+ width: Dp = 136.dp,
+ height: Dp = 204.dp
) {
val movieDescription = buildString {
append(movie.name)
@@ -350,8 +353,8 @@ fun MovieCard(
onClick = onClick,
onLongClick = onLongClick,
modifier = modifier,
- width = 136.dp,
- height = 204.dp,
+ width = width,
+ height = height,
isReorderMode = isReorderMode,
isDragging = isDragging,
semanticsDescription = movieDescription,
@@ -427,7 +430,9 @@ fun SeriesCard(
watchProgress: Float = 0f,
subtitle: String? = null,
isReorderMode: Boolean = false,
- isDragging: Boolean = false
+ isDragging: Boolean = false,
+ width: Dp = 136.dp,
+ height: Dp = 204.dp
) {
val seriesDescription = buildString {
append(series.name)
@@ -447,8 +452,8 @@ fun SeriesCard(
onClick = onClick,
onLongClick = onLongClick,
modifier = modifier,
- width = 136.dp,
- height = 204.dp,
+ width = width,
+ height = height,
isReorderMode = isReorderMode,
isDragging = isDragging,
semanticsDescription = seriesDescription,
diff --git a/app/src/main/java/com/streamvault/app/ui/components/CategoryRow.kt b/app/src/main/java/com/streamvault/app/ui/components/CategoryRow.kt
index e0763bf5..fc1ac6c5 100644
--- a/app/src/main/java/com/streamvault/app/ui/components/CategoryRow.kt
+++ b/app/src/main/java/com/streamvault/app/ui/components/CategoryRow.kt
@@ -46,6 +46,7 @@ fun <T : Any> CategoryRow(
Column(
modifier = modifier
.fillMaxWidth()
+ .suppressParentVerticalScroll()
) {
if (onSeeAll != null) {
val seeAllFocusRequester = remember { FocusRequester() }
diff --git a/app/src/main/java/com/streamvault/app/ui/components/ContinueWatchingRow.kt b/app/src/main/java/com/streamvault/app/ui/components/ContinueWatchingRow.kt
index 995e920d..3ea486b8 100644
--- a/app/src/main/java/com/streamvault/app/ui/components/ContinueWatchingRow.kt
+++ b/app/src/main/java/com/streamvault/app/ui/components/ContinueWatchingRow.kt
@@ -50,7 +50,7 @@ fun ContinueWatchingRow(
) {
if (items.isEmpty()) return
- Column(modifier = modifier.fillMaxWidth()) {
+ Column(modifier = modifier.fillMaxWidth().suppressParentVerticalScroll()) {
Row(
modifier = Modifier
.fillMaxWidth()
diff --git a/app/src/main/java/com/streamvault/app/ui/components/RowScrollFix.kt b/app/src/main/java/com/streamvault/app/ui/components/RowScrollFix.kt
new file mode 100644
index 00000000..ac707ea7
--- /dev/null
+++ b/app/src/main/java/com/streamvault/app/ui/components/RowScrollFix.kt
@@ -0,0 +1,37 @@
+@file:Suppress("DEPRECATION")
+
+package com.streamvault.app.ui.components
+
+import androidx.compose.foundation.ExperimentalFoundationApi
+import androidx.compose.foundation.relocation.BringIntoViewResponder
+import androidx.compose.foundation.relocation.bringIntoViewResponder
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableFloatStateOf
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.composed
+import androidx.compose.ui.geometry.Rect
+import androidx.compose.ui.layout.onSizeChanged
+
+/**
+ * Prevents a parent scrollable (e.g. LazyColumn) from micro-scrolling vertically
+ * when D-pad focus moves between children of an inner horizontal row (e.g. LazyRow).
+ *
+ * Works by replacing the per-card BringIntoView rect with the full height of this
+ * container, so the parent only scrolls to ensure the whole row section is visible.
+ */
+@OptIn(ExperimentalFoundationApi::class)
+fun Modifier.suppressParentVerticalScroll(): Modifier = composed {
+ var height by mutableFloatStateOf(0f)
+
+ this
+ .onSizeChanged { height = it.height.toFloat() }
+ .bringIntoViewResponder(object : BringIntoViewResponder {
+ override fun calculateRectForParent(localRect: Rect): Rect =
+ Rect(localRect.left, 0f, localRect.right, height)
+
+ override suspend fun bringChildIntoView(localRect: () -> Rect?) {
+ // No-op: horizontal scrolling is handled by the inner LazyRow.
+ }
+ })
+}
diff --git a/app/src/main/java/com/streamvault/app/ui/components/SavedCategoryContextCard.kt b/app/src/main/java/com/streamvault/app/ui/components/SavedCategoryContextCard.kt
index 629d4d53..2ebfab8d 100644
--- a/app/src/main/java/com/streamvault/app/ui/components/SavedCategoryContextCard.kt
+++ b/app/src/main/java/com/streamvault/app/ui/components/SavedCategoryContextCard.kt
@@ -31,6 +31,7 @@ import com.streamvault.app.ui.theme.OnSurface
import com.streamvault.app.ui.theme.OnSurfaceDim
import com.streamvault.app.ui.theme.Primary
import com.streamvault.app.ui.theme.SurfaceElevated
+import com.streamvault.app.ui.interaction.mouseClickable
@Composable
fun SavedCategoryContextCard(
@@ -98,6 +99,7 @@ fun SavedCategoryContextCard(
) {
Button(
onClick = onManageClick,
+ modifier = Modifier.mouseClickable(onClick = onManageClick),
colors = ButtonDefaults.colors(
containerColor = Primary.copy(alpha = 0.92f),
focusedContainerColor = Primary,
@@ -114,6 +116,7 @@ fun SavedCategoryContextCard(
}
Button(
onClick = onBrowseAllClick,
+ modifier = Modifier.mouseClickable(onClick = onBrowseAllClick),
colors = ButtonDefaults.colors(
containerColor = SurfaceElevated.copy(alpha = 0.78f),
contentColor = OnSurface,
diff --git a/app/src/main/java/com/streamvault/app/ui/components/SavedCategoryShortcutsRow.kt b/app/src/main/java/com/streamvault/app/ui/components/SavedCategoryShortcutsRow.kt
index 06bce975..a1c345d9 100644
--- a/app/src/main/java/com/streamvault/app/ui/components/SavedCategoryShortcutsRow.kt
+++ b/app/src/main/java/com/streamvault/app/ui/components/SavedCategoryShortcutsRow.kt
@@ -33,6 +33,7 @@ import com.streamvault.app.ui.theme.OnSurface
import com.streamvault.app.ui.theme.OnSurfaceDim
import com.streamvault.app.ui.theme.Primary
import com.streamvault.app.ui.theme.SurfaceElevated
+import com.streamvault.app.ui.interaction.mouseClickable
data class SavedCategoryShortcut(
val name: String,
@@ -116,7 +117,7 @@ fun SavedCategoryShortcutsRow(
item(key = "primary_shortcut") {
Surface(
onClick = onPrimaryShortcutClick,
- modifier = Modifier.width(shortcutWidth),
+ modifier = Modifier.width(shortcutWidth).mouseClickable(onClick = onPrimaryShortcutClick),
shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(14.dp)),
colors = ClickableSurfaceDefaults.colors(
containerColor = if (isPrimaryShortcutSelected) {
@@ -164,7 +165,10 @@ fun SavedCategoryShortcutsRow(
onLongClick = onShortcutLongClick?.let { handler ->
{ handler(shortcut.name) }
},
- modifier = Modifier.width(shortcutWidth),
+ modifier = Modifier.width(shortcutWidth).mouseClickable(
+ onClick = { onShortcutClick(shortcut.name) },
+ onLongClick = onShortcutLongClick?.let { handler -> { handler(shortcut.name) } }
+ ),
shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(14.dp)),
colors = ClickableSurfaceDefaults.colors(
containerColor = if (isSelected) Primary.copy(alpha = 0.18f) else SurfaceElevated,
diff --git a/app/src/main/java/com/streamvault/app/ui/components/SelectionChipRow.kt b/app/src/main/java/com/streamvault/app/ui/components/SelectionChipRow.kt
index af67236f..4d878225 100644
--- a/app/src/main/java/com/streamvault/app/ui/components/SelectionChipRow.kt
+++ b/app/src/main/java/com/streamvault/app/ui/components/SelectionChipRow.kt
@@ -69,6 +69,7 @@ fun ChipRowSection(
modifier = modifier
.fillMaxWidth()
.padding(vertical = 6.dp)
+ .suppressParentVerticalScroll()
) {
if (!title.isNullOrBlank()) {
Text(
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.kt
index 2e3653de..e8444900 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
@@ -30,6 +30,7 @@ import androidx.compose.foundation.shape.CircleShape
import kotlinx.coroutines.delay
import androidx.tv.material3.*
import com.streamvault.app.device.rememberIsTelevisionDevice
+import com.streamvault.app.ui.interaction.mouseClickable
import android.view.KeyEvent as AndroidKeyEvent
@Composable
@@ -148,7 +149,8 @@ fun AddToGroupDialog(
if (isFocused) 3.dp else 0.dp,
if (isFocused) AppColors.Focus else Color.Transparent,
CircleShape
- ),
+ )
+ .mouseClickable(onClick = safeToggleFavorite),
colors = ButtonDefaults.colors(
containerColor = when {
isFocused -> AppColors.Focus
@@ -190,7 +192,8 @@ fun AddToGroupDialog(
if (isFocused) 3.dp else 0.dp,
if (isFocused) AppColors.Focus else Color.Transparent,
CircleShape
- ),
+ )
+ .mouseClickable(onClick = safeOpenSplitScreenPlanner),
colors = ButtonDefaults.colors(
containerColor = when {
isFocused -> AppColors.Focus
@@ -234,6 +237,7 @@ fun AddToGroupDialog(
items(groups) { group ->
val isMember = memberOfGroups.contains(group.id)
var isFocused by remember { mutableStateOf(false) }
+ val groupAction = { if (isMember) safeRemoveFromGroup(group) else safeAddToGroup(group) }
Row(
modifier = Modifier.fillMaxWidth().padding(vertical = 4.dp),
@@ -247,9 +251,7 @@ fun AddToGroupDialog(
modifier = Modifier.weight(1f)
)
Button(
- onClick = {
- if (isMember) safeRemoveFromGroup(group) else safeAddToGroup(group)
- },
+ onClick = groupAction,
modifier = Modifier
.background(
color = if (isFocused) AppColors.Focus else Color.Transparent,
@@ -260,7 +262,8 @@ fun AddToGroupDialog(
if (isFocused) 3.dp else 0.dp,
if (isFocused) AppColors.Focus else Color.Transparent,
CircleShape
- ),
+ )
+ .mouseClickable(onClick = groupAction),
colors = ButtonDefaults.colors(
containerColor = when {
isFocused -> AppColors.Focus
@@ -294,7 +297,8 @@ fun AddToGroupDialog(
if (isFocused) 3.dp else 1.dp,
if (isFocused) AppColors.Focus else AppColors.BrandMuted.copy(alpha = 0.55f),
CircleShape
- ),
+ )
+ .mouseClickable(onClick = safeCreateGroup),
colors = ButtonDefaults.colors(
containerColor = if (isFocused) AppColors.Focus else Color.Transparent,
contentColor = if (isFocused) Color.Black else AppColors.TextPrimary
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.kt
index ccb75beb..35fa27ef 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
@@ -30,6 +30,9 @@ import com.streamvault.app.ui.theme.OnSurface
import com.streamvault.app.ui.theme.OnSurfaceDim
import com.streamvault.app.ui.theme.Primary
import com.streamvault.app.ui.theme.SurfaceElevated
+import com.streamvault.app.ui.interaction.mouseClickable
+import androidx.compose.foundation.layout.BoxWithConstraints
+import androidx.compose.ui.Alignment
import com.streamvault.domain.model.Category
import kotlinx.coroutines.delay
@@ -56,8 +59,17 @@ fun CategoryOptionsDialog(
onDismissRequest = safeDismiss,
properties = DialogProperties(usePlatformDefaultWidth = false)
) {
+ BoxWithConstraints(
+ modifier = Modifier.fillMaxWidth(),
+ contentAlignment = Alignment.Center
+ ) {
+ val dialogWidth = when {
+ maxWidth < 700.dp -> 0.9f
+ maxWidth < 1280.dp -> 0.56f
+ else -> 0.38f
+ }
Surface(
- modifier = Modifier.fillMaxWidth(0.38f),
+ modifier = Modifier.fillMaxWidth(dialogWidth),
shape = RoundedCornerShape(24.dp),
colors = SurfaceDefaults.colors(containerColor = SurfaceElevated)
) {
@@ -144,6 +156,7 @@ fun CategoryOptionsDialog(
Button(
onClick = safeDismiss,
+ modifier = Modifier.mouseClickable(onClick = safeDismiss),
colors = ButtonDefaults.colors(
containerColor = Color.White.copy(alpha = 0.08f),
contentColor = OnSurface
@@ -153,6 +166,7 @@ fun CategoryOptionsDialog(
}
}
}
+ }
}
}
@@ -164,7 +178,7 @@ private fun PremiumDialogAction(
) {
Button(
onClick = onClick,
- modifier = Modifier.fillMaxWidth(),
+ modifier = Modifier.fillMaxWidth().mouseClickable(onClick = onClick),
colors = ButtonDefaults.colors(
containerColor = if (destructive) MaterialTheme.colorScheme.errorContainer else Color.White.copy(alpha = 0.08f),
contentColor = if (destructive) MaterialTheme.colorScheme.onErrorContainer else OnSurface
diff --git a/app/src/main/java/com/streamvault/app/ui/components/dialogs/CreateGroupDialog.kt b/app/src/main/java/com/streamvault/app/ui/components/dialogs/CreateGroupDialog.kt
index a061ad3f..3b30dfdd 100644
--- a/app/src/main/java/com/streamvault/app/ui/components/dialogs/CreateGroupDialog.kt
+++ b/app/src/main/java/com/streamvault/app/ui/components/dialogs/CreateGroupDialog.kt
@@ -39,6 +39,7 @@ import androidx.tv.material3.SurfaceDefaults
import androidx.tv.material3.Text
import com.streamvault.app.R
import com.streamvault.app.device.rememberIsTelevisionDevice
+import com.streamvault.app.ui.interaction.mouseClickable
import com.streamvault.app.ui.theme.OnSurface
import com.streamvault.app.ui.theme.OnSurfaceDim
import com.streamvault.app.ui.theme.Primary
@@ -132,13 +133,22 @@ fun CreateGroupDialog(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(12.dp)
) {
+ val cancelHandler = {
+ if (canInteract) {
+ keyboardController?.hide()
+ onDismissRequest()
+ }
+ }
+ val createHandler = {
+ val normalized = value.trim()
+ if (canInteract && normalized.isNotEmpty()) {
+ keyboardController?.hide()
+ onConfirm(normalized)
+ }
+ }
Button(
- onClick = {
- if (canInteract) {
- keyboardController?.hide()
- onDismissRequest()
- }
- },
+ onClick = cancelHandler,
+ modifier = Modifier.mouseClickable(onClick = cancelHandler),
colors = ButtonDefaults.colors(
containerColor = Color.White.copy(alpha = 0.08f),
contentColor = OnSurface
@@ -147,14 +157,12 @@ fun CreateGroupDialog(
Text(stringResource(R.string.add_group_cancel))
}
Button(
- onClick = {
- val normalized = value.trim()
- if (canInteract && normalized.isNotEmpty()) {
- keyboardController?.hide()
- onConfirm(normalized)
- }
- },
+ onClick = createHandler,
enabled = canInteract && value.trim().isNotEmpty(),
+ modifier = Modifier.mouseClickable(
+ enabled = canInteract && value.trim().isNotEmpty(),
+ onClick = createHandler
+ ),
colors = ButtonDefaults.colors(
containerColor = Primary,
contentColor = Color.White
diff --git a/app/src/main/java/com/streamvault/app/ui/components/dialogs/DeleteGroupDialog.kt b/app/src/main/java/com/streamvault/app/ui/components/dialogs/DeleteGroupDialog.kt
index b6909527..354f6a2c 100644
--- a/app/src/main/java/com/streamvault/app/ui/components/dialogs/DeleteGroupDialog.kt
+++ b/app/src/main/java/com/streamvault/app/ui/components/dialogs/DeleteGroupDialog.kt
@@ -30,6 +30,7 @@ import androidx.tv.material3.SurfaceDefaults
import androidx.tv.material3.Text
import com.streamvault.app.R
import com.streamvault.app.device.rememberIsTelevisionDevice
+import com.streamvault.app.ui.interaction.mouseClickable
import com.streamvault.app.ui.theme.ErrorColor
import com.streamvault.app.ui.theme.OnSurface
import com.streamvault.app.ui.theme.OnSurfaceDim
@@ -90,6 +91,7 @@ fun DeleteGroupDialog(
) {
Button(
onClick = safeDismiss,
+ modifier = Modifier.mouseClickable(onClick = safeDismiss),
colors = ButtonDefaults.colors(
containerColor = Color.White.copy(alpha = 0.08f),
contentColor = OnSurface
@@ -99,6 +101,7 @@ fun DeleteGroupDialog(
}
Button(
onClick = { if (canInteract) onConfirmDelete() },
+ modifier = Modifier.mouseClickable(onClick = { if (canInteract) onConfirmDelete() }),
colors = ButtonDefaults.colors(
containerColor = ErrorColor,
contentColor = Color.White
diff --git a/app/src/main/java/com/streamvault/app/ui/components/dialogs/PinDialog.kt b/app/src/main/java/com/streamvault/app/ui/components/dialogs/PinDialog.kt
index aa85ed70..d6f32610 100644
--- a/app/src/main/java/com/streamvault/app/ui/components/dialogs/PinDialog.kt
+++ b/app/src/main/java/com/streamvault/app/ui/components/dialogs/PinDialog.kt
@@ -20,6 +20,7 @@ import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import com.streamvault.app.device.rememberIsTelevisionDevice
+import com.streamvault.app.ui.interaction.mouseClickable
import com.streamvault.app.ui.theme.ErrorColor
import com.streamvault.app.ui.theme.FocusBorder
import com.streamvault.app.ui.theme.Primary
@@ -110,6 +111,15 @@ fun PinDialog(
}
val keys = listOf("1", "2", "3", "4", "5", "6", "7", "8", "9", "", "0", "⌫")
+ val handleKeyPress: (String) -> Unit = { key ->
+ if (canInteract) {
+ if (key == "⌫") {
+ if (pin.isNotEmpty()) pin = pin.dropLast(1)
+ } else if (pin.length < 4) {
+ pin += key
+ }
+ }
+ }
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
keys.chunked(3).forEach { row ->
Row(
@@ -123,17 +133,11 @@ fun PinDialog(
Spacer(modifier = Modifier.fillMaxWidth().height(48.dp))
} else {
Button(
- onClick = {
- if (!canInteract) return@Button
- if (key == "⌫") {
- if (pin.isNotEmpty()) pin = pin.dropLast(1)
- } else if (pin.length < 4) {
- pin += key
- }
- },
+ onClick = { handleKeyPress(key) },
modifier = Modifier
.fillMaxWidth()
- .then(if (isFirst) Modifier.focusRequester(firstKeyFocusRequester) else Modifier),
+ .then(if (isFirst) Modifier.focusRequester(firstKeyFocusRequester) else Modifier)
+ .mouseClickable(onClick = { handleKeyPress(key) }),
colors = ButtonDefaults.colors(
containerColor = Color.White.copy(alpha = 0.08f),
contentColor = Color.White,
@@ -153,8 +157,10 @@ fun PinDialog(
}
}
+ val dismissHandler = { if (canInteract) onDismissRequest() }
Button(
- onClick = { if (canInteract) onDismissRequest() },
+ onClick = dismissHandler,
+ modifier = Modifier.mouseClickable(onClick = dismissHandler),
colors = ButtonDefaults.colors(
containerColor = Color.Transparent,
contentColor = Color.White.copy(alpha = 0.7f),
diff --git a/app/src/main/java/com/streamvault/app/ui/components/dialogs/PremiumDialog.kt b/app/src/main/java/com/streamvault/app/ui/components/dialogs/PremiumDialog.kt
index 706b30de..23c9e1b9 100644
--- a/app/src/main/java/com/streamvault/app/ui/components/dialogs/PremiumDialog.kt
+++ b/app/src/main/java/com/streamvault/app/ui/components/dialogs/PremiumDialog.kt
@@ -32,6 +32,7 @@ import androidx.tv.material3.Surface
import androidx.tv.material3.SurfaceDefaults
import androidx.tv.material3.Text
import com.streamvault.app.device.rememberIsTelevisionDevice
+import com.streamvault.app.ui.interaction.mouseClickable
import com.streamvault.app.ui.design.AppColors
import com.streamvault.app.ui.design.FocusSpec
@@ -178,7 +179,7 @@ fun PremiumDialogActionButton(
Button(
onClick = onClick,
enabled = enabled,
- modifier = modifier.fillMaxWidth(),
+ modifier = modifier.fillMaxWidth().mouseClickable(enabled = enabled, onClick = onClick),
colors = ButtonDefaults.colors(
containerColor = containerColor,
contentColor = contentColor,
@@ -219,6 +220,7 @@ fun PremiumDialogFooterButton(
Button(
onClick = onClick,
enabled = enabled,
+ modifier = Modifier.mouseClickable(enabled = enabled, onClick = onClick),
colors = ButtonDefaults.colors(
containerColor = containerColor,
contentColor = contentColor,
diff --git a/app/src/main/java/com/streamvault/app/ui/components/dialogs/RenameGroupDialog.kt b/app/src/main/java/com/streamvault/app/ui/components/dialogs/RenameGroupDialog.kt
index 619e32e0..2fdf83af 100644
--- a/app/src/main/java/com/streamvault/app/ui/components/dialogs/RenameGroupDialog.kt
+++ b/app/src/main/java/com/streamvault/app/ui/components/dialogs/RenameGroupDialog.kt
@@ -44,6 +44,7 @@ import com.streamvault.app.ui.design.requestFocusSafely
import com.streamvault.app.ui.design.FocusSpec
import com.streamvault.app.R
import com.streamvault.app.device.rememberIsTelevisionDevice
+import com.streamvault.app.ui.interaction.mouseClickable
import com.streamvault.app.ui.theme.FocusBorder
import com.streamvault.app.ui.theme.OnSurface
import com.streamvault.app.ui.theme.OnSurfaceDim
@@ -145,13 +146,22 @@ fun RenameGroupDialog(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(12.dp)
) {
+ val cancelHandler = {
+ if (canInteract) {
+ keyboardController?.hide()
+ onDismissRequest()
+ }
+ }
+ val renameHandler = {
+ val normalized = value.trim()
+ if (canInteract && normalized.isNotEmpty()) {
+ keyboardController?.hide()
+ onConfirm(normalized)
+ }
+ }
Button(
- onClick = {
- if (canInteract) {
- keyboardController?.hide()
- onDismissRequest()
- }
- },
+ onClick = cancelHandler,
+ modifier = Modifier.mouseClickable(onClick = cancelHandler),
colors = ButtonDefaults.colors(
containerColor = Color.White.copy(alpha = 0.08f),
contentColor = OnSurface,
@@ -168,14 +178,12 @@ fun RenameGroupDialog(
Text(stringResource(R.string.add_group_cancel))
}
Button(
- onClick = {
- val normalized = value.trim()
- if (canInteract && normalized.isNotEmpty()) {
- keyboardController?.hide()
- onConfirm(normalized)
- }
- },
+ onClick = renameHandler,
enabled = canInteract && value.trim().isNotEmpty(),
+ modifier = Modifier.mouseClickable(
+ enabled = canInteract && value.trim().isNotEmpty(),
+ onClick = renameHandler
+ ),
colors = ButtonDefaults.colors(
containerColor = Primary,
contentColor = Color.White,
diff --git a/app/src/main/java/com/streamvault/app/ui/interaction/MouseSupport.kt b/app/src/main/java/com/streamvault/app/ui/interaction/MouseSupport.kt
index a33d7498..3ff52366 100644
--- a/app/src/main/java/com/streamvault/app/ui/interaction/MouseSupport.kt
+++ b/app/src/main/java/com/streamvault/app/ui/interaction/MouseSupport.kt
@@ -2,51 +2,76 @@ package com.streamvault.app.ui.interaction
import android.view.InputDevice
import android.view.MotionEvent
-import androidx.compose.ui.composed
+import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
-import androidx.compose.ui.input.pointer.pointerInteropFilter
+import androidx.compose.ui.composed
import androidx.compose.ui.focus.FocusRequester
+import androidx.compose.ui.input.pointer.pointerInput
+import androidx.compose.ui.input.pointer.pointerInteropFilter
+import androidx.compose.ui.platform.LocalContext
+import com.streamvault.app.device.isTelevisionDevice
+/**
+ * Makes a TV-Surface-wrapped composable respond correctly to both remote-pointer
+ * (mouse/trackpad) and finger-touch input.
+ *
+ * - **TV / no touchscreen**: existing `pointerInteropFilter` path (mouse pointer clicks).
+ * - **Phone / tablet**: `pointerInput + detectTapGestures` fires [onClick] on the FIRST
+ * tap (and [onLongClick] on a long-press) by intercepting the pointer event before the
+ * TV Surface's focus-first machinery can suppress it. `detectTapGestures` consumes
+ * the event so the inner TV Surface's `combinedClickable` does not double-fire.
+ */
fun Modifier.mouseClickable(
enabled: Boolean = true,
focusRequester: FocusRequester? = null,
- onClick: () -> Unit
+ onLongClick: (() -> Unit)? = null,
+ onClick: () -> Unit,
): Modifier = composed {
+ val context = LocalContext.current
+ val isTv = remember(context) { context.isTelevisionDevice() }
var pressedFromMouse by remember { mutableStateOf(false) }
- pointerInteropFilter { event ->
- if (!enabled || !event.isMouseLikePrimaryPress()) {
- return@pointerInteropFilter false
- }
-
- when (event.actionMasked) {
- MotionEvent.ACTION_DOWN,
- MotionEvent.ACTION_BUTTON_PRESS -> {
- pressedFromMouse = true
- focusRequester?.requestFocus()
- true
+ if (!isTv) {
+ // Phone / tablet path: intercept touch so the first tap fires the action without
+ // needing the TV Surface's "focus first, then click on second tap" behaviour.
+ if (enabled) {
+ this.pointerInput(onClick, onLongClick) {
+ detectTapGestures(
+ onTap = { _ -> onClick() },
+ onLongPress = onLongClick?.let { lc -> { _ -> lc() } }
+ )
}
-
- MotionEvent.ACTION_UP,
- MotionEvent.ACTION_BUTTON_RELEASE -> {
- val shouldClick = pressedFromMouse
- pressedFromMouse = false
- if (shouldClick) {
- onClick()
+ } else {
+ this
+ }
+ } else {
+ // TV path: existing mouse / pointer-device interop filter.
+ this.pointerInteropFilter { event ->
+ if (!enabled || !event.isMouseLikePrimaryPress()) return@pointerInteropFilter false
+ when (event.actionMasked) {
+ MotionEvent.ACTION_DOWN,
+ MotionEvent.ACTION_BUTTON_PRESS -> {
+ pressedFromMouse = true
+ focusRequester?.requestFocus()
+ true
}
- shouldClick
- }
-
- MotionEvent.ACTION_CANCEL -> {
- pressedFromMouse = false
- false
+ MotionEvent.ACTION_UP,
+ MotionEvent.ACTION_BUTTON_RELEASE -> {
+ val shouldClick = pressedFromMouse
+ pressedFromMouse = false
+ if (shouldClick) onClick()
+ shouldClick
+ }
+ MotionEvent.ACTION_CANCEL -> {
+ pressedFromMouse = false
+ false
+ }
+ else -> false
}
-
- else -> false
}
}
}
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.kt
index f16ebc9c..0f8cb443 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
@@ -614,12 +614,33 @@ class EpgViewModel @Inject constructor(
}
val guideKeys = channels.mapNotNull(Channel::guideLookupKey).distinct()
- val xmltvKeys = channels.mapNotNull { it.epgChannelId?.trim()?.takeIf { value -> value.isNotEmpty() } }.distinct()
- val programsByChannel = runCatching {
- if (xmltvKeys.isEmpty()) emptyMap()
- else epgRepository.getProgramsForChannels(providerId, xmltvKeys, windowStart, windowEnd).first()
+
+ // 1. Try the multi-source resolved path first
+ val channelIds = channels.map { it.id }
+ val resolvedPrograms = runCatching {
+ epgRepository.getResolvedProgramsForChannels(providerId, channelIds, windowStart, windowEnd)
}.getOrElse { emptyMap() }
+ // 2. For channels not covered by resolution, fall back to legacy provider-native query
+ val unresolvedChannels = channels.filter { channel ->
+ val key = channel.guideLookupKey()
+ key == null || resolvedPrograms[key].isNullOrEmpty()
+ }
+ val legacyPrograms = if (unresolvedChannels.isNotEmpty()) {
+ val xmltvKeys = unresolvedChannels.mapNotNull {
+ it.epgChannelId?.trim()?.takeIf(String::isNotEmpty)
+ }.distinct()
+ runCatching {
+ if (xmltvKeys.isEmpty()) emptyMap()
+ else epgRepository.getProgramsForChannels(providerId, xmltvKeys, windowStart, windowEnd).first()
+ }.getOrElse { emptyMap() }
+ } else {
+ emptyMap()
+ }
+
+ val programsByChannel = resolvedPrograms + legacyPrograms
+
+ // 3. Xtream on-demand fallback for still-missing channels
val fallbackProgramsByChannel = fetchXtreamGuideFallback(
provider = provider,
providerId = providerId,
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.kt
index 5caf91de..dfc28af3 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
@@ -15,6 +15,7 @@ import androidx.compose.runtime.*
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
+import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.ui.unit.dp
import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel
import androidx.tv.material3.*
@@ -641,7 +642,7 @@ private fun MoviesVodContent(
}
LazyVerticalGrid(
- columns = GridCells.Adaptive(minSize = 148.dp),
+ columns = GridCells.Adaptive(minSize = 136.dp),
modifier = Modifier
.fillMaxSize()
.onPreviewKeyEvent { event ->
@@ -756,6 +757,9 @@ private fun MoviesVodContent(
isLocked = isLocked,
isReorderMode = uiState.isReorderMode,
isDragging = isDraggingThis,
+ modifier = Modifier
+ .fillMaxWidth()
+ .aspectRatio(2f / 3f),
onClick = {
if (uiState.isReorderMode) {
draggingMovie = if (isDraggingThis) null else movie
@@ -1028,7 +1032,7 @@ private fun MoviesVodClassicContent(
}
LazyVerticalGrid(
- columns = GridCells.Adaptive(minSize = 148.dp),
+ columns = GridCells.Adaptive(minSize = 136.dp),
modifier = Modifier
.fillMaxWidth()
.weight(1f)
@@ -1072,6 +1076,9 @@ private fun MoviesVodClassicContent(
isLocked = isLocked,
isReorderMode = uiState.isReorderMode,
isDragging = isDraggingThis,
+ modifier = Modifier
+ .fillMaxWidth()
+ .aspectRatio(2f / 3f),
onClick = {
if (uiState.isReorderMode) {
draggingMovie = if (isDraggingThis) null else movie
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.kt
index ae9a00cf..e6979c7f 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
@@ -214,16 +214,14 @@ class MoviesViewModel @Inject constructor(
favoriteRepository.getAllFavorites(ContentType.MOVIE),
getCustomCategories(ContentType.MOVIE),
movieRepository.getCategories(provider.id),
- movieRepository.getCategoryItemCounts(provider.id),
preferencesRepository.getHiddenCategoryIds(provider.id, ContentType.MOVIE),
preferencesRepository.getCategorySortMode(provider.id, ContentType.MOVIE)
) { values ->
val allFavorites = values[0] as List<com.streamvault.domain.model.Favorite>
val customCategories = values[1] as List<Category>
val providerCategories = values[2] as List<Category>
- val providerCategoryCounts = values[3] as Map<Long, Int>
- val hiddenCategoryIds = values[4] as Set<Long>
- val sortMode = values[5] as CategorySortMode
+ val hiddenCategoryIds = values[3] as Set<Long>
+ val sortMode = values[4] as CategorySortMode
MovieCategorySelectionDependencies(
allFavorites = allFavorites,
customCategories = customCategories,
@@ -232,7 +230,6 @@ class MoviesViewModel @Inject constructor(
hiddenCategoryIds = hiddenCategoryIds,
sortMode = sortMode
),
- providerCategoryCounts = providerCategoryCounts,
hiddenCategoryIds = hiddenCategoryIds
)
}.combine(
@@ -262,7 +259,6 @@ class MoviesViewModel @Inject constructor(
allFavorites = dependencies.allFavorites,
customCategories = dependencies.customCategories,
providerCategories = dependencies.providerCategories,
- providerCategoryCounts = dependencies.providerCategoryCounts,
hiddenCategoryIds = dependencies.hiddenCategoryIds
)
}
@@ -1078,7 +1074,6 @@ private data class MovieCategorySelectionDependencies(
val allFavorites: List<com.streamvault.domain.model.Favorite>,
val customCategories: List<Category>,
val providerCategories: List<Category>,
- val providerCategoryCounts: Map<Long, Int>,
val hiddenCategoryIds: Set<Long>
)
@@ -1092,7 +1087,6 @@ private data class SelectedMovieCategoryRequest(
val allFavorites: List<com.streamvault.domain.model.Favorite>,
val customCategories: List<Category>,
val providerCategories: List<Category>,
- val providerCategoryCounts: Map<Long, Int>,
val hiddenCategoryIds: Set<Long>
)
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/multiview/MultiViewScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/multiview/MultiViewScreen.kt
index ed6d0f80..3221a8db 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/multiview/MultiViewScreen.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/multiview/MultiViewScreen.kt
@@ -1,7 +1,9 @@
package com.streamvault.app.ui.screens.multiview
+import android.app.Activity
import android.view.View
import android.view.KeyEvent
+import android.view.WindowManager
import androidx.activity.compose.BackHandler
import androidx.annotation.OptIn
import androidx.compose.animation.AnimatedVisibility
@@ -133,6 +135,13 @@ fun MultiViewScreen(
}
}
+ // Prevent screen from sleeping while watching multiview
+ val multiViewWindow = (LocalContext.current as? Activity)?.window
+ DisposableEffect(Unit) {
+ multiViewWindow?.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
+ onDispose { multiViewWindow?.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) }
+ }
+
DisposableEffect(lifecycleOwner, viewModel) {
val observer = LifecycleEventObserver { _, event ->
when (event) {
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.kt
index 5e6ebfa4..58f507f4 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
@@ -2,6 +2,7 @@ package com.streamvault.app.ui.screens.player
import android.app.Activity
import android.view.KeyEvent
+import android.view.WindowManager
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
@@ -236,6 +237,19 @@ fun PlayerScreen(
}
}
+ // Prevent screen from sleeping during active playback
+ val playerWindow = mainActivity?.window
+ DisposableEffect(Unit) {
+ onDispose { playerWindow?.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) }
+ }
+ LaunchedEffect(isPlaying, playbackState) {
+ if (isPlaying || playbackState == PlaybackState.BUFFERING) {
+ playerWindow?.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
+ } else {
+ playerWindow?.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
+ }
+ }
+
// Consolidated focus management for all overlays
val liveOverlayVisible = contentType == "LIVE" && (showChannelListOverlay || showCategoryListOverlay || showEpgOverlay || showChannelInfoOverlay)
val anyOverlayVisible = liveOverlayVisible || showTrackSelection != null || showSpeedSelection || showProgramHistory || showSplitDialog || showDiagnostics
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.kt
index 2b122a46..5fcce956 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
@@ -7,6 +7,7 @@ import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
+import com.streamvault.app.ui.interaction.mouseClickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
@@ -534,7 +535,7 @@ private fun SourceTypeCard(
) {
Surface(
onClick = { if (enabled) onClick() },
- modifier = Modifier.fillMaxWidth(),
+ modifier = Modifier.fillMaxWidth().mouseClickable(enabled = enabled, onClick = onClick),
shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(12.dp)),
colors = ClickableSurfaceDefaults.colors(
containerColor = if (selected) Primary.copy(alpha = 0.18f) else SurfaceElevated,
@@ -710,7 +711,8 @@ private fun ActionButton(
.fillMaxWidth()
.height(52.dp)
.scale(scale)
- .onFocusEvent { isFocused = it.hasFocus },
+ .onFocusEvent { isFocused = it.hasFocus }
+ .mouseClickable(enabled = !isLoading, onClick = onClick),
shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(10.dp)),
colors = ClickableSurfaceDefaults.colors(
containerColor = if (!isLoading) Primary else SurfaceHighlight,
@@ -751,7 +753,7 @@ private fun FileSelectorCard(
Surface(
onClick = onClick,
- modifier = Modifier.fillMaxWidth().height(80.dp).onFocusEvent { isFocused = it.hasFocus },
+ modifier = Modifier.fillMaxWidth().height(80.dp).onFocusEvent { isFocused = it.hasFocus }.mouseClickable(onClick = onClick),
shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(12.dp)),
border = ClickableSurfaceDefaults.border(
border = Border(BorderStroke(1.dp, borderColor)),
@@ -782,7 +784,7 @@ private fun TabButton(text: String, isSelected: Boolean, onClick: () -> Unit) {
var isFocused by remember { mutableStateOf(false) }
Surface(
onClick = onClick,
- modifier = Modifier.onFocusEvent { isFocused = it.hasFocus },
+ modifier = Modifier.onFocusEvent { isFocused = it.hasFocus }.mouseClickable(onClick = onClick),
shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(10.dp)),
colors = ClickableSurfaceDefaults.colors(
containerColor = if (isSelected) Primary.copy(alpha = 0.2f) else Surface,
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.kt
index ccb024f0..04f3f6ae 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
@@ -16,6 +16,7 @@ import androidx.compose.runtime.*
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
+import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.ui.unit.dp
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel
@@ -628,7 +629,7 @@ private fun SeriesVodContent(
}
LazyVerticalGrid(
- columns = GridCells.Adaptive(minSize = 148.dp),
+ columns = GridCells.Adaptive(minSize = 136.dp),
modifier = Modifier
.fillMaxSize()
.onPreviewKeyEvent { event ->
@@ -743,6 +744,9 @@ private fun SeriesVodContent(
isLocked = isLocked,
isReorderMode = uiState.isReorderMode,
isDragging = isDraggingThis,
+ modifier = Modifier
+ .fillMaxWidth()
+ .aspectRatio(2f / 3f),
onClick = {
if (uiState.isReorderMode) {
draggingSeries = if (isDraggingThis) null else series
@@ -1015,7 +1019,7 @@ private fun SeriesVodClassicContent(
}
LazyVerticalGrid(
- columns = GridCells.Adaptive(minSize = 148.dp),
+ columns = GridCells.Adaptive(minSize = 136.dp),
modifier = Modifier
.fillMaxWidth()
.weight(1f)
@@ -1059,6 +1063,9 @@ private fun SeriesVodClassicContent(
isLocked = isLocked,
isReorderMode = uiState.isReorderMode,
isDragging = isDraggingThis,
+ modifier = Modifier
+ .fillMaxWidth()
+ .aspectRatio(2f / 3f),
onClick = {
if (uiState.isReorderMode) {
draggingSeries = if (isDraggingThis) null else series
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.kt
index 13710043..c3ec2b8d 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
@@ -212,7 +212,6 @@ class SeriesViewModel @Inject constructor(
favoriteRepository.getAllFavorites(ContentType.SERIES),
getCustomCategories(ContentType.SERIES),
seriesRepository.getCategories(provider.id),
- seriesRepository.getCategoryItemCounts(provider.id),
playbackHistoryRepository.getRecentlyWatchedByProvider(provider.id, limit = 2_000),
preferencesRepository.getHiddenCategoryIds(provider.id, ContentType.SERIES),
preferencesRepository.getCategorySortMode(provider.id, ContentType.SERIES)
@@ -220,10 +219,9 @@ class SeriesViewModel @Inject constructor(
val allFavorites = values[0] as List<com.streamvault.domain.model.Favorite>
val customCategories = values[1] as List<Category>
val providerCategories = values[2] as List<Category>
- val providerCategoryCounts = values[3] as Map<Long, Int>
- val history = values[4] as List<PlaybackHistory>
- val hiddenCategoryIds = values[5] as Set<Long>
- val sortMode = values[6] as CategorySortMode
+ val history = values[3] as List<PlaybackHistory>
+ val hiddenCategoryIds = values[4] as Set<Long>
+ val sortMode = values[5] as CategorySortMode
SeriesCategorySelectionDependencies(
allFavorites = allFavorites,
customCategories = customCategories,
@@ -232,7 +230,6 @@ class SeriesViewModel @Inject constructor(
hiddenCategoryIds = hiddenCategoryIds,
sortMode = sortMode
),
- providerCategoryCounts = providerCategoryCounts,
history = history,
hiddenCategoryIds = hiddenCategoryIds
)
@@ -264,7 +261,6 @@ class SeriesViewModel @Inject constructor(
history = dependencies.history,
customCategories = dependencies.customCategories,
providerCategories = dependencies.providerCategories,
- providerCategoryCounts = dependencies.providerCategoryCounts,
hiddenCategoryIds = dependencies.hiddenCategoryIds
)
}
@@ -1080,7 +1076,6 @@ private data class SeriesCategorySelectionDependencies(
val history: List<PlaybackHistory>,
val customCategories: List<Category>,
val providerCategories: List<Category>,
- val providerCategoryCounts: Map<Long, Int>,
val hiddenCategoryIds: Set<Long>
)
@@ -1095,7 +1090,6 @@ private data class SelectedSeriesCategoryRequest(
val history: List<PlaybackHistory>,
val customCategories: List<Category>,
val providerCategories: List<Category>,
- val providerCategoryCounts: Map<Long, Int>,
val hiddenCategoryIds: Set<Long>
)
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.kt
index b01f91a7..1bf615da 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
@@ -2,11 +2,13 @@ package com.streamvault.app.ui.screens.settings
import androidx.compose.foundation.background
import androidx.compose.foundation.border
+import androidx.compose.ui.draw.clip
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
+import androidx.compose.foundation.text.BasicTextField
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.compose.runtime.*
import androidx.compose.runtime.saveable.rememberSaveable
@@ -24,6 +26,7 @@ import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.graphics.SolidColor
import androidx.compose.foundation.clickable
import androidx.compose.material3.Switch
import androidx.compose.material3.RadioButton
@@ -208,7 +211,8 @@ fun SettingsScreen(
item { SettingsNavItem(stringResource(R.string.settings_privacy), "L", Color(0xFFFFB74D), selectedCategory == 2) { selectedCategory = 2 } }
item { SettingsNavItem(stringResource(R.string.settings_recording_title), "R", Color(0xFFEF5350), selectedCategory == 3) { selectedCategory = 3 } }
item { SettingsNavItem(stringResource(R.string.settings_backup_restore), "B", Color(0xFF42A5F5), selectedCategory == 4) { selectedCategory = 4 } }
- item { SettingsNavItem(stringResource(R.string.settings_about), "i", Color(0xFF78909C), selectedCategory == 5) { selectedCategory = 5 } }
+ item { SettingsNavItem("EPG Sources", "E", Color(0xFF66BB6A), selectedCategory == 5) { selectedCategory = 5; viewModel.loadEpgSources() } }
+ item { SettingsNavItem(stringResource(R.string.settings_about), "i", Color(0xFF78909C), selectedCategory == 6) { selectedCategory = 6 } }
}
// Thin vertical separator
@@ -624,7 +628,259 @@ fun SettingsScreen(
}
}
- // ── 5: About ──────────────────────────────────────────────
+ // ── 5: EPG Sources ───────────────────────────────────────
+ else if (selectedCategory == 5) {
+ val epgSources = uiState.epgSources
+ val providers = uiState.providers
+
+ item {
+ Text(
+ text = "EPG Sources",
+ style = MaterialTheme.typography.titleMedium,
+ color = Color(0xFF66BB6A),
+ modifier = Modifier.padding(bottom = 8.dp)
+ )
+ Text(
+ text = "Add external XMLTV EPG sources and assign them to providers. External sources are matched to channels by ID or name and override provider-native EPG data.",
+ style = MaterialTheme.typography.bodySmall,
+ color = OnSurfaceDim,
+ modifier = Modifier.padding(bottom = 16.dp)
+ )
+ }
+
+ // Add source form
+ item {
+ var newName by remember { mutableStateOf("") }
+ var newUrl by remember { mutableStateOf("") }
+ val ctx = androidx.compose.ui.platform.LocalContext.current
+ val filePickerLauncher = rememberLauncherForActivityResult(
+ contract = ActivityResultContracts.OpenDocument()
+ ) { uri ->
+ if (uri != null) {
+ try {
+ ctx.contentResolver.takePersistableUriPermission(
+ uri, android.content.Intent.FLAG_GRANT_READ_URI_PERMISSION
+ )
+ } catch (_: SecurityException) { /* provider does not offer persistable permission */ }
+ newUrl = uri.toString()
+ }
+ }
+ Box(
+ modifier = Modifier
+ .fillMaxWidth()
+ .clip(RoundedCornerShape(12.dp))
+ .background(Color.White.copy(alpha = 0.06f))
+ ) {
+ Column(modifier = Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
+ Text("Add EPG Source", style = MaterialTheme.typography.titleSmall, color = Color.White)
+ EpgSourceTextField(value = newName, onValueChange = { newName = it }, placeholder = "Source name")
+ Row(
+ horizontalArrangement = Arrangement.spacedBy(8.dp),
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ Box(modifier = Modifier.weight(1f)) {
+ EpgSourceTextField(
+ value = newUrl,
+ onValueChange = { newUrl = it },
+ placeholder = "XMLTV URL (HTTPS) or browse file"
+ )
+ }
+ Surface(
+ onClick = { filePickerLauncher.launch(arrayOf("*/*")) },
+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(8.dp)),
+ colors = ClickableSurfaceDefaults.colors(
+ containerColor = Primary.copy(alpha = 0.15f),
+ focusedContainerColor = Primary.copy(alpha = 0.3f)
+ ),
+ scale = ClickableSurfaceDefaults.scale(focusedScale = 1f)
+ ) {
+ Text("Browse", modifier = Modifier.padding(horizontal = 12.dp, vertical = 10.dp), style = MaterialTheme.typography.labelMedium, color = Primary)
+ }
+ }
+ Surface(
+ onClick = {
+ if (newName.isNotBlank() && newUrl.isNotBlank()) {
+ viewModel.addEpgSource(newName.trim(), newUrl.trim())
+ newName = ""
+ newUrl = ""
+ }
+ },
+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(8.dp)),
+ colors = ClickableSurfaceDefaults.colors(
+ containerColor = Color(0xFF66BB6A).copy(alpha = 0.2f),
+ focusedContainerColor = Color(0xFF66BB6A).copy(alpha = 0.4f)
+ ),
+ scale = ClickableSurfaceDefaults.scale(focusedScale = 1f)
+ ) {
+ Text("Add Source", modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp), color = Color(0xFF66BB6A))
+ }
+ }
+ }
+ }
+
+ // Source list
+ if (epgSources.isEmpty()) {
+ item {
+ Text(
+ text = "No external EPG sources configured. Add a source above to get started.",
+ style = MaterialTheme.typography.bodyMedium,
+ color = OnSurfaceDim,
+ modifier = Modifier.padding(vertical = 16.dp)
+ )
+ }
+ } else {
+ items(epgSources.size) { index ->
+ val source = epgSources[index]
+ Box(
+ modifier = Modifier
+ .fillMaxWidth()
+ .clip(RoundedCornerShape(12.dp))
+ .background(Color.White.copy(alpha = 0.06f))
+ ) {
+ Column(modifier = Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) {
+ Row(verticalAlignment = Alignment.CenterVertically) {
+ Column(modifier = Modifier.weight(1f)) {
+ Text(source.name, style = MaterialTheme.typography.titleSmall, color = Color.White)
+ Text(displayableEpgUrl(source.url), style = MaterialTheme.typography.bodySmall, color = OnSurfaceDim, maxLines = 1)
+ if (source.lastError != null) {
+ Text("Error: ${source.lastError}", style = MaterialTheme.typography.bodySmall, color = Color(0xFFEF5350))
+ }
+ if (source.lastSuccessAt != null) {
+ val ago = (System.currentTimeMillis() - source.lastSuccessAt) / 60000
+ Text("Last synced: ${ago}m ago", style = MaterialTheme.typography.bodySmall, color = OnSurfaceDim)
+ }
+ }
+ Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ Surface(
+ onClick = { viewModel.toggleEpgSourceEnabled(source.id, !source.enabled) },
+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(8.dp)),
+ 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)
+ ),
+ scale = ClickableSurfaceDefaults.scale(focusedScale = 1f)
+ ) {
+ Text(
+ if (source.enabled) "ON" else "OFF",
+ modifier = Modifier.padding(horizontal = 12.dp, vertical = 6.dp),
+ style = MaterialTheme.typography.labelSmall,
+ color = if (source.enabled) Color(0xFF66BB6A) else OnSurfaceDim
+ )
+ }
+ Surface(
+ onClick = { viewModel.refreshEpgSource(source.id) },
+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(8.dp)),
+ colors = ClickableSurfaceDefaults.colors(
+ containerColor = Primary.copy(alpha = 0.15f),
+ focusedContainerColor = Primary.copy(alpha = 0.3f)
+ ),
+ scale = ClickableSurfaceDefaults.scale(focusedScale = 1f)
+ ) {
+ Text("Refresh", modifier = Modifier.padding(horizontal = 12.dp, vertical = 6.dp), style = MaterialTheme.typography.labelSmall, color = Primary)
+ }
+ Surface(
+ 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))
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ // Provider assignment section
+ if (providers.isNotEmpty() && epgSources.isNotEmpty()) {
+ item {
+ Text(
+ text = "Provider Assignments",
+ style = MaterialTheme.typography.titleMedium,
+ color = Color(0xFF66BB6A),
+ modifier = Modifier.padding(top = 24.dp, bottom = 8.dp)
+ )
+ Text(
+ text = "Assign EPG sources to providers. Channels will be matched automatically by ID or name.",
+ style = MaterialTheme.typography.bodySmall,
+ color = OnSurfaceDim,
+ modifier = Modifier.padding(bottom = 8.dp)
+ )
+ }
+ items(providers.size) { providerIndex ->
+ val provider = providers[providerIndex]
+ val assignments = uiState.epgSourceAssignments[provider.id].orEmpty()
+ val assignedSourceIds = assignments.map { it.epgSourceId }.toSet()
+ val unassignedSources = epgSources.filter { it.id !in assignedSourceIds }
+
+ LaunchedEffect(provider.id) {
+ viewModel.loadEpgAssignments(provider.id)
+ }
+
+ Box(
+ modifier = Modifier
+ .fillMaxWidth()
+ .clip(RoundedCornerShape(12.dp))
+ .background(Color.White.copy(alpha = 0.06f))
+ ) {
+ Column(modifier = Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
+ Text(provider.name, style = MaterialTheme.typography.titleSmall, color = Color.White)
+
+ if (assignments.isEmpty()) {
+ Text("No EPG sources assigned", style = MaterialTheme.typography.bodySmall, color = OnSurfaceDim)
+ } else {
+ assignments.forEach { assignment ->
+ Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {
+ Text(
+ "${assignment.epgSourceName} (priority: ${assignment.priority})",
+ style = MaterialTheme.typography.bodySmall,
+ color = Color.White,
+ modifier = Modifier.weight(1f)
+ )
+ Surface(
+ onClick = { viewModel.unassignEpgSourceFromProvider(provider.id, assignment.epgSourceId) },
+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(6.dp)),
+ colors = ClickableSurfaceDefaults.colors(
+ containerColor = Color(0xFFEF5350).copy(alpha = 0.12f),
+ focusedContainerColor = Color(0xFFEF5350).copy(alpha = 0.25f)
+ ),
+ scale = ClickableSurfaceDefaults.scale(focusedScale = 1f)
+ ) {
+ Text("Remove", modifier = Modifier.padding(horizontal = 8.dp, vertical = 4.dp), style = MaterialTheme.typography.labelSmall, color = Color(0xFFEF5350))
+ }
+ }
+ }
+ }
+
+ if (unassignedSources.isNotEmpty()) {
+ Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ unassignedSources.forEach { source ->
+ Surface(
+ onClick = { viewModel.assignEpgSourceToProvider(provider.id, source.id) },
+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(8.dp)),
+ colors = ClickableSurfaceDefaults.colors(
+ containerColor = Color(0xFF66BB6A).copy(alpha = 0.12f),
+ focusedContainerColor = Color(0xFF66BB6A).copy(alpha = 0.25f)
+ ),
+ scale = ClickableSurfaceDefaults.scale(focusedScale = 1f)
+ ) {
+ Text("+ ${source.name}", modifier = Modifier.padding(horizontal = 12.dp, vertical = 6.dp), style = MaterialTheme.typography.labelSmall, color = Color(0xFF66BB6A))
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ // ── 6: About ──────────────────────────────────────────────
else {
item {
SettingsRow(label = stringResource(R.string.settings_app_version), value = "${BuildConfig.VERSION_NAME} (${BuildConfig.VERSION_CODE})")
@@ -2702,6 +2958,52 @@ private fun RecordingItemCard(
}
}
+private fun displayableEpgUrl(url: String): String = when {
+ url.startsWith("content://") -> {
+ val lastSegment = try { android.net.Uri.parse(url).lastPathSegment } catch (_: Exception) { null }
+ val decoded = lastSegment?.let { android.net.Uri.decode(it) }?.substringAfterLast("/")?.substringAfterLast("\\")
+ if (!decoded.isNullOrBlank() && decoded.length < 60) "local: $decoded" else "local file"
+ }
+ else -> url
+}
+
+@Composable
+private fun EpgSourceTextField(
+ value: String,
+ onValueChange: (String) -> Unit,
+ placeholder: String
+) {
+ val focusRequester = remember { FocusRequester() }
+ var isFocused by remember { mutableStateOf(false) }
+ Surface(
+ onClick = { focusRequester.requestFocus() },
+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(8.dp)),
+ colors = ClickableSurfaceDefaults.colors(
+ containerColor = Color.White.copy(alpha = 0.08f),
+ focusedContainerColor = Color.White.copy(alpha = 0.12f)
+ ),
+ scale = ClickableSurfaceDefaults.scale(focusedScale = 1f),
+ modifier = Modifier.fillMaxWidth()
+ ) {
+ Box(modifier = Modifier.padding(horizontal = 12.dp, vertical = 10.dp)) {
+ if (value.isEmpty() && !isFocused) {
+ Text(placeholder, style = MaterialTheme.typography.bodyMedium, color = OnSurfaceDim)
+ }
+ BasicTextField(
+ value = value,
+ onValueChange = onValueChange,
+ textStyle = MaterialTheme.typography.bodyMedium.copy(color = Color.White),
+ singleLine = true,
+ cursorBrush = SolidColor(Primary),
+ modifier = Modifier
+ .fillMaxWidth()
+ .focusRequester(focusRequester)
+ .onFocusChanged { isFocused = it.isFocused }
+ )
+ }
+ }
+}
+
@Composable
private fun SettingsNavItem(
label: String,
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.kt
index 6442087b..0295dd4a 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
@@ -100,7 +100,8 @@ class SettingsViewModel @Inject constructor(
private val syncMetadataRepository: SyncMetadataRepository,
private val playbackHistoryRepository: com.streamvault.domain.repository.PlaybackHistoryRepository,
private val tvInputChannelSyncManager: TvInputChannelSyncManager,
- private val syncProvider: SyncProvider
+ private val syncProvider: SyncProvider,
+ private val epgSourceRepository: com.streamvault.domain.repository.EpgSourceRepository
) : ViewModel() {
private val appContext = application
private val exportBackup = ExportBackup(backupManager)
@@ -838,6 +839,77 @@ class SettingsViewModel @Inject constructor(
}
}
+ // ── EPG Source Management ────────────────────────────────────────
+
+ fun loadEpgSources() {
+ viewModelScope.launch {
+ epgSourceRepository.getAllSources().collect { sources ->
+ _uiState.update { it.copy(epgSources = sources) }
+ }
+ }
+ }
+
+ fun loadEpgAssignments(providerId: Long) {
+ viewModelScope.launch {
+ epgSourceRepository.getAssignmentsForProvider(providerId).collect { assignments ->
+ _uiState.update {
+ it.copy(epgSourceAssignments = it.epgSourceAssignments + (providerId to assignments))
+ }
+ }
+ }
+ }
+
+ fun addEpgSource(name: String, url: String) {
+ viewModelScope.launch {
+ val result = epgSourceRepository.addSource(name, url)
+ if (result is Result.Error) {
+ _uiState.update { it.copy(userMessage = result.message) }
+ }
+ }
+ }
+
+ fun deleteEpgSource(sourceId: Long) {
+ viewModelScope.launch {
+ epgSourceRepository.deleteSource(sourceId)
+ }
+ }
+
+ fun toggleEpgSourceEnabled(sourceId: Long, enabled: Boolean) {
+ viewModelScope.launch {
+ epgSourceRepository.setSourceEnabled(sourceId, enabled)
+ }
+ }
+
+ fun refreshEpgSource(sourceId: Long) {
+ viewModelScope.launch {
+ _uiState.update { it.copy(isSyncing = true) }
+ val result = epgSourceRepository.refreshSource(sourceId)
+ _uiState.update {
+ it.copy(
+ isSyncing = false,
+ userMessage = if (result is Result.Error) result.message else "EPG source refreshed"
+ )
+ }
+ }
+ }
+
+ fun assignEpgSourceToProvider(providerId: Long, epgSourceId: Long) {
+ viewModelScope.launch {
+ val existingAssignments = _uiState.value.epgSourceAssignments[providerId].orEmpty()
+ val nextPriority = (existingAssignments.maxOfOrNull { it.priority } ?: 0) + 1
+ val result = epgSourceRepository.assignSourceToProvider(providerId, epgSourceId, nextPriority)
+ if (result is Result.Error) {
+ _uiState.update { it.copy(userMessage = result.message) }
+ }
+ }
+ }
+
+ fun unassignEpgSourceFromProvider(providerId: Long, epgSourceId: Long) {
+ viewModelScope.launch {
+ epgSourceRepository.unassignSourceFromProvider(providerId, epgSourceId)
+ }
+ }
+
private fun buildCapabilitySummary(provider: Provider): String {
return when (provider.type) {
ProviderType.XTREAM_CODES -> {
@@ -911,7 +983,9 @@ data class SettingsUiState(
val liveChannelNumberingMode: ChannelNumberingMode = ChannelNumberingMode.GROUP,
val vodViewMode: VodViewMode = VodViewMode.MODERN,
val categorySortModes: Map<ContentType, CategorySortMode> = emptyMap(),
- val hiddenCategories: List<Category> = emptyList()
+ 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()
)
private fun ProviderSyncSelection.label(application: Application): String = when (this) {
diff --git a/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/app/src/main/res/mipmap-anydpi-v26/ic_launcher_vault.xml
similarity index 100%
rename from app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml
rename to app/src/main/res/mipmap-anydpi-v26/ic_launcher_vault.xml
diff --git a/app/src/main/res/mipmap-hdpi/ic_launcher_vault.png b/app/src/main/res/mipmap-hdpi/ic_launcher_vault.png
new file mode 100644
index 00000000..b095e588
Binary files /dev/null and b/app/src/main/res/mipmap-hdpi/ic_launcher_vault.png differ
diff --git a/app/src/main/res/mipmap-mdpi/ic_launcher_vault.png b/app/src/main/res/mipmap-mdpi/ic_launcher_vault.png
new file mode 100644
index 00000000..a61ea42b
Binary files /dev/null and b/app/src/main/res/mipmap-mdpi/ic_launcher_vault.png differ
diff --git a/app/src/main/res/mipmap-xhdpi/ic_launcher_vault.png b/app/src/main/res/mipmap-xhdpi/ic_launcher_vault.png
new file mode 100644
index 00000000..3afd423d
Binary files /dev/null and b/app/src/main/res/mipmap-xhdpi/ic_launcher_vault.png differ
diff --git a/app/src/main/res/mipmap-xxhdpi/ic_launcher_vault.png b/app/src/main/res/mipmap-xxhdpi/ic_launcher_vault.png
new file mode 100644
index 00000000..96d6808b
Binary files /dev/null and b/app/src/main/res/mipmap-xxhdpi/ic_launcher_vault.png differ
diff --git a/data/schemas/com.streamvault.data.local.StreamVaultDatabase/25.json b/data/schemas/com.streamvault.data.local.StreamVaultDatabase/25.json
new file mode 100644
index 00000000..2e9290b3
--- /dev/null
+++ b/data/schemas/com.streamvault.data.local.StreamVaultDatabase/25.json
@@ -0,0 +1,2923 @@
+{
+ "formatVersion": 1,
+ "database": {
+ "version": 25,
+ "identityHash": "1384402f630af7c54497946f2ef66530",
+ "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, `xtream_fast_sync_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": "xtreamFastSyncEnabled",
+ "columnName": "xtream_fast_sync_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, 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
+ }
+ ],
+ "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": "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"
+ ]
+ }
+ ]
+ }
+ ],
+ "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, '1384402f630af7c54497946f2ef66530')"
+ ]
+ }
+}
\ No newline at end of file
diff --git a/data/src/main/java/com/streamvault/data/epg/EpgNameNormalizer.kt b/data/src/main/java/com/streamvault/data/epg/EpgNameNormalizer.kt
new file mode 100644
index 00000000..db0c4fac
--- /dev/null
+++ b/data/src/main/java/com/streamvault/data/epg/EpgNameNormalizer.kt
@@ -0,0 +1,33 @@
+package com.streamvault.data.epg
+
+import java.text.Normalizer
+import java.util.Locale
+
+/**
+ * Normalizes channel display names for EPG matching.
+ * Designed for comparing channel names across different EPG sources.
+ *
+ * This is intentionally simpler than [ChannelNormalizer.getLogicalGroupId]
+ * — it does not strip quality tags or country prefixes because those may be
+ * meaningful when matching EPG channels to provider channels.
+ */
+object EpgNameNormalizer {
+
+ private val nonAlphanumericRegex = Regex("[^a-z0-9]")
+
+ /**
+ * Produces a normalized key from a channel display name.
+ * - lowercase
+ * - strip accents
+ * - remove all non-alphanumeric characters
+ *
+ * Example: "BBC One HD" → "bbconehd"
+ */
+ fun normalize(name: String): String {
+ if (name.isBlank()) return ""
+ val lower = name.lowercase(Locale.ROOT)
+ val stripped = Normalizer.normalize(lower, Normalizer.Form.NFD)
+ .replace(Regex("\\p{InCombiningDiacriticalMarks}+"), "")
+ return stripped.replace(nonAlphanumericRegex, "")
+ }
+}
diff --git a/data/src/main/java/com/streamvault/data/epg/EpgResolutionEngine.kt b/data/src/main/java/com/streamvault/data/epg/EpgResolutionEngine.kt
new file mode 100644
index 00000000..9f5f5b29
--- /dev/null
+++ b/data/src/main/java/com/streamvault/data/epg/EpgResolutionEngine.kt
@@ -0,0 +1,333 @@
+package com.streamvault.data.epg
+
+import android.util.Log
+import com.streamvault.data.local.dao.ChannelDao
+import com.streamvault.data.local.dao.ChannelEpgMappingDao
+import com.streamvault.data.local.dao.EpgChannelDao
+import com.streamvault.data.local.dao.EpgProgrammeDao
+import com.streamvault.data.local.dao.ProgramDao
+import com.streamvault.data.local.dao.ProviderEpgSourceDao
+import com.streamvault.data.local.entity.ChannelEpgMappingEntity
+import com.streamvault.data.mapper.toDomain
+import com.streamvault.data.mapper.toDomainProgram
+import com.streamvault.domain.model.EpgMatchType
+import com.streamvault.domain.model.EpgResolutionSummary
+import com.streamvault.domain.model.EpgSourceType
+import com.streamvault.domain.model.Program
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.withContext
+import javax.inject.Inject
+import javax.inject.Singleton
+
+/**
+ * Resolves the best EPG source and channel for each provider channel.
+ *
+ * Resolution order per channel:
+ * 1. Manual override (future)
+ * 2. External source with exact ID match (highest-priority source first)
+ * 3. External source with normalized name match (highest-priority source first)
+ * 4. Provider-native EPG if available
+ * 5. No EPG
+ *
+ * Results are persisted in `channel_epg_mappings` and used by the guide grid.
+ */
+@Singleton
+class EpgResolutionEngine @Inject constructor(
+ private val channelDao: ChannelDao,
+ private val channelEpgMappingDao: ChannelEpgMappingDao,
+ private val providerEpgSourceDao: ProviderEpgSourceDao,
+ private val epgChannelDao: EpgChannelDao,
+ private val epgProgrammeDao: EpgProgrammeDao,
+ private val programDao: ProgramDao
+) {
+ companion object {
+ private const val TAG = "EpgResolutionEngine"
+ }
+
+ /**
+ * Runs a full resolution pass for a provider.
+ * - Loads all channels for the provider
+ * - Loads all assigned external EPG sources (priority-ordered)
+ * - For each channel, finds the best match
+ * - Persists results in `channel_epg_mappings`
+ *
+ * @return summary statistics
+ */
+ suspend fun resolveForProvider(providerId: Long): EpgResolutionSummary = withContext(Dispatchers.Default) {
+ val channels = channelDao.getByProviderSync(providerId)
+ if (channels.isEmpty()) {
+ channelEpgMappingDao.deleteByProvider(providerId)
+ return@withContext EpgResolutionSummary()
+ }
+
+ val enabledAssignments = providerEpgSourceDao.getEnabledForProviderSync(providerId)
+ val sourceIds = enabledAssignments.map { it.epgSourceId }
+
+ // Load all EPG channels from assigned sources in one query
+ val epgChannelsBySource = if (sourceIds.isNotEmpty()) {
+ epgChannelDao.getBySources(sourceIds).groupBy { it.epgSourceId }
+ } else {
+ emptyMap()
+ }
+
+ // Build lookup indexes for fast matching
+ // sourceId -> (xmltvChannelId -> EpgChannelEntity)
+ val exactIdIndex = mutableMapOf<Long, Map<String, String>>()
+ // sourceId -> (normalizedName -> xmltvChannelId)
+ val nameIndex = mutableMapOf<Long, Map<String, String>>()
+
+ for ((sourceId, epgChannels) in epgChannelsBySource) {
+ exactIdIndex[sourceId] = epgChannels.associate { it.xmltvChannelId to it.xmltvChannelId }
+ // For name index, first occurrence wins (avoids ambiguity)
+ val nameMap = mutableMapOf<String, String>()
+ for (ch in epgChannels) {
+ val normalized = ch.normalizedName
+ if (normalized.isNotEmpty() && normalized !in nameMap) {
+ nameMap[normalized] = ch.xmltvChannelId
+ }
+ }
+ nameIndex[sourceId] = nameMap
+ }
+
+ // Check which channels have provider-native EPG data
+ val providerEpgChannelIds = channels.mapNotNull { it.epgChannelId?.trim()?.takeIf(String::isNotEmpty) }
+ val providerHasEpg = if (providerEpgChannelIds.isNotEmpty()) {
+ programDao.countByProvider(providerId) > 0
+ } else {
+ false
+ }
+
+ // Preserve existing manual overrides
+ val existingMappings = channelEpgMappingDao.getForProvider(providerId)
+ val manualOverrides = existingMappings.filter { it.isManualOverride }
+ .associateBy { it.providerChannelId }
+
+ val now = System.currentTimeMillis()
+ var exactIdMatches = 0
+ var normalizedNameMatches = 0
+ var providerNativeMatches = 0
+ var unresolvedCount = 0
+
+ val mappings = channels.map { channel ->
+ // 1. Check for manual override
+ val manual = manualOverrides[channel.id]
+ if (manual != null) {
+ return@map manual.copy(updatedAt = now)
+ }
+
+ val channelEpgId = channel.epgChannelId?.trim()?.takeIf(String::isNotEmpty)
+
+ // 2. Try external sources in priority order — exact ID match
+ for (assignment in enabledAssignments) {
+ val sid = assignment.epgSourceId
+ val index = exactIdIndex[sid] ?: continue
+ if (channelEpgId != null && channelEpgId in index) {
+ exactIdMatches++
+ return@map ChannelEpgMappingEntity(
+ providerChannelId = channel.id,
+ providerId = providerId,
+ sourceType = EpgSourceType.EXTERNAL.name,
+ epgSourceId = sid,
+ xmltvChannelId = channelEpgId,
+ matchType = EpgMatchType.EXACT_ID.name,
+ confidence = 1.0f,
+ updatedAt = now
+ )
+ }
+ }
+
+ // 3. Try external sources — normalized name match
+ val channelNormalizedName = EpgNameNormalizer.normalize(channel.name)
+ if (channelNormalizedName.isNotEmpty()) {
+ for (assignment in enabledAssignments) {
+ val sid = assignment.epgSourceId
+ val nIndex = nameIndex[sid] ?: continue
+ val matchedXmltvId = nIndex[channelNormalizedName]
+ if (matchedXmltvId != null) {
+ normalizedNameMatches++
+ return@map ChannelEpgMappingEntity(
+ providerChannelId = channel.id,
+ providerId = providerId,
+ sourceType = EpgSourceType.EXTERNAL.name,
+ epgSourceId = sid,
+ xmltvChannelId = matchedXmltvId,
+ matchType = EpgMatchType.NORMALIZED_NAME.name,
+ confidence = 0.7f,
+ updatedAt = now
+ )
+ }
+ }
+ }
+
+ // 4. Fall back to provider-native EPG
+ if (providerHasEpg && channelEpgId != null) {
+ providerNativeMatches++
+ return@map ChannelEpgMappingEntity(
+ providerChannelId = channel.id,
+ providerId = providerId,
+ sourceType = EpgSourceType.PROVIDER.name,
+ epgSourceId = null,
+ xmltvChannelId = channelEpgId,
+ matchType = EpgMatchType.PROVIDER_NATIVE.name,
+ confidence = 0.5f,
+ updatedAt = now
+ )
+ }
+
+ // 5. No EPG
+ unresolvedCount++
+ ChannelEpgMappingEntity(
+ providerChannelId = channel.id,
+ providerId = providerId,
+ sourceType = EpgSourceType.NONE.name,
+ epgSourceId = null,
+ xmltvChannelId = null,
+ matchType = null,
+ confidence = 0f,
+ updatedAt = now
+ )
+ }
+
+ channelEpgMappingDao.replaceForProvider(providerId, mappings)
+
+ val summary = EpgResolutionSummary(
+ totalChannels = channels.size,
+ exactIdMatches = exactIdMatches,
+ normalizedNameMatches = normalizedNameMatches,
+ providerNativeMatches = providerNativeMatches,
+ unresolvedChannels = unresolvedCount
+ )
+ Log.d(TAG, "Resolution for provider $providerId: $summary")
+ summary
+ }
+
+ /**
+ * Queries resolved programme data for a set of channels.
+ *
+ * For channels mapped to EXTERNAL, reads from `epg_programmes`.
+ * For channels mapped to PROVIDER, reads from `programs`.
+ * For unmapped channels, returns empty.
+ *
+ * Returns map keyed by the channel's `epgChannelId` (the lookup key used by the guide grid).
+ */
+ suspend fun getResolvedProgrammes(
+ providerId: Long,
+ channelIds: List<Long>,
+ startTime: Long,
+ endTime: Long
+ ): Map<String, List<Program>> = withContext(Dispatchers.IO) {
+ if (channelIds.isEmpty()) return@withContext emptyMap()
+
+ val mappings = if (channelIds.size <= 500) {
+ channelEpgMappingDao.getForChannels(providerId, channelIds)
+ } else {
+ channelIds.chunked(500).flatMap { chunk ->
+ channelEpgMappingDao.getForChannels(providerId, chunk)
+ }
+ }
+
+ if (mappings.isEmpty()) return@withContext emptyMap()
+
+ // Also load channel entities to get epgChannelId for the lookup key
+ val channels = channelDao.getByProviderSync(providerId)
+ val channelById = channels.associateBy { it.id }
+
+ val result = mutableMapOf<String, List<Program>>()
+
+ // Group external mappings by source
+ val externalBySource = mappings
+ .filter { it.sourceType == EpgSourceType.EXTERNAL.name && it.epgSourceId != null && it.xmltvChannelId != null }
+ .groupBy { it.epgSourceId!! }
+
+ for ((sourceId, sourceMappings) in externalBySource) {
+ val xmltvIds = sourceMappings.map { it.xmltvChannelId!! }.distinct()
+ val programmes = if (xmltvIds.size <= 500) {
+ epgProgrammeDao.getForChannels(sourceId, xmltvIds, startTime, endTime)
+ } else {
+ xmltvIds.chunked(500).flatMap { chunk ->
+ epgProgrammeDao.getForChannels(sourceId, chunk, startTime, endTime)
+ }
+ }
+ val programsByXmltvId = programmes.groupBy { it.xmltvChannelId }
+
+ for (mapping in sourceMappings) {
+ val channel = channelById[mapping.providerChannelId] ?: continue
+ val lookupKey = channel.epgChannelId?.trim()?.takeIf(String::isNotEmpty)
+ ?: channel.streamId.takeIf { it > 0L }?.toString()
+ ?: continue
+ val progs = programsByXmltvId[mapping.xmltvChannelId]
+ ?.map { it.toDomainProgram(providerId) }
+ ?.sortedBy { it.startTime }
+ .orEmpty()
+ if (progs.isNotEmpty()) {
+ result[lookupKey] = progs
+ }
+ }
+ }
+
+ // For PROVIDER type, we don't need to query — the existing ProgramDao path
+ // in EpgRepositoryImpl handles that. But we can include them here for completeness
+ // of the resolved query path.
+ val providerMappings = mappings.filter { it.sourceType == EpgSourceType.PROVIDER.name && it.xmltvChannelId != null }
+ if (providerMappings.isNotEmpty()) {
+ val providerXmltvIds = providerMappings.mapNotNull { it.xmltvChannelId }.distinct()
+ val providerPrograms = if (providerXmltvIds.size <= 500) {
+ programDao.getForChannelsSync(providerId, providerXmltvIds, startTime, endTime)
+ } else {
+ providerXmltvIds.chunked(500).flatMap { chunk ->
+ programDao.getForChannelsSync(providerId, chunk, startTime, endTime)
+ }
+ }
+ val groupedByChannel = providerPrograms
+ .map { it.toDomain() }
+ .groupBy { it.channelId }
+
+ for (mapping in providerMappings) {
+ val channel = channelById[mapping.providerChannelId] ?: continue
+ val lookupKey = channel.epgChannelId?.trim()?.takeIf(String::isNotEmpty)
+ ?: channel.streamId.takeIf { it > 0L }?.toString()
+ ?: continue
+ // Don't overwrite external data (external wins if already resolved)
+ if (lookupKey !in result) {
+ val progs = groupedByChannel[mapping.xmltvChannelId].orEmpty()
+ if (progs.isNotEmpty()) {
+ result[lookupKey] = progs
+ }
+ }
+ }
+ }
+
+ result
+ }
+
+ /**
+ * Returns resolution statistics from the persisted mappings.
+ */
+ suspend fun getResolutionSummary(providerId: Long): EpgResolutionSummary {
+ val stats = channelEpgMappingDao.getResolutionStats(providerId)
+ var total = 0
+ var exactId = 0
+ var normalizedName = 0
+ var providerNative = 0
+ var unresolved = 0
+
+ for (row in stats) {
+ total += row.cnt
+ when {
+ row.sourceType == EpgSourceType.NONE.name -> unresolved += row.cnt
+ row.matchType == EpgMatchType.EXACT_ID.name -> exactId += row.cnt
+ row.matchType == EpgMatchType.NORMALIZED_NAME.name -> normalizedName += row.cnt
+ row.matchType == EpgMatchType.PROVIDER_NATIVE.name -> providerNative += row.cnt
+ row.matchType == EpgMatchType.MANUAL.name -> exactId += row.cnt // count manual as exact
+ }
+ }
+
+ return EpgResolutionSummary(
+ totalChannels = total,
+ exactIdMatches = exactId,
+ normalizedNameMatches = normalizedName,
+ providerNativeMatches = providerNative,
+ unresolvedChannels = unresolved
+ )
+ }
+}
diff --git a/data/src/main/java/com/streamvault/data/local/StreamVaultDatabase.kt b/data/src/main/java/com/streamvault/data/local/StreamVaultDatabase.kt
index 6cc8a6be..26544a12 100644
--- a/data/src/main/java/com/streamvault/data/local/StreamVaultDatabase.kt
+++ b/data/src/main/java/com/streamvault/data/local/StreamVaultDatabase.kt
@@ -29,9 +29,14 @@ import com.streamvault.data.local.entity.*
VirtualGroupEntity::class,
PlaybackHistoryEntity::class,
SyncMetadataEntity::class,
- MovieCategoryHydrationEntity::class
+ MovieCategoryHydrationEntity::class,
+ EpgSourceEntity::class,
+ ProviderEpgSourceEntity::class,
+ EpgChannelEntity::class,
+ EpgProgrammeEntity::class,
+ ChannelEpgMappingEntity::class
],
- version = 24,
+ version = 25,
exportSchema = true // ← was false; schema JSON now tracked in version control
)
@TypeConverters(RoomEnumConverters::class)
@@ -50,6 +55,11 @@ abstract class StreamVaultDatabase : RoomDatabase() {
abstract fun playbackHistoryDao(): PlaybackHistoryDao
abstract fun syncMetadataDao(): SyncMetadataDao
abstract fun movieCategoryHydrationDao(): MovieCategoryHydrationDao
+ abstract fun epgSourceDao(): EpgSourceDao
+ abstract fun providerEpgSourceDao(): ProviderEpgSourceDao
+ abstract fun epgChannelDao(): EpgChannelDao
+ abstract fun epgProgrammeDao(): EpgProgrammeDao
+ abstract fun channelEpgMappingDao(): ChannelEpgMappingDao
companion object {
/**
@@ -1169,5 +1179,100 @@ abstract class StreamVaultDatabase : RoomDatabase() {
)
}
}
+
+ val MIGRATION_24_25 = object : Migration(24, 25) {
+ override fun migrate(database: SupportSQLiteDatabase) {
+ // ── epg_sources ──
+ database.execSQL("""
+ CREATE TABLE IF NOT EXISTS epg_sources (
+ id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
+ name TEXT NOT NULL,
+ url TEXT NOT NULL,
+ enabled INTEGER NOT NULL DEFAULT 1,
+ last_refresh_at INTEGER NOT NULL DEFAULT 0,
+ last_success_at INTEGER NOT NULL DEFAULT 0,
+ last_error TEXT,
+ priority INTEGER NOT NULL DEFAULT 0,
+ created_at INTEGER NOT NULL DEFAULT 0,
+ updated_at INTEGER NOT NULL DEFAULT 0
+ )
+ """.trimIndent())
+ database.execSQL("CREATE UNIQUE INDEX IF NOT EXISTS index_epg_sources_url ON epg_sources(url)")
+
+ // ── provider_epg_sources ──
+ database.execSQL("""
+ CREATE TABLE IF NOT EXISTS provider_epg_sources (
+ id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
+ provider_id INTEGER NOT NULL,
+ epg_source_id INTEGER NOT NULL,
+ priority INTEGER NOT NULL DEFAULT 0,
+ enabled INTEGER NOT NULL DEFAULT 1,
+ FOREIGN KEY(provider_id) REFERENCES providers(id) ON DELETE CASCADE,
+ FOREIGN KEY(epg_source_id) REFERENCES epg_sources(id) ON DELETE CASCADE
+ )
+ """.trimIndent())
+ database.execSQL("CREATE UNIQUE INDEX IF NOT EXISTS index_provider_epg_sources_provider_id_epg_source_id ON provider_epg_sources(provider_id, epg_source_id)")
+ database.execSQL("CREATE INDEX IF NOT EXISTS index_provider_epg_sources_epg_source_id ON provider_epg_sources(epg_source_id)")
+
+ // ── epg_channels ──
+ database.execSQL("""
+ CREATE TABLE IF NOT EXISTS epg_channels (
+ id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
+ epg_source_id INTEGER NOT NULL,
+ xmltv_channel_id TEXT NOT NULL,
+ display_name TEXT NOT NULL,
+ normalized_name TEXT NOT NULL DEFAULT '',
+ icon_url TEXT,
+ FOREIGN KEY(epg_source_id) REFERENCES epg_sources(id) ON DELETE CASCADE
+ )
+ """.trimIndent())
+ database.execSQL("CREATE UNIQUE INDEX IF NOT EXISTS index_epg_channels_epg_source_id_xmltv_channel_id ON epg_channels(epg_source_id, xmltv_channel_id)")
+ database.execSQL("CREATE INDEX IF NOT EXISTS index_epg_channels_epg_source_id ON epg_channels(epg_source_id)")
+ database.execSQL("CREATE INDEX IF NOT EXISTS index_epg_channels_normalized_name ON epg_channels(normalized_name)")
+
+ // ── epg_programmes ──
+ database.execSQL("""
+ CREATE TABLE IF NOT EXISTS epg_programmes (
+ id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
+ epg_source_id INTEGER NOT NULL,
+ xmltv_channel_id TEXT NOT NULL,
+ start_time INTEGER NOT NULL DEFAULT 0,
+ end_time INTEGER NOT NULL DEFAULT 0,
+ title TEXT NOT NULL,
+ subtitle TEXT,
+ description TEXT NOT NULL DEFAULT '',
+ category TEXT,
+ lang TEXT NOT NULL DEFAULT '',
+ rating TEXT,
+ image_url TEXT,
+ episode_info TEXT,
+ FOREIGN KEY(epg_source_id) REFERENCES epg_sources(id) ON DELETE CASCADE
+ )
+ """.trimIndent())
+ database.execSQL("CREATE INDEX IF NOT EXISTS index_epg_programmes_epg_source_id_xmltv_channel_id_start_time ON epg_programmes(epg_source_id, xmltv_channel_id, start_time)")
+ database.execSQL("CREATE UNIQUE INDEX IF NOT EXISTS index_epg_programmes_epg_source_id_xmltv_channel_id_start_time_end_time ON epg_programmes(epg_source_id, xmltv_channel_id, start_time, end_time)")
+ database.execSQL("CREATE INDEX IF NOT EXISTS index_epg_programmes_epg_source_id ON epg_programmes(epg_source_id)")
+ database.execSQL("CREATE INDEX IF NOT EXISTS index_epg_programmes_start_time ON epg_programmes(start_time)")
+
+ // ── channel_epg_mappings ──
+ database.execSQL("""
+ CREATE TABLE IF NOT EXISTS channel_epg_mappings (
+ id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
+ provider_channel_id INTEGER NOT NULL,
+ provider_id INTEGER NOT NULL,
+ source_type TEXT NOT NULL DEFAULT 'NONE',
+ epg_source_id INTEGER,
+ xmltv_channel_id TEXT,
+ match_type TEXT,
+ confidence REAL NOT NULL DEFAULT 0,
+ is_manual_override INTEGER NOT NULL DEFAULT 0,
+ updated_at INTEGER NOT NULL DEFAULT 0,
+ FOREIGN KEY(provider_id) REFERENCES providers(id) ON DELETE CASCADE
+ )
+ """.trimIndent())
+ database.execSQL("CREATE UNIQUE INDEX IF NOT EXISTS index_channel_epg_mappings_provider_id_provider_channel_id ON channel_epg_mappings(provider_id, provider_channel_id)")
+ database.execSQL("CREATE INDEX IF NOT EXISTS index_channel_epg_mappings_provider_id ON channel_epg_mappings(provider_id)")
+ }
+ }
}
}
diff --git a/data/src/main/java/com/streamvault/data/local/dao/Daos.kt b/data/src/main/java/com/streamvault/data/local/dao/Daos.kt
index 926c9c16..eb6119c4 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
@@ -1518,6 +1518,35 @@ interface ProgramDao {
)
suspend fun getNowPlayingForChannelsSync(providerId: Long, channelIds: List<String>, now: Long = System.currentTimeMillis()): List<ProgramBrowseEntity>
+ @Query(
+ """
+ SELECT
+ id,
+ provider_id,
+ channel_id,
+ title,
+ CASE
+ WHEN LENGTH(description) > 600 THEN SUBSTR(description, 1, 600) || '...'
+ ELSE description
+ END AS description,
+ start_time,
+ end_time,
+ lang,
+ NULL AS rating,
+ NULL AS image_url,
+ NULL AS genre,
+ NULL AS category,
+ has_archive
+ FROM programs
+ WHERE provider_id = :providerId
+ AND channel_id IN (:channelIds)
+ AND end_time > :startTime
+ AND start_time < :endTime
+ ORDER BY channel_id ASC, start_time ASC
+ """
+ )
+ suspend fun getForChannelsSync(providerId: Long, channelIds: List<String>, startTime: Long, endTime: Long): List<ProgramBrowseEntity>
+
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertAll(programs: List<ProgramEntity>)
@@ -1663,3 +1692,197 @@ interface MovieCategoryHydrationDao {
@Query("DELETE FROM movie_category_hydration WHERE provider_id = :providerId")
suspend fun deleteByProvider(providerId: Long)
}
+
+// ── EPG Source DAOs ────────────────────────────────────────────────
+
+@Dao
+interface EpgSourceDao {
+ @Query("SELECT * FROM epg_sources ORDER BY priority ASC, name ASC")
+ fun getAll(): Flow<List<EpgSourceEntity>>
+
+ @Query("SELECT * FROM epg_sources ORDER BY priority ASC, name ASC")
+ suspend fun getAllSync(): List<EpgSourceEntity>
+
+ @Query("SELECT * FROM epg_sources WHERE id = :id")
+ suspend fun getById(id: Long): EpgSourceEntity?
+
+ @Query("SELECT * FROM epg_sources WHERE url = :url LIMIT 1")
+ suspend fun getByUrl(url: String): EpgSourceEntity?
+
+ @Query("SELECT * FROM epg_sources WHERE enabled = 1 ORDER BY priority ASC, name ASC")
+ suspend fun getEnabled(): List<EpgSourceEntity>
+
+ @Insert(onConflict = OnConflictStrategy.ABORT)
+ suspend fun insert(source: EpgSourceEntity): Long
+
+ @Update
+ suspend fun update(source: EpgSourceEntity)
+
+ @Query("DELETE FROM epg_sources WHERE id = :id")
+ suspend fun delete(id: Long)
+
+ @Query("UPDATE epg_sources SET enabled = :enabled, updated_at = :now WHERE id = :id")
+ suspend fun setEnabled(id: Long, enabled: Boolean, now: Long = System.currentTimeMillis())
+
+ @Query("UPDATE epg_sources SET last_refresh_at = :at, last_error = :error, updated_at = :at WHERE id = :id")
+ suspend fun updateRefreshStatus(id: Long, at: Long, error: String?)
+
+ @Query("UPDATE epg_sources SET last_refresh_at = :at, last_success_at = :at, last_error = NULL, updated_at = :at WHERE id = :id")
+ suspend fun updateRefreshSuccess(id: Long, at: Long)
+}
+
+@Dao
+interface ProviderEpgSourceDao {
+ @Query("""
+ SELECT pes.*, es.name AS epg_source_name, es.url AS epg_source_url
+ FROM provider_epg_sources pes
+ JOIN epg_sources es ON es.id = pes.epg_source_id
+ WHERE pes.provider_id = :providerId
+ ORDER BY pes.priority ASC
+ """)
+ fun getForProvider(providerId: Long): Flow<List<ProviderEpgSourceWithDetails>>
+
+ @Query("""
+ SELECT pes.*
+ FROM provider_epg_sources pes
+ JOIN epg_sources es ON es.id = pes.epg_source_id
+ WHERE pes.provider_id = :providerId AND pes.enabled = 1 AND es.enabled = 1
+ ORDER BY pes.priority ASC
+ """)
+ suspend fun getEnabledForProviderSync(providerId: Long): List<ProviderEpgSourceEntity>
+
+ @Query("""
+ SELECT pes.*
+ FROM provider_epg_sources pes
+ WHERE pes.provider_id = :providerId
+ ORDER BY pes.priority ASC
+ """)
+ suspend fun getForProviderSync(providerId: Long): List<ProviderEpgSourceEntity>
+
+ @Insert(onConflict = OnConflictStrategy.REPLACE)
+ suspend fun insert(assignment: ProviderEpgSourceEntity): Long
+
+ @Update
+ 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)
+
+ @Query("DELETE FROM provider_epg_sources WHERE provider_id = :providerId")
+ suspend fun deleteByProvider(providerId: Long)
+}
+
+data class ProviderEpgSourceWithDetails(
+ val id: Long,
+ @ColumnInfo(name = "provider_id") val providerId: Long,
+ @ColumnInfo(name = "epg_source_id") val epgSourceId: Long,
+ val priority: Int,
+ val enabled: Boolean,
+ @ColumnInfo(name = "epg_source_name") val epgSourceName: String,
+ @ColumnInfo(name = "epg_source_url") val epgSourceUrl: String
+)
+
+@Dao
+interface EpgChannelDao {
+ @Query("SELECT * FROM epg_channels WHERE epg_source_id = :sourceId ORDER BY display_name ASC")
+ suspend fun getBySource(sourceId: Long): List<EpgChannelEntity>
+
+ @Query("SELECT * FROM epg_channels WHERE epg_source_id = :sourceId AND xmltv_channel_id = :channelId LIMIT 1")
+ suspend fun getBySourceAndChannelId(sourceId: Long, channelId: String): EpgChannelEntity?
+
+ @Query("SELECT * FROM epg_channels WHERE epg_source_id IN (:sourceIds)")
+ suspend fun getBySources(sourceIds: List<Long>): List<EpgChannelEntity>
+
+ @Insert(onConflict = OnConflictStrategy.REPLACE)
+ suspend fun insertAll(channels: List<EpgChannelEntity>)
+
+ @Query("DELETE FROM epg_channels WHERE epg_source_id = :sourceId")
+ suspend fun deleteBySource(sourceId: Long)
+}
+
+@Dao
+interface EpgProgrammeDao {
+ @Query("""
+ SELECT * FROM epg_programmes
+ WHERE epg_source_id = :sourceId
+ AND xmltv_channel_id = :channelId
+ AND end_time > :startTime
+ AND start_time < :endTime
+ ORDER BY start_time ASC
+ """)
+ suspend fun getForChannel(sourceId: Long, channelId: String, startTime: Long, endTime: Long): List<EpgProgrammeEntity>
+
+ @Query("""
+ SELECT * FROM epg_programmes
+ WHERE epg_source_id = :sourceId
+ AND xmltv_channel_id IN (:channelIds)
+ AND end_time > :startTime
+ AND start_time < :endTime
+ ORDER BY xmltv_channel_id ASC, start_time ASC
+ """)
+ suspend fun getForChannels(sourceId: Long, channelIds: List<String>, startTime: Long, endTime: Long): List<EpgProgrammeEntity>
+
+ @Insert(onConflict = OnConflictStrategy.REPLACE)
+ suspend fun insertAll(programmes: List<EpgProgrammeEntity>)
+
+ @Query("DELETE FROM epg_programmes WHERE epg_source_id = :sourceId")
+ suspend fun deleteBySource(sourceId: Long)
+
+ @Query("DELETE FROM epg_programmes WHERE end_time < :beforeTime")
+ suspend fun deleteOld(beforeTime: Long): Int
+
+ @Query("SELECT COUNT(*) FROM epg_programmes WHERE epg_source_id = :sourceId")
+ suspend fun countBySource(sourceId: Long): Int
+
+ @Query("""
+ SELECT COUNT(*) FROM epg_programmes
+ WHERE epg_source_id = :sourceId
+ AND xmltv_channel_id = :channelId
+ AND end_time > :now
+ """)
+ suspend fun countUpcomingForChannel(sourceId: Long, channelId: String, now: Long = System.currentTimeMillis()): Int
+}
+
+@Dao
+abstract class ChannelEpgMappingDao {
+ @Query("SELECT * FROM channel_epg_mappings WHERE provider_id = :providerId")
+ abstract suspend fun getForProvider(providerId: Long): List<ChannelEpgMappingEntity>
+
+ @Query("SELECT * FROM channel_epg_mappings WHERE provider_id = :providerId AND provider_channel_id = :channelId LIMIT 1")
+ abstract suspend fun getForChannel(providerId: Long, channelId: Long): ChannelEpgMappingEntity?
+
+ @Query("""
+ SELECT * FROM channel_epg_mappings
+ WHERE provider_id = :providerId
+ AND provider_channel_id IN (:channelIds)
+ """)
+ abstract suspend fun getForChannels(providerId: Long, channelIds: List<Long>): List<ChannelEpgMappingEntity>
+
+ @Insert(onConflict = OnConflictStrategy.REPLACE)
+ abstract suspend fun insertAll(mappings: List<ChannelEpgMappingEntity>)
+
+ @Query("DELETE FROM channel_epg_mappings WHERE provider_id = :providerId")
+ abstract suspend fun deleteByProvider(providerId: Long)
+
+ @Transaction
+ open suspend fun replaceForProvider(providerId: Long, mappings: List<ChannelEpgMappingEntity>) {
+ deleteByProvider(providerId)
+ if (mappings.isNotEmpty()) {
+ insertAll(mappings)
+ }
+ }
+
+ @Query("""
+ SELECT source_type, match_type, COUNT(*) as cnt
+ FROM channel_epg_mappings
+ WHERE provider_id = :providerId
+ GROUP BY source_type, match_type
+ """)
+ abstract suspend fun getResolutionStats(providerId: Long): List<EpgResolutionStatRow>
+}
+
+data class EpgResolutionStatRow(
+ @ColumnInfo(name = "source_type") val sourceType: String,
+ @ColumnInfo(name = "match_type") val matchType: String?,
+ val cnt: 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.kt
index 75b8a3d8..9a80ac5d 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
@@ -682,3 +682,144 @@ data class MovieCategoryHydrationEntity(
@ColumnInfo(name = "last_status") val lastStatus: String = "IDLE",
@ColumnInfo(name = "last_error") val lastError: String? = null
)
+
+// ── External EPG Source ────────────────────────────────────────────
+
+@Entity(
+ tableName = "epg_sources",
+ indices = [Index(value = ["url"], unique = true)]
+)
+data class EpgSourceEntity(
+ @PrimaryKey(autoGenerate = true)
+ val id: Long = 0,
+ val name: String,
+ val url: String,
+ val enabled: Boolean = true,
+ @ColumnInfo(name = "last_refresh_at") val lastRefreshAt: Long = 0,
+ @ColumnInfo(name = "last_success_at") val lastSuccessAt: Long = 0,
+ @ColumnInfo(name = "last_error") val lastError: String? = null,
+ val priority: Int = 0,
+ @ColumnInfo(name = "created_at") val createdAt: Long = System.currentTimeMillis(),
+ @ColumnInfo(name = "updated_at") val updatedAt: Long = System.currentTimeMillis()
+)
+
+// ── Provider ↔ EPG Source Assignment ───────────────────────────────
+
+@Entity(
+ tableName = "provider_epg_sources",
+ foreignKeys = [
+ ForeignKey(
+ entity = ProviderEntity::class,
+ parentColumns = ["id"],
+ childColumns = ["provider_id"],
+ onDelete = ForeignKey.CASCADE
+ ),
+ ForeignKey(
+ entity = EpgSourceEntity::class,
+ parentColumns = ["id"],
+ childColumns = ["epg_source_id"],
+ onDelete = ForeignKey.CASCADE
+ )
+ ],
+ indices = [
+ Index(value = ["provider_id", "epg_source_id"], unique = true),
+ Index(value = ["epg_source_id"])
+ ]
+)
+data class ProviderEpgSourceEntity(
+ @PrimaryKey(autoGenerate = true)
+ val id: Long = 0,
+ @ColumnInfo(name = "provider_id") val providerId: Long,
+ @ColumnInfo(name = "epg_source_id") val epgSourceId: Long,
+ val priority: Int = 0,
+ val enabled: Boolean = true
+)
+
+// ── EPG Channel (from external source) ─────────────────────────────
+
+@Entity(
+ tableName = "epg_channels",
+ foreignKeys = [ForeignKey(
+ entity = EpgSourceEntity::class,
+ parentColumns = ["id"],
+ childColumns = ["epg_source_id"],
+ onDelete = ForeignKey.CASCADE
+ )],
+ indices = [
+ Index(value = ["epg_source_id", "xmltv_channel_id"], unique = true),
+ Index(value = ["epg_source_id"]),
+ Index(value = ["normalized_name"])
+ ]
+)
+data class EpgChannelEntity(
+ @PrimaryKey(autoGenerate = true)
+ val id: Long = 0,
+ @ColumnInfo(name = "epg_source_id") val epgSourceId: Long,
+ @ColumnInfo(name = "xmltv_channel_id") val xmltvChannelId: String,
+ @ColumnInfo(name = "display_name") val displayName: String,
+ @ColumnInfo(name = "normalized_name") val normalizedName: String = "",
+ @ColumnInfo(name = "icon_url") val iconUrl: String? = null
+)
+
+// ── EPG Programme (from external source) ───────────────────────────
+
+@Entity(
+ tableName = "epg_programmes",
+ foreignKeys = [ForeignKey(
+ entity = EpgSourceEntity::class,
+ parentColumns = ["id"],
+ childColumns = ["epg_source_id"],
+ onDelete = ForeignKey.CASCADE
+ )],
+ indices = [
+ Index(value = ["epg_source_id", "xmltv_channel_id", "start_time"]),
+ Index(value = ["epg_source_id", "xmltv_channel_id", "start_time", "end_time"], unique = true),
+ Index(value = ["epg_source_id"]),
+ Index(value = ["start_time"])
+ ]
+)
+data class EpgProgrammeEntity(
+ @PrimaryKey(autoGenerate = true)
+ val id: Long = 0,
+ @ColumnInfo(name = "epg_source_id") val epgSourceId: Long,
+ @ColumnInfo(name = "xmltv_channel_id") val xmltvChannelId: String,
+ @ColumnInfo(name = "start_time") val startTime: Long = 0,
+ @ColumnInfo(name = "end_time") val endTime: Long = 0,
+ val title: String,
+ val subtitle: String? = null,
+ val description: String = "",
+ val category: String? = null,
+ val lang: String = "",
+ val rating: String? = null,
+ @ColumnInfo(name = "image_url") val imageUrl: String? = null,
+ @ColumnInfo(name = "episode_info") val episodeInfo: String? = null
+)
+
+// ── Channel EPG Mapping (resolved) ─────────────────────────────────
+
+@Entity(
+ tableName = "channel_epg_mappings",
+ foreignKeys = [ForeignKey(
+ entity = ProviderEntity::class,
+ parentColumns = ["id"],
+ childColumns = ["provider_id"],
+ onDelete = ForeignKey.CASCADE
+ )],
+ indices = [
+ Index(value = ["provider_id", "provider_channel_id"], unique = true),
+ Index(value = ["provider_id"])
+ ]
+)
+data class ChannelEpgMappingEntity(
+ @PrimaryKey(autoGenerate = true)
+ val id: Long = 0,
+ @ColumnInfo(name = "provider_channel_id") val providerChannelId: Long,
+ @ColumnInfo(name = "provider_id") val providerId: Long,
+ @ColumnInfo(name = "source_type") val sourceType: String = "NONE",
+ @ColumnInfo(name = "epg_source_id") val epgSourceId: Long? = null,
+ @ColumnInfo(name = "xmltv_channel_id") val xmltvChannelId: String? = null,
+ @ColumnInfo(name = "match_type") val matchType: String? = null,
+ val confidence: Float = 0f,
+ @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/mapper/EntityMappers.kt b/data/src/main/java/com/streamvault/data/mapper/EntityMappers.kt
index 40e6b95e..bdccfbfa 100644
--- a/data/src/main/java/com/streamvault/data/mapper/EntityMappers.kt
+++ b/data/src/main/java/com/streamvault/data/mapper/EntityMappers.kt
@@ -592,3 +592,113 @@ private fun String?.toPlaybackWatchedStatus(): PlaybackWatchedStatus =
runCatching {
this?.let(PlaybackWatchedStatus::valueOf)
}.getOrNull() ?: PlaybackWatchedStatus.IN_PROGRESS
+
+// ── EPG Source ─────────────────────────────────────────────────────
+
+fun EpgSourceEntity.toDomain() = com.streamvault.domain.model.EpgSource(
+ id = id,
+ name = name,
+ url = url,
+ enabled = enabled,
+ lastRefreshAt = lastRefreshAt,
+ lastSuccessAt = lastSuccessAt,
+ lastError = lastError,
+ priority = priority,
+ createdAt = createdAt,
+ updatedAt = updatedAt
+)
+
+fun com.streamvault.domain.model.EpgSource.toEntity() = EpgSourceEntity(
+ id = id,
+ name = name,
+ url = url,
+ enabled = enabled,
+ lastRefreshAt = lastRefreshAt,
+ lastSuccessAt = lastSuccessAt,
+ lastError = lastError,
+ priority = priority,
+ createdAt = createdAt,
+ updatedAt = updatedAt
+)
+
+// ── Provider EPG Source Assignment ─────────────────────────────────
+
+fun com.streamvault.data.local.dao.ProviderEpgSourceWithDetails.toDomain() =
+ com.streamvault.domain.model.ProviderEpgSourceAssignment(
+ id = id,
+ providerId = providerId,
+ epgSourceId = epgSourceId,
+ priority = priority,
+ enabled = enabled,
+ epgSourceName = epgSourceName,
+ epgSourceUrl = epgSourceUrl
+ )
+
+fun com.streamvault.domain.model.ProviderEpgSourceAssignment.toEntity() = ProviderEpgSourceEntity(
+ id = id,
+ providerId = providerId,
+ epgSourceId = epgSourceId,
+ priority = priority,
+ enabled = enabled
+)
+
+// ── EPG Channel ────────────────────────────────────────────────────
+
+fun EpgChannelEntity.toDomain() = com.streamvault.domain.model.EpgChannelInfo(
+ id = id,
+ epgSourceId = epgSourceId,
+ xmltvChannelId = xmltvChannelId,
+ displayName = displayName,
+ normalizedName = normalizedName,
+ iconUrl = iconUrl
+)
+
+// ── EPG Programme → Program ────────────────────────────────────────
+
+fun EpgProgrammeEntity.toDomainProgram(providerId: Long = 0L) = Program(
+ id = id,
+ channelId = xmltvChannelId,
+ title = title,
+ description = buildString {
+ subtitle?.let { append(it); append("\n") }
+ append(description)
+ }.trim(),
+ startTime = startTime,
+ endTime = endTime,
+ lang = lang,
+ rating = rating,
+ imageUrl = imageUrl,
+ category = category,
+ providerId = providerId
+)
+
+// ── Channel EPG Mapping ────────────────────────────────────────────
+
+fun ChannelEpgMappingEntity.toDomain() = com.streamvault.domain.model.ChannelEpgMapping(
+ id = id,
+ providerChannelId = providerChannelId,
+ providerId = providerId,
+ sourceType = runCatching { com.streamvault.domain.model.EpgSourceType.valueOf(sourceType) }
+ .getOrDefault(com.streamvault.domain.model.EpgSourceType.NONE),
+ epgSourceId = epgSourceId,
+ xmltvChannelId = xmltvChannelId,
+ matchType = matchType?.let {
+ runCatching { com.streamvault.domain.model.EpgMatchType.valueOf(it) }.getOrNull()
+ },
+ confidence = confidence,
+ isManualOverride = isManualOverride,
+ updatedAt = updatedAt
+)
+
+fun com.streamvault.domain.model.ChannelEpgMapping.toEntity() = ChannelEpgMappingEntity(
+ id = id,
+ providerChannelId = providerChannelId,
+ providerId = providerId,
+ sourceType = sourceType.name,
+ epgSourceId = epgSourceId,
+ xmltvChannelId = xmltvChannelId,
+ matchType = matchType?.name,
+ confidence = confidence,
+ 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.kt
index c3a2f0e7..79d74916 100644
--- a/data/src/main/java/com/streamvault/data/parser/XmltvParser.kt
+++ b/data/src/main/java/com/streamvault/data/parser/XmltvParser.kt
@@ -13,6 +13,31 @@ import java.time.format.DateTimeFormatterBuilder
import java.util.Locale
import java.util.logging.Level
import java.util.logging.Logger
+import java.util.zip.GZIPInputStream
+
+/**
+ * Channel metadata parsed from an XMLTV `<channel>` element.
+ */
+data class XmltvChannel(
+ val id: String,
+ val displayName: String,
+ val iconUrl: String? = null
+)
+
+data class XmltvProgramme(
+ val channelId: String,
+ val title: String,
+ val subtitle: String? = null,
+ val description: String = "",
+ val startTime: Long = 0L,
+ val endTime: Long = 0L,
+ val lang: String = "",
+ val rating: String? = null,
+ val imageUrl: String? = null,
+ val category: String? = null,
+ val genre: String? = null,
+ val episodeInfo: String? = null
+)
/**
* XMLTV EPG parser using XmlPullParser for memory-efficient streaming parsing.
@@ -284,6 +309,192 @@ class XmltvParser {
}
}
+ /**
+ * Streaming parser that yields both `<channel>` and `<programme>` elements.
+ * Channels are emitted first (they appear before programmes in standard XMLTV).
+ */
+ suspend fun parseStreamingWithChannels(
+ inputStream: InputStream,
+ onChannel: suspend (XmltvChannel) -> Unit,
+ onProgramme: suspend (XmltvProgramme) -> Unit
+ ) {
+ val factory = XmlPullParserFactory.newInstance()
+ factory.isNamespaceAware = false
+ val parser = factory.newPullParser()
+ parser.setInput(inputStream, "UTF-8")
+
+ var eventType = parser.eventType
+ // Channel state
+ var inChannel = false
+ var channelId: String? = null
+ var channelDisplayName: String? = null
+ var channelIconUrl: String? = null
+ var channelTag: String? = null
+ // Programme state
+ var inProgramme = false
+ var currentChannelId: String? = null
+ var currentTitle: String? = null
+ var currentDescription: String? = null
+ var currentStart: Long = 0
+ var currentEnd: Long = 0
+ var currentLang: String = ""
+ var currentImageUrl: String? = null
+ val currentCategories = mutableListOf<String>()
+ var currentSubtitle: String? = null
+ var currentEpisodeNum: String? = null
+ var currentRating: String? = null
+ var inRating = false
+ var currentTag: String? = null
+ var channelCount = 0
+ var programmeCount = 0
+
+ try {
+ while (eventType != XmlPullParser.END_DOCUMENT) {
+ when (eventType) {
+ XmlPullParser.START_TAG -> {
+ when (parser.name) {
+ "channel" -> {
+ inChannel = true
+ channelId = parser.getAttributeValue(null, "id")
+ channelDisplayName = null
+ channelIconUrl = null
+ }
+ "display-name" -> {
+ if (inChannel) channelTag = "display-name"
+ }
+ "icon" -> {
+ if (inChannel) {
+ channelIconUrl = parser.getAttributeValue(null, "src")
+ } else if (inProgramme) {
+ currentImageUrl = parser.getAttributeValue(null, "src")
+ }
+ }
+ "programme" -> {
+ inProgramme = true
+ currentChannelId = parser.getAttributeValue(null, "channel")
+ currentStart = parseDate(parser.getAttributeValue(null, "start"))
+ currentEnd = parseDate(parser.getAttributeValue(null, "stop"))
+ currentTitle = null
+ currentDescription = null
+ currentLang = ""
+ currentImageUrl = null
+ currentCategories.clear()
+ currentRating = null
+ inRating = false
+ }
+ "title" -> {
+ if (inProgramme) {
+ currentLang = parser.getAttributeValue(null, "lang") ?: ""
+ currentTag = "title"
+ }
+ }
+ "sub-title" -> {
+ if (inProgramme) currentTag = "sub-title"
+ }
+ "desc" -> {
+ if (inProgramme) currentTag = "desc"
+ }
+ "episode-num" -> {
+ if (inProgramme) currentTag = "episode-num"
+ }
+ "category" -> {
+ if (inProgramme) currentTag = "category"
+ }
+ "rating" -> {
+ if (inProgramme) inRating = true
+ }
+ "value" -> {
+ if (inProgramme && inRating) currentTag = "rating"
+ }
+ }
+ }
+ XmlPullParser.TEXT -> {
+ if (inChannel) {
+ when (channelTag) {
+ "display-name" -> {
+ if (channelDisplayName == null) {
+ channelDisplayName = parser.text?.trim()
+ }
+ }
+ }
+ channelTag = null
+ }
+ if (inProgramme) {
+ when (currentTag) {
+ "title" -> currentTitle = parser.text
+ "sub-title" -> currentSubtitle = parser.text?.trim()?.takeIf { it.isNotEmpty() }
+ "desc" -> currentDescription = parser.text
+ "episode-num" -> currentEpisodeNum = parser.text?.trim()?.takeIf { it.isNotEmpty() }
+ "category" -> parser.text?.trim()?.takeIf { it.isNotEmpty() }?.let(currentCategories::add)
+ "rating" -> currentRating = parser.text?.trim()?.takeIf { it.isNotEmpty() }
+ }
+ currentTag = null
+ }
+ }
+ XmlPullParser.END_TAG -> {
+ if (parser.name == "channel" && inChannel) {
+ if (channelId != null && channelDisplayName != null) {
+ onChannel(
+ XmltvChannel(
+ id = channelId,
+ displayName = channelDisplayName!!,
+ iconUrl = channelIconUrl
+ )
+ )
+ channelCount++
+ }
+ inChannel = false
+ }
+ if (parser.name == "rating") {
+ inRating = false
+ }
+ if (parser.name == "programme" && inProgramme) {
+ if (currentChannelId != null && currentTitle != null) {
+ onProgramme(
+ XmltvProgramme(
+ channelId = currentChannelId,
+ title = currentTitle,
+ subtitle = currentSubtitle,
+ description = currentDescription ?: "",
+ startTime = currentStart,
+ endTime = currentEnd,
+ lang = currentLang,
+ rating = currentRating,
+ imageUrl = currentImageUrl,
+ genre = currentCategories.distinct().joinToString(" / ").takeIf { it.isNotBlank() },
+ category = currentCategories.firstOrNull(),
+ episodeInfo = currentEpisodeNum
+ )
+ )
+ programmeCount++
+ }
+ inProgramme = false
+ }
+ }
+ }
+ eventType = parser.next()
+ }
+ } catch (e: Exception) {
+ logger.log(
+ Level.WARNING,
+ "XMLTV streaming parse failed after $channelCount channel(s) and $programmeCount programme(s)",
+ e
+ )
+ throw e
+ }
+ }
+
+ /**
+ * Wraps the input stream with GZIPInputStream if the URL ends in `.gz`.
+ */
+ fun maybeDecompressGzip(url: String, inputStream: InputStream): InputStream {
+ return if (url.lowercase(Locale.ROOT).let { it.endsWith(".gz") || it.endsWith(".gzip") }) {
+ GZIPInputStream(inputStream)
+ } else {
+ inputStream
+ }
+ }
+
private fun parseDate(dateStr: String?): Long {
if (dateStr.isNullOrBlank()) return 0
diff --git a/data/src/main/java/com/streamvault/data/repository/EpgRepositoryImpl.kt b/data/src/main/java/com/streamvault/data/repository/EpgRepositoryImpl.kt
index 5324878b..08dad004 100644
--- a/data/src/main/java/com/streamvault/data/repository/EpgRepositoryImpl.kt
+++ b/data/src/main/java/com/streamvault/data/repository/EpgRepositoryImpl.kt
@@ -10,6 +10,7 @@ import com.streamvault.data.util.rankSearchResults
import com.streamvault.domain.model.Program
import com.streamvault.domain.model.Result
import com.streamvault.domain.repository.EpgRepository
+import com.streamvault.domain.repository.EpgSourceRepository
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.delay
@@ -36,7 +37,8 @@ class EpgRepositoryImpl @Inject constructor(
private val programDao: ProgramDao,
private val xmltvParser: XmltvParser,
private val okHttpClient: OkHttpClient,
- private val transactionRunner: DatabaseTransactionRunner
+ private val transactionRunner: DatabaseTransactionRunner,
+ private val epgSourceRepository: EpgSourceRepository
) : EpgRepository {
private val providerRefreshMutexes = ConcurrentHashMap<Long, Mutex>()
@@ -232,6 +234,14 @@ class EpgRepositoryImpl @Inject constructor(
programDao.deleteOld(beforeTime)
}
+ override suspend fun getResolvedProgramsForChannels(
+ providerId: Long,
+ channelIds: List<Long>,
+ startTime: Long,
+ endTime: Long
+ ): Map<String, List<Program>> =
+ epgSourceRepository.getResolvedProgramsForChannels(providerId, channelIds, startTime, endTime)
+
private fun nowTicker(): Flow<Long> = flow {
while (true) {
emit(System.currentTimeMillis())
diff --git a/data/src/main/java/com/streamvault/data/repository/EpgSourceRepositoryImpl.kt b/data/src/main/java/com/streamvault/data/repository/EpgSourceRepositoryImpl.kt
new file mode 100644
index 00000000..5cf4e223
--- /dev/null
+++ b/data/src/main/java/com/streamvault/data/repository/EpgSourceRepositoryImpl.kt
@@ -0,0 +1,314 @@
+package com.streamvault.data.repository
+
+import android.content.Context
+import android.net.Uri
+import android.util.Log
+import com.streamvault.data.epg.EpgNameNormalizer
+import com.streamvault.data.epg.EpgResolutionEngine
+import com.streamvault.data.local.dao.EpgChannelDao
+import com.streamvault.data.local.dao.EpgProgrammeDao
+import com.streamvault.data.local.dao.EpgSourceDao
+import com.streamvault.data.local.dao.ProviderEpgSourceDao
+import com.streamvault.data.local.entity.EpgChannelEntity
+import com.streamvault.data.local.entity.EpgProgrammeEntity
+import com.streamvault.data.local.entity.EpgSourceEntity
+import com.streamvault.data.local.entity.ProviderEpgSourceEntity
+import com.streamvault.data.mapper.toDomain
+import com.streamvault.data.parser.XmltvParser
+import com.streamvault.data.util.UrlSecurityPolicy
+import com.streamvault.domain.model.EpgResolutionSummary
+import com.streamvault.domain.model.EpgSource
+import com.streamvault.domain.model.Program
+import com.streamvault.domain.model.ProviderEpgSourceAssignment
+import com.streamvault.domain.model.Result
+import com.streamvault.domain.repository.EpgSourceRepository
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.map
+import kotlinx.coroutines.sync.Mutex
+import kotlinx.coroutines.sync.withLock
+import kotlinx.coroutines.withContext
+import okhttp3.OkHttpClient
+import okhttp3.Request
+import java.io.FilterInputStream
+import java.io.IOException
+import dagger.hilt.android.qualifiers.ApplicationContext
+import java.util.concurrent.ConcurrentHashMap
+import javax.inject.Inject
+import javax.inject.Singleton
+
+@Singleton
+class EpgSourceRepositoryImpl @Inject constructor(
+ @ApplicationContext private val context: Context,
+ private val epgSourceDao: EpgSourceDao,
+ private val providerEpgSourceDao: ProviderEpgSourceDao,
+ private val epgChannelDao: EpgChannelDao,
+ private val epgProgrammeDao: EpgProgrammeDao,
+ private val xmltvParser: XmltvParser,
+ private val okHttpClient: OkHttpClient,
+ private val resolutionEngine: EpgResolutionEngine
+) : EpgSourceRepository {
+
+ companion object {
+ private const val TAG = "EpgSourceRepo"
+ private const val MAX_EPG_SIZE_BYTES = 200L * 1_048_576 // 200 MB
+ private const val CHANNEL_BATCH_SIZE = 500
+ private const val PROGRAMME_BATCH_SIZE = 500
+ }
+
+ private val sourceRefreshMutexes = ConcurrentHashMap<Long, Mutex>()
+
+ // ── EPG Source CRUD ────────────────────────────────────────────
+
+ override fun getAllSources(): Flow<List<EpgSource>> =
+ epgSourceDao.getAll().map { entities -> entities.map { it.toDomain() } }
+
+ override suspend fun getSourceById(id: Long): EpgSource? =
+ epgSourceDao.getById(id)?.toDomain()
+
+ override suspend fun addSource(name: String, url: String): Result<EpgSource> {
+ val trimmedUrl = url.trim()
+ 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")
+
+ val trimmedName = name.trim().takeIf { it.isNotEmpty() } ?: "EPG Source"
+ val now = System.currentTimeMillis()
+ val entity = EpgSourceEntity(
+ name = trimmedName,
+ url = trimmedUrl,
+ createdAt = now,
+ updatedAt = now
+ )
+ val id = epgSourceDao.insert(entity)
+ return Result.success(entity.copy(id = id).toDomain())
+ }
+
+ override suspend fun updateSource(source: EpgSource): Result<Unit> {
+ val trimmedUrl = source.url.trim()
+ val validationError = UrlSecurityPolicy.validateOptionalEpgUrl(trimmedUrl)
+ if (validationError != null) return Result.error(validationError)
+
+ val existing = epgSourceDao.getById(source.id) ?: return Result.error("Source not found")
+ epgSourceDao.update(
+ existing.copy(
+ name = source.name.trim().takeIf { it.isNotEmpty() } ?: existing.name,
+ url = trimmedUrl,
+ enabled = source.enabled,
+ priority = source.priority,
+ updatedAt = System.currentTimeMillis()
+ )
+ )
+ return Result.success(Unit)
+ }
+
+ override suspend fun deleteSource(id: Long) {
+ // Cascade: delete channels + programmes for this source, then the source itself
+ epgProgrammeDao.deleteBySource(id)
+ epgChannelDao.deleteBySource(id)
+ epgSourceDao.delete(id)
+ }
+
+ override suspend fun setSourceEnabled(id: Long, enabled: Boolean) {
+ epgSourceDao.setEnabled(id, enabled)
+ }
+
+ // ── Provider ↔ Source assignment ───────────────────────────────
+
+ override fun getAssignmentsForProvider(providerId: Long): Flow<List<ProviderEpgSourceAssignment>> =
+ providerEpgSourceDao.getForProvider(providerId)
+ .map { entities -> entities.map { it.toDomain() } }
+
+ override suspend fun assignSourceToProvider(
+ providerId: Long,
+ epgSourceId: Long,
+ priority: Int
+ ): Result<Unit> {
+ val source = epgSourceDao.getById(epgSourceId) ?: return Result.error("Source not found")
+ providerEpgSourceDao.insert(
+ ProviderEpgSourceEntity(
+ providerId = providerId,
+ epgSourceId = source.id,
+ priority = priority
+ )
+ )
+ return Result.success(Unit)
+ }
+
+ override suspend fun unassignSourceFromProvider(providerId: Long, epgSourceId: Long) {
+ providerEpgSourceDao.delete(providerId, epgSourceId)
+ }
+
+ override suspend fun updateAssignmentPriority(providerId: Long, epgSourceId: Long, priority: Int) {
+ val assignments = providerEpgSourceDao.getForProviderSync(providerId)
+ val target = assignments.find { it.epgSourceId == epgSourceId } ?: return
+ providerEpgSourceDao.update(target.copy(priority = priority))
+ }
+
+ // ── Refresh / Ingestion ────────────────────────────────────────
+
+ override suspend fun refreshSource(sourceId: Long): Result<Unit> = withContext(Dispatchers.IO) {
+ val mutex = sourceRefreshMutexes.computeIfAbsent(sourceId) { Mutex() }
+ mutex.withLock {
+ val source = epgSourceDao.getById(sourceId)
+ ?: return@withLock Result.error("Source not found")
+
+ val now = System.currentTimeMillis()
+ try {
+ epgSourceDao.updateRefreshStatus(sourceId, now, null)
+
+ val rawInputStream: java.io.InputStream = if (source.url.startsWith("content://")) {
+ context.contentResolver.openInputStream(Uri.parse(source.url))
+ ?: run {
+ val err = "Cannot open local file"
+ epgSourceDao.updateRefreshStatus(sourceId, now, err)
+ return@withLock Result.error(err)
+ }
+ } else {
+ val request = Request.Builder().url(source.url).build()
+ val response = okHttpClient.newCall(request).execute()
+
+ if (!response.isSuccessful) {
+ val err = "HTTP ${response.code}"
+ response.close()
+ epgSourceDao.updateRefreshStatus(sourceId, now, err)
+ return@withLock Result.error("Failed to download EPG: $err")
+ }
+
+ val contentLength = response.header("Content-Length")?.toLongOrNull() ?: -1L
+ if (contentLength > MAX_EPG_SIZE_BYTES) {
+ response.close()
+ val err = "File too large (${contentLength / 1_048_576}MB)"
+ epgSourceDao.updateRefreshStatus(sourceId, now, err)
+ return@withLock Result.error(err)
+ }
+
+ response.body?.byteStream() ?: run {
+ epgSourceDao.updateRefreshStatus(sourceId, now, "Empty response")
+ return@withLock Result.error("Empty EPG response")
+ }
+ }
+
+ val channelBatch = ArrayList<EpgChannelEntity>(CHANNEL_BATCH_SIZE)
+ val programmeBatch = ArrayList<EpgProgrammeEntity>(PROGRAMME_BATCH_SIZE)
+ var channelCount = 0
+ var programmeCount = 0
+
+ // Delete old data before ingesting
+ epgChannelDao.deleteBySource(sourceId)
+ epgProgrammeDao.deleteBySource(sourceId)
+
+ rawInputStream.use { raw ->
+ val limited = object : FilterInputStream(raw) {
+ 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 }
+ }
+ }
+ val decompressed = xmltvParser.maybeDecompressGzip(source.url, limited)
+
+ xmltvParser.parseStreamingWithChannels(
+ inputStream = decompressed,
+ onChannel = { xmltvChannel ->
+ channelBatch.add(
+ EpgChannelEntity(
+ epgSourceId = sourceId,
+ xmltvChannelId = xmltvChannel.id,
+ displayName = xmltvChannel.displayName,
+ normalizedName = EpgNameNormalizer.normalize(xmltvChannel.displayName),
+ iconUrl = xmltvChannel.iconUrl
+ )
+ )
+ channelCount++
+ if (channelBatch.size >= CHANNEL_BATCH_SIZE) {
+ epgChannelDao.insertAll(channelBatch.toList())
+ channelBatch.clear()
+ }
+ },
+ onProgramme = { programme ->
+ programmeBatch.add(
+ EpgProgrammeEntity(
+ epgSourceId = sourceId,
+ xmltvChannelId = programme.channelId,
+ startTime = programme.startTime,
+ endTime = programme.endTime,
+ title = programme.title,
+ subtitle = programme.subtitle,
+ description = programme.description,
+ category = programme.category,
+ lang = programme.lang,
+ rating = programme.rating,
+ imageUrl = programme.imageUrl,
+ episodeInfo = programme.episodeInfo
+ )
+ )
+ programmeCount++
+ if (programmeBatch.size >= PROGRAMME_BATCH_SIZE) {
+ epgProgrammeDao.insertAll(programmeBatch.toList())
+ programmeBatch.clear()
+ }
+ }
+ )
+ }
+
+ // Flush remaining
+ if (channelBatch.isNotEmpty()) {
+ epgChannelDao.insertAll(channelBatch.toList())
+ }
+ if (programmeBatch.isNotEmpty()) {
+ epgProgrammeDao.insertAll(programmeBatch.toList())
+ }
+
+ epgSourceDao.updateRefreshSuccess(sourceId, System.currentTimeMillis())
+ Log.d(TAG, "Refreshed source $sourceId: $channelCount channels, $programmeCount programmes")
+ 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)
+ }
+ }
+ }
+
+ override suspend fun refreshAllForProvider(providerId: Long): Result<Unit> {
+ val assignments = providerEpgSourceDao.getEnabledForProviderSync(providerId)
+ val errors = mutableListOf<String>()
+ for (assignment in assignments) {
+ val result = refreshSource(assignment.epgSourceId)
+ if (result is Result.Error) {
+ errors.add("Source ${assignment.epgSourceId}: ${result.message}")
+ }
+ }
+ return if (errors.isEmpty()) {
+ Result.success(Unit)
+ } else {
+ Result.error("Some sources failed: ${errors.joinToString("; ")}")
+ }
+ }
+
+ // ── Resolution ─────────────────────────────────────────────────
+
+ override suspend fun resolveForProvider(providerId: Long): EpgResolutionSummary =
+ resolutionEngine.resolveForProvider(providerId)
+
+ override suspend fun getResolutionSummary(providerId: Long): EpgResolutionSummary =
+ resolutionEngine.getResolutionSummary(providerId)
+
+ // ── Resolved query ─────────────────────────────────────────────
+
+ override suspend fun getResolvedProgramsForChannels(
+ providerId: Long,
+ channelIds: List<Long>,
+ startTime: Long,
+ endTime: Long
+ ): Map<String, List<Program>> =
+ resolutionEngine.getResolvedProgrammes(providerId, channelIds, startTime, endTime)
+}
diff --git a/data/src/main/java/com/streamvault/data/sync/DatabaseMaintenanceManager.kt b/data/src/main/java/com/streamvault/data/sync/DatabaseMaintenanceManager.kt
index e82af47b..c3d4721a 100644
--- a/data/src/main/java/com/streamvault/data/sync/DatabaseMaintenanceManager.kt
+++ b/data/src/main/java/com/streamvault/data/sync/DatabaseMaintenanceManager.kt
@@ -2,6 +2,7 @@ package com.streamvault.data.sync
import android.util.Log
import com.streamvault.data.local.StreamVaultDatabase
+import com.streamvault.data.local.dao.EpgProgrammeDao
import com.streamvault.data.local.dao.EpisodeDao
import com.streamvault.data.local.dao.FavoriteDao
import com.streamvault.data.local.dao.ProgramDao
@@ -15,6 +16,7 @@ import kotlinx.coroutines.withContext
class DatabaseMaintenanceManager @Inject constructor(
private val database: StreamVaultDatabase,
private val programDao: ProgramDao,
+ private val epgProgrammeDao: EpgProgrammeDao,
private val episodeDao: EpisodeDao,
private val favoriteDao: FavoriteDao
) {
@@ -22,6 +24,7 @@ class DatabaseMaintenanceManager @Inject constructor(
suspend fun runDailyMaintenance(now: Long = System.currentTimeMillis()): MaintenanceReport = withContext(Dispatchers.IO) {
val oldProgramThreshold = now - PROGRAM_RETENTION_MILLIS
val deletedPrograms = programDao.deleteOld(oldProgramThreshold)
+ val deletedExternalProgrammes = epgProgrammeDao.deleteOld(oldProgramThreshold)
val deletedOrphanEpisodes = episodeDao.deleteOrphans()
val deletedStaleFavorites = favoriteDao.deleteMissingLiveFavorites() +
favoriteDao.deleteMissingMovieFavorites() +
@@ -36,6 +39,7 @@ class DatabaseMaintenanceManager @Inject constructor(
MaintenanceReport(
deletedPrograms = deletedPrograms,
+ deletedExternalProgrammes = deletedExternalProgrammes,
deletedOrphanEpisodes = deletedOrphanEpisodes,
deletedStaleFavorites = deletedStaleFavorites,
vacuumRan = vacuumRan,
@@ -88,6 +92,7 @@ class DatabaseMaintenanceManager @Inject constructor(
data class MaintenanceReport(
val deletedPrograms: Int,
+ val deletedExternalProgrammes: Int = 0,
val deletedOrphanEpisodes: Int,
val deletedStaleFavorites: Int,
val vacuumRan: Boolean,
diff --git a/data/src/main/java/com/streamvault/data/sync/SyncManager.kt b/data/src/main/java/com/streamvault/data/sync/SyncManager.kt
index 722b8971..6dbc9c71 100644
--- a/data/src/main/java/com/streamvault/data/sync/SyncManager.kt
+++ b/data/src/main/java/com/streamvault/data/sync/SyncManager.kt
@@ -41,6 +41,7 @@ import com.streamvault.domain.model.SyncMetadata
import com.streamvault.domain.model.SyncState
import com.streamvault.domain.model.VodSyncMode
import com.streamvault.domain.repository.EpgRepository
+import com.streamvault.domain.repository.EpgSourceRepository
import com.streamvault.domain.repository.SyncMetadataRepository
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.CancellationException
@@ -112,6 +113,7 @@ class SyncManager @Inject constructor(
private val xtreamJson: Json,
private val m3uParser: M3uParser,
private val epgRepository: EpgRepository,
+ private val epgSourceRepository: EpgSourceRepository,
private val okHttpClient: OkHttpClient,
private val syncMetadataRepository: SyncMetadataRepository,
private val transactionRunner: DatabaseTransactionRunner,
@@ -817,6 +819,19 @@ class SyncManager @Inject constructor(
}
}
+ // Refresh external EPG sources assigned to this provider, then run resolution
+ try {
+ progress(provider.id, onProgress, "Refreshing external EPG sources...")
+ epgSourceRepository.refreshAllForProvider(provider.id)
+ progress(provider.id, onProgress, "Resolving EPG mappings...")
+ epgSourceRepository.resolveForProvider(provider.id)
+ } catch (e: CancellationException) {
+ throw e
+ } catch (e: Exception) {
+ Log.e(TAG, "External EPG resolution failed (non-fatal): ${sanitizeThrowableMessage(e)}")
+ warnings.add("External EPG source refresh/resolution failed.")
+ }
+
return if (warnings.isEmpty()) SyncOutcome() else SyncOutcome(partial = true, warnings = warnings)
}
@@ -877,6 +892,19 @@ class SyncManager @Inject constructor(
}
}
+ // Refresh external EPG sources assigned to this provider, then run resolution
+ try {
+ progress(provider.id, onProgress, "Refreshing external EPG sources...")
+ epgSourceRepository.refreshAllForProvider(provider.id)
+ progress(provider.id, onProgress, "Resolving EPG mappings...")
+ epgSourceRepository.resolveForProvider(provider.id)
+ } catch (e: CancellationException) {
+ throw e
+ } catch (e: Exception) {
+ Log.e(TAG, "External EPG resolution failed (non-fatal): ${sanitizeThrowableMessage(e)}")
+ warnings.add("External EPG source refresh/resolution failed.")
+ }
+
return if (warnings.isEmpty()) SyncOutcome() else SyncOutcome(partial = true, warnings = warnings)
}
@@ -912,6 +940,12 @@ class SyncManager @Inject constructor(
epgCount = programDao.countByProvider(provider.id)
)
syncMetadataRepository.updateMetadata(metadata)
+
+ // Also refresh external sources and run resolution
+ progress(provider.id, onProgress, "Refreshing external EPG sources...")
+ epgSourceRepository.refreshAllForProvider(provider.id)
+ progress(provider.id, onProgress, "Resolving EPG mappings...")
+ epgSourceRepository.resolveForProvider(provider.id)
}
private suspend fun syncLiveOnly(
diff --git a/data/src/main/java/com/streamvault/data/util/UrlSecurityPolicy.kt b/data/src/main/java/com/streamvault/data/util/UrlSecurityPolicy.kt
index f745903e..c870a444 100644
--- a/data/src/main/java/com/streamvault/data/util/UrlSecurityPolicy.kt
+++ b/data/src/main/java/com/streamvault/data/util/UrlSecurityPolicy.kt
@@ -45,10 +45,11 @@ object UrlSecurityPolicy {
}
fun validateOptionalEpgUrl(url: String): String? {
- return if (url.isBlank() || isSecureRemoteUrl(url)) {
- null
- } else {
- "EPG URLs must use HTTPS."
+ return when {
+ url.isBlank() -> null
+ url.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."
}
}
diff --git a/data/src/test/java/com/streamvault/data/epg/EpgNameNormalizerTest.kt b/data/src/test/java/com/streamvault/data/epg/EpgNameNormalizerTest.kt
new file mode 100644
index 00000000..794d901f
--- /dev/null
+++ b/data/src/test/java/com/streamvault/data/epg/EpgNameNormalizerTest.kt
@@ -0,0 +1,53 @@
+package com.streamvault.data.epg
+
+import com.google.common.truth.Truth.assertThat
+import org.junit.Test
+
+class EpgNameNormalizerTest {
+
+ @Test
+ fun `normalize_basicName_lowercaseAndStripped`() {
+ assertThat(EpgNameNormalizer.normalize("BBC One HD")).isEqualTo("bbconehd")
+ }
+
+ @Test
+ fun `normalize_accents_removed`() {
+ assertThat(EpgNameNormalizer.normalize("Télé Loisirs")).isEqualTo("teleloisirs")
+ }
+
+ @Test
+ fun `normalize_specialChars_removed`() {
+ assertThat(EpgNameNormalizer.normalize("CNN - US (Int'l)")).isEqualTo("cnnusintl")
+ }
+
+ @Test
+ fun `normalize_empty_returnsEmpty`() {
+ assertThat(EpgNameNormalizer.normalize("")).isEmpty()
+ assertThat(EpgNameNormalizer.normalize(" ")).isEmpty()
+ }
+
+ @Test
+ fun `normalize_numbersPreserved`() {
+ assertThat(EpgNameNormalizer.normalize("Sport 1")).isEqualTo("sport1")
+ }
+
+ @Test
+ fun `normalize_mixedCase_lowered`() {
+ assertThat(EpgNameNormalizer.normalize("DiScOvErY")).isEqualTo("discovery")
+ }
+
+ @Test
+ fun `normalize_allSpecialChars_returnsEmpty`() {
+ assertThat(EpgNameNormalizer.normalize("---")).isEmpty()
+ }
+
+ @Test
+ fun `normalize_germanUmlauts_stripped`() {
+ assertThat(EpgNameNormalizer.normalize("ZDF Küche")).isEqualTo("zdfkuche")
+ }
+
+ @Test
+ fun `normalize_frenchCedilla_stripped`() {
+ assertThat(EpgNameNormalizer.normalize("Garçon")).isEqualTo("garcon")
+ }
+}
diff --git a/data/src/test/java/com/streamvault/data/epg/EpgResolutionEngineTest.kt b/data/src/test/java/com/streamvault/data/epg/EpgResolutionEngineTest.kt
new file mode 100644
index 00000000..d006fc1c
--- /dev/null
+++ b/data/src/test/java/com/streamvault/data/epg/EpgResolutionEngineTest.kt
@@ -0,0 +1,366 @@
+package com.streamvault.data.epg
+
+import com.google.common.truth.Truth.assertThat
+import com.streamvault.data.local.dao.ChannelDao
+import com.streamvault.data.local.dao.ChannelEpgMappingDao
+import com.streamvault.data.local.dao.EpgChannelDao
+import com.streamvault.data.local.dao.EpgProgrammeDao
+import com.streamvault.data.local.dao.ProgramDao
+import com.streamvault.data.local.dao.ProviderEpgSourceDao
+import com.streamvault.data.local.entity.ChannelEntity
+import com.streamvault.data.local.entity.ChannelEpgMappingEntity
+import com.streamvault.data.local.entity.EpgChannelEntity
+import com.streamvault.data.local.entity.EpgProgrammeEntity
+import com.streamvault.data.local.entity.ProgramBrowseEntity
+import com.streamvault.data.local.entity.ProviderEpgSourceEntity
+import com.streamvault.domain.model.EpgMatchType
+import com.streamvault.domain.model.EpgSourceType
+import kotlinx.coroutines.test.runTest
+import org.junit.Before
+import org.junit.Test
+import org.mockito.kotlin.any
+import org.mockito.kotlin.argumentCaptor
+import org.mockito.kotlin.mock
+import org.mockito.kotlin.verify
+import org.mockito.kotlin.whenever
+
+class EpgResolutionEngineTest {
+
+ private val channelDao: ChannelDao = mock()
+ private val channelEpgMappingDao: ChannelEpgMappingDao = mock()
+ private val providerEpgSourceDao: ProviderEpgSourceDao = mock()
+ private val epgChannelDao: EpgChannelDao = mock()
+ private val epgProgrammeDao: EpgProgrammeDao = mock()
+ private val programDao: ProgramDao = mock()
+
+ private lateinit var engine: EpgResolutionEngine
+
+ companion object {
+ private const val PROVIDER_ID = 1L
+ private const val SOURCE_1 = 10L
+ private const val SOURCE_2 = 20L
+ }
+
+ @Before
+ fun setup() {
+ engine = EpgResolutionEngine(
+ channelDao = channelDao,
+ channelEpgMappingDao = channelEpgMappingDao,
+ providerEpgSourceDao = providerEpgSourceDao,
+ epgChannelDao = epgChannelDao,
+ epgProgrammeDao = epgProgrammeDao,
+ programDao = programDao
+ )
+ }
+
+ // ── resolveForProvider ─────────────────────────────────────────
+
+ @Test
+ fun `resolveForProvider_exactIdMatch_resolvesAsExternalExactId`() = runTest {
+ val channel = makeChannel(id = 1, name = "BBC One", epgChannelId = "bbc1.uk")
+ whenever(channelDao.getByProviderSync(PROVIDER_ID)).thenReturn(listOf(channel))
+ whenever(providerEpgSourceDao.getEnabledForProviderSync(PROVIDER_ID)).thenReturn(
+ listOf(ProviderEpgSourceEntity(id = 1, providerId = PROVIDER_ID, epgSourceId = SOURCE_1, priority = 0))
+ )
+ whenever(epgChannelDao.getBySources(listOf(SOURCE_1))).thenReturn(
+ listOf(EpgChannelEntity(id = 1, epgSourceId = SOURCE_1, xmltvChannelId = "bbc1.uk", displayName = "BBC One", normalizedName = "bbcone"))
+ )
+ whenever(channelEpgMappingDao.getForProvider(PROVIDER_ID)).thenReturn(emptyList())
+ whenever(programDao.countByProvider(PROVIDER_ID)).thenReturn(0)
+
+ val summary = engine.resolveForProvider(PROVIDER_ID)
+
+ assertThat(summary.exactIdMatches).isEqualTo(1)
+ assertThat(summary.totalChannels).isEqualTo(1)
+
+ val captor = argumentCaptor<List<ChannelEpgMappingEntity>>()
+ verify(channelEpgMappingDao).replaceForProvider(any(), captor.capture())
+ val mapping = captor.firstValue.single()
+ assertThat(mapping.sourceType).isEqualTo(EpgSourceType.EXTERNAL.name)
+ assertThat(mapping.matchType).isEqualTo(EpgMatchType.EXACT_ID.name)
+ assertThat(mapping.xmltvChannelId).isEqualTo("bbc1.uk")
+ assertThat(mapping.confidence).isEqualTo(1.0f)
+ }
+
+ @Test
+ fun `resolveForProvider_normalizedNameFallback_resolvesAsNormalizedName`() = runTest {
+ // Channel has no matching epgChannelId but name matches after normalization
+ val channel = makeChannel(id = 1, name = "CNN International", epgChannelId = null)
+ whenever(channelDao.getByProviderSync(PROVIDER_ID)).thenReturn(listOf(channel))
+ whenever(providerEpgSourceDao.getEnabledForProviderSync(PROVIDER_ID)).thenReturn(
+ listOf(ProviderEpgSourceEntity(id = 1, providerId = PROVIDER_ID, epgSourceId = SOURCE_1, priority = 0))
+ )
+ whenever(epgChannelDao.getBySources(listOf(SOURCE_1))).thenReturn(
+ listOf(EpgChannelEntity(id = 1, epgSourceId = SOURCE_1, xmltvChannelId = "cnn.intl", displayName = "CNN International", normalizedName = EpgNameNormalizer.normalize("CNN International")))
+ )
+ whenever(channelEpgMappingDao.getForProvider(PROVIDER_ID)).thenReturn(emptyList())
+ whenever(programDao.countByProvider(PROVIDER_ID)).thenReturn(0)
+
+ val summary = engine.resolveForProvider(PROVIDER_ID)
+
+ assertThat(summary.normalizedNameMatches).isEqualTo(1)
+
+ val captor = argumentCaptor<List<ChannelEpgMappingEntity>>()
+ verify(channelEpgMappingDao).replaceForProvider(any(), captor.capture())
+ val mapping = captor.firstValue.single()
+ assertThat(mapping.matchType).isEqualTo(EpgMatchType.NORMALIZED_NAME.name)
+ assertThat(mapping.xmltvChannelId).isEqualTo("cnn.intl")
+ assertThat(mapping.confidence).isEqualTo(0.7f)
+ }
+
+ @Test
+ fun `resolveForProvider_providerNativeFallback_resolvesAsProvider`() = runTest {
+ // Channel has epgChannelId but no external source matches — falls back to provider native
+ 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)
+
+ val captor = argumentCaptor<List<ChannelEpgMappingEntity>>()
+ verify(channelEpgMappingDao).replaceForProvider(any(), captor.capture())
+ val mapping = captor.firstValue.single()
+ assertThat(mapping.sourceType).isEqualTo(EpgSourceType.PROVIDER.name)
+ assertThat(mapping.matchType).isEqualTo(EpgMatchType.PROVIDER_NATIVE.name)
+ }
+
+ @Test
+ fun `resolveForProvider_unresolvedChannel_noEpg`() = runTest {
+ val channel = makeChannel(id = 1, name = "Mystery Channel", epgChannelId = null)
+ 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(0)
+
+ val summary = engine.resolveForProvider(PROVIDER_ID)
+
+ assertThat(summary.unresolvedChannels).isEqualTo(1)
+
+ val captor = argumentCaptor<List<ChannelEpgMappingEntity>>()
+ verify(channelEpgMappingDao).replaceForProvider(any(), captor.capture())
+ val mapping = captor.firstValue.single()
+ assertThat(mapping.sourceType).isEqualTo(EpgSourceType.NONE.name)
+ assertThat(mapping.matchType).isNull()
+ }
+
+ @Test
+ fun `resolveForProvider_higherPrioritySourceWins`() = runTest {
+ // Both sources match the same channel by exact ID — source with lower priority index wins
+ val channel = makeChannel(id = 1, name = "BBC One", epgChannelId = "bbc1")
+ whenever(channelDao.getByProviderSync(PROVIDER_ID)).thenReturn(listOf(channel))
+ // assignment order = priority order (source_1 first)
+ whenever(providerEpgSourceDao.getEnabledForProviderSync(PROVIDER_ID)).thenReturn(listOf(
+ ProviderEpgSourceEntity(id = 1, providerId = PROVIDER_ID, epgSourceId = SOURCE_1, priority = 0),
+ ProviderEpgSourceEntity(id = 2, providerId = PROVIDER_ID, epgSourceId = SOURCE_2, priority = 1)
+ ))
+ whenever(epgChannelDao.getBySources(listOf(SOURCE_1, SOURCE_2))).thenReturn(listOf(
+ EpgChannelEntity(id = 1, epgSourceId = SOURCE_1, xmltvChannelId = "bbc1", displayName = "BBC One", normalizedName = "bbcone"),
+ EpgChannelEntity(id = 2, epgSourceId = SOURCE_2, xmltvChannelId = "bbc1", displayName = "BBC 1", normalizedName = "bbc1")
+ ))
+ whenever(channelEpgMappingDao.getForProvider(PROVIDER_ID)).thenReturn(emptyList())
+ whenever(programDao.countByProvider(PROVIDER_ID)).thenReturn(0)
+
+ val summary = engine.resolveForProvider(PROVIDER_ID)
+
+ assertThat(summary.exactIdMatches).isEqualTo(1)
+
+ val captor = argumentCaptor<List<ChannelEpgMappingEntity>>()
+ verify(channelEpgMappingDao).replaceForProvider(any(), captor.capture())
+ val mapping = captor.firstValue.single()
+ // SOURCE_1 should win because it appears first in the priority-ordered list
+ assertThat(mapping.epgSourceId).isEqualTo(SOURCE_1)
+ }
+
+ @Test
+ fun `resolveForProvider_manualOverridePreserved`() = runTest {
+ val channel = makeChannel(id = 1, name = "BBC One", epgChannelId = "bbc1")
+ whenever(channelDao.getByProviderSync(PROVIDER_ID)).thenReturn(listOf(channel))
+ whenever(providerEpgSourceDao.getEnabledForProviderSync(PROVIDER_ID)).thenReturn(
+ listOf(ProviderEpgSourceEntity(id = 1, providerId = PROVIDER_ID, epgSourceId = SOURCE_1, priority = 0))
+ )
+ whenever(epgChannelDao.getBySources(listOf(SOURCE_1))).thenReturn(
+ listOf(EpgChannelEntity(id = 1, epgSourceId = SOURCE_1, xmltvChannelId = "bbc1", displayName = "BBC One", normalizedName = "bbcone"))
+ )
+ // Existing manual override
+ val manualMapping = ChannelEpgMappingEntity(
+ id = 99, providerChannelId = 1, providerId = PROVIDER_ID,
+ sourceType = EpgSourceType.EXTERNAL.name, epgSourceId = SOURCE_2,
+ xmltvChannelId = "bbc1.manual", matchType = EpgMatchType.MANUAL.name,
+ confidence = 1.0f, isManualOverride = true, updatedAt = 1000L
+ )
+ whenever(channelEpgMappingDao.getForProvider(PROVIDER_ID)).thenReturn(listOf(manualMapping))
+ whenever(programDao.countByProvider(PROVIDER_ID)).thenReturn(0)
+
+ engine.resolveForProvider(PROVIDER_ID)
+
+ val captor = argumentCaptor<List<ChannelEpgMappingEntity>>()
+ verify(channelEpgMappingDao).replaceForProvider(any(), captor.capture())
+ val mapping = captor.firstValue.single()
+ // Manual override should be preserved with updated timestamp
+ assertThat(mapping.isManualOverride).isTrue()
+ assertThat(mapping.xmltvChannelId).isEqualTo("bbc1.manual")
+ assertThat(mapping.epgSourceId).isEqualTo(SOURCE_2)
+ }
+
+ @Test
+ fun `resolveForProvider_emptyChannelList_clearsAndReturnsEmpty`() = runTest {
+ whenever(channelDao.getByProviderSync(PROVIDER_ID)).thenReturn(emptyList())
+
+ val summary = engine.resolveForProvider(PROVIDER_ID)
+
+ assertThat(summary.totalChannels).isEqualTo(0)
+ verify(channelEpgMappingDao).deleteByProvider(PROVIDER_ID)
+ }
+
+ @Test
+ fun `resolveForProvider_exactIdBeatsNormalizedName`() = runTest {
+ // Channel has both exact ID and name match — exact ID should win
+ val channel = makeChannel(id = 1, name = "BBC One HD", epgChannelId = "bbc.one.hd")
+ whenever(channelDao.getByProviderSync(PROVIDER_ID)).thenReturn(listOf(channel))
+ whenever(providerEpgSourceDao.getEnabledForProviderSync(PROVIDER_ID)).thenReturn(
+ listOf(ProviderEpgSourceEntity(id = 1, providerId = PROVIDER_ID, epgSourceId = SOURCE_1, priority = 0))
+ )
+ whenever(epgChannelDao.getBySources(listOf(SOURCE_1))).thenReturn(listOf(
+ // Has exact ID match
+ EpgChannelEntity(id = 1, epgSourceId = SOURCE_1, xmltvChannelId = "bbc.one.hd", displayName = "BBC 1 HD", normalizedName = "bbc1hd"),
+ // Also has a name match (normalizes to same thing)
+ EpgChannelEntity(id = 2, epgSourceId = SOURCE_1, xmltvChannelId = "bbc.one.sd", displayName = "BBC One HD", normalizedName = EpgNameNormalizer.normalize("BBC One HD"))
+ ))
+ whenever(channelEpgMappingDao.getForProvider(PROVIDER_ID)).thenReturn(emptyList())
+ whenever(programDao.countByProvider(PROVIDER_ID)).thenReturn(0)
+
+ val summary = engine.resolveForProvider(PROVIDER_ID)
+
+ assertThat(summary.exactIdMatches).isEqualTo(1)
+ assertThat(summary.normalizedNameMatches).isEqualTo(0)
+
+ val captor = argumentCaptor<List<ChannelEpgMappingEntity>>()
+ verify(channelEpgMappingDao).replaceForProvider(any(), captor.capture())
+ val mapping = captor.firstValue.single()
+ assertThat(mapping.matchType).isEqualTo(EpgMatchType.EXACT_ID.name)
+ assertThat(mapping.xmltvChannelId).isEqualTo("bbc.one.hd")
+ }
+
+ @Test
+ fun `resolveForProvider_duplicateSourceDoesNotCreateDuplicateMappings`() = runTest {
+ // Two channels that map to the same source — each gets its own mapping
+ val ch1 = makeChannel(id = 1, name = "Channel A", epgChannelId = "ch-a")
+ val ch2 = makeChannel(id = 2, name = "Channel B", epgChannelId = "ch-b")
+ whenever(channelDao.getByProviderSync(PROVIDER_ID)).thenReturn(listOf(ch1, ch2))
+ whenever(providerEpgSourceDao.getEnabledForProviderSync(PROVIDER_ID)).thenReturn(
+ listOf(ProviderEpgSourceEntity(id = 1, providerId = PROVIDER_ID, epgSourceId = SOURCE_1, priority = 0))
+ )
+ whenever(epgChannelDao.getBySources(listOf(SOURCE_1))).thenReturn(listOf(
+ EpgChannelEntity(id = 1, epgSourceId = SOURCE_1, xmltvChannelId = "ch-a", displayName = "Channel A", normalizedName = "channela"),
+ EpgChannelEntity(id = 2, epgSourceId = SOURCE_1, xmltvChannelId = "ch-b", displayName = "Channel B", normalizedName = "channelb")
+ ))
+ whenever(channelEpgMappingDao.getForProvider(PROVIDER_ID)).thenReturn(emptyList())
+ whenever(programDao.countByProvider(PROVIDER_ID)).thenReturn(0)
+
+ val summary = engine.resolveForProvider(PROVIDER_ID)
+
+ assertThat(summary.exactIdMatches).isEqualTo(2)
+ assertThat(summary.totalChannels).isEqualTo(2)
+
+ val captor = argumentCaptor<List<ChannelEpgMappingEntity>>()
+ verify(channelEpgMappingDao).replaceForProvider(any(), captor.capture())
+ val mappings = captor.firstValue
+ assertThat(mappings).hasSize(2)
+ // Each channel gets exactly one mapping — no duplicates
+ assertThat(mappings.map { it.providerChannelId }.toSet()).containsExactly(1L, 2L)
+ }
+
+ // ── getResolvedProgrammes ──────────────────────────────────────
+
+ @Test
+ fun `getResolvedProgrammes_externalSource_returnsProgrammes`() = runTest {
+ val now = System.currentTimeMillis()
+ val startTime = now - 3600_000
+ val endTime = now + 3600_000
+
+ whenever(channelEpgMappingDao.getForChannels(PROVIDER_ID, listOf(1L))).thenReturn(listOf(
+ ChannelEpgMappingEntity(
+ id = 1, providerChannelId = 1, providerId = PROVIDER_ID,
+ sourceType = EpgSourceType.EXTERNAL.name, epgSourceId = SOURCE_1,
+ xmltvChannelId = "bbc1", matchType = EpgMatchType.EXACT_ID.name,
+ confidence = 1.0f, updatedAt = now
+ )
+ ))
+ whenever(channelDao.getByProviderSync(PROVIDER_ID)).thenReturn(listOf(
+ makeChannel(id = 1, name = "BBC One", epgChannelId = "bbc1")
+ ))
+ whenever(epgProgrammeDao.getForChannels(SOURCE_1, listOf("bbc1"), startTime, endTime)).thenReturn(listOf(
+ EpgProgrammeEntity(id = 1, epgSourceId = SOURCE_1, xmltvChannelId = "bbc1", startTime = startTime, endTime = endTime, title = "News")
+ ))
+
+ val result = engine.getResolvedProgrammes(PROVIDER_ID, listOf(1L), startTime, endTime)
+
+ assertThat(result).containsKey("bbc1")
+ assertThat(result["bbc1"]).hasSize(1)
+ assertThat(result["bbc1"]!![0].title).isEqualTo("News")
+ }
+
+ @Test
+ fun `getResolvedProgrammes_providerNative_returnsProgrammes`() = runTest {
+ val now = System.currentTimeMillis()
+ val startTime = now - 3600_000
+ val endTime = now + 3600_000
+
+ whenever(channelEpgMappingDao.getForChannels(PROVIDER_ID, listOf(1L))).thenReturn(listOf(
+ ChannelEpgMappingEntity(
+ id = 1, providerChannelId = 1, providerId = PROVIDER_ID,
+ sourceType = EpgSourceType.PROVIDER.name, epgSourceId = null,
+ xmltvChannelId = "local.ch1", matchType = EpgMatchType.PROVIDER_NATIVE.name,
+ confidence = 0.5f, updatedAt = now
+ )
+ ))
+ whenever(channelDao.getByProviderSync(PROVIDER_ID)).thenReturn(listOf(
+ makeChannel(id = 1, name = "Local Channel", epgChannelId = "local.ch1")
+ ))
+ whenever(programDao.getForChannelsSync(PROVIDER_ID, listOf("local.ch1"), startTime, endTime)).thenReturn(listOf(
+ ProgramBrowseEntity(id = 1, providerId = PROVIDER_ID, channelId = "local.ch1", title = "Local News", startTime = startTime, endTime = endTime)
+ ))
+
+ val result = engine.getResolvedProgrammes(PROVIDER_ID, listOf(1L), startTime, endTime)
+
+ assertThat(result).containsKey("local.ch1")
+ assertThat(result["local.ch1"]!!.first().title).isEqualTo("Local News")
+ }
+
+ @Test
+ fun `getResolvedProgrammes_unmappedChannel_returnsEmpty`() = runTest {
+ val now = System.currentTimeMillis()
+ whenever(channelEpgMappingDao.getForChannels(PROVIDER_ID, listOf(1L))).thenReturn(listOf(
+ ChannelEpgMappingEntity(
+ id = 1, providerChannelId = 1, providerId = PROVIDER_ID,
+ sourceType = EpgSourceType.NONE.name, updatedAt = now
+ )
+ ))
+ whenever(channelDao.getByProviderSync(PROVIDER_ID)).thenReturn(listOf(
+ makeChannel(id = 1, name = "Mystery Channel", epgChannelId = null)
+ ))
+
+ val result = engine.getResolvedProgrammes(PROVIDER_ID, listOf(1L), now - 3600_000, now + 3600_000)
+
+ assertThat(result).isEmpty()
+ }
+
+ // ── Helpers ────────────────────────────────────────────────────
+
+ private fun makeChannel(
+ id: Long,
+ name: String,
+ epgChannelId: String? = null,
+ streamId: Long = 0L
+ ) = ChannelEntity(
+ id = id,
+ name = name,
+ epgChannelId = epgChannelId,
+ streamId = streamId,
+ providerId = PROVIDER_ID
+ )
+}
diff --git a/data/src/test/java/com/streamvault/data/parser/XmltvParserTest.kt b/data/src/test/java/com/streamvault/data/parser/XmltvParserTest.kt
index 135663e5..081059de 100644
--- a/data/src/test/java/com/streamvault/data/parser/XmltvParserTest.kt
+++ b/data/src/test/java/com/streamvault/data/parser/XmltvParserTest.kt
@@ -224,4 +224,108 @@ class XmltvParserTest {
assertThat(timestamps.distinct()).containsExactly(1_735_722_000_000L)
}
+
+ // ── parseStreamingWithChannels ─────────────────────────────────
+
+ @Test
+ fun `parseStreamingWithChannels_yieldsChannelsAndProgrammes`() = runTest {
+ val xml = """
+ <?xml version="1.0" encoding="UTF-8"?>
+ <tv>
+ <channel id="ch1">
+ <display-name>BBC One</display-name>
+ <icon src="http://example.com/bbc.png"/>
+ </channel>
+ <channel id="ch2">
+ <display-name>CNN</display-name>
+ </channel>
+ <programme start="20250101120000 +0000" stop="20250101130000 +0000" channel="ch1">
+ <title>News</title>
+ <desc>Daily news</desc>
+ </programme>
+ <programme start="20250101130000 +0000" stop="20250101140000 +0000" channel="ch2">
+ <title>Sports</title>
+ </programme>
+ </tv>
+ """.trimIndent()
+
+ val channels = mutableListOf<XmltvChannel>()
+ val programmes = mutableListOf<XmltvProgramme>()
+
+ parser.parseStreamingWithChannels(
+ inputStream = xml.byteInputStream(),
+ onChannel = { channels.add(it) },
+ onProgramme = { programmes.add(it) }
+ )
+
+ assertThat(channels).hasSize(2)
+ assertThat(channels[0].id).isEqualTo("ch1")
+ assertThat(channels[0].displayName).isEqualTo("BBC One")
+ assertThat(channels[0].iconUrl).isEqualTo("http://example.com/bbc.png")
+ assertThat(channels[1].id).isEqualTo("ch2")
+ assertThat(channels[1].displayName).isEqualTo("CNN")
+ assertThat(channels[1].iconUrl).isNull()
+
+ assertThat(programmes).hasSize(2)
+ assertThat(programmes[0].channelId).isEqualTo("ch1")
+ assertThat(programmes[0].title).isEqualTo("News")
+ assertThat(programmes[1].channelId).isEqualTo("ch2")
+ assertThat(programmes[1].title).isEqualTo("Sports")
+ }
+
+ @Test
+ fun `parseStreamingWithChannels_parsesSubtitleAndEpisodeInfo`() = runTest {
+ val xml = """
+ <?xml version="1.0" encoding="UTF-8"?>
+ <tv>
+ <channel id="ch1">
+ <display-name>BBC One</display-name>
+ </channel>
+ <programme start="20250101120000 +0000" stop="20250101130000 +0000" channel="ch1">
+ <title>Doctor Who</title>
+ <sub-title>The Christmas Invasion</sub-title>
+ <episode-num system="xmltv_ns">1.2.0/1</episode-num>
+ <desc>A holiday special</desc>
+ </programme>
+ </tv>
+ """.trimIndent()
+
+ val programmes = mutableListOf<XmltvProgramme>()
+ parser.parseStreamingWithChannels(
+ inputStream = xml.byteInputStream(),
+ onChannel = { },
+ onProgramme = { programmes.add(it) }
+ )
+
+ assertThat(programmes).hasSize(1)
+ assertThat(programmes[0].subtitle).isEqualTo("The Christmas Invasion")
+ assertThat(programmes[0].episodeInfo).isEqualTo("1.2.0/1")
+ }
+
+ @Test
+ fun `parseStreamingWithChannels_emptyXml_yieldsNothing`() = runTest {
+ val xml = """
+ <?xml version="1.0" encoding="UTF-8"?>
+ <tv></tv>
+ """.trimIndent()
+
+ val channels = mutableListOf<XmltvChannel>()
+ val programmes = mutableListOf<XmltvProgramme>()
+
+ parser.parseStreamingWithChannels(
+ inputStream = xml.byteInputStream(),
+ onChannel = { channels.add(it) },
+ onProgramme = { programmes.add(it) }
+ )
+
+ assertThat(channels).isEmpty()
+ assertThat(programmes).isEmpty()
+ }
+
+ @Test
+ fun `maybeDecompressGzip_nonGzUrl_returnsOriginal`() {
+ val original = "hello".byteInputStream()
+ val result = parser.maybeDecompressGzip("http://example.com/epg.xml", original)
+ assertThat(result).isSameInstanceAs(original)
+ }
}
diff --git a/data/src/test/java/com/streamvault/data/repository/EpgRepositoryImplTest.kt b/data/src/test/java/com/streamvault/data/repository/EpgRepositoryImplTest.kt
index dfee6f92..fcfb56e6 100644
--- a/data/src/test/java/com/streamvault/data/repository/EpgRepositoryImplTest.kt
+++ b/data/src/test/java/com/streamvault/data/repository/EpgRepositoryImplTest.kt
@@ -27,6 +27,7 @@ import org.mockito.kotlin.argumentCaptor
import org.mockito.kotlin.atLeastOnce
import org.mockito.kotlin.mock
import org.mockito.kotlin.times
+import com.streamvault.domain.repository.EpgSourceRepository
import org.mockito.kotlin.verify
import org.mockito.kotlin.whenever
import java.util.concurrent.atomic.AtomicInteger
@@ -36,6 +37,7 @@ class EpgRepositoryImplTest {
private val programDao: ProgramDao = mock()
private val xmltvParser: XmltvParser = mock()
+ private val epgSourceRepository: EpgSourceRepository = mock()
private val transactionRunner = object : DatabaseTransactionRunner {
override suspend fun <T> inTransaction(block: suspend () -> T): T = block()
}
@@ -69,7 +71,8 @@ class EpgRepositoryImplTest {
programDao = programDao,
xmltvParser = xmltvParser,
okHttpClient = okHttpClientReturningXml(),
- transactionRunner = transactionRunner
+ transactionRunner = transactionRunner,
+ epgSourceRepository = epgSourceRepository
)
val result = repository.searchPrograms(7L, "sports", 0L, 100L).first()
@@ -122,7 +125,8 @@ class EpgRepositoryImplTest {
programDao = programDao,
xmltvParser = xmltvParser,
okHttpClient = okHttpClientReturningXml(),
- transactionRunner = transactionRunner
+ transactionRunner = transactionRunner,
+ epgSourceRepository = epgSourceRepository
)
val firstRefresh = async { repository.refreshEpg(7L, "https://example.com/epg.xml") }
diff --git a/data/src/test/java/com/streamvault/data/sync/SyncManagerTest.kt b/data/src/test/java/com/streamvault/data/sync/SyncManagerTest.kt
index b4dd7e27..d478d634 100644
--- a/data/src/test/java/com/streamvault/data/sync/SyncManagerTest.kt
+++ b/data/src/test/java/com/streamvault/data/sync/SyncManagerTest.kt
@@ -16,6 +16,8 @@ import com.streamvault.domain.model.Result
import com.streamvault.domain.model.ProviderType
import com.streamvault.domain.model.SyncMetadata
import com.streamvault.domain.repository.EpgRepository
+import com.streamvault.domain.repository.EpgSourceRepository
+import com.streamvault.data.preferences.PreferencesRepository
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.first
@@ -145,6 +147,8 @@ class SyncManagerTest {
private val categoryDao: CategoryDao = mock()
private val catalogSyncDao: CatalogSyncDao = mock()
private val epgRepo: EpgRepository = mock()
+ private val epgSourceRepo: EpgSourceRepository = mock()
+ private val preferencesRepo: PreferencesRepository = mock()
private val xtreamBackend = FakeXtreamBackend()
private val xtreamJson = Json {
ignoreUnknownKeys = true
@@ -176,9 +180,11 @@ class SyncManagerTest {
xtreamJson = xtreamJson,
m3uParser = M3uParser(),
epgRepository = epgRepo,
+ epgSourceRepository = epgSourceRepo,
okHttpClient = xtreamBackend.okHttpClient(),
syncMetadataRepository = syncMetadataRepo,
- transactionRunner = transactionRunner
+ transactionRunner = transactionRunner,
+ preferencesRepository = preferencesRepo
)
// ── Initial state ───────────────────────────────────────────────
diff --git a/docs/EPG_MULTI_SOURCE_ARCHITECTURE.md b/docs/EPG_MULTI_SOURCE_ARCHITECTURE.md
new file mode 100644
index 00000000..854d1c92
--- /dev/null
+++ b/docs/EPG_MULTI_SOURCE_ARCHITECTURE.md
@@ -0,0 +1,209 @@
+# EPG Multi-Source Architecture
+
+## Overview
+
+StreamVault supports multiple EPG (Electronic Program Guide) sources per provider. External XMLTV sources can be added, assigned to providers, and matched against channels using ID- or name-based matching. The system resolves the best EPG source per channel at sync time and persists the result for fast guide rendering.
+
+## Data Flow
+
+```
+User adds EPG source (Settings)
+ │
+ ▼
+┌─────────────────────────────────────────────────────────────────┐
+│ EpgSourceRepository.addSource(name, url) │
+│ → Insert into `epg_sources` table │
+│ → Assign to provider via `provider_epg_sources` │
+└───────────┬─────────────────────────────────────────────────────┘
+ │
+ SyncManager (full sync or EPG-only)
+ │
+ ▼
+┌─────────────────────────────────────────────────────────────────┐
+│ 1. Refresh provider-native EPG (existing `programs` table) │
+│ 2. Refresh external sources (EpgSourceRepositoryImpl) │
+│ → Download XMLTV (.xml or .xml.gz) │
+│ → Parse channels → `epg_channels` table │
+│ → Parse programmes → `epg_programmes` table │
+│ 3. Run resolution engine (EpgResolutionEngine) │
+│ → Match each channel to best source │
+│ → Persist results in `channel_epg_mappings` table │
+└───────────┬─────────────────────────────────────────────────────┘
+ │
+ Guide Grid render (EpgViewModel)
+ │
+ ▼
+┌─────────────────────────────────────────────────────────────────┐
+│ EpgRepository.getResolvedProgramsForChannels() │
+│ → Read `channel_epg_mappings` for provider │
+│ → EXTERNAL mappings → query `epg_programmes` table │
+│ → PROVIDER mappings → query `programs` table (legacy) │
+│ → Merge into unified Map<lookupKey, List<Program>> │
+│ → Fallback: Xtream on-demand API for unmapped channels │
+└─────────────────────────────────────────────────────────────────┘
+```
+
+## Resolution Algorithm
+
+For each provider channel, the `EpgResolutionEngine` evaluates matches in priority order:
+
+| Priority | Match Type | Confidence | Source | Description |
+|----------|-------------------|------------|------------|-------------|
+| 1 | MANUAL | 1.0 | External | User-overridden mapping (future feature) |
+| 2 | EXACT_ID | 1.0 | External | Channel's `epgChannelId` matches XMLTV `channel@id` |
+| 3 | NORMALIZED_NAME | 0.7 | External | Normalized channel name matches XMLTV `<display-name>` |
+| 4 | PROVIDER_NATIVE | 0.5 | Provider | Provider has EPG data for this channel |
+| 5 | NONE | 0.0 | — | No EPG coverage |
+
+When multiple external sources are assigned, they are evaluated in assignment priority order (lowest number = highest priority). First match wins.
+
+## Database Schema (v25)
+
+### `epg_sources`
+Global registry of external XMLTV EPG URLs.
+
+| Column | Type | Notes |
+|--------|------|-------|
+| id | INTEGER PK | Auto-increment |
+| name | TEXT | User-facing label |
+| url | TEXT UNIQUE | XMLTV URL (HTTPS) |
+| enabled | INTEGER | 1/0 |
+| priority | INTEGER | Global ordering |
+| last_refresh_at | INTEGER | Epoch millis |
+| last_success_at | INTEGER | Epoch millis, null if never |
+| last_error | TEXT | Last error message |
+| created_at | INTEGER | Epoch millis |
+| updated_at | INTEGER | Epoch millis |
+
+### `provider_epg_sources`
+Many-to-many: which external sources are assigned to which providers.
+
+| Column | Type | Notes |
+|--------|------|-------|
+| id | INTEGER PK | Auto-increment |
+| provider_id | INTEGER FK | → providers.id (CASCADE) |
+| epg_source_id | INTEGER FK | → epg_sources.id (CASCADE) |
+| priority | INTEGER | Per-provider ordering |
+| enabled | INTEGER | 1/0 |
+
+### `epg_channels`
+Channels from external XMLTV sources. Rebuilt on each source refresh.
+
+| Column | Type | Notes |
+|--------|------|-------|
+| id | INTEGER PK | Auto-increment |
+| epg_source_id | INTEGER FK | → epg_sources.id (CASCADE) |
+| xmltv_channel_id | TEXT | From `<channel id="...">` |
+| display_name | TEXT | From `<display-name>` |
+| normalized_name | TEXT | Lowercased, accent/symbol-stripped |
+| icon_url | TEXT | From `<icon src="...">` |
+
+### `epg_programmes`
+Programme data from external XMLTV sources. Rebuilt on each source refresh.
+
+| Column | Type | Notes |
+|--------|------|-------|
+| id | INTEGER PK | Auto-increment |
+| epg_source_id | INTEGER FK | → epg_sources.id (CASCADE) |
+| xmltv_channel_id | TEXT | Maps to epg_channels |
+| start_time, end_time | INTEGER | Epoch millis |
+| title, description | TEXT | Programme info |
+| category, lang, rating, image_url | TEXT | Optional metadata |
+
+### `channel_epg_mappings`
+Precomputed resolution results. One row per provider channel.
+
+| Column | Type | Notes |
+|--------|------|-------|
+| id | INTEGER PK | Auto-increment |
+| provider_channel_id | INTEGER FK | → channels.id |
+| provider_id | INTEGER FK | → providers.id (CASCADE) |
+| source_type | TEXT | EXTERNAL / PROVIDER / NONE |
+| epg_source_id | INTEGER | Nullable, FK → epg_sources.id |
+| xmltv_channel_id | TEXT | Nullable |
+| match_type | TEXT | EXACT_ID / NORMALIZED_NAME / MANUAL / PROVIDER_NATIVE |
+| confidence | REAL | 0.0–1.0 |
+| is_manual_override | INTEGER | 1/0 |
+| updated_at | INTEGER | Epoch millis |
+
+## Key Classes
+
+| Class | Module | Purpose |
+|-------|--------|---------|
+| `EpgSource`, `ProviderEpgSourceAssignment`, etc. | domain | Domain models |
+| `EpgSourceRepository` | domain | Interface for source management |
+| `EpgSourceRepositoryImpl` | data | CRUD, download, ingestion |
+| `EpgResolutionEngine` | data | Resolution algorithm + resolved queries |
+| `EpgNameNormalizer` | data | Name normalization for fuzzy matching |
+| `XmltvParser.parseStreamingWithChannels()` | data | Streaming channel+programme parser |
+| `XmltvParser.maybeDecompressGzip()` | data | Transparent .gz support |
+| `EpgViewModel.loadGuidePrograms()` | app | Resolved → legacy → Xtream fallback |
+
+## Backward Compatibility
+
+- The existing `programs` table and all existing queries remain unchanged
+- Provider-native EPG continues to work exactly as before
+- If no external sources are assigned, the guide falls back to legacy behavior
+- Resolution is additive: external sources enhance, never remove, existing EPG coverage
+- Migration 24→25 is non-destructive (creates new tables only)
+
+## Matching Strategy
+
+Channel-to-source matching uses a two-tier approach:
+
+1. **Exact ID match** — the channel's `epgChannelId` (from `tvg-id` in M3U, or provider API) is compared directly against `<channel id="...">` in the XMLTV source. This is the strongest signal (confidence 1.0) and is always preferred.
+
+2. **Normalized name match** — if no exact ID match exists, the channel's display name is normalized via `EpgNameNormalizer` (lowercase, trim, strip accents/punctuation/separators, remove common quality suffixes like HD/FHD/4K) and compared against the pre-normalized `normalized_name` column in `epg_channels`. Confidence is 0.7.
+
+When multiple external sources are assigned to a provider, they are evaluated in their assignment priority order. The first source that produces a match wins. This prevents ambiguity and ensures deterministic results.
+
+Fuzzy matching is deliberately conservative to avoid wrong mappings — there is no Levenshtein distance or partial substring matching.
+
+## Refresh Flow
+
+1. **SyncManager** triggers refresh during full provider sync or EPG-only sync
+2. For each enabled external source assigned to the provider:
+ - `EpgSourceRepositoryImpl.refreshSource()` downloads the XMLTV URL
+ - `.gz` files are auto-detected via URL suffix and decompressed with `GZIPInputStream`
+ - The response is size-limited (200 MB) and streamed through `XmltvParser.parseStreamingWithChannels()`
+ - Existing data for that source is **deleted before ingestion** (atomic swap per source)
+ - Channels and programmes are batch-inserted (500 items per batch)
+ - Source `last_refresh_at`, `last_success_at`, or `last_error` are updated
+3. After all source refreshes complete, `EpgResolutionEngine.resolveForProvider()` runs:
+ - Recomputes all channel mappings for that provider
+ - Preserves any existing manual overrides
+ - Replaces all mappings atomically via `replaceForProvider()`
+4. If a refresh **fails**, the error is recorded but previously-ingested data has already been cleared for that source (current design choice favoring consistency over stale data retention)
+
+## Conflict Resolution
+
+The system uses a **source-selection model**, not a programme-merge model:
+
+- Each channel gets exactly **one effective source** (external or provider-native)
+- The guide grid shows **one programme timeline per channel** — no visible collisions
+- When two external sources both match the same channel, the **higher-priority source** (lower priority number) wins
+- External sources always beat provider-native EPG for the same channel
+- Resolution is precomputed at sync time and stored in `channel_epg_mappings`, not evaluated at render time
+
+This design avoids the complexity and UX issues of per-programme conflict fusion (overlapping time blocks, duplicate entries, inconsistent data from different sources).
+
+## Known Limitations
+
+1. **Source refresh deletes before inserting** — if a refresh fails mid-parse, the source's data is lost. A staging-table approach could be added for higher reliability but adds complexity.
+2. **No incremental XMLTV update** — every refresh re-downloads and re-parses the full XMLTV file. Conditional HTTP (`If-Modified-Since`) is not yet implemented.
+3. **Manual override UI not implemented** — the data model supports it (`is_manual_override`, `MANUAL` match type) but there is no settings screen to set per-channel overrides yet.
+4. **No per-channel EPG source indicator in the guide** — the guide grid shows resolved data but doesn't visually indicate which source provided it.
+5. **Name normalization is conservative** — channels with significantly different naming across sources (e.g., "BBC 1" vs "BBC One") may not auto-match. Manual override or exact ID is needed.
+6. **Resolution runs for all channels** — for providers with very large channel counts (10k+), the resolution pass touches every channel. This is fast in practice but could be optimized to only re-resolve when sources change.
+7. **No stale programme auto-cleanup for external sources** — `DatabaseMaintenanceManager` handles provider-native programmes via `ProgramDao.deleteOld()`, but external `epg_programmes` stale data cleanup uses the same approach.
+
+## Future Extension Points
+
+1. **Manual override per channel** — add a channel details screen with "Override EPG Source" action that writes a `MANUAL` mapping to `channel_epg_mappings`
+2. **Per-channel EPG diagnostics** — show match type, confidence, source name, and alternative candidates on a channel info screen
+3. **Conditional refresh** — use `If-Modified-Since` / `ETag` headers to skip re-download when the source hasn't changed
+4. **Staging-swap refresh** — ingest into temporary tables and swap atomically, preserving old data on failure
+5. **Local XMLTV file import** — add a file picker for `.xml`/`.xml.gz` files on local storage
+6. **Match preview** — show exact-ID/name/unresolved counts before committing source assignment
+7. **Provider EPG toggle** — allow disabling provider-native EPG entirely when external sources provide better coverage
+8. **Background refresh scheduling** — periodic refresh of external sources independent of full provider sync
diff --git a/domain/src/main/java/com/streamvault/domain/model/EpgModels.kt b/domain/src/main/java/com/streamvault/domain/model/EpgModels.kt
new file mode 100644
index 00000000..29ada18f
--- /dev/null
+++ b/domain/src/main/java/com/streamvault/domain/model/EpgModels.kt
@@ -0,0 +1,97 @@
+package com.streamvault.domain.model
+
+/**
+ * Represents an external EPG source (e.g. an XMLTV URL).
+ */
+data class EpgSource(
+ val id: Long = 0,
+ val name: String,
+ val url: String,
+ val enabled: Boolean = true,
+ val lastRefreshAt: Long = 0,
+ val lastSuccessAt: Long = 0,
+ val lastError: String? = null,
+ val priority: Int = 0,
+ val createdAt: Long = System.currentTimeMillis(),
+ val updatedAt: Long = System.currentTimeMillis()
+)
+
+/**
+ * Represents the assignment of an external EPG source to a provider,
+ * with a priority for conflict resolution ordering.
+ */
+data class ProviderEpgSourceAssignment(
+ val id: Long = 0,
+ val providerId: Long,
+ val epgSourceId: Long,
+ val priority: Int = 0,
+ val enabled: Boolean = true,
+ val epgSourceName: String = "",
+ val epgSourceUrl: String = ""
+)
+
+/**
+ * Represents a channel entry parsed from an EPG source.
+ */
+data class EpgChannelInfo(
+ val id: Long = 0,
+ val epgSourceId: Long,
+ val xmltvChannelId: String,
+ val displayName: String,
+ val normalizedName: String = "",
+ val iconUrl: String? = null
+)
+
+/**
+ * How an EPG source was matched to a channel.
+ */
+enum class EpgMatchType {
+ /** Exact tvg-id / xmltv channel id match */
+ EXACT_ID,
+ /** Normalized display name match */
+ NORMALIZED_NAME,
+ /** User manually assigned */
+ MANUAL,
+ /** Provider-native EPG (existing programs table) */
+ PROVIDER_NATIVE
+}
+
+/**
+ * Which type of source supplies the EPG data.
+ */
+enum class EpgSourceType {
+ /** Data comes from the provider's built-in EPG (programs table) */
+ PROVIDER,
+ /** Data comes from an external XMLTV source (epg_programmes table) */
+ EXTERNAL,
+ /** No EPG data available */
+ NONE
+}
+
+/**
+ * The resolved EPG mapping for a single app channel.
+ * This is precomputed by the resolution engine and persisted.
+ */
+data class ChannelEpgMapping(
+ val id: Long = 0,
+ val providerChannelId: Long,
+ val providerId: Long,
+ val sourceType: EpgSourceType = EpgSourceType.NONE,
+ val epgSourceId: Long? = null,
+ val xmltvChannelId: String? = null,
+ val matchType: EpgMatchType? = null,
+ val confidence: Float = 0f,
+ val isManualOverride: Boolean = false,
+ val updatedAt: Long = System.currentTimeMillis()
+)
+
+/**
+ * Summary statistics from an EPG resolution pass.
+ */
+data class EpgResolutionSummary(
+ val totalChannels: Int = 0,
+ val exactIdMatches: Int = 0,
+ val normalizedNameMatches: Int = 0,
+ val providerNativeMatches: Int = 0,
+ val unresolvedChannels: Int = 0
+)
diff --git a/domain/src/main/java/com/streamvault/domain/repository/EpgRepository.kt b/domain/src/main/java/com/streamvault/domain/repository/EpgRepository.kt
index 31b953be..94049c0a 100644
--- a/domain/src/main/java/com/streamvault/domain/repository/EpgRepository.kt
+++ b/domain/src/main/java/com/streamvault/domain/repository/EpgRepository.kt
@@ -15,4 +15,12 @@ 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)
+
+ /** Returns resolved EPG programmes using multi-source resolution (external + provider-native). */
+ suspend fun getResolvedProgramsForChannels(
+ providerId: Long,
+ channelIds: List<Long>,
+ startTime: Long,
+ endTime: Long
+ ): Map<String, List<Program>>
}
diff --git a/domain/src/main/java/com/streamvault/domain/repository/EpgSourceRepository.kt b/domain/src/main/java/com/streamvault/domain/repository/EpgSourceRepository.kt
new file mode 100644
index 00000000..1fde2f53
--- /dev/null
+++ b/domain/src/main/java/com/streamvault/domain/repository/EpgSourceRepository.kt
@@ -0,0 +1,57 @@
+package com.streamvault.domain.repository
+
+import com.streamvault.domain.model.ChannelEpgMapping
+import com.streamvault.domain.model.EpgResolutionSummary
+import com.streamvault.domain.model.EpgSource
+import com.streamvault.domain.model.Program
+import com.streamvault.domain.model.ProviderEpgSourceAssignment
+import com.streamvault.domain.model.Result
+import kotlinx.coroutines.flow.Flow
+
+interface EpgSourceRepository {
+
+ // ── EPG Source CRUD ────────────────────────────────────────────
+
+ fun getAllSources(): Flow<List<EpgSource>>
+
+ suspend fun getSourceById(id: Long): EpgSource?
+
+ suspend fun addSource(name: String, url: String): Result<EpgSource>
+
+ suspend fun updateSource(source: EpgSource): Result<Unit>
+
+ suspend fun deleteSource(id: Long)
+
+ suspend fun setSourceEnabled(id: Long, enabled: Boolean)
+
+ // ── Provider ↔ Source assignment ───────────────────────────────
+
+ fun getAssignmentsForProvider(providerId: Long): Flow<List<ProviderEpgSourceAssignment>>
+
+ suspend fun assignSourceToProvider(providerId: Long, epgSourceId: Long, priority: Int): Result<Unit>
+
+ suspend fun unassignSourceFromProvider(providerId: Long, epgSourceId: Long)
+
+ suspend fun updateAssignmentPriority(providerId: Long, epgSourceId: Long, priority: Int)
+
+ // ── Refresh / Ingestion ────────────────────────────────────────
+
+ suspend fun refreshSource(sourceId: Long): Result<Unit>
+
+ suspend fun refreshAllForProvider(providerId: Long): Result<Unit>
+
+ // ── Resolution ─────────────────────────────────────────────────
+
+ suspend fun resolveForProvider(providerId: Long): EpgResolutionSummary
+
+ suspend fun getResolutionSummary(providerId: Long): EpgResolutionSummary
+
+ // ── Resolved query ─────────────────────────────────────────────
+
+ suspend fun getResolvedProgramsForChannels(
+ providerId: Long,
+ channelIds: List<Long>,
+ startTime: Long,
+ endTime: Long
+ ): Map<String, List<Program>>
+}