Skip to content

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

Complete IPTV audit fixes and parental control hardening

Davidonab7ce503f7442
diff --git a/.gitignore b/.gitignore
index d78564aa..d708012f 100644
--- a/.gitignore
+++ b/.gitignore
@@ -22,3 +22,6 @@ local.properties
# Build output
build_output_*.txt
+
+# Generated sources
+domain/bin/
diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml
index 775ff5b3..b9c86777 100644
--- a/app/src/main/AndroidManifest.xml
+++ b/app/src/main/AndroidManifest.xml
@@ -15,10 +15,11 @@
<application
android:name=".StreamVaultApp"
- android:allowBackup="true"
+ android:allowBackup="false"
android:banner="@drawable/app_banner"
android:icon="@mipmap/ic_launcher_vault"
android:label="StreamVault"
+ android:networkSecurityConfig="@xml/network_security_config"
android:supportsRtl="true"
android:theme="@style/Theme.StreamVault">
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 f19af23f..578c2a04 100644
--- a/app/src/main/java/com/streamvault/app/di/DatabaseModule.kt
+++ b/app/src/main/java/com/streamvault/app/di/DatabaseModule.kt
@@ -27,7 +27,11 @@ object DatabaseModule {
StreamVaultDatabase.MIGRATION_2_3,
StreamVaultDatabase.MIGRATION_3_4,
StreamVaultDatabase.MIGRATION_4_5,
- StreamVaultDatabase.MIGRATION_5_6
+ StreamVaultDatabase.MIGRATION_5_6,
+ StreamVaultDatabase.MIGRATION_6_7,
+ StreamVaultDatabase.MIGRATION_7_8,
+ StreamVaultDatabase.MIGRATION_8_9,
+ StreamVaultDatabase.MIGRATION_9_10
)
// NOTE: fallbackToDestructiveMigration() intentionally removed.
// All future schema changes MUST add a corresponding Migration in StreamVaultDatabase.
diff --git a/app/src/main/java/com/streamvault/app/di/NetworkModule.kt b/app/src/main/java/com/streamvault/app/di/NetworkModule.kt
index 72127214..a53dd97b 100644
--- a/app/src/main/java/com/streamvault/app/di/NetworkModule.kt
+++ b/app/src/main/java/com/streamvault/app/di/NetworkModule.kt
@@ -1,6 +1,7 @@
package com.streamvault.app.di
import android.content.Context
+import android.content.pm.ApplicationInfo
import com.streamvault.data.remote.xtream.XtreamApiService
import com.streamvault.data.parser.XmltvParser
import com.streamvault.player.Media3PlayerEngine
@@ -25,14 +26,23 @@ object NetworkModule {
@Provides
@Singleton
- fun provideOkHttpClient(): OkHttpClient =
- OkHttpClient.Builder()
+ fun provideOkHttpClient(
+ @ApplicationContext context: Context
+ ): OkHttpClient {
+ val isDebuggable = (context.applicationInfo.flags and ApplicationInfo.FLAG_DEBUGGABLE) != 0
+ val loggingLevel = if (isDebuggable) {
+ HttpLoggingInterceptor.Level.BASIC
+ } else {
+ HttpLoggingInterceptor.Level.NONE
+ }
+
+ return OkHttpClient.Builder()
.connectTimeout(30, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS)
.addInterceptor(
HttpLoggingInterceptor().apply {
- level = HttpLoggingInterceptor.Level.BASIC
+ level = loggingLevel
}
)
.followRedirects(true)
@@ -43,6 +53,7 @@ object NetworkModule {
maxRequestsPerHost = 10 // Increase host limit for Multi-View
})
.build()
+ }
@Provides
@Singleton
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 ab36ba3a..4a2a7816 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
@@ -1,43 +1,62 @@
package com.streamvault.app.ui.components
-import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.core.FastOutSlowInEasing
-import androidx.compose.animation.core.animateDpAsState
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.tween
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.background
-import androidx.compose.foundation.layout.*
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.BoxScope
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.fillMaxHeight
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
-import androidx.compose.runtime.*
+import androidx.compose.material3.LinearProgressIndicator
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
-import androidx.compose.ui.draw.scale
-import androidx.compose.ui.draw.shadow
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.layout.ContentScale
+import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
-import androidx.compose.material3.LinearProgressIndicator
import androidx.tv.material3.Border
import androidx.tv.material3.ClickableSurfaceDefaults
import androidx.tv.material3.MaterialTheme
import androidx.tv.material3.Surface
import androidx.tv.material3.Text
import coil3.compose.AsyncImage
-import com.streamvault.app.ui.theme.*
+import com.streamvault.app.R
+import com.streamvault.app.ui.theme.AccentAmber
+import com.streamvault.app.ui.theme.AccentCyan
+import com.streamvault.app.ui.theme.AccentRed
+import com.streamvault.app.ui.theme.CardBackground
+import com.streamvault.app.ui.theme.FocusBorder
+import com.streamvault.app.ui.theme.GradientOverlayBottom
+import com.streamvault.app.ui.theme.Primary
+import com.streamvault.app.ui.theme.SurfaceElevated
+import com.streamvault.app.ui.theme.SurfaceHighlight
+import com.streamvault.app.ui.theme.TextPrimary
+import com.streamvault.app.ui.theme.TextSecondary
+import com.streamvault.app.ui.theme.TextTertiary
import com.streamvault.domain.model.Channel
import com.streamvault.domain.model.Movie
import com.streamvault.domain.model.Series
-import androidx.compose.ui.res.stringResource
-import com.streamvault.app.R
-
-// ── Focusable Card Base ────────────────────────────────────────────
@Composable
fun FocusableCard(
@@ -52,21 +71,20 @@ fun FocusableCard(
) {
var isFocused by remember { mutableStateOf(false) }
- // In reorder mode, only the dragging item scales. Otherwise grid is static.
val scale by animateFloatAsState(
targetValue = if (isFocused) {
- if (isReorderMode && !isDragging) 1f else 1.1f // PREMIUM: 1.1x for better visibility
+ if (isReorderMode && !isDragging) 1f else 1.1f
} else {
if (isDragging) 1.1f else 1f
},
- animationSpec = tween(durationMillis = 200, easing = FastOutSlowInEasing), // PREMIUM: 200ms
- label = "scale"
+ animationSpec = tween(durationMillis = 200, easing = FastOutSlowInEasing),
+ label = "cardScale"
)
val shadowElevation by animateFloatAsState(
- targetValue = if (isDragging) 16f else if (isFocused) 8f else 0f, // PREMIUM: Down from 24dp to 8dp
+ targetValue = if (isDragging) 16f else if (isFocused) 8f else 0f,
animationSpec = tween(durationMillis = 200),
- label = "elevation"
+ label = "cardElevation"
)
Surface(
@@ -80,10 +98,10 @@ fun FocusableCard(
scaleY = scale
this.shadowElevation = shadowElevation
shape = RoundedCornerShape(12.dp)
- clip = false // PREMIUM: Allow focus border and shadow to show outside
+ clip = false
}
.onFocusChanged { isFocused = it.isFocused },
- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(12.dp)), // PREMIUM: 12dp
+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(12.dp)),
colors = ClickableSurfaceDefaults.colors(
containerColor = CardBackground,
focusedContainerColor = SurfaceHighlight
@@ -91,14 +109,14 @@ fun FocusableCard(
border = ClickableSurfaceDefaults.border(
border = Border(
border = BorderStroke(0.dp, Color.Transparent),
- shape = RoundedCornerShape(12.dp) // PREMIUM: 12dp
+ shape = RoundedCornerShape(12.dp)
),
focusedBorder = Border(
border = BorderStroke(
- width = if (isDragging) 4.dp else 3.dp, // PREMIUM: 3dp border
- color = if (isDragging) AccentAmber else FocusBorder // PREMIUM: FocusBorder (White)
+ width = if (isDragging) 4.dp else 3.dp,
+ color = if (isDragging) AccentAmber else FocusBorder
),
- shape = RoundedCornerShape(12.dp) // PREMIUM: 12dp
+ shape = RoundedCornerShape(12.dp)
)
)
) {
@@ -108,8 +126,6 @@ fun FocusableCard(
}
}
-// ── Channel Card (16:9 landscape tile) ────────────────────────────
-
@Composable
fun ChannelCard(
channel: Channel,
@@ -129,7 +145,6 @@ fun ChannelCard(
isReorderMode = isReorderMode,
isDragging = isDragging
) { isFocused ->
- // Background: logo or solid surface
if (!channel.logoUrl.isNullOrBlank() && !isLocked) {
AsyncImage(
model = channel.logoUrl,
@@ -141,7 +156,6 @@ fun ChannelCard(
)
}
- // Bottom gradient overlay
Box(
modifier = Modifier
.align(Alignment.BottomCenter)
@@ -154,7 +168,6 @@ fun ChannelCard(
)
)
- // Bottom content: channel name + EPG + progress
Column(
modifier = Modifier
.align(Alignment.BottomStart)
@@ -179,13 +192,18 @@ fun ChannelCard(
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
+
val now = System.currentTimeMillis()
val totalDuration = program.endTime - program.startTime
val elapsed = now - program.startTime
val progress = if (totalDuration > 0) elapsed.toFloat() / totalDuration else 0f
+
LinearProgressIndicator(
progress = { progress.coerceIn(0f, 1f) },
- modifier = Modifier.fillMaxWidth().height(2.dp).clip(RoundedCornerShape(1.dp)),
+ modifier = Modifier
+ .fillMaxWidth()
+ .height(2.dp)
+ .clip(RoundedCornerShape(1.dp)),
color = AccentCyan,
trackColor = SurfaceHighlight
)
@@ -193,61 +211,38 @@ fun ChannelCard(
}
}
- // Top-right badges
if (!isLocked) {
Row(
- modifier = Modifier.align(Alignment.TopEnd).padding(6.dp),
+ modifier = Modifier
+ .align(Alignment.TopEnd)
+ .padding(6.dp),
horizontalArrangement = Arrangement.spacedBy(4.dp),
verticalAlignment = Alignment.CenterVertically
) {
if (channel.isFavorite) {
- Box(
- modifier = Modifier
- .background(AccentAmber, RoundedCornerShape(4.dp))
- .padding(horizontal = 5.dp, vertical = 2.dp)
- ) {
- Text("★", style = MaterialTheme.typography.labelSmall, color = Color.Black)
- }
+ StatusBadge(label = "FAV", containerColor = AccentAmber, contentColor = Color.Black)
}
if (channel.errorCount > 0) {
- Box(
- modifier = Modifier
- .background(AccentRed, RoundedCornerShape(4.dp))
- .padding(horizontal = 5.dp, vertical = 2.dp)
- ) {
- Text("⚠️", style = MaterialTheme.typography.labelSmall, color = Color.White)
- }
+ StatusBadge(label = "ERR", containerColor = AccentRed)
}
if (channel.catchUpSupported) {
- Box(
- modifier = Modifier
- .background(Primary, RoundedCornerShape(4.dp))
- .padding(horizontal = 6.dp, vertical = 2.dp)
- ) {
- Text("📼", style = MaterialTheme.typography.labelSmall, color = Color.White)
- }
- }
- Box(
- modifier = Modifier
- .background(AccentRed, RoundedCornerShape(4.dp))
- .padding(horizontal = 6.dp, vertical = 2.dp)
- ) {
- Text(stringResource(R.string.card_live_badge), style = MaterialTheme.typography.labelSmall, color = Color.White)
+ StatusBadge(label = "CATCH UP", containerColor = Primary)
}
+ StatusBadge(
+ label = stringResource(R.string.card_live_badge),
+ containerColor = AccentRed
+ )
}
}
- // Lock overlay
if (isLocked) {
Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
- Text("🔒", style = MaterialTheme.typography.displayMedium)
+ StatusBadge(label = "LOCKED", containerColor = SurfaceHighlight)
}
}
}
}
-// ── Movie Card (16:9 landscape thumbnail) ─────────────────────────────────────────
-
@Composable
fun MovieCard(
movie: Movie,
@@ -263,35 +258,35 @@ fun MovieCard(
onClick = onClick,
onLongClick = onLongClick,
modifier = modifier,
- width = 160.dp, // PREMIUM: Vertical aspect ratio
+ width = 160.dp,
height = 240.dp,
isReorderMode = isReorderMode,
isDragging = isDragging
- ) { isFocused ->
- // Poster image
+ ) {
if (!movie.posterUrl.isNullOrBlank() && !isLocked) {
AsyncImage(
model = movie.posterUrl,
contentDescription = movie.name,
modifier = Modifier
.fillMaxSize()
- .clip(RoundedCornerShape(12.dp)) // PREMIUM: Clip poster to card shape
- .background(SurfaceElevated), // Background for non-standard posters
- contentScale = ContentScale.Fit // PREMIUM: Fits entire poster inside card
+ .clip(RoundedCornerShape(12.dp))
+ .background(SurfaceElevated),
+ contentScale = ContentScale.Fit
)
} else {
Box(
- modifier = Modifier.fillMaxSize().background(SurfaceElevated),
+ modifier = Modifier
+ .fillMaxSize()
+ .background(SurfaceElevated),
contentAlignment = Alignment.Center
) {
- Text(
- text = if (isLocked) "🔒" else "🎬",
- style = MaterialTheme.typography.displayMedium
+ StatusBadge(
+ label = if (isLocked) "LOCKED" else "MOVIE",
+ containerColor = SurfaceHighlight
)
}
}
- // Bottom gradient overlay - Higher for vertical text
Box(
modifier = Modifier
.align(Alignment.BottomCenter)
@@ -299,17 +294,16 @@ fun MovieCard(
.fillMaxHeight(0.6f)
.background(
Brush.verticalGradient(
- colors = listOf(Color.Transparent, Color.Black.copy(alpha = 0.85f)),
+ colors = listOf(Color.Transparent, Color.Black.copy(alpha = 0.85f))
)
)
)
- // Title + metadata at bottom
Column(
modifier = Modifier
.align(Alignment.BottomStart)
.fillMaxWidth()
- .padding(12.dp), // Increased padding
+ .padding(12.dp),
verticalArrangement = Arrangement.spacedBy(2.dp)
) {
Text(
@@ -319,6 +313,7 @@ fun MovieCard(
maxLines = 2,
overflow = TextOverflow.Ellipsis
)
+
if (!isLocked && movie.year != null) {
Text(
text = movie.year!!,
@@ -328,7 +323,6 @@ fun MovieCard(
}
}
- // Watch progress bar
if (watchProgress > 0f && !isLocked) {
LinearProgressIndicator(
progress = { watchProgress.coerceIn(0f, 1f) },
@@ -341,9 +335,7 @@ fun MovieCard(
)
}
- // Badges
if (!isLocked) {
- // Rating badge (Bottom Right above title area or overlap)
if (movie.rating > 0f) {
Box(
modifier = Modifier
@@ -353,31 +345,22 @@ fun MovieCard(
.padding(horizontal = 6.dp, vertical = 2.dp)
) {
Text(
- text = "⭐ ${String.format("%.1f", movie.rating)}",
+ text = "RTG ${String.format("%.1f", movie.rating)}",
style = MaterialTheme.typography.labelSmall,
color = AccentAmber
)
}
}
- // Favorite badge
if (movie.isFavorite) {
- Box(
- modifier = Modifier
- .align(Alignment.TopEnd)
- .padding(8.dp)
- .background(Color.Red.copy(alpha = 0.8f), RoundedCornerShape(4.dp))
- .padding(4.dp)
- ) {
- Text("❤", style = MaterialTheme.typography.labelSmall, color = Color.White)
+ Box(modifier = Modifier.align(Alignment.TopEnd).padding(8.dp)) {
+ StatusBadge(label = "FAV", containerColor = AccentRed)
}
}
}
}
}
-// ── Series Card (16:9 landscape thumbnail) ────────────────────────────────────────
-
@Composable
fun SeriesCard(
series: Series,
@@ -394,35 +377,35 @@ fun SeriesCard(
onClick = onClick,
onLongClick = onLongClick,
modifier = modifier,
- width = 160.dp, // PREMIUM: Vertical aspect ratio
+ width = 160.dp,
height = 240.dp,
isReorderMode = isReorderMode,
isDragging = isDragging
- ) { isFocused ->
- // Poster image
+ ) {
if (!series.posterUrl.isNullOrBlank() && !isLocked) {
AsyncImage(
model = series.posterUrl,
contentDescription = series.name,
modifier = Modifier
.fillMaxSize()
- .clip(RoundedCornerShape(12.dp)) // PREMIUM: Clip poster to card shape
+ .clip(RoundedCornerShape(12.dp))
.background(SurfaceElevated),
- contentScale = ContentScale.Fit // PREMIUM: Fits entire poster inside card
+ contentScale = ContentScale.Fit
)
} else {
Box(
- modifier = Modifier.fillMaxSize().background(SurfaceElevated),
+ modifier = Modifier
+ .fillMaxSize()
+ .background(SurfaceElevated),
contentAlignment = Alignment.Center
) {
- Text(
- text = if (isLocked) "🔒" else "📺",
- style = MaterialTheme.typography.displayMedium
+ StatusBadge(
+ label = if (isLocked) "LOCKED" else "SERIES",
+ containerColor = SurfaceHighlight
)
}
}
- // Bottom gradient overlay
Box(
modifier = Modifier
.align(Alignment.BottomCenter)
@@ -430,12 +413,11 @@ fun SeriesCard(
.fillMaxHeight(0.6f)
.background(
Brush.verticalGradient(
- colors = listOf(Color.Transparent, Color.Black.copy(alpha = 0.85f)),
+ colors = listOf(Color.Transparent, Color.Black.copy(alpha = 0.85f))
)
)
)
- // Title at bottom
Column(
modifier = Modifier
.align(Alignment.BottomStart)
@@ -460,7 +442,6 @@ fun SeriesCard(
}
}
- // Watch progress bar
if (watchProgress > 0f && !isLocked) {
LinearProgressIndicator(
progress = { watchProgress.coerceIn(0f, 1f) },
@@ -473,9 +454,7 @@ fun SeriesCard(
)
}
- // Badges
if (!isLocked) {
- // Rating badge
if (series.rating > 0f) {
Box(
modifier = Modifier
@@ -485,26 +464,37 @@ fun SeriesCard(
.padding(horizontal = 6.dp, vertical = 2.dp)
) {
Text(
- text = "⭐ ${String.format("%.1f", series.rating)}",
+ text = "RTG ${String.format("%.1f", series.rating)}",
style = MaterialTheme.typography.labelSmall,
color = AccentAmber
)
}
}
- // Favorite badge
if (series.isFavorite) {
- Box(
- modifier = Modifier
- .align(Alignment.TopEnd)
- .padding(8.dp)
- .background(Color.Red.copy(alpha = 0.8f), RoundedCornerShape(4.dp))
- .padding(4.dp)
- ) {
- Text("❤", style = MaterialTheme.typography.labelSmall, color = Color.White)
+ Box(modifier = Modifier.align(Alignment.TopEnd).padding(8.dp)) {
+ StatusBadge(label = "FAV", containerColor = AccentRed)
}
}
}
}
}
+@Composable
+private fun StatusBadge(
+ label: String,
+ containerColor: Color,
+ contentColor: Color = Color.White
+) {
+ Box(
+ modifier = Modifier
+ .background(containerColor, RoundedCornerShape(4.dp))
+ .padding(horizontal = 6.dp, vertical = 2.dp)
+ ) {
+ Text(
+ text = label,
+ style = MaterialTheme.typography.labelSmall,
+ color = contentColor
+ )
+ }
+}
diff --git a/app/src/main/java/com/streamvault/app/ui/components/TopNavBar.kt b/app/src/main/java/com/streamvault/app/ui/components/TopNavBar.kt
index d4553624..ec50fe37 100644
--- a/app/src/main/java/com/streamvault/app/ui/components/TopNavBar.kt
+++ b/app/src/main/java/com/streamvault/app/ui/components/TopNavBar.kt
@@ -1,26 +1,48 @@
package com.streamvault.app.ui.components
+import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.tween
-import androidx.compose.foundation.layout.*
+import androidx.compose.foundation.BorderStroke
+import androidx.compose.foundation.background
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.Spacer
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
-import androidx.compose.runtime.*
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusProperties
import androidx.compose.ui.focus.focusRequester
-import androidx.compose.ui.draw.scale
import androidx.compose.ui.focus.onFocusChanged
-import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
-import androidx.compose.ui.unit.dp
-import androidx.compose.foundation.BorderStroke
-import androidx.tv.material3.*
-import com.streamvault.app.navigation.Routes
-import com.streamvault.app.ui.theme.*
import androidx.compose.ui.res.stringResource
+import androidx.compose.ui.unit.dp
+import androidx.tv.material3.Border
+import androidx.tv.material3.ClickableSurfaceDefaults
+import androidx.tv.material3.MaterialTheme
+import androidx.tv.material3.Surface
+import androidx.tv.material3.Text
import com.streamvault.app.R
+import com.streamvault.app.navigation.Routes
+import com.streamvault.app.ui.theme.FocusBorder
+import com.streamvault.app.ui.theme.LocalSpacing
+import com.streamvault.app.ui.theme.Primary
+import com.streamvault.app.ui.theme.SurfaceElevated
+import com.streamvault.app.ui.theme.TextPrimary
+import com.streamvault.app.ui.theme.TextSecondary
+import com.streamvault.app.ui.theme.TextTertiary
@OptIn(androidx.compose.ui.ExperimentalComposeUiApi::class)
@Composable
@@ -42,29 +64,33 @@ fun TopNavBar(
Row(
modifier = modifier
.fillMaxWidth()
- .height(64.dp) // Premium height
- .padding(horizontal = LocalSpacing.current.safeHoriz) // Premium 48dp overscan
+ .height(82.dp)
+ .padding(horizontal = LocalSpacing.current.safeHoriz)
.focusProperties {
enter = {
val activeTabRoute = tabs.firstOrNull { it.route == currentRoute }?.route
- val activeRequester = focusRequesters[activeTabRoute]
- activeRequester ?: FocusRequester.Default
+ focusRequesters[activeTabRoute] ?: FocusRequester.Default
}
},
verticalAlignment = Alignment.CenterVertically,
- horizontalArrangement = Arrangement.spacedBy(LocalSpacing.current.lg) // Premium 32dp spacing
+ horizontalArrangement = Arrangement.SpaceBetween
) {
- // Logo / App Name
- Text(
- text = stringResource(id = R.string.app_name),
- style = MaterialTheme.typography.titleLarge,
- color = Primary,
- modifier = Modifier.padding(end = LocalSpacing.current.lg)
- )
+ Column {
+ Text(
+ text = stringResource(id = R.string.app_name),
+ style = MaterialTheme.typography.titleLarge,
+ color = TextPrimary
+ )
+ Text(
+ text = stringResource(id = R.string.nav_live_tv),
+ style = MaterialTheme.typography.labelSmall,
+ color = TextTertiary
+ )
+ }
- Row(
- horizontalArrangement = Arrangement.spacedBy(LocalSpacing.current.sm)
- ) {
+ Spacer(modifier = Modifier.width(LocalSpacing.current.md))
+
+ Row(horizontalArrangement = Arrangement.spacedBy(LocalSpacing.current.sm)) {
tabs.forEach { tab ->
val requester = focusRequesters.getOrPut(tab.route) { FocusRequester() }
NavTabButton(
@@ -92,21 +118,15 @@ private fun NavTabButton(
var isFocused by remember { mutableStateOf(false) }
val scale by animateFloatAsState(
- targetValue = if (isFocused) 1.03f else 1f, // Premium subtle scale
- animationSpec = tween(durationMillis = 200),
+ targetValue = if (isFocused) 1.02f else 1f,
+ animationSpec = tween(durationMillis = 180),
label = "tabScale"
)
- val backgroundColor = when {
- isSelected -> Primary.copy(alpha = 0.15f) // Cleaner selection tint
- isFocused -> SurfaceElevated
- else -> Color.Transparent
- }
-
val textColor = when {
isSelected -> Primary
- isFocused -> TextPrimary // High contrast white
- else -> TextSecondary // Muted inactive
+ isFocused -> TextPrimary
+ else -> TextSecondary
}
Surface(
@@ -117,28 +137,50 @@ private fun NavTabButton(
scaleY = scale
}
.onFocusChanged { isFocused = it.isFocused },
- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(12.dp)), // Premium 12dp
+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(12.dp)),
colors = ClickableSurfaceDefaults.colors(
- containerColor = backgroundColor,
+ containerColor = if (isSelected) Primary.copy(alpha = 0.16f) else SurfaceElevated,
focusedContainerColor = SurfaceElevated
),
border = ClickableSurfaceDefaults.border(
- border = Border.None,
+ border = Border(
+ border = BorderStroke(1.dp, SurfaceElevated),
+ shape = RoundedCornerShape(12.dp)
+ ),
focusedBorder = Border(
- border = BorderStroke(2.dp, FocusBorder), // Premium White Focus
+ border = BorderStroke(2.dp, FocusBorder),
shape = RoundedCornerShape(12.dp)
)
)
) {
- Text(
- text = text,
- style = MaterialTheme.typography.titleSmall, // 16sp, robust TV font
- color = textColor,
- modifier = Modifier.padding(
- horizontal = LocalSpacing.current.md,
- vertical = LocalSpacing.current.xs
+ Column(
+ modifier = Modifier.padding(horizontal = 22.dp, vertical = 10.dp),
+ horizontalAlignment = Alignment.CenterHorizontally,
+ verticalArrangement = Arrangement.spacedBy(3.dp)
+ ) {
+ Text(
+ text = text,
+ style = MaterialTheme.typography.titleSmall,
+ color = textColor
)
- )
+ AnimatedVisibility(visible = isSelected || isFocused) {
+ Box(
+ modifier = Modifier
+ .width(28.dp)
+ .height(3.dp),
+ ) {
+ Box(
+ modifier = Modifier
+ .fillMaxWidth()
+ .height(3.dp)
+ .background(
+ color = if (isSelected) Primary else FocusBorder,
+ shape = RoundedCornerShape(999.dp)
+ )
+ )
+ }
+ }
+ }
}
}
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 c4a30d0b..a7e77e6a 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
@@ -42,7 +42,7 @@ class EpgViewModel @Inject constructor(
val epgIds = channels.mapNotNull { it.epgChannelId }.distinct()
// Listen for EPG updates for all these channels
- epgRepository.getNowPlayingForChannels(epgIds).collect { programsDict ->
+ epgRepository.getNowPlayingForChannels(provider.id, epgIds).collect { programsDict ->
_uiState.update {
it.copy(
channels = channels.take(100), // Limit to 100 for now to avoid grid overload
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/favorites/FavoritesViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/favorites/FavoritesViewModel.kt
index 3e5ae8db..de42b571 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/favorites/FavoritesViewModel.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/favorites/FavoritesViewModel.kt
@@ -10,6 +10,7 @@ import com.streamvault.domain.repository.FavoriteRepository
import com.streamvault.domain.repository.MovieRepository
import com.streamvault.domain.repository.SeriesRepository
import dagger.hilt.android.lifecycle.HiltViewModel
+import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import javax.inject.Inject
@@ -22,6 +23,7 @@ data class FavoriteUiModel(
)
@HiltViewModel
+@OptIn(ExperimentalCoroutinesApi::class)
class FavoritesViewModel @Inject constructor(
private val favoriteRepository: FavoriteRepository,
private val channelRepository: ChannelRepository,
@@ -34,51 +36,55 @@ class FavoritesViewModel @Inject constructor(
init {
viewModelScope.launch {
- favoriteRepository.getFavorites(null).collect { favorites ->
- val uiModels = favorites.mapNotNull { fav ->
- try {
- when (fav.contentType) {
- ContentType.LIVE -> {
- val channel = channelRepository.getChannel(fav.contentId)
- if (channel != null) {
+ favoriteRepository.getFavorites(null)
+ .flatMapLatest { favorites ->
+ val channelIds = favorites.filter { it.contentType == ContentType.LIVE }.map { it.contentId }
+ val movieIds = favorites.filter { it.contentType == ContentType.MOVIE }.map { it.contentId }
+ val seriesIds = favorites.filter { it.contentType == ContentType.SERIES }.map { it.contentId }
+
+ combine(
+ if (channelIds.isEmpty()) flowOf(emptyList()) else channelRepository.getChannelsByIds(channelIds),
+ if (movieIds.isEmpty()) flowOf(emptyList()) else movieRepository.getMoviesByIds(movieIds),
+ if (seriesIds.isEmpty()) flowOf(emptyList()) else seriesRepository.getSeriesByIds(seriesIds)
+ ) { channels, movies, series ->
+ val channelsById = channels.associateBy { it.id }
+ val moviesById = movies.associateBy { it.id }
+ val seriesById = series.associateBy { it.id }
+
+ favorites.mapNotNull { favorite ->
+ when (favorite.contentType) {
+ ContentType.LIVE -> channelsById[favorite.contentId]?.let { channel ->
FavoriteUiModel(
- favorite = fav,
+ favorite = favorite,
title = channel.name,
subtitle = "Channel ${channel.number}",
streamUrl = channel.streamUrl
)
- } else null
- }
- ContentType.MOVIE -> {
- val movie = movieRepository.getMovie(fav.contentId)
- if (movie != null) {
+ }
+ ContentType.MOVIE -> moviesById[favorite.contentId]?.let { movie ->
FavoriteUiModel(
- favorite = fav,
+ favorite = favorite,
title = movie.name,
subtitle = "Movie",
streamUrl = movie.streamUrl
)
- } else null
- }
- ContentType.SERIES -> {
- val series = seriesRepository.getSeriesById(fav.contentId)
- if (series != null) {
+ }
+ ContentType.SERIES -> seriesById[favorite.contentId]?.let { seriesItem ->
FavoriteUiModel(
- favorite = fav,
- title = series.name,
+ favorite = favorite,
+ title = seriesItem.name,
subtitle = "Series",
streamUrl = "" // Series doesn't have a single stream URL
)
- } else null
+ }
+ else -> null
}
- else -> null // SERIES_EPISODE and future types not favoriteable
}
- } catch (e: Exception) {
- null
}
}
- _uiState.update { it.copy(favorites = uiModels, isLoading = false) }
- }
+ .collect { uiModels ->
+ _uiState.update { it.copy(favorites = uiModels, isLoading = false) }
+ }
}
viewModelScope.launch {
favoriteRepository.getGroups(ContentType.LIVE).collect { groups ->
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/home/HomeScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/home/HomeScreen.kt
index f2698f48..d90b9445 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/home/HomeScreen.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/home/HomeScreen.kt
@@ -13,6 +13,7 @@ import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.*
+import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import com.streamvault.app.ui.components.SearchInput
@@ -260,8 +261,61 @@ fun HomeScreen(
}
}
} else {
- val context = androidx.compose.ui.platform.LocalContext.current
-
+ val channelSearchFocusRequester = remember { FocusRequester() }
+ val categoryFocusRequesters = remember { mutableMapOf<Long, FocusRequester>() }
+ val channelFocusRequesters = remember { mutableMapOf<Long, FocusRequester>() }
+ var lastFocusedCategoryId by rememberSaveable { mutableStateOf<Long?>(null) }
+ var lastFocusedChannelId by rememberSaveable { mutableStateOf<Long?>(null) }
+ var shouldRestoreCategoryFocus by remember { mutableStateOf(false) }
+ var shouldRestoreChannelFocus by remember { mutableStateOf(false) }
+
+ LaunchedEffect(
+ uiState.showDialog,
+ showPinDialog,
+ uiState.showDeleteGroupDialog,
+ uiState.selectedCategoryForOptions
+ ) {
+ val modalClosed =
+ !uiState.showDialog &&
+ !showPinDialog &&
+ !uiState.showDeleteGroupDialog &&
+ uiState.selectedCategoryForOptions == null
+
+ if (!modalClosed) return@LaunchedEffect
+
+ val canRestoreChannel = lastFocusedChannelId != null &&
+ uiState.filteredChannels.any { it.id == lastFocusedChannelId }
+ val canRestoreCategory = lastFocusedCategoryId != null &&
+ uiState.categories.any { it.id == lastFocusedCategoryId }
+
+ shouldRestoreChannelFocus = canRestoreChannel
+ shouldRestoreCategoryFocus = !canRestoreChannel && canRestoreCategory
+ }
+
+ LaunchedEffect(shouldRestoreChannelFocus, uiState.filteredChannels) {
+ if (!shouldRestoreChannelFocus) return@LaunchedEffect
+ kotlinx.coroutines.delay(80)
+ val channelId = lastFocusedChannelId
+ val restored = channelId != null && runCatching {
+ channelFocusRequesters[channelId]?.requestFocus()
+ }.isSuccess
+ if (!restored) {
+ val fallbackId = uiState.filteredChannels.firstOrNull()?.id
+ fallbackId?.let { channelFocusRequesters[it]?.requestFocus() }
+ }
+ shouldRestoreChannelFocus = false
+ }
+
+ LaunchedEffect(shouldRestoreCategoryFocus, uiState.categories) {
+ if (!shouldRestoreCategoryFocus) return@LaunchedEffect
+ kotlinx.coroutines.delay(80)
+ val categoryId = lastFocusedCategoryId
+ if (categoryId != null) {
+ runCatching { categoryFocusRequesters[categoryId]?.requestFocus() }
+ }
+ shouldRestoreCategoryFocus = false
+ }
+
Row(modifier = Modifier.fillMaxSize()) {
// Sidebar - Categories
val categorySearchFocusRequester = remember { FocusRequester() }
@@ -360,11 +414,13 @@ fun HomeScreen(
key = { it.id }
) { category ->
val isLocked = (category.isAdult || category.isUserProtected) && uiState.parentalControlLevel == 1
+ val categoryFocusRequester = categoryFocusRequesters.getOrPut(category.id) { FocusRequester() }
CategoryItem(
category = category,
isSelected = category.id == uiState.selectedCategory?.id,
isLocked = isLocked,
+ focusRequester = categoryFocusRequester,
onClick = {
if (isLocked) {
pendingUnlockCategory = category
@@ -374,7 +430,18 @@ fun HomeScreen(
}
},
onLongClick = { viewModel.showCategoryOptions(category) },
- onJumpToSearch = { categorySearchFocusRequester.requestFocus() }
+ onJumpToSearch = { categorySearchFocusRequester.requestFocus() },
+ onJumpToContent = {
+ if (uiState.filteredChannels.isNotEmpty()) {
+ val preferredChannelId = lastFocusedChannelId
+ ?.takeIf { channelId -> uiState.filteredChannels.any { it.id == channelId } }
+ ?: uiState.filteredChannels.first().id
+ channelFocusRequesters[preferredChannelId]?.requestFocus()
+ } else {
+ channelSearchFocusRequester.requestFocus()
+ }
+ },
+ onFocused = { lastFocusedCategoryId = category.id }
)
}
}
@@ -404,6 +471,7 @@ fun HomeScreen(
onValueChange = { viewModel.updateChannelSearchQuery(it) },
placeholder = stringResource(R.string.home_search_channels),
onSearch = { focusManager.clearFocus() },
+ focusRequester = channelSearchFocusRequester,
modifier = Modifier.width(300.dp)
)
}
@@ -507,6 +575,7 @@ fun HomeScreen(
) { channel ->
val isLocked = (channel.isAdult || channel.isUserProtected || (uiState.selectedCategory?.isUserProtected ?: false)) && uiState.parentalControlLevel == 1
val isDraggingThis = draggingChannel == channel
+ val channelFocusRequester = channelFocusRequesters.getOrPut(channel.id) { FocusRequester() }
ChannelCard(
channel = channel,
@@ -536,6 +605,12 @@ fun HomeScreen(
},
modifier = Modifier
.aspectRatio(16f/9f)
+ .focusRequester(channelFocusRequester)
+ .onFocusChanged { focusState ->
+ if (focusState.isFocused) {
+ lastFocusedChannelId = channel.id
+ }
+ }
.onPreviewKeyEvent { event ->
if (uiState.isChannelReorderMode && isDraggingThis && event.nativeKeyEvent.action == android.view.KeyEvent.ACTION_DOWN) {
// Consume D-pad to move item instead of changing focus
@@ -634,9 +709,12 @@ private fun CategoryItem(
category: Category,
isSelected: Boolean,
isLocked: Boolean = false,
+ focusRequester: FocusRequester,
onClick: () -> Unit,
onLongClick: (() -> Unit)? = null,
- onJumpToSearch: () -> Unit
+ onJumpToSearch: () -> Unit,
+ onJumpToContent: () -> Unit,
+ onFocused: () -> Unit
) {
var isFocused by remember { mutableStateOf(false) }
@@ -646,13 +724,24 @@ private fun CategoryItem(
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 4.dp)
- .onFocusChanged { isFocused = it.isFocused }
+ .focusRequester(focusRequester)
+ .onFocusChanged {
+ isFocused = it.isFocused
+ if (it.isFocused) onFocused()
+ }
.onPreviewKeyEvent { event ->
if (event.nativeKeyEvent.action == android.view.KeyEvent.ACTION_DOWN) {
- if (event.nativeKeyEvent.keyCode == android.view.KeyEvent.KEYCODE_DPAD_LEFT) {
- onJumpToSearch()
- true
- } else false
+ when (event.nativeKeyEvent.keyCode) {
+ android.view.KeyEvent.KEYCODE_DPAD_LEFT -> {
+ onJumpToSearch()
+ true
+ }
+ android.view.KeyEvent.KEYCODE_DPAD_RIGHT -> {
+ onJumpToContent()
+ true
+ }
+ else -> false
+ }
} else false
},
shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(8.dp)),
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/home/HomeViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/home/HomeViewModel.kt
index e9154963..7b077641 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/home/HomeViewModel.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/home/HomeViewModel.kt
@@ -15,12 +15,14 @@ import com.streamvault.domain.repository.FavoriteRepository
import com.streamvault.domain.repository.ProviderRepository
import com.streamvault.domain.usecase.GetCustomCategories
import dagger.hilt.android.lifecycle.HiltViewModel
+import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
+@OptIn(ExperimentalCoroutinesApi::class)
class HomeViewModel @Inject constructor(
private val providerRepository: ProviderRepository,
private val channelRepository: ChannelRepository,
@@ -141,7 +143,7 @@ class HomeViewModel @Inject constructor(
fun selectCategory(category: Category) {
if (_uiState.value.selectedCategory?.id == category.id) return
- parentalControlManager.clearUnlockedCategories()
+ parentalControlManager.clearUnlockedCategories(_uiState.value.provider?.id)
_uiState.update { it.copy(selectedCategory = category, isLoading = true) }
loadChannelsForCategory(category)
}
@@ -194,11 +196,12 @@ class HomeViewModel @Inject constructor(
private fun fetchEpgForChannels(channels: List<Channel>) {
epgJob?.cancel()
+ val providerId = _uiState.value.provider?.id ?: return
val epgIds = channels.mapNotNull { it.epgChannelId }.distinct()
epgJob = viewModelScope.launch {
val programMap = if (epgIds.isNotEmpty()) {
- epgRepository.getNowPlayingForChannels(epgIds).firstOrNull() ?: emptyMap()
+ epgRepository.getNowPlayingForChannels(providerId, epgIds).firstOrNull() ?: emptyMap()
} else {
emptyMap()
}
@@ -349,7 +352,7 @@ class HomeViewModel @Inject constructor(
val provider = _uiState.value.provider ?: return
viewModelScope.launch {
_uiState.update { it.copy(isLoading = true) }
- providerRepository.refreshProviderData(provider.id)
+ providerRepository.refreshProviderData(provider.id, force = true)
_uiState.update { it.copy(isLoading = false) }
}
}
@@ -367,12 +370,12 @@ class HomeViewModel @Inject constructor(
}
suspend fun verifyPin(pin: String): Boolean {
- val storedPin = preferencesRepository.parentalPin.firstOrNull() ?: "0000"
- return pin == storedPin
+ return preferencesRepository.verifyParentalPin(pin)
}
fun unlockCategory(category: Category) {
- parentalControlManager.unlockCategory(category.id)
+ val providerId = _uiState.value.provider?.id ?: return
+ parentalControlManager.unlockCategory(providerId, category.id)
}
fun setDefaultCategory(category: Category) {
@@ -383,9 +386,10 @@ class HomeViewModel @Inject constructor(
}
fun toggleCategoryLock(category: Category) {
+ val providerId = _uiState.value.provider?.id ?: return
viewModelScope.launch {
val newStatus = !category.isUserProtected
- categoryRepository.setCategoryProtection(category.id, newStatus)
+ categoryRepository.setCategoryProtection(providerId, category.id, category.type, newStatus)
val msg = if (newStatus) "Locked '${category.name}'" else "Unlocked '${category.name}'"
_uiState.update { it.copy(userMessage = msg) }
}
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 0f72446e..26dbf491 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
@@ -121,7 +121,7 @@ class MoviesViewModel @Inject constructor(
}
suspend fun verifyPin(pin: String): Boolean {
- return preferencesRepository.parentalPin.first() == pin
+ return preferencesRepository.verifyParentalPin(pin)
}
fun onShowDialog(movie: Movie) {
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/multiview/MultiViewPlannerDialog.kt b/app/src/main/java/com/streamvault/app/ui/screens/multiview/MultiViewPlannerDialog.kt
index 30e721ae..8631cb9a 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/multiview/MultiViewPlannerDialog.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/multiview/MultiViewPlannerDialog.kt
@@ -127,8 +127,8 @@ fun MultiViewPlannerDialog(
.weight(1f)
.then(if (slotIndex == 0) Modifier.focusRequester(firstSlotFocusRequester) else Modifier),
onSlotClick = {
- if (stillPicking && pendingChannel != null) {
- viewModel.assignChannelToSlot(slotIndex, pendingChannel)
+ if (stillPicking) {
+ viewModel.assignChannelToSlot(slotIndex, pendingChannel!!)
channelPlaced = true // stay open
}
},
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 3f93a8ed..35fc55e4 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,33 +1,46 @@
package com.streamvault.app.ui.screens.multiview
import android.view.View
+import androidx.activity.compose.BackHandler
import androidx.annotation.OptIn
-import androidx.compose.ui.text.style.TextAlign
-import androidx.compose.ui.unit.dp
-import androidx.compose.ui.unit.sp
-import androidx.compose.ui.viewinterop.AndroidView
-import androidx.hilt.navigation.compose.hiltViewModel
-import androidx.media3.common.util.UnstableApi
-import androidx.media3.ui.PlayerView
-import androidx.media3.ui.AspectRatioFrameLayout
-import com.streamvault.app.R
-import com.streamvault.app.ui.theme.*
-import androidx.tv.material3.*
-import androidx.compose.runtime.*
-import androidx.compose.ui.*
-import androidx.compose.ui.Modifier
-import androidx.compose.ui.graphics.Color
-import androidx.compose.foundation.layout.*
import androidx.compose.foundation.background
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.fillMaxHeight
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Text
-import androidx.compose.ui.focus.FocusRequester
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.collectAsState
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.remember
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.focus.onFocusChanged
+import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
-import androidx.compose.ui.res.stringResource
+import androidx.compose.ui.unit.dp
+import androidx.compose.ui.unit.sp
+import androidx.compose.ui.viewinterop.AndroidView
+import androidx.hilt.navigation.compose.hiltViewModel
+import androidx.media3.common.util.UnstableApi
+import androidx.media3.ui.AspectRatioFrameLayout
+import androidx.media3.ui.PlayerView
+import androidx.tv.material3.Border
+import androidx.tv.material3.ClickableSurfaceDefaults
+import androidx.tv.material3.Surface
+import com.streamvault.app.R
+import com.streamvault.app.ui.theme.Primary
@Composable
fun MultiViewScreen(
@@ -37,13 +50,16 @@ fun MultiViewScreen(
val uiState by viewModel.uiState.collectAsState()
val firstSlotFocusRequester = remember { androidx.compose.ui.focus.FocusRequester() }
+ BackHandler(onBack = onBack)
+
LaunchedEffect(Unit) {
viewModel.initSlots()
try {
- // Force focus on first slot after a tiny delay for inflation
kotlinx.coroutines.delay(100)
firstSlotFocusRequester.requestFocus()
- } catch (e: Exception) {}
+ } catch (_: Exception) {
+ // No-op: focus request can fail during composition transitions.
+ }
}
Box(
@@ -52,13 +68,15 @@ fun MultiViewScreen(
.background(Color.Black)
) {
Column(modifier = Modifier.fillMaxSize()) {
- // Row 1
Row(modifier = Modifier.weight(1f)) {
PlayerCell(
slot = uiState.slots.getOrNull(0),
isFocused = uiState.focusedSlotIndex == 0,
showSelectionBorder = uiState.showSelectionBorder,
- modifier = Modifier.weight(1f).fillMaxHeight().focusRequester(firstSlotFocusRequester),
+ modifier = Modifier
+ .weight(1f)
+ .fillMaxHeight()
+ .focusRequester(firstSlotFocusRequester),
onFocused = { viewModel.setFocus(0) }
)
PlayerCell(
@@ -69,7 +87,6 @@ fun MultiViewScreen(
onFocused = { viewModel.setFocus(1) }
)
}
- // Row 2
Row(modifier = Modifier.weight(1f)) {
PlayerCell(
slot = uiState.slots.getOrNull(2),
@@ -88,11 +105,10 @@ fun MultiViewScreen(
}
}
- // Focused slot label at bottom center
val focused = uiState.slots.getOrNull(uiState.focusedSlotIndex)
if (focused != null && focused.title.isNotBlank()) {
Text(
- text = "▶ ${focused.title}",
+ text = "Focused: ${focused.title}",
color = Color(0xFF4CAF50),
fontSize = 12.sp,
fontWeight = FontWeight.Bold,
@@ -116,130 +132,125 @@ private fun PlayerCell(
onFocused: () -> Unit
) {
val showBorder = isFocused && showSelectionBorder
-
- Surface(
- onClick = { /* Could open full screen? */ },
- modifier = modifier
- .padding(2.dp)
- .onFocusChanged { if (it.isFocused) onFocused() },
- scale = ClickableSurfaceDefaults.scale(focusedScale = 1.02f),
- border = ClickableSurfaceDefaults.border(
- border = Border(
- border = androidx.compose.foundation.BorderStroke(
- width = if (showBorder) 4.dp else 0.dp,
- color = if (showBorder) Color.White else Color.Transparent
- )
- ),
- focusedBorder = Border.None,
- pressedBorder = Border.None
- ),
- colors = ClickableSurfaceDefaults.colors(
- containerColor = Color(0xFF111111),
- contentColor = Color.White,
- focusedContainerColor = Color(0xFF111111)
+
+ Surface(
+ onClick = { },
+ modifier = modifier
+ .padding(2.dp)
+ .onFocusChanged { if (it.isFocused) onFocused() },
+ scale = ClickableSurfaceDefaults.scale(focusedScale = 1.02f),
+ border = ClickableSurfaceDefaults.border(
+ border = Border(
+ border = androidx.compose.foundation.BorderStroke(
+ width = if (showBorder) 4.dp else 0.dp,
+ color = if (showBorder) Color.White else Color.Transparent
+ )
),
- shape = ClickableSurfaceDefaults.shape(androidx.compose.foundation.shape.RoundedCornerShape(4.dp))
- ) {
+ focusedBorder = Border.None,
+ pressedBorder = Border.None
+ ),
+ colors = ClickableSurfaceDefaults.colors(
+ containerColor = Color(0xFF111111),
+ contentColor = Color.White,
+ focusedContainerColor = Color(0xFF111111)
+ ),
+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(4.dp))
+ ) {
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.Center
) {
- when {
- slot == null || slot.isEmpty -> {
- Column(horizontalAlignment = Alignment.CenterHorizontally) {
- Text("+", color = Color(0xFF555555), fontSize = 32.sp)
- Text(
- text = stringResource(R.string.multiview_empty_slot),
- color = Color(0xFF555555),
- fontSize = 12.sp
- )
+ when {
+ slot == null || slot.isEmpty -> {
+ Column(horizontalAlignment = Alignment.CenterHorizontally) {
+ Text("+", color = Color(0xFF555555), fontSize = 32.sp)
+ Text(
+ text = androidx.compose.ui.res.stringResource(R.string.multiview_empty_slot),
+ color = Color(0xFF555555),
+ fontSize = 12.sp
+ )
+ }
}
- }
- slot.isLoading -> {
- CircularProgressIndicator(
- color = Color(0xFF4CAF50),
- modifier = Modifier.size(32.dp)
- )
- }
- slot.hasError -> {
- Column(horizontalAlignment = Alignment.CenterHorizontally) {
- Text("⚠", color = Color(0xFFFF5252), fontSize = 24.sp)
- Text(
- text = stringResource(R.string.multiview_stream_error),
- color = Color(0xFFFF5252),
- fontSize = 11.sp,
- textAlign = TextAlign.Center
+
+ slot.isLoading -> {
+ CircularProgressIndicator(
+ color = Color(0xFF4CAF50),
+ modifier = Modifier.size(32.dp)
)
}
- }
- else -> {
- // ✅ Attach ExoPlayer to a Media3 PlayerView — this is what actually renders video
- val engine = slot.playerEngine
- if (engine != null) {
- val exoPlayer = engine.getPlayerView()
- if (exoPlayer is androidx.media3.common.Player) {
- AndroidView(
- factory = { ctx ->
- PlayerView(ctx).apply {
- player = exoPlayer
- useController = false
- resizeMode = AspectRatioFrameLayout.RESIZE_MODE_FILL
- // CRITICAL: Ensure view doesn't steal focus
- isFocusable = false
- isFocusableInTouchMode = false
- importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_NO
- }
- },
- update = { view ->
- if (view.player != exoPlayer) {
- view.player = exoPlayer
- }
- },
- modifier = Modifier.fillMaxSize()
+
+ slot.hasError -> {
+ Column(horizontalAlignment = Alignment.CenterHorizontally) {
+ Text("!", color = Color(0xFFFF5252), fontSize = 24.sp, fontWeight = FontWeight.Bold)
+ Text(
+ text = androidx.compose.ui.res.stringResource(R.string.multiview_stream_error),
+ color = Color(0xFFFF5252),
+ fontSize = 11.sp,
+ textAlign = TextAlign.Center
)
}
}
+ else -> {
+ val engine = slot.playerEngine
+ if (engine != null) {
+ val exoPlayer = engine.getPlayerView()
+ if (exoPlayer is androidx.media3.common.Player) {
+ AndroidView(
+ factory = { ctx ->
+ PlayerView(ctx).apply {
+ player = exoPlayer
+ useController = false
+ resizeMode = AspectRatioFrameLayout.RESIZE_MODE_FILL
+ isFocusable = false
+ isFocusableInTouchMode = false
+ importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_NO
+ }
+ },
+ update = { view ->
+ if (view.player != exoPlayer) {
+ view.player = exoPlayer
+ }
+ },
+ modifier = Modifier.fillMaxSize()
+ )
+ }
+ }
-
- // Speaker icon overlay (only when focused and has channel)
- if (isFocused && !slot.isEmpty) {
- Box(
- modifier = Modifier
- .align(Alignment.TopEnd)
- .padding(12.dp)
- .background(Color.Black.copy(alpha = 0.6f), RoundedCornerShape(8.dp))
- .padding(horizontal = 8.dp, vertical = 6.dp)
- ) {
- Row(verticalAlignment = Alignment.CenterVertically) {
+ if (isFocused && !slot.isEmpty) {
+ Box(
+ modifier = Modifier
+ .align(Alignment.TopEnd)
+ .padding(12.dp)
+ .background(Color.Black.copy(alpha = 0.6f), RoundedCornerShape(8.dp))
+ .padding(horizontal = 8.dp, vertical = 6.dp)
+ ) {
Text(
- text = "🔊",
+ text = "AUDIO",
color = Primary,
- fontSize = 16.sp,
+ fontSize = 12.sp,
fontWeight = FontWeight.Bold
)
}
}
- }
- // Title overlay at bottom
- Box(
- modifier = Modifier
- .fillMaxWidth()
- .align(Alignment.BottomCenter)
- .background(Color.Black.copy(alpha = 0.5f))
- .padding(4.dp)
- ) {
- Text(
- text = slot.title,
- color = Color.White,
- fontSize = 10.sp,
- maxLines = 1,
- overflow = TextOverflow.Ellipsis
- )
+ Box(
+ modifier = Modifier
+ .fillMaxWidth()
+ .align(Alignment.BottomCenter)
+ .background(Color.Black.copy(alpha = 0.5f))
+ .padding(4.dp)
+ ) {
+ Text(
+ text = slot.title,
+ color = Color.White,
+ fontSize = 10.sp,
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis
+ )
+ }
}
}
}
}
}
-}
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/EpgOverlay.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/EpgOverlay.kt
deleted file mode 100644
index 962e5e34..00000000
--- a/app/src/main/java/com/streamvault/app/ui/screens/player/EpgOverlay.kt
+++ /dev/null
@@ -1,162 +0,0 @@
-package com.streamvault.app.ui.screens.player
-
-import androidx.compose.animation.*
-import androidx.compose.foundation.background
-import androidx.compose.foundation.layout.*
-import androidx.compose.foundation.shape.RoundedCornerShape
-import androidx.compose.material3.LinearProgressIndicator
-import androidx.compose.runtime.Composable
-import androidx.compose.ui.Alignment
-import androidx.compose.ui.Modifier
-import androidx.compose.ui.graphics.Brush
-import androidx.compose.ui.graphics.Color
-import androidx.compose.ui.res.stringResource
-import androidx.compose.ui.text.font.FontWeight
-import androidx.compose.ui.text.style.TextOverflow
-import androidx.compose.ui.unit.dp
-import androidx.tv.material3.MaterialTheme
-import androidx.tv.material3.Text
-import com.streamvault.app.R
-import com.streamvault.app.ui.theme.Primary
-import com.streamvault.domain.model.Channel
-import com.streamvault.domain.model.Program
-import java.text.SimpleDateFormat
-import java.util.*
-
-@Composable
-fun EpgOverlay(
- isVisible: Boolean,
- currentChannel: Channel?,
- displayChannelNumber: Int = 0,
- currentProgram: Program?,
- nextProgram: Program?,
- modifier: Modifier = Modifier
-) {
- val timeFormat = SimpleDateFormat("HH:mm", Locale.getDefault())
-
- AnimatedVisibility(
- visible = isVisible,
- enter = fadeIn() + slideInHorizontally(initialOffsetX = { it / 2 }),
- exit = fadeOut() + slideOutHorizontally(targetOffsetX = { it / 2 }),
- modifier = modifier.fillMaxSize()
- ) {
- Box(
- modifier = Modifier
- .fillMaxSize()
- .background(
- Brush.horizontalGradient(
- colors = listOf(Color.Transparent, Color.Black.copy(alpha = 0.9f)),
- startX = 0f,
- endX = 1000f
- )
- ),
- contentAlignment = Alignment.CenterEnd
- ) {
- Column(
- modifier = Modifier
- .fillMaxHeight()
- .width(400.dp)
- .padding(32.dp),
- verticalArrangement = Arrangement.Center
- ) {
- // Channel Info Header
- if (currentChannel != null) {
- Text(
- text = "$displayChannelNumber. ${currentChannel.name}",
- style = MaterialTheme.typography.displaySmall,
- color = Primary,
- fontWeight = FontWeight.Bold,
- maxLines = 1,
- overflow = TextOverflow.Ellipsis
- )
- Spacer(modifier = Modifier.height(32.dp))
- }
-
- // Now Playing
- Text(
- text = stringResource(R.string.epg_now_playing),
- style = MaterialTheme.typography.labelSmall,
- color = Primary,
- fontWeight = FontWeight.Bold
- )
- Spacer(modifier = Modifier.height(8.dp))
- if (currentProgram != null) {
- Text(
- text = currentProgram.title,
- style = MaterialTheme.typography.headlineMedium,
- color = Color.White,
- fontWeight = FontWeight.Bold,
- maxLines = 2,
- overflow = TextOverflow.Ellipsis
- )
- Spacer(modifier = Modifier.height(8.dp))
- Text(
- text = "${timeFormat.format(Date(currentProgram.startTime))} - ${timeFormat.format(Date(currentProgram.endTime))}",
- style = MaterialTheme.typography.bodyMedium,
- color = Color.White.copy(alpha = 0.7f)
- )
-
- if (!currentProgram.description.isNullOrEmpty()) {
- Spacer(modifier = Modifier.height(16.dp))
- Text(
- text = currentProgram.description!!,
- style = MaterialTheme.typography.bodyMedium,
- color = Color.White.copy(alpha = 0.6f),
- maxLines = 4,
- overflow = TextOverflow.Ellipsis
- )
- }
-
- Spacer(modifier = Modifier.height(16.dp))
-
- val now = System.currentTimeMillis()
- val start = currentProgram.startTime
- val end = currentProgram.endTime
- if (start in 1..<end) {
- val progress = (now - start).toFloat() / (end - start)
- LinearProgressIndicator(
- progress = { progress.coerceIn(0f, 1f) },
- modifier = Modifier
- .fillMaxWidth()
- .height(4.dp),
- color = Primary,
- trackColor = Color.White.copy(alpha = 0.2f)
- )
- }
- } else {
- Text(
- text = stringResource(R.string.epg_no_data),
- style = MaterialTheme.typography.headlineMedium,
- color = Color.White.copy(alpha = 0.5f)
- )
- }
-
- Spacer(modifier = Modifier.height(48.dp))
-
- // Next Up
- if (nextProgram != null) {
- Text(
- text = stringResource(R.string.epg_up_next),
- style = MaterialTheme.typography.labelSmall,
- color = Color.White.copy(alpha = 0.5f),
- fontWeight = FontWeight.Bold
- )
- Spacer(modifier = Modifier.height(8.dp))
- Text(
- text = nextProgram.title,
- style = MaterialTheme.typography.titleLarge,
- color = Color.White.copy(alpha = 0.9f),
- maxLines = 2,
- overflow = TextOverflow.Ellipsis
- )
- Spacer(modifier = Modifier.height(4.dp))
- Text(
- text = "${timeFormat.format(Date(nextProgram.startTime))} - ${timeFormat.format(Date(nextProgram.endTime))}",
- style = MaterialTheme.typography.bodySmall,
- color = Color.White.copy(alpha = 0.5f)
- )
- }
- }
- }
- }
-}
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 ce4799ef..28fd5d1c 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
@@ -6,6 +6,7 @@ import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.*
+import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
@@ -54,8 +55,12 @@ import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.clickable
import androidx.compose.material3.Slider
import androidx.compose.material3.SliderDefaults
+import androidx.compose.material3.CircularProgressIndicator
import com.streamvault.app.ui.components.dialogs.ProgramHistoryDialog
import androidx.compose.ui.res.stringResource
+import androidx.lifecycle.Lifecycle
+import androidx.lifecycle.LifecycleEventObserver
+import androidx.lifecycle.compose.LocalLifecycleOwner
import com.streamvault.app.R
import com.streamvault.app.ui.screens.multiview.MultiViewViewModel
import com.streamvault.app.ui.screens.multiview.MultiViewPlannerDialog
@@ -98,6 +103,7 @@ fun PlayerScreen(
val displayChannelNumber by viewModel.displayChannelNumber.collectAsState()
val upcomingPrograms by viewModel.upcomingPrograms.collectAsState()
val showChannelInfoOverlay by viewModel.showChannelInfoOverlay.collectAsState()
+ val numericChannelInput by viewModel.numericChannelInput.collectAsState()
val availableAudioTracks by viewModel.availableAudioTracks.collectAsState()
val availableSubtitleTracks by viewModel.availableSubtitleTracks.collectAsState()
@@ -114,15 +120,34 @@ fun PlayerScreen(
val focusRequester = remember { FocusRequester() }
val channelListFocusRequester = remember { FocusRequester() }
+ val epgFocusRequester = remember { FocusRequester() }
val playButtonFocusRequester = remember { FocusRequester() }
val channelInfoFocusRequester = remember { FocusRequester() } // NEW
+ var lastFocusedChannelListItemId by rememberSaveable { mutableStateOf<Long?>(null) }
+ var lastFocusedEpgProgramToken by rememberSaveable { mutableStateOf<Long?>(null) }
val layoutDirection = LocalLayoutDirection.current
val isRtl = layoutDirection == LayoutDirection.Rtl
+ val lifecycleOwner = LocalLifecycleOwner.current
LaunchedEffect(Unit) {
focusRequester.requestFocus()
}
+ DisposableEffect(lifecycleOwner) {
+ val observer = LifecycleEventObserver { _, event ->
+ when (event) {
+ Lifecycle.Event.ON_START -> viewModel.onAppForegrounded()
+ Lifecycle.Event.ON_STOP -> viewModel.onAppBackgrounded()
+ else -> Unit
+ }
+ }
+ lifecycleOwner.lifecycle.addObserver(observer)
+ onDispose {
+ lifecycleOwner.lifecycle.removeObserver(observer)
+ viewModel.onPlayerScreenDisposed()
+ }
+ }
+
// Consolidated focus management for all overlays
val anyOverlayVisible = showChannelListOverlay || showEpgOverlay || showChannelInfoOverlay || showTrackSelection != null || showProgramHistory || showSplitDialog || showZapOverlay || showDiagnostics
@@ -133,6 +158,7 @@ fun PlayerScreen(
try {
when {
showChannelListOverlay -> channelListFocusRequester.requestFocus()
+ showEpgOverlay -> epgFocusRequester.requestFocus()
showChannelInfoOverlay -> channelInfoFocusRequester.requestFocus()
// EPG and Dialogs usually handle their own initial focus or use their own re-composition logic
}
@@ -207,7 +233,9 @@ fun PlayerScreen(
if (event.nativeKeyEvent.action == KeyEvent.ACTION_DOWN) {
when (event.nativeKeyEvent.keyCode) {
KeyEvent.KEYCODE_DPAD_CENTER, KeyEvent.KEYCODE_ENTER -> {
- if (contentType == "LIVE") {
+ if (contentType == "LIVE" && viewModel.hasPendingNumericChannelInput()) {
+ viewModel.commitNumericChannelInput()
+ } else if (contentType == "LIVE") {
if (showChannelInfoOverlay) viewModel.closeChannelInfoOverlay()
else viewModel.openChannelInfoOverlay()
} else {
@@ -238,32 +266,49 @@ fun PlayerScreen(
}
}
KeyEvent.KEYCODE_DPAD_UP -> {
- if (!showChannelListOverlay && !showEpgOverlay) {
+ if (showChannelListOverlay || showEpgOverlay) return@onKeyEvent false
+
+ if (contentType == "LIVE") {
viewModel.playNext()
- true
} else {
- // Let the overlay LazyColumn handle this event
- false
+ viewModel.toggleControls()
}
+ true
}
KeyEvent.KEYCODE_DPAD_DOWN -> {
- if (!showChannelListOverlay && !showEpgOverlay) {
+ if (showChannelListOverlay || showEpgOverlay) return@onKeyEvent false
+
+ if (contentType == "LIVE") {
viewModel.playPrevious()
- true
} else {
- // Let the overlay LazyColumn handle this event
- false
+ viewModel.toggleControls()
}
+ true
}
KeyEvent.KEYCODE_BACK -> {
- if (showChannelInfoOverlay) {
+ if (viewModel.hasPendingNumericChannelInput()) {
+ viewModel.clearNumericChannelInput()
+ true
+ } else if (showProgramHistory) {
+ showProgramHistory = false
+ true
+ } else if (showSplitDialog) {
+ showSplitDialog = false
+ true
+ } else if (showTrackSelection != null) {
+ showTrackSelection = null
+ true
+ } else if (showDiagnostics) {
+ viewModel.toggleDiagnostics()
+ true
+ } else if (showChannelInfoOverlay) {
viewModel.closeChannelInfoOverlay()
true
} else if (showChannelListOverlay || showEpgOverlay) {
viewModel.closeOverlays()
true
- } else if (showTrackSelection != null) {
- showTrackSelection = null
+ } else if (showControls) {
+ viewModel.toggleControls()
true
} else {
onBack()
@@ -275,16 +320,58 @@ fun PlayerScreen(
true
}
KeyEvent.KEYCODE_CHANNEL_UP, KeyEvent.KEYCODE_DPAD_UP_RIGHT -> {
- viewModel.playNext()
- true
+ if (contentType == "LIVE") {
+ viewModel.playNext()
+ true
+ } else {
+ false
+ }
}
KeyEvent.KEYCODE_CHANNEL_DOWN, KeyEvent.KEYCODE_DPAD_DOWN_LEFT -> {
- viewModel.playPrevious()
- true
+ if (contentType == "LIVE") {
+ viewModel.playPrevious()
+ true
+ } else {
+ false
+ }
+ }
+ KeyEvent.KEYCODE_MEDIA_PREVIOUS -> {
+ if (contentType == "LIVE") {
+ viewModel.zapToLastChannel()
+ true
+ } else {
+ false
+ }
+ }
+ KeyEvent.KEYCODE_GUIDE -> {
+ if (contentType == "LIVE") {
+ viewModel.openEpgOverlay()
+ true
+ } else {
+ false
+ }
+ }
+ KeyEvent.KEYCODE_INFO -> {
+ if (contentType == "LIVE") {
+ if (showChannelInfoOverlay) viewModel.closeChannelInfoOverlay()
+ else viewModel.openChannelInfoOverlay()
+ } else {
+ viewModel.toggleControls()
+ }
+ true
+ }
+ KeyEvent.KEYCODE_MENU -> {
+ viewModel.toggleControls()
+ true
}
- KeyEvent.KEYCODE_MEDIA_PREVIOUS, KeyEvent.KEYCODE_0 -> {
- viewModel.zapToLastChannel()
- true
+ in KeyEvent.KEYCODE_0..KeyEvent.KEYCODE_9 -> {
+ if (contentType == "LIVE" && !showChannelListOverlay && !showEpgOverlay && !showChannelInfoOverlay) {
+ val digit = event.nativeKeyEvent.keyCode - KeyEvent.KEYCODE_0
+ viewModel.inputNumericChannelDigit(digit)
+ true
+ } else {
+ false
+ }
}
else -> false
}
@@ -301,7 +388,7 @@ fun PlayerScreen(
androidx.media3.ui.PlayerView(context).apply {
this.player = player
useController = false
- setShowBuffering(androidx.media3.ui.PlayerView.SHOW_BUFFERING_WHEN_PLAYING)
+ setShowBuffering(androidx.media3.ui.PlayerView.SHOW_BUFFERING_NEVER)
}
},
update = { playerView ->
@@ -318,14 +405,29 @@ fun PlayerScreen(
// Buffering indicator
if (playbackState == PlaybackState.BUFFERING) {
Box(
- modifier = Modifier.fillMaxSize(),
- contentAlignment = Alignment.Center
+ modifier = Modifier
+ .fillMaxSize()
+ .padding(top = 64.dp),
+ contentAlignment = Alignment.TopCenter
) {
- Text(
- text = stringResource(R.string.player_buffering),
- style = MaterialTheme.typography.bodyLarge,
- color = Color.White
- )
+ Row(
+ modifier = Modifier
+ .background(Color.Black.copy(alpha = 0.62f), RoundedCornerShape(12.dp))
+ .padding(horizontal = 16.dp, vertical = 10.dp),
+ horizontalArrangement = Arrangement.spacedBy(10.dp),
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ CircularProgressIndicator(
+ color = Primary,
+ strokeWidth = 2.dp,
+ modifier = Modifier.size(18.dp)
+ )
+ Text(
+ text = stringResource(R.string.player_buffering),
+ style = MaterialTheme.typography.bodyMedium,
+ color = Color.White
+ )
+ }
}
}
@@ -337,7 +439,7 @@ fun PlayerScreen(
) {
Column(horizontalAlignment = Alignment.CenterHorizontally) {
Text(
- text = "⚠️ " + stringResource(R.string.player_error_title),
+ text = stringResource(R.string.player_error_title),
style = MaterialTheme.typography.titleMedium,
color = ErrorColor
)
@@ -459,7 +561,7 @@ fun PlayerScreen(
)
) {
Text(
- text = "✕ " + stringResource(R.string.player_close),
+ text = stringResource(R.string.player_close),
color = Color.White,
modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp)
)
@@ -507,21 +609,20 @@ fun PlayerScreen(
// Track selection buttons shifted here for Live
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
if (currentChannel?.catchUpSupported == true) {
- QuickSettingsButton("🔄 " + stringResource(R.string.player_restart)) { viewModel.restartCurrentProgram() }
- QuickSettingsButton("📼 " + stringResource(R.string.player_archive)) { showProgramHistory = true }
+ QuickSettingsButton(stringResource(R.string.player_restart)) { viewModel.restartCurrentProgram() }
+ QuickSettingsButton(stringResource(R.string.player_archive)) { showProgramHistory = true }
}
- QuickSettingsButton("📺 ${aspectRatio.modeName}") { viewModel.toggleAspectRatio() }
+ QuickSettingsButton(stringResource(R.string.player_aspect_ratio_label, aspectRatio.modeName)) { viewModel.toggleAspectRatio() }
if (availableSubtitleTracks.isNotEmpty()) {
- QuickSettingsButton("💬 " + stringResource(R.string.player_subs)) { showTrackSelection = TrackType.TEXT }
+ QuickSettingsButton(stringResource(R.string.player_subs)) { showTrackSelection = TrackType.TEXT }
}
if (availableAudioTracks.size > 1) {
- QuickSettingsButton("🔊 " + stringResource(R.string.player_audio)) { showTrackSelection = TrackType.AUDIO }
+ QuickSettingsButton(stringResource(R.string.player_audio)) { showTrackSelection = TrackType.AUDIO }
}
if (availableVideoQualities.size > 1) {
- QuickSettingsButton("⚙ HD") { showTrackSelection = TrackType.VIDEO }
+ QuickSettingsButton(stringResource(R.string.player_video_quality)) { showTrackSelection = TrackType.VIDEO }
}
- // Split Screen button — available in LIVE mode
- QuickSettingsButton("🔳 " + stringResource(R.string.multiview_nav)) { showSplitDialog = true }
+ QuickSettingsButton(stringResource(R.string.multiview_nav)) { showSplitDialog = true }
}
}
@@ -593,16 +694,15 @@ fun PlayerScreen(
// Track selection for VOD
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
- QuickSettingsButton("📺 ${aspectRatio.modeName}") { viewModel.toggleAspectRatio() }
+ QuickSettingsButton(stringResource(R.string.player_aspect_ratio_label, aspectRatio.modeName)) { viewModel.toggleAspectRatio() }
if (availableSubtitleTracks.isNotEmpty()) {
- QuickSettingsButton("💬 " + stringResource(R.string.player_subs)) { showTrackSelection = TrackType.TEXT }
+ QuickSettingsButton(stringResource(R.string.player_subs)) { showTrackSelection = TrackType.TEXT }
}
if (availableAudioTracks.size > 1) {
- QuickSettingsButton("🔊 " + stringResource(R.string.player_audio)) { showTrackSelection = TrackType.AUDIO }
+ QuickSettingsButton(stringResource(R.string.player_audio)) { showTrackSelection = TrackType.AUDIO }
}
if (availableVideoQualities.size > 1) {
- // VODs might have multiple qualities in rare cases if the provider provides them as separate stream IDs and we grouped them, though our grouping targets Live channels mostly.
- QuickSettingsButton("⚙ HD") { showTrackSelection = TrackType.VIDEO }
+ QuickSettingsButton(stringResource(R.string.player_video_quality)) { showTrackSelection = TrackType.VIDEO }
}
}
}
@@ -617,7 +717,7 @@ fun PlayerScreen(
verticalAlignment = Alignment.CenterVertically
) {
if (contentType != "LIVE") {
- TransportButton("⏪") { viewModel.seekBackward() }
+ TransportButton("<<") { viewModel.seekBackward() }
}
if (contentType != "LIVE") {
@@ -634,7 +734,7 @@ fun PlayerScreen(
) {
Box(contentAlignment = Alignment.Center, modifier = Modifier.fillMaxSize()) {
Text(
- text = if (isPlaying) "⏸" else "▶",
+ text = if (isPlaying) "||" else ">",
style = MaterialTheme.typography.headlineMedium,
color = Color.White
)
@@ -643,7 +743,7 @@ fun PlayerScreen(
}
if (contentType != "LIVE") {
- TransportButton("⏩") { viewModel.seekForward() }
+ TransportButton(">>") { viewModel.seekForward() }
}
}
}
@@ -698,6 +798,42 @@ fun PlayerScreen(
}
}
+ AnimatedVisibility(
+ visible = numericChannelInput != null && contentType == "LIVE" && !showControls,
+ enter = fadeIn() + slideInVertically(initialOffsetY = { -it / 2 }),
+ exit = fadeOut() + slideOutVertically(targetOffsetY = { -it / 2 }),
+ modifier = Modifier
+ .align(Alignment.TopCenter)
+ .padding(top = 40.dp)
+ ) {
+ val inputState = numericChannelInput ?: return@AnimatedVisibility
+ Box(
+ modifier = Modifier
+ .background(Color.Black.copy(alpha = 0.82f), RoundedCornerShape(14.dp))
+ .padding(horizontal = 22.dp, vertical = 12.dp)
+ ) {
+ Column(horizontalAlignment = Alignment.CenterHorizontally) {
+ Text(
+ text = inputState.input,
+ style = MaterialTheme.typography.headlineMedium,
+ color = if (inputState.invalid) ErrorColor else Primary,
+ fontWeight = FontWeight.Bold
+ )
+ Text(
+ text = when {
+ inputState.invalid -> "Channel not found"
+ !inputState.matchedChannelName.isNullOrBlank() -> inputState.matchedChannelName
+ else -> "Type channel number"
+ },
+ style = MaterialTheme.typography.bodySmall,
+ color = Color.White.copy(alpha = 0.85f),
+ maxLines = 1,
+ overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis
+ )
+ }
+ }
+ }
+
// Aspect Ratio confirmation Toast
var showAspectRatioToast by remember { mutableStateOf(false) }
LaunchedEffect(aspectRatio) {
@@ -909,6 +1045,8 @@ fun PlayerScreen(
channels = currentChannelList,
currentChannelId = internalChannelId,
overlayFocusRequester = channelListFocusRequester,
+ preferredFocusedChannelId = lastFocusedChannelListItemId,
+ onFocusedChannelChange = { channelId -> lastFocusedChannelListItemId = channelId },
onSelectChannel = { channelId -> viewModel.zapToChannel(channelId) },
onDismiss = { viewModel.closeOverlays() }
)
@@ -930,6 +1068,9 @@ fun PlayerScreen(
currentProgram = currentProgram,
nextProgram = nextProgram,
upcomingPrograms = upcomingPrograms,
+ overlayFocusRequester = epgFocusRequester,
+ preferredFocusedProgramToken = lastFocusedEpgProgramToken,
+ onFocusedProgramChange = { token -> lastFocusedEpgProgramToken = token },
onDismiss = { viewModel.closeOverlays() },
onPlayCatchUp = { program ->
viewModel.playCatchUp(program)
@@ -1038,7 +1179,7 @@ fun ChannelInfoOverlay(
.background(Primary.copy(alpha = 0.8f), RoundedCornerShape(4.dp))
.padding(horizontal = 8.dp, vertical = 3.dp)
) {
- Text("⏪ Catch-Up", style = MaterialTheme.typography.labelSmall, color = Color.White)
+ Text(stringResource(R.string.player_catchup_badge), style = MaterialTheme.typography.labelSmall, color = Color.White)
}
}
}
@@ -1061,7 +1202,12 @@ fun ChannelInfoOverlay(
overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis
)
Text(
- text = "${timeFormat.format(java.util.Date(currentProgram.startTime))} – ${timeFormat.format(java.util.Date(currentProgram.endTime))} · ${currentProgram.durationMinutes} min",
+ text = stringResource(
+ R.string.player_time_range_minutes,
+ timeFormat.format(java.util.Date(currentProgram.startTime)),
+ timeFormat.format(java.util.Date(currentProgram.endTime)),
+ currentProgram.durationMinutes
+ ),
style = MaterialTheme.typography.labelMedium,
color = Color.White.copy(alpha = 0.7f)
)
@@ -1099,7 +1245,7 @@ fun ChannelInfoOverlay(
if (nextProgram != null) {
Row(verticalAlignment = Alignment.CenterVertically) {
Text(
- text = "Next: ",
+ text = stringResource(R.string.player_next_label),
style = MaterialTheme.typography.labelMedium,
color = Primary
)
@@ -1126,8 +1272,8 @@ fun ChannelInfoOverlay(
verticalAlignment = Alignment.CenterVertically
) {
QuickActionButton(
- icon = if (isPlaying) "⏸" else "▶",
- label = if (isPlaying) "Pause" else "Play",
+ icon = if (isPlaying) "||" else ">",
+ label = if (isPlaying) stringResource(R.string.player_pause) else stringResource(R.string.player_play),
onClick = onTogglePlayPause,
colors = ClickableSurfaceDefaults.colors(
containerColor = Primary.copy(alpha = 0.25f),
@@ -1137,8 +1283,8 @@ fun ChannelInfoOverlay(
)
if (currentChannel?.catchUpSupported == true && currentProgram?.hasArchive == true) {
QuickActionButton(
- icon = "⏮",
- label = "Restart",
+ icon = "R",
+ label = stringResource(R.string.player_restart),
onClick = {
onRestartProgram()
onDismiss()
@@ -1146,27 +1292,27 @@ fun ChannelInfoOverlay(
)
}
QuickActionButton(
- icon = "📺",
+ icon = "AR",
label = currentAspectRatio,
onClick = onToggleAspectRatio,
modifier = Modifier.focusRequester(focusRequester)
)
QuickActionButton(
- icon = "📋",
- label = "Full EPG",
+ icon = "EPG",
+ label = stringResource(R.string.player_full_epg),
onClick = onOpenFullEpg
)
QuickActionButton(
- icon = "🔳",
- label = "Split Screen",
+ icon = "MV",
+ label = stringResource(R.string.multiview_nav),
onClick = {
onDismiss()
onOpenSplitScreen()
}
)
QuickActionButton(
- icon = if (isDiagnosticsEnabled) "🛠️" else "📊",
- label = "Stats",
+ icon = if (isDiagnosticsEnabled) "ON" else "OFF",
+ label = stringResource(R.string.player_stats),
onClick = onToggleDiagnostics
)
}
@@ -1243,7 +1389,7 @@ private fun TrackItem(
modifier = Modifier.weight(1f)
)
if (isSelected) {
- Text("✓", color = Primary, style = MaterialTheme.typography.bodyLarge)
+ Text(stringResource(R.string.player_selected), color = Primary, style = MaterialTheme.typography.labelSmall)
}
}
}
@@ -1254,17 +1400,26 @@ fun ChannelListOverlay(
channels: List<com.streamvault.domain.model.Channel>,
currentChannelId: Long,
overlayFocusRequester: FocusRequester = remember { FocusRequester() },
+ preferredFocusedChannelId: Long? = null,
+ onFocusedChannelChange: (Long) -> Unit = {},
onSelectChannel: (Long) -> Unit,
onDismiss: () -> Unit
) {
val listState = androidx.compose.foundation.lazy.rememberLazyListState()
+ val scope = rememberCoroutineScope()
val currentIndex = remember(channels, currentChannelId) {
channels.indexOfFirst { it.id == currentChannelId }.coerceAtLeast(0)
}
- // Scroll to current item when channels load
- LaunchedEffect(channels) {
+ val preferredIndex = remember(channels, currentChannelId, preferredFocusedChannelId) {
+ val focused = preferredFocusedChannelId?.let { channelId ->
+ channels.indexOfFirst { it.id == channelId }.takeIf { it >= 0 }
+ }
+ focused ?: currentIndex
+ }
+ // Scroll to focused/current item when channels load
+ LaunchedEffect(channels, preferredIndex) {
if (channels.isNotEmpty()) {
- listState.scrollToItem(currentIndex)
+ listState.scrollToItem(preferredIndex)
}
}
@@ -1279,7 +1434,7 @@ fun ChannelListOverlay(
) {
item {
Text(
- text = "Channels (${channels.size})",
+ text = stringResource(R.string.player_channel_list_title, channels.size),
style = MaterialTheme.typography.titleMedium,
color = Primary,
modifier = Modifier.padding(horizontal = 24.dp, vertical = 24.dp)
@@ -1288,7 +1443,8 @@ fun ChannelListOverlay(
items(channels.size) { index ->
val channel = channels[index]
val isSelected = channel.id == currentChannelId
- var isFocused by remember { mutableStateOf(false) }
+ val shouldRequestFocus = preferredFocusedChannelId?.let { it == channel.id } ?: isSelected
+ val channelNumber = if (channel.number > 0) channel.number else index + 1
Surface(
onClick = {
@@ -1298,11 +1454,20 @@ fun ChannelListOverlay(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 3.dp)
- .onFocusChanged { isFocused = it.isFocused }
+ .onFocusChanged {
+ if (it.isFocused) {
+ onFocusedChannelChange(channel.id)
+ scope.launch {
+ val targetIndex = (index - 1).coerceAtLeast(0)
+ listState.animateScrollToItem(targetIndex)
+ }
+ }
+ }
.then(
- if (isSelected) Modifier.focusRequester(overlayFocusRequester)
+ if (shouldRequestFocus) Modifier.focusRequester(overlayFocusRequester)
else Modifier
),
+ scale = ClickableSurfaceDefaults.scale(focusedScale = 1f),
shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(8.dp)),
colors = ClickableSurfaceDefaults.colors(
containerColor = if (isSelected) Primary.copy(alpha = 0.25f) else Color.White.copy(alpha = 0.05f),
@@ -1317,10 +1482,15 @@ fun ChannelListOverlay(
horizontalArrangement = Arrangement.spacedBy(12.dp)
) {
if (isSelected) {
- Text("▶", color = Color.White, style = MaterialTheme.typography.bodySmall)
+ Text(stringResource(R.string.player_channel_selected), color = Color.White, style = MaterialTheme.typography.labelSmall)
} else {
Text(" ", style = MaterialTheme.typography.bodySmall)
}
+ Text(
+ text = channelNumber.toString().padStart(2, '0'),
+ style = MaterialTheme.typography.labelMedium,
+ color = Color.White.copy(alpha = 0.72f)
+ )
Text(
text = channel.name,
style = MaterialTheme.typography.bodyLarge,
@@ -1330,7 +1500,7 @@ fun ChannelListOverlay(
modifier = Modifier.weight(1f)
)
if (channel.catchUpSupported) {
- Text("📼", style = MaterialTheme.typography.bodySmall)
+ Text(stringResource(R.string.player_archive_badge), style = MaterialTheme.typography.labelSmall)
}
}
}
@@ -1346,10 +1516,20 @@ fun EpgOverlay(
currentProgram: Program?,
nextProgram: Program?,
upcomingPrograms: List<Program>,
+ overlayFocusRequester: FocusRequester = remember { FocusRequester() },
+ preferredFocusedProgramToken: Long? = null,
+ onFocusedProgramChange: (Long) -> Unit = {},
onDismiss: () -> Unit,
onPlayCatchUp: (Program) -> Unit
) {
val timeFormat = java.text.SimpleDateFormat("HH:mm", java.util.Locale.getDefault())
+ val listState = androidx.compose.foundation.lazy.rememberLazyListState()
+ val filteredUpcoming = remember(upcomingPrograms, currentProgram, nextProgram) {
+ upcomingPrograms.filter { it.id != currentProgram?.id && it.id != nextProgram?.id }
+ }
+ val displayPrograms = remember(filteredUpcoming, nextProgram) {
+ if (nextProgram != null) listOf(nextProgram) + filteredUpcoming else filteredUpcoming
+ }
BackHandler { onDismiss() }
@@ -1359,6 +1539,7 @@ fun EpgOverlay(
.background(Color.Black.copy(alpha = 0.70f))
) {
androidx.compose.foundation.lazy.LazyColumn(
+ state = listState,
modifier = Modifier
.fillMaxSize()
.padding(24.dp),
@@ -1368,11 +1549,7 @@ fun EpgOverlay(
item {
Row(verticalAlignment = Alignment.CenterVertically) {
Text(
- text = "📺 ",
- style = MaterialTheme.typography.titleLarge
- )
- Text(
- text = "Advanced EPG",
+ text = stringResource(R.string.epg_title),
style = MaterialTheme.typography.titleLarge,
color = Primary,
fontWeight = FontWeight.Bold
@@ -1389,7 +1566,7 @@ fun EpgOverlay(
if (currentChannel.catchUpSupported) {
Spacer(Modifier.height(4.dp))
Text(
- text = "⏪ Catch-Up available (${currentChannel.catchUpDays} days)",
+ text = stringResource(R.string.epg_catchup_available, currentChannel.catchUpDays),
style = MaterialTheme.typography.bodySmall,
color = Primary.copy(alpha = 0.8f)
)
@@ -1402,7 +1579,7 @@ fun EpgOverlay(
androidx.compose.material3.HorizontalDivider(color = SurfaceVariant)
Spacer(Modifier.height(8.dp))
Text(
- text = "NOW PLAYING",
+ text = stringResource(R.string.epg_now_playing),
style = MaterialTheme.typography.labelMedium,
color = Primary,
fontWeight = FontWeight.Bold
@@ -1453,7 +1630,7 @@ fun EpgOverlay(
)
Spacer(Modifier.height(4.dp))
Text(
- text = "$remainingMin min remaining",
+ text = stringResource(R.string.player_minutes_remaining, remainingMin),
style = MaterialTheme.typography.bodySmall,
color = OnSurfaceDim
)
@@ -1470,7 +1647,7 @@ fun EpgOverlay(
)
}
} else {
- Text("No EPG Information", color = OnSurfaceDim)
+ Text(stringResource(R.string.epg_no_info), color = OnSurfaceDim)
}
}
@@ -1481,18 +1658,17 @@ fun EpgOverlay(
androidx.compose.material3.HorizontalDivider(color = SurfaceVariant)
Spacer(Modifier.height(8.dp))
Text(
- text = "UPCOMING SCHEDULE",
+ text = stringResource(R.string.epg_upcoming_schedule),
style = MaterialTheme.typography.labelMedium,
color = Primary,
fontWeight = FontWeight.Bold
)
}
- // Skip the current program if it appears in upcoming list
- val filteredUpcoming = upcomingPrograms.filter { it.id != currentProgram?.id && it.id != nextProgram?.id }
- val displayPrograms = if (nextProgram != null) listOf(nextProgram) + filteredUpcoming else filteredUpcoming
items(displayPrograms.size) { index ->
val program = displayPrograms[index]
val isNext = index == 0 && nextProgram != null
+ val focusToken = if (program.id > 0) program.id else program.startTime
+ val shouldRequestFocus = preferredFocusedProgramToken?.let { it == focusToken } ?: (index == 0)
Surface(
onClick = {
@@ -1505,14 +1681,22 @@ fun EpgOverlay(
containerColor = if (isNext) Primary.copy(alpha = 0.08f) else Color.Transparent,
focusedContainerColor = Primary.copy(alpha = 0.2f)
),
- modifier = Modifier.fillMaxWidth()
+ modifier = Modifier
+ .fillMaxWidth()
+ .then(
+ if (shouldRequestFocus) Modifier.focusRequester(overlayFocusRequester)
+ else Modifier
+ )
+ .onFocusChanged {
+ if (it.isFocused) onFocusedProgramChange(focusToken)
+ }
) {
Column(
modifier = Modifier.padding(12.dp)
) {
if (isNext) {
Text(
- text = "UP NEXT",
+ text = stringResource(R.string.epg_up_next),
style = MaterialTheme.typography.labelSmall,
color = Primary,
fontWeight = FontWeight.Bold
@@ -1543,8 +1727,8 @@ fun EpgOverlay(
if (program.hasArchive) {
Spacer(Modifier.width(8.dp))
Text(
- text = "📼",
- style = MaterialTheme.typography.bodySmall
+ text = stringResource(R.string.player_archive_badge),
+ style = MaterialTheme.typography.labelSmall
)
}
}
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModel.kt
index 8a16fe32..c6075d48 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModel.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModel.kt
@@ -4,6 +4,7 @@ import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.streamvault.domain.model.Program
import com.streamvault.domain.model.ContentType
+import com.streamvault.domain.model.DecoderMode
import com.streamvault.domain.model.PlaybackHistory
import com.streamvault.domain.model.VideoFormat
import com.streamvault.domain.repository.ChannelRepository
@@ -13,6 +14,7 @@ import com.streamvault.player.PlaybackState
import com.streamvault.player.PlayerEngine
import com.streamvault.player.PlayerError
import dagger.hilt.android.lifecycle.HiltViewModel
+import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.*
@@ -25,6 +27,12 @@ data class ResumePromptState(
val title: String = ""
)
+data class NumericChannelInputState(
+ val input: String = "",
+ val matchedChannelName: String? = null,
+ val invalid: Boolean = false
+)
+
enum class AspectRatio(val modeName: String) {
FIT("Fit"),
FILL("Stretch"),
@@ -32,6 +40,7 @@ enum class AspectRatio(val modeName: String) {
}
@HiltViewModel
+@OptIn(ExperimentalCoroutinesApi::class)
class PlayerViewModel @Inject constructor(
val playerEngine: PlayerEngine,
private val epgRepository: EpgRepository,
@@ -84,11 +93,18 @@ class PlayerViewModel @Inject constructor(
private val _showChannelInfoOverlay = MutableStateFlow(false)
val showChannelInfoOverlay: StateFlow<Boolean> = _showChannelInfoOverlay.asStateFlow()
+ private val _numericChannelInput = MutableStateFlow<NumericChannelInputState?>(null)
+ val numericChannelInput: StateFlow<NumericChannelInputState?> = _numericChannelInput.asStateFlow()
+
private val _showDiagnostics = MutableStateFlow(false)
val showDiagnostics: StateFlow<Boolean> = _showDiagnostics.asStateFlow()
private var channelInfoHideJob: Job? = null
+ private var numericInputCommitJob: Job? = null
+ private var numericInputFeedbackJob: Job? = null
+ private var numericInputBuffer: String = ""
private val triedAlternativeStreams = mutableSetOf<String>()
+ private var hasRetriedWithSoftwareDecoder = false
init {
viewModelScope.launch {
@@ -101,6 +117,7 @@ class PlayerViewModel @Inject constructor(
viewModelScope.launch {
playerEngine.playbackState.collect { state ->
if (state == PlaybackState.READY && currentContentType == ContentType.LIVE) {
+ zapBufferWatchdogJob?.cancel()
_currentChannel.value?.let { channel ->
if (channel.errorCount > 0) {
channelRepository.resetChannelErrorCount(channel.id)
@@ -112,6 +129,14 @@ class PlayerViewModel @Inject constructor(
}
private fun handlePlaybackError(error: PlayerError) {
+ if (error is PlayerError.DecoderError && !hasRetriedWithSoftwareDecoder) {
+ hasRetriedWithSoftwareDecoder = true
+ android.util.Log.w("PlayerVM", "Decoder error detected. Retrying with software decoder mode.")
+ playerEngine.setDecoderMode(DecoderMode.SOFTWARE)
+ playerEngine.play()
+ return
+ }
+
// Only auto-switch for live TV
if (currentContentType != ContentType.LIVE) return
@@ -130,7 +155,7 @@ class PlayerViewModel @Inject constructor(
if (nextStream != null) {
triedAlternativeStreams.add(nextStream)
- android.util.Log.d("PlayerVM", "Switching to alternative stream: $nextStream")
+ android.util.Log.d("PlayerVM", "Switching to alternative stream for current channel")
val streamInfo = com.streamvault.domain.model.StreamInfo(
url = nextStream,
@@ -139,13 +164,15 @@ class PlayerViewModel @Inject constructor(
playerEngine.prepare(streamInfo)
playerEngine.play()
} else {
- android.util.Log.e("PlayerVM", "No more alternative streams for channel: ${channel.name}")
+ android.util.Log.e("PlayerVM", "No more alternative streams for current channel")
+ fallbackToPreviousChannel("No alternative stream")
}
}
}
}
fun openChannelListOverlay() {
+ clearNumericChannelInput()
_showChannelListOverlay.value = true
_showEpgOverlay.value = false
_showChannelInfoOverlay.value = false
@@ -153,6 +180,7 @@ class PlayerViewModel @Inject constructor(
}
fun openEpgOverlay() {
+ clearNumericChannelInput()
_showEpgOverlay.value = true
_showChannelListOverlay.value = false
_showChannelInfoOverlay.value = false
@@ -160,6 +188,7 @@ class PlayerViewModel @Inject constructor(
}
fun openChannelInfoOverlay() {
+ clearNumericChannelInput()
_showChannelInfoOverlay.value = true
_showChannelListOverlay.value = false
_showEpgOverlay.value = false
@@ -177,6 +206,7 @@ class PlayerViewModel @Inject constructor(
}
fun closeOverlays() {
+ clearNumericChannelInput()
_showChannelListOverlay.value = false
_showEpgOverlay.value = false
_showChannelInfoOverlay.value = false
@@ -204,6 +234,9 @@ class PlayerViewModel @Inject constructor(
private var progressTrackingJob: Job? = null
private var zapOverlayJob: Job? = null
private var aspectRatioJob: Job? = null
+ private var zapBufferWatchdogJob: Job? = null
+ private var isAppInForeground: Boolean = true
+ private var shouldResumeAfterForeground: Boolean = false
val playerError: StateFlow<PlayerError?> = playerEngine.error
.stateIn(viewModelScope, kotlinx.coroutines.flow.SharingStarted.WhileSubscribed(5000), null)
@@ -253,6 +286,8 @@ class PlayerViewModel @Inject constructor(
currentContentId = internalChannelId
currentTitle = title
currentContentType = try { ContentType.valueOf(contentType) } catch (e: Exception) { ContentType.LIVE }
+ hasRetriedWithSoftwareDecoder = false
+ playerEngine.setDecoderMode(DecoderMode.AUTO)
// Reset tried streams for manual switch
triedAlternativeStreams.clear()
@@ -301,7 +336,7 @@ class PlayerViewModel @Inject constructor(
currentStreamUrl = streamUrl
// Fetch EPG if ID provided
- fetchEpg(epgChannelId)
+ fetchEpg(currentProviderId, epgChannelId)
// Load Aspect Ratio safely (fallback to FIT if none saved)
aspectRatioJob?.cancel()
@@ -363,37 +398,87 @@ class PlayerViewModel @Inject constructor(
progressTrackingJob = viewModelScope.launch {
while (true) {
delay(5000) // Track every 5 seconds
- val pos = playerEngine.currentPosition.value
- val dur = playerEngine.duration.value
-
- if (pos > 0 && dur > 0 && currentContentId != -1L) {
- val history = PlaybackHistory(
- contentId = currentContentId,
- contentType = currentContentType,
- providerId = currentProviderId,
- title = currentTitle,
- streamUrl = currentStreamUrl,
- resumePositionMs = pos,
- totalDurationMs = dur,
- lastWatchedAt = System.currentTimeMillis()
- )
- playbackHistoryRepository.updateResumePosition(history)
- }
+ if (!isAppInForeground || !playerEngine.isPlaying.value) continue
+ persistPlaybackProgress()
}
}
}
- private fun fetchEpg(epgChannelId: String?) {
+ private suspend fun persistPlaybackProgress() {
+ val pos = playerEngine.currentPosition.value
+ val dur = playerEngine.duration.value
+
+ if (pos > 0 && dur > 0 && currentContentId != -1L && currentProviderId != -1L) {
+ val history = PlaybackHistory(
+ contentId = currentContentId,
+ contentType = currentContentType,
+ providerId = currentProviderId,
+ title = currentTitle,
+ streamUrl = currentStreamUrl,
+ resumePositionMs = pos,
+ totalDurationMs = dur,
+ lastWatchedAt = System.currentTimeMillis()
+ )
+ playbackHistoryRepository.updateResumePosition(history)
+ }
+ }
+
+ fun onAppBackgrounded() {
+ if (!isAppInForeground) return
+ isAppInForeground = false
+ shouldResumeAfterForeground = playerEngine.isPlaying.value
+ if (shouldResumeAfterForeground) {
+ playerEngine.pause()
+ }
+ if (currentContentType != ContentType.LIVE) {
+ viewModelScope.launch { persistPlaybackProgress() }
+ }
+ }
+
+ fun onAppForegrounded() {
+ if (isAppInForeground) return
+ isAppInForeground = true
+ if (shouldResumeAfterForeground && !_resumePrompt.value.show) {
+ playerEngine.play()
+ }
+ shouldResumeAfterForeground = false
+ }
+
+ fun onPlayerScreenDisposed() {
+ if (currentContentType != ContentType.LIVE) {
+ viewModelScope.launch { persistPlaybackProgress() }
+ }
+ }
+
+ private fun fetchEpg(providerId: Long, epgChannelId: String?) {
epgJob?.cancel()
- if (epgChannelId != null) {
+ if (providerId > 0 && epgChannelId != null) {
epgJob = viewModelScope.launch {
- epgRepository.getNowAndNext(epgChannelId).collect { (now, next) ->
- _currentProgram.value = now
- _nextProgram.value = next
+ launch {
+ epgRepository.getNowAndNext(providerId, epgChannelId).collect { (now, next) ->
+ _currentProgram.value = now
+ _nextProgram.value = next
+ }
+ }
+ launch {
+ // Fetch last 24 hours.
+ val now = System.currentTimeMillis()
+ val start = now - (24 * 60 * 60 * 1000L)
+ epgRepository.getProgramsForChannel(providerId, epgChannelId, start, now).collect { programs ->
+ _programHistory.value = programs
+ .filter { it.hasArchive }
+ .sortedByDescending { it.startTime }
+ }
+ }
+ launch {
+ // Fetch next 6 hours.
+ val now = System.currentTimeMillis()
+ val end = now + (6 * 60 * 60 * 1000L)
+ epgRepository.getProgramsForChannel(providerId, epgChannelId, now, end).collect { programs ->
+ _upcomingPrograms.value = programs.sortedBy { it.startTime }
+ }
}
}
- fetchProgramHistory(epgChannelId)
- fetchUpcomingPrograms(epgChannelId)
} else {
_currentProgram.value = null
_nextProgram.value = null
@@ -402,29 +487,6 @@ class PlayerViewModel @Inject constructor(
}
}
- private fun fetchProgramHistory(channelId: String) {
- viewModelScope.launch {
- // Fetch last 24 hours
- val now = System.currentTimeMillis()
- val start = now - (24 * 60 * 60 * 1000L)
- epgRepository.getProgramsForChannel(channelId, start, now).collect { programs ->
- // Only show programs that have archive (for Xtream)
- _programHistory.value = programs.filter { it.hasArchive }.sortedByDescending { it.startTime }
- }
- }
- }
-
- private fun fetchUpcomingPrograms(channelId: String) {
- viewModelScope.launch {
- // Fetch next 6 hours
- val now = System.currentTimeMillis()
- val end = now + (6 * 60 * 60 * 1000L)
- epgRepository.getProgramsForChannel(channelId, now, end).collect { programs ->
- _upcomingPrograms.value = programs.sortedBy { it.startTime }
- }
- }
- }
-
private fun loadPlaylist(categoryId: Long, providerId: Long, isVirtual: Boolean, initialChannelId: Long) {
playlistJob?.cancel()
playlistJob = viewModelScope.launch {
@@ -474,6 +536,7 @@ class PlayerViewModel @Inject constructor(
private var currentStreamUrl: String = ""
fun playNext() {
+ clearNumericChannelInput()
if (channelList.isEmpty()) return
if (currentChannelIndex == -1) {
@@ -486,6 +549,7 @@ class PlayerViewModel @Inject constructor(
}
fun playPrevious() {
+ clearNumericChannelInput()
if (channelList.isEmpty()) return
if (currentChannelIndex == -1) {
@@ -498,6 +562,7 @@ class PlayerViewModel @Inject constructor(
}
fun zapToChannel(channelId: Long) {
+ clearNumericChannelInput()
if (channelList.isEmpty()) return
val index = channelList.indexOfFirst { it.id == channelId }
if (index != -1) {
@@ -507,11 +572,75 @@ class PlayerViewModel @Inject constructor(
}
fun zapToLastChannel() {
+ clearNumericChannelInput()
if (channelList.isEmpty() || previousChannelIndex == -1) return
changeChannel(previousChannelIndex)
}
+ fun hasPendingNumericChannelInput(): Boolean = numericInputBuffer.isNotBlank()
+
+ fun inputNumericChannelDigit(digit: Int) {
+ if (currentContentType != ContentType.LIVE || channelList.isEmpty() || digit !in 0..9) return
+
+ if (numericInputBuffer.isEmpty() && digit == 0) {
+ zapToLastChannel()
+ return
+ }
+
+ numericInputBuffer = if (numericInputBuffer.length >= 4) {
+ digit.toString()
+ } else {
+ numericInputBuffer + digit.toString()
+ }
+
+ val exactMatch = resolveChannelByNumber(numericInputBuffer.toIntOrNull())
+ val previewMatch = exactMatch ?: resolveChannelByPrefix(numericInputBuffer)
+
+ _numericChannelInput.value = NumericChannelInputState(
+ input = numericInputBuffer,
+ matchedChannelName = previewMatch?.name,
+ invalid = false
+ )
+
+ scheduleNumericChannelCommit()
+ }
+
+ fun commitNumericChannelInput() {
+ numericInputCommitJob?.cancel()
+ if (numericInputBuffer.isBlank()) return
+
+ val targetChannel = resolveChannelByNumber(numericInputBuffer.toIntOrNull())
+ if (targetChannel != null) {
+ val targetIndex = channelList.indexOfFirst { it.id == targetChannel.id }
+ if (targetIndex != -1) {
+ changeChannel(targetIndex)
+ }
+ clearNumericChannelInput()
+ return
+ }
+
+ _numericChannelInput.value = NumericChannelInputState(
+ input = numericInputBuffer,
+ matchedChannelName = null,
+ invalid = true
+ )
+
+ numericInputFeedbackJob?.cancel()
+ numericInputFeedbackJob = viewModelScope.launch {
+ delay(900)
+ clearNumericChannelInput()
+ }
+ }
+
+ fun clearNumericChannelInput() {
+ numericInputCommitJob?.cancel()
+ numericInputFeedbackJob?.cancel()
+ numericInputBuffer = ""
+ _numericChannelInput.value = null
+ }
+
private fun changeChannel(index: Int) {
+ clearNumericChannelInput()
if (currentChannelIndex != -1 && currentChannelIndex != index) {
previousChannelIndex = currentChannelIndex
}
@@ -528,7 +657,7 @@ class PlayerViewModel @Inject constructor(
playerEngine.prepare(streamInfo)
playerEngine.play()
- fetchEpg(channel.epgChannelId)
+ fetchEpg(currentProviderId, channel.epgChannelId)
// Show Zap Overlay & Brief Info
_showZapOverlay.value = true
@@ -540,8 +669,62 @@ class PlayerViewModel @Inject constructor(
triedAlternativeStreams.add(channel.streamUrl)
hideZapOverlayAfterDelay()
+ if (currentContentType == ContentType.LIVE) {
+ scheduleZapBufferWatchdog(index)
+ }
}
+ private fun scheduleZapBufferWatchdog(targetIndex: Int) {
+ zapBufferWatchdogJob?.cancel()
+ zapBufferWatchdogJob = viewModelScope.launch {
+ delay(9000)
+ val stillOnTarget = currentChannelIndex == targetIndex
+ val state = playerEngine.playbackState.value
+ val stalled = state == PlaybackState.BUFFERING || state == PlaybackState.ERROR
+ if (stillOnTarget && stalled) {
+ fallbackToPreviousChannel("Channel timed out in buffering state")
+ }
+ }
+ }
+
+ private fun fallbackToPreviousChannel(reason: String) {
+ val fallbackIndex = previousChannelIndex
+ if (fallbackIndex in channelList.indices && fallbackIndex != currentChannelIndex) {
+ android.util.Log.w("PlayerVM", "Falling back to previous channel: $reason")
+ changeChannel(fallbackIndex)
+ }
+ }
+
+ private fun scheduleNumericChannelCommit() {
+ numericInputCommitJob?.cancel()
+ numericInputCommitJob = viewModelScope.launch {
+ delay(1300)
+ commitNumericChannelInput()
+ }
+ }
+
+ private fun resolveChannelByNumber(number: Int?): com.streamvault.domain.model.Channel? {
+ if (number == null) return null
+ return channelList
+ .withIndex()
+ .firstOrNull { (index, channel) -> resolveChannelNumber(channel, index) == number }
+ ?.value
+ }
+
+ private fun resolveChannelByPrefix(prefix: String): com.streamvault.domain.model.Channel? {
+ return channelList
+ .withIndex()
+ .firstOrNull { (index, channel) ->
+ resolveChannelNumber(channel, index).toString().startsWith(prefix)
+ }
+ ?.value
+ }
+
+ private fun resolveChannelNumber(
+ channel: com.streamvault.domain.model.Channel,
+ index: Int
+ ): Int = if (channel.number > 0) channel.number else index + 1
+
fun play() = playerEngine.play()
fun pause() = playerEngine.pause()
fun seekForward() = playerEngine.seekForward()
@@ -633,9 +816,17 @@ class PlayerViewModel @Inject constructor(
override fun onCleared() {
super.onCleared()
+ onPlayerScreenDisposed()
+ channelInfoHideJob?.cancel()
+ numericInputCommitJob?.cancel()
+ numericInputFeedbackJob?.cancel()
+ epgJob?.cancel()
+ playlistJob?.cancel()
controlsHideJob?.cancel()
zapOverlayJob?.cancel()
+ zapBufferWatchdogJob?.cancel()
progressTrackingJob?.cancel()
+ aspectRatioJob?.cancel()
playerEngine.release()
}
}
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 221b2f38..33649457 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
@@ -18,7 +18,11 @@ import androidx.compose.ui.draw.scale
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.focus.onFocusChanged
+import androidx.compose.ui.graphics.Brush
+import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.style.TextAlign
+import androidx.compose.ui.text.input.PasswordVisualTransformation
+import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog
import androidx.hilt.navigation.compose.hiltViewModel
@@ -40,11 +44,13 @@ fun ProviderSetupScreen(
viewModel: ProviderSetupViewModel = hiltViewModel()
) {
val uiState by viewModel.uiState.collectAsState()
+ val knownLocalM3uUrls by viewModel.knownLocalM3uUrls.collectAsState()
val context = LocalContext.current
val coroutineScope = rememberCoroutineScope()
var name by remember { mutableStateOf("") }
var m3uUrl by remember { mutableStateOf("") }
+ var fileImportError by remember { mutableStateOf<String?>(null) }
val filePickerLauncher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.OpenDocument()
@@ -74,22 +80,60 @@ fun ProviderSetupScreen(
outFile.outputStream().use { out ->
inputStream.copyTo(out)
}
+ cleanupOldImportedM3uFiles(
+ filesDir = context.filesDir,
+ protectedFileUris = knownLocalM3uUrls + "file://${outFile.absolutePath}",
+ keepLatest = 20
+ )
withContext(Dispatchers.Main) {
m3uUrl = "file://${outFile.absolutePath}"
if (name.isEmpty()) name = fileName
+ fileImportError = null
+ }
+ } else {
+ withContext(Dispatchers.Main) {
+ fileImportError = context.getString(R.string.setup_file_import_failed)
}
}
} catch (e: Exception) {
- e.printStackTrace()
+ withContext(Dispatchers.Main) {
+ fileImportError = resolveFileImportError(context, e)
+ }
}
}
}
}
+ LaunchedEffect(knownLocalM3uUrls) {
+ cleanupOldImportedM3uFiles(
+ filesDir = context.filesDir,
+ protectedFileUris = knownLocalM3uUrls,
+ keepLatest = 20
+ )
+ }
+
// Navigate on success
LaunchedEffect(uiState.loginSuccess) {
- if (uiState.loginSuccess) onProviderAdded()
+ if (uiState.loginSuccess) {
+ val previousLocal = uiState.m3uUrl.takeIf { it.startsWith("file://") }
+ val selectedLocal = m3uUrl.takeIf { it.startsWith("file://") }
+ val protectedUris = buildSet {
+ knownLocalM3uUrls.forEach { knownUri ->
+ if (knownUri != previousLocal || previousLocal == selectedLocal) {
+ add(knownUri)
+ }
+ }
+ selectedLocal?.let(::add)
+ }
+
+ cleanupOldImportedM3uFiles(
+ filesDir = context.filesDir,
+ protectedFileUris = protectedUris,
+ keepLatest = 20
+ )
+ onProviderAdded()
+ }
}
// Auto-skip logic moved to MainActivity/Splash - preventing redirect loop here
@@ -126,122 +170,162 @@ fun ProviderSetupScreen(
// We already have the vars defined above.
Box(
- modifier = Modifier.fillMaxSize(),
+ modifier = Modifier
+ .fillMaxSize()
+ .background(
+ Brush.verticalGradient(
+ colors = listOf(BackgroundDeep, Background, Surface)
+ )
+ ),
contentAlignment = Alignment.Center
) {
- Column(
+ Box(
modifier = Modifier
- .width(500.dp)
- .padding(32.dp)
- .verticalScroll(rememberScrollState()),
- horizontalAlignment = Alignment.CenterHorizontally,
- verticalArrangement = Arrangement.spacedBy(16.dp)
+ .width(620.dp)
+ .padding(horizontal = 32.dp, vertical = 24.dp)
+ .background(SurfaceElevated.copy(alpha = 0.94f), RoundedCornerShape(20.dp))
+ .border(1.dp, SurfaceHighlight, RoundedCornerShape(20.dp))
) {
- // Title
- Text(
- text = if (uiState.isEditing) stringResource(R.string.setup_edit_provider) else stringResource(R.string.setup_title_streamvault),
- style = MaterialTheme.typography.displaySmall,
- color = Primary
- )
- Text(
- text = if (uiState.isEditing) stringResource(R.string.setup_update_desc) else stringResource(R.string.setup_add_desc),
- style = MaterialTheme.typography.bodyLarge,
- color = OnSurface
- )
-
- Spacer(modifier = Modifier.height(16.dp))
+ Column(
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(28.dp)
+ .verticalScroll(rememberScrollState()),
+ horizontalAlignment = Alignment.Start,
+ verticalArrangement = Arrangement.spacedBy(16.dp)
+ ) {
+ Text(
+ text = if (uiState.isEditing) stringResource(R.string.setup_edit_provider) else stringResource(R.string.setup_title_streamvault),
+ style = MaterialTheme.typography.headlineMedium,
+ color = TextPrimary
+ )
+ Text(
+ text = if (uiState.isEditing) stringResource(R.string.setup_update_desc) else stringResource(R.string.setup_add_desc),
+ style = MaterialTheme.typography.bodyLarge,
+ color = OnSurface
+ )
- // Tab selector - Disable changing type during edit
- Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
-
- if (!uiState.isEditing || uiState.selectedTab == 0) {
- TabButton(stringResource(R.string.setup_xtream), selectedTab == 0) { if (!uiState.isEditing) selectedTab = 0 }
- }
- if (!uiState.isEditing || uiState.selectedTab == 1) {
- TabButton(stringResource(R.string.setup_m3u), selectedTab == 1) { if (!uiState.isEditing) selectedTab = 1 }
+ Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ if (!uiState.isEditing || uiState.selectedTab == 0) {
+ TabButton(stringResource(R.string.setup_xtream), selectedTab == 0) {
+ if (!uiState.isEditing) selectedTab = 0
+ }
+ }
+ if (!uiState.isEditing || uiState.selectedTab == 1) {
+ TabButton(stringResource(R.string.setup_m3u), selectedTab == 1) {
+ if (!uiState.isEditing) selectedTab = 1
+ }
+ }
}
- }
-
- Spacer(modifier = Modifier.height(8.dp))
- // Playlist Name (Common)
- TvTextField(
- value = name,
- onValueChange = { name = it },
- label = stringResource(R.string.setup_name_hint)
- )
+ TvTextField(
+ value = name,
+ onValueChange = { name = it },
+ label = stringResource(R.string.setup_name_hint)
+ )
- when (selectedTab) {
- 0 -> {
- TvTextField(value = serverUrl, onValueChange = { serverUrl = it }, label = stringResource(R.string.setup_server_hint))
- TvTextField(value = username, onValueChange = { username = it }, label = stringResource(R.string.setup_user_hint))
- TvTextField(value = password, onValueChange = { password = it }, label = stringResource(R.string.setup_pass_hint))
-
- ActionButton(
- text = if (uiState.isLoading) stringResource(R.string.setup_connecting) else if (uiState.isEditing) stringResource(R.string.setup_save) else stringResource(R.string.setup_login),
- enabled = !uiState.isLoading,
- onClick = {
- viewModel.loginXtream(serverUrl, username, password, name)
- }
- )
- }
- 1 -> {
- // Sub-tabs for M3U: URL vs File
- Row(
- horizontalArrangement = Arrangement.spacedBy(8.dp),
- modifier = Modifier.padding(bottom = 8.dp)
- ) {
- TabButton(
- text = "URL",
- isSelected = uiState.m3uTab == 0,
- onClick = { viewModel.updateM3uTab(0) }
+ when (selectedTab) {
+ 0 -> {
+ TvTextField(
+ value = serverUrl,
+ onValueChange = { serverUrl = it },
+ label = stringResource(R.string.setup_server_hint)
)
- TabButton(
- text = "File",
- isSelected = uiState.m3uTab == 1,
- onClick = { viewModel.updateM3uTab(1) }
+ TvTextField(
+ value = username,
+ onValueChange = { username = it },
+ label = stringResource(R.string.setup_user_hint)
)
- }
-
- if (uiState.m3uTab == 0) {
TvTextField(
- value = m3uUrl,
- onValueChange = { m3uUrl = it },
- label = stringResource(R.string.setup_m3u_hint)
+ value = password,
+ onValueChange = { password = it },
+ label = stringResource(R.string.setup_pass_hint),
+ isPassword = true
)
- } else {
- FileSelectorCard(
- fileName = if (m3uUrl.startsWith("file://")) m3uUrl.substringAfterLast("/") else null,
- onClick = { filePickerLauncher.launch(arrayOf("*/*")) }
+
+ ActionButton(
+ text = if (uiState.isLoading) {
+ stringResource(R.string.setup_connecting)
+ } else if (uiState.isEditing) {
+ stringResource(R.string.setup_save)
+ } else {
+ stringResource(R.string.setup_login)
+ },
+ enabled = !uiState.isLoading,
+ onClick = {
+ viewModel.loginXtream(serverUrl, username, password, name)
+ }
)
}
+ 1 -> {
+ Row(
+ horizontalArrangement = Arrangement.spacedBy(8.dp),
+ modifier = Modifier.padding(bottom = 8.dp)
+ ) {
+ TabButton(
+ text = stringResource(R.string.setup_tab_url),
+ isSelected = uiState.m3uTab == 0,
+ onClick = { viewModel.updateM3uTab(0) }
+ )
+ TabButton(
+ text = stringResource(R.string.setup_tab_file),
+ isSelected = uiState.m3uTab == 1,
+ onClick = { viewModel.updateM3uTab(1) }
+ )
+ }
- Spacer(modifier = Modifier.height(8.dp))
+ if (uiState.m3uTab == 0) {
+ TvTextField(
+ value = m3uUrl,
+ onValueChange = { m3uUrl = it },
+ label = stringResource(R.string.setup_m3u_hint)
+ )
+ } else {
+ FileSelectorCard(
+ fileName = if (m3uUrl.startsWith("file://")) m3uUrl.substringAfterLast("/") else null,
+ fileSelectedHint = stringResource(R.string.setup_file_replace_hint),
+ emptySelectionTitle = stringResource(R.string.setup_file_select_title),
+ emptySelectionHint = stringResource(R.string.setup_file_browse_hint),
+ onClick = { filePickerLauncher.launch(arrayOf("*/*")) }
+ )
+ fileImportError?.let { importError ->
+ Text(
+ text = importError,
+ style = MaterialTheme.typography.bodyMedium,
+ color = ErrorColor
+ )
+ }
+ }
+
+ ActionButton(
+ text = if (uiState.isLoading) {
+ stringResource(R.string.setup_validating)
+ } else if (uiState.isEditing) {
+ stringResource(R.string.setup_save)
+ } else {
+ stringResource(R.string.setup_add)
+ },
+ enabled = !uiState.isLoading,
+ onClick = { viewModel.addM3u(m3uUrl, name) }
+ )
+ }
+ }
- ActionButton(
- text = if (uiState.isLoading) stringResource(R.string.setup_validating) else if (uiState.isEditing) stringResource(R.string.setup_save) else stringResource(R.string.setup_add),
- enabled = !uiState.isLoading,
- onClick = { viewModel.addM3u(m3uUrl, name) }
+ uiState.validationError?.let { error ->
+ Text(
+ text = error,
+ style = MaterialTheme.typography.bodyMedium,
+ color = ErrorColor
)
}
- }
- // Validation error
- uiState.validationError?.let { error ->
- Text(
- text = error,
- style = MaterialTheme.typography.bodySmall,
- color = ErrorColor
- )
- }
-
- // Error message
- uiState.error?.let { error ->
- Text(
- text = error,
- style = MaterialTheme.typography.bodySmall,
- color = ErrorColor
- )
+ uiState.error?.let { error ->
+ Text(
+ text = error,
+ style = MaterialTheme.typography.bodyMedium,
+ color = ErrorColor
+ )
+ }
}
}
}
@@ -281,6 +365,7 @@ private fun TvTextField(
value: String,
onValueChange: (String) -> Unit,
label: String,
+ isPassword: Boolean = false,
modifier: Modifier = Modifier
) {
var isFocused by remember { mutableStateOf(false) }
@@ -321,6 +406,7 @@ private fun TvTextField(
color = OnBackground
),
singleLine = true,
+ visualTransformation = if (isPassword) PasswordVisualTransformation() else VisualTransformation.None,
cursorBrush = androidx.compose.ui.graphics.SolidColor(Primary)
)
}
@@ -344,20 +430,24 @@ private fun ActionButton(
onClick = { if (enabled) onClick() },
modifier = Modifier
.fillMaxWidth()
- .height(48.dp)
+ .height(52.dp)
.scale(scale)
.onFocusChanged { isFocused = it.isFocused },
- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(8.dp)),
+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(10.dp)),
colors = ClickableSurfaceDefaults.colors(
containerColor = if (enabled) Primary else SurfaceHighlight,
focusedContainerColor = if (enabled) PrimaryVariant else SurfaceHighlight
+ ),
+ border = ClickableSurfaceDefaults.border(
+ border = Border(BorderStroke(1.dp, if (enabled) PrimaryDark else SurfaceHighlight)),
+ focusedBorder = Border(BorderStroke(2.dp, FocusBorder))
)
) {
Box(contentAlignment = Alignment.Center, modifier = Modifier.fillMaxSize()) {
Text(
text = text,
style = MaterialTheme.typography.bodyMedium,
- color = if (enabled) OnBackground else OnSurfaceDim
+ color = if (enabled) Color.White else OnSurfaceDim
)
}
}
@@ -366,6 +456,9 @@ private fun ActionButton(
@Composable
private fun FileSelectorCard(
fileName: String?,
+ fileSelectedHint: String,
+ emptySelectionTitle: String,
+ emptySelectionHint: String,
onClick: () -> Unit
) {
var isFocused by remember { mutableStateOf(false) }
@@ -403,18 +496,18 @@ private fun FileSelectorCard(
textAlign = TextAlign.Center
)
Text(
- text = "Click to change file",
+ text = fileSelectedHint,
style = MaterialTheme.typography.bodySmall,
color = OnSurfaceDim
)
} else {
Text(
- text = "Select M3U File",
+ text = emptySelectionTitle,
style = MaterialTheme.typography.bodyLarge,
- color = OnSurfaceDim
+ color = OnBackground
)
Text(
- text = "Browse local storage",
+ text = emptySelectionHint,
style = MaterialTheme.typography.bodySmall,
color = OnSurfaceDim
)
@@ -434,17 +527,62 @@ private fun TabButton(
Surface(
onClick = onClick,
modifier = Modifier.onFocusChanged { isFocused = it.isFocused },
- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(8.dp)),
+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(10.dp)),
colors = ClickableSurfaceDefaults.colors(
- containerColor = if (isSelected) Primary.copy(alpha = 0.2f) else SurfaceElevated,
+ containerColor = if (isSelected) Primary.copy(alpha = 0.2f) else Surface,
focusedContainerColor = SurfaceHighlight
+ ),
+ border = ClickableSurfaceDefaults.border(
+ border = Border(BorderStroke(1.dp, if (isSelected) Primary.copy(alpha = 0.4f) else SurfaceHighlight)),
+ focusedBorder = Border(BorderStroke(2.dp, FocusBorder))
)
) {
Text(
text = text,
style = MaterialTheme.typography.bodyMedium,
- color = if (isSelected) Primary else OnSurface,
+ color = if (isSelected) Primary else if (isFocused) TextPrimary else OnSurface,
modifier = Modifier.padding(horizontal = 24.dp, vertical = 10.dp)
)
}
}
+
+private fun cleanupOldImportedM3uFiles(
+ filesDir: java.io.File,
+ protectedFileUris: Set<String>,
+ keepLatest: Int
+) {
+ val protectedPaths = protectedFileUris
+ .mapNotNull { uri ->
+ uri.removePrefix("file://").takeIf { it.isNotBlank() }
+ }
+ .toSet()
+
+ val importedFiles = filesDir
+ .listFiles { file -> file.isFile && file.name.startsWith("m3u_") && file.name.endsWith(".m3u") }
+ ?.sortedByDescending { it.lastModified() }
+ ?: return
+
+ importedFiles
+ .drop(keepLatest)
+ .forEach { staleFile ->
+ if (staleFile.absolutePath !in protectedPaths) {
+ runCatching { staleFile.delete() }
+ }
+ }
+}
+
+private fun resolveFileImportError(
+ context: android.content.Context,
+ error: Throwable
+): String {
+ val message = error.message.orEmpty()
+ val isStorageFull = message.contains("ENOSPC", ignoreCase = true) ||
+ message.contains("no space", ignoreCase = true) ||
+ message.contains("space left", ignoreCase = true)
+
+ return if (isStorageFull) {
+ context.getString(R.string.setup_file_import_storage_full)
+ } else {
+ context.getString(R.string.setup_file_import_failed)
+ }
+}
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupViewModel.kt
index f84ad762..b8e1c6bf 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupViewModel.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupViewModel.kt
@@ -17,6 +17,8 @@ class ProviderSetupViewModel @Inject constructor(
private val _uiState = MutableStateFlow(ProviderSetupState())
val uiState: StateFlow<ProviderSetupState> = _uiState.asStateFlow()
+ private val _knownLocalM3uUrls = MutableStateFlow<Set<String>>(emptySet())
+ val knownLocalM3uUrls: StateFlow<Set<String>> = _knownLocalM3uUrls.asStateFlow()
init {
viewModelScope.launch {
@@ -26,6 +28,15 @@ class ProviderSetupViewModel @Inject constructor(
}
}
}
+ viewModelScope.launch {
+ providerRepository.getProviders().collect { providers ->
+ _knownLocalM3uUrls.value = providers
+ .mapNotNull { provider ->
+ provider.m3uUrl.takeIf { it.startsWith("file://") }
+ }
+ .toSet()
+ }
+ }
}
fun loadProvider(id: Long) {
@@ -39,7 +50,8 @@ class ProviderSetupViewModel @Inject constructor(
name = provider.name,
serverUrl = provider.serverUrl,
username = provider.username,
- password = provider.password,
+ // Do not prefill stored passwords back into UI.
+ password = "",
m3uUrl = provider.m3uUrl,
selectedTab = if (provider.type == ProviderType.M3U) 1 else 0,
m3uTab = if (provider.m3uUrl.startsWith("file://")) 1 else 0
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/search/SearchScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/search/SearchScreen.kt
index 0fc03890..71aeca80 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/search/SearchScreen.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/search/SearchScreen.kt
@@ -42,12 +42,14 @@ import com.streamvault.domain.repository.MovieRepository
import com.streamvault.domain.repository.ProviderRepository
import com.streamvault.domain.repository.SeriesRepository
import dagger.hilt.android.lifecycle.HiltViewModel
+import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.FlowPreview
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
+@OptIn(ExperimentalCoroutinesApi::class)
class SearchViewModel @Inject constructor(
private val providerRepository: ProviderRepository,
private val channelRepository: ChannelRepository,
@@ -55,6 +57,9 @@ class SearchViewModel @Inject constructor(
private val seriesRepository: SeriesRepository,
private val preferencesRepository: com.streamvault.data.preferences.PreferencesRepository
) : ViewModel() {
+ private companion object {
+ const val MAX_RESULTS_PER_SECTION = 120
+ }
private val _query = MutableStateFlow("")
val query: StateFlow<String> = _query.asStateFlow()
@@ -99,9 +104,9 @@ class SearchViewModel @Inject constructor(
seriesRepository.searchSeries(providerId, query) else flowOf(emptyList())
) { channels, movies, series ->
SearchUiState(
- channels = channels,
- movies = movies,
- series = series,
+ channels = channels.take(MAX_RESULTS_PER_SECTION),
+ movies = movies.take(MAX_RESULTS_PER_SECTION),
+ series = series.take(MAX_RESULTS_PER_SECTION),
isLoading = false,
hasSearched = true,
parentalControlLevel = level
@@ -119,7 +124,7 @@ class SearchViewModel @Inject constructor(
}
suspend fun verifyPin(pin: String): Boolean {
- return preferencesRepository.parentalPin.first() == pin
+ return preferencesRepository.verifyParentalPin(pin)
}
}
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesDetailViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesDetailViewModel.kt
index 522167b8..0ad25d7e 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesDetailViewModel.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesDetailViewModel.kt
@@ -46,8 +46,7 @@ class SeriesDetailViewModel @Inject constructor(
return@launch
}
- // Fetch details
- // seriesId from navigation is likely the 'series_id' from Xtream, which fits 'seriesId' in our repo call
+ // Fetch details (repository resolves remote provider IDs internally when needed).
val result = seriesRepository.getSeriesDetails(provider.id, seriesId)
when (result) {
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 91329803..0bc05633 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
@@ -121,7 +121,7 @@ class SeriesViewModel @Inject constructor(
}
suspend fun verifyPin(pin: String): Boolean {
- return preferencesRepository.parentalPin.first() == pin
+ return preferencesRepository.verifyParentalPin(pin)
}
fun onShowDialog(series: Series) {
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 6f842ba2..8fec3ac4 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
@@ -31,8 +31,11 @@ import com.streamvault.app.ui.components.dialogs.PinDialog
import com.streamvault.app.ui.components.TopNavBar
import com.streamvault.app.ui.theme.*
import com.streamvault.domain.model.Provider
+import com.streamvault.domain.model.ProviderType
+import com.streamvault.domain.model.ProviderStatus
import kotlinx.coroutines.launch
import androidx.compose.ui.res.stringResource
+import androidx.compose.ui.window.Dialog
import com.streamvault.app.R
@@ -128,6 +131,8 @@ fun SettingsScreen(
provider = provider,
isActive = provider.id == uiState.activeProviderId,
isSyncing = uiState.isSyncing,
+ syncWarnings = uiState.syncWarningsByProvider[provider.id].orEmpty(),
+ onRetryWarningAction = { action -> viewModel.retryWarningAction(provider.id, action) },
onConnect = { viewModel.setActiveProvider(provider.id) },
onRefresh = { viewModel.refreshProvider(provider.id) },
onDelete = { viewModel.deleteProvider(provider.id) },
@@ -391,92 +396,76 @@ fun SettingsScreen(
}
if (showLevelDialog) {
- AlertDialog(
- onDismissRequest = { showLevelDialog = false },
- title = { Text(stringResource(R.string.settings_select_level)) },
- text = {
- Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
- LevelOption(0, stringResource(R.string.settings_level_off_desc), uiState.parentalControlLevel) {
- viewModel.setParentalControlLevel(0)
- showLevelDialog = false
- }
- LevelOption(1, stringResource(R.string.settings_level_locked_desc), uiState.parentalControlLevel) {
- viewModel.setParentalControlLevel(1)
- showLevelDialog = false
- }
- LevelOption(2, stringResource(R.string.settings_level_hidden_desc), uiState.parentalControlLevel) {
- viewModel.setParentalControlLevel(2)
- showLevelDialog = false
- }
- }
- },
- confirmButton = {
- TextButton(onClick = { showLevelDialog = false }) {
- Text(stringResource(R.string.settings_cancel))
- }
+ PremiumSelectionDialog(
+ title = stringResource(R.string.settings_select_level),
+ onDismiss = { showLevelDialog = false }
+ ) {
+ LevelOption(0, stringResource(R.string.settings_level_off_desc), uiState.parentalControlLevel) {
+ viewModel.setParentalControlLevel(0)
+ showLevelDialog = false
}
- )
+ LevelOption(1, stringResource(R.string.settings_level_locked_desc), uiState.parentalControlLevel) {
+ viewModel.setParentalControlLevel(1)
+ showLevelDialog = false
+ }
+ LevelOption(2, stringResource(R.string.settings_level_hidden_desc), uiState.parentalControlLevel) {
+ viewModel.setParentalControlLevel(2)
+ showLevelDialog = false
+ }
+ }
}
if (showLanguageDialog) {
- AlertDialog(
- onDismissRequest = { showLanguageDialog = false },
- title = { Text(stringResource(R.string.settings_select_language)) },
- text = {
- Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
- LevelOption(
- level = 0,
- text = stringResource(R.string.settings_system_default),
- currentLevel = if (uiState.appLanguage == "system") 0 else -1,
- onSelect = {
- viewModel.setAppLanguage("system")
- showLanguageDialog = false
- }
- )
- LevelOption(
- level = 1,
- text = "English",
- currentLevel = if (uiState.appLanguage == "en") 1 else -1,
- onSelect = {
- viewModel.setAppLanguage("en")
- showLanguageDialog = false
- }
- )
- LevelOption(
- level = 2,
- text = "עברית (Hebrew)",
- currentLevel = if (uiState.appLanguage == "he") 2 else -1,
- onSelect = {
- viewModel.setAppLanguage("he")
- showLanguageDialog = false
- }
- )
- LevelOption(
- level = 3,
- text = "العربية (Arabic)",
- currentLevel = if (uiState.appLanguage == "ar") 3 else -1,
- onSelect = {
- viewModel.setAppLanguage("ar")
- showLanguageDialog = false
- }
- )
- LevelOption(
- level = 4,
- text = "Русский (Russian)",
- currentLevel = if (uiState.appLanguage == "ru") 4 else -1,
- onSelect = {
- viewModel.setAppLanguage("ru")
- showLanguageDialog = false
- }
- )
+ PremiumSelectionDialog(
+ title = stringResource(R.string.settings_select_language),
+ onDismiss = { showLanguageDialog = false }
+ ) {
+ LevelOption(
+ level = 0,
+ text = stringResource(R.string.settings_system_default),
+ currentLevel = if (uiState.appLanguage == "system") 0 else -1,
+ onSelect = {
+ viewModel.setAppLanguage("system")
+ showLanguageDialog = false
}
- },
- confirmButton = {
- TextButton(onClick = { showLanguageDialog = false }) {
- Text(stringResource(R.string.settings_cancel))
+ )
+ LevelOption(
+ level = 1,
+ text = "English",
+ currentLevel = if (uiState.appLanguage == "en") 1 else -1,
+ onSelect = {
+ viewModel.setAppLanguage("en")
+ showLanguageDialog = false
}
- }
- )
+ )
+ LevelOption(
+ level = 2,
+ text = "Hebrew",
+ currentLevel = if (uiState.appLanguage == "he") 2 else -1,
+ onSelect = {
+ viewModel.setAppLanguage("he")
+ showLanguageDialog = false
+ }
+ )
+ LevelOption(
+ level = 3,
+ text = "Arabic",
+ currentLevel = if (uiState.appLanguage == "ar") 3 else -1,
+ onSelect = {
+ viewModel.setAppLanguage("ar")
+ showLanguageDialog = false
+ }
+ )
+ LevelOption(
+ level = 4,
+ text = "Russian",
+ currentLevel = if (uiState.appLanguage == "ru") 4 else -1,
+ onSelect = {
+ viewModel.setAppLanguage("ru")
+ showLanguageDialog = false
+ }
+ )
+ }
}
}
}
@@ -485,6 +474,61 @@ private enum class ParentalAction {
ChangeLevel, ChangePin, SetNewPin
}
+@Composable
+private fun PremiumSelectionDialog(
+ title: String,
+ onDismiss: () -> Unit,
+ content: @Composable ColumnScope.() -> Unit
+) {
+ Dialog(onDismissRequest = onDismiss) {
+ androidx.compose.material3.Surface(
+ shape = RoundedCornerShape(14.dp),
+ color = SurfaceElevated,
+ modifier = Modifier
+ .fillMaxWidth(0.62f)
+ .border(1.dp, Primary.copy(alpha = 0.4f), RoundedCornerShape(14.dp))
+ ) {
+ Column(
+ modifier = Modifier.padding(18.dp),
+ verticalArrangement = Arrangement.spacedBy(8.dp)
+ ) {
+ Text(
+ text = title,
+ style = MaterialTheme.typography.titleMedium,
+ color = Primary
+ )
+ HorizontalDivider(color = Color.White.copy(alpha = 0.1f))
+ Column(
+ verticalArrangement = Arrangement.spacedBy(6.dp),
+ modifier = Modifier.padding(top = 6.dp)
+ ) {
+ content()
+ }
+ Row(
+ modifier = Modifier.fillMaxWidth().padding(top = 8.dp),
+ horizontalArrangement = Arrangement.End
+ ) {
+ Surface(
+ onClick = onDismiss,
+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(6.dp)),
+ colors = ClickableSurfaceDefaults.colors(
+ containerColor = Primary.copy(alpha = 0.2f),
+ focusedContainerColor = Primary.copy(alpha = 0.4f)
+ )
+ ) {
+ Text(
+ text = stringResource(R.string.settings_cancel),
+ style = MaterialTheme.typography.labelMedium,
+ color = Primary,
+ modifier = Modifier.padding(horizontal = 14.dp, vertical = 9.dp)
+ )
+ }
+ }
+ }
+ }
+ }
+}
+
@Composable
private fun LevelOption(level: Int, text: String, currentLevel: Int, onSelect: () -> Unit) {
Row(
@@ -499,8 +543,7 @@ private fun LevelOption(level: Int, text: String, currentLevel: Int, onSelect: (
onClick = onSelect
)
Spacer(modifier = Modifier.width(8.dp))
- // Explicitly use Black for dialog text as it likely has a light background
- Text(text, style = MaterialTheme.typography.bodyMedium, color = Color.Black)
+ Text(text, style = MaterialTheme.typography.bodyMedium, color = OnBackground)
}
}
@@ -590,6 +633,8 @@ private fun ProviderSettingsCard(
provider: Provider,
isActive: Boolean,
isSyncing: Boolean,
+ syncWarnings: List<String>,
+ onRetryWarningAction: (ProviderWarningAction) -> Unit,
onConnect: () -> Unit,
onRefresh: () -> Unit,
onDelete: () -> Unit,
@@ -626,11 +671,12 @@ private fun ProviderSettingsCard(
color = OnBackground
)
Text(
- text = "${provider.type.name} • ${provider.status.name}",
+ text = provider.type.name,
style = MaterialTheme.typography.bodySmall,
color = OnSurface
)
}
+ ProviderStatusBadge(status = provider.status)
if (isActive) {
Text(
text = stringResource(R.string.settings_active),
@@ -659,6 +705,75 @@ private fun ProviderSettingsCard(
color = if (expDate != null && expDate < System.currentTimeMillis() && expDate != Long.MAX_VALUE) ErrorColor else OnSurfaceDim
)
+ if (syncWarnings.isNotEmpty()) {
+ val hasEpgWarning = syncWarnings.any { it.contains("EPG", ignoreCase = true) }
+ val hasMoviesWarning = syncWarnings.any { it.contains("Movies", ignoreCase = true) }
+ val hasSeriesWarning = syncWarnings.any { it.contains("Series", ignoreCase = true) }
+
+ Text(
+ text = "Warnings: ${syncWarnings.take(3).joinToString(", ")}",
+ style = MaterialTheme.typography.bodySmall,
+ color = Secondary
+ )
+
+ Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ if (hasEpgWarning) {
+ Surface(
+ onClick = { onRetryWarningAction(ProviderWarningAction.EPG) },
+ enabled = !isSyncing,
+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(6.dp)),
+ colors = ClickableSurfaceDefaults.colors(
+ containerColor = Secondary.copy(alpha = 0.16f),
+ focusedContainerColor = Secondary.copy(alpha = 0.35f)
+ )
+ ) {
+ Text(
+ text = "Retry EPG",
+ style = MaterialTheme.typography.labelSmall,
+ color = Secondary,
+ modifier = Modifier.padding(horizontal = 10.dp, vertical = 8.dp)
+ )
+ }
+ }
+ if (hasMoviesWarning) {
+ Surface(
+ onClick = { onRetryWarningAction(ProviderWarningAction.MOVIES) },
+ enabled = !isSyncing,
+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(6.dp)),
+ colors = ClickableSurfaceDefaults.colors(
+ containerColor = Secondary.copy(alpha = 0.16f),
+ focusedContainerColor = Secondary.copy(alpha = 0.35f)
+ )
+ ) {
+ Text(
+ text = "Retry Movies",
+ style = MaterialTheme.typography.labelSmall,
+ color = Secondary,
+ modifier = Modifier.padding(horizontal = 10.dp, vertical = 8.dp)
+ )
+ }
+ }
+ if (hasSeriesWarning && provider.type == ProviderType.XTREAM_CODES) {
+ Surface(
+ onClick = { onRetryWarningAction(ProviderWarningAction.SERIES) },
+ enabled = !isSyncing,
+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(6.dp)),
+ colors = ClickableSurfaceDefaults.colors(
+ containerColor = Secondary.copy(alpha = 0.16f),
+ focusedContainerColor = Secondary.copy(alpha = 0.35f)
+ )
+ ) {
+ Text(
+ text = "Retry Series",
+ style = MaterialTheme.typography.labelSmall,
+ color = Secondary,
+ modifier = Modifier.padding(horizontal = 10.dp, vertical = 8.dp)
+ )
+ }
+ }
+ }
+ }
+
// Action buttons - each independently focusable for d-pad
Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {
if (!isActive) {
@@ -749,6 +864,28 @@ private fun ProviderSettingsCard(
}
}
+@Composable
+private fun ProviderStatusBadge(status: ProviderStatus) {
+ val (label, color) = when (status) {
+ ProviderStatus.ACTIVE -> "Active" to Primary
+ ProviderStatus.PARTIAL -> "Partial" to Secondary
+ ProviderStatus.ERROR -> "Error" to ErrorColor
+ ProviderStatus.EXPIRED -> "Expired" to ErrorColor
+ ProviderStatus.DISABLED -> "Disabled" to OnSurfaceDim
+ ProviderStatus.UNKNOWN -> "Unknown" to OnSurfaceDim
+ }
+
+ Text(
+ text = label,
+ style = MaterialTheme.typography.labelSmall,
+ color = color,
+ fontWeight = androidx.compose.ui.text.font.FontWeight.Bold,
+ modifier = Modifier
+ .background(color.copy(alpha = 0.16f), RoundedCornerShape(4.dp))
+ .padding(horizontal = 8.dp, vertical = 4.dp)
+ )
+}
+
@Composable
private fun SettingsRow(label: String, value: String) {
Row(
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 d14249da..2405bd16 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
@@ -3,8 +3,12 @@ package com.streamvault.app.ui.screens.settings
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.streamvault.data.preferences.PreferencesRepository
+import com.streamvault.data.sync.SyncManager
+import com.streamvault.data.sync.SyncRepairSection
import com.streamvault.domain.model.Provider
+import com.streamvault.domain.model.ProviderStatus
import com.streamvault.domain.model.Result
+import com.streamvault.domain.model.SyncState
import com.streamvault.domain.repository.ProviderRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.*
@@ -13,11 +17,18 @@ import javax.inject.Inject
import com.streamvault.domain.manager.BackupManager
+enum class ProviderWarningAction {
+ EPG,
+ MOVIES,
+ SERIES
+}
+
@HiltViewModel
class SettingsViewModel @Inject constructor(
private val providerRepository: ProviderRepository,
private val preferencesRepository: PreferencesRepository,
- private val backupManager: BackupManager
+ private val backupManager: BackupManager,
+ private val syncManager: SyncManager
) : ViewModel() {
private val _uiState = MutableStateFlow(SettingsUiState())
@@ -68,8 +79,7 @@ class SettingsViewModel @Inject constructor(
}
suspend fun verifyPin(pin: String): Boolean {
- val currentPin = preferencesRepository.parentalPin.firstOrNull() ?: "0000"
- return pin == currentPin
+ return preferencesRepository.verifyParentalPin(pin)
}
fun changePin(newPin: String) {
@@ -86,18 +96,73 @@ class SettingsViewModel @Inject constructor(
fun refreshProvider(providerId: Long) {
viewModelScope.launch {
_uiState.update { it.copy(isSyncing = true) }
- val result = providerRepository.refreshProviderData(providerId)
+ val result = providerRepository.refreshProviderData(providerId, force = true)
+ val refreshedProvider = providerRepository.getProvider(providerId)
_uiState.update { state ->
+ val partialWarnings = (syncManager.syncState.value as? SyncState.Partial)?.warnings.orEmpty()
+ val warningsMessage = partialWarnings
+ .take(3)
+ .joinToString(separator = ", ")
+ .ifBlank { "Some sections are incomplete." }
state.copy(
isSyncing = false,
- userMessage = if (result is Result.Error)
- "Refresh failed: ${result.message}"
- else "Provider refreshed successfully"
+ userMessage = when {
+ result is Result.Error -> "Refresh failed: ${result.message}"
+ refreshedProvider?.status == ProviderStatus.PARTIAL -> "Refresh completed with warnings: $warningsMessage"
+ else -> "Provider refreshed successfully"
+ },
+ syncWarningsByProvider = when {
+ result is Result.Error -> state.syncWarningsByProvider - providerId
+ refreshedProvider?.status == ProviderStatus.PARTIAL -> state.syncWarningsByProvider + (providerId to partialWarnings)
+ else -> state.syncWarningsByProvider - providerId
+ }
)
}
}
}
+ fun retryWarningAction(providerId: Long, action: ProviderWarningAction) {
+ viewModelScope.launch {
+ _uiState.update { it.copy(isSyncing = true) }
+ val section = when (action) {
+ ProviderWarningAction.EPG -> SyncRepairSection.EPG
+ ProviderWarningAction.MOVIES -> SyncRepairSection.MOVIES
+ ProviderWarningAction.SERIES -> SyncRepairSection.SERIES
+ }
+ val result = syncManager.retrySection(providerId, section)
+ _uiState.update { state ->
+ if (result is Result.Error) {
+ state.copy(
+ isSyncing = false,
+ userMessage = "Retry failed: ${result.message}"
+ )
+ } else {
+ val currentWarnings = state.syncWarningsByProvider[providerId].orEmpty()
+ val updatedWarnings = currentWarnings.filterNot { warning ->
+ when (action) {
+ ProviderWarningAction.EPG -> warning.contains("EPG", ignoreCase = true)
+ ProviderWarningAction.MOVIES -> warning.contains("Movies", ignoreCase = true)
+ ProviderWarningAction.SERIES -> warning.contains("Series", ignoreCase = true)
+ }
+ }
+ state.copy(
+ isSyncing = false,
+ userMessage = if (updatedWarnings.isEmpty()) {
+ "Section retry succeeded. All current warnings cleared."
+ } else {
+ "Section retry succeeded."
+ },
+ syncWarningsByProvider = if (updatedWarnings.isEmpty()) {
+ state.syncWarningsByProvider - providerId
+ } else {
+ state.syncWarningsByProvider + (providerId to updatedWarnings)
+ }
+ )
+ }
+ }
+ }
+ }
+
fun deleteProvider(providerId: Long) {
viewModelScope.launch {
providerRepository.deleteProvider(providerId)
@@ -144,6 +209,7 @@ data class SettingsUiState(
val activeProviderId: Long? = null,
val isSyncing: Boolean = false,
val userMessage: String? = null,
+ val syncWarningsByProvider: Map<Long, List<String>> = emptyMap(),
val parentalControlLevel: Int = 0,
val appLanguage: String = "system"
)
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/parental/ParentalControlGroupScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/parental/ParentalControlGroupScreen.kt
index 14b04710..a1eb4a2b 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/parental/ParentalControlGroupScreen.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/parental/ParentalControlGroupScreen.kt
@@ -17,10 +17,12 @@ import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import com.streamvault.app.ui.components.TopNavBar
import com.streamvault.domain.model.Category
+import com.streamvault.domain.model.ContentType
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.focus.FocusRequester
@@ -135,7 +137,7 @@ fun ParentalControlGroupScreen(
contentPadding = PaddingValues(16.dp),
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
- items(uiState.categories, key = { it.id }) { category ->
+ items(uiState.categories, key = { "${it.type.name}:${it.id}" }) { category ->
CategoryProtectionCard(
category = category,
onToggle = { viewModel.toggleCategoryProtection(category) }
@@ -161,8 +163,6 @@ fun CategoryProtectionCard(
val borderColor = if (isFocused) MaterialTheme.colorScheme.primary else Color.Transparent
val borderWidth = if (isFocused) 2.dp else 0.dp
- val backgroundColor = if (isFocused) MaterialTheme.colorScheme.surface else MaterialTheme.colorScheme.surfaceVariant
-
Surface(
onClick = {
if (!category.isAdult) {
@@ -196,22 +196,28 @@ fun CategoryProtectionCard(
.weight(1f)
.padding(end = 16.dp)
) {
+ Row(
+ verticalAlignment = Alignment.CenterVertically,
+ horizontalArrangement = Arrangement.spacedBy(10.dp)
+ ) {
+ TypeBadge(type = category.type)
+ if (category.isAdult) {
+ Text(
+ text = stringResource(R.string.parental_group_auto_protected),
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.error,
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis
+ )
+ }
+ }
Text(
text = category.name,
style = MaterialTheme.typography.titleMedium,
color = MaterialTheme.colorScheme.onSurface,
maxLines = 1,
- overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis
+ overflow = TextOverflow.Ellipsis
)
- if (category.isAdult) {
- Text(
- text = stringResource(R.string.parental_group_auto_protected),
- style = MaterialTheme.typography.bodySmall,
- color = MaterialTheme.colorScheme.error,
- maxLines = 1,
- overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis
- )
- }
}
androidx.compose.material3.Switch(
@@ -233,3 +239,26 @@ fun CategoryProtectionCard(
}
}
}
+
+@Composable
+private fun TypeBadge(type: ContentType) {
+ val label = when (type) {
+ ContentType.LIVE -> "Live"
+ ContentType.MOVIE -> "Movies"
+ ContentType.SERIES -> "Series"
+ ContentType.SERIES_EPISODE -> "Episodes"
+ }
+ Surface(
+ shape = MaterialTheme.shapes.small,
+ colors = SurfaceDefaults.colors(
+ containerColor = MaterialTheme.colorScheme.primaryContainer,
+ contentColor = MaterialTheme.colorScheme.onPrimaryContainer
+ )
+ ) {
+ Text(
+ text = label,
+ style = MaterialTheme.typography.labelSmall,
+ modifier = Modifier.padding(horizontal = 8.dp, vertical = 4.dp)
+ )
+ }
+}
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/parental/ParentalControlGroupViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/parental/ParentalControlGroupViewModel.kt
index ec67ad49..48e4fcf0 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/parental/ParentalControlGroupViewModel.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/parental/ParentalControlGroupViewModel.kt
@@ -59,7 +59,12 @@ class ParentalControlGroupViewModel @Inject constructor(
fun toggleCategoryProtection(category: Category) {
viewModelScope.launch {
- categoryRepository.setCategoryProtection(category.id, !category.isUserProtected)
+ categoryRepository.setCategoryProtection(
+ providerId = providerId,
+ categoryId = category.id,
+ type = category.type,
+ isProtected = !category.isUserProtected
+ )
}
}
}
diff --git a/app/src/main/java/com/streamvault/app/ui/theme/Color.kt b/app/src/main/java/com/streamvault/app/ui/theme/Color.kt
index a779ed3e..7e2292ec 100644
--- a/app/src/main/java/com/streamvault/app/ui/theme/Color.kt
+++ b/app/src/main/java/com/streamvault/app/ui/theme/Color.kt
@@ -2,53 +2,48 @@ package com.streamvault.app.ui.theme
import androidx.compose.ui.graphics.Color
-// ── Brand Primary — Deep Indigo-Violet ────────────────────────────
-val Primary = Color(0xFF6C63FF)
-val PrimaryLight = Color(0xFF9D97FF) // hover/pressed states
-val PrimaryVariant = PrimaryLight // legacy alias
-val PrimaryDark = Color(0xFF4A42DB)
-val PrimaryGlow = Color(0x336C63FF) // 20% opacity glow ring
-
-// ── TV-Optimized Backgrounds — Cinematic Depth ──────────────────
-val BackgroundDeep = Color(0xFF09090E) // Ultra Deep — behind everything
-val Background = Color(0xFF0D0D12) // Legacy alias fallback
-val Surface = Color(0xFF14141E) // Standard Card surfaces
-val SurfaceElevated = Color(0xFF1E1E2D) // Modals, overlays, sidebars
-val SurfaceHighlight = Color(0xFF2A2A3D) // Soft selection indication
-val SurfaceVariant = SurfaceElevated
-
-// ── TV-Optimized Text — Massive Readability ───────────────────────
-val TextPrimary = Color(0xFFFFFFFF) // Absolute White for core data
-val TextSecondary = Color(0xFFA0A0B0) // Sub-titles / descriptions
-val TextTertiary = Color(0xFF656575) // Low priority metadata
-val TextDisabled = Color(0xFF4A4A58) // Disabled states
-
-// Legacy aliases kept for compatibility
-val OnBackground = TextPrimary
-val OnSurface = TextSecondary
+// Broadcast-inspired premium palette with strong TV contrast.
+val Primary = Color(0xFF3E8BFF)
+val PrimaryLight = Color(0xFF74ABFF)
+val PrimaryVariant = PrimaryLight
+val PrimaryDark = Color(0xFF1F5EB6)
+val PrimaryGlow = Color(0x403E8BFF)
+
+val BackgroundDeep = Color(0xFF050A12)
+val Background = Color(0xFF09101A)
+val Surface = Color(0xFF111A27)
+val SurfaceElevated = Color(0xFF172233)
+val SurfaceHighlight = Color(0xFF263346)
+val SurfaceVariant = SurfaceElevated
+
+val TextPrimary = Color(0xFFF4F8FF)
+val TextSecondary = Color(0xFFB7C2D4)
+val TextTertiary = Color(0xFF8693A8)
+val TextDisabled = Color(0xFF5A6678)
+
+// Legacy aliases kept for compatibility.
+val OnBackground = TextPrimary
+val OnSurface = TextSecondary
val OnSurfaceVariant = TextSecondary
-val OnSurfaceDim = TextTertiary
-
-// ── Accents ────────────────────────────────────────────────────────
-val AccentRed = Color(0xFFFF4B6A) // Live indicator, errors
-val AccentGreen = Color(0xFF2DD881) // Success, online
-val AccentAmber = Color(0xFFFFA742) // Warnings, badges (Reorder drag)
-val AccentCyan = Color(0xFF00D4FF) // EPG progress, info
-
-// Legacy aliases
-val OnPrimary = Color(0xFFFFFFFF)
-val Secondary = Color(0xFF03DAC6)
-val ErrorColor = AccentRed
-val SuccessColor = AccentGreen
-val LiveIndicator = AccentRed
-val WarningColor = AccentAmber
-
-// ── Cinematic Gradient Overlays ───────────────────────────────────
-val GradientOverlayTop = Color(0x99050508) // 60% opacity for cleaner fade
-val GradientOverlayBottom = Color(0xE6050508) // 90% opacity for solid dark-read
-
-// ── TV Focus System ───────────────────────────────────────────────
-val FocusBorder = Color(0xFFF0F0F5) // HIGH CONTRAST WHITE for 10-foot legibility
-val CardBackground = Surface
-val ProgressBar = Primary
-val ProgressBarBackground = Color(0xFF1E1E2D)
+val OnSurfaceDim = TextTertiary
+
+val AccentRed = Color(0xFFFF4D5D)
+val AccentGreen = Color(0xFF43C98D)
+val AccentAmber = Color(0xFFFFBE55)
+val AccentCyan = Color(0xFF4FC8FF)
+
+// Legacy aliases.
+val OnPrimary = Color(0xFFFFFFFF)
+val Secondary = Color(0xFF63E2C9)
+val ErrorColor = AccentRed
+val SuccessColor = AccentGreen
+val LiveIndicator = AccentRed
+val WarningColor = AccentAmber
+
+val GradientOverlayTop = Color(0x99050A12)
+val GradientOverlayBottom = Color(0xE6050A12)
+
+val FocusBorder = Color(0xFFE9F2FF)
+val CardBackground = Surface
+val ProgressBar = Primary
+val ProgressBarBackground = Color(0xFF233145)
diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml
index 46e0920a..80f43fe6 100644
--- a/app/src/main/res/values/strings.xml
+++ b/app/src/main/res/values/strings.xml
@@ -158,6 +158,13 @@
<string name="setup_save">Save Changes</string>
<string name="setup_login">Login</string>
<string name="setup_m3u_hint">M3U URL</string>
+ <string name="setup_tab_url">URL</string>
+ <string name="setup_tab_file">File</string>
+ <string name="setup_file_replace_hint">Press to replace file</string>
+ <string name="setup_file_select_title">Select M3U File</string>
+ <string name="setup_file_browse_hint">Browse local storage or USB</string>
+ <string name="setup_file_import_failed">Could not import playlist file. Please try again.</string>
+ <string name="setup_file_import_storage_full">Storage is full. Free up space and try importing again.</string>
<string name="setup_validating">Validating...</string>
<string name="setup_add">Add Playlist</string>
@@ -173,6 +180,8 @@
<string name="player_type_movie">Movie</string>
<string name="player_type_series">Series</string>
<string name="player_close">Close</string>
+ <string name="player_play">Play</string>
+ <string name="player_pause">Pause</string>
<string name="player_next">NEXT</string>
<string name="player_restart">Restart</string>
<string name="player_archive">Archive</string>
@@ -186,6 +195,21 @@
<string name="player_track_subs">Select Subtitles</string>
<string name="player_track_off">Off</string>
<string name="player_video_quality">Video Quality</string>
+ <string name="player_aspect_ratio_label">Aspect %1$s</string>
+ <string name="player_selected">Selected</string>
+ <string name="player_channel_list_title">Channels (%1$d)</string>
+ <string name="player_channel_selected">Now</string>
+ <string name="player_archive_badge">ARCHIVE</string>
+ <string name="player_catchup_badge">CATCH-UP</string>
+ <string name="player_time_range_minutes">%1$s - %2$s | %3$d min</string>
+ <string name="player_next_label">Next:</string>
+ <string name="player_full_epg">Full EPG</string>
+ <string name="player_stats">Stats</string>
+ <string name="player_minutes_remaining">%1$d min remaining</string>
+ <string name="epg_title">TV Guide</string>
+ <string name="epg_catchup_available">Catch-up available (%1$d days)</string>
+ <string name="epg_upcoming_schedule">Upcoming Schedule</string>
+ <string name="epg_no_info">No EPG information</string>
<!-- Parental Control Group -->
<string name="parental_group_title">Protected Groups</string>
diff --git a/app/src/main/res/xml/network_security_config.xml b/app/src/main/res/xml/network_security_config.xml
new file mode 100644
index 00000000..c18e0e4e
--- /dev/null
+++ b/app/src/main/res/xml/network_security_config.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="utf-8"?>
+<network-security-config>
+ <!-- IPTV providers often expose HTTP-only endpoints; keep behavior explicit. -->
+ <base-config cleartextTrafficPermitted="true" />
+</network-security-config>
diff --git a/app/src/test/java/com/streamvault/app/ui/screens/home/HomeViewModelTest.kt b/app/src/test/java/com/streamvault/app/ui/screens/home/HomeViewModelTest.kt
index 69b9965e..e7f3eb0e 100644
--- a/app/src/test/java/com/streamvault/app/ui/screens/home/HomeViewModelTest.kt
+++ b/app/src/test/java/com/streamvault/app/ui/screens/home/HomeViewModelTest.kt
@@ -101,6 +101,6 @@ class HomeViewModelTest {
val state = viewModel.uiState.value
assertThat(state.selectedCategory).isEqualTo(category)
- verify(parentalControlManager).clearUnlockedCategories()
+ verify(parentalControlManager).clearUnlockedCategories(anyOrNull())
}
}
diff --git a/data/build.gradle.kts b/data/build.gradle.kts
index 8ef3ced8..741c0c73 100644
--- a/data/build.gradle.kts
+++ b/data/build.gradle.kts
@@ -75,4 +75,11 @@ dependencies {
testImplementation(libs.kxml2)
// Mocking for SyncManagerTest
testImplementation(libs.mockito.kotlin)
+
+ // Android instrumentation tests
+ androidTestImplementation("androidx.room:room-testing:2.6.1")
+ androidTestImplementation("androidx.test:runner:1.6.2")
+ androidTestImplementation("androidx.test.ext:junit:1.2.1")
+ androidTestImplementation(libs.truth)
+ androidTestImplementation(libs.coroutines.test)
}
diff --git a/data/schemas/com.streamvault.data.local.StreamVaultDatabase/10.json b/data/schemas/com.streamvault.data.local.StreamVaultDatabase/10.json
new file mode 100644
index 00000000..910a35ab
--- /dev/null
+++ b/data/schemas/com.streamvault.data.local.StreamVaultDatabase/10.json
@@ -0,0 +1,1451 @@
+{
+ "formatVersion": 1,
+ "database": {
+ "version": 10,
+ "identityHash": "0cd2cff8beb878ba0b1ffce358469af5",
+ "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, `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",
+ "notNull": false
+ },
+ {
+ "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`)"
+ }
+ ],
+ "foreignKeys": []
+ },
+ {
+ "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)",
+ "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",
+ "notNull": false
+ },
+ {
+ "fieldPath": "groupTitle",
+ "columnName": "group_title",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "categoryId",
+ "columnName": "category_id",
+ "affinity": "INTEGER",
+ "notNull": false
+ },
+ {
+ "fieldPath": "categoryName",
+ "columnName": "category_name",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "streamUrl",
+ "columnName": "stream_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "epgChannelId",
+ "columnName": "epg_channel_id",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "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",
+ "notNull": false
+ },
+ {
+ "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
+ }
+ ],
+ "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`)"
+ }
+ ],
+ "foreignKeys": []
+ },
+ {
+ "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": "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": []
+ },
+ "indices": [],
+ "foreignKeys": []
+ },
+ {
+ "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)",
+ "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",
+ "notNull": false
+ },
+ {
+ "fieldPath": "backdropUrl",
+ "columnName": "backdrop_url",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "categoryId",
+ "columnName": "category_id",
+ "affinity": "INTEGER",
+ "notNull": false
+ },
+ {
+ "fieldPath": "categoryName",
+ "columnName": "category_name",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "streamUrl",
+ "columnName": "stream_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "containerExtension",
+ "columnName": "container_extension",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "plot",
+ "columnName": "plot",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "cast",
+ "columnName": "cast",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "director",
+ "columnName": "director",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "genre",
+ "columnName": "genre",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "releaseDate",
+ "columnName": "release_date",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "duration",
+ "columnName": "duration",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "durationSeconds",
+ "columnName": "duration_seconds",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "rating",
+ "columnName": "rating",
+ "affinity": "REAL",
+ "notNull": true
+ },
+ {
+ "fieldPath": "year",
+ "columnName": "year",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "tmdbId",
+ "columnName": "tmdb_id",
+ "affinity": "INTEGER",
+ "notNull": false
+ },
+ {
+ "fieldPath": "youtubeTrailer",
+ "columnName": "youtube_trailer",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "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_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": []
+ },
+ {
+ "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": "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": []
+ },
+ "indices": [],
+ "foreignKeys": []
+ },
+ {
+ "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)",
+ "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",
+ "notNull": false
+ },
+ {
+ "fieldPath": "backdropUrl",
+ "columnName": "backdrop_url",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "categoryId",
+ "columnName": "category_id",
+ "affinity": "INTEGER",
+ "notNull": false
+ },
+ {
+ "fieldPath": "categoryName",
+ "columnName": "category_name",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "plot",
+ "columnName": "plot",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "cast",
+ "columnName": "cast",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "director",
+ "columnName": "director",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "genre",
+ "columnName": "genre",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "releaseDate",
+ "columnName": "release_date",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "rating",
+ "columnName": "rating",
+ "affinity": "REAL",
+ "notNull": true
+ },
+ {
+ "fieldPath": "tmdbId",
+ "columnName": "tmdb_id",
+ "affinity": "INTEGER",
+ "notNull": false
+ },
+ {
+ "fieldPath": "youtubeTrailer",
+ "columnName": "youtube_trailer",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "episodeRunTime",
+ "columnName": "episode_run_time",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "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
+ }
+ ],
+ "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": []
+ },
+ {
+ "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": "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": []
+ },
+ "indices": [],
+ "foreignKeys": []
+ },
+ {
+ "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)",
+ "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",
+ "notNull": false
+ },
+ {
+ "fieldPath": "coverUrl",
+ "columnName": "cover_url",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "plot",
+ "columnName": "plot",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "duration",
+ "columnName": "duration",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "durationSeconds",
+ "columnName": "duration_seconds",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "rating",
+ "columnName": "rating",
+ "affinity": "REAL",
+ "notNull": true
+ },
+ {
+ "fieldPath": "releaseDate",
+ "columnName": "release_date",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "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": []
+ },
+ {
+ "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)",
+ "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",
+ "notNull": false
+ },
+ {
+ "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
+ }
+ ],
+ "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_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": []
+ },
+ {
+ "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, `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": "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_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`)"
+ }
+ ],
+ "foreignKeys": []
+ },
+ {
+ "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)",
+ "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",
+ "notNull": false
+ },
+ {
+ "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": []
+ },
+ {
+ "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",
+ "notNull": false
+ },
+ {
+ "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`)"
+ }
+ ],
+ "foreignKeys": []
+ },
+ {
+ "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, `series_id` INTEGER, `season_number` INTEGER, `episode_number` INTEGER)",
+ "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",
+ "notNull": false
+ },
+ {
+ "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": "seriesId",
+ "columnName": "series_id",
+ "affinity": "INTEGER",
+ "notNull": false
+ },
+ {
+ "fieldPath": "seasonNumber",
+ "columnName": "season_number",
+ "affinity": "INTEGER",
+ "notNull": false
+ },
+ {
+ "fieldPath": "episodeNumber",
+ "columnName": "episode_number",
+ "affinity": "INTEGER",
+ "notNull": false
+ }
+ ],
+ "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": []
+ },
+ {
+ "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, `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, PRIMARY KEY(`provider_id`))",
+ "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": "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
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "provider_id"
+ ]
+ },
+ "indices": [],
+ "foreignKeys": []
+ }
+ ],
+ "views": [],
+ "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, '0cd2cff8beb878ba0b1ffce358469af5')"
+ ]
+ }
+}
\ No newline at end of file
diff --git a/data/schemas/com.streamvault.data.local.StreamVaultDatabase/8.json b/data/schemas/com.streamvault.data.local.StreamVaultDatabase/8.json
new file mode 100644
index 00000000..0d9e77f8
--- /dev/null
+++ b/data/schemas/com.streamvault.data.local.StreamVaultDatabase/8.json
@@ -0,0 +1,1346 @@
+{
+ "formatVersion": 1,
+ "database": {
+ "version": 8,
+ "identityHash": "445807544db812de77496d3e86906a38",
+ "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, `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",
+ "notNull": false
+ },
+ {
+ "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`)"
+ }
+ ],
+ "foreignKeys": []
+ },
+ {
+ "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)",
+ "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",
+ "notNull": false
+ },
+ {
+ "fieldPath": "groupTitle",
+ "columnName": "group_title",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "categoryId",
+ "columnName": "category_id",
+ "affinity": "INTEGER",
+ "notNull": false
+ },
+ {
+ "fieldPath": "categoryName",
+ "columnName": "category_name",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "streamUrl",
+ "columnName": "stream_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "epgChannelId",
+ "columnName": "epg_channel_id",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "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",
+ "notNull": false
+ },
+ {
+ "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
+ }
+ ],
+ "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`)"
+ }
+ ],
+ "foreignKeys": []
+ },
+ {
+ "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)",
+ "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",
+ "notNull": false
+ },
+ {
+ "fieldPath": "backdropUrl",
+ "columnName": "backdrop_url",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "categoryId",
+ "columnName": "category_id",
+ "affinity": "INTEGER",
+ "notNull": false
+ },
+ {
+ "fieldPath": "categoryName",
+ "columnName": "category_name",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "streamUrl",
+ "columnName": "stream_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "containerExtension",
+ "columnName": "container_extension",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "plot",
+ "columnName": "plot",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "cast",
+ "columnName": "cast",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "director",
+ "columnName": "director",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "genre",
+ "columnName": "genre",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "releaseDate",
+ "columnName": "release_date",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "duration",
+ "columnName": "duration",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "durationSeconds",
+ "columnName": "duration_seconds",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "rating",
+ "columnName": "rating",
+ "affinity": "REAL",
+ "notNull": true
+ },
+ {
+ "fieldPath": "year",
+ "columnName": "year",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "tmdbId",
+ "columnName": "tmdb_id",
+ "affinity": "INTEGER",
+ "notNull": false
+ },
+ {
+ "fieldPath": "youtubeTrailer",
+ "columnName": "youtube_trailer",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "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_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": []
+ },
+ {
+ "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)",
+ "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",
+ "notNull": false
+ },
+ {
+ "fieldPath": "backdropUrl",
+ "columnName": "backdrop_url",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "categoryId",
+ "columnName": "category_id",
+ "affinity": "INTEGER",
+ "notNull": false
+ },
+ {
+ "fieldPath": "categoryName",
+ "columnName": "category_name",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "plot",
+ "columnName": "plot",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "cast",
+ "columnName": "cast",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "director",
+ "columnName": "director",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "genre",
+ "columnName": "genre",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "releaseDate",
+ "columnName": "release_date",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "rating",
+ "columnName": "rating",
+ "affinity": "REAL",
+ "notNull": true
+ },
+ {
+ "fieldPath": "tmdbId",
+ "columnName": "tmdb_id",
+ "affinity": "INTEGER",
+ "notNull": false
+ },
+ {
+ "fieldPath": "youtubeTrailer",
+ "columnName": "youtube_trailer",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "episodeRunTime",
+ "columnName": "episode_run_time",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "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
+ }
+ ],
+ "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": []
+ },
+ {
+ "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)",
+ "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",
+ "notNull": false
+ },
+ {
+ "fieldPath": "coverUrl",
+ "columnName": "cover_url",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "plot",
+ "columnName": "plot",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "duration",
+ "columnName": "duration",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "durationSeconds",
+ "columnName": "duration_seconds",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "rating",
+ "columnName": "rating",
+ "affinity": "REAL",
+ "notNull": true
+ },
+ {
+ "fieldPath": "releaseDate",
+ "columnName": "release_date",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "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": []
+ },
+ {
+ "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)",
+ "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",
+ "notNull": false
+ },
+ {
+ "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
+ }
+ ],
+ "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_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": []
+ },
+ {
+ "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, `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": "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_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`)"
+ }
+ ],
+ "foreignKeys": []
+ },
+ {
+ "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)",
+ "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",
+ "notNull": false
+ },
+ {
+ "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": []
+ },
+ {
+ "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",
+ "notNull": false
+ },
+ {
+ "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`)"
+ }
+ ],
+ "foreignKeys": []
+ },
+ {
+ "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, `series_id` INTEGER, `season_number` INTEGER, `episode_number` INTEGER)",
+ "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",
+ "notNull": false
+ },
+ {
+ "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": "seriesId",
+ "columnName": "series_id",
+ "affinity": "INTEGER",
+ "notNull": false
+ },
+ {
+ "fieldPath": "seasonNumber",
+ "columnName": "season_number",
+ "affinity": "INTEGER",
+ "notNull": false
+ },
+ {
+ "fieldPath": "episodeNumber",
+ "columnName": "episode_number",
+ "affinity": "INTEGER",
+ "notNull": false
+ }
+ ],
+ "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": []
+ },
+ {
+ "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, `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, PRIMARY KEY(`provider_id`))",
+ "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": "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
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "provider_id"
+ ]
+ },
+ "indices": [],
+ "foreignKeys": []
+ }
+ ],
+ "views": [],
+ "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, '445807544db812de77496d3e86906a38')"
+ ]
+ }
+}
\ No newline at end of file
diff --git a/data/schemas/com.streamvault.data.local.StreamVaultDatabase/9.json b/data/schemas/com.streamvault.data.local.StreamVaultDatabase/9.json
new file mode 100644
index 00000000..a8157bd2
--- /dev/null
+++ b/data/schemas/com.streamvault.data.local.StreamVaultDatabase/9.json
@@ -0,0 +1,1346 @@
+{
+ "formatVersion": 1,
+ "database": {
+ "version": 9,
+ "identityHash": "445807544db812de77496d3e86906a38",
+ "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, `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",
+ "notNull": false
+ },
+ {
+ "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`)"
+ }
+ ],
+ "foreignKeys": []
+ },
+ {
+ "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)",
+ "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",
+ "notNull": false
+ },
+ {
+ "fieldPath": "groupTitle",
+ "columnName": "group_title",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "categoryId",
+ "columnName": "category_id",
+ "affinity": "INTEGER",
+ "notNull": false
+ },
+ {
+ "fieldPath": "categoryName",
+ "columnName": "category_name",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "streamUrl",
+ "columnName": "stream_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "epgChannelId",
+ "columnName": "epg_channel_id",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "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",
+ "notNull": false
+ },
+ {
+ "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
+ }
+ ],
+ "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`)"
+ }
+ ],
+ "foreignKeys": []
+ },
+ {
+ "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)",
+ "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",
+ "notNull": false
+ },
+ {
+ "fieldPath": "backdropUrl",
+ "columnName": "backdrop_url",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "categoryId",
+ "columnName": "category_id",
+ "affinity": "INTEGER",
+ "notNull": false
+ },
+ {
+ "fieldPath": "categoryName",
+ "columnName": "category_name",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "streamUrl",
+ "columnName": "stream_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "containerExtension",
+ "columnName": "container_extension",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "plot",
+ "columnName": "plot",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "cast",
+ "columnName": "cast",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "director",
+ "columnName": "director",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "genre",
+ "columnName": "genre",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "releaseDate",
+ "columnName": "release_date",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "duration",
+ "columnName": "duration",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "durationSeconds",
+ "columnName": "duration_seconds",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "rating",
+ "columnName": "rating",
+ "affinity": "REAL",
+ "notNull": true
+ },
+ {
+ "fieldPath": "year",
+ "columnName": "year",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "tmdbId",
+ "columnName": "tmdb_id",
+ "affinity": "INTEGER",
+ "notNull": false
+ },
+ {
+ "fieldPath": "youtubeTrailer",
+ "columnName": "youtube_trailer",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "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_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": []
+ },
+ {
+ "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)",
+ "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",
+ "notNull": false
+ },
+ {
+ "fieldPath": "backdropUrl",
+ "columnName": "backdrop_url",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "categoryId",
+ "columnName": "category_id",
+ "affinity": "INTEGER",
+ "notNull": false
+ },
+ {
+ "fieldPath": "categoryName",
+ "columnName": "category_name",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "plot",
+ "columnName": "plot",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "cast",
+ "columnName": "cast",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "director",
+ "columnName": "director",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "genre",
+ "columnName": "genre",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "releaseDate",
+ "columnName": "release_date",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "rating",
+ "columnName": "rating",
+ "affinity": "REAL",
+ "notNull": true
+ },
+ {
+ "fieldPath": "tmdbId",
+ "columnName": "tmdb_id",
+ "affinity": "INTEGER",
+ "notNull": false
+ },
+ {
+ "fieldPath": "youtubeTrailer",
+ "columnName": "youtube_trailer",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "episodeRunTime",
+ "columnName": "episode_run_time",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "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
+ }
+ ],
+ "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": []
+ },
+ {
+ "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)",
+ "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",
+ "notNull": false
+ },
+ {
+ "fieldPath": "coverUrl",
+ "columnName": "cover_url",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "plot",
+ "columnName": "plot",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "duration",
+ "columnName": "duration",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "fieldPath": "durationSeconds",
+ "columnName": "duration_seconds",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "rating",
+ "columnName": "rating",
+ "affinity": "REAL",
+ "notNull": true
+ },
+ {
+ "fieldPath": "releaseDate",
+ "columnName": "release_date",
+ "affinity": "TEXT",
+ "notNull": false
+ },
+ {
+ "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": []
+ },
+ {
+ "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)",
+ "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",
+ "notNull": false
+ },
+ {
+ "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
+ }
+ ],
+ "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_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": []
+ },
+ {
+ "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, `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": "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_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`)"
+ }
+ ],
+ "foreignKeys": []
+ },
+ {
+ "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)",
+ "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",
+ "notNull": false
+ },
+ {
+ "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": []
+ },
+ {
+ "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",
+ "notNull": false
+ },
+ {
+ "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`)"
+ }
+ ],
+ "foreignKeys": []
+ },
+ {
+ "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, `series_id` INTEGER, `season_number` INTEGER, `episode_number` INTEGER)",
+ "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",
+ "notNull": false
+ },
+ {
+ "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": "seriesId",
+ "columnName": "series_id",
+ "affinity": "INTEGER",
+ "notNull": false
+ },
+ {
+ "fieldPath": "seasonNumber",
+ "columnName": "season_number",
+ "affinity": "INTEGER",
+ "notNull": false
+ },
+ {
+ "fieldPath": "episodeNumber",
+ "columnName": "episode_number",
+ "affinity": "INTEGER",
+ "notNull": false
+ }
+ ],
+ "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": []
+ },
+ {
+ "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, `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, PRIMARY KEY(`provider_id`))",
+ "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": "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
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "provider_id"
+ ]
+ },
+ "indices": [],
+ "foreignKeys": []
+ }
+ ],
+ "views": [],
+ "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, '445807544db812de77496d3e86906a38')"
+ ]
+ }
+}
\ No newline at end of file
diff --git a/data/src/androidTest/java/com/streamvault/data/local/ProgramDaoTest.kt b/data/src/androidTest/java/com/streamvault/data/local/ProgramDaoTest.kt
index 542656a1..5a4b66af 100644
--- a/data/src/androidTest/java/com/streamvault/data/local/ProgramDaoTest.kt
+++ b/data/src/androidTest/java/com/streamvault/data/local/ProgramDaoTest.kt
@@ -38,6 +38,7 @@ class ProgramDaoTest {
@Test
fun writeProgramsAndReadInList() = runTest {
val program = ProgramEntity(
+ providerId = 1L,
channelId = "channel1",
title = "Test Program",
description = "Test Desc",
@@ -47,7 +48,7 @@ class ProgramDaoTest {
hasArchive = false
)
programDao.insertAll(listOf(program))
- val byChannel = programDao.getForChannel("channel1", 500L, 2500L).first()
+ val byChannel = programDao.getForChannel(1L, "channel1", 500L, 2500L).first()
assertThat(byChannel).hasSize(1)
assertThat(byChannel[0].title).isEqualTo("Test Program")
}
@@ -55,12 +56,14 @@ class ProgramDaoTest {
@Test
fun deleteOldPrograms() = runTest {
val program1 = ProgramEntity(
+ providerId = 1L,
channelId = "channel1",
title = "Old Program",
startTime = 100L,
endTime = 500L
)
val program2 = ProgramEntity(
+ providerId = 1L,
channelId = "channel1",
title = "New Program",
startTime = 1000L,
@@ -71,7 +74,7 @@ class ProgramDaoTest {
// Delete older than 800L
programDao.deleteOld(800L)
- val all = programDao.getForChannel("channel1", 0L, 2000L).first()
+ val all = programDao.getForChannel(1L, "channel1", 0L, 2000L).first()
assertThat(all).hasSize(1)
assertThat(all[0].title).isEqualTo("New Program")
}
@@ -79,18 +82,21 @@ class ProgramDaoTest {
@Test
fun getNowPlayingForChannels() = runTest {
val program1 = ProgramEntity(
+ providerId = 1L,
channelId = "channel1",
title = "Now Playing 1",
startTime = 1000L,
endTime = 2000L
)
val program2 = ProgramEntity(
+ providerId = 1L,
channelId = "channel2",
title = "Now Playing 2",
startTime = 1500L,
endTime = 2500L
)
val program3 = ProgramEntity(
+ providerId = 1L,
channelId = "channel2",
title = "Next Playing 2",
startTime = 2500L,
@@ -99,12 +105,12 @@ class ProgramDaoTest {
programDao.insertAll(listOf(program1, program2, program3))
// Check around time 1600L
- val nowPlaying = programDao.getNowPlayingForChannels(listOf("channel1", "channel2"), 1600L).first()
+ val nowPlaying = programDao.getNowPlayingForChannels(1L, listOf("channel1", "channel2"), 1600L).first()
assertThat(nowPlaying).hasSize(2)
assertThat(nowPlaying.map { it.title }).containsExactly("Now Playing 1", "Now Playing 2")
// Check around time 2200L
- val laterPlaying = programDao.getNowPlayingForChannels(listOf("channel1", "channel2"), 2200L).first()
+ val laterPlaying = programDao.getNowPlayingForChannels(1L, listOf("channel1", "channel2"), 2200L).first()
assertThat(laterPlaying).hasSize(1)
assertThat(laterPlaying[0].title).isEqualTo("Now Playing 2")
}
diff --git a/data/src/androidTest/java/com/streamvault/data/local/StreamVaultDatabaseMigrationTest.kt b/data/src/androidTest/java/com/streamvault/data/local/StreamVaultDatabaseMigrationTest.kt
new file mode 100644
index 00000000..5b51a94a
--- /dev/null
+++ b/data/src/androidTest/java/com/streamvault/data/local/StreamVaultDatabaseMigrationTest.kt
@@ -0,0 +1,97 @@
+package com.streamvault.data.local
+
+import androidx.room.testing.MigrationTestHelper
+import androidx.sqlite.db.framework.FrameworkSQLiteOpenHelperFactory
+import androidx.test.ext.junit.runners.AndroidJUnit4
+import androidx.test.platform.app.InstrumentationRegistry
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Rule
+import org.junit.Test
+import org.junit.runner.RunWith
+
+@RunWith(AndroidJUnit4::class)
+class StreamVaultDatabaseMigrationTest {
+
+ private val testDbName = "streamvault-migration-test"
+
+ @get:Rule
+ val migrationTestHelper: MigrationTestHelper = MigrationTestHelper(
+ InstrumentationRegistry.getInstrumentation(),
+ StreamVaultDatabase::class.java,
+ emptyList(),
+ FrameworkSQLiteOpenHelperFactory()
+ )
+
+ @Test
+ fun migrate9To10_createsBackfillsAndMaintainsFtsTables() {
+ migrationTestHelper.createDatabase(testDbName, 9).apply {
+ execSQL(
+ """
+ INSERT INTO channels (
+ stream_id, name, stream_url, number, catch_up_supported, catch_up_days,
+ provider_id, is_adult, is_user_protected, logical_group_id, error_count
+ ) VALUES (1001, 'News One', 'http://test/live/news', 101, 0, 0, 1, 0, 0, '', 0)
+ """.trimIndent()
+ )
+ execSQL(
+ """
+ INSERT INTO movies (
+ stream_id, name, stream_url, duration_seconds, rating, provider_id,
+ watch_progress, last_watched_at, is_adult, is_user_protected
+ ) VALUES (2001, 'Movie Alpha', 'http://test/movie/alpha', 7200, 7.5, 1, 0, 0, 0, 0)
+ """.trimIndent()
+ )
+ execSQL(
+ """
+ INSERT INTO series (
+ series_id, name, rating, last_modified, provider_id, is_adult, is_user_protected
+ ) VALUES (3001, 'Series Prime', 8.1, 0, 1, 0, 0)
+ """.trimIndent()
+ )
+ close()
+ }
+
+ val migratedDb = migrationTestHelper.runMigrationsAndValidate(
+ testDbName,
+ 10,
+ true,
+ StreamVaultDatabase.MIGRATION_9_10
+ )
+
+ assertEquals(1, countRows(migratedDb, "SELECT COUNT(*) FROM channels_fts WHERE channels_fts MATCH 'news*'"))
+ assertEquals(1, countRows(migratedDb, "SELECT COUNT(*) FROM movies_fts WHERE movies_fts MATCH 'movie*'"))
+ assertEquals(1, countRows(migratedDb, "SELECT COUNT(*) FROM series_fts WHERE series_fts MATCH 'series*'"))
+
+ migratedDb.execSQL(
+ """
+ INSERT INTO channels (
+ stream_id, name, stream_url, number, catch_up_supported, catch_up_days,
+ provider_id, is_adult, is_user_protected, logical_group_id, error_count
+ ) VALUES (1002, 'Sports Arena', 'http://test/live/sports', 102, 0, 0, 1, 0, 0, '', 0)
+ """.trimIndent()
+ )
+ assertEquals(1, countRows(migratedDb, "SELECT COUNT(*) FROM channels_fts WHERE channels_fts MATCH 'sports*'"))
+
+ migratedDb.execSQL("UPDATE channels SET name = 'Sports Central' WHERE stream_id = 1002")
+ assertEquals(1, countRows(migratedDb, "SELECT COUNT(*) FROM channels_fts WHERE channels_fts MATCH 'central*'"))
+
+ migratedDb.execSQL("DELETE FROM channels WHERE stream_id = 1002")
+ assertFalse(exists(migratedDb, "SELECT 1 FROM channels_fts WHERE channels_fts MATCH 'central*'"))
+
+ migratedDb.close()
+ }
+
+ private fun countRows(db: androidx.sqlite.db.SupportSQLiteDatabase, sql: String): Int {
+ db.query(sql).use { cursor ->
+ if (!cursor.moveToFirst()) return 0
+ return cursor.getInt(0)
+ }
+ }
+
+ private fun exists(db: androidx.sqlite.db.SupportSQLiteDatabase, sql: String): Boolean {
+ db.query(sql).use { cursor ->
+ return cursor.moveToFirst()
+ }
+ }
+}
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 88de3fdc..54eccf0d 100644
--- a/data/src/main/java/com/streamvault/data/local/StreamVaultDatabase.kt
+++ b/data/src/main/java/com/streamvault/data/local/StreamVaultDatabase.kt
@@ -11,8 +11,11 @@ import com.streamvault.data.local.entity.*
entities = [
ProviderEntity::class,
ChannelEntity::class,
+ ChannelFtsEntity::class,
MovieEntity::class,
+ MovieFtsEntity::class,
SeriesEntity::class,
+ SeriesFtsEntity::class,
EpisodeEntity::class,
CategoryEntity::class,
ProgramEntity::class,
@@ -21,7 +24,7 @@ import com.streamvault.data.local.entity.*
PlaybackHistoryEntity::class,
SyncMetadataEntity::class
],
- version = 7,
+ version = 10,
exportSchema = true // ← was false; schema JSON now tracked in version control
)
abstract class StreamVaultDatabase : RoomDatabase() {
@@ -145,5 +148,426 @@ abstract class StreamVaultDatabase : RoomDatabase() {
database.execSQL("CREATE INDEX IF NOT EXISTS index_channels_logical_group_id ON channels(logical_group_id)")
}
}
+
+ val MIGRATION_7_8 = object : Migration(7, 8) {
+ override fun migrate(database: SupportSQLiteDatabase) {
+ database.execSQL("ALTER TABLE programs ADD COLUMN provider_id INTEGER NOT NULL DEFAULT 0")
+ database.execSQL("DROP INDEX IF EXISTS index_programs_channel_id")
+ database.execSQL("DROP INDEX IF EXISTS index_programs_channel_id_start_time")
+ database.execSQL("CREATE INDEX IF NOT EXISTS index_programs_provider_id ON programs(provider_id)")
+ database.execSQL("CREATE INDEX IF NOT EXISTS index_programs_provider_id_channel_id ON programs(provider_id, channel_id)")
+ database.execSQL("CREATE INDEX IF NOT EXISTS index_programs_provider_id_channel_id_start_time ON programs(provider_id, channel_id, start_time)")
+ database.execSQL(
+ "CREATE UNIQUE INDEX IF NOT EXISTS index_programs_provider_id_channel_id_start_time_end_time " +
+ "ON programs(provider_id, channel_id, start_time, end_time)"
+ )
+ }
+ }
+
+ val MIGRATION_8_9 = object : Migration(8, 9) {
+ override fun migrate(database: SupportSQLiteDatabase) {
+ // Rebuild media tables to normalize legacy local IDs and keep only provider-scoped remote IDs as remote keys.
+ // This preserves user-facing references by remapping favorites/history through temporary ID maps.
+
+ // Channels
+ database.execSQL(
+ """
+ CREATE TABLE IF NOT EXISTS channels_new (
+ id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
+ stream_id INTEGER NOT NULL,
+ name TEXT NOT NULL,
+ logo_url TEXT,
+ group_title TEXT,
+ category_id INTEGER,
+ category_name TEXT,
+ stream_url TEXT NOT NULL,
+ epg_channel_id TEXT,
+ number INTEGER NOT NULL,
+ catch_up_supported INTEGER NOT NULL,
+ catch_up_days INTEGER NOT NULL,
+ catchUpSource TEXT,
+ provider_id INTEGER NOT NULL,
+ is_adult INTEGER NOT NULL,
+ is_user_protected INTEGER NOT NULL,
+ logical_group_id TEXT NOT NULL,
+ error_count INTEGER NOT NULL
+ )
+ """.trimIndent()
+ )
+ database.execSQL(
+ """
+ INSERT INTO channels_new (
+ stream_id, name, logo_url, group_title, category_id, category_name, stream_url,
+ epg_channel_id, number, catch_up_supported, catch_up_days, catchUpSource,
+ provider_id, is_adult, is_user_protected, logical_group_id, error_count
+ )
+ SELECT
+ stream_id, name, logo_url, group_title, category_id, category_name, stream_url,
+ epg_channel_id, number, catch_up_supported, catch_up_days, catchUpSource,
+ provider_id, is_adult, is_user_protected, logical_group_id, error_count
+ FROM channels
+ """.trimIndent()
+ )
+ database.execSQL("CREATE TEMP TABLE channel_id_map(old_id INTEGER PRIMARY KEY NOT NULL, new_id INTEGER NOT NULL)")
+ database.execSQL(
+ """
+ INSERT INTO channel_id_map(old_id, new_id)
+ SELECT old.id, new.id
+ FROM channels old
+ JOIN channels_new new
+ ON new.provider_id = old.provider_id
+ AND new.stream_id = old.stream_id
+ """.trimIndent()
+ )
+ database.execSQL(
+ """
+ UPDATE favorites
+ SET content_id = (SELECT new_id FROM channel_id_map WHERE old_id = content_id)
+ WHERE content_type = 'LIVE'
+ AND content_id IN (SELECT old_id FROM channel_id_map)
+ """.trimIndent()
+ )
+ database.execSQL(
+ """
+ UPDATE playback_history
+ SET content_id = (SELECT new_id FROM channel_id_map WHERE old_id = content_id)
+ WHERE content_type = 'LIVE'
+ AND content_id IN (SELECT old_id FROM channel_id_map)
+ """.trimIndent()
+ )
+ database.execSQL("DROP TABLE channels")
+ database.execSQL("ALTER TABLE channels_new RENAME TO channels")
+ database.execSQL("CREATE INDEX IF NOT EXISTS index_channels_provider_id ON channels(provider_id)")
+ database.execSQL("CREATE INDEX IF NOT EXISTS index_channels_provider_id_category_id ON channels(provider_id, category_id)")
+ database.execSQL("CREATE UNIQUE INDEX IF NOT EXISTS index_channels_provider_id_stream_id ON channels(provider_id, stream_id)")
+ database.execSQL("CREATE INDEX IF NOT EXISTS index_channels_logical_group_id ON channels(logical_group_id)")
+ database.execSQL("DROP TABLE channel_id_map")
+
+ // Movies
+ database.execSQL(
+ """
+ CREATE TABLE IF NOT EXISTS movies_new (
+ id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
+ stream_id INTEGER NOT NULL,
+ name TEXT NOT NULL,
+ poster_url TEXT,
+ backdrop_url TEXT,
+ category_id INTEGER,
+ category_name TEXT,
+ stream_url TEXT NOT NULL,
+ container_extension TEXT,
+ plot TEXT,
+ cast TEXT,
+ director TEXT,
+ genre TEXT,
+ release_date TEXT,
+ duration TEXT,
+ duration_seconds INTEGER NOT NULL,
+ rating REAL NOT NULL,
+ year TEXT,
+ tmdb_id INTEGER,
+ youtube_trailer TEXT,
+ provider_id INTEGER NOT NULL,
+ watch_progress INTEGER NOT NULL,
+ last_watched_at INTEGER NOT NULL,
+ is_adult INTEGER NOT NULL,
+ is_user_protected INTEGER NOT NULL
+ )
+ """.trimIndent()
+ )
+ database.execSQL(
+ """
+ INSERT INTO movies_new (
+ stream_id, name, poster_url, backdrop_url, category_id, category_name, stream_url,
+ container_extension, plot, cast, director, genre, release_date, duration, duration_seconds,
+ rating, year, tmdb_id, youtube_trailer, provider_id, watch_progress, last_watched_at,
+ is_adult, is_user_protected
+ )
+ SELECT
+ stream_id, name, poster_url, backdrop_url, category_id, category_name, stream_url,
+ container_extension, plot, cast, director, genre, release_date, duration, duration_seconds,
+ rating, year, tmdb_id, youtube_trailer, provider_id, watch_progress, last_watched_at,
+ is_adult, is_user_protected
+ FROM movies
+ """.trimIndent()
+ )
+ database.execSQL("CREATE TEMP TABLE movie_id_map(old_id INTEGER PRIMARY KEY NOT NULL, new_id INTEGER NOT NULL)")
+ database.execSQL(
+ """
+ INSERT INTO movie_id_map(old_id, new_id)
+ SELECT old.id, new.id
+ FROM movies old
+ JOIN movies_new new
+ ON new.provider_id = old.provider_id
+ AND new.stream_id = old.stream_id
+ """.trimIndent()
+ )
+ database.execSQL(
+ """
+ UPDATE favorites
+ SET content_id = (SELECT new_id FROM movie_id_map WHERE old_id = content_id)
+ WHERE content_type = 'MOVIE'
+ AND content_id IN (SELECT old_id FROM movie_id_map)
+ """.trimIndent()
+ )
+ database.execSQL(
+ """
+ UPDATE playback_history
+ SET content_id = (SELECT new_id FROM movie_id_map WHERE old_id = content_id)
+ WHERE content_type = 'MOVIE'
+ AND content_id IN (SELECT old_id FROM movie_id_map)
+ """.trimIndent()
+ )
+ database.execSQL("DROP TABLE movies")
+ database.execSQL("ALTER TABLE movies_new RENAME TO movies")
+ database.execSQL("CREATE INDEX IF NOT EXISTS index_movies_provider_id ON movies(provider_id)")
+ database.execSQL("CREATE INDEX IF NOT EXISTS index_movies_provider_id_category_id ON movies(provider_id, category_id)")
+ database.execSQL("CREATE UNIQUE INDEX IF NOT EXISTS index_movies_provider_id_stream_id ON movies(provider_id, stream_id)")
+ database.execSQL("DROP TABLE movie_id_map")
+
+ // Series
+ database.execSQL(
+ """
+ CREATE TABLE IF NOT EXISTS series_new (
+ id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
+ series_id INTEGER NOT NULL,
+ name TEXT NOT NULL,
+ poster_url TEXT,
+ backdrop_url TEXT,
+ category_id INTEGER,
+ category_name TEXT,
+ plot TEXT,
+ cast TEXT,
+ director TEXT,
+ genre TEXT,
+ release_date TEXT,
+ rating REAL NOT NULL,
+ tmdb_id INTEGER,
+ youtube_trailer TEXT,
+ episode_run_time TEXT,
+ last_modified INTEGER NOT NULL,
+ provider_id INTEGER NOT NULL,
+ is_adult INTEGER NOT NULL,
+ is_user_protected INTEGER NOT NULL
+ )
+ """.trimIndent()
+ )
+ database.execSQL(
+ """
+ INSERT INTO series_new (
+ series_id, name, poster_url, backdrop_url, category_id, category_name, plot, cast,
+ director, genre, release_date, rating, tmdb_id, youtube_trailer, episode_run_time,
+ last_modified, provider_id, is_adult, is_user_protected
+ )
+ SELECT
+ series_id, name, poster_url, backdrop_url, category_id, category_name, plot, cast,
+ director, genre, release_date, rating, tmdb_id, youtube_trailer, episode_run_time,
+ last_modified, provider_id, is_adult, is_user_protected
+ FROM series
+ """.trimIndent()
+ )
+ database.execSQL("CREATE TEMP TABLE series_id_map(old_id INTEGER PRIMARY KEY NOT NULL, new_id INTEGER NOT NULL)")
+ database.execSQL(
+ """
+ INSERT INTO series_id_map(old_id, new_id)
+ SELECT old.id, new.id
+ FROM series old
+ JOIN series_new new
+ ON new.provider_id = old.provider_id
+ AND new.series_id = old.series_id
+ """.trimIndent()
+ )
+ database.execSQL(
+ """
+ UPDATE favorites
+ SET content_id = (SELECT new_id FROM series_id_map WHERE old_id = content_id)
+ WHERE content_type = 'SERIES'
+ AND content_id IN (SELECT old_id FROM series_id_map)
+ """.trimIndent()
+ )
+ database.execSQL(
+ """
+ UPDATE playback_history
+ SET content_id = (SELECT new_id FROM series_id_map WHERE old_id = content_id)
+ WHERE content_type = 'SERIES'
+ AND content_id IN (SELECT old_id FROM series_id_map)
+ """.trimIndent()
+ )
+ database.execSQL(
+ """
+ UPDATE playback_history
+ SET series_id = (SELECT new_id FROM series_id_map WHERE old_id = series_id)
+ WHERE series_id IS NOT NULL
+ AND series_id IN (SELECT old_id FROM series_id_map)
+ """.trimIndent()
+ )
+ database.execSQL(
+ """
+ UPDATE episodes
+ SET series_id = (SELECT new_id FROM series_id_map WHERE old_id = series_id)
+ WHERE series_id IN (SELECT old_id FROM series_id_map)
+ """.trimIndent()
+ )
+ database.execSQL("DROP TABLE series")
+ database.execSQL("ALTER TABLE series_new RENAME TO series")
+ database.execSQL("CREATE INDEX IF NOT EXISTS index_series_provider_id ON series(provider_id)")
+ database.execSQL("CREATE INDEX IF NOT EXISTS index_series_provider_id_category_id ON series(provider_id, category_id)")
+ database.execSQL("CREATE UNIQUE INDEX IF NOT EXISTS index_series_provider_id_series_id ON series(provider_id, series_id)")
+ database.execSQL("DROP TABLE series_id_map")
+
+ // Episodes
+ database.execSQL(
+ """
+ CREATE TABLE IF NOT EXISTS episodes_new (
+ id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
+ episode_id INTEGER NOT NULL,
+ title TEXT NOT NULL,
+ episode_number INTEGER NOT NULL,
+ season_number INTEGER NOT NULL,
+ stream_url TEXT NOT NULL,
+ container_extension TEXT,
+ cover_url TEXT,
+ plot TEXT,
+ duration TEXT,
+ duration_seconds INTEGER NOT NULL,
+ rating REAL NOT NULL,
+ release_date TEXT,
+ series_id INTEGER NOT NULL,
+ provider_id INTEGER NOT NULL,
+ watch_progress INTEGER NOT NULL,
+ last_watched_at INTEGER NOT NULL,
+ is_adult INTEGER NOT NULL,
+ is_user_protected INTEGER NOT NULL
+ )
+ """.trimIndent()
+ )
+ database.execSQL(
+ """
+ INSERT INTO episodes_new (
+ episode_id, title, episode_number, season_number, stream_url, container_extension, cover_url,
+ plot, duration, duration_seconds, rating, release_date, series_id, provider_id, watch_progress,
+ last_watched_at, is_adult, is_user_protected
+ )
+ SELECT
+ episode_id, title, episode_number, season_number, stream_url, container_extension, cover_url,
+ plot, duration, duration_seconds, rating, release_date, series_id, provider_id, watch_progress,
+ last_watched_at, is_adult, is_user_protected
+ FROM episodes
+ """.trimIndent()
+ )
+ database.execSQL("CREATE TEMP TABLE episode_id_map(old_id INTEGER PRIMARY KEY NOT NULL, new_id INTEGER NOT NULL)")
+ database.execSQL(
+ """
+ INSERT INTO episode_id_map(old_id, new_id)
+ SELECT old.id, new.id
+ FROM episodes old
+ JOIN episodes_new new
+ ON new.provider_id = old.provider_id
+ AND new.episode_id = old.episode_id
+ """.trimIndent()
+ )
+ database.execSQL(
+ """
+ UPDATE playback_history
+ SET content_id = (SELECT new_id FROM episode_id_map WHERE old_id = content_id)
+ WHERE content_type = 'SERIES_EPISODE'
+ AND content_id IN (SELECT old_id FROM episode_id_map)
+ """.trimIndent()
+ )
+ database.execSQL("DROP TABLE episodes")
+ database.execSQL("ALTER TABLE episodes_new RENAME TO episodes")
+ database.execSQL("CREATE INDEX IF NOT EXISTS index_episodes_series_id ON episodes(series_id)")
+ database.execSQL("CREATE INDEX IF NOT EXISTS index_episodes_provider_id ON episodes(provider_id)")
+ database.execSQL("CREATE UNIQUE INDEX IF NOT EXISTS index_episodes_provider_id_episode_id ON episodes(provider_id, episode_id)")
+ database.execSQL("DROP TABLE episode_id_map")
+ }
+ }
+
+ val MIGRATION_9_10 = object : Migration(9, 10) {
+ override fun migrate(database: SupportSQLiteDatabase) {
+ database.execSQL("CREATE VIRTUAL TABLE IF NOT EXISTS channels_fts USING fts4(name, content='channels')")
+ database.execSQL("CREATE VIRTUAL TABLE IF NOT EXISTS movies_fts USING fts4(name, content='movies')")
+ database.execSQL("CREATE VIRTUAL TABLE IF NOT EXISTS series_fts USING fts4(name, content='series')")
+
+ database.execSQL("INSERT INTO channels_fts(rowid, name) SELECT id, name FROM channels")
+ database.execSQL("INSERT INTO movies_fts(rowid, name) SELECT id, name FROM movies")
+ database.execSQL("INSERT INTO series_fts(rowid, name) SELECT id, name FROM series")
+
+ database.execSQL(
+ """
+ CREATE TRIGGER IF NOT EXISTS channels_ai
+ AFTER INSERT ON channels BEGIN
+ INSERT INTO channels_fts(rowid, name) VALUES (new.id, new.name);
+ END
+ """.trimIndent()
+ )
+ database.execSQL(
+ """
+ CREATE TRIGGER IF NOT EXISTS channels_ad
+ AFTER DELETE ON channels BEGIN
+ DELETE FROM channels_fts WHERE rowid = old.id;
+ END
+ """.trimIndent()
+ )
+ database.execSQL(
+ """
+ CREATE TRIGGER IF NOT EXISTS channels_au
+ AFTER UPDATE OF name ON channels BEGIN
+ UPDATE channels_fts SET name = new.name WHERE rowid = old.id;
+ END
+ """.trimIndent()
+ )
+
+ database.execSQL(
+ """
+ CREATE TRIGGER IF NOT EXISTS movies_ai
+ AFTER INSERT ON movies BEGIN
+ INSERT INTO movies_fts(rowid, name) VALUES (new.id, new.name);
+ END
+ """.trimIndent()
+ )
+ database.execSQL(
+ """
+ CREATE TRIGGER IF NOT EXISTS movies_ad
+ AFTER DELETE ON movies BEGIN
+ DELETE FROM movies_fts WHERE rowid = old.id;
+ END
+ """.trimIndent()
+ )
+ database.execSQL(
+ """
+ CREATE TRIGGER IF NOT EXISTS movies_au
+ AFTER UPDATE OF name ON movies BEGIN
+ UPDATE movies_fts SET name = new.name WHERE rowid = old.id;
+ END
+ """.trimIndent()
+ )
+
+ database.execSQL(
+ """
+ CREATE TRIGGER IF NOT EXISTS series_ai
+ AFTER INSERT ON series BEGIN
+ INSERT INTO series_fts(rowid, name) VALUES (new.id, new.name);
+ END
+ """.trimIndent()
+ )
+ database.execSQL(
+ """
+ CREATE TRIGGER IF NOT EXISTS series_ad
+ AFTER DELETE ON series BEGIN
+ DELETE FROM series_fts WHERE rowid = old.id;
+ END
+ """.trimIndent()
+ )
+ database.execSQL(
+ """
+ CREATE TRIGGER IF NOT EXISTS series_au
+ AFTER UPDATE OF name ON series BEGIN
+ UPDATE series_fts SET name = new.name WHERE rowid = old.id;
+ END
+ """.trimIndent()
+ )
+ }
+ }
}
}
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 00e181b6..30e9b236 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
@@ -4,6 +4,11 @@ import androidx.room.*
import com.streamvault.data.local.entity.*
import kotlinx.coroutines.flow.Flow
+data class RemoteIdMapping(
+ @ColumnInfo(name = "id") val id: Long,
+ @ColumnInfo(name = "remote_id") val remoteId: Long
+)
+
@Dao
interface ProviderDao {
@Query("SELECT * FROM providers ORDER BY created_at DESC")
@@ -48,7 +53,16 @@ interface ChannelDao {
@Query("SELECT * FROM channels WHERE provider_id = :providerId AND category_id = :categoryId ORDER BY number ASC")
fun getByCategory(providerId: Long, categoryId: Long): Flow<List<ChannelEntity>>
- @Query("SELECT * FROM channels WHERE provider_id = :providerId AND name LIKE '%' || :query || '%' ORDER BY name ASC")
+ @Query(
+ """
+ SELECT c.* FROM channels c
+ JOIN channels_fts ON c.id = channels_fts.rowid
+ WHERE c.provider_id = :providerId
+ AND channels_fts MATCH :query
+ ORDER BY c.name ASC
+ LIMIT 300
+ """
+ )
fun search(providerId: Long, query: String): Flow<List<ChannelEntity>>
@Query("SELECT * FROM channels WHERE id = :id")
@@ -57,13 +71,20 @@ interface ChannelDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertAll(channels: List<ChannelEntity>)
+ @Query("SELECT id, stream_id AS remote_id FROM channels WHERE provider_id = :providerId")
+ suspend fun getIdMappings(providerId: Long): List<RemoteIdMapping>
+
@Query("DELETE FROM channels WHERE provider_id = :providerId")
suspend fun deleteByProvider(providerId: Long)
@Transaction
suspend fun replaceAll(providerId: Long, channels: List<ChannelEntity>) {
+ val existingByRemoteId = getIdMappings(providerId).associate { it.remoteId to it.id }
+ val remapped = channels
+ .distinctBy { it.streamId }
+ .map { entity -> entity.copy(id = existingByRemoteId[entity.streamId] ?: 0L) }
deleteByProvider(providerId)
- insertAll(channels)
+ insertAll(remapped)
}
@Query("SELECT * FROM channels WHERE id IN (:ids)")
@@ -75,8 +96,8 @@ interface ChannelDao {
@Query("SELECT COUNT(*) FROM channels WHERE provider_id = :providerId")
fun getCount(providerId: Long): Flow<Int>
- @Query("UPDATE channels SET is_user_protected = :isProtected WHERE category_id = :categoryId")
- suspend fun updateProtectionStatus(categoryId: Long, isProtected: Boolean)
+ @Query("UPDATE channels SET is_user_protected = :isProtected WHERE provider_id = :providerId AND category_id = :categoryId")
+ suspend fun updateProtectionStatus(providerId: Long, categoryId: Long, isProtected: Boolean)
@Query("UPDATE channels SET error_count = error_count + 1 WHERE id = :id")
suspend fun incrementErrorCount(id: Long)
@@ -93,18 +114,33 @@ interface MovieDao {
@Query("SELECT * FROM movies WHERE provider_id = :providerId AND category_id = :categoryId ORDER BY name ASC")
fun getByCategory(providerId: Long, categoryId: Long): Flow<List<MovieEntity>>
- @Query("SELECT * FROM movies WHERE provider_id = :providerId AND name LIKE '%' || :query || '%' ORDER BY name ASC")
+ @Query(
+ """
+ SELECT m.* FROM movies m
+ JOIN movies_fts ON m.id = movies_fts.rowid
+ WHERE m.provider_id = :providerId
+ AND movies_fts MATCH :query
+ ORDER BY m.name ASC
+ LIMIT 300
+ """
+ )
fun search(providerId: Long, query: String): Flow<List<MovieEntity>>
@Query("SELECT * FROM movies WHERE id = :id")
suspend fun getById(id: Long): MovieEntity?
+ @Query("SELECT * FROM movies WHERE id IN (:ids)")
+ fun getByIds(ids: List<Long>): Flow<List<MovieEntity>>
+
@Query("SELECT * FROM movies WHERE provider_id = :providerId AND stream_id = :streamId")
suspend fun getByStreamId(providerId: Long, streamId: Long): MovieEntity?
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertAll(movies: List<MovieEntity>)
+ @Query("SELECT id, stream_id AS remote_id FROM movies WHERE provider_id = :providerId")
+ suspend fun getIdMappings(providerId: Long): List<RemoteIdMapping>
+
@Update
suspend fun update(movie: MovieEntity)
@@ -132,8 +168,12 @@ interface MovieDao {
@Transaction
suspend fun replaceAll(providerId: Long, movies: List<MovieEntity>) {
+ val existingByRemoteId = getIdMappings(providerId).associate { it.remoteId to it.id }
+ val remapped = movies
+ .distinctBy { it.streamId }
+ .map { entity -> entity.copy(id = existingByRemoteId[entity.streamId] ?: 0L) }
deleteByProvider(providerId)
- insertAll(movies)
+ insertAll(remapped)
restoreWatchProgress(providerId)
}
@@ -143,8 +183,8 @@ interface MovieDao {
@Query("SELECT COUNT(*) FROM movies WHERE provider_id = :providerId")
fun getCount(providerId: Long): Flow<Int>
- @Query("UPDATE movies SET is_user_protected = :isProtected WHERE category_id = :categoryId")
- suspend fun updateProtectionStatus(categoryId: Long, isProtected: Boolean)
+ @Query("UPDATE movies SET is_user_protected = :isProtected WHERE provider_id = :providerId AND category_id = :categoryId")
+ suspend fun updateProtectionStatus(providerId: Long, categoryId: Long, isProtected: Boolean)
}
@Dao
@@ -155,22 +195,47 @@ interface SeriesDao {
@Query("SELECT * FROM series WHERE provider_id = :providerId AND category_id = :categoryId ORDER BY name ASC")
fun getByCategory(providerId: Long, categoryId: Long): Flow<List<SeriesEntity>>
- @Query("SELECT * FROM series WHERE provider_id = :providerId AND name LIKE '%' || :query || '%' ORDER BY name ASC")
+ @Query(
+ """
+ SELECT s.* FROM series s
+ JOIN series_fts ON s.id = series_fts.rowid
+ WHERE s.provider_id = :providerId
+ AND series_fts MATCH :query
+ ORDER BY s.name ASC
+ LIMIT 300
+ """
+ )
fun search(providerId: Long, query: String): Flow<List<SeriesEntity>>
@Query("SELECT * FROM series WHERE id = :id")
suspend fun getById(id: Long): SeriesEntity?
+ @Query("SELECT * FROM series WHERE id IN (:ids)")
+ fun getByIds(ids: List<Long>): Flow<List<SeriesEntity>>
+
+ @Query("SELECT * FROM series WHERE provider_id = :providerId AND series_id = :seriesId LIMIT 1")
+ suspend fun getBySeriesId(providerId: Long, seriesId: Long): SeriesEntity?
+
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertAll(series: List<SeriesEntity>)
+ @Update
+ suspend fun update(series: SeriesEntity)
+
+ @Query("SELECT id, series_id AS remote_id FROM series WHERE provider_id = :providerId")
+ suspend fun getIdMappings(providerId: Long): List<RemoteIdMapping>
+
@Query("DELETE FROM series WHERE provider_id = :providerId")
suspend fun deleteByProvider(providerId: Long)
@Transaction
suspend fun replaceAll(providerId: Long, series: List<SeriesEntity>) {
+ val existingByRemoteId = getIdMappings(providerId).associate { it.remoteId to it.id }
+ val remapped = series
+ .distinctBy { it.seriesId }
+ .map { entity -> entity.copy(id = existingByRemoteId[entity.seriesId] ?: 0L) }
deleteByProvider(providerId)
- insertAll(series)
+ insertAll(remapped)
}
@Query("SELECT category_id, COUNT(*) as item_count FROM series WHERE provider_id = :providerId AND category_id IS NOT NULL GROUP BY category_id")
@@ -179,8 +244,8 @@ interface SeriesDao {
@Query("SELECT COUNT(*) FROM series WHERE provider_id = :providerId")
fun getCount(providerId: Long): Flow<Int>
- @Query("UPDATE series SET is_user_protected = :isProtected WHERE category_id = :categoryId")
- suspend fun updateProtectionStatus(categoryId: Long, isProtected: Boolean)
+ @Query("UPDATE series SET is_user_protected = :isProtected WHERE provider_id = :providerId AND category_id = :categoryId")
+ suspend fun updateProtectionStatus(providerId: Long, categoryId: Long, isProtected: Boolean)
}
@@ -189,12 +254,18 @@ interface EpisodeDao {
@Query("SELECT * FROM episodes WHERE series_id = :seriesId ORDER BY season_number ASC, episode_number ASC")
fun getBySeries(seriesId: Long): Flow<List<EpisodeEntity>>
+ @Query("SELECT * FROM episodes WHERE series_id = :seriesId ORDER BY season_number ASC, episode_number ASC")
+ suspend fun getBySeriesSync(seriesId: Long): List<EpisodeEntity>
+
@Query("SELECT * FROM episodes WHERE id = :id")
suspend fun getById(id: Long): EpisodeEntity?
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertAll(episodes: List<EpisodeEntity>)
+ @Query("SELECT id, episode_id AS remote_id FROM episodes WHERE provider_id = :providerId AND series_id = :seriesId")
+ suspend fun getIdMappings(providerId: Long, seriesId: Long): List<RemoteIdMapping>
+
@Query("UPDATE episodes SET watch_progress = :progress, last_watched_at = :timestamp WHERE id = :id")
suspend fun updateWatchProgress(id: Long, progress: Long, timestamp: Long = System.currentTimeMillis())
@@ -218,9 +289,13 @@ interface EpisodeDao {
suspend fun restoreWatchProgress(seriesId: Long)
@Transaction
- suspend fun replaceAll(seriesId: Long, episodes: List<EpisodeEntity>) {
+ suspend fun replaceAll(seriesId: Long, providerId: Long, episodes: List<EpisodeEntity>) {
+ val existingByRemoteId = getIdMappings(providerId, seriesId).associate { it.remoteId to it.id }
+ val remapped = episodes
+ .distinctBy { it.episodeId }
+ .map { entity -> entity.copy(id = existingByRemoteId[entity.episodeId] ?: 0L) }
deleteBySeries(seriesId)
- insertAll(episodes)
+ insertAll(remapped)
restoreWatchProgress(seriesId)
}
}
@@ -242,20 +317,20 @@ interface CategoryDao {
insertAll(categories)
}
- @Query("UPDATE categories SET is_user_protected = :isProtected WHERE category_id = :categoryId")
- suspend fun updateProtectionStatus(categoryId: Long, isProtected: Boolean)
+ @Query("UPDATE categories SET is_user_protected = :isProtected WHERE provider_id = :providerId AND category_id = :categoryId AND type = :type")
+ suspend fun updateProtectionStatus(providerId: Long, categoryId: Long, type: String, isProtected: Boolean)
}
@Dao
interface ProgramDao {
- @Query("SELECT * FROM programs WHERE channel_id = :channelId AND start_time >= :startTime AND end_time <= :endTime ORDER BY start_time ASC")
- fun getForChannel(channelId: String, startTime: Long, endTime: Long): Flow<List<ProgramEntity>>
+ @Query("SELECT * FROM programs WHERE provider_id = :providerId AND channel_id = :channelId AND start_time >= :startTime AND end_time <= :endTime ORDER BY start_time ASC")
+ fun getForChannel(providerId: Long, channelId: String, startTime: Long, endTime: Long): Flow<List<ProgramEntity>>
- @Query("SELECT * FROM programs WHERE channel_id = :channelId AND start_time <= :now AND end_time > :now LIMIT 1")
- fun getNowPlaying(channelId: String, now: Long = System.currentTimeMillis()): Flow<ProgramEntity?>
+ @Query("SELECT * FROM programs WHERE provider_id = :providerId AND channel_id = :channelId AND start_time <= :now AND end_time > :now LIMIT 1")
+ fun getNowPlaying(providerId: Long, channelId: String, now: Long = System.currentTimeMillis()): Flow<ProgramEntity?>
- @Query("SELECT * FROM programs WHERE channel_id IN (:channelIds) AND start_time <= :now AND end_time > :now")
- fun getNowPlayingForChannels(channelIds: List<String>, now: Long = System.currentTimeMillis()): Flow<List<ProgramEntity>>
+ @Query("SELECT * FROM programs WHERE provider_id = :providerId AND channel_id IN (:channelIds) AND start_time <= :now AND end_time > :now")
+ fun getNowPlayingForChannels(providerId: Long, channelIds: List<String>, now: Long = System.currentTimeMillis()): Flow<List<ProgramEntity>>
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertAll(programs: List<ProgramEntity>)
@@ -263,8 +338,11 @@ interface ProgramDao {
@Query("DELETE FROM programs WHERE end_time < :beforeTime")
suspend fun deleteOld(beforeTime: Long)
- @Query("DELETE FROM programs WHERE channel_id = :channelId")
- suspend fun deleteForChannel(channelId: String)
+ @Query("DELETE FROM programs WHERE provider_id = :providerId")
+ suspend fun deleteByProvider(providerId: Long)
+
+ @Query("DELETE FROM programs WHERE provider_id = :providerId AND channel_id = :channelId")
+ suspend fun deleteForChannel(providerId: Long, channelId: String)
}
@Dao
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 51521373..d3ed5dd9 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
@@ -2,6 +2,7 @@ package com.streamvault.data.local.entity
import androidx.room.ColumnInfo
import androidx.room.Entity
+import androidx.room.Fts4
import androidx.room.Index
import androidx.room.PrimaryKey
@@ -127,6 +128,24 @@ data class SeriesEntity(
@ColumnInfo(name = "is_user_protected") val isUserProtected: Boolean = false
)
+@Fts4(contentEntity = ChannelEntity::class)
+@Entity(tableName = "channels_fts")
+data class ChannelFtsEntity(
+ val name: String
+)
+
+@Fts4(contentEntity = MovieEntity::class)
+@Entity(tableName = "movies_fts")
+data class MovieFtsEntity(
+ val name: String
+)
+
+@Fts4(contentEntity = SeriesEntity::class)
+@Entity(tableName = "series_fts")
+data class SeriesFtsEntity(
+ val name: String
+)
+
@Entity(
tableName = "episodes",
indices = [
@@ -180,14 +199,17 @@ data class CategoryEntity(
@Entity(
tableName = "programs",
indices = [
- Index(value = ["channel_id"]),
+ Index(value = ["provider_id"]),
+ Index(value = ["provider_id", "channel_id"]),
Index(value = ["start_time"]),
- Index(value = ["channel_id", "start_time"])
+ Index(value = ["provider_id", "channel_id", "start_time"]),
+ Index(value = ["provider_id", "channel_id", "start_time", "end_time"], unique = true)
]
)
data class ProgramEntity(
@PrimaryKey(autoGenerate = true)
val id: Long = 0,
+ @ColumnInfo(name = "provider_id") val providerId: Long = 0,
@ColumnInfo(name = "channel_id") val channelId: String,
val title: String,
val description: String = "",
diff --git a/data/src/main/java/com/streamvault/data/manager/BackupManagerImpl.kt b/data/src/main/java/com/streamvault/data/manager/BackupManagerImpl.kt
index 8b208e07..356413b5 100644
--- a/data/src/main/java/com/streamvault/data/manager/BackupManagerImpl.kt
+++ b/data/src/main/java/com/streamvault/data/manager/BackupManagerImpl.kt
@@ -35,7 +35,6 @@ class BackupManagerImpl @Inject constructor(
// 1. Gather Data
val prefs = mapOf(
"parentalControlLevel" to preferencesRepository.parentalControlLevel.first().toString(),
- "parentalPin" to (preferencesRepository.parentalPin.first() ?: ""),
// We're leaving out provider credentials/URLs from the backup for security/complexity,
// but we could back them up as well if requested.
)
@@ -92,9 +91,6 @@ class BackupManagerImpl @Inject constructor(
prefs["parentalControlLevel"]?.toIntOrNull()?.let {
preferencesRepository.setParentalControlLevel(it)
}
- prefs["parentalPin"]?.let { pin ->
- if (pin.isNotBlank()) preferencesRepository.setParentalPin(pin)
- }
}
// 3. Restore Virtual Groups
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 f13c432e..84b48a9e 100644
--- a/data/src/main/java/com/streamvault/data/mapper/EntityMappers.kt
+++ b/data/src/main/java/com/streamvault/data/mapper/EntityMappers.kt
@@ -58,12 +58,13 @@ fun ChannelEntity.toDomain() = Channel(
isAdult = isAdult,
isUserProtected = isUserProtected,
logicalGroupId = logicalGroupId,
- errorCount = errorCount
+ errorCount = errorCount,
+ streamId = streamId
)
fun Channel.toEntity() = ChannelEntity(
id = id,
- streamId = id,
+ streamId = streamId.takeIf { it > 0 } ?: id,
name = name,
logoUrl = logoUrl,
groupTitle = groupTitle,
@@ -108,12 +109,13 @@ fun MovieEntity.toDomain() = Movie(
watchProgress = watchProgress,
lastWatchedAt = lastWatchedAt,
isAdult = isAdult,
- isUserProtected = isUserProtected
+ isUserProtected = isUserProtected,
+ streamId = streamId
)
fun Movie.toEntity() = MovieEntity(
id = id,
- streamId = id,
+ streamId = streamId.takeIf { it > 0 } ?: id,
name = name,
posterUrl = posterUrl,
backdropUrl = backdropUrl,
@@ -160,12 +162,13 @@ fun SeriesEntity.toDomain() = Series(
lastModified = lastModified,
providerId = providerId,
isAdult = isAdult,
- isUserProtected = isUserProtected
+ isUserProtected = isUserProtected,
+ seriesId = seriesId
)
fun Series.toEntity() = SeriesEntity(
id = id,
- seriesId = id,
+ seriesId = seriesId.takeIf { it > 0 } ?: id,
name = name,
posterUrl = posterUrl,
backdropUrl = backdropUrl,
@@ -206,12 +209,13 @@ fun EpisodeEntity.toDomain() = Episode(
watchProgress = watchProgress,
lastWatchedAt = lastWatchedAt,
isAdult = isAdult,
- isUserProtected = isUserProtected
+ isUserProtected = isUserProtected,
+ episodeId = episodeId
)
fun Episode.toEntity() = EpisodeEntity(
id = id,
- episodeId = id,
+ episodeId = episodeId.takeIf { it > 0 } ?: id,
title = title,
episodeNumber = episodeNumber,
seasonNumber = seasonNumber,
@@ -262,18 +266,20 @@ fun ProgramEntity.toDomain() = Program(
startTime = startTime,
endTime = endTime,
lang = lang,
- hasArchive = hasArchive
+ hasArchive = hasArchive,
+ providerId = providerId
)
fun Program.toEntity() = ProgramEntity(
- id = id,
+ id = 0,
channelId = channelId,
title = title,
description = description,
startTime = startTime,
endTime = endTime,
lang = lang,
- hasArchive = hasArchive
+ hasArchive = hasArchive,
+ providerId = providerId
)
// ── Favorite ───────────────────────────────────────────────────────
diff --git a/data/src/main/java/com/streamvault/data/preferences/PreferencesRepository.kt b/data/src/main/java/com/streamvault/data/preferences/PreferencesRepository.kt
index 43181dd3..08cbaef2 100644
--- a/data/src/main/java/com/streamvault/data/preferences/PreferencesRepository.kt
+++ b/data/src/main/java/com/streamvault/data/preferences/PreferencesRepository.kt
@@ -8,7 +8,11 @@ import androidx.datastore.preferences.core.intPreferencesKey
import androidx.datastore.preferences.core.longPreferencesKey
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
+import java.security.SecureRandom
+import javax.crypto.SecretKeyFactory
+import javax.crypto.spec.PBEKeySpec
import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map
import javax.inject.Inject
import javax.inject.Singleton
@@ -21,11 +25,19 @@ private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(na
class PreferencesRepository @Inject constructor(
@ApplicationContext private val context: Context
) {
+ companion object {
+ private const val PIN_SALT_BYTES = 16
+ private const val PIN_HASH_ITERATIONS = 120_000
+ private const val PIN_HASH_KEY_BITS = 256
+ }
+
private object PreferencesKeys {
val LAST_ACTIVE_PROVIDER_ID = longPreferencesKey("last_active_provider_id")
val DEFAULT_VIEW_MODE = stringPreferencesKey("default_view_mode")
val PARENTAL_CONTROL_LEVEL = intPreferencesKey("parental_control_level")
- val PARENTAL_PIN = stringPreferencesKey("parental_pin")
+ val LEGACY_PARENTAL_PIN = stringPreferencesKey("parental_pin")
+ val PARENTAL_PIN_HASH = stringPreferencesKey("parental_pin_hash")
+ val PARENTAL_PIN_SALT = stringPreferencesKey("parental_pin_salt")
val DEFAULT_CATEGORY_ID = longPreferencesKey("default_category_id")
val APP_LANGUAGE = stringPreferencesKey("app_language")
}
@@ -43,11 +55,6 @@ class PreferencesRepository @Inject constructor(
preferences[PreferencesKeys.PARENTAL_CONTROL_LEVEL] ?: 1 // Default to 1 = LOCKED
}
- val parentalPin: Flow<String> = context.dataStore.data
- .map { preferences ->
- preferences[PreferencesKeys.PARENTAL_PIN] ?: "0000"
- }
-
suspend fun setLastActiveProviderId(id: Long) {
context.dataStore.edit { preferences ->
preferences[PreferencesKeys.LAST_ACTIVE_PROVIDER_ID] = id
@@ -67,13 +74,46 @@ class PreferencesRepository @Inject constructor(
}
suspend fun setParentalPin(pin: String) {
+ val salt = ByteArray(PIN_SALT_BYTES).also { SecureRandom().nextBytes(it) }
+ val hash = hashPin(pin, salt)
+ val saltBase64 = java.util.Base64.getEncoder().encodeToString(salt)
context.dataStore.edit { preferences ->
- preferences[PreferencesKeys.PARENTAL_PIN] = pin
+ preferences[PreferencesKeys.PARENTAL_PIN_HASH] = hash
+ preferences[PreferencesKeys.PARENTAL_PIN_SALT] = saltBase64
+ preferences.remove(PreferencesKeys.LEGACY_PARENTAL_PIN)
}
}
+ suspend fun verifyParentalPin(pin: String): Boolean {
+ val preferences = context.dataStore.data.first()
+
+ val storedHash = preferences[PreferencesKeys.PARENTAL_PIN_HASH]
+ val storedSaltBase64 = preferences[PreferencesKeys.PARENTAL_PIN_SALT]
+
+ if (!storedHash.isNullOrBlank() && !storedSaltBase64.isNullOrBlank()) {
+ val salt = runCatching { java.util.Base64.getDecoder().decode(storedSaltBase64) }.getOrNull()
+ ?: return false
+ return hashPin(pin, salt) == storedHash
+ }
+
+ val legacyPin = preferences[PreferencesKeys.LEGACY_PARENTAL_PIN]
+ val valid = if (!legacyPin.isNullOrBlank()) {
+ pin == legacyPin
+ } else {
+ pin == "0000"
+ }
+
+ if (valid) {
+ // One-way migrate legacy/default behavior to hashed PIN storage.
+ setParentalPin(pin)
+ }
+
+ return valid
+ }
+
suspend fun clearDefaultViewMode() {
context.dataStore.edit { preferences ->
+ preferences.remove(PreferencesKeys.DEFAULT_VIEW_MODE)
}
}
@@ -110,4 +150,10 @@ class PreferencesRepository @Inject constructor(
preferences[key] = ratio
}
}
+
+ private fun hashPin(pin: String, salt: ByteArray): String {
+ val spec = PBEKeySpec(pin.toCharArray(), salt, PIN_HASH_ITERATIONS, PIN_HASH_KEY_BITS)
+ val secret = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256").generateSecret(spec)
+ return java.util.Base64.getEncoder().encodeToString(secret.encoded)
+ }
}
diff --git a/data/src/main/java/com/streamvault/data/remote/xtream/XtreamApiService.kt b/data/src/main/java/com/streamvault/data/remote/xtream/XtreamApiService.kt
index a0278ce8..1b7013c1 100644
--- a/data/src/main/java/com/streamvault/data/remote/xtream/XtreamApiService.kt
+++ b/data/src/main/java/com/streamvault/data/remote/xtream/XtreamApiService.kt
@@ -1,96 +1,102 @@
package com.streamvault.data.remote.xtream
-import com.streamvault.data.remote.dto.*
+import com.streamvault.data.remote.dto.XtreamAuthResponse
+import com.streamvault.data.remote.dto.XtreamCategory
+import com.streamvault.data.remote.dto.XtreamEpgResponse
+import com.streamvault.data.remote.dto.XtreamSeriesInfoResponse
+import com.streamvault.data.remote.dto.XtreamSeriesItem
+import com.streamvault.data.remote.dto.XtreamStream
+import com.streamvault.data.remote.dto.XtreamVodInfoResponse
import retrofit2.http.GET
import retrofit2.http.Query
+import retrofit2.http.Url
/**
- * Retrofit interface for the Xtream Codes player API.
- * Base URL format: http://server:port/player_api.php
+ * Retrofit interface for Xtream Codes player API.
*
- * All endpoints require username and password query params.
+ * Calls use dynamic @Url so each provider can target its own server host.
*/
interface XtreamApiService {
- // ── Authentication ──────────────────────────────────────────────
-
- @GET("player_api.php")
+ @GET
suspend fun authenticate(
+ @Url endpoint: String,
@Query("username") username: String,
@Query("password") password: String
): XtreamAuthResponse
- // ── Live TV ─────────────────────────────────────────────────────
-
- @GET("player_api.php")
+ @GET
suspend fun getLiveCategories(
+ @Url endpoint: String,
@Query("username") username: String,
@Query("password") password: String,
@Query("action") action: String = "get_live_categories"
): List<XtreamCategory>
- @GET("player_api.php")
+ @GET
suspend fun getLiveStreams(
+ @Url endpoint: String,
@Query("username") username: String,
@Query("password") password: String,
@Query("action") action: String = "get_live_streams",
@Query("category_id") categoryId: String? = null
): List<XtreamStream>
- // ── VOD (Movies) ────────────────────────────────────────────────
-
- @GET("player_api.php")
+ @GET
suspend fun getVodCategories(
+ @Url endpoint: String,
@Query("username") username: String,
@Query("password") password: String,
@Query("action") action: String = "get_vod_categories"
): List<XtreamCategory>
- @GET("player_api.php")
+ @GET
suspend fun getVodStreams(
+ @Url endpoint: String,
@Query("username") username: String,
@Query("password") password: String,
@Query("action") action: String = "get_vod_streams",
@Query("category_id") categoryId: String? = null
): List<XtreamStream>
- @GET("player_api.php")
+ @GET
suspend fun getVodInfo(
+ @Url endpoint: String,
@Query("username") username: String,
@Query("password") password: String,
@Query("action") action: String = "get_vod_info",
@Query("vod_id") vodId: Long
): XtreamVodInfoResponse
- // ── Series ──────────────────────────────────────────────────────
-
- @GET("player_api.php")
+ @GET
suspend fun getSeriesCategories(
+ @Url endpoint: String,
@Query("username") username: String,
@Query("password") password: String,
@Query("action") action: String = "get_series_categories"
): List<XtreamCategory>
- @GET("player_api.php")
+ @GET
suspend fun getSeriesList(
+ @Url endpoint: String,
@Query("username") username: String,
@Query("password") password: String,
@Query("action") action: String = "get_series",
@Query("category_id") categoryId: String? = null
): List<XtreamSeriesItem>
- @GET("player_api.php")
+ @GET
suspend fun getSeriesInfo(
+ @Url endpoint: String,
@Query("username") username: String,
@Query("password") password: String,
@Query("action") action: String = "get_series_info",
@Query("series_id") seriesId: Long
): XtreamSeriesInfoResponse
- // ── EPG ─────────────────────────────────────────────────────────
-
- @GET("player_api.php")
+ @GET
suspend fun getShortEpg(
+ @Url endpoint: String,
@Query("username") username: String,
@Query("password") password: String,
@Query("action") action: String = "get_short_epg",
@@ -98,8 +104,9 @@ interface XtreamApiService {
@Query("limit") limit: Int = 4
): XtreamEpgResponse
- @GET("player_api.php")
+ @GET
suspend fun getFullEpg(
+ @Url endpoint: String,
@Query("username") username: String,
@Query("password") password: String,
@Query("action") action: String = "get_simple_data_table",
diff --git a/data/src/main/java/com/streamvault/data/remote/xtream/XtreamProvider.kt b/data/src/main/java/com/streamvault/data/remote/xtream/XtreamProvider.kt
index ea9ee733..20bb239d 100644
--- a/data/src/main/java/com/streamvault/data/remote/xtream/XtreamProvider.kt
+++ b/data/src/main/java/com/streamvault/data/remote/xtream/XtreamProvider.kt
@@ -1,6 +1,7 @@
package com.streamvault.data.remote.xtream
import com.streamvault.data.remote.dto.*
+import com.streamvault.data.util.AdultContentClassifier
import com.streamvault.domain.model.*
import com.streamvault.domain.provider.IptvProvider
import com.streamvault.domain.util.ChannelNormalizer
@@ -19,9 +20,10 @@ class XtreamProvider(
) : IptvProvider {
private var serverInfo: XtreamServerInfo? = null
+ private val apiEndpoint: String = "${serverUrl.trimEnd('/')}/player_api.php"
override suspend fun authenticate(): Result<Provider> = try {
- val response = api.authenticate(username, password)
+ val response = api.authenticate(apiEndpoint, username, password)
serverInfo = response.serverInfo
if (response.userInfo.auth != 1) {
@@ -85,18 +87,19 @@ class XtreamProvider(
// ── Live TV ────────────────────────────────────────────────────
override suspend fun getLiveCategories(): Result<List<Category>> = try {
- val categories = api.getLiveCategories(username, password)
+ val categories = api.getLiveCategories(apiEndpoint, username, password)
Result.success(categories.map { it.toDomain(ContentType.LIVE) })
} catch (e: Exception) {
Result.error("Failed to load live categories: ${e.message}", e)
}
override suspend fun getLiveStreams(categoryId: Long?): Result<List<Channel>> = try {
+ val adultCategoryIds = loadAdultCategoryIds(ContentType.LIVE)
val streams = api.getLiveStreams(
- username, password,
+ apiEndpoint, username, password,
categoryId = categoryId?.toString()
)
- Result.success(streams.map { it.toChannel() })
+ Result.success(streams.map { it.toChannel(adultCategoryIds) })
} catch (e: Exception) {
Result.error("Failed to load live streams: ${e.message}", e)
}
@@ -104,24 +107,25 @@ class XtreamProvider(
// ── VOD ────────────────────────────────────────────────────────
override suspend fun getVodCategories(): Result<List<Category>> = try {
- val categories = api.getVodCategories(username, password)
+ val categories = api.getVodCategories(apiEndpoint, username, password)
Result.success(categories.map { it.toDomain(ContentType.MOVIE) })
} catch (e: Exception) {
Result.error("Failed to load VOD categories: ${e.message}", e)
}
override suspend fun getVodStreams(categoryId: Long?): Result<List<Movie>> = try {
+ val adultCategoryIds = loadAdultCategoryIds(ContentType.MOVIE)
val streams = api.getVodStreams(
- username, password,
+ apiEndpoint, username, password,
categoryId = categoryId?.toString()
)
- Result.success(streams.map { it.toMovie() })
+ Result.success(streams.map { it.toMovie(adultCategoryIds) })
} catch (e: Exception) {
Result.error("Failed to load VOD: ${e.message}", e)
}
override suspend fun getVodInfo(vodId: Long): Result<Movie> = try {
- val response = api.getVodInfo(username, password, vodId = vodId)
+ val response = api.getVodInfo(apiEndpoint, username, password, vodId = vodId)
val movieData = response.movieData
val info = response.info
@@ -147,7 +151,13 @@ class XtreamProvider(
tmdbId = info?.tmdbId,
youtubeTrailer = info?.youtubeTrailer,
providerId = providerId,
- streamUrl = buildMovieStreamUrl(movieData.streamId, movieData.containerExtension)
+ streamUrl = buildMovieStreamUrl(movieData.streamId, movieData.containerExtension),
+ streamId = movieData.streamId,
+ isAdult = resolveAdultFlag(
+ categoryId = movieData.categoryId?.toLongOrNull(),
+ categoryName = null,
+ adultCategoryIds = loadAdultCategoryIds(ContentType.MOVIE)
+ )
)
)
}
@@ -158,29 +168,36 @@ class XtreamProvider(
// ── Series ─────────────────────────────────────────────────────
override suspend fun getSeriesCategories(): Result<List<Category>> = try {
- val categories = api.getSeriesCategories(username, password)
+ val categories = api.getSeriesCategories(apiEndpoint, username, password)
Result.success(categories.map { it.toDomain(ContentType.SERIES) })
} catch (e: Exception) {
Result.error("Failed to load series categories: ${e.message}", e)
}
override suspend fun getSeriesList(categoryId: Long?): Result<List<Series>> = try {
+ val adultCategoryIds = loadAdultCategoryIds(ContentType.SERIES)
val items = api.getSeriesList(
- username, password,
+ apiEndpoint, username, password,
categoryId = categoryId?.toString()
)
- Result.success(items.map { it.toDomain() })
+ Result.success(items.map { it.toDomain(adultCategoryIds) })
} catch (e: Exception) {
Result.error("Failed to load series: ${e.message}", e)
}
override suspend fun getSeriesInfo(seriesId: Long): Result<Series> = try {
- val response = api.getSeriesInfo(username, password, seriesId = seriesId)
+ val response = api.getSeriesInfo(apiEndpoint, username, password, seriesId = seriesId)
val info = response.info
if (info == null) {
Result.error("Series not found")
} else {
+ val adultCategoryIds = loadAdultCategoryIds(ContentType.SERIES)
+ val isAdult = resolveAdultFlag(
+ categoryId = info.categoryId?.toLongOrNull(),
+ categoryName = null,
+ adultCategoryIds = adultCategoryIds
+ )
val seasons = response.episodes.map { (seasonNum, episodes) ->
Season(
seasonNumber = seasonNum.toIntOrNull() ?: 0,
@@ -207,8 +224,9 @@ class XtreamProvider(
ep.id.toLongOrNull() ?: 0,
ep.containerExtension
),
- isAdult = false,
- isUserProtected = false
+ isAdult = isAdult,
+ isUserProtected = false,
+ episodeId = ep.id.toLongOrNull() ?: 0
)
},
episodeCount = episodes.size
@@ -216,9 +234,10 @@ class XtreamProvider(
}.sortedBy { it.seasonNumber }
Result.success(
- info.toDomain().copy(
+ info.toDomain(adultCategoryIds).copy(
seasons = seasons,
- providerId = providerId
+ providerId = providerId,
+ isAdult = isAdult
)
)
}
@@ -230,7 +249,7 @@ class XtreamProvider(
override suspend fun getEpg(channelId: String): Result<List<Program>> = try {
val streamId = channelId.toLongOrNull() ?: 0
- val response = api.getFullEpg(username, password, streamId = streamId)
+ val response = api.getFullEpg(apiEndpoint, username, password, streamId = streamId)
Result.success(response.epgListings.map { it.toDomain() })
} catch (e: Exception) {
Result.error("Failed to load EPG: ${e.message}", e)
@@ -238,7 +257,7 @@ class XtreamProvider(
override suspend fun getShortEpg(channelId: String, limit: Int): Result<List<Program>> = try {
val streamId = channelId.toLongOrNull() ?: 0
- val response = api.getShortEpg(username, password, streamId = streamId, limit = limit)
+ val response = api.getShortEpg(apiEndpoint, username, password, streamId = streamId, limit = limit)
Result.success(response.epgListings.map { it.toDomain() })
} catch (e: Exception) {
Result.error("Failed to load EPG: ${e.message}", e)
@@ -274,10 +293,26 @@ class XtreamProvider(
// ── Mappers ────────────────────────────────────────────────────
- private fun isAdultContent(name: String?): Boolean {
- if (name == null) return false
- val keywords = listOf("XXX", "Adult", "Porn", "Erotic", "18+")
- return keywords.any { name.contains(it, ignoreCase = true) }
+ private suspend fun loadAdultCategoryIds(type: ContentType): Set<Long> {
+ val categories = when (type) {
+ ContentType.LIVE -> api.getLiveCategories(apiEndpoint, username, password)
+ ContentType.MOVIE -> api.getVodCategories(apiEndpoint, username, password)
+ ContentType.SERIES -> api.getSeriesCategories(apiEndpoint, username, password)
+ ContentType.SERIES_EPISODE -> emptyList()
+ }
+ return categories
+ .filter { AdultContentClassifier.isAdultCategoryName(it.categoryName) }
+ .mapNotNull { it.categoryId.toLongOrNull() }
+ .toSet()
+ }
+
+ private fun resolveAdultFlag(
+ categoryId: Long?,
+ categoryName: String?,
+ adultCategoryIds: Set<Long>
+ ): Boolean {
+ return (categoryId != null && categoryId in adultCategoryIds) ||
+ AdultContentClassifier.isAdultCategoryName(categoryName)
}
private fun XtreamCategory.toDomain(type: ContentType) = Category(
@@ -285,16 +320,12 @@ class XtreamProvider(
name = categoryName,
parentId = if (parentId > 0) parentId.toLong() else null,
type = type,
- isAdult = isAdultContent(categoryName)
+ isAdult = AdultContentClassifier.isAdultCategoryName(categoryName)
)
- private fun XtreamStream.toChannel(): Channel {
- val isCatAdult = isAdultContent(categoryName)
- // Check group title as fallback if available, though usually categoryName is the group
- val isGroupAdult = false
-
+ private fun XtreamStream.toChannel(adultCategoryIds: Set<Long>): Channel {
return Channel(
- id = streamId,
+ id = 0,
name = name,
logoUrl = streamIcon,
categoryId = categoryId?.toLongOrNull(),
@@ -305,14 +336,19 @@ class XtreamProvider(
catchUpDays = tvArchiveDuration ?: 0,
providerId = providerId,
streamUrl = "$serverUrl/live/$username/$password/$streamId.ts",
- isAdult = isCatAdult,
+ isAdult = resolveAdultFlag(
+ categoryId = categoryId?.toLongOrNull(),
+ categoryName = categoryName,
+ adultCategoryIds = adultCategoryIds
+ ),
isUserProtected = false,
- logicalGroupId = ChannelNormalizer.getLogicalGroupId(name, providerId)
+ logicalGroupId = ChannelNormalizer.getLogicalGroupId(name, providerId),
+ streamId = streamId
)
}
- private fun XtreamStream.toMovie() = Movie(
- id = streamId,
+ private fun XtreamStream.toMovie(adultCategoryIds: Set<Long>) = Movie(
+ id = 0,
name = name,
posterUrl = streamIcon,
categoryId = categoryId?.toLongOrNull(),
@@ -321,12 +357,17 @@ class XtreamProvider(
rating = rating5based?.toFloatOrNull() ?: 0f,
providerId = providerId,
streamUrl = buildMovieStreamUrl(streamId, containerExtension),
- isAdult = isAdultContent(categoryName),
- isUserProtected = false
+ isAdult = resolveAdultFlag(
+ categoryId = categoryId?.toLongOrNull(),
+ categoryName = categoryName,
+ adultCategoryIds = adultCategoryIds
+ ),
+ isUserProtected = false,
+ streamId = streamId
)
- private fun XtreamSeriesItem.toDomain() = Series(
- id = seriesId,
+ private fun XtreamSeriesItem.toDomain(adultCategoryIds: Set<Long>) = Series(
+ id = 0,
name = name,
posterUrl = cover,
backdropUrl = backdropPath?.firstOrNull(),
@@ -341,8 +382,13 @@ class XtreamProvider(
episodeRunTime = episodeRunTime,
lastModified = lastModified?.toLongOrNull() ?: 0L,
providerId = providerId,
- isAdult = false, // Category name not on series item in Xtream
- isUserProtected = false
+ isAdult = resolveAdultFlag(
+ categoryId = categoryId?.toLongOrNull(),
+ categoryName = null,
+ adultCategoryIds = adultCategoryIds
+ ),
+ isUserProtected = false,
+ seriesId = seriesId
)
private fun XtreamEpgListing.toDomain(): Program {
@@ -359,7 +405,8 @@ class XtreamProvider(
endTime = stopTimestamp * 1000L,
lang = lang,
hasArchive = hasArchive == 1,
- isNowPlaying = nowPlaying == 1
+ isNowPlaying = nowPlaying == 1,
+ providerId = providerId
)
}
diff --git a/data/src/main/java/com/streamvault/data/repository/CategoryRepositoryImpl.kt b/data/src/main/java/com/streamvault/data/repository/CategoryRepositoryImpl.kt
index 0721bd09..a3a4797f 100644
--- a/data/src/main/java/com/streamvault/data/repository/CategoryRepositoryImpl.kt
+++ b/data/src/main/java/com/streamvault/data/repository/CategoryRepositoryImpl.kt
@@ -1,12 +1,12 @@
package com.streamvault.data.repository
import com.streamvault.data.local.dao.*
-import com.streamvault.data.local.entity.CategoryEntity
import com.streamvault.data.mapper.toDomain
import com.streamvault.domain.model.Category
import com.streamvault.domain.model.ContentType
import com.streamvault.domain.repository.CategoryRepository
import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.map
import javax.inject.Inject
import javax.inject.Singleton
@@ -20,16 +20,28 @@ class CategoryRepositoryImpl @Inject constructor(
) : CategoryRepository {
override fun getCategories(providerId: Long): Flow<List<Category>> =
- categoryDao.getByProviderAndType(providerId, ContentType.LIVE.name)
- .map { entities -> entities.map { it.toDomain() } }
+ combine(
+ categoryDao.getByProviderAndType(providerId, ContentType.LIVE.name),
+ categoryDao.getByProviderAndType(providerId, ContentType.MOVIE.name),
+ categoryDao.getByProviderAndType(providerId, ContentType.SERIES.name)
+ ) { live, movies, series ->
+ (live + movies + series)
+ .map { it.toDomain() }
+ .sortedWith(compareBy<Category>({ it.type.ordinal }, { it.name.lowercase() }))
+ }
- override suspend fun setCategoryProtection(categoryId: Long, isProtected: Boolean) {
- // Update category table
- categoryDao.updateProtectionStatus(categoryId, isProtected)
-
- // Update items tables
- channelDao.updateProtectionStatus(categoryId, isProtected)
- movieDao.updateProtectionStatus(categoryId, isProtected)
- seriesDao.updateProtectionStatus(categoryId, isProtected)
+ override suspend fun setCategoryProtection(
+ providerId: Long,
+ categoryId: Long,
+ type: ContentType,
+ isProtected: Boolean
+ ) {
+ categoryDao.updateProtectionStatus(providerId, categoryId, type.name, isProtected)
+ when (type) {
+ ContentType.LIVE -> channelDao.updateProtectionStatus(providerId, categoryId, isProtected)
+ ContentType.MOVIE -> movieDao.updateProtectionStatus(providerId, categoryId, isProtected)
+ ContentType.SERIES -> seriesDao.updateProtectionStatus(providerId, categoryId, isProtected)
+ ContentType.SERIES_EPISODE -> Unit
+ }
}
}
diff --git a/data/src/main/java/com/streamvault/data/repository/ChannelRepositoryImpl.kt b/data/src/main/java/com/streamvault/data/repository/ChannelRepositoryImpl.kt
index 3908998a..d1b154a4 100644
--- a/data/src/main/java/com/streamvault/data/repository/ChannelRepositoryImpl.kt
+++ b/data/src/main/java/com/streamvault/data/repository/ChannelRepositoryImpl.kt
@@ -14,6 +14,7 @@ import com.streamvault.domain.repository.ChannelRepository
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.combine
+import kotlinx.coroutines.flow.flowOf
import javax.inject.Inject
import com.streamvault.data.preferences.PreferencesRepository
import javax.inject.Singleton
@@ -30,7 +31,7 @@ class ChannelRepositoryImpl @Inject constructor(
combine(
channelDao.getByProvider(providerId),
preferencesRepository.parentalControlLevel,
- parentalControlManager.unlockedCategories
+ parentalControlManager.unlockedCategoriesForProvider(providerId)
) { entities, level, unlockedCats ->
// Level 2 = HIDDEN.
// If hidden, filter out adult/protected UNLESS they are in unlockedCats.
@@ -54,7 +55,7 @@ class ChannelRepositoryImpl @Inject constructor(
channelDao.getByCategory(providerId, categoryId)
},
preferencesRepository.parentalControlLevel,
- parentalControlManager.unlockedCategories
+ parentalControlManager.unlockedCategoriesForProvider(providerId)
) { entities, level, unlockedCats ->
// Level 2 = HIDDEN.
// If hidden, filter out adult/protected UNLESS they are in unlockedCats.
@@ -76,7 +77,7 @@ class ChannelRepositoryImpl @Inject constructor(
channelDao.getCategoryCounts(providerId),
channelDao.getCount(providerId),
preferencesRepository.parentalControlLevel,
- parentalControlManager.unlockedCategories
+ parentalControlManager.unlockedCategoriesForProvider(providerId)
) { categories: List<CategoryEntity>, counts: List<CategoryCount>, totalCount: Int, level: Int, unlockedCats: Set<Long> ->
android.util.Log.d("ChannelRepo", "getCategories: ${categories.size} cats, ${counts.size} counts, total: $totalCount")
val countMap = counts.associate { it.categoryId to it.item_count }
@@ -112,21 +113,25 @@ class ChannelRepositoryImpl @Inject constructor(
}
override fun searchChannels(providerId: Long, query: String): Flow<List<Channel>> =
- combine(
- channelDao.search(providerId, query),
- preferencesRepository.parentalControlLevel,
- parentalControlManager.unlockedCategories
- ) { entities, level, unlockedCats ->
- val filtered = if (level == 2) {
- entities.filter { entity ->
- val isUnlocked = entity.categoryId != null && unlockedCats.contains(entity.categoryId)
- (!entity.isAdult && !entity.isUserProtected) || isUnlocked
+ query.toFtsPrefixQuery().let { ftsQuery ->
+ if (ftsQuery.isBlank()) {
+ flowOf(emptyList())
+ } else combine(
+ channelDao.search(providerId, ftsQuery),
+ preferencesRepository.parentalControlLevel,
+ parentalControlManager.unlockedCategoriesForProvider(providerId)
+ ) { entities, level, unlockedCats ->
+ val filtered = if (level == 2) {
+ entities.filter { entity ->
+ val isUnlocked = entity.categoryId != null && unlockedCats.contains(entity.categoryId)
+ (!entity.isAdult && !entity.isUserProtected) || isUnlocked
+ }
+ } else {
+ entities
}
- } else {
- entities
+
+ groupAndMapChannels(filtered, unlockedCats)
}
-
- groupAndMapChannels(filtered, unlockedCats)
}
override suspend fun getChannel(channelId: Long): Channel? =
@@ -176,4 +181,13 @@ class ChannelRepositoryImpl @Inject constructor(
}
}
}
+
+ private fun String.toFtsPrefixQuery(): String {
+ val tokens = trim()
+ .split(Regex("\\s+"))
+ .map { token -> token.replace(Regex("[^\\p{L}\\p{N}_]"), "") }
+ .filter { it.length >= 2 }
+
+ return tokens.joinToString(" AND ") { "$it*" }
+ }
}
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 73be795f..688c10cc 100644
--- a/data/src/main/java/com/streamvault/data/repository/EpgRepositoryImpl.kt
+++ b/data/src/main/java/com/streamvault/data/repository/EpgRepositoryImpl.kt
@@ -24,26 +24,28 @@ class EpgRepositoryImpl @Inject constructor(
) : EpgRepository {
override fun getProgramsForChannel(
+ providerId: Long,
channelId: String,
startTime: Long,
endTime: Long
): Flow<List<Program>> =
- programDao.getForChannel(channelId, startTime, endTime)
+ programDao.getForChannel(providerId, channelId, startTime, endTime)
.map { entities -> entities.map { it.toDomain() } }
- override fun getNowPlaying(channelId: String): Flow<Program?> =
- programDao.getNowPlaying(channelId, System.currentTimeMillis())
+ override fun getNowPlaying(providerId: Long, channelId: String): Flow<Program?> =
+ programDao.getNowPlaying(providerId, channelId, System.currentTimeMillis())
.map { it?.toDomain() }
- override fun getNowPlayingForChannels(channelIds: List<String>): Flow<Map<String, List<Program>>> =
- programDao.getNowPlayingForChannels(channelIds, System.currentTimeMillis())
+ override fun getNowPlayingForChannels(providerId: Long, channelIds: List<String>): Flow<Map<String, List<Program>>> =
+ programDao.getNowPlayingForChannels(providerId, channelIds, System.currentTimeMillis())
.map { entities ->
entities.map { it.toDomain() }
.groupBy { it.channelId }
}
- override fun getNowAndNext(channelId: String): Flow<Pair<Program?, Program?>> =
+ override fun getNowAndNext(providerId: Long, channelId: String): Flow<Pair<Program?, Program?>> =
programDao.getForChannel(
+ providerId,
channelId,
System.currentTimeMillis() - 3600000, // 1 hour ago
System.currentTimeMillis() + 7200000 // 2 hours from now
@@ -71,8 +73,11 @@ class EpgRepositoryImpl @Inject constructor(
xmltvParser.parse(inputStream)
}
+ // Keep provider datasets isolated and avoid stale entries after partial guide updates.
+ programDao.deleteByProvider(providerId)
+
// Batch insert in chunks to avoid memory pressure
- val entities = programs.map { it.toEntity() }
+ val entities = programs.map { it.copy(providerId = providerId).toEntity() }
entities.chunked(500).forEach { chunk ->
programDao.insertAll(chunk)
}
diff --git a/data/src/main/java/com/streamvault/data/repository/MovieRepositoryImpl.kt b/data/src/main/java/com/streamvault/data/repository/MovieRepositoryImpl.kt
index 1c567df5..663e7876 100644
--- a/data/src/main/java/com/streamvault/data/repository/MovieRepositoryImpl.kt
+++ b/data/src/main/java/com/streamvault/data/repository/MovieRepositoryImpl.kt
@@ -12,6 +12,7 @@ import com.streamvault.domain.model.Result
import com.streamvault.domain.repository.MovieRepository
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.combine
+import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.map
import javax.inject.Inject
import com.streamvault.data.preferences.PreferencesRepository
@@ -48,6 +49,9 @@ class MovieRepositoryImpl @Inject constructor(
}
}.map { list -> list.map { it.toDomain() } }
+ override fun getMoviesByIds(ids: List<Long>): Flow<List<Movie>> =
+ movieDao.getByIds(ids).map { entities -> entities.map { it.toDomain() } }
+
override fun getCategories(providerId: Long): Flow<List<Category>> =
combine(
categoryDao.getByProviderAndType(providerId, ContentType.MOVIE.name),
@@ -62,16 +66,20 @@ class MovieRepositoryImpl @Inject constructor(
}
override fun searchMovies(providerId: Long, query: String): Flow<List<Movie>> =
- combine(
- movieDao.search(providerId, query),
- preferencesRepository.parentalControlLevel
- ) { entities: List<MovieEntity>, level: Int ->
- if (level == 2) {
- entities.filter { !it.isUserProtected }
- } else {
- entities
- }
- }.map { list -> list.map { it.toDomain() } }
+ query.toFtsPrefixQuery().let { ftsQuery ->
+ if (ftsQuery.isBlank()) {
+ flowOf(emptyList())
+ } else combine(
+ movieDao.search(providerId, ftsQuery),
+ preferencesRepository.parentalControlLevel
+ ) { entities: List<MovieEntity>, level: Int ->
+ if (level == 2) {
+ entities.filter { !it.isUserProtected }
+ } else {
+ entities
+ }
+ }.map { list -> list.map { it.toDomain() } }
+ }
override suspend fun getMovie(movieId: Long): Movie? =
movieDao.getById(movieId)?.toDomain()
@@ -94,4 +102,13 @@ class MovieRepositoryImpl @Inject constructor(
override suspend fun updateWatchProgress(movieId: Long, progress: Long) {
movieDao.updateWatchProgress(movieId, progress)
}
+
+ private fun String.toFtsPrefixQuery(): String {
+ val tokens = trim()
+ .split(Regex("\\s+"))
+ .map { token -> token.replace(Regex("[^\\p{L}\\p{N}_]"), "") }
+ .filter { it.length >= 2 }
+
+ return tokens.joinToString(" AND ") { "$it*" }
+ }
}
diff --git a/data/src/main/java/com/streamvault/data/repository/PlaybackHistoryRepositoryImpl.kt b/data/src/main/java/com/streamvault/data/repository/PlaybackHistoryRepositoryImpl.kt
index 885957ab..9c93070c 100644
--- a/data/src/main/java/com/streamvault/data/repository/PlaybackHistoryRepositoryImpl.kt
+++ b/data/src/main/java/com/streamvault/data/repository/PlaybackHistoryRepositoryImpl.kt
@@ -30,11 +30,11 @@ class PlaybackHistoryRepositoryImpl @Inject constructor(
override suspend fun updateResumePosition(history: PlaybackHistory) {
val existing = dao.get(history.contentId, history.contentType.name, history.providerId)
- val watchCount = existing?.watchCount ?: 0
-
- // If the item exists and the watch is fresh, maybe bump watch count, but for now just use max 1 or explicit watch_count
+
+ // Resume ticks should not increment watch count on every update.
+ // Keep existing count for ongoing sessions; initialize to 1 on first save.
val updatedHistory = history.copy(
- watchCount = if (existing == null) 1 else existing.watchCount + 1,
+ watchCount = existing?.watchCount ?: 1,
lastWatchedAt = System.currentTimeMillis()
)
dao.insertOrUpdate(updatedHistory.toEntity())
diff --git a/data/src/main/java/com/streamvault/data/repository/ProviderRepositoryImpl.kt b/data/src/main/java/com/streamvault/data/repository/ProviderRepositoryImpl.kt
index 4c68208e..e720d1d2 100644
--- a/data/src/main/java/com/streamvault/data/repository/ProviderRepositoryImpl.kt
+++ b/data/src/main/java/com/streamvault/data/repository/ProviderRepositoryImpl.kt
@@ -5,6 +5,7 @@ import com.streamvault.data.local.entity.ProviderEntity
import com.streamvault.data.mapper.*
import com.streamvault.data.remote.xtream.XtreamApiService
import com.streamvault.data.remote.xtream.XtreamProvider
+import com.streamvault.data.security.CredentialCrypto
import com.streamvault.data.sync.SyncManager
import com.streamvault.domain.model.*
import com.streamvault.domain.provider.IptvProvider
@@ -27,23 +28,23 @@ class ProviderRepositoryImpl @Inject constructor(
) : ProviderRepository {
override fun getProviders(): Flow<List<Provider>> =
- providerDao.getAll().map { entities -> entities.map { it.toDomain() } }
+ providerDao.getAll().map { entities -> entities.map { it.toPublicDomain() } }
override fun getActiveProvider(): Flow<Provider?> =
- providerDao.getActive().map { it?.toDomain() }
+ providerDao.getActive().map { it?.toPublicDomain() }
override suspend fun getProvider(id: Long): Provider? =
- providerDao.getById(id)?.toDomain()
+ providerDao.getById(id)?.toPublicDomain()
override suspend fun addProvider(provider: Provider): Result<Long> = try {
- val id = providerDao.insert(provider.toEntity())
+ val id = providerDao.insert(provider.toSecureEntity())
Result.success(id)
} catch (e: Exception) {
Result.error("Failed to add provider: ${e.message}", e)
}
override suspend fun updateProvider(provider: Provider): Result<Unit> = try {
- providerDao.update(provider.toEntity())
+ providerDao.update(provider.toSecureEntity())
Result.success(Unit)
} catch (e: Exception) {
Result.error("Failed to update provider: ${e.message}", e)
@@ -79,14 +80,17 @@ class ProviderRepositoryImpl @Inject constructor(
id: Long?
): Result<Provider> {
onProgress?.invoke("Authenticating...")
- val provider = createXtreamProvider(0, serverUrl, username, password)
+ val existingProvider = if (id != null) {
+ providerDao.getById(id)
+ } else {
+ providerDao.getByUrlAndUser(serverUrl, username)
+ }
+ val effectivePassword = password.takeIf { it.isNotBlank() }
+ ?: existingProvider?.password?.let(CredentialCrypto::decryptIfNeeded)
+ ?: ""
+ val provider = createXtreamProvider(0, serverUrl, username, effectivePassword)
return when (val authResult = provider.authenticate()) {
is Result.Success -> {
- val existingProvider = if (id != null) {
- providerDao.getById(id)
- } else {
- providerDao.getByUrlAndUser(serverUrl, username)
- }
val providerData = if (existingProvider != null) {
onProgress?.invoke("Updating existing provider...")
@@ -94,27 +98,42 @@ class ProviderRepositoryImpl @Inject constructor(
name = name.ifBlank { existingProvider.name },
serverUrl = serverUrl,
username = username,
- password = password,
+ password = effectivePassword,
isActive = true,
lastSyncedAt = 0
)
- providerDao.update(updated)
- updated.toDomain()
+ providerDao.update(
+ updated.copy(password = CredentialCrypto.encryptIfNeeded(updated.password))
+ )
+ updated.toPublicDomain()
} else {
val newData = authResult.data.copy(name = name.ifBlank { authResult.data.name })
- val newId = providerDao.insert(newData.toEntity())
- newData.copy(id = newId)
+ val newId = providerDao.insert(newData.toSecureEntity())
+ newData.copy(id = newId).copy(password = "")
}
- try {
- providerDao.deactivateAll()
- providerDao.activate(providerData.id)
- // Delegate sync to SyncManager
- syncManager.sync(providerData.id, onProgress)
- } catch (e: Exception) {
- android.util.Log.e("ProviderRepo", "Initial Xtream sync failed: ${e.message}")
+ providerDao.deactivateAll()
+ providerDao.activate(providerData.id)
+
+ when (val syncResult = syncManager.sync(providerData.id, force = false, onProgress = onProgress)) {
+ is Result.Success -> {
+ val finalStatus = if (syncManager.syncState.value is SyncState.Partial) {
+ ProviderStatus.PARTIAL
+ } else {
+ ProviderStatus.ACTIVE
+ }
+ updateProviderSyncStatus(providerData.id, finalStatus, System.currentTimeMillis())
+ Result.success(providerData.copy(status = finalStatus))
+ }
+ is Result.Error -> {
+ updateProviderSyncStatus(providerData.id, ProviderStatus.ERROR)
+ Result.error(
+ "Provider authenticated, but initial sync failed: ${syncResult.message}",
+ syncResult.exception
+ )
+ }
+ is Result.Loading -> Result.error("Unexpected loading state")
}
- Result.success(providerData)
}
is Result.Error -> Result.error(authResult.message, authResult.exception)
is Result.Loading -> Result.error("Unexpected loading state")
@@ -147,7 +166,7 @@ class ProviderRepositoryImpl @Inject constructor(
lastSyncedAt = 0
)
providerDao.update(updated)
- updated.toDomain()
+ updated.toPublicDomain()
} else {
val provider = Provider(
name = providerName,
@@ -156,19 +175,32 @@ class ProviderRepositoryImpl @Inject constructor(
m3uUrl = url,
status = ProviderStatus.ACTIVE
)
- val newId = providerDao.insert(provider.toEntity())
- provider.copy(id = newId)
+ val newId = providerDao.insert(provider.toSecureEntity())
+ provider.copy(id = newId).copy(password = "")
}
- try {
- providerDao.deactivateAll()
- providerDao.activate(providerData.id)
- // Delegate sync to SyncManager
- syncManager.sync(providerData.id, onProgress)
- } catch (e: Exception) {
- android.util.Log.e("ProviderRepo", "Initial M3U sync failed: ${e.message}")
+ providerDao.deactivateAll()
+ providerDao.activate(providerData.id)
+
+ when (val syncResult = syncManager.sync(providerData.id, force = false, onProgress = onProgress)) {
+ is Result.Success -> {
+ val finalStatus = if (syncManager.syncState.value is SyncState.Partial) {
+ ProviderStatus.PARTIAL
+ } else {
+ ProviderStatus.ACTIVE
+ }
+ updateProviderSyncStatus(providerData.id, finalStatus, System.currentTimeMillis())
+ Result.success(providerData.copy(status = finalStatus))
+ }
+ is Result.Error -> {
+ updateProviderSyncStatus(providerData.id, ProviderStatus.ERROR)
+ Result.error(
+ "Playlist saved, but initial sync failed: ${syncResult.message}",
+ syncResult.exception
+ )
+ }
+ is Result.Loading -> Result.error("Unexpected loading state")
}
- Result.success(providerData)
} catch (e: Exception) {
Result.error("Failed to add M3U provider: ${e.message}", e)
}
@@ -178,18 +210,39 @@ class ProviderRepositoryImpl @Inject constructor(
*/
override suspend fun refreshProviderData(
providerId: Long,
+ force: Boolean,
onProgress: ((String) -> Unit)?
- ): Result<Unit> = syncManager.sync(providerId, onProgress)
+ ): Result<Unit> {
+ return when (val syncResult = syncManager.sync(providerId, force = force, onProgress = onProgress)) {
+ is Result.Success -> {
+ val finalStatus = if (syncManager.syncState.value is SyncState.Partial) {
+ ProviderStatus.PARTIAL
+ } else {
+ ProviderStatus.ACTIVE
+ }
+ updateProviderSyncStatus(providerId, finalStatus, System.currentTimeMillis())
+ syncResult
+ }
+ is Result.Error -> {
+ updateProviderSyncStatus(providerId, ProviderStatus.ERROR)
+ syncResult
+ }
+ is Result.Loading -> Result.error("Unexpected loading state")
+ }
+ }
override suspend fun buildCatchUpUrl(providerId: Long, streamId: Long, start: Long, end: Long): String? {
- val provider = providerDao.getById(providerId) ?: return null
- return if (provider.type == ProviderType.XTREAM_CODES.name) {
- createXtreamProvider(providerId, provider.serverUrl, provider.username, provider.password)
- .buildCatchUpUrl(streamId, start, end)
+ val providerEntity = providerDao.getById(providerId) ?: return null
+ val provider = providerEntity.toPublicDomain()
+ val providerPassword = CredentialCrypto.decryptIfNeeded(providerEntity.password)
+ val channel = channelDao.getById(streamId)
+ val resolvedStreamId = channel?.streamId?.takeIf { it > 0 } ?: streamId
+ return if (provider.type == ProviderType.XTREAM_CODES) {
+ createXtreamProvider(providerId, provider.serverUrl, provider.username, providerPassword)
+ .buildCatchUpUrl(resolvedStreamId, start, end)
} else {
// M3U catch-up
- val channel = channelDao.getById(streamId) ?: return null
- val source = channel.catchUpSource ?: return null
+ val source = channel?.catchUpSource ?: return null
// Substitute variables in template
source.replace("{start}", start.toString())
@@ -213,4 +266,26 @@ class ProviderRepositoryImpl @Inject constructor(
username = username,
password = password
)
+
+ private fun ProviderEntity.toPublicDomain(): Provider {
+ return toDomain().copy(password = "")
+ }
+
+ private fun Provider.toSecureEntity(): ProviderEntity {
+ val encryptedPassword = CredentialCrypto.encryptIfNeeded(password)
+ return copy(password = encryptedPassword).toEntity()
+ }
+
+ private suspend fun updateProviderSyncStatus(
+ providerId: Long,
+ status: ProviderStatus,
+ lastSyncedAt: Long? = null
+ ) {
+ val current = providerDao.getById(providerId) ?: return
+ val updated = current.copy(
+ status = status.name,
+ lastSyncedAt = lastSyncedAt ?: current.lastSyncedAt
+ )
+ providerDao.update(updated)
+ }
}
diff --git a/data/src/main/java/com/streamvault/data/repository/SeriesRepositoryImpl.kt b/data/src/main/java/com/streamvault/data/repository/SeriesRepositoryImpl.kt
index a5ab3209..d438018f 100644
--- a/data/src/main/java/com/streamvault/data/repository/SeriesRepositoryImpl.kt
+++ b/data/src/main/java/com/streamvault/data/repository/SeriesRepositoryImpl.kt
@@ -3,10 +3,14 @@ package com.streamvault.data.repository
import com.streamvault.data.local.dao.*
import com.streamvault.data.local.entity.*
import com.streamvault.data.mapper.*
+import com.streamvault.data.remote.xtream.XtreamApiService
+import com.streamvault.data.remote.xtream.XtreamProvider
+import com.streamvault.data.security.CredentialCrypto
import com.streamvault.domain.model.*
import com.streamvault.domain.repository.SeriesRepository
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.combine
+import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.map
import javax.inject.Inject
import com.streamvault.data.preferences.PreferencesRepository
@@ -17,6 +21,8 @@ class SeriesRepositoryImpl @Inject constructor(
private val seriesDao: SeriesDao,
private val episodeDao: EpisodeDao,
private val categoryDao: CategoryDao,
+ private val providerDao: ProviderDao,
+ private val xtreamApiService: XtreamApiService,
private val preferencesRepository: PreferencesRepository
) : SeriesRepository {
@@ -44,6 +50,9 @@ class SeriesRepositoryImpl @Inject constructor(
}
}.map { list: List<SeriesEntity> -> list.map { it.toDomain() } }
+ override fun getSeriesByIds(ids: List<Long>): Flow<List<Series>> =
+ seriesDao.getByIds(ids).map { entities -> entities.map { it.toDomain() } }
+
override fun getCategories(providerId: Long): Flow<List<Category>> =
combine(
categoryDao.getByProviderAndType(providerId, ContentType.SERIES.name),
@@ -58,23 +67,141 @@ class SeriesRepositoryImpl @Inject constructor(
}
override fun searchSeries(providerId: Long, query: String): Flow<List<Series>> =
- combine(
- seriesDao.search(providerId, query),
- preferencesRepository.parentalControlLevel
- ) { entities: List<SeriesEntity>, level: Int ->
- if (level == 2) {
- entities.filter { !it.isUserProtected }
- } else {
- entities
- }
- }.map { list: List<SeriesEntity> -> list.map { it.toDomain() } }
+ query.toFtsPrefixQuery().let { ftsQuery ->
+ if (ftsQuery.isBlank()) {
+ flowOf(emptyList())
+ } else combine(
+ seriesDao.search(providerId, ftsQuery),
+ preferencesRepository.parentalControlLevel
+ ) { entities: List<SeriesEntity>, level: Int ->
+ if (level == 2) {
+ entities.filter { !it.isUserProtected }
+ } else {
+ entities
+ }
+ }.map { list: List<SeriesEntity> -> list.map { it.toDomain() } }
+ }
override suspend fun getSeriesById(seriesId: Long): Series? =
seriesDao.getById(seriesId)?.toDomain()
override suspend fun getSeriesDetails(providerId: Long, seriesId: Long): Result<Series> {
- val series = seriesDao.getById(seriesId)?.toDomain()
- return if (series != null) Result.success(series) else Result.error("Series not found")
+ val seriesEntity = seriesDao.getById(seriesId)
+ ?: return Result.error("Series not found")
+
+ val provider = providerDao.getById(providerId)
+ ?: return Result.error("Provider not found")
+
+ // M3U and other non-Xtream providers have no standardized series-detail endpoint.
+ if (provider.type != ProviderType.XTREAM_CODES.name) {
+ return Result.success(buildSeriesWithPersistedEpisodes(seriesEntity))
+ }
+
+ val xtreamProvider = XtreamProvider(
+ providerId = providerId,
+ api = xtreamApiService,
+ serverUrl = provider.serverUrl,
+ username = provider.username,
+ password = CredentialCrypto.decryptIfNeeded(provider.password)
+ )
+
+ return when (val remoteResult = xtreamProvider.getSeriesInfo(seriesEntity.seriesId)) {
+ is Result.Success -> {
+ val remoteSeries = remoteResult.data
+
+ val updatedSeries = seriesEntity.copy(
+ name = remoteSeries.name.ifBlank { seriesEntity.name },
+ posterUrl = remoteSeries.posterUrl ?: seriesEntity.posterUrl,
+ backdropUrl = remoteSeries.backdropUrl ?: seriesEntity.backdropUrl,
+ categoryId = remoteSeries.categoryId ?: seriesEntity.categoryId,
+ categoryName = remoteSeries.categoryName ?: seriesEntity.categoryName,
+ plot = remoteSeries.plot ?: seriesEntity.plot,
+ cast = remoteSeries.cast ?: seriesEntity.cast,
+ director = remoteSeries.director ?: seriesEntity.director,
+ genre = remoteSeries.genre ?: seriesEntity.genre,
+ releaseDate = remoteSeries.releaseDate ?: seriesEntity.releaseDate,
+ rating = if (remoteSeries.rating > 0f) remoteSeries.rating else seriesEntity.rating,
+ tmdbId = remoteSeries.tmdbId ?: seriesEntity.tmdbId,
+ youtubeTrailer = remoteSeries.youtubeTrailer ?: seriesEntity.youtubeTrailer,
+ episodeRunTime = remoteSeries.episodeRunTime ?: seriesEntity.episodeRunTime,
+ lastModified = if (remoteSeries.lastModified > 0) remoteSeries.lastModified else seriesEntity.lastModified
+ )
+ seriesDao.update(updatedSeries)
+
+ val episodesToPersist = remoteSeries.seasons
+ .flatMap { season ->
+ season.episodes.map { episode ->
+ val remoteEpisodeId = episode.episodeId.takeIf { it > 0 } ?: episode.id
+ episode.copy(
+ id = 0,
+ episodeId = remoteEpisodeId,
+ seasonNumber = if (episode.seasonNumber > 0) episode.seasonNumber else season.seasonNumber,
+ seriesId = seriesEntity.id,
+ providerId = providerId
+ ).toEntity().copy(
+ id = 0,
+ episodeId = remoteEpisodeId,
+ seriesId = seriesEntity.id,
+ providerId = providerId
+ )
+ }
+ }
+
+ if (episodesToPersist.isNotEmpty()) {
+ episodeDao.replaceAll(seriesEntity.id, providerId, episodesToPersist)
+ }
+
+ val persistedSeries = seriesDao.getById(seriesEntity.id) ?: updatedSeries
+ val persistedEpisodes = episodeDao.getBySeriesSync(seriesEntity.id).map { it.toDomain() }
+ val persistedByRemoteEpisodeId = persistedEpisodes.associateBy {
+ it.episodeId.takeIf { remoteId -> remoteId > 0 } ?: it.id
+ }
+
+ val mergedSeasons = if (remoteSeries.seasons.isNotEmpty()) {
+ remoteSeries.seasons
+ .sortedBy { it.seasonNumber }
+ .map { remoteSeason ->
+ val mergedEpisodes = remoteSeason.episodes.map { remoteEpisode ->
+ val remoteEpisodeId = remoteEpisode.episodeId.takeIf { it > 0 } ?: remoteEpisode.id
+ persistedByRemoteEpisodeId[remoteEpisodeId] ?: remoteEpisode.copy(
+ episodeId = remoteEpisodeId,
+ seriesId = seriesEntity.id,
+ providerId = providerId
+ )
+ }
+ remoteSeason.copy(
+ episodes = mergedEpisodes,
+ episodeCount = mergedEpisodes.size
+ )
+ }
+ } else {
+ persistedEpisodes.groupBy { it.seasonNumber }
+ .entries
+ .sortedBy { it.key }
+ .map { (seasonNumber, episodes) ->
+ Season(
+ seasonNumber = seasonNumber,
+ name = "Season $seasonNumber",
+ episodes = episodes,
+ episodeCount = episodes.size
+ )
+ }
+ }
+
+ Result.success(
+ persistedSeries.toDomain().copy(seasons = mergedSeasons)
+ )
+ }
+ is Result.Error -> {
+ val localSeries = buildSeriesWithPersistedEpisodes(seriesEntity)
+ if (localSeries.seasons.isNotEmpty()) {
+ Result.success(localSeries)
+ } else {
+ Result.error(remoteResult.message, remoteResult.exception)
+ }
+ }
+ is Result.Loading -> Result.error("Unexpected loading state")
+ }
}
override suspend fun getEpisodeStreamUrl(episode: Episode): Result<String> =
@@ -90,4 +217,29 @@ class SeriesRepositoryImpl @Inject constructor(
override suspend fun updateEpisodeWatchProgress(episodeId: Long, progress: Long) {
episodeDao.updateWatchProgress(episodeId, progress)
}
+
+ private suspend fun buildSeriesWithPersistedEpisodes(seriesEntity: SeriesEntity): Series {
+ val episodes = episodeDao.getBySeriesSync(seriesEntity.id).map { it.toDomain() }
+ val seasons = episodes.groupBy { it.seasonNumber }
+ .entries
+ .sortedBy { it.key }
+ .map { (seasonNumber, seasonEpisodes) ->
+ Season(
+ seasonNumber = seasonNumber,
+ name = "Season $seasonNumber",
+ episodes = seasonEpisodes,
+ episodeCount = seasonEpisodes.size
+ )
+ }
+ return seriesEntity.toDomain().copy(seasons = seasons)
+ }
+
+ private fun String.toFtsPrefixQuery(): String {
+ val tokens = trim()
+ .split(Regex("\\s+"))
+ .map { token -> token.replace(Regex("[^\\p{L}\\p{N}_]"), "") }
+ .filter { it.length >= 2 }
+
+ return tokens.joinToString(" AND ") { "$it*" }
+ }
}
diff --git a/data/src/main/java/com/streamvault/data/security/CredentialCrypto.kt b/data/src/main/java/com/streamvault/data/security/CredentialCrypto.kt
new file mode 100644
index 00000000..18fa3de3
--- /dev/null
+++ b/data/src/main/java/com/streamvault/data/security/CredentialCrypto.kt
@@ -0,0 +1,82 @@
+package com.streamvault.data.security
+
+import android.security.keystore.KeyGenParameterSpec
+import android.security.keystore.KeyProperties
+import java.security.KeyStore
+import javax.crypto.Cipher
+import javax.crypto.KeyGenerator
+import javax.crypto.SecretKey
+import javax.crypto.spec.GCMParameterSpec
+
+/**
+ * AES-GCM credential crypto backed by Android Keystore.
+ *
+ * Values are persisted as: enc:v1:<base64(iv + ciphertext)>
+ */
+object CredentialCrypto {
+ private const val KEYSTORE_TYPE = "AndroidKeyStore"
+ private const val KEY_ALIAS = "streamvault_credentials"
+ private const val TRANSFORMATION = "AES/GCM/NoPadding"
+ private const val IV_SIZE_BYTES = 12
+ private const val AUTH_TAG_BITS = 128
+ private const val PREFIX = "enc:v1:"
+
+ fun encryptIfNeeded(value: String): String {
+ if (value.isBlank() || value.startsWith(PREFIX)) return value
+
+ return try {
+ val cipher = Cipher.getInstance(TRANSFORMATION)
+ cipher.init(Cipher.ENCRYPT_MODE, getOrCreateSecretKey())
+ val iv = cipher.iv
+ val encrypted = cipher.doFinal(value.toByteArray(Charsets.UTF_8))
+ val packed = iv + encrypted
+ PREFIX + java.util.Base64.getEncoder().encodeToString(packed)
+ } catch (_: Exception) {
+ // Fail closed would break existing users; keep original value if crypto fails.
+ value
+ }
+ }
+
+ fun decryptIfNeeded(value: String): String {
+ if (!value.startsWith(PREFIX)) return value
+
+ return try {
+ val payload = value.removePrefix(PREFIX)
+ val bytes = java.util.Base64.getDecoder().decode(payload)
+ if (bytes.size <= IV_SIZE_BYTES) return value
+
+ val iv = bytes.copyOfRange(0, IV_SIZE_BYTES)
+ val ciphertext = bytes.copyOfRange(IV_SIZE_BYTES, bytes.size)
+
+ val cipher = Cipher.getInstance(TRANSFORMATION)
+ cipher.init(
+ Cipher.DECRYPT_MODE,
+ getOrCreateSecretKey(),
+ GCMParameterSpec(AUTH_TAG_BITS, iv)
+ )
+ String(cipher.doFinal(ciphertext), Charsets.UTF_8)
+ } catch (_: Exception) {
+ value
+ }
+ }
+
+ private fun getOrCreateSecretKey(): SecretKey {
+ val keyStore = KeyStore.getInstance(KEYSTORE_TYPE).apply { load(null) }
+ val existing = keyStore.getKey(KEY_ALIAS, null) as? SecretKey
+ if (existing != null) return existing
+
+ val keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, KEYSTORE_TYPE)
+ val spec = KeyGenParameterSpec.Builder(
+ KEY_ALIAS,
+ KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT
+ )
+ .setBlockModes(KeyProperties.BLOCK_MODE_GCM)
+ .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
+ .setRandomizedEncryptionRequired(true)
+ .setUserAuthenticationRequired(false)
+ .build()
+
+ keyGenerator.init(spec)
+ return keyGenerator.generateKey()
+ }
+}
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 d42df0fb..63b1de20 100644
--- a/data/src/main/java/com/streamvault/data/sync/SyncManager.kt
+++ b/data/src/main/java/com/streamvault/data/sync/SyncManager.kt
@@ -11,7 +11,10 @@ import com.streamvault.data.mapper.*
import com.streamvault.data.parser.M3uParser
import com.streamvault.data.remote.xtream.XtreamApiService
import com.streamvault.data.remote.xtream.XtreamProvider
+import com.streamvault.data.security.CredentialCrypto
+import com.streamvault.data.util.AdultContentClassifier
import com.streamvault.domain.model.Channel
+import com.streamvault.domain.model.ContentType
import com.streamvault.domain.model.Movie
import com.streamvault.domain.model.Provider
import com.streamvault.domain.model.ProviderType
@@ -25,16 +28,24 @@ import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import com.streamvault.domain.repository.SyncMetadataRepository
import com.streamvault.domain.model.SyncMetadata
+import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import okhttp3.OkHttpClient
import okhttp3.Request
+import java.io.IOException
import java.security.MessageDigest
import javax.inject.Inject
import javax.inject.Singleton
private const val TAG = "SyncManager"
+enum class SyncRepairSection {
+ EPG,
+ MOVIES,
+ SERIES
+}
+
/**
* Centralised sync engine that owns the state machine and all data refresh logic.
*
@@ -58,6 +69,11 @@ class SyncManager @Inject constructor(
private val okHttpClient: OkHttpClient,
private val syncMetadataRepository: SyncMetadataRepository
) {
+ private data class SyncOutcome(
+ val partial: Boolean = false,
+ val warnings: List<String> = emptyList()
+ )
+
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
private val _syncState = MutableStateFlow<SyncState>(SyncState.Idle)
@@ -71,21 +87,31 @@ class SyncManager @Inject constructor(
*/
suspend fun sync(
providerId: Long,
+ force: Boolean = false,
onProgress: ((String) -> Unit)? = null
): com.streamvault.domain.model.Result<Unit> {
val providerEntity = providerDao.getById(providerId)
?: return com.streamvault.domain.model.Result.error("Provider $providerId not found")
- val provider = providerEntity.toDomain()
+ val provider = providerEntity
+ .copy(password = CredentialCrypto.decryptIfNeeded(providerEntity.password))
+ .toDomain()
_syncState.value = SyncState.Syncing("Starting…")
return try {
- when (provider.type) {
- ProviderType.XTREAM_CODES -> syncXtream(provider, onProgress)
- ProviderType.M3U -> syncM3u(provider, onProgress)
+ val outcome = when (provider.type) {
+ ProviderType.XTREAM_CODES -> syncXtream(provider, force, onProgress)
+ ProviderType.M3U -> syncM3u(provider, force, onProgress)
}
providerDao.updateSyncTime(providerId, System.currentTimeMillis())
- _syncState.value = SyncState.Success()
+ if (outcome.partial) {
+ _syncState.value = SyncState.Partial(
+ message = "Sync completed with warnings",
+ warnings = outcome.warnings
+ )
+ } else {
+ _syncState.value = SyncState.Success()
+ }
com.streamvault.domain.model.Result.success(Unit)
} catch (e: Exception) {
Log.e(TAG, "Sync failed for provider $providerId: ${e.message}", e)
@@ -95,17 +121,49 @@ class SyncManager @Inject constructor(
}
/** Fire-and-forget variant — launches on the internal scope so callers don't need to await. */
- fun syncAsync(providerId: Long, onProgress: ((String) -> Unit)? = null) {
- scope.launch { sync(providerId, onProgress) }
+ fun syncAsync(providerId: Long, force: Boolean = false, onProgress: ((String) -> Unit)? = null) {
+ scope.launch { sync(providerId, force, onProgress) }
}
fun resetState() {
_syncState.value = SyncState.Idle
}
+ suspend fun retrySection(
+ providerId: Long,
+ section: SyncRepairSection,
+ onProgress: ((String) -> Unit)? = null
+ ): com.streamvault.domain.model.Result<Unit> {
+ val providerEntity = providerDao.getById(providerId)
+ ?: return com.streamvault.domain.model.Result.error("Provider $providerId not found")
+
+ val provider = providerEntity
+ .copy(password = CredentialCrypto.decryptIfNeeded(providerEntity.password))
+ .toDomain()
+
+ return try {
+ when (section) {
+ SyncRepairSection.EPG -> syncEpgOnly(provider, onProgress)
+ SyncRepairSection.MOVIES -> syncMoviesOnly(provider, onProgress)
+ SyncRepairSection.SERIES -> syncSeriesOnly(provider, onProgress)
+ }
+ _syncState.value = SyncState.Success()
+ com.streamvault.domain.model.Result.success(Unit)
+ } catch (e: Exception) {
+ Log.e(TAG, "Section retry failed for provider $providerId [$section]: ${e.message}", e)
+ _syncState.value = SyncState.Error(e.message ?: "Retry failed", e)
+ com.streamvault.domain.model.Result.error(e.message ?: "Retry failed", e)
+ }
+ }
+
// ── Xtream sync ─────────────────────────────────────────────────
- private suspend fun syncXtream(provider: Provider, onProgress: ((String) -> Unit)?) {
+ private suspend fun syncXtream(
+ provider: Provider,
+ force: Boolean,
+ onProgress: ((String) -> Unit)?
+ ): SyncOutcome {
+ val warnings = mutableListOf<String>()
progress(onProgress, "Connecting to server…")
val api = XtreamProvider(
providerId = provider.id,
@@ -119,13 +177,13 @@ class SyncManager @Inject constructor(
val now = System.currentTimeMillis()
// Live (TTL 24h)
- if (!isCacheValid(metadata.lastLiveSync, TTL_24_HOURS, now)) {
+ if (force || !isCacheValid(metadata.lastLiveSync, TTL_24_HOURS, now)) {
progress(onProgress, "Downloading Live TV…")
- val cats = api.getLiveCategories().getOrThrow("Live categories")
+ val cats = retryTransient { api.getLiveCategories().getOrThrow("Live categories") }
Log.d(TAG, "Saving ${cats.size} live categories")
categoryDao.replaceAll(provider.id, "LIVE", cats.map { it.toEntity(provider.id) })
- val channels = api.getLiveStreams().getOrThrow("Live streams")
+ val channels = retryTransient { api.getLiveStreams().getOrThrow("Live streams") }
Log.d(TAG, "Saving ${channels.size} channels")
channelDao.replaceAll(provider.id, channels.map { it.toEntity() })
@@ -136,72 +194,92 @@ class SyncManager @Inject constructor(
}
// VOD (TTL 24h)
- if (!isCacheValid(metadata.lastMovieSync, TTL_24_HOURS, now)) {
+ if (force || !isCacheValid(metadata.lastMovieSync, TTL_24_HOURS, now)) {
progress(onProgress, "Downloading Movies…")
- val cats = api.getVodCategories().getOrNull()
+ val catsResult = runCatching { retryTransient { api.getVodCategories().getOrThrow("VOD categories") } }
+ val cats = catsResult.getOrNull()
if (cats != null) {
Log.d(TAG, "Saving ${cats.size} VOD categories")
categoryDao.replaceAll(provider.id, "MOVIE", cats.map { it.toEntity(provider.id) })
+ } else {
+ warnings.add("Movies categories sync failed")
}
- val movies = api.getVodStreams().getOrNull()
+ val moviesResult = runCatching { retryTransient { api.getVodStreams().getOrThrow("VOD streams") } }
+ val movies = moviesResult.getOrNull()
if (movies != null) {
Log.d(TAG, "Saving ${movies.size} movies")
movieDao.replaceAll(provider.id, movies.map { it.toEntity() })
metadata = metadata.copy(lastMovieSync = now, movieCount = movies.size)
syncMetadataRepository.updateMetadata(metadata)
+ } else {
+ warnings.add("Movies streams sync failed")
}
} else {
Log.d(TAG, "Skipping Movies sync (cache still valid)")
}
// Series (TTL 24h)
- if (!isCacheValid(metadata.lastSeriesSync, TTL_24_HOURS, now)) {
+ if (force || !isCacheValid(metadata.lastSeriesSync, TTL_24_HOURS, now)) {
progress(onProgress, "Downloading Series…")
- val cats = api.getSeriesCategories().getOrNull()
+ val catsResult = runCatching { retryTransient { api.getSeriesCategories().getOrThrow("Series categories") } }
+ val cats = catsResult.getOrNull()
if (cats != null) {
Log.d(TAG, "Saving ${cats.size} series categories")
categoryDao.replaceAll(provider.id, "SERIES", cats.map { it.toEntity(provider.id) })
+ } else {
+ warnings.add("Series categories sync failed")
}
- val seriesList = api.getSeriesList().getOrNull()
+ val seriesResult = runCatching { retryTransient { api.getSeriesList().getOrThrow("Series list") } }
+ val seriesList = seriesResult.getOrNull()
if (seriesList != null) {
Log.d(TAG, "Saving ${seriesList.size} series")
seriesDao.replaceAll(provider.id, seriesList.map { it.toEntity() })
metadata = metadata.copy(lastSeriesSync = now, seriesCount = seriesList.size)
syncMetadataRepository.updateMetadata(metadata)
+ } else {
+ warnings.add("Series list sync failed")
}
} else {
Log.d(TAG, "Skipping Series sync (cache still valid)")
}
// EPG (TTL 6h)
- if (!isCacheValid(metadata.lastEpgSync, TTL_6_HOURS, now)) {
+ if (force || !isCacheValid(metadata.lastEpgSync, TTL_6_HOURS, now)) {
try {
progress(onProgress, "Downloading EPG…")
val base = provider.serverUrl.trimEnd('/')
val xmltvUrl = provider.epgUrl.ifBlank { "$base/xmltv.php?username=${provider.username}&password=${provider.password}" }
- epgRepository.refreshEpg(provider.id, xmltvUrl)
+ retryTransient { epgRepository.refreshEpg(provider.id, xmltvUrl) }
metadata = metadata.copy(lastEpgSync = now)
syncMetadataRepository.updateMetadata(metadata)
} catch (e: Exception) {
Log.e(TAG, "EPG sync failed (non-fatal): ${e.message}")
+ warnings.add("EPG sync failed")
}
} else {
Log.d(TAG, "Skipping EPG sync (cache still valid)")
}
+
+ return if (warnings.isEmpty()) SyncOutcome() else SyncOutcome(partial = true, warnings = warnings)
}
// ── M3U sync ────────────────────────────────────────────────────
- private suspend fun syncM3u(provider: Provider, onProgress: ((String) -> Unit)?) {
+ private suspend fun syncM3u(
+ provider: Provider,
+ force: Boolean,
+ onProgress: ((String) -> Unit)?
+ ): SyncOutcome {
+ val warnings = mutableListOf<String>()
var metadata = syncMetadataRepository.getMetadata(provider.id) ?: SyncMetadata(provider.id)
val now = System.currentTimeMillis()
// M3U must be fully re-downloaded (no granular deltas), so we use lastLiveSync
// as the general indicator for the playlist payload TTL (24h)
- if (!isCacheValid(metadata.lastLiveSync, TTL_24_HOURS, now)) {
+ if (force || !isCacheValid(metadata.lastLiveSync, TTL_24_HOURS, now)) {
withContext(Dispatchers.IO) {
Log.d(TAG, "Starting M3U refresh for ${provider.name}")
progress(onProgress, "Downloading Playlist…")
@@ -209,11 +287,18 @@ class SyncManager @Inject constructor(
val inputStream = if (urlStr.startsWith("file://")) {
java.io.File(java.net.URI(urlStr)).inputStream()
} else {
- val response = okHttpClient.newCall(Request.Builder().url(urlStr).build()).execute()
- if (!response.isSuccessful) {
- throw Exception("Failed to download M3U: HTTP ${response.code}")
+ val payload = retryTransient {
+ okHttpClient.newCall(Request.Builder().url(urlStr).build()).execute().use { response ->
+ if (!response.isSuccessful) {
+ if (response.code in 500..599 || response.code == 429) {
+ throw IOException("Transient HTTP ${response.code}")
+ }
+ throw IllegalStateException("Failed to download M3U: HTTP ${response.code}")
+ }
+ response.body?.bytes() ?: throw IllegalStateException("Empty M3U response")
+ }
}
- response.body?.byteStream() ?: throw Exception("Empty M3U response")
+ payload.inputStream()
}
progress(onProgress, "Parsing Playlist…")
@@ -222,14 +307,21 @@ class SyncManager @Inject constructor(
val header = parseResult.header
Log.d(TAG, "Parsed ${entries.size} M3U entries")
+ if (entries.isEmpty()) {
+ throw IllegalStateException("Playlist is empty or contains no supported entries")
+ }
+
// Auto-update EPG URL from header if missing
if (provider.epgUrl.isBlank() && !header.tvgUrl.isNullOrBlank()) {
- Log.d(TAG, "Auto-discovered EPG URL from header: ${header.tvgUrl}")
+ Log.d(TAG, "Auto-discovered EPG URL from header: ${redactUrlForLogs(header.tvgUrl)}")
providerDao.updateEpgUrl(provider.id, header.tvgUrl)
}
val liveEntries = entries.filter { !isVodEntry(it) }
val vodEntries = entries.filter { isVodEntry(it) }
+ if (liveEntries.isEmpty() && vodEntries.isEmpty()) {
+ throw IllegalStateException("Playlist contains no playable live or VOD entries")
+ }
// ── Categories ──────────────────────────────────────
val liveGroups = liveEntries.map { it.groupTitle }.distinct()
@@ -237,11 +329,13 @@ class SyncManager @Inject constructor(
val liveCategories = liveGroups.mapIndexed { i, name ->
CategoryEntity(categoryId = (i + 1).toLong(), name = name,
- parentId = 0, type = "LIVE", providerId = provider.id)
+ parentId = 0, type = "LIVE", providerId = provider.id,
+ isAdult = AdultContentClassifier.isAdultCategoryName(name))
}
val vodCategories = vodGroups.mapIndexed { i, name ->
CategoryEntity(categoryId = (i + 10_000).toLong(), name = name,
- parentId = 0, type = "MOVIE", providerId = provider.id)
+ parentId = 0, type = "MOVIE", providerId = provider.id,
+ isAdult = AdultContentClassifier.isAdultCategoryName(name))
}
progress(onProgress, "Saving Channels…")
@@ -253,8 +347,9 @@ class SyncManager @Inject constructor(
// ── Channels with stable hash IDs ───────────────────
val channels = liveEntries.map { entry ->
+ val stableStreamId = stableId(provider.id, entry.tvgId, entry.url)
Channel(
- id = stableId(provider.id, entry.tvgId, entry.url),
+ id = 0,
name = entry.name,
logoUrl = entry.tvgLogo,
groupTitle = entry.groupTitle,
@@ -266,7 +361,9 @@ class SyncManager @Inject constructor(
catchUpSupported = entry.catchUp != null,
catchUpDays = entry.catchUpDays ?: 0,
catchUpSource = entry.catchUpSource,
- providerId = provider.id
+ providerId = provider.id,
+ isAdult = AdultContentClassifier.isAdultCategoryName(entry.groupTitle),
+ streamId = stableStreamId
).toEntity()
}
Log.d(TAG, "Saving ${channels.size} channels")
@@ -275,8 +372,9 @@ class SyncManager @Inject constructor(
// ── Movies with stable hash IDs ─────────────────────
progress(onProgress, "Saving Movies…")
val movies = vodEntries.map { entry ->
+ val stableStreamId = stableId(provider.id, entry.tvgId, entry.url)
Movie(
- id = stableId(provider.id, entry.tvgId, entry.url),
+ id = 0,
name = entry.name,
posterUrl = entry.tvgLogo,
categoryId = vodCategoryMap[entry.groupTitle],
@@ -285,7 +383,9 @@ class SyncManager @Inject constructor(
providerId = provider.id,
rating = entry.rating?.toFloatOrNull() ?: 0f,
year = entry.year,
- genre = entry.genre
+ genre = entry.genre,
+ isAdult = AdultContentClassifier.isAdultCategoryName(entry.groupTitle),
+ streamId = stableStreamId
).toEntity()
}
Log.d(TAG, "Saving ${movies.size} movies")
@@ -305,19 +405,163 @@ class SyncManager @Inject constructor(
// Try EPG refresh if standard M3U provider linked an EPG URL or auto-discovered one
val currentEpgUrl = providerDao.getById(provider.id)?.epgUrl ?: provider.epgUrl
if (!currentEpgUrl.isNullOrBlank()) {
- if (!isCacheValid(metadata.lastEpgSync, TTL_6_HOURS, now)) {
+ if (force || !isCacheValid(metadata.lastEpgSync, TTL_6_HOURS, now)) {
try {
progress(onProgress, "Downloading EPG…")
- epgRepository.refreshEpg(provider.id, currentEpgUrl)
+ retryTransient { epgRepository.refreshEpg(provider.id, currentEpgUrl) }
metadata = metadata.copy(lastEpgSync = now)
syncMetadataRepository.updateMetadata(metadata)
} catch (e: Exception) {
Log.e(TAG, "EPG sync failed (non-fatal): ${e.message}")
+ warnings.add("EPG sync failed")
}
} else {
Log.d(TAG, "Skipping EPG sync (cache still valid)")
}
}
+
+ return if (warnings.isEmpty()) SyncOutcome() else SyncOutcome(partial = true, warnings = warnings)
+ }
+
+ private suspend fun syncEpgOnly(
+ provider: Provider,
+ onProgress: ((String) -> Unit)?
+ ) {
+ progress(onProgress, "Retrying EPG…")
+ val epgUrl = when (provider.type) {
+ ProviderType.XTREAM_CODES -> {
+ val base = provider.serverUrl.trimEnd('/')
+ provider.epgUrl.ifBlank { "$base/xmltv.php?username=${provider.username}&password=${provider.password}" }
+ }
+ ProviderType.M3U -> {
+ providerDao.getById(provider.id)?.epgUrl ?: provider.epgUrl
+ }
+ }
+ if (epgUrl.isBlank()) {
+ throw IllegalStateException("No EPG URL configured for this provider")
+ }
+ retryTransient { epgRepository.refreshEpg(provider.id, epgUrl) }
+ val now = System.currentTimeMillis()
+ val metadata = (syncMetadataRepository.getMetadata(provider.id) ?: SyncMetadata(provider.id))
+ .copy(lastEpgSync = now)
+ syncMetadataRepository.updateMetadata(metadata)
+ }
+
+ private suspend fun syncMoviesOnly(
+ provider: Provider,
+ onProgress: ((String) -> Unit)?
+ ) {
+ val now = System.currentTimeMillis()
+ when (provider.type) {
+ ProviderType.XTREAM_CODES -> {
+ progress(onProgress, "Retrying Movies…")
+ val api = XtreamProvider(
+ providerId = provider.id,
+ api = xtreamApiService,
+ serverUrl = provider.serverUrl,
+ username = provider.username,
+ password = provider.password
+ )
+ val cats = retryTransient { api.getVodCategories().getOrThrow("VOD categories") }
+ categoryDao.replaceAll(provider.id, "MOVIE", cats.map { it.toEntity(provider.id) })
+
+ val movies = retryTransient { api.getVodStreams().getOrThrow("VOD streams") }
+ movieDao.replaceAll(provider.id, movies.map { it.toEntity() })
+
+ val metadata = (syncMetadataRepository.getMetadata(provider.id) ?: SyncMetadata(provider.id))
+ .copy(lastMovieSync = now, movieCount = movies.size)
+ syncMetadataRepository.updateMetadata(metadata)
+ }
+ ProviderType.M3U -> {
+ progress(onProgress, "Retrying Movies…")
+ withContext(Dispatchers.IO) {
+ val parseResult = loadM3uParseResult(provider)
+ val entries = parseResult.entries
+ val vodEntries = entries.filter { isVodEntry(it) }
+ if (vodEntries.isEmpty()) {
+ throw IllegalStateException("Playlist contains no movie entries")
+ }
+ val vodGroups = vodEntries.map { it.groupTitle }.distinct()
+ val vodCategories = vodGroups.mapIndexed { i, name ->
+ CategoryEntity(
+ categoryId = (i + 10_000).toLong(),
+ name = name,
+ parentId = 0,
+ type = "MOVIE",
+ providerId = provider.id,
+ isAdult = AdultContentClassifier.isAdultCategoryName(name)
+ )
+ }
+ categoryDao.replaceAll(provider.id, "MOVIE", vodCategories)
+ val vodCategoryMap = vodGroups.withIndex().associate { (i, n) -> n to (i + 10_000).toLong() }
+ val movies = vodEntries.map { entry ->
+ val stableStreamId = stableId(provider.id, entry.tvgId, entry.url)
+ Movie(
+ id = 0,
+ name = entry.name,
+ posterUrl = entry.tvgLogo,
+ categoryId = vodCategoryMap[entry.groupTitle],
+ categoryName = entry.groupTitle,
+ streamUrl = entry.url,
+ providerId = provider.id,
+ rating = entry.rating?.toFloatOrNull() ?: 0f,
+ year = entry.year,
+ genre = entry.genre,
+ isAdult = AdultContentClassifier.isAdultCategoryName(entry.groupTitle),
+ streamId = stableStreamId
+ ).toEntity()
+ }
+ movieDao.replaceAll(provider.id, movies)
+ val metadata = (syncMetadataRepository.getMetadata(provider.id) ?: SyncMetadata(provider.id))
+ .copy(lastMovieSync = now, movieCount = movies.size)
+ syncMetadataRepository.updateMetadata(metadata)
+ }
+ }
+ }
+ }
+
+ private suspend fun syncSeriesOnly(
+ provider: Provider,
+ onProgress: ((String) -> Unit)?
+ ) {
+ if (provider.type != ProviderType.XTREAM_CODES) {
+ throw IllegalStateException("Series retry is available only for Xtream providers")
+ }
+ progress(onProgress, "Retrying Series…")
+ val api = XtreamProvider(
+ providerId = provider.id,
+ api = xtreamApiService,
+ serverUrl = provider.serverUrl,
+ username = provider.username,
+ password = provider.password
+ )
+
+ val cats = retryTransient { api.getSeriesCategories().getOrThrow("Series categories") }
+ categoryDao.replaceAll(provider.id, "SERIES", cats.map { it.toEntity(provider.id) })
+
+ val seriesList = retryTransient { api.getSeriesList().getOrThrow("Series list") }
+ seriesDao.replaceAll(provider.id, seriesList.map { it.toEntity() })
+
+ val now = System.currentTimeMillis()
+ val metadata = (syncMetadataRepository.getMetadata(provider.id) ?: SyncMetadata(provider.id))
+ .copy(lastSeriesSync = now, seriesCount = seriesList.size)
+ syncMetadataRepository.updateMetadata(metadata)
+ }
+
+ private fun loadM3uParseResult(provider: Provider): M3uParser.ParseResult {
+ val urlStr = provider.m3uUrl.ifBlank { provider.serverUrl }
+ val inputStream = if (urlStr.startsWith("file://")) {
+ java.io.File(java.net.URI(urlStr)).inputStream()
+ } else {
+ val payload = okHttpClient.newCall(Request.Builder().url(urlStr).build()).execute().use { response ->
+ if (!response.isSuccessful) {
+ throw IllegalStateException("Failed to download M3U: HTTP ${response.code}")
+ }
+ response.body?.bytes() ?: throw IllegalStateException("Empty M3U response")
+ }
+ payload.inputStream()
+ }
+ return inputStream.use { m3uParser.parse(it) }
}
// ── Helpers ─────────────────────────────────────────────────────
@@ -376,6 +620,55 @@ class SyncManager @Inject constructor(
callback?.invoke(message)
}
+ private fun redactUrlForLogs(url: String?): String {
+ if (url.isNullOrBlank()) return "<empty>"
+ return runCatching {
+ val parsed = java.net.URI(url)
+ val scheme = parsed.scheme ?: "http"
+ val host = parsed.host ?: return@runCatching "<redacted>"
+ val path = parsed.path.orEmpty()
+ "$scheme://$host$path"
+ }.getOrDefault("<redacted>")
+ }
+
+ private suspend fun <T> retryTransient(
+ maxAttempts: Int = 3,
+ initialDelayMs: Long = 700L,
+ block: suspend () -> T
+ ): T {
+ var attempt = 0
+ var delayMs = initialDelayMs
+ var lastError: Throwable? = null
+
+ while (attempt < maxAttempts) {
+ try {
+ return block()
+ } catch (t: Throwable) {
+ lastError = t
+ attempt++
+ if (attempt >= maxAttempts || !isRetryable(t)) {
+ throw t
+ }
+ delay(delayMs)
+ delayMs *= 2
+ }
+ }
+
+ throw lastError ?: IllegalStateException("Unknown sync retry failure")
+ }
+
+ private fun isRetryable(error: Throwable): Boolean {
+ if (error is IOException) return true
+
+ val message = error.message.orEmpty().lowercase()
+ return message.contains("timeout") ||
+ message.contains("timed out") ||
+ message.contains("unable to resolve host") ||
+ message.contains("connection reset") ||
+ message.contains("connect") ||
+ message.contains("network")
+ }
+
companion object {
const val TTL_24_HOURS = 24L * 60 * 60 * 1000L
const val TTL_6_HOURS = 6L * 60 * 60 * 1000L
diff --git a/data/src/main/java/com/streamvault/data/util/AdultContentClassifier.kt b/data/src/main/java/com/streamvault/data/util/AdultContentClassifier.kt
new file mode 100644
index 00000000..98981949
--- /dev/null
+++ b/data/src/main/java/com/streamvault/data/util/AdultContentClassifier.kt
@@ -0,0 +1,42 @@
+package com.streamvault.data.util
+
+import java.util.Locale
+
+object AdultContentClassifier {
+ private val keywords = listOf(
+ "xxx",
+ "adult",
+ "18+",
+ "18 plus",
+ "18plus",
+ "porn",
+ "porno",
+ "sex",
+ "erotic",
+ "hustler",
+ "playboy",
+ "redlight",
+ "red light"
+ )
+
+ fun isAdultCategoryName(name: String?): Boolean {
+ if (name.isNullOrBlank()) return false
+ val normalized = normalize(name)
+ return keywords.any { keyword ->
+ normalized.contains(normalize(keyword))
+ }
+ }
+
+ fun adultCategoryIds(namesById: Map<Long, String>): Set<Long> {
+ return namesById
+ .filterValues(::isAdultCategoryName)
+ .keys
+ }
+
+ private fun normalize(value: String): String {
+ return value
+ .lowercase(Locale.ROOT)
+ .replace(Regex("[^a-z0-9+]+"), " ")
+ .trim()
+ }
+}
diff --git a/data/src/test/java/com/streamvault/data/parser/M3uParserTest.kt b/data/src/test/java/com/streamvault/data/parser/M3uParserTest.kt
index 892df62b..d41b944f 100644
--- a/data/src/test/java/com/streamvault/data/parser/M3uParserTest.kt
+++ b/data/src/test/java/com/streamvault/data/parser/M3uParserTest.kt
@@ -1,7 +1,6 @@
package com.streamvault.data.parser
import com.google.common.truth.Truth.assertThat
-import com.streamvault.data.sync.SyncManager
import org.junit.Before
import org.junit.Test
@@ -33,7 +32,7 @@ class M3uParserTest {
http://stream.example.com/sports.ts
""".trimIndent()
- val entries = parser.parse(m3u.byteInputStream())
+ val entries = parseEntries(m3u)
assertThat(entries).hasSize(3)
@@ -67,7 +66,7 @@ class M3uParserTest {
http://stream.example.com/another.ts
""".trimIndent()
- val entries = parser.parse(m3u.byteInputStream())
+ val entries = parseEntries(m3u)
// "Bad Channel" is skipped since its "URL" line is another #EXTINF
assertThat(entries.map { it.name }).containsExactly("Good Channel", "Another Good Channel")
@@ -75,7 +74,7 @@ class M3uParserTest {
@Test
fun `parse_emptyInputStream_returnsEmptyList`() {
- val entries = parser.parse("".byteInputStream())
+ val entries = parseEntries("")
assertThat(entries).isEmpty()
}
@@ -87,7 +86,7 @@ class M3uParserTest {
http://stream.example.com/channel2.ts
""".trimIndent()
- val entries = parser.parse(m3u.byteInputStream())
+ val entries = parseEntries(m3u)
assertThat(entries).isEmpty()
}
@@ -101,7 +100,7 @@ class M3uParserTest {
http://vod.example.com/movie1.mp4
""".trimIndent()
- val entries = parser.parse(m3u.byteInputStream())
+ val entries = parseEntries(m3u)
assertThat(entries).hasSize(1)
assertThat(entries[0].groupTitle).isEqualTo("Movies HD")
@@ -115,7 +114,7 @@ class M3uParserTest {
http://stream.example.com/aljazeera.ts
""".trimIndent()
- val entries = parser.parse(m3u.byteInputStream())
+ val entries = parseEntries(m3u)
assertThat(entries).hasSize(1)
assertThat(entries[0].groupTitle).isEqualTo("Al Jazeera | Arabic")
@@ -129,7 +128,7 @@ class M3uParserTest {
http://stream.example.com/ch1.ts
""".trimIndent()
- val entries = parser.parse(m3u.byteInputStream())
+ val entries = parseEntries(m3u)
assertThat(entries).hasSize(1)
with(entries[0]) {
@@ -146,7 +145,7 @@ class M3uParserTest {
"#EXTINF:-1 group-title=\"Hebrew\",ערוץ ראשון\n" +
"http://stream.example.com/hebrew.ts"
- val entries = parser.parse(m3u.byteInputStream())
+ val entries = parseEntries(m3u)
assertThat(entries).hasSize(2)
assertThat(entries[0].name).isEqualTo("قناة الأولى")
@@ -162,7 +161,7 @@ class M3uParserTest {
$tokenizedUrl
""".trimIndent()
- val entries = parser.parse(m3u.byteInputStream())
+ val entries = parseEntries(m3u)
assertThat(entries).hasSize(1)
assertThat(entries[0].url).isEqualTo(tokenizedUrl)
@@ -174,11 +173,11 @@ class M3uParserTest {
fun `isVodEntry_movieExtension_returnsTrue`() {
// Create a throwaway SyncManager reference to access the internal helper
// We test via the M3uParser-level behaviour: parse a playlist and verify isVod logic
- val entries = parser.parse(buildPlaylist(
+ val entries = parseEntries(buildPlaylist(
"http://vod.example.com/avatar.mp4" to "Movies",
"http://vod.example.com/inception.mkv" to "VOD",
"http://vod.example.com/oldfilm.avi" to "Films"
- ).byteInputStream())
+ ))
assertThat(entries).hasSize(3)
// All three entries should be classified as VOD by SyncManager
@@ -194,10 +193,10 @@ class M3uParserTest {
@Test
fun `isVodEntry_liveStream_returnsFalse`() {
- val entries = parser.parse(buildPlaylist(
+ val entries = parseEntries(buildPlaylist(
"http://live.example.com/ch1.ts" to "Live",
"http://live.example.com/ch2.m3u8" to "Sports"
- ).byteInputStream())
+ ))
assertThat(entries).hasSize(2)
entries.forEach { entry ->
@@ -220,4 +219,8 @@ class M3uParserTest {
}
return sb.toString()
}
+
+ private fun parseEntries(m3u: String): List<M3uParser.M3uEntry> {
+ return parser.parse(m3u.byteInputStream()).entries
+ }
}
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 dbbd18b0..2f37ad00 100644
--- a/data/src/test/java/com/streamvault/data/sync/SyncManagerTest.kt
+++ b/data/src/test/java/com/streamvault/data/sync/SyncManagerTest.kt
@@ -18,7 +18,12 @@ import kotlinx.coroutines.launch
import kotlinx.coroutines.test.runTest
import okhttp3.OkHttpClient
import org.junit.Test
+import org.mockito.kotlin.any
+import org.mockito.kotlin.anyOrNull
import org.mockito.kotlin.mock
+import org.mockito.kotlin.never
+import org.mockito.kotlin.verify
+import org.mockito.kotlin.whenever
/**
* Unit tests for [SyncManager] state machine transitions.
@@ -48,6 +53,7 @@ class SyncManagerTest {
override suspend fun deactivateAll() = Unit
override suspend fun activate(id: Long) = Unit
override suspend fun getByUrlAndUser(url: String, user: String): ProviderEntity? = null
+ override suspend fun updateEpgUrl(id: Long, epgUrl: String) = Unit
}
companion object {
@@ -142,6 +148,54 @@ class SyncManagerTest {
assertThat(state!!.message).isNotEmpty()
}
+ @Test
+ fun `sync_xtream_withFreshCache_andForceFalse_skipsRemoteCalls`() = runTest {
+ val mgr = buildManager(providerType = "XTREAM_CODES")
+ val now = System.currentTimeMillis()
+ whenever(syncMetadataRepo.getMetadata(1L)).thenReturn(
+ com.streamvault.domain.model.SyncMetadata(
+ providerId = 1L,
+ lastLiveSync = now,
+ lastMovieSync = now,
+ lastSeriesSync = now,
+ lastEpgSync = now
+ )
+ )
+
+ val result = mgr.sync(1L, force = false)
+
+ assertThat(result.isSuccess).isTrue()
+ verify(xtreamApi, never()).getLiveCategories(any(), any(), any(), any())
+ verify(xtreamApi, never()).getLiveStreams(any(), any(), any(), any(), anyOrNull())
+ }
+
+ @Test
+ fun `sync_xtream_withFreshCache_andForceTrue_executesRemoteCalls`() = runTest {
+ val mgr = buildManager(providerType = "XTREAM_CODES")
+ val now = System.currentTimeMillis()
+ whenever(syncMetadataRepo.getMetadata(1L)).thenReturn(
+ com.streamvault.domain.model.SyncMetadata(
+ providerId = 1L,
+ lastLiveSync = now,
+ lastMovieSync = now,
+ lastSeriesSync = now,
+ lastEpgSync = now
+ )
+ )
+ whenever(xtreamApi.getLiveCategories(any(), any(), any(), any())).thenReturn(emptyList())
+ whenever(xtreamApi.getLiveStreams(any(), any(), any(), any(), anyOrNull())).thenReturn(emptyList())
+ whenever(xtreamApi.getVodCategories(any(), any(), any(), any())).thenReturn(emptyList())
+ whenever(xtreamApi.getVodStreams(any(), any(), any(), any(), anyOrNull())).thenReturn(emptyList())
+ whenever(xtreamApi.getSeriesCategories(any(), any(), any(), any())).thenReturn(emptyList())
+ whenever(xtreamApi.getSeriesList(any(), any(), any(), any(), anyOrNull())).thenReturn(emptyList())
+
+ val result = mgr.sync(1L, force = true)
+
+ assertThat(result.isSuccess).isTrue()
+ verify(xtreamApi).getLiveCategories(any(), any(), any(), any())
+ verify(xtreamApi).getLiveStreams(any(), any(), any(), any(), anyOrNull())
+ }
+
// ── M3U sync failure ────────────────────────────────────────────
@Test
diff --git a/docs/code-review/DEAD_CODE_EDGE_CASE_MATRIX.md b/docs/code-review/DEAD_CODE_EDGE_CASE_MATRIX.md
new file mode 100644
index 00000000..fc289933
--- /dev/null
+++ b/docs/code-review/DEAD_CODE_EDGE_CASE_MATRIX.md
@@ -0,0 +1,91 @@
+# Dead Code, Reachability, and Edge-Case Matrix
+
+## Progress Tracking (code-review branch)
+- [x] `M3uParserTest` compilation fixed for new parser `ParseResult` contract.
+- [x] `SyncManagerTest` fake DAO updated to implement `updateEpgUrl`.
+- [x] Removed no-op behavior in `PreferencesRepository.clearDefaultViewMode`.
+- [x] Player EPG collector fan-out fixed by consolidating under one cancellable parent job.
+- [x] Duplicate EPG overlay paths consolidated.
+- [x] Generated `domain/bin` tree removed from VCS.
+- [x] Favorites N+1 resolution replaced with batched content lookups.
+- [x] MultiView top-level back handling wired via `BackHandler`.
+- [x] Search upgraded to FTS for channels/movies/series with SQL and UI result caps retained.
+- [x] Local imported M3U files are trimmed on provider-list updates and post-save flows while preserving provider-referenced files.
+- [x] Live player numeric channel entry implemented (buffer, preview, timeout commit, invalid feedback).
+- [x] Player remote key semantics tightened (GUIDE/INFO/MENU support, layered Back behavior, no VOD zap on channel keys).
+- [x] Home category rail now supports explicit DPAD-right handoff into content/search focus targets.
+- [x] Player overlays migrated away from hardcoded/garbled icon text to localized string resources and ASCII-safe control labels.
+- [x] Home screen now restores focus to last active category/channel after modal dialogs close (favorites/group/PIN/delete/category-options flows).
+- [x] Player channel list and EPG overlays now persist last focused row/program and restore focus on reopen.
+- [x] Provider edit flow no longer rehydrates stored passwords into UI state; blank password preserves existing encrypted secret.
+- [x] Sensitive URL logging reduced by redacting discovered EPG URLs and alternative stream debug outputs.
+- [x] Provider repository read paths now return redacted password fields instead of decrypted credential values.
+- [x] Provider onboarding now persists sync outcome in provider status (`ACTIVE`/`ERROR`) for clearer failure semantics.
+- [x] M3U sync now aborts on empty/no-playable payloads before DB replace-all operations.
+- [x] Provider local file import now surfaces storage-full specific error messaging.
+- [x] SyncManager now retries transient network failures with bounded exponential backoff for Xtream, M3U HTTP fetch, and EPG refresh.
+- [x] Player lifecycle now reacts to foreground/background transitions and flushes VOD progress on stop/dispose boundaries.
+- [x] Player decoder errors now trigger one-time software-decoder fallback before hard-fail.
+- [x] Manual provider refresh now updates provider sync status (`ACTIVE`/`ERROR`) consistently with onboarding sync.
+- [x] Sync pipeline now exposes degraded-but-complete outcomes via `SyncState.Partial` and provider `PARTIAL` status.
+- [x] Settings now surfaces `PARTIAL` refresh outcomes with explicit warning snackbar and provider status badge.
+- [x] Settings now includes per-section warning detail text (snackbar + provider card strip) for partial syncs.
+- [x] Warning strips now include actionable section-retry controls with real backend handlers (`EPG`, `Movies`, `Series` where supported).
+- [x] Live zapping now has a buffering-timeout watchdog with automatic fallback to the previous channel.
+- [x] Settings popups (language/parental level) migrated from default alert style to premium TV dialog styling.
+- [x] Player channel list overlay now shows group-local numbering and uses animated list scrolling without focus-scale jump.
+- [x] Adult-content detection is now centralized with case-insensitive matching and reused by both M3U sync and Xtream mapping.
+- [x] Xtream series and episode detail paths now inherit adult status from classified series categories instead of hardcoding `false`.
+- [x] Parental-control category management now spans LIVE/MOVIE/SERIES and scopes protection writes by category type.
+
+## C. Dead Code / Redundancy / Reachability
+
+### Duplicated logic
+- Resolved in `code-review`: duplicate EPG overlay file removed.
+ - Kept canonical implementation in `app/src/main/java/com/streamvault/app/ui/screens/player/PlayerScreen.kt`.
+
+### Unused or suspicious structures
+- Potentially unused parser helpers:
+ - `data/src/main/java/com/streamvault/data/parser/M3uParser.kt:100` (`parseToChannels`)
+ - `data/src/main/java/com/streamvault/data/parser/M3uParser.kt:183` (`isVodEntry`)
+
+### Unreachable / suspicious branches
+- Parental control loading/state flow appears inconsistent and may represent dead branch behavior:
+ - `app/src/main/java/com/streamvault/app/ui/screens/settings/parental/ParentalControlGroupViewModel.kt:31-38,48`
+
+### Simplification candidates
+- Introduce shared badge composables and shared focus surface patterns.
+- Remove duplicated overlay rendering paths.
+- Delete generated source artifacts from repository and CI packaging.
+
+## F. Edge Case Matrix
+
+| Edge Case | Status | Evidence / Note |
+|---|---|---|
+| No internet during provider add | Covered well | Provider add flow now returns explicit error when initial sync fails (`ProviderRepositoryImpl.kt`). |
+| Slow internet / high latency | Partially handled | Sync pipeline now retries transient failures with bounded exponential backoff; UX-level retry feedback/control is still basic. |
+| Playlist partially loads | Partially handled | Initial sync failures surface explicitly; degraded section refreshes now mark provider `PARTIAL`, surface section-level warnings, and provide section-specific retry actions from Settings. |
+| Invalid playlist URL/file | Covered well | Validation/error paths present in setup flow. |
+| Empty playlist | Covered well | M3U sync now fails fast on empty/no-playable payloads and does not perform destructive replace-all writes. |
+| Huge playlist (50k+ channels/items) | Partially handled | Favorites N+1 removed and FTS-backed search added; full stress/perf validation still pending. |
+| Broken stream URL | Partially handled | Player now auto-falls back to previous channel when live zap stalls in buffering/error state; broader multi-strategy fallback UX is still limited. |
+| Missing EPG | Partially handled | EPG optional paths exist, but stale/missing signaling is weak. |
+| Corrupted provider response | Partially handled | Exceptions are handled and transient failures are retried; semantic validation/recovery for malformed payload subsets is still limited. |
+| Resume after device sleep | Partially handled | Player observes lifecycle and now auto-pauses on `ON_STOP` with conditional resume on `ON_START`; still needs long-run device sleep stress validation. |
+| Resume after process death | Partially handled | ViewModel/state restore is mixed; no clear end-to-end guarantee observed. |
+| Returning from background during playback | Covered well | Player screen now wires lifecycle observer (`ON_STOP`/`ON_START`) and VM persists VOD progress + resumes only when session was playing pre-background. |
+| Rapid channel switching | Partially handled | `PlayerViewModel.fetchEpg` now uses one cancellable parent job for all EPG collectors. |
+| Repeated play/stop/open/close | Partially handled | Improved with lifecycle-driven pause/resume and progress flush; still requires endurance validation for long sessions/memory pressure. |
+| Storage full on import/cache | Partially handled | Local M3U import now reports explicit storage-full error; broader cache/storage-pressure handling is still limited. |
+| Permission issues on file import | Partially handled | Try/catch exists and setup now shows explicit import-failure feedback; retry/help UX is still basic. |
+| Low memory conditions | Unknown | No targeted low-memory handling observed. |
+| Unsupported codecs | Partially handled | Improved: decoder errors now attempt one software-decoder fallback automatically; still needs device-level codec compatibility test matrix. |
+| Multiple input methods/remotes | Partially handled | D-pad, numeric entry, GUIDE/INFO/MENU remote keys, and back-stack behavior are improved; hardware keyboard-specific UX remains basic. |
+| Provider metadata inconsistencies | Partially handled | Category-level adult classification is now centralized and propagated for M3U/Xtream, but provider naming remains heuristic when no explicit metadata exists. |
+| Duplicate/empty categories | Partially handled | UI supports category lists; robust dedupe strategy unclear. |
+| Large dataset search | Partially handled | FTS-backed search is in place with SQL/UI caps; ranking and stress tuning are still pending. |
+| First launch vs returning user | Covered well | Welcome/setup split exists; still needs stronger failure-state signaling. |
+
+## Tracking Notes
+- Use this file as implementation checklist.
+- Mark each row to `covered well` only after test evidence (unit/integration/manual scenario).
diff --git a/docs/code-review/IPTV_APP_AUDIT.md b/docs/code-review/IPTV_APP_AUDIT.md
new file mode 100644
index 00000000..ce7a61ff
--- /dev/null
+++ b/docs/code-review/IPTV_APP_AUDIT.md
@@ -0,0 +1,481 @@
+# IPTV Android TV App Audit (Source-Level)
+
+## Scope and Confidence
+- Analysis type: source-level review (not APK-only); findings are based on current repository code.
+- Confidence: high for issues with direct file/line evidence; medium for runtime behavior not fully exercised.
+- Date: 2026-03-09
+- Branch: code-review
+
+## Progress Tracking (code-review branch)
+- [x] Register Room migration `6 -> 7` in DI database builder.
+- [x] Disable OkHttp logging in non-debug builds.
+- [x] Fix Xtream API host handling by switching to dynamic `@Url` endpoint calls.
+- [x] Stop returning silent success when initial provider sync fails.
+- [x] Mask provider password input in setup UI.
+- [x] Fix broken unit test compilation (`M3uParserTest`, `SyncManagerTest`).
+- [x] Hash/salt parental PIN storage and remove PIN from backup export/import.
+- [x] Encrypt provider password-at-rest with Keystore-backed AES-GCM (transparent decrypt on read).
+- [x] Disable Android auto-backup (`allowBackup=false`).
+- [x] Scope category protection DB updates by provider (prevents cross-provider lock updates).
+- [x] Scope in-memory unlocked categories by provider (session unlock isolation fixed).
+- [x] Add explicit forced refresh path that bypasses TTL for user-triggered sync.
+- [x] Tie all player EPG collectors to one cancellable parent job (prevents zap-time collector buildup).
+- [x] Remove generated `domain/bin` source tree from VCS and ignore it in `.gitignore`.
+- [x] Consolidate duplicate EPG overlay implementation to a single component path.
+- [x] Rework provider-scoped EPG persistence/query model.
+- [x] Preserve remote content IDs separately (`streamId` / `seriesId` / `episodeId`) in domain mapping.
+- [x] Stabilize sync identity by remapping local IDs from provider+remote ID lookups before provider replace-all writes.
+- [x] Rework provider-scoped identity model for channels/movies/series/programs (including legacy ID normalization migration `8 -> 9`).
+- [x] Add migration test coverage for Room upgrade paths including `9 -> 10` FTS schema migration.
+- [x] Stop playback-history watch count inflation during periodic resume updates.
+- [x] Implement series details fetch+persistence (Xtream seasons/episodes) with local fallback.
+- [x] Replace favorites N+1 hydration with batched `IN` queries by content type.
+- [x] Add top-level `BackHandler` integration to MultiView screen and clean broken overlay labels.
+- [x] Replace `%LIKE%` search scans with provider-scoped FTS queries (plus SQL/UI result caps).
+- [x] Add local imported M3U cleanup policy (retain latest files, delete stale imports).
+- [x] Implement timed numeric channel entry (digit buffer + preview + delayed commit + invalid feedback) in player.
+- [x] Add explicit network security policy via manifest `networkSecurityConfig`.
+- [x] Harden Provider Setup local-file UX (localized labels + user-facing import failure messaging).
+- [x] Clean Kotlin warnings in active TV flows (`HomeViewModel`, `MultiViewPlannerDialog`).
+- [x] Polish player remote behavior: layered Back handling and GUIDE/INFO/MENU mappings; prevent VOD channel-zap key side effects.
+- [x] Improve Home TV focus navigation from category rail to content/search via explicit DPAD-right handoff.
+- [x] Normalize player overlay copy/icons to resource-driven TV labels (remove garbled/hardcoded symbols in controls, channel list, and EPG overlays).
+- [x] Add Home focus restoration memory (return to last focused category/channel after dialog/pin/delete/options modal dismissal).
+- [x] Add Player overlay focus restoration memory (channel list + EPG remember and restore last focused item across close/reopen).
+- [x] Stop exposing stored Xtream passwords in edit UI; blank edit password now preserves existing encrypted secret.
+- [x] Redact sensitive URL data from sync/player debug logging paths.
+- [x] Stop returning decrypted provider passwords from repository read APIs (`getProviders`/`getProvider`/`getActiveProvider` now return redacted password fields).
+- [x] Persist provider sync health on onboarding (`ACTIVE` on successful initial sync, `ERROR` on failed initial sync).
+- [x] Guard M3U sync against empty/no-playable payloads before replace-all writes (prevents accidental data wipe on malformed/empty playlists).
+- [x] Improve local M3U import error UX with explicit storage-full messaging.
+- [x] Add transient retry/backoff for sync network paths (Xtream fetches, M3U HTTP download, and EPG refresh) to reduce failures on slow/unstable links.
+- [x] Add lifecycle-aware player foreground/background handling (auto-pause/conditional resume + VOD progress flush on stop/dispose).
+- [x] Add decoder-error recovery path (one-shot fallback to software decoder mode before failing playback).
+- [x] Update provider sync health during manual refresh paths (`ACTIVE` on success, `ERROR` on failure).
+- [x] Add partial-sync semantics (`SyncState.Partial` + provider `PARTIAL` status) for non-fatal degraded refreshes.
+- [x] Surface partial-sync outcomes in Settings UX (provider status badge + warning snackbar on refresh).
+- [x] Show per-section partial warning details in Settings refresh feedback and provider cards.
+- [x] Add actionable partial-warning remediation buttons in Settings (`Retry EPG`, `Retry Movies`, `Retry Series`) backed by section-specific sync retries.
+- [x] Add live zap buffering watchdog with automatic fallback to previous channel when channel switch stalls.
+- [x] Replace old Settings selection popups with TV-styled premium dialogs (level/language selectors).
+- [x] Improve player channel-list overlay with group-local numbering and smoother focus/scroll behavior during long-list navigation.
+- [x] Centralize adult-content category classification with case-insensitive matching for M3U and Xtream.
+- [x] Apply Xtream parental classification by category for series/items instead of leaving series permanently unprotected.
+- [x] Expand parental category management to LIVE, Movies, and Series with type-scoped protection updates.
+
+## A. Executive Summary
+- Overall quality rating: 5.8/10 (strong ambition, fragile internals, TV UX partially mature)
+- Main strengths:
+ - Clear module split (`app`, `data`, `domain`, `player`)
+ - Broad feature scope (Live, Movies, Series, EPG, multiview, parental controls)
+ - Compose TV-first UI foundation with focus handling in many screens
+- Main weaknesses:
+ - Several critical data/network correctness risks
+ - Security/privacy posture is below production baseline
+ - High coupling between provider sync and local schema assumptions
+ - UI styling is inconsistent and partly non-native/polish-deficient for premium TV apps
+- Biggest risks:
+ - Xtream connection flow may fail due base URL wiring
+ - DB migration path mismatch can break upgrades
+ - Cross-provider data corruption/overlap risk for IDs and EPG
+ - Memory/leak-like behavior from uncancelled collector jobs in player
+- Biggest opportunities:
+ - Fix data model boundaries (provider-scoped IDs and EPG keys)
+ - Harden sync/retry/error states
+ - Improve premium TV UX consistency and focus ergonomics
+ - Implement secure credential storage and logging hardening
+
+## B. Findings by Category
+
+### 1) Xtream API base URL wiring is likely broken
+- Severity: Critical
+- Area: Reliability / Networking / IPTV
+- Status: Done in `code-review` (dynamic `@Url` endpoint implementation)
+- What is wrong:
+ - Retrofit service is created with fixed placeholder base URL (`https://placeholder.com/`). Xtream API methods are static relative paths and do not use dynamic `@Url`.
+- Why it matters:
+ - Authentication/data calls can hit wrong host or fail for real providers.
+- Evidence:
+ - `app/src/main/java/com/streamvault/app/di/NetworkModule.kt:49-53`
+ - `data/src/main/java/com/streamvault/data/remote/xtream/XtreamApiService.kt:17-21`
+ - `data/src/main/java/com/streamvault/data/remote/xtream/XtreamProvider.kt:23-25`
+ - `data/src/main/java/com/streamvault/data/sync/SyncManager.kt:110-114`
+- Recommended fix:
+ - Either build Retrofit per-provider base URL, or change service methods to dynamic `@Url` and pass full endpoint per call.
+
+### 2) Room migration registration mismatch
+- Severity: Critical
+- Area: Reliability / Storage
+- Status: Done in `code-review` (registered missing migrations and added migration instrumentation test coverage including `9 -> 10`)
+- What is wrong:
+ - DB version is 7 and `MIGRATION_6_7` exists, but DI builder registers migrations only to `5_6`.
+- Why it matters:
+ - App upgrades from v6 can fail at startup.
+- Evidence:
+ - `data/src/main/java/com/streamvault/data/local/StreamVaultDatabase.kt:24,141-146`
+ - `app/src/main/java/com/streamvault/app/di/DatabaseModule.kt:26-31`
+- Recommended fix:
+ - Register `StreamVaultDatabase.MIGRATION_6_7` in Hilt database module and add upgrade test.
+
+### 3) External IDs are written into auto-generated primary keys
+- Severity: Critical
+- Area: Architecture / Data Integrity
+- Status: Done in `code-review` (remote IDs are explicit domain fields; sync writes keep local PK internal; migration `8 -> 9` normalizes legacy local IDs and remaps favorites/history/episode links)
+- What is wrong:
+ - Entities define `id` as auto-generated local PK but mappers set `id = externalStreamId`.
+- Why it matters:
+ - Collisions and inconsistent identity across providers; broken references and updates.
+- Evidence:
+ - `data/src/main/java/com/streamvault/data/local/entity/Entities.kt:39-43,69-73,106-110`
+ - `data/src/main/java/com/streamvault/data/mapper/EntityMappers.kt:64-67,114-117`
+- Recommended fix:
+ - Keep local PK internal; store remote IDs in dedicated columns with provider-scoped unique indices.
+
+### 4) EPG persistence is not provider-scoped and has unstable IDs
+- Severity: Critical
+- Area: IPTV / Data Integrity / Reliability
+- Status: Done in `code-review` (program table now carries `provider_id`; DAO/repository/viewmodel queries are provider-scoped; migration `7 -> 8` added)
+- What is wrong:
+ - Program table/query paths are not fully provider-scoped; mapper keeps parser IDs that can default to 0.
+- Why it matters:
+ - EPG overlap, duplicate inserts, wrong now-playing data between providers.
+- Evidence:
+ - `data/src/main/java/com/streamvault/data/local/entity/Entities.kt:180-198`
+ - `data/src/main/java/com/streamvault/data/local/dao/Daos.kt:257-258`
+ - `data/src/main/java/com/streamvault/data/repository/EpgRepositoryImpl.kt:58-78`
+ - `data/src/main/java/com/streamvault/data/mapper/EntityMappers.kt:268-277`
+- Recommended fix:
+ - Add provider key to program identity, define stable composite uniqueness, and enforce provider filter in queries.
+
+### 5) Provider setup can succeed while initial sync failed
+- Severity: High
+- Area: Reliability / UX
+- Status: Done in `code-review` (setup now returns error on initial sync failure; successful sync sets `ACTIVE`; degraded non-fatal sync sections now map to `PARTIAL`; hard failures map to `ERROR`, across onboarding and manual refresh paths)
+- What is wrong:
+ - Exceptions during first sync are swallowed and setup still returns success.
+- Why it matters:
+ - User sees provider as added but data is incomplete/empty.
+- Evidence:
+ - `data/src/main/java/com/streamvault/data/repository/ProviderRepositoryImpl.kt:109-118,163-171`
+- Recommended fix:
+ - Surface sync status explicitly and mark provider as `degraded` until first successful sync.
+
+### 6) Parental lock operations are not provider-scoped
+- Severity: High
+- Area: Correctness / Security / IPTV
+- Status: Done in `code-review` (DB write paths and in-memory unlock model are provider-scoped)
+- What is wrong:
+ - Category lock updates match only category ID; memory unlock state also lacks provider dimension.
+- Why it matters:
+ - Locks can apply incorrectly across providers with same category IDs.
+- Evidence:
+ - `data/src/main/java/com/streamvault/data/local/dao/Daos.kt:78-79,146-147,182-183,245-246`
+ - `data/src/main/java/com/streamvault/data/repository/CategoryRepositoryImpl.kt:26-33`
+ - `domain/src/main/java/com/streamvault/domain/manager/ParentalControlManager.kt:11-26`
+- Recommended fix:
+ - Scope lock state by `(providerId, categoryId)` in DB and in-memory manager.
+
+### 7) Player EPG collection jobs can accumulate during channel zapping
+- Severity: High
+- Area: Performance / Reliability
+- Status: Done in `code-review` (single parent `epgJob` now owns now/next/history/upcoming collectors)
+- What is wrong:
+ - `fetchEpg` cancels one job but spawns additional collectors that are not fully tied to a single cancellable handle.
+- Why it matters:
+ - Increased memory/CPU and inconsistent UI updates during fast channel switching.
+- Evidence:
+ - `app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModel.kt:386-397,405-425`
+- Recommended fix:
+ - Use one structured `channelEpgJob` per channel and cancel/restart atomically.
+
+### 8) Series details loading appears incomplete
+- Severity: High
+- Area: IPTV / Correctness
+- Status: Done in `code-review` (Xtream `getSeriesInfo` is fetched by remote `series_id`, persisted to local `series`/`episodes`, and returned with merged seasons/episodes; local-cache fallback on remote failure)
+- What is wrong:
+ - Repository returns local series row only; detail VM expects seasons/episodes structure.
+- Why it matters:
+ - Empty/partial series detail screen in real-world providers.
+- Evidence:
+ - `data/src/main/java/com/streamvault/data/repository/SeriesRepositoryImpl.kt:75-78`
+ - `app/src/main/java/com/streamvault/app/ui/screens/series/SeriesDetailViewModel.kt:51-60`
+- Recommended fix:
+ - Add remote details fetch + local relational persistence for seasons/episodes.
+
+### 9) Credentials and PIN are stored unsafely
+- Severity: High
+- Area: Security / Privacy
+- Status: Partially done in `code-review` (PIN hashed/salted, PIN removed from backup export/import, provider password-at-rest encrypted, edit flow no longer pre-fills stored password, provider repository read APIs now redact password fields by default, and sensitive stream/EPG URL logging is redacted; broader secrets hardening still pending)
+- What is wrong:
+ - Provider credentials saved plaintext in Room; parental PIN stored plaintext with default `0000`; backup includes PIN.
+- Why it matters:
+ - Device compromise or backups can expose sensitive account controls.
+- Evidence:
+ - `data/src/main/java/com/streamvault/data/local/entity/Entities.kt:18-20`
+ - `data/src/main/java/com/streamvault/data/preferences/PreferencesRepository.kt:46-49,69-72`
+ - `data/src/main/java/com/streamvault/data/manager/BackupManagerImpl.kt:36-39,91-97`
+- Recommended fix:
+ - Encrypt credentials with Android Keystore backed keys; hash PIN with strong KDF; remove secrets from backup payloads.
+
+### 10) Network logging and backup flags are production-risky
+- Severity: High
+- Area: Security
+- Status: Done in `code-review` (release logging disabled and `allowBackup=false`)
+- What is wrong:
+ - OkHttp logging interceptor is BASIC globally; `allowBackup=true` in manifest.
+- Why it matters:
+ - Metadata leakage and broader extraction surface.
+- Evidence:
+ - `app/src/main/java/com/streamvault/app/di/NetworkModule.kt:33-36`
+ - `app/src/main/AndroidManifest.xml:18`
+- Recommended fix:
+ - Disable network logging for release builds; review backup policy and sensitive exclusions.
+
+### 11) Unit tests do not compile in current state
+- Severity: High
+- Area: Maintainability / Reliability
+- Status: Done in `code-review` (`./gradlew test` passes)
+- What is wrong:
+ - Parser test expects wrong return type; fake DAO missing new method.
+- Why it matters:
+ - CI quality gate is broken; regression risk is high.
+- Evidence:
+ - `data/src/test/java/com/streamvault/data/parser/M3uParserTest.kt:36-41`
+ - `data/src/main/java/com/streamvault/data/parser/M3uParser.kt:53`
+ - `data/src/test/java/com/streamvault/data/sync/SyncManagerTest.kt:38-50`
+- Recommended fix:
+ - Update tests to new parser contract and DAO interface; enforce CI on PR.
+
+### 12) Manual refresh is not truly forced
+- Severity: Medium
+- Area: UX / Reliability
+- Status: Done in `code-review` (`ProviderRepository.refreshProviderData(force=true)` wired from user-triggered refresh actions)
+- What is wrong:
+ - Settings refresh path can still be gated by TTL checks in sync manager.
+- Why it matters:
+ - User requests refresh but stale data remains.
+- Evidence:
+ - `app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsViewModel.kt:53-55,86-89`
+ - `data/src/main/java/com/streamvault/data/sync/SyncManager.kt:122-193`
+- Recommended fix:
+ - Add explicit `force=true` path that bypasses TTL for user-triggered refresh.
+
+### 13) Playback history watch count is inflated
+- Severity: Medium
+- Area: Data Quality / UX
+- Status: Done in `code-review` (periodic resume updates now preserve existing `watchCount` instead of incrementing on each tick)
+- What is wrong:
+ - Resume updates every 5 seconds may increase watch count repeatedly for same session.
+- Why it matters:
+ - Incorrect popularity/recent metrics and resume UX noise.
+- Evidence:
+ - `app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModel.kt:363-381`
+ - `data/src/main/java/com/streamvault/data/repository/PlaybackHistoryRepositoryImpl.kt:31-40`
+- Recommended fix:
+ - Increment watch count on session start/end events, not periodic progress ticks.
+
+### 14) Search path is not scalable for large datasets
+- Severity: Medium
+- Area: Performance / IPTV
+- Status: Done in `code-review` (provider-scoped FTS search implemented for channels/movies/series; SQL and UI caps remain in place)
+- What is wrong:
+ - Previous implementation used `%query%` LIKE scans without FTS/index strategy, which was expensive on large datasets.
+- Why it matters:
+ - Large playlists will lag and hurt remote responsiveness.
+- Evidence:
+ - `data/src/main/java/com/streamvault/data/local/dao/Daos.kt:51-52,96-97,158-159`
+ - `app/src/main/java/com/streamvault/app/ui/screens/search/SearchScreen.kt:93-100`
+- Recommended fix:
+ - Add Room FTS tables or prefix indexing, debounce, and result limits.
+
+### 15) Favorites screen has N+1 lookup behavior
+- Severity: Medium
+- Area: Performance
+- Status: Done in `code-review` (FavoritesViewModel now batch-resolves channel/movie/series records through `get*ByIds` flow combines)
+- What is wrong:
+ - For each favorite, additional repository lookups are performed.
+- Why it matters:
+ - Slow loading and unnecessary DB work with large favorites list.
+- Evidence:
+ - `app/src/main/java/com/streamvault/app/ui/screens/favorites/FavoritesViewModel.kt:37-65`
+- Recommended fix:
+ - Replace with joined query returning fully typed favorite payloads in one flow.
+
+### 16) TV key behavior is incomplete for numeric channel input
+- Severity: Medium
+- Area: Android TV UX
+- Status: Done in `code-review` (live player now supports buffered numeric entry with preview, timeout auto-commit, Enter commit, and invalid-input feedback; `0` retains last-channel quick recall when buffer is empty; remote GUIDE/INFO/MENU behavior and Back stack were tightened for TV expectations)
+- What is wrong:
+ - Supports `KEYCODE_0` recall behavior but no robust direct numeric entry workflow.
+- Why it matters:
+ - Power users with remotes expect fast channel number zapping.
+- Evidence:
+ - `app/src/main/java/com/streamvault/app/ui/screens/player/PlayerScreen.kt:285-287`
+- Recommended fix:
+ - Implement timed numeric buffer + candidate preview + confirm/fallback behavior.
+
+### 17) MultiView screen back handling appears incomplete
+- Severity: Medium
+- Area: Android TV UX / Navigation
+- Status: Done in `code-review` (explicit `BackHandler` wired to `onBack`; focused-slot overlays cleaned)
+- What is wrong:
+ - Screen API includes `onBack` but no clear local `BackHandler` integration at top-level.
+- Why it matters:
+ - Potential inconsistent exit behavior for remote back key.
+- Evidence:
+ - `app/src/main/java/com/streamvault/app/ui/screens/multiview/MultiViewScreen.kt:33-35`
+- Recommended fix:
+ - Add explicit `BackHandler` contract and focus-safe exit path.
+
+### 18) Provider setup password field is visible text
+- Severity: Medium
+- Area: Security / UX
+- Status: Done in `code-review` (password masking added)
+- What is wrong:
+ - Password input is plain text field without masking.
+- Why it matters:
+ - Credential exposure on-screen in shared living-room environments.
+- Evidence:
+ - `app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupScreen.kt:176-178`
+- Recommended fix:
+ - Add visual transformation and optional reveal toggle.
+
+### 19) Local file-imported playlists may accumulate
+- Severity: Medium
+- Area: Storage / Maintainability
+- Status: Done in `code-review` (cleanup now runs on every provider-list change and after successful provider save/edit; stale `m3u_*.m3u` files are trimmed while preserving currently referenced local playlists)
+- What is wrong:
+ - M3U import writes timestamped files under app files without visible cleanup lifecycle.
+- Why it matters:
+ - Wasted storage and stale artifacts.
+- Evidence:
+ - `app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupScreen.kt:73-76`
+- Recommended fix:
+ - Track ownership and garbage-collect old imported playlists.
+
+### 20) Potential cleartext compatibility ambiguity
+- Severity: Low
+- Area: Security / Compatibility
+- Status: Done in `code-review` (explicit `network_security_config` added and wired in manifest)
+- What is wrong:
+ - No explicit network security config policy for HTTP-only providers.
+- Why it matters:
+ - Either runtime failures for HTTP providers or unintended broad cleartext allowance later.
+- Evidence:
+ - Manifest/config inspection (no explicit cleartext policy observed in app manifest).
+- Recommended fix:
+ - Define network security config with minimal allowed domains/policies.
+
+### 21) Duplicate EPG overlay implementations
+- Severity: Low
+- Area: Maintainability / Redundancy
+- Status: Done in `code-review` (removed redundant `EpgOverlay.kt`; only `PlayerScreen` overlay remains)
+- What is wrong:
+ - EPG overlay logic exists in separate files and can drift.
+- Why it matters:
+ - Inconsistent UX and duplicated bug fixes.
+- Evidence:
+ - `app/src/main/java/com/streamvault/app/ui/screens/player/PlayerScreen.kt:1343`
+ - `app/src/main/java/com/streamvault/app/ui/screens/player/EpgOverlay.kt:27`
+- Recommended fix:
+ - Consolidate into a single reusable overlay component.
+
+### 22) Generated `domain/bin` sources are committed
+- Severity: Low
+- Area: Maintainability / Hygiene
+- Status: Done in `code-review` (tree removed from VCS; `domain/bin/` ignored)
+- What is wrong:
+ - Repository includes generated duplicate source tree.
+- Why it matters:
+ - Confusion, stale code, noisy diffs.
+- Evidence:
+ - `domain/bin/main/...`
+- Recommended fix:
+ - Remove generated outputs from VCS and enforce ignore rules.
+
+### 23) Player lifecycle handling was not foreground-aware
+- Severity: Medium
+- Area: Reliability / Android TV
+- Status: Done in `code-review` (screen lifecycle now pauses on background, conditionally resumes on foreground, and flushes VOD progress on stop/dispose)
+- What is wrong:
+ - Playback/progress tracking paths were not tied to screen lifecycle events, so background/sleep transitions could continue stale state updates.
+- Why it matters:
+ - Leads to unstable resume behavior, unnecessary background writes, and weaker resilience when returning to playback after sleep/home transitions.
+- Evidence:
+ - `app/src/main/java/com/streamvault/app/ui/screens/player/PlayerScreen.kt:135-146`
+ - `app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModel.kt:392-434,780`
+- Recommended fix:
+ - Observe lifecycle (`ON_STOP`/`ON_START`) in player screen, pause/resume intentionally, and persist VOD progress at lifecycle boundaries.
+
+### 24) Decoder failures had no runtime fallback strategy
+- Severity: Medium
+- Area: Reliability / Playback
+- Status: Done in `code-review` (decoder errors now trigger one-time software-decoder fallback and replay attempt)
+- What is wrong:
+ - Decoder errors previously surfaced directly to error UI with no automatic recovery strategy.
+- Why it matters:
+ - IPTV providers often mix problematic streams/codecs; immediate hard-fail hurts playback continuity and perceived quality.
+- Evidence:
+ - `app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModel.kt:127-134,275-276`
+- Recommended fix:
+ - On decoder failure, attempt one bounded fallback path (software decoder) before surfacing hard failure.
+
+## D. Premium App Gap Analysis
+
+### What premium IPTV apps do better
+- Provider onboarding trust flow: visible connectivity test, masked credentials, clear error categories, and first-sync progress with recover actions.
+- Live TV channel zap ergonomics: direct number input, quick channel list overlay, instant last-channel switch, predictable back behavior.
+- EPG reliability: resilient merge strategy, conflict resolution, timezone handling, clear stale/partial indicators.
+- Large dataset handling: fast indexed search, lazy loading, aggressive caching, incremental rendering.
+- Playback experience: clean overlays, stable focus paths, subtitle/audio controls, reliable resume and error recovery.
+
+### What this app currently lacks
+- Robust provider-scoped data model for IDs and EPG.
+- Production-grade secrets handling and release logging policy.
+- Mature first-sync state model (success/degraded/failed).
+- High-confidence performance strategy for very large playlists.
+- Fully premium visual consistency across setup, navigation, and playback overlays.
+
+### What changes would have highest impact
+1. Fix data identity and EPG scoping (prevents silent corruption and wrong content display).
+2. Fix Xtream networking host handling and migration chain (prevents hard failures).
+3. Harden provider setup + sync status model (prevents false success).
+4. Ship secure credential/PIN handling (trust and compliance baseline).
+5. Unify TV interaction model (focus, back, key handling, overlays) and polished visual system.
+
+## E. Optimization Opportunities (Prioritized)
+1. Done in `code-review`: provider-scoped DB indices for channels/programs + FTS search tables.
+2. High impact: structured concurrency cleanup in player EPG observers.
+3. High impact: batch queries for favorites/history instead of per-item lookups.
+4. Medium impact: add force-refresh pathway bypassing TTL for explicit user action.
+5. Medium impact: reduce recomposition pressure in large grids via stable item models and `derivedStateOf` guards.
+6. Medium impact: optimize image loading policies for logos/posters (size hints, placeholders, cache strategy).
+7. Medium impact: incremental EPG ingestion pipeline with bounded memory and checkpointing.
+8. Low impact: remove dead/duplicate code paths and generated `domain/bin` tree.
+
+## G. Refactoring Plan
+
+### 1) Quick wins (1-3 days)
+- Register missing migration in DI.
+- Fix broken tests (`M3uParserTest`, `SyncManagerTest`).
+- Mask password input in provider setup.
+- Disable verbose/network logging in release.
+- Add explicit UI messaging when initial sync fails.
+
+### 2) Medium effort (3-10 days)
+- Introduce forced refresh path and sync state model (`idle/running/partial/failed/success`).
+- Consolidate EPG overlay component.
+- Add provider-aware parental lock keying.
+- Replace N+1 favorites and broad search with optimized DAO queries.
+
+### 3) High-impact architectural changes (2-6 weeks)
+- Rework entity identity model: local PK + provider-scoped remote IDs and constraints.
+- Rebuild EPG persistence schema for provider/channel scoping and dedupe.
+- Re-architect Xtream service host strategy.
+- Add encrypted secret storage and secure backup strategy.
+
+### 4) Nice-to-have premium upgrades
+- Numeric channel input with timed buffer and visual confirmation.
+- Rich channel zap mini-guide and fast category switching.
+- Better fallback handling for broken logos/metadata.
+- Premium visual polish pass across all major screens and overlays.
diff --git a/domain/bin/main/com/streamvault/domain/manager/BackupManager.kt b/domain/bin/main/com/streamvault/domain/manager/BackupManager.kt
deleted file mode 100644
index c08c2634..00000000
--- a/domain/bin/main/com/streamvault/domain/manager/BackupManager.kt
+++ /dev/null
@@ -1,23 +0,0 @@
-package com.streamvault.domain.manager
-
-import kotlinx.coroutines.flow.Flow
-import com.streamvault.domain.model.Result
-
-data class BackupData(
- val version: Int = 1,
- val preferences: Map<String, String>? = null,
- val favorites: List<com.streamvault.domain.model.Favorite>? = null,
- val virtualGroups: List<com.streamvault.domain.model.VirtualGroup>? = null
-)
-
-interface BackupManager {
- /**
- * Exports the configuration to the provided URI string (SAF document URI)
- */
- suspend fun exportConfig(uriString: String): com.streamvault.domain.model.Result<Unit>
-
- /**
- * Imports the configuration from the provided URI string (SAF document URI)
- */
- suspend fun importConfig(uriString: String): com.streamvault.domain.model.Result<Unit>
-}
diff --git a/domain/bin/main/com/streamvault/domain/manager/ParentalControlManager.kt b/domain/bin/main/com/streamvault/domain/manager/ParentalControlManager.kt
deleted file mode 100644
index 2f82762d..00000000
--- a/domain/bin/main/com/streamvault/domain/manager/ParentalControlManager.kt
+++ /dev/null
@@ -1,27 +0,0 @@
-package com.streamvault.domain.manager
-
-import kotlinx.coroutines.flow.MutableStateFlow
-import kotlinx.coroutines.flow.StateFlow
-import kotlinx.coroutines.flow.asStateFlow
-import javax.inject.Inject
-import javax.inject.Singleton
-
-@Singleton
-class ParentalControlManager @Inject constructor() {
- private val _unlockedCategories = MutableStateFlow<Set<Long>>(emptySet())
- val unlockedCategories: StateFlow<Set<Long>> = _unlockedCategories.asStateFlow()
-
- fun unlockCategory(categoryId: Long) {
- val current = _unlockedCategories.value.toMutableSet()
- current.add(categoryId)
- _unlockedCategories.value = current
- }
-
- fun isCategoryUnlocked(categoryId: Long): Boolean {
- return _unlockedCategories.value.contains(categoryId)
- }
-
- fun clearUnlockedCategories() {
- _unlockedCategories.value = emptySet()
- }
-}
diff --git a/domain/bin/main/com/streamvault/domain/model/Category.kt b/domain/bin/main/com/streamvault/domain/model/Category.kt
deleted file mode 100644
index a26bfd47..00000000
--- a/domain/bin/main/com/streamvault/domain/model/Category.kt
+++ /dev/null
@@ -1,12 +0,0 @@
-package com.streamvault.domain.model
-
-data class Category(
- val id: Long,
- val name: String,
- val parentId: Long? = null,
- val type: ContentType = ContentType.LIVE,
- val isVirtual: Boolean = false,
- val count: Int = 0,
- val isAdult: Boolean = false,
- val isUserProtected: Boolean = false
-)
diff --git a/domain/bin/main/com/streamvault/domain/model/Channel.kt b/domain/bin/main/com/streamvault/domain/model/Channel.kt
deleted file mode 100644
index e9d78180..00000000
--- a/domain/bin/main/com/streamvault/domain/model/Channel.kt
+++ /dev/null
@@ -1,25 +0,0 @@
-package com.streamvault.domain.model
-
-data class Channel(
- val id: Long,
- val name: String,
- val logoUrl: String? = null,
- val groupTitle: String? = null,
- val categoryId: Long? = null,
- val categoryName: String? = null,
- val streamUrl: String = "",
- val epgChannelId: String? = null,
- val number: Int = 0,
- val isFavorite: Boolean = false,
- val catchUpSupported: Boolean = false,
- val catchUpDays: Int = 0,
- val catchUpSource: String? = null,
- val providerId: Long = 0,
- val currentProgram: Program? = null,
- val nextProgram: Program? = null,
- val isAdult: Boolean = false,
- val isUserProtected: Boolean = false,
- val logicalGroupId: String = "",
- val errorCount: Int = 0,
- val alternativeStreams: List<String> = emptyList()
-)
diff --git a/domain/bin/main/com/streamvault/domain/model/ContentType.kt b/domain/bin/main/com/streamvault/domain/model/ContentType.kt
deleted file mode 100644
index 283a509d..00000000
--- a/domain/bin/main/com/streamvault/domain/model/ContentType.kt
+++ /dev/null
@@ -1,8 +0,0 @@
-package com.streamvault.domain.model
-
-enum class ContentType {
- LIVE,
- MOVIE,
- SERIES,
- SERIES_EPISODE
-}
diff --git a/domain/bin/main/com/streamvault/domain/model/Favorite.kt b/domain/bin/main/com/streamvault/domain/model/Favorite.kt
deleted file mode 100644
index abe12a6c..00000000
--- a/domain/bin/main/com/streamvault/domain/model/Favorite.kt
+++ /dev/null
@@ -1,19 +0,0 @@
-package com.streamvault.domain.model
-
-data class Favorite(
- val id: Long = 0,
- val contentId: Long,
- val contentType: ContentType,
- val position: Int = 0,
- val groupId: Long? = null,
- val addedAt: Long = System.currentTimeMillis()
-)
-
-data class VirtualGroup(
- val id: Long = 0,
- val name: String,
- val iconEmoji: String? = null,
- val position: Int = 0,
- val createdAt: Long = System.currentTimeMillis(),
- val contentType: ContentType = ContentType.LIVE
-)
diff --git a/domain/bin/main/com/streamvault/domain/model/Movie.kt b/domain/bin/main/com/streamvault/domain/model/Movie.kt
deleted file mode 100644
index 365804fe..00000000
--- a/domain/bin/main/com/streamvault/domain/model/Movie.kt
+++ /dev/null
@@ -1,29 +0,0 @@
-package com.streamvault.domain.model
-
-data class Movie(
- val id: Long,
- val name: String,
- val posterUrl: String? = null,
- val backdropUrl: String? = null,
- val categoryId: Long? = null,
- val categoryName: String? = null,
- val streamUrl: String = "",
- val containerExtension: String? = null,
- val plot: String? = null,
- val cast: String? = null,
- val director: String? = null,
- val genre: String? = null,
- val releaseDate: String? = null,
- val duration: String? = null,
- val durationSeconds: Int = 0,
- val rating: Float = 0f,
- val year: String? = null,
- val tmdbId: Long? = null,
- val youtubeTrailer: String? = null,
- val isFavorite: Boolean = false,
- val providerId: Long = 0,
- val watchProgress: Long = 0L,
- val lastWatchedAt: Long = 0L,
- val isAdult: Boolean = false,
- val isUserProtected: Boolean = false
-)
diff --git a/domain/bin/main/com/streamvault/domain/model/PlaybackHistory.kt b/domain/bin/main/com/streamvault/domain/model/PlaybackHistory.kt
deleted file mode 100644
index 9c502588..00000000
--- a/domain/bin/main/com/streamvault/domain/model/PlaybackHistory.kt
+++ /dev/null
@@ -1,18 +0,0 @@
-package com.streamvault.domain.model
-
-data class PlaybackHistory(
- val id: Long = 0,
- val contentId: Long,
- val contentType: ContentType,
- val providerId: Long,
- val title: String,
- val posterUrl: String? = null,
- val streamUrl: String,
- val resumePositionMs: Long = 0,
- val totalDurationMs: Long = 0,
- val lastWatchedAt: Long = 0,
- val watchCount: Int = 1,
- val seriesId: Long? = null,
- val seasonNumber: Int? = null,
- val episodeNumber: Int? = null
-)
diff --git a/domain/bin/main/com/streamvault/domain/model/Program.kt b/domain/bin/main/com/streamvault/domain/model/Program.kt
deleted file mode 100644
index 6264b748..00000000
--- a/domain/bin/main/com/streamvault/domain/model/Program.kt
+++ /dev/null
@@ -1,24 +0,0 @@
-package com.streamvault.domain.model
-
-data class Program(
- val id: Long = 0,
- val channelId: String,
- val title: String,
- val description: String = "",
- val startTime: Long = 0L,
- val endTime: Long = 0L,
- val lang: String = "",
- val hasArchive: Boolean = false,
- val isNowPlaying: Boolean = false
-) {
- val durationMinutes: Int
- get() = ((endTime - startTime) / 60000).toInt()
-
- val progressPercent: Float
- get() {
- if (!isNowPlaying) return 0f
- val now = System.currentTimeMillis()
- if (now < startTime || endTime <= startTime) return 0f
- return ((now - startTime).toFloat() / (endTime - startTime).toFloat()).coerceIn(0f, 1f)
- }
-}
diff --git a/domain/bin/main/com/streamvault/domain/model/Provider.kt b/domain/bin/main/com/streamvault/domain/model/Provider.kt
deleted file mode 100644
index 6b5a6d06..00000000
--- a/domain/bin/main/com/streamvault/domain/model/Provider.kt
+++ /dev/null
@@ -1,31 +0,0 @@
-package com.streamvault.domain.model
-
-data class Provider(
- val id: Long = 0,
- val name: String,
- val type: ProviderType,
- val serverUrl: String,
- val username: String = "",
- val password: String = "",
- val m3uUrl: String = "",
- val epgUrl: String = "",
- val isActive: Boolean = true,
- val maxConnections: Int = 1,
- val expirationDate: Long? = null,
- val status: ProviderStatus = ProviderStatus.UNKNOWN,
- val lastSyncedAt: Long = 0L,
- val createdAt: Long = System.currentTimeMillis()
-)
-
-enum class ProviderType {
- XTREAM_CODES,
- M3U
-}
-
-enum class ProviderStatus {
- ACTIVE,
- EXPIRED,
- DISABLED,
- ERROR,
- UNKNOWN
-}
diff --git a/domain/bin/main/com/streamvault/domain/model/Result.kt b/domain/bin/main/com/streamvault/domain/model/Result.kt
deleted file mode 100644
index b9240014..00000000
--- a/domain/bin/main/com/streamvault/domain/model/Result.kt
+++ /dev/null
@@ -1,27 +0,0 @@
-package com.streamvault.domain.model
-
-/**
- * Generic result wrapper for handling success/failure across layers.
- */
-sealed class Result<out T> {
- data class Success<T>(val data: T) : Result<T>()
- data class Error(val message: String, val exception: Throwable? = null) : Result<Nothing>()
- data object Loading : Result<Nothing>()
-
- val isSuccess: Boolean get() = this is Success
- val isError: Boolean get() = this is Error
-
- fun getOrNull(): T? = (this as? Success)?.data
- fun errorMessageOrNull(): String? = (this as? Error)?.message
-
- fun <R> map(transform: (T) -> R): Result<R> = when (this) {
- is Success -> Success(transform(data))
- is Error -> Error(message, exception)
- is Loading -> Loading
- }
-
- companion object {
- fun <T> success(data: T) = Success(data)
- fun error(message: String, exception: Throwable? = null) = Error(message, exception)
- }
-}
diff --git a/domain/bin/main/com/streamvault/domain/model/Series.kt b/domain/bin/main/com/streamvault/domain/model/Series.kt
deleted file mode 100644
index 61c5efd6..00000000
--- a/domain/bin/main/com/streamvault/domain/model/Series.kt
+++ /dev/null
@@ -1,55 +0,0 @@
-package com.streamvault.domain.model
-
-data class Series(
- val id: Long,
- val name: String,
- val posterUrl: String? = null,
- val backdropUrl: String? = null,
- val categoryId: Long? = null,
- val categoryName: String? = null,
- val plot: String? = null,
- val cast: String? = null,
- val director: String? = null,
- val genre: String? = null,
- val releaseDate: String? = null,
- val rating: Float = 0f,
- val tmdbId: Long? = null,
- val youtubeTrailer: String? = null,
- val isFavorite: Boolean = false,
- val providerId: Long = 0,
- val seasons: List<Season> = emptyList(),
- val episodeRunTime: String? = null,
- val lastModified: Long = 0L,
- val isAdult: Boolean = false,
- val isUserProtected: Boolean = false
-)
-
-data class Season(
- val seasonNumber: Int,
- val name: String = "Season $seasonNumber",
- val coverUrl: String? = null,
- val episodes: List<Episode> = emptyList(),
- val airDate: String? = null,
- val episodeCount: Int = 0
-)
-
-data class Episode(
- val id: Long,
- val title: String,
- val episodeNumber: Int,
- val seasonNumber: Int,
- val streamUrl: String = "",
- val containerExtension: String? = null,
- val coverUrl: String? = null,
- val plot: String? = null,
- val duration: String? = null,
- val durationSeconds: Int = 0,
- val rating: Float = 0f,
- val releaseDate: String? = null,
- val seriesId: Long = 0,
- val providerId: Long = 0,
- val watchProgress: Long = 0L,
- val lastWatchedAt: Long = 0L,
- val isAdult: Boolean = false,
- val isUserProtected: Boolean = false
-)
diff --git a/domain/bin/main/com/streamvault/domain/model/StreamInfo.kt b/domain/bin/main/com/streamvault/domain/model/StreamInfo.kt
deleted file mode 100644
index c9019467..00000000
--- a/domain/bin/main/com/streamvault/domain/model/StreamInfo.kt
+++ /dev/null
@@ -1,24 +0,0 @@
-package com.streamvault.domain.model
-
-data class StreamInfo(
- val url: String,
- val headers: Map<String, String> = emptyMap(),
- val userAgent: String? = null,
- val streamType: StreamType = StreamType.UNKNOWN,
- val containerExtension: String? = null,
- val catchUpUrl: String? = null
-)
-
-enum class StreamType {
- HLS,
- DASH,
- MPEG_TS,
- PROGRESSIVE,
- UNKNOWN
-}
-
-enum class DecoderMode {
- AUTO,
- HARDWARE,
- SOFTWARE
-}
diff --git a/domain/bin/main/com/streamvault/domain/model/SyncMetadata.kt b/domain/bin/main/com/streamvault/domain/model/SyncMetadata.kt
deleted file mode 100644
index 1189253e..00000000
--- a/domain/bin/main/com/streamvault/domain/model/SyncMetadata.kt
+++ /dev/null
@@ -1,14 +0,0 @@
-package com.streamvault.domain.model
-
-data class SyncMetadata(
- val providerId: Long,
- val lastLiveSync: Long = 0,
- val lastMovieSync: Long = 0,
- val lastSeriesSync: Long = 0,
- val lastEpgSync: Long = 0,
- val liveCount: Int = 0,
- val movieCount: Int = 0,
- val seriesCount: Int = 0,
- val epgCount: Int = 0,
- val lastSyncStatus: String = "NONE"
-)
diff --git a/domain/bin/main/com/streamvault/domain/model/SyncState.kt b/domain/bin/main/com/streamvault/domain/model/SyncState.kt
deleted file mode 100644
index 7be31580..00000000
--- a/domain/bin/main/com/streamvault/domain/model/SyncState.kt
+++ /dev/null
@@ -1,33 +0,0 @@
-package com.streamvault.domain.model
-
-/**
- * Represents every stage of a provider sync operation.
- *
- * Designed as a sealed hierarchy so `when` branches are exhaustive and
- * the compiler enforces handling of every state.
- */
-sealed class SyncState {
-
- /** No sync is in progress and no result is available yet. */
- object Idle : SyncState()
-
- /** A sync is actively running. [phase] describes the current work (e.g. "Downloading Live TV…"). */
- data class Syncing(val phase: String = "") : SyncState()
-
- /** The most recent sync completed successfully at [timestamp] (epoch millis). */
- data class Success(val timestamp: Long = System.currentTimeMillis()) : SyncState()
-
- /**
- * The most recent sync failed.
- *
- * @param message Human-readable description of the failure.
- * @param cause Optional underlying exception for diagnostics.
- */
- data class Error(val message: String, val cause: Throwable? = null) : SyncState()
-
- // ── Convenience helpers ─────────────────────────────────────────
-
- val isSyncing: Boolean get() = this is Syncing
- val isError: Boolean get() = this is Error
- val isSuccess: Boolean get() = this is Success
-}
diff --git a/domain/bin/main/com/streamvault/domain/model/VideoFormat.kt b/domain/bin/main/com/streamvault/domain/model/VideoFormat.kt
deleted file mode 100644
index 6dfe7bbe..00000000
--- a/domain/bin/main/com/streamvault/domain/model/VideoFormat.kt
+++ /dev/null
@@ -1,22 +0,0 @@
-package com.streamvault.domain.model
-
-data class VideoFormat(
- val width: Int,
- val height: Int,
- val frameRate: Float = 0f,
- val bitrate: Int = 0,
- val codecV: String? = null,
- val codecA: String? = null
-) {
- val resolutionLabel: String
- get() = when {
- height >= 2160 -> "4K"
- height >= 1440 -> "1440p"
- height >= 1080 -> "1080p"
- height >= 720 -> "720p"
- height > 0 -> "${height}p"
- else -> "Unknown"
- }
-
- val isEmpty: Boolean get() = width == 0 && height == 0
-}
diff --git a/domain/bin/main/com/streamvault/domain/provider/IptvProvider.kt b/domain/bin/main/com/streamvault/domain/provider/IptvProvider.kt
deleted file mode 100644
index b9e92e2b..00000000
--- a/domain/bin/main/com/streamvault/domain/provider/IptvProvider.kt
+++ /dev/null
@@ -1,30 +0,0 @@
-package com.streamvault.domain.provider
-
-import com.streamvault.domain.model.*
-
-/**
- * Shared interface for all IPTV providers (Xtream Codes, M3U, etc.).
- * Each provider type implements this to normalize data into domain models.
- */
-interface IptvProvider {
- val providerId: Long
-
- suspend fun authenticate(): Result<Provider>
-
- suspend fun getLiveCategories(): Result<List<Category>>
- suspend fun getLiveStreams(categoryId: Long? = null): Result<List<Channel>>
-
- suspend fun getVodCategories(): Result<List<Category>>
- suspend fun getVodStreams(categoryId: Long? = null): Result<List<Movie>>
- suspend fun getVodInfo(vodId: Long): Result<Movie>
-
- suspend fun getSeriesCategories(): Result<List<Category>>
- suspend fun getSeriesList(categoryId: Long? = null): Result<List<Series>>
- suspend fun getSeriesInfo(seriesId: Long): Result<Series>
-
- suspend fun getEpg(channelId: String): Result<List<Program>>
- suspend fun getShortEpg(channelId: String, limit: Int = 4): Result<List<Program>>
-
- suspend fun buildStreamUrl(streamId: Long, containerExtension: String? = null): String
- suspend fun buildCatchUpUrl(streamId: Long, start: Long, end: Long): String?
-}
diff --git a/domain/bin/main/com/streamvault/domain/repository/CategoryRepository.kt b/domain/bin/main/com/streamvault/domain/repository/CategoryRepository.kt
deleted file mode 100644
index a5fb174b..00000000
--- a/domain/bin/main/com/streamvault/domain/repository/CategoryRepository.kt
+++ /dev/null
@@ -1,9 +0,0 @@
-package com.streamvault.domain.repository
-
-import com.streamvault.domain.model.Category
-import kotlinx.coroutines.flow.Flow
-
-interface CategoryRepository {
- fun getCategories(providerId: Long): Flow<List<Category>>
- suspend fun setCategoryProtection(categoryId: Long, isProtected: Boolean)
-}
diff --git a/domain/bin/main/com/streamvault/domain/repository/ChannelRepository.kt b/domain/bin/main/com/streamvault/domain/repository/ChannelRepository.kt
deleted file mode 100644
index ff8ec1d1..00000000
--- a/domain/bin/main/com/streamvault/domain/repository/ChannelRepository.kt
+++ /dev/null
@@ -1,23 +0,0 @@
-package com.streamvault.domain.repository
-
-import com.streamvault.domain.model.Category
-import com.streamvault.domain.model.Channel
-import com.streamvault.domain.model.Result
-import kotlinx.coroutines.flow.Flow
-
-interface ChannelRepository {
- fun getChannels(providerId: Long): Flow<List<Channel>>
- fun getChannelsByCategory(providerId: Long, categoryId: Long): Flow<List<Channel>>
- fun getCategories(providerId: Long): Flow<List<Category>>
- fun searchChannels(providerId: Long, query: String): Flow<List<Channel>>
- suspend fun getChannel(channelId: Long): Channel?
- suspend fun getStreamUrl(channel: Channel): Result<String>
- suspend fun refreshChannels(providerId: Long): Result<Unit>
- fun getChannelsByIds(ids: List<Long>): Flow<List<Channel>>
- suspend fun incrementChannelErrorCount(channelId: Long)
- suspend fun resetChannelErrorCount(channelId: Long)
-
- companion object {
- const val ALL_CHANNELS_ID = -1_000_000L
- }
-}
diff --git a/domain/bin/main/com/streamvault/domain/repository/EpgRepository.kt b/domain/bin/main/com/streamvault/domain/repository/EpgRepository.kt
deleted file mode 100644
index 6cac2055..00000000
--- a/domain/bin/main/com/streamvault/domain/repository/EpgRepository.kt
+++ /dev/null
@@ -1,14 +0,0 @@
-package com.streamvault.domain.repository
-
-import com.streamvault.domain.model.Program
-import com.streamvault.domain.model.Result
-import kotlinx.coroutines.flow.Flow
-
-interface EpgRepository {
- fun getProgramsForChannel(channelId: String, startTime: Long, endTime: Long): Flow<List<Program>>
- fun getNowPlaying(channelId: String): Flow<Program?>
- fun getNowPlayingForChannels(channelIds: List<String>): Flow<Map<String, List<Program>>>
- fun getNowAndNext(channelId: String): Flow<Pair<Program?, Program?>>
- suspend fun refreshEpg(providerId: Long, epgUrl: String): Result<Unit>
- suspend fun clearOldPrograms(beforeTime: Long)
-}
diff --git a/domain/bin/main/com/streamvault/domain/repository/FavoriteRepository.kt b/domain/bin/main/com/streamvault/domain/repository/FavoriteRepository.kt
deleted file mode 100644
index c2d6deb7..00000000
--- a/domain/bin/main/com/streamvault/domain/repository/FavoriteRepository.kt
+++ /dev/null
@@ -1,29 +0,0 @@
-package com.streamvault.domain.repository
-
-import com.streamvault.domain.model.ContentType
-import com.streamvault.domain.model.Favorite
-import com.streamvault.domain.model.Result
-import com.streamvault.domain.model.VirtualGroup
-import kotlinx.coroutines.flow.Flow
-
-interface FavoriteRepository {
- fun getFavorites(contentType: ContentType? = null): Flow<List<Favorite>>
- fun getAllFavorites(contentType: ContentType): Flow<List<Favorite>>
- fun getFavoritesByGroup(groupId: Long): Flow<List<Favorite>>
- fun getGroups(contentType: ContentType): Flow<List<VirtualGroup>>
-
- fun getGlobalFavoriteCount(contentType: ContentType): Flow<Int>
- fun getGroupFavoriteCounts(contentType: ContentType): Flow<Map<Long, Int>>
-
- suspend fun addFavorite(contentId: Long, contentType: ContentType, groupId: Long? = null): Result<Unit>
- suspend fun removeFavorite(contentId: Long, contentType: ContentType, groupId: Long? = null): Result<Unit>
-
- suspend fun reorderFavorites(favorites: List<Favorite>): Result<Unit>
- suspend fun isFavorite(contentId: Long, contentType: ContentType): Boolean
-
- suspend fun getGroupMemberships(contentId: Long, contentType: ContentType): List<Long>
-
- suspend fun createGroup(name: String, iconEmoji: String? = null, contentType: ContentType): Result<VirtualGroup>
- suspend fun deleteGroup(groupId: Long): Result<Unit>
- suspend fun renameGroup(groupId: Long, newName: String): Result<Unit>
-}
diff --git a/domain/bin/main/com/streamvault/domain/repository/MovieRepository.kt b/domain/bin/main/com/streamvault/domain/repository/MovieRepository.kt
deleted file mode 100644
index 3f9bef68..00000000
--- a/domain/bin/main/com/streamvault/domain/repository/MovieRepository.kt
+++ /dev/null
@@ -1,18 +0,0 @@
-package com.streamvault.domain.repository
-
-import com.streamvault.domain.model.Category
-import com.streamvault.domain.model.Movie
-import com.streamvault.domain.model.Result
-import kotlinx.coroutines.flow.Flow
-
-interface MovieRepository {
- fun getMovies(providerId: Long): Flow<List<Movie>>
- fun getMoviesByCategory(providerId: Long, categoryId: Long): Flow<List<Movie>>
- fun getCategories(providerId: Long): Flow<List<Category>>
- fun searchMovies(providerId: Long, query: String): Flow<List<Movie>>
- suspend fun getMovie(movieId: Long): Movie?
- suspend fun getMovieDetails(providerId: Long, movieId: Long): Result<Movie>
- suspend fun getStreamUrl(movie: Movie): Result<String>
- suspend fun refreshMovies(providerId: Long): Result<Unit>
- suspend fun updateWatchProgress(movieId: Long, progress: Long)
-}
diff --git a/domain/bin/main/com/streamvault/domain/repository/PlaybackHistoryRepository.kt b/domain/bin/main/com/streamvault/domain/repository/PlaybackHistoryRepository.kt
deleted file mode 100644
index e69a467d..00000000
--- a/domain/bin/main/com/streamvault/domain/repository/PlaybackHistoryRepository.kt
+++ /dev/null
@@ -1,16 +0,0 @@
-package com.streamvault.domain.repository
-
-import com.streamvault.domain.model.ContentType
-import com.streamvault.domain.model.PlaybackHistory
-import kotlinx.coroutines.flow.Flow
-
-interface PlaybackHistoryRepository {
- fun getRecentlyWatched(limit: Int = 100): Flow<List<PlaybackHistory>>
- fun getRecentlyWatchedByProvider(providerId: Long, limit: Int = 100): Flow<List<PlaybackHistory>>
- suspend fun getPlaybackHistory(contentId: Long, contentType: ContentType, providerId: Long): PlaybackHistory?
-
- suspend fun updateResumePosition(history: PlaybackHistory)
- suspend fun removeFromHistory(contentId: Long, contentType: ContentType, providerId: Long)
- suspend fun clearAllHistory()
- suspend fun clearHistoryForProvider(providerId: Long)
-}
diff --git a/domain/bin/main/com/streamvault/domain/repository/ProviderRepository.kt b/domain/bin/main/com/streamvault/domain/repository/ProviderRepository.kt
deleted file mode 100644
index 14939dc0..00000000
--- a/domain/bin/main/com/streamvault/domain/repository/ProviderRepository.kt
+++ /dev/null
@@ -1,19 +0,0 @@
-package com.streamvault.domain.repository
-
-import com.streamvault.domain.model.Provider
-import com.streamvault.domain.model.Result
-import kotlinx.coroutines.flow.Flow
-
-interface ProviderRepository {
- fun getProviders(): Flow<List<Provider>>
- fun getActiveProvider(): Flow<Provider?>
- suspend fun getProvider(id: Long): Provider?
- suspend fun addProvider(provider: Provider): Result<Long>
- suspend fun updateProvider(provider: Provider): Result<Unit>
- suspend fun deleteProvider(id: Long): Result<Unit>
- suspend fun setActiveProvider(id: Long): Result<Unit>
- suspend fun loginXtream(serverUrl: String, username: String, password: String, name: String, onProgress: ((String) -> Unit)? = null, id: Long? = null): Result<Provider>
- suspend fun validateM3u(url: String, name: String, onProgress: ((String) -> Unit)? = null, id: Long? = null): Result<Provider>
- suspend fun refreshProviderData(providerId: Long, onProgress: ((String) -> Unit)? = null): Result<Unit>
- suspend fun buildCatchUpUrl(providerId: Long, streamId: Long, start: Long, end: Long): String?
-}
diff --git a/domain/bin/main/com/streamvault/domain/repository/SeriesRepository.kt b/domain/bin/main/com/streamvault/domain/repository/SeriesRepository.kt
deleted file mode 100644
index 6c394dc2..00000000
--- a/domain/bin/main/com/streamvault/domain/repository/SeriesRepository.kt
+++ /dev/null
@@ -1,19 +0,0 @@
-package com.streamvault.domain.repository
-
-import com.streamvault.domain.model.Category
-import com.streamvault.domain.model.Episode
-import com.streamvault.domain.model.Result
-import com.streamvault.domain.model.Series
-import kotlinx.coroutines.flow.Flow
-
-interface SeriesRepository {
- fun getSeries(providerId: Long): Flow<List<Series>>
- fun getSeriesByCategory(providerId: Long, categoryId: Long): Flow<List<Series>>
- fun getCategories(providerId: Long): Flow<List<Category>>
- fun searchSeries(providerId: Long, query: String): Flow<List<Series>>
- suspend fun getSeriesById(seriesId: Long): Series?
- suspend fun getSeriesDetails(providerId: Long, seriesId: Long): Result<Series>
- suspend fun getEpisodeStreamUrl(episode: Episode): Result<String>
- suspend fun refreshSeries(providerId: Long): Result<Unit>
- suspend fun updateEpisodeWatchProgress(episodeId: Long, progress: Long)
-}
diff --git a/domain/bin/main/com/streamvault/domain/repository/SyncMetadataRepository.kt b/domain/bin/main/com/streamvault/domain/repository/SyncMetadataRepository.kt
deleted file mode 100644
index 48faefe6..00000000
--- a/domain/bin/main/com/streamvault/domain/repository/SyncMetadataRepository.kt
+++ /dev/null
@@ -1,11 +0,0 @@
-package com.streamvault.domain.repository
-
-import com.streamvault.domain.model.SyncMetadata
-import kotlinx.coroutines.flow.Flow
-
-interface SyncMetadataRepository {
- fun observeMetadata(providerId: Long): Flow<SyncMetadata?>
- suspend fun getMetadata(providerId: Long): SyncMetadata?
- suspend fun updateMetadata(metadata: SyncMetadata)
- suspend fun clearMetadata(providerId: Long)
-}
diff --git a/domain/bin/main/com/streamvault/domain/usecase/GetCustomCategories.kt b/domain/bin/main/com/streamvault/domain/usecase/GetCustomCategories.kt
deleted file mode 100644
index df7cebae..00000000
--- a/domain/bin/main/com/streamvault/domain/usecase/GetCustomCategories.kt
+++ /dev/null
@@ -1,49 +0,0 @@
-package com.streamvault.domain.usecase
-
-import com.streamvault.domain.model.Category
-import com.streamvault.domain.model.ContentType
-import com.streamvault.domain.repository.FavoriteRepository
-import kotlinx.coroutines.flow.Flow
-import kotlinx.coroutines.flow.map
-import javax.inject.Inject
-
-class GetCustomCategories @Inject constructor(
- private val favoriteRepository: FavoriteRepository
-) {
- operator fun invoke(contentType: ContentType = ContentType.LIVE): Flow<List<Category>> {
- return kotlinx.coroutines.flow.combine(
- favoriteRepository.getGroups(contentType),
- favoriteRepository.getGlobalFavoriteCount(contentType),
- favoriteRepository.getGroupFavoriteCounts(contentType)
- ) { groups, globalCount, groupCounts ->
- try {
- println("GetCustomCategories: Processing ${groups.size} groups. Global: $globalCount, Counts: ${groupCounts.size}")
-
- val categories = groups.map { group ->
- Category(
- id = -group.id, // Use negative ID for virtual groups
- name = group.name,
- type = contentType,
- isVirtual = true,
- count = groupCounts.getOrDefault(group.id, 0)
- )
- }.toMutableList()
-
- // prepend "Favorites" as a special virtual category
- categories.add(0, Category(
- id = -999L, // Special ID for "All Favorites"
- name = "★ Favorites",
- type = contentType,
- isVirtual = true,
- count = globalCount
- ))
-
- categories
- } catch (e: Exception) {
- println("GetCustomCategories: Error processing categories: ${e.message}")
- e.printStackTrace()
- emptyList<Category>()
- }
- }
- }
-}
diff --git a/domain/bin/main/com/streamvault/domain/util/ChannelNormalizer.kt b/domain/bin/main/com/streamvault/domain/util/ChannelNormalizer.kt
deleted file mode 100644
index 4adf37b2..00000000
--- a/domain/bin/main/com/streamvault/domain/util/ChannelNormalizer.kt
+++ /dev/null
@@ -1,59 +0,0 @@
-package com.streamvault.domain.util
-
-import java.util.Locale
-
-object ChannelNormalizer {
-
- /**
- * Common tags found in IPTV channel names that do not denote different content,
- * but rather quality, source, or generic metadata.
- */
- private val qualityTags = listOf(
- "sd", "hd", "fhd", "uhd", "4k", "8k", "hevc", "h265", "raw", "vip", "premium", "pro",
- "1080p", "720p", "1080i", "4k bluray", "blu-ray", "blu ray", "mkv", "mp4", "ts"
- )
-
- private val specialCharactersRegex = Regex("[^a-zA-Z0-9 ]")
- private val extraSpacesRegex = Regex("\\s+")
-
- /**
- * Normalizes a channel name to a deterministic base logical group ID.
- * Removes quality tags, country prefixes/suffixes (e.g. "US:", "|UK|"), and special characters.
- *
- * Examples:
- * "BBC One HD" -> "bbcone"
- * "US: HBO Max FHD" -> "hbomax"
- * "|UK| Sky Sports 1 (FHD)" -> "skysports1"
- */
- fun getLogicalGroupId(channelName: String, providerId: Long): String {
- var normalized = channelName.lowercase(Locale.ROOT)
-
- // 1. Remove bracketed/parenthesized tags (often country codes or "FHD")
- // e.g. [UK], (USA), |FR|
- normalized = normalized.replace(Regex("\\[.*?\\]"), " ")
- normalized = normalized.replace(Regex("\\(.*?\\)"), " ")
- normalized = normalized.replace(Regex("\\|.*?\\|"), " ")
-
- // 2. Remove isolated country prefixes like "US:", "UK -", "FR:"
- normalized = normalized.replace(Regex("^[a-z]{2,3}[:\\-]\\s*"), " ")
-
- // 3. Remove all non-alphanumeric characters (keeps spaces for word boundary checking)
- normalized = normalized.replace(specialCharactersRegex, " ")
-
- // 4. Tokenize and remove quality tags
- val words = normalized.split(extraSpacesRegex).filter { it.isNotBlank() }
- val filteredWords = words.filter { word ->
- !qualityTags.contains(word)
- }
-
- // 5. Rejoin and strip all spaces for the final deterministic ID
- // Also prepend the providerId so we don't merge across different subscriptions
- // unless explicitly desired (which is complex for playback tokens).
- val baseId = filteredWords.joinToString("").ifEmpty {
- // Fallback if the name was literally just "FHD" or empty
- channelName.replace(specialCharactersRegex, "").lowercase(Locale.ROOT)
- }
-
- return "${providerId}_${baseId}"
- }
-}
diff --git a/domain/src/main/java/com/streamvault/domain/manager/ParentalControlManager.kt b/domain/src/main/java/com/streamvault/domain/manager/ParentalControlManager.kt
index 2f82762d..6e65c12b 100644
--- a/domain/src/main/java/com/streamvault/domain/manager/ParentalControlManager.kt
+++ b/domain/src/main/java/com/streamvault/domain/manager/ParentalControlManager.kt
@@ -3,25 +3,39 @@ package com.streamvault.domain.manager
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
+import kotlinx.coroutines.flow.map
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class ParentalControlManager @Inject constructor() {
- private val _unlockedCategories = MutableStateFlow<Set<Long>>(emptySet())
- val unlockedCategories: StateFlow<Set<Long>> = _unlockedCategories.asStateFlow()
+ private val _unlockedCategoriesByProvider = MutableStateFlow<Map<Long, Set<Long>>>(emptyMap())
+ val unlockedCategoriesByProvider: StateFlow<Map<Long, Set<Long>>> =
+ _unlockedCategoriesByProvider.asStateFlow()
- fun unlockCategory(categoryId: Long) {
- val current = _unlockedCategories.value.toMutableSet()
- current.add(categoryId)
- _unlockedCategories.value = current
+ fun unlockedCategoriesForProvider(providerId: Long) =
+ unlockedCategoriesByProvider.map { it[providerId] ?: emptySet() }
+
+ fun unlockCategory(providerId: Long, categoryId: Long) {
+ val current = _unlockedCategoriesByProvider.value.toMutableMap()
+ val providerSet = (current[providerId] ?: emptySet()).toMutableSet()
+ providerSet.add(categoryId)
+ current[providerId] = providerSet
+ _unlockedCategoriesByProvider.value = current
}
- fun isCategoryUnlocked(categoryId: Long): Boolean {
- return _unlockedCategories.value.contains(categoryId)
+ fun isCategoryUnlocked(providerId: Long, categoryId: Long): Boolean {
+ return _unlockedCategoriesByProvider.value[providerId]?.contains(categoryId) == true
}
- fun clearUnlockedCategories() {
- _unlockedCategories.value = emptySet()
+ fun clearUnlockedCategories(providerId: Long? = null) {
+ if (providerId == null) {
+ _unlockedCategoriesByProvider.value = emptyMap()
+ return
+ }
+
+ val current = _unlockedCategoriesByProvider.value.toMutableMap()
+ current.remove(providerId)
+ _unlockedCategoriesByProvider.value = current
}
}
diff --git a/domain/src/main/java/com/streamvault/domain/model/Channel.kt b/domain/src/main/java/com/streamvault/domain/model/Channel.kt
index e9d78180..c6db5a8f 100644
--- a/domain/src/main/java/com/streamvault/domain/model/Channel.kt
+++ b/domain/src/main/java/com/streamvault/domain/model/Channel.kt
@@ -21,5 +21,6 @@ data class Channel(
val isUserProtected: Boolean = false,
val logicalGroupId: String = "",
val errorCount: Int = 0,
- val alternativeStreams: List<String> = emptyList()
+ val alternativeStreams: List<String> = emptyList(),
+ val streamId: Long = 0L
)
diff --git a/domain/src/main/java/com/streamvault/domain/model/Movie.kt b/domain/src/main/java/com/streamvault/domain/model/Movie.kt
index 365804fe..8475ec28 100644
--- a/domain/src/main/java/com/streamvault/domain/model/Movie.kt
+++ b/domain/src/main/java/com/streamvault/domain/model/Movie.kt
@@ -25,5 +25,6 @@ data class Movie(
val watchProgress: Long = 0L,
val lastWatchedAt: Long = 0L,
val isAdult: Boolean = false,
- val isUserProtected: Boolean = false
+ val isUserProtected: Boolean = false,
+ val streamId: Long = 0L
)
diff --git a/domain/src/main/java/com/streamvault/domain/model/Program.kt b/domain/src/main/java/com/streamvault/domain/model/Program.kt
index 6264b748..bd5816bd 100644
--- a/domain/src/main/java/com/streamvault/domain/model/Program.kt
+++ b/domain/src/main/java/com/streamvault/domain/model/Program.kt
@@ -9,7 +9,8 @@ data class Program(
val endTime: Long = 0L,
val lang: String = "",
val hasArchive: Boolean = false,
- val isNowPlaying: Boolean = false
+ val isNowPlaying: Boolean = false,
+ val providerId: Long = 0L
) {
val durationMinutes: Int
get() = ((endTime - startTime) / 60000).toInt()
diff --git a/domain/src/main/java/com/streamvault/domain/model/Provider.kt b/domain/src/main/java/com/streamvault/domain/model/Provider.kt
index 6b5a6d06..ebf99ddb 100644
--- a/domain/src/main/java/com/streamvault/domain/model/Provider.kt
+++ b/domain/src/main/java/com/streamvault/domain/model/Provider.kt
@@ -24,6 +24,7 @@ enum class ProviderType {
enum class ProviderStatus {
ACTIVE,
+ PARTIAL,
EXPIRED,
DISABLED,
ERROR,
diff --git a/domain/src/main/java/com/streamvault/domain/model/Series.kt b/domain/src/main/java/com/streamvault/domain/model/Series.kt
index 61c5efd6..2f2ed239 100644
--- a/domain/src/main/java/com/streamvault/domain/model/Series.kt
+++ b/domain/src/main/java/com/streamvault/domain/model/Series.kt
@@ -21,7 +21,8 @@ data class Series(
val episodeRunTime: String? = null,
val lastModified: Long = 0L,
val isAdult: Boolean = false,
- val isUserProtected: Boolean = false
+ val isUserProtected: Boolean = false,
+ val seriesId: Long = 0L
)
data class Season(
@@ -51,5 +52,6 @@ data class Episode(
val watchProgress: Long = 0L,
val lastWatchedAt: Long = 0L,
val isAdult: Boolean = false,
- val isUserProtected: Boolean = false
+ val isUserProtected: Boolean = false,
+ val episodeId: Long = 0L
)
diff --git a/domain/src/main/java/com/streamvault/domain/model/SyncState.kt b/domain/src/main/java/com/streamvault/domain/model/SyncState.kt
index 7be31580..4eaf8e91 100644
--- a/domain/src/main/java/com/streamvault/domain/model/SyncState.kt
+++ b/domain/src/main/java/com/streamvault/domain/model/SyncState.kt
@@ -17,6 +17,18 @@ sealed class SyncState {
/** The most recent sync completed successfully at [timestamp] (epoch millis). */
data class Success(val timestamp: Long = System.currentTimeMillis()) : SyncState()
+ /**
+ * The most recent sync completed but with non-fatal degradations.
+ *
+ * @param message Human-readable partial-sync summary.
+ * @param warnings Detailed list of failed/skipped sub-operations.
+ */
+ data class Partial(
+ val message: String,
+ val warnings: List<String> = emptyList(),
+ val timestamp: Long = System.currentTimeMillis()
+ ) : SyncState()
+
/**
* The most recent sync failed.
*
@@ -30,4 +42,5 @@ sealed class SyncState {
val isSyncing: Boolean get() = this is Syncing
val isError: Boolean get() = this is Error
val isSuccess: Boolean get() = this is Success
+ val isPartial: Boolean get() = this is Partial
}
diff --git a/domain/src/main/java/com/streamvault/domain/repository/CategoryRepository.kt b/domain/src/main/java/com/streamvault/domain/repository/CategoryRepository.kt
index a5fb174b..9dfafe09 100644
--- a/domain/src/main/java/com/streamvault/domain/repository/CategoryRepository.kt
+++ b/domain/src/main/java/com/streamvault/domain/repository/CategoryRepository.kt
@@ -1,9 +1,15 @@
package com.streamvault.domain.repository
import com.streamvault.domain.model.Category
+import com.streamvault.domain.model.ContentType
import kotlinx.coroutines.flow.Flow
interface CategoryRepository {
fun getCategories(providerId: Long): Flow<List<Category>>
- suspend fun setCategoryProtection(categoryId: Long, isProtected: Boolean)
+ suspend fun setCategoryProtection(
+ providerId: Long,
+ categoryId: Long,
+ type: ContentType,
+ isProtected: Boolean
+ )
}
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 6cac2055..e0ab7d3c 100644
--- a/domain/src/main/java/com/streamvault/domain/repository/EpgRepository.kt
+++ b/domain/src/main/java/com/streamvault/domain/repository/EpgRepository.kt
@@ -5,10 +5,10 @@ import com.streamvault.domain.model.Result
import kotlinx.coroutines.flow.Flow
interface EpgRepository {
- fun getProgramsForChannel(channelId: String, startTime: Long, endTime: Long): Flow<List<Program>>
- fun getNowPlaying(channelId: String): Flow<Program?>
- fun getNowPlayingForChannels(channelIds: List<String>): Flow<Map<String, List<Program>>>
- fun getNowAndNext(channelId: String): Flow<Pair<Program?, Program?>>
+ fun getProgramsForChannel(providerId: Long, channelId: String, startTime: Long, endTime: Long): Flow<List<Program>>
+ fun getNowPlaying(providerId: Long, channelId: String): Flow<Program?>
+ fun getNowPlayingForChannels(providerId: Long, channelIds: List<String>): Flow<Map<String, List<Program>>>
+ fun getNowAndNext(providerId: Long, channelId: String): Flow<Pair<Program?, Program?>>
suspend fun refreshEpg(providerId: Long, epgUrl: String): Result<Unit>
suspend fun clearOldPrograms(beforeTime: Long)
}
diff --git a/domain/src/main/java/com/streamvault/domain/repository/MovieRepository.kt b/domain/src/main/java/com/streamvault/domain/repository/MovieRepository.kt
index 3f9bef68..66380a66 100644
--- a/domain/src/main/java/com/streamvault/domain/repository/MovieRepository.kt
+++ b/domain/src/main/java/com/streamvault/domain/repository/MovieRepository.kt
@@ -8,6 +8,7 @@ import kotlinx.coroutines.flow.Flow
interface MovieRepository {
fun getMovies(providerId: Long): Flow<List<Movie>>
fun getMoviesByCategory(providerId: Long, categoryId: Long): Flow<List<Movie>>
+ fun getMoviesByIds(ids: List<Long>): Flow<List<Movie>>
fun getCategories(providerId: Long): Flow<List<Category>>
fun searchMovies(providerId: Long, query: String): Flow<List<Movie>>
suspend fun getMovie(movieId: Long): Movie?
diff --git a/domain/src/main/java/com/streamvault/domain/repository/ProviderRepository.kt b/domain/src/main/java/com/streamvault/domain/repository/ProviderRepository.kt
index 14939dc0..230bfa01 100644
--- a/domain/src/main/java/com/streamvault/domain/repository/ProviderRepository.kt
+++ b/domain/src/main/java/com/streamvault/domain/repository/ProviderRepository.kt
@@ -14,6 +14,10 @@ interface ProviderRepository {
suspend fun setActiveProvider(id: Long): Result<Unit>
suspend fun loginXtream(serverUrl: String, username: String, password: String, name: String, onProgress: ((String) -> Unit)? = null, id: Long? = null): Result<Provider>
suspend fun validateM3u(url: String, name: String, onProgress: ((String) -> Unit)? = null, id: Long? = null): Result<Provider>
- suspend fun refreshProviderData(providerId: Long, onProgress: ((String) -> Unit)? = null): Result<Unit>
+ suspend fun refreshProviderData(
+ providerId: Long,
+ force: Boolean = false,
+ onProgress: ((String) -> Unit)? = null
+ ): Result<Unit>
suspend fun buildCatchUpUrl(providerId: Long, streamId: Long, start: Long, end: Long): String?
}
diff --git a/domain/src/main/java/com/streamvault/domain/repository/SeriesRepository.kt b/domain/src/main/java/com/streamvault/domain/repository/SeriesRepository.kt
index 6c394dc2..5a918f24 100644
--- a/domain/src/main/java/com/streamvault/domain/repository/SeriesRepository.kt
+++ b/domain/src/main/java/com/streamvault/domain/repository/SeriesRepository.kt
@@ -9,6 +9,7 @@ import kotlinx.coroutines.flow.Flow
interface SeriesRepository {
fun getSeries(providerId: Long): Flow<List<Series>>
fun getSeriesByCategory(providerId: Long, categoryId: Long): Flow<List<Series>>
+ fun getSeriesByIds(ids: List<Long>): Flow<List<Series>>
fun getCategories(providerId: Long): Flow<List<Category>>
fun searchSeries(providerId: Long, query: String): Flow<List<Series>>
suspend fun getSeriesById(seriesId: Long): Series?
diff --git a/domain/src/main/java/com/streamvault/domain/usecase/GetCustomCategories.kt b/domain/src/main/java/com/streamvault/domain/usecase/GetCustomCategories.kt
index df7cebae..3a163893 100644
--- a/domain/src/main/java/com/streamvault/domain/usecase/GetCustomCategories.kt
+++ b/domain/src/main/java/com/streamvault/domain/usecase/GetCustomCategories.kt
@@ -4,7 +4,6 @@ import com.streamvault.domain.model.Category
import com.streamvault.domain.model.ContentType
import com.streamvault.domain.repository.FavoriteRepository
import kotlinx.coroutines.flow.Flow
-import kotlinx.coroutines.flow.map
import javax.inject.Inject
class GetCustomCategories @Inject constructor(
@@ -16,12 +15,10 @@ class GetCustomCategories @Inject constructor(
favoriteRepository.getGlobalFavoriteCount(contentType),
favoriteRepository.getGroupFavoriteCounts(contentType)
) { groups, globalCount, groupCounts ->
- try {
- println("GetCustomCategories: Processing ${groups.size} groups. Global: $globalCount, Counts: ${groupCounts.size}")
-
+ runCatching {
val categories = groups.map { group ->
Category(
- id = -group.id, // Use negative ID for virtual groups
+ id = -group.id, // Negative IDs reserve virtual groups.
name = group.name,
type = contentType,
isVirtual = true,
@@ -29,20 +26,21 @@ class GetCustomCategories @Inject constructor(
)
}.toMutableList()
- // prepend "Favorites" as a special virtual category
- categories.add(0, Category(
- id = -999L, // Special ID for "All Favorites"
- name = "★ Favorites",
- type = contentType,
- isVirtual = true,
- count = globalCount
- ))
+ // Prepend global "Favorites" virtual category.
+ categories.add(
+ index = 0,
+ element = Category(
+ id = -999L,
+ name = "Favorites",
+ type = contentType,
+ isVirtual = true,
+ count = globalCount
+ )
+ )
categories
- } catch (e: Exception) {
- println("GetCustomCategories: Error processing categories: ${e.message}")
- e.printStackTrace()
- emptyList<Category>()
+ }.getOrElse {
+ emptyList()
}
}
}