StreamVault is a TV-first free IPTV player for Android TV built with Kotlin, Jetpack Compose, Room, Hilt, and Media3.
Kotlin iptv-player
feat: provider sync change
David Nashash2df0d1262e9c
diff --git a/.codex/hooks.json b/.codex/hooks.jsonnew file mode 100644index 00000000..f905deab--- /dev/null+++ b/.codex/hooks.json@@ -0,0 +1,15 @@+{+ "hooks": {+ "PreToolUse": [+ {+ "matcher": "Bash",+ "hooks": [+ {+ "type": "command",+ "command": "graphify hook-check"+ }+ ]+ }+ ]+ }+}\ No newline at end of filediff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.mdnew file mode 100644index 00000000..7a6fd1d6--- /dev/null+++ b/.github/copilot-instructions.md@@ -0,0 +1,7 @@+## graphify++If a task mentions Graphify or requires building, updating, or querying the knowledge graph, load the global `graphify` skill first if it is not already loaded in the current session. Treat the loaded Graphify skill as the source of truth for invocation and workflow details rather than inferring commands from memory.++Before answering architecture or codebase questions, read `graphify-out/GRAPH_REPORT.md` if it exists.+If `graphify-out/wiki/index.md` exists, navigate it for deep questions.+Type `/graphify` in Copilot Chat to build or update the knowledge graph.diff --git a/.graphifyignore b/.graphifyignorenew file mode 100644index 00000000..0557d009--- /dev/null+++ b/.graphifyignore@@ -0,0 +1,23 @@+.git/+.gradle/+.kotlin/+.venv/+.vscode/+.tmp-inspect/++build/+**/build/+domain/bin/+tmp/++local.properties+**/local.properties+*.local.properties+keystore.properties+release-signing-info.local.txt+keystore/++graphify-out/+AGENTS.md+.codex/+.github/copilot-instructions.md\ No newline at end of filediff --git a/AGENTS.md b/AGENTS.mdnew file mode 100644index 00000000..f449b672--- /dev/null+++ b/AGENTS.md@@ -0,0 +1,9 @@+## graphify++This project has a graphify knowledge graph at graphify-out/.++Rules:+- Before answering architecture or codebase questions, read graphify-out/GRAPH_REPORT.md for god nodes and community structure+- If graphify-out/wiki/index.md exists, navigate it instead of reading raw files+- For cross-module "how does X relate to Y" questions, prefer `graphify query "<question>"`, `graphify path "<A>" "<B>"`, or `graphify explain "<concept>"` over grep — these traverse the graph's EXTRACTED + INFERRED edges instead of scanning files+- After modifying code files in this session, run `graphify update .` to keep the graph current (AST-only, no API cost)diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xmlindex 1a9f42d6..1ccd5bda 100644--- a/app/src/main/AndroidManifest.xml+++ b/app/src/main/AndroidManifest.xml@@ -4,6 +4,7 @@<uses-permission android:name="android.permission.INTERNET" /><uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />+ <uses-permission android:name="android.permission.POST_NOTIFICATIONS" /><uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" /><uses-permission android:name="com.android.providers.tv.permission.READ_EPG_DATA" /><uses-permission android:name="com.android.providers.tv.permission.WRITE_EPG_DATA" />diff --git a/app/src/main/java/com/streamvault/app/MainActivity.kt b/app/src/main/java/com/streamvault/app/MainActivity.ktindex 72361ab2..0a07dfda 100644--- a/app/src/main/java/com/streamvault/app/MainActivity.kt+++ b/app/src/main/java/com/streamvault/app/MainActivity.kt@@ -16,6 +16,7 @@ import com.streamvault.app.cast.CastRouteChooserActivityimport com.streamvault.app.device.isTelevisionDeviceimport com.streamvault.app.localization.resolveAppLocaleimport com.streamvault.app.navigation.AppNavigation+import com.streamvault.app.navigation.ExternalDestinationimport com.streamvault.app.navigation.ExternalNavigationRequestimport com.streamvault.app.navigation.PlayerNavigationRequestimport com.streamvault.app.tv.LauncherRecommendationsManager@@ -55,6 +56,7 @@ class MainActivity : ComponentActivity() {companion object {const val EXTRA_PLAYER_REQUEST = "com.streamvault.app.extra.PLAYER_REQUEST"+ const val EXTRA_EXTERNAL_DESTINATION = "com.streamvault.app.extra.EXTERNAL_DESTINATION"const val EXTRA_EXTERNAL_ROUTE = "com.streamvault.app.extra.EXTERNAL_ROUTE"private const val MAX_PIP_ASPECT_RATIO = 2.39fprivate const val MIN_PIP_ASPECT_RATIO = 1f / MAX_PIP_ASPECT_RATIO@@ -280,7 +282,13 @@ class MainActivity : ComponentActivity() {private fun Intent.toExternalNavigationRequest(): ExternalNavigationRequest? {readPlayerRequestExtra()?.let { return ExternalNavigationRequest.Player(it) }- getStringExtra(EXTRA_EXTERNAL_ROUTE)?.let { return ExternalNavigationRequest.Route(it) }+ readExternalDestinationExtra()?.let { return ExternalNavigationRequest.Destination(it) }+ getStringExtra(EXTRA_EXTERNAL_ROUTE)+ ?.let(ExternalDestination::fromLegacyRoute)+ ?.let { return ExternalNavigationRequest.Destination(it) }+ if (hasExtra(EXTRA_EXTERNAL_ROUTE)) {+ return ExternalNavigationRequest.Destination(ExternalDestination.Home)+ }readImportedPlaylistUri()?.let { return ExternalNavigationRequest.ImportM3u(it) }val query = when (action) {@@ -294,7 +302,13 @@ class MainActivity : ComponentActivity() {else -> null}?.trim().orEmpty()- return query.takeIf { it.isNotBlank() }?.let(ExternalNavigationRequest::Search)+ query.takeIf { it.isNotBlank() }?.let(ExternalNavigationRequest::Search)?.let { return it }++ return if (action == Intent.ACTION_VIEW) {+ ExternalNavigationRequest.Destination(ExternalDestination.Home)+ } else {+ null+ }}private fun Intent.readImportedPlaylistUri(): String? {@@ -325,4 +339,13 @@ class MainActivity : ComponentActivity() {getSerializableExtra(EXTRA_PLAYER_REQUEST) as? PlayerNavigationRequest}}++ @Suppress("DEPRECATION")+ private fun Intent.readExternalDestinationExtra(): ExternalDestination? {+ return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {+ getSerializableExtra(EXTRA_EXTERNAL_DESTINATION, ExternalDestination::class.java)+ } else {+ getSerializableExtra(EXTRA_EXTERNAL_DESTINATION) as? ExternalDestination+ }+ }}diff --git a/app/src/main/java/com/streamvault/app/di/DatabaseModule.kt b/app/src/main/java/com/streamvault/app/di/DatabaseModule.ktindex 06941333..ee0543bc 100644--- a/app/src/main/java/com/streamvault/app/di/DatabaseModule.kt+++ b/app/src/main/java/com/streamvault/app/di/DatabaseModule.kt@@ -82,7 +82,10 @@ object DatabaseModule {StreamVaultDatabase.MIGRATION_40_41,StreamVaultDatabase.MIGRATION_41_42,StreamVaultDatabase.MIGRATION_42_43,- StreamVaultDatabase.MIGRATION_43_44+ StreamVaultDatabase.MIGRATION_43_44,+ StreamVaultDatabase.MIGRATION_44_45,+ StreamVaultDatabase.MIGRATION_45_46,+ StreamVaultDatabase.MIGRATION_46_47)// 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/navigation/AppNavigation.kt b/app/src/main/java/com/streamvault/app/navigation/AppNavigation.ktindex 589a3751..ddb3333d 100644--- a/app/src/main/java/com/streamvault/app/navigation/AppNavigation.kt+++ b/app/src/main/java/com/streamvault/app/navigation/AppNavigation.kt@@ -11,8 +11,10 @@ import androidx.navigation.NavOptionsBuilderimport androidx.navigation.NavTypeimport androidx.navigation.compose.NavHostimport androidx.navigation.compose.composable+import androidx.navigation.compose.currentBackStackEntryAsStateimport androidx.navigation.compose.rememberNavControllerimport androidx.navigation.navArgument+import com.streamvault.app.ui.model.isArchivePlayableimport com.streamvault.domain.model.Channelimport com.streamvault.domain.model.Episodeimport com.streamvault.domain.model.Movie@@ -50,7 +52,8 @@ data class PlayerNavigationRequest(val returnRoute: String? = null,val seriesId: Long? = null,val seasonNumber: Int? = null,- val episodeNumber: Int? = null+ val episodeNumber: Int? = null,+ val episodeId: Long? = null) : Serializableobject Routes {@@ -132,7 +135,8 @@ object Routes {artworkUrl = episode.coverUrl,seriesId = episode.seriesId.takeIf { it > 0L },seasonNumber = episode.seasonNumber,- episodeNumber = episode.episodeNumber+ episodeNumber = episode.episodeNumber,+ episodeId = episode.episodeId.takeIf { it > 0L })}@@ -157,7 +161,8 @@ object Routes {returnRoute: String? = null,seriesId: Long? = null,seasonNumber: Int? = null,- episodeNumber: Int? = null+ episodeNumber: Int? = null,+ episodeId: Long? = null): PlayerNavigationRequest {return PlayerNavigationRequest(streamUrl = streamUrl,@@ -177,7 +182,8 @@ object Routes {returnRoute = returnRoute,seriesId = seriesId,seasonNumber = seasonNumber,- episodeNumber = episodeNumber+ episodeNumber = episodeNumber,+ episodeId = episodeId)}@@ -196,47 +202,56 @@ private fun isStreamUrlSafe(url: String?): Boolean {}/** Navigate only when the current destination is fully resumed – prevents double-navigation during transitions. */-private fun NavHostController.navigateIfResumed(route: String, builder: NavOptionsBuilder.() -> Unit = {}) {- if (currentBackStackEntry?.lifecycle?.currentState?.isAtLeast(Lifecycle.State.RESUMED) != true) return+private fun NavHostController.navigateIfResumed(route: String, builder: NavOptionsBuilder.() -> Unit = {}): Boolean {+ if (currentBackStackEntry?.lifecycle?.currentState?.isAtLeast(Lifecycle.State.RESUMED) != true) return falsenavigate(route, builder)+ return true}-private fun NavHostController.navigateToPlayer(request: PlayerNavigationRequest) {- if (currentBackStackEntry?.lifecycle?.currentState?.isAtLeast(Lifecycle.State.RESUMED) != true) return+private fun NavHostController.navigateToPlayer(request: PlayerNavigationRequest): Boolean {+ if (currentBackStackEntry?.lifecycle?.currentState?.isAtLeast(Lifecycle.State.RESUMED) != true) return falsecurrentBackStackEntry?.savedStateHandle?.set(PLAYER_REQUEST_KEY, request)navigate(Routes.PLAYER) { launchSingleTop = true }+ return true}-private fun NavHostController.navigateToExternalPlayer(request: PlayerNavigationRequest) {+private fun NavHostController.navigateToExternalPlayer(request: PlayerNavigationRequest): Boolean {+ if (currentBackStackEntry?.lifecycle?.currentState?.isAtLeast(Lifecycle.State.RESUMED) != true) return falsecurrentBackStackEntry?.savedStateHandle?.set(PLAYER_REQUEST_KEY, request)navigate(Routes.PLAYER) { launchSingleTop = true }+ return true}@Composablefun AppNavigation(mainActivity: MainActivity) {val navController = rememberNavController()+ val currentBackStackEntry = navController.currentBackStackEntryAsState().valueval externalNavigationRequest = mainActivity.externalNavigationRequestFlow.collectAsStateWithLifecycle().value- LaunchedEffect(externalNavigationRequest) {+ LaunchedEffect(externalNavigationRequest, currentBackStackEntry?.lifecycle?.currentState) {when (val request = externalNavigationRequest) {is ExternalNavigationRequest.Player -> {- navController.navigateToExternalPlayer(request.request)- mainActivity.clearExternalNavigationRequest()+ if (navController.navigateToExternalPlayer(request.request)) {+ mainActivity.clearExternalNavigationRequest()+ }}- is ExternalNavigationRequest.Route -> {- navController.navigate(request.route) { launchSingleTop = true }- mainActivity.clearExternalNavigationRequest()+ is ExternalNavigationRequest.Destination -> {+ if (navController.navigateIfResumed(request.destination.toRoute()) { launchSingleTop = true }) {+ mainActivity.clearExternalNavigationRequest()+ }}is ExternalNavigationRequest.ImportM3u -> {- navController.navigate(Routes.providerSetup(importUri = request.uri)) { launchSingleTop = true }- mainActivity.clearExternalNavigationRequest()+ if (navController.navigateIfResumed(Routes.providerSetup(importUri = request.uri)) { launchSingleTop = true }) {+ mainActivity.clearExternalNavigationRequest()+ }}is ExternalNavigationRequest.Search -> {- navController.navigate(Routes.search(request.query)) { launchSingleTop = true }- mainActivity.clearExternalNavigationRequest()+ if (navController.navigateIfResumed(Routes.search(request.query)) { launchSingleTop = true }) {+ mainActivity.clearExternalNavigationRequest()+ }}null -> Unit@@ -420,6 +435,11 @@ fun AppNavigation(mainActivity: MainActivity) {onMovieClick = { movie ->navController.navigateIfResumed(Routes.movieDetail(movie.id, Routes.MOVIES))},+ onContinueWatchingPlay = { history ->+ navController.navigateToPlayer(+ history.toPlayerNavigationRequest().copy(returnRoute = Routes.MOVIES)+ )+ },onNavigate = { route -> tabNavigate(route) },currentRoute = Routes.MOVIES)@@ -464,6 +484,9 @@ fun AppNavigation(mainActivity: MainActivity) {)},onPlayArchive = { channel, program, categoryId, isVirtual, combinedProfileId, returnRoute ->+ if (!channel.isArchivePlayable(program)) {+ return@FullEpgScreen+ }navController.navigateToPlayer(Routes.player(streamUrl = channel.streamUrl,@@ -574,6 +597,7 @@ fun AppNavigation(mainActivity: MainActivity) {seriesId = playerRequest?.seriesId,seasonNumber = playerRequest?.seasonNumber,episodeNumber = playerRequest?.episodeNumber,+ episodeId = playerRequest?.episodeId,onBack = {val route = playerRequest?.returnRouteif (!route.isNullOrBlank() && navController.popBackStack(route, false)) {diff --git a/app/src/main/java/com/streamvault/app/navigation/ExternalNavigationRequest.kt b/app/src/main/java/com/streamvault/app/navigation/ExternalNavigationRequest.ktindex cdb0ee67..24632f1d 100644--- a/app/src/main/java/com/streamvault/app/navigation/ExternalNavigationRequest.kt+++ b/app/src/main/java/com/streamvault/app/navigation/ExternalNavigationRequest.kt@@ -1,8 +1,95 @@package com.streamvault.app.navigation+import java.io.Serializable+import java.net.URLDecoder+import java.nio.charset.StandardCharsets++sealed class ExternalDestination : Serializable {+ data object Home : ExternalDestination()++ data class ProviderSetup(+ val providerId: Long? = null,+ val importUri: String? = null+ ) : ExternalDestination()++ data class MovieDetail(+ val movieId: Long,+ val returnRoute: String? = null+ ) : ExternalDestination()++ data class SeriesDetail(+ val seriesId: Long,+ val returnRoute: String? = null+ ) : ExternalDestination()++ fun toRoute(): String = when (this) {+ Home -> Routes.HOME+ is ProviderSetup -> Routes.providerSetup(providerId = providerId, importUri = importUri)+ is MovieDetail -> Routes.movieDetail(movieId = movieId, returnRoute = returnRoute)+ is SeriesDetail -> Routes.seriesDetail(seriesId = seriesId, returnRoute = returnRoute)+ }++ companion object {+ fun fromLegacyRoute(route: String): ExternalDestination? {+ val normalizedRoute = route.trim()+ if (normalizedRoute.isEmpty()) return null++ return when {+ normalizedRoute == Routes.HOME -> Home+ normalizedRoute.startsWith(Routes.PROVIDER_SETUP.substringBefore('?')) -> {+ val queryParameters = normalizedRoute.queryParameters()+ val providerId = queryParameters["providerId"]+ ?.toLongOrNull()+ ?.takeIf { it >= 0L }+ val importUri = queryParameters["importUri"]+ ?.takeIf { it.isNotBlank() }+ ProviderSetup(providerId = providerId, importUri = importUri)+ }++ normalizedRoute.startsWith("movie_detail/") -> {+ val pathSegments = normalizedRoute.pathSegments()+ val movieId = pathSegments.getOrNull(1)?.toLongOrNull() ?: return null+ MovieDetail(+ movieId = movieId,+ returnRoute = normalizedRoute.queryParameters()["returnRoute"]+ ?.takeIf { it.isNotBlank() }+ )+ }++ normalizedRoute.startsWith("series_detail/") -> {+ val pathSegments = normalizedRoute.pathSegments()+ val seriesId = pathSegments.getOrNull(1)?.toLongOrNull() ?: return null+ SeriesDetail(+ seriesId = seriesId,+ returnRoute = normalizedRoute.queryParameters()["returnRoute"]+ ?.takeIf { it.isNotBlank() }+ )+ }++ else -> null+ }+ }+ }+}++private fun String.pathSegments(): List<String> = substringBefore('?').split('/').filter { it.isNotBlank() }++private fun String.queryParameters(): Map<String, String> {+ val query = substringAfter('?', missingDelimiterValue = "")+ if (query.isBlank()) return emptyMap()+ return query.split('&')+ .mapNotNull { entry ->+ val key = entry.substringBefore('=', missingDelimiterValue = "").takeIf { it.isNotBlank() }+ ?: return@mapNotNull null+ val rawValue = entry.substringAfter('=', missingDelimiterValue = "")+ key to URLDecoder.decode(rawValue, StandardCharsets.UTF_8)+ }+ .toMap()+}+sealed interface ExternalNavigationRequest {data class Search(val query: String) : ExternalNavigationRequestdata class Player(val request: PlayerNavigationRequest) : ExternalNavigationRequest- data class Route(val route: String) : ExternalNavigationRequest+ data class Destination(val destination: ExternalDestination) : ExternalNavigationRequestdata class ImportM3u(val uri: String) : ExternalNavigationRequest}diff --git a/app/src/main/java/com/streamvault/app/navigation/PlaybackHistoryNavigation.kt b/app/src/main/java/com/streamvault/app/navigation/PlaybackHistoryNavigation.ktnew file mode 100644index 00000000..656cc8f6--- /dev/null+++ b/app/src/main/java/com/streamvault/app/navigation/PlaybackHistoryNavigation.kt@@ -0,0 +1,16 @@+package com.streamvault.app.navigation++import com.streamvault.domain.model.PlaybackHistory++internal fun PlaybackHistory.toPlayerNavigationRequest(): PlayerNavigationRequest =+ PlayerNavigationRequest(+ streamUrl = streamUrl,+ title = title,+ internalId = contentId,+ providerId = providerId,+ contentType = contentType.name,+ artworkUrl = posterUrl,+ seriesId = seriesId,+ seasonNumber = seasonNumber,+ episodeNumber = episodeNumber+ )\ No newline at end of filediff --git a/app/src/main/java/com/streamvault/app/tv/LauncherRecommendationsManager.kt b/app/src/main/java/com/streamvault/app/tv/LauncherRecommendationsManager.ktindex 74d1ad5f..b1f3b8a4 100644--- a/app/src/main/java/com/streamvault/app/tv/LauncherRecommendationsManager.kt+++ b/app/src/main/java/com/streamvault/app/tv/LauncherRecommendationsManager.kt@@ -13,15 +13,22 @@ import android.util.Logimport com.streamvault.app.MainActivityimport com.streamvault.app.Rimport com.streamvault.app.device.isTelevisionDevice+import com.streamvault.app.navigation.ExternalDestinationimport com.streamvault.app.navigation.PlayerNavigationRequest+import com.streamvault.app.navigation.toPlayerNavigationRequest+import com.streamvault.domain.model.ActiveLiveSourceimport com.streamvault.domain.model.ContentTypeimport com.streamvault.domain.model.PlaybackHistoryimport com.streamvault.domain.model.Provider+import com.streamvault.domain.repository.CombinedM3uRepositoryimport com.streamvault.domain.repository.MovieRepositoryimport com.streamvault.domain.repository.PlaybackHistoryRepositoryimport com.streamvault.domain.repository.ProviderRepositoryimport com.streamvault.domain.repository.SeriesRepositoryimport com.streamvault.domain.usecase.GetRecommendations+import com.streamvault.domain.usecase.GetContinueWatching+import com.streamvault.domain.usecase.ContinueWatchingResult+import com.streamvault.domain.usecase.RecommendationsResultimport kotlinx.coroutines.Dispatchersimport dagger.hilt.android.qualifiers.ApplicationContextimport kotlinx.coroutines.flow.first@@ -36,11 +43,13 @@ import javax.inject.Singletonclass LauncherRecommendationsManager @Inject constructor(@ApplicationContext private val context: Context,private val providerRepository: ProviderRepository,+ private val combinedM3uRepository: CombinedM3uRepository,private val playbackHistoryRepository: PlaybackHistoryRepository,movieRepository: MovieRepository,private val seriesRepository: SeriesRepository) {private val getRecommendations = GetRecommendations(movieRepository)+ private val getContinueWatching = GetContinueWatching(playbackHistoryRepository)private val refreshMutex = Mutex()@Volatileprivate var lastRefreshAtMs: Long = 0L@@ -54,7 +63,7 @@ class LauncherRecommendationsManager @Inject constructor(return@withLock}- val provider = providerRepository.getActiveProvider().first()+ val provider = resolveActiveProvider()if (provider == null) {deleteAllManagedChannels()lastRefreshAtMs = now@@ -72,6 +81,10 @@ class LauncherRecommendationsManager @Inject constructor(.forEach(::deleteChannel)specs.forEach { spec ->+ if (spec.isDegraded) {+ // Transient failure — preserve existing channel and programs unchanged.+ return@forEach+ }if (spec.programs.isEmpty()) {existingChannels[spec.key]?.let(::deleteChannel)return@forEach@@ -89,54 +102,86 @@ class LauncherRecommendationsManager @Inject constructor(}}+ /**+ * Resolves the provider that should drive launcher recommendation channels.+ * In single-provider mode, returns the active provider directly.+ * In combined-live mode, prefers the globally active provider only when it is a+ * member of the active combined profile; otherwise falls back to the first enabled member.+ */+ private suspend fun resolveActiveProvider(): Provider? {+ val activeSource = combinedM3uRepository.getActiveLiveSource().first()+ return when (activeSource) {+ is ActiveLiveSource.CombinedM3uSource -> {+ val memberIds = combinedM3uRepository.getProfile(activeSource.profileId)+ ?.members.orEmpty()+ .filter { it.enabled }+ .map { it.providerId }+ val activeProvider = providerRepository.getActiveProvider().first()+ activeProvider?.takeIf { it.id in memberIds }+ ?: memberIds.firstOrNull()?.let { providerRepository.getProvider(it) }+ }+ is ActiveLiveSource.ProviderSource -> {+ providerRepository.getActiveProvider().first()+ ?.takeIf { it.id == activeSource.providerId }+ ?: providerRepository.getProvider(activeSource.providerId)+ }+ null -> providerRepository.getActiveProvider().first()+ }+ }+private suspend fun buildChannelSpecs(provider: Provider): List<RecommendationChannelSpec> {- val continueWatching = playbackHistoryRepository.getRecentlyWatchedByProvider(provider.id, limit = 12)- .first()- .asSequence()- .filter { it.contentType == ContentType.MOVIE || it.contentType == ContentType.SERIES_EPISODE }- .filter { it.resumePositionMs > 0L && it.totalDurationMs > 0L }- .distinctBy { it.contentType to it.contentId }- .sortedByDescending { it.lastWatchedAt }- .map { history ->+ val continueWatching = when (val result = getContinueWatching(provider.id, limit = 12, requireResumePosition = true).first()) {+ is ContinueWatchingResult.Items -> result.items+ ContinueWatchingResult.Degraded -> emptyList()+ }.map { history ->RecommendationProgramSpec(key = "cw:${history.contentType.name}:${history.contentId}",title = history.title,description = context.getString(R.string.saved_preset_watch_next),posterArtUri = artworkUri(history.posterUrl),- intentUri = buildPlayerIntent(history.toPlayerRequest()).toUri(Intent.URI_INTENT_SCHEME),+ intentUri = buildPlayerIntent(history.toPlayerNavigationRequest()).toUri(Intent.URI_INTENT_SCHEME),weight = history.lastWatchedAt.toInt().coerceAtLeast(0),durationMillis = history.totalDurationMs,playbackPositionMillis = history.resumePositionMs,contentType = history.contentType)}- .toList()- val recommendedMovies = getRecommendations(provider.id, limit = 12)- .first()- .mapIndexed { index, movie ->- RecommendationProgramSpec(- key = "movie:${movie.id}",- title = movie.name,- description = movie.plot ?: movie.genre ?: provider.name,- posterArtUri = artworkUri(movie.posterUrl ?: movie.backdropUrl),- intentUri = buildPlayerIntent(- PlayerNavigationRequest(- streamUrl = movie.streamUrl,- title = movie.name,- internalId = movie.id,- categoryId = movie.categoryId,- providerId = movie.providerId,- contentType = ContentType.MOVIE.name,- artworkUrl = movie.posterUrl ?: movie.backdropUrl- )- ).toUri(Intent.URI_INTENT_SCHEME),- weight = (TOP_MOVIE_WEIGHT_BASE - index).coerceAtLeast(0),- durationMillis = movie.durationSeconds.toLong() * 1000L,- playbackPositionMillis = movie.watchProgress,- contentType = ContentType.MOVIE- )+ val recommendationsResult = getRecommendations(provider.id, limit = 12).first()+ val recommendedMovies: List<RecommendationProgramSpec>?+ val recommendationsDegraded: Boolean+ when (recommendationsResult) {+ is RecommendationsResult.Success -> {+ recommendedMovies = recommendationsResult.movies.mapIndexed { index, movie ->+ RecommendationProgramSpec(+ key = "movie:${movie.id}",+ title = movie.name,+ description = movie.plot ?: movie.genre ?: provider.name,+ posterArtUri = artworkUri(movie.posterUrl ?: movie.backdropUrl),+ intentUri = buildPlayerIntent(+ PlayerNavigationRequest(+ streamUrl = movie.streamUrl,+ title = movie.name,+ internalId = movie.id,+ categoryId = movie.categoryId,+ providerId = movie.providerId,+ contentType = ContentType.MOVIE.name,+ artworkUrl = movie.posterUrl ?: movie.backdropUrl+ )+ ).toUri(Intent.URI_INTENT_SCHEME),+ weight = (TOP_MOVIE_WEIGHT_BASE - index).coerceAtLeast(0),+ durationMillis = movie.durationSeconds.toLong() * 1000L,+ playbackPositionMillis = movie.watchProgress,+ contentType = ContentType.MOVIE+ )+ }+ recommendationsDegraded = false+ }+ RecommendationsResult.Degraded -> {+ recommendedMovies = emptyList()+ recommendationsDegraded = true}+ }val freshSeries = seriesRepository.getFreshPreview(provider.id, limit = 12).first()@@ -146,7 +191,9 @@ class LauncherRecommendationsManager @Inject constructor(title = series.name,description = series.plot ?: series.genre ?: provider.name,posterArtUri = artworkUri(series.posterUrl ?: series.backdropUrl),- intentUri = buildRouteIntent("series_detail/${series.id}").toUri(Intent.URI_INTENT_SCHEME),+ intentUri = buildDestinationIntent(+ ExternalDestination.SeriesDetail(series.id)+ ).toUri(Intent.URI_INTENT_SCHEME),weight = (FRESH_SERIES_WEIGHT_BASE - index).coerceAtLeast(0),durationMillis = 0L,playbackPositionMillis = 0L,@@ -165,7 +212,8 @@ class LauncherRecommendationsManager @Inject constructor(key = CHANNEL_TOP_MOVIES,title = context.getString(R.string.tv_channel_recommended_movies_title),description = context.getString(R.string.tv_channel_recommended_movies_description, provider.name),- programs = recommendedMovies+ programs = recommendedMovies,+ isDegraded = recommendationsDegraded),RecommendationChannelSpec(key = CHANNEL_FRESH_SERIES,@@ -304,16 +352,14 @@ class LauncherRecommendationsManager @Inject constructor(.putExtra(MainActivity.EXTRA_PLAYER_REQUEST, request).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP)- private fun buildRouteIntent(route: String): Intent =+ private fun buildDestinationIntent(destination: ExternalDestination): Intent =Intent(context, MainActivity::class.java).setAction(Intent.ACTION_VIEW)- .putExtra(MainActivity.EXTRA_EXTERNAL_ROUTE, route)+ .putExtra(MainActivity.EXTRA_EXTERNAL_DESTINATION, destination).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP)private fun buildBrowseIntent(): Intent =- Intent(context, MainActivity::class.java)- .setAction(Intent.ACTION_VIEW)- .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP)+ buildDestinationIntent(ExternalDestination.Home)private fun requestChannelBrowsable(channelId: Long) {runCatching {@@ -357,21 +403,12 @@ class LauncherRecommendationsManager @Inject constructor(return Uri.parse("android.resource://${context.packageName}/${R.mipmap.ic_launcher_vault}")}- private fun PlaybackHistory.toPlayerRequest(): PlayerNavigationRequest =- PlayerNavigationRequest(- streamUrl = streamUrl,- title = title,- internalId = contentId,- providerId = providerId,- contentType = contentType.name,- artworkUrl = posterUrl- )-private data class RecommendationChannelSpec(val key: String,val title: String,val description: String,- val programs: List<RecommendationProgramSpec>+ val programs: List<RecommendationProgramSpec>,+ val isDegraded: Boolean = false)private data class RecommendationProgramSpec(diff --git a/app/src/main/java/com/streamvault/app/tv/WatchNextManager.kt b/app/src/main/java/com/streamvault/app/tv/WatchNextManager.ktindex 8d9eca54..a22b6a41 100644--- a/app/src/main/java/com/streamvault/app/tv/WatchNextManager.kt+++ b/app/src/main/java/com/streamvault/app/tv/WatchNextManager.kt@@ -11,31 +11,37 @@ import android.util.Logimport com.streamvault.app.MainActivityimport com.streamvault.app.Rimport com.streamvault.app.device.isTelevisionDevice-import com.streamvault.app.navigation.PlayerNavigationRequest+import com.streamvault.app.navigation.toPlayerNavigationRequestimport com.streamvault.domain.model.ContentTypeimport com.streamvault.domain.model.PlaybackHistoryimport com.streamvault.domain.repository.PlaybackHistoryRepository+import com.streamvault.domain.repository.ProviderRepositoryimport dagger.hilt.android.qualifiers.ApplicationContext+import kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.flow.first+import kotlinx.coroutines.withContextimport javax.inject.Injectimport javax.inject.Singleton@Singletonclass WatchNextManager @Inject constructor(@ApplicationContext private val context: Context,- private val playbackHistoryRepository: PlaybackHistoryRepository+ private val playbackHistoryRepository: PlaybackHistoryRepository,+ private val providerRepository: ProviderRepository) {- suspend fun refreshWatchNext() {- if (!context.isTelevisionDevice()) return- val historyEntries = playbackHistoryRepository.getRecentlyWatched(limit = 40)- .first()- .asSequence()- .filter(::isEligibleForWatchNext)- .distinctBy(::watchNextKey)- .sortedByDescending { it.lastWatchedAt }- .take(MAX_WATCH_NEXT_ITEMS)- .toList()+ suspend fun refreshWatchNext() = withContext(Dispatchers.IO) {+ if (!context.isTelevisionDevice()) return@withContext+ val activeProviderId = providerRepository.getActiveProvider().first()?.id+ val historyEntries = selectWatchNextHistoryEntries(+ activeProviderId = activeProviderId,+ historyEntries = when {+ activeProviderId == null -> emptyList()+ else -> playbackHistoryRepository+ .getRecentlyWatchedByProvider(activeProviderId, limit = 40)+ .first()+ }+ )runCatching {val existingEntries = loadExistingEntries()@@ -93,7 +99,7 @@ class WatchNextManager @Inject constructor(private fun buildWatchNextValues(history: PlaybackHistory): ContentValues {val launchIntent = Intent(context, MainActivity::class.java).setAction(Intent.ACTION_VIEW)- .putExtra(MainActivity.EXTRA_PLAYER_REQUEST, history.toPlayerRequest())+ .putExtra(MainActivity.EXTRA_PLAYER_REQUEST, history.toPlayerNavigationRequest()).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP)return ContentValues().apply {@@ -137,16 +143,6 @@ class WatchNextManager @Inject constructor(private fun watchNextKey(history: PlaybackHistory): String ="${history.providerId}:${history.contentType.name}:${history.contentId}"- private fun PlaybackHistory.toPlayerRequest(): PlayerNavigationRequest =- PlayerNavigationRequest(- streamUrl = streamUrl,- title = title,- internalId = contentId,- providerId = providerId,- contentType = contentType.name,- artworkUrl = posterUrl- )-private companion object {const val TAG = "WatchNextManager"const val MAX_WATCH_NEXT_ITEMS = 12@@ -163,3 +159,23 @@ class WatchNextManager @Inject constructor(const val COLUMN_WATCH_NEXT_TYPE = "watch_next_type"}}++internal fun selectWatchNextHistoryEntries(+ activeProviderId: Long?,+ historyEntries: List<PlaybackHistory>+): List<PlaybackHistory> {+ val scopedProviderId = activeProviderId?.takeIf { it > 0L } ?: return emptyList()+ return historyEntries+ .asSequence()+ .filter { it.providerId == scopedProviderId }+ .filter { history ->+ history.resumePositionMs > 0L &&+ history.totalDurationMs > 0L &&+ (history.contentType == ContentType.MOVIE || history.contentType == ContentType.SERIES_EPISODE) &&+ history.resumePositionMs < history.totalDurationMs * 0.95f+ }+ .distinctBy { history -> "${history.providerId}:${history.contentType.name}:${history.contentId}" }+ .sortedByDescending { it.lastWatchedAt }+ .take(12)+ .toList()+}diff --git a/app/src/main/java/com/streamvault/app/tvinput/TvInputChannelSyncManager.kt b/app/src/main/java/com/streamvault/app/tvinput/TvInputChannelSyncManager.ktindex 91f81e57..5a1812ae 100644--- a/app/src/main/java/com/streamvault/app/tvinput/TvInputChannelSyncManager.kt+++ b/app/src/main/java/com/streamvault/app/tvinput/TvInputChannelSyncManager.kt@@ -154,6 +154,8 @@ class TvInputChannelSyncManager @Inject constructor(channel: Channel,existingChannelIds: MutableMap<String, Long>) {+ if (!shouldReplaceTvPrograms(channel, programs)) return+val resolver = context.contentResolvervar activeChannelId = channelId@@ -296,3 +298,8 @@ class TvInputChannelSyncManager @Inject constructor(val syncMutex = Mutex()}}++internal fun shouldReplaceTvPrograms(channel: Channel, programs: List<Program>): Boolean {+ if (programs.isNotEmpty()) return true+ return channel.epgChannelId.isNullOrBlank()+}diff --git a/app/src/main/java/com/streamvault/app/tvinput/TvInputSetupActivity.kt b/app/src/main/java/com/streamvault/app/tvinput/TvInputSetupActivity.ktindex 21e2e291..020d48d3 100644--- a/app/src/main/java/com/streamvault/app/tvinput/TvInputSetupActivity.kt+++ b/app/src/main/java/com/streamvault/app/tvinput/TvInputSetupActivity.kt@@ -38,7 +38,7 @@ import androidx.lifecycle.compose.collectAsStateWithLifecycleimport androidx.lifecycle.viewModelScopeimport com.streamvault.app.Rimport com.streamvault.app.MainActivity-import com.streamvault.app.navigation.Routes+import com.streamvault.app.navigation.ExternalDestinationimport com.streamvault.app.ui.theme.ErrorColorimport com.streamvault.app.ui.theme.OnBackgroundimport com.streamvault.app.ui.theme.OnSurfaceDim@@ -72,7 +72,10 @@ class TvInputSetupActivity : ComponentActivity() {onOpenProviderSetup = {startActivity(Intent(this, MainActivity::class.java)- .putExtra(MainActivity.EXTRA_EXTERNAL_ROUTE, Routes.providerSetup())+ .putExtra(+ MainActivity.EXTRA_EXTERNAL_DESTINATION,+ ExternalDestination.ProviderSetup()+ ).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP))},diff --git a/app/src/main/java/com/streamvault/app/ui/components/dialogs/AddToGroupDialog.kt b/app/src/main/java/com/streamvault/app/ui/components/dialogs/AddToGroupDialog.ktindex 039ad2b7..dd023857 100644--- a/app/src/main/java/com/streamvault/app/ui/components/dialogs/AddToGroupDialog.kt+++ b/app/src/main/java/com/streamvault/app/ui/components/dialogs/AddToGroupDialog.kt@@ -44,7 +44,7 @@ fun AddToGroupDialog(onToggleFavorite: () -> Unit,onAddToGroup: (Category) -> Unit,onRemoveFromGroup: (Category) -> Unit,- onCreateGroup: (String) -> Unit,+ onCreateGroup: ((String) -> Unit)? = null,isQueuedForSplitScreen: Boolean = false,onOpenSplitScreenPlanner: (() -> Unit)? = null,onRemoveFromRecent: (() -> Unit)? = null@@ -77,15 +77,15 @@ fun AddToGroupDialog(val safeToggleFavorite = { if (canInteract) onToggleFavorite() }val safeOpenSplitScreenPlanner = { if (canInteract) onOpenSplitScreenPlanner?.invoke() }val safeRemoveFromRecent = { if (canInteract) onRemoveFromRecent?.invoke() }- val safeCreateGroup = { if (canInteract) showCreateGroup = true }+ val safeCreateGroup = { if (canInteract && onCreateGroup != null) showCreateGroup = true }val safeAddToGroup: (Category) -> Unit = { group -> if (canInteract) onAddToGroup(group) }val safeRemoveFromGroup: (Category) -> Unit = { group -> if (canInteract) onRemoveFromGroup(group) }- if (showCreateGroup) {+ if (showCreateGroup && onCreateGroup != null) {CreateGroupDialog(onDismissRequest = { showCreateGroup = false },onConfirm = { name ->- onCreateGroup(name)+ onCreateGroup.invoke(name)showCreateGroup = false})@@ -325,7 +325,7 @@ fun AddToGroupDialog(}}- item {+ if (onCreateGroup != null) item {var isFocused by remember { mutableStateOf(false) }Spacer(modifier = Modifier.height(8.dp))OutlinedButton(diff --git a/app/src/main/java/com/streamvault/app/ui/components/dialogs/PremiumDialog.kt b/app/src/main/java/com/streamvault/app/ui/components/dialogs/PremiumDialog.ktindex 8492d4c8..706eef25 100644--- a/app/src/main/java/com/streamvault/app/ui/components/dialogs/PremiumDialog.kt+++ b/app/src/main/java/com/streamvault/app/ui/components/dialogs/PremiumDialog.kt@@ -3,15 +3,20 @@ package com.streamvault.app.ui.components.dialogsimport android.view.KeyEvent as AndroidKeyEventimport androidx.compose.foundation.BorderStrokeimport androidx.compose.foundation.background+import androidx.compose.foundation.layout.Boximport androidx.compose.foundation.layout.Arrangementimport androidx.compose.foundation.layout.BoxWithConstraintsimport androidx.compose.foundation.layout.Columnimport androidx.compose.foundation.layout.ColumnScope+import androidx.compose.foundation.layout.heightInimport androidx.compose.foundation.layout.Rowimport androidx.compose.foundation.layout.RowScopeimport androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.fillMaxHeightimport androidx.compose.foundation.layout.padding+import androidx.compose.foundation.rememberScrollStateimport androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.foundation.verticalScrollimport androidx.compose.runtime.Composableimport androidx.compose.runtime.LaunchedEffectimport androidx.compose.runtime.compositionLocalOf@@ -64,6 +69,7 @@ fun PremiumDialog(onDismissRequest: () -> Unit,modifier: Modifier = Modifier,widthFraction: Float = 0.42f,+ heightFraction: Float? = 0.88f,content: @Composable ColumnScope.() -> Unit,footer: @Composable RowScope.() -> Unit = {}) {@@ -81,49 +87,66 @@ fun PremiumDialog() {androidx.compose.runtime.CompositionLocalProvider(LocalDialogCanInteract provides canInteract) {if (isTelevisionDevice) {- Surface(- modifier = modifier- .fillMaxWidth(widthFraction)- .onPreviewKeyEvent(blockOpenGesture),- shape = RoundedCornerShape(28.dp),- colors = SurfaceDefaults.colors(containerColor = AppColors.SurfaceElevated)+ BoxWithConstraints(+ modifier = Modifier.fillMaxWidth(),+ contentAlignment = Alignment.Center) {- Column(- modifier = Modifier- .background(- Brush.verticalGradient(- colors = listOf(- AppColors.BrandMuted.copy(alpha = 0.18f),- AppColors.SurfaceElevated,- AppColors.Surface+ val maxDialogBodyHeight = maxHeight * 0.5f+ val dialogModifier = modifier+ .fillMaxWidth(widthFraction)+ .then(+ if (heightFraction != null) Modifier.fillMaxHeight(heightFraction) else Modifier+ )+ .onPreviewKeyEvent(blockOpenGesture)+ Surface(+ modifier = dialogModifier,+ shape = RoundedCornerShape(28.dp),+ colors = SurfaceDefaults.colors(containerColor = AppColors.SurfaceElevated)+ ) {+ Column(+ modifier = Modifier+ .background(+ Brush.verticalGradient(+ colors = listOf(+ AppColors.BrandMuted.copy(alpha = 0.18f),+ AppColors.SurfaceElevated,+ AppColors.Surface+ )))- )- .padding(28.dp),- verticalArrangement = Arrangement.spacedBy(18.dp)- ) {- Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {- Text(- text = title,- style = MaterialTheme.typography.headlineMedium,- color = AppColors.TextPrimary- )- if (!subtitle.isNullOrBlank()) {+ .padding(28.dp),+ verticalArrangement = Arrangement.spacedBy(18.dp)+ ) {+ Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {Text(- text = subtitle,- style = MaterialTheme.typography.bodyMedium,- color = AppColors.TextSecondary+ text = title,+ style = MaterialTheme.typography.headlineMedium,+ color = AppColors.TextPrimary)+ if (!subtitle.isNullOrBlank()) {+ Text(+ text = subtitle,+ style = MaterialTheme.typography.bodyMedium,+ color = AppColors.TextSecondary+ )+ }}- }- Column(verticalArrangement = Arrangement.spacedBy(12.dp), content = content)+ Box(+ modifier = Modifier+ .weight(1f, fill = false)+ .heightIn(max = maxDialogBodyHeight)+ .verticalScroll(rememberScrollState())+ ) {+ Column(verticalArrangement = Arrangement.spacedBy(12.dp), content = content)+ }- Row(- modifier = Modifier.fillMaxWidth(),- horizontalArrangement = Arrangement.spacedBy(10.dp, androidx.compose.ui.Alignment.End),- content = footer- )+ Row(+ modifier = Modifier.fillMaxWidth(),+ horizontalArrangement = Arrangement.spacedBy(10.dp, androidx.compose.ui.Alignment.End),+ content = footer+ )+ }}}} else {@@ -136,11 +159,16 @@ fun PremiumDialog(maxWidth < 1000.dp -> maxOf(widthFraction, 0.62f)else -> widthFraction}+ val maxDialogBodyHeight = maxHeight * 0.5f+ val dialogModifier = modifier+ .fillMaxWidth(resolvedWidthFraction)+ .then(+ if (heightFraction != null) Modifier.fillMaxHeight(heightFraction) else Modifier+ )+ .onPreviewKeyEvent(blockOpenGesture)Surface(- modifier = modifier- .fillMaxWidth(resolvedWidthFraction)- .onPreviewKeyEvent(blockOpenGesture),+ modifier = dialogModifier,shape = RoundedCornerShape(28.dp),colors = SurfaceDefaults.colors(containerColor = AppColors.SurfaceElevated)) {@@ -173,7 +201,14 @@ fun PremiumDialog(}}- Column(verticalArrangement = Arrangement.spacedBy(12.dp), content = content)+ Box(+ modifier = Modifier+ .weight(1f, fill = false)+ .heightIn(max = maxDialogBodyHeight)+ .verticalScroll(rememberScrollState())+ ) {+ Column(verticalArrangement = Arrangement.spacedBy(12.dp), content = content)+ }Row(modifier = Modifier.fillMaxWidth(),diff --git a/app/src/main/java/com/streamvault/app/ui/interaction/TvComponents.kt b/app/src/main/java/com/streamvault/app/ui/interaction/TvComponents.ktindex 537f0fd6..9ad4f6a8 100644--- a/app/src/main/java/com/streamvault/app/ui/interaction/TvComponents.kt+++ b/app/src/main/java/com/streamvault/app/ui/interaction/TvComponents.kt@@ -21,6 +21,7 @@ import androidx.tv.material3.ClickableSurfaceGlowimport androidx.tv.material3.ClickableSurfaceScaleimport androidx.tv.material3.ClickableSurfaceShapeimport androidx.tv.material3.IconButton+import androidx.tv.material3.IconButtonDefaultsimport androidx.tv.material3.Surface/**@@ -98,13 +99,27 @@ fun TvButton(fun TvIconButton(onClick: () -> Unit,modifier: Modifier = Modifier,+ onLongClick: (() -> Unit)? = null,enabled: Boolean = true,+ scale: ButtonScale = IconButtonDefaults.scale(),+ glow: ButtonGlow = IconButtonDefaults.glow(),+ interactionSource: MutableInteractionSource? = null,+ shape: ButtonShape = IconButtonDefaults.shape(),+ colors: ButtonColors = IconButtonDefaults.colors(),+ border: ButtonBorder = IconButtonDefaults.border(),content: @Composable BoxScope.() -> Unit,) {IconButton(onClick = onClick,+ onLongClick = onLongClick,modifier = modifier.mouseClickable(onClick = onClick, enabled = enabled),enabled = enabled,+ scale = scale,+ glow = glow,+ interactionSource = interactionSource,+ shape = shape,+ colors = colors,+ border = border,content = content,)}diff --git a/app/src/main/java/com/streamvault/app/ui/model/ArchivePlayback.kt b/app/src/main/java/com/streamvault/app/ui/model/ArchivePlayback.ktnew file mode 100644index 00000000..43be5bad--- /dev/null+++ b/app/src/main/java/com/streamvault/app/ui/model/ArchivePlayback.kt@@ -0,0 +1,22 @@+package com.streamvault.app.ui.model++import com.streamvault.domain.model.Channel+import com.streamvault.domain.model.Program++private const val MILLIS_PER_DAY = 86_400_000L++fun Channel.isArchivePlayable(+ program: Program,+ now: Long = System.currentTimeMillis()+): Boolean {+ if (id <= 0L || providerId <= 0L) return false+ if (program.startTime <= 0L || program.endTime <= program.startTime) return false+ if (program.hasArchive) return true+ if (!catchUpSupported || program.endTime > now) return false++ val catchUpWindowStart = catchUpDays+ .takeIf { it > 0 }+ ?.let { days -> now - (days.toLong() * MILLIS_PER_DAY) }++ return catchUpWindowStart == null || program.startTime >= catchUpWindowStart+}\ No newline at end of filediff --git a/app/src/main/java/com/streamvault/app/ui/notifications/NotificationPermissionGate.kt b/app/src/main/java/com/streamvault/app/ui/notifications/NotificationPermissionGate.ktnew file mode 100644index 00000000..7ec08095--- /dev/null+++ b/app/src/main/java/com/streamvault/app/ui/notifications/NotificationPermissionGate.kt@@ -0,0 +1,103 @@+package com.streamvault.app.ui.notifications++import android.Manifest+import android.content.Context+import android.content.pm.PackageManager+import android.os.Build+import androidx.activity.compose.rememberLauncherForActivityResult+import androidx.activity.result.contract.ActivityResultContracts+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.platform.LocalContext+import androidx.core.app.NotificationManagerCompat+import androidx.core.content.ContextCompat++internal class NotificationPermissionGate(+ private val runReminderActionImpl: (() -> Unit) -> Unit,+ private val runRecordingActionImpl: (() -> Unit) -> Unit,+) {+ fun runReminderAction(action: () -> Unit) {+ runReminderActionImpl(action)+ }++ fun runRecordingAction(action: () -> Unit) {+ runRecordingActionImpl(action)+ }+}++private enum class NotificationPermissionRequestType {+ REMINDER,+ RECORDING_ALERTS,+}++@Composable+internal fun rememberNotificationPermissionGate(+ onNotificationsBlocked: (String) -> Unit,+ reminderBlockedMessage: String,+ recordingBlockedMessage: String,+): NotificationPermissionGate {+ val context = LocalContext.current+ var pendingReminderAction by remember { mutableStateOf<(() -> Unit)?>(null) }+ var pendingRequestType by remember { mutableStateOf<NotificationPermissionRequestType?>(null) }+ val permissionLauncher = rememberLauncherForActivityResult(+ contract = ActivityResultContracts.RequestPermission()+ ) { granted ->+ val requestType = pendingRequestType+ val reminderAction = pendingReminderAction+ pendingRequestType = null+ pendingReminderAction = null+ if (granted && notificationsEnabled(context)) {+ reminderAction?.invoke()+ return@rememberLauncherForActivityResult+ }+ when (requestType) {+ NotificationPermissionRequestType.REMINDER -> onNotificationsBlocked(reminderBlockedMessage)+ NotificationPermissionRequestType.RECORDING_ALERTS -> onNotificationsBlocked(recordingBlockedMessage)+ null -> Unit+ }+ }++ return NotificationPermissionGate(+ runReminderActionImpl = { action ->+ when {+ notificationsEnabled(context) -> action()+ needsNotificationRuntimePermission(context) -> {+ pendingReminderAction = action+ pendingRequestType = NotificationPermissionRequestType.REMINDER+ permissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS)+ }+ else -> {+ pendingReminderAction = null+ pendingRequestType = null+ onNotificationsBlocked(reminderBlockedMessage)+ }+ }+ },+ runRecordingActionImpl = { action ->+ when {+ needsNotificationRuntimePermission(context) -> {+ pendingReminderAction = null+ pendingRequestType = NotificationPermissionRequestType.RECORDING_ALERTS+ permissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS)+ }+ !notificationsEnabled(context) -> onNotificationsBlocked(recordingBlockedMessage)+ }+ action()+ }+ )+}++private fun needsNotificationRuntimePermission(context: Context): Boolean {+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {+ return false+ }+ return ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED+}++private fun notificationsEnabled(context: Context): Boolean {+ return !needsNotificationRuntimePermission(context) &&+ NotificationManagerCompat.from(context).areNotificationsEnabled()+}\ No newline at end of filediff --git a/app/src/main/java/com/streamvault/app/ui/screens/dashboard/DashboardViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/dashboard/DashboardViewModel.ktindex a8e484bc..5bf5e0de 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/dashboard/DashboardViewModel.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/dashboard/DashboardViewModel.kt@@ -27,6 +27,7 @@ import com.streamvault.domain.repository.MovieRepositoryimport com.streamvault.domain.repository.PlaybackHistoryRepositoryimport com.streamvault.domain.repository.ProviderRepositoryimport com.streamvault.domain.repository.SeriesRepository+import com.streamvault.domain.usecase.ContinueWatchingResultimport com.streamvault.domain.usecase.ContinueWatchingScopeimport com.streamvault.domain.usecase.GetContinueWatchingimport com.streamvault.domain.usecase.GetCustomCategories@@ -138,7 +139,7 @@ class DashboardViewModel @Inject constructor(.filter { it.enabled }.map { it.providerId }.distinct()- val provider = activeProvider+ val provider = activeProvider?.takeIf { it.id in liveProviderIds }?: liveProviderIds.firstOrNull()?.let { providerRepository.getProvider(it) }?: run {emit(DashboardUiState(isLoading = false, currentCombinedProfileId = activeSource.profileId))@@ -181,14 +182,15 @@ class DashboardViewModel @Inject constructor(val contentShelves = combine(observeFavoriteChannels(liveProviderIds).onStart { emit(emptyList()) },observeRecentChannels(liveProviderIds).onStart { emit(emptyList()) },- observeContinueWatching(provider.id).onStart { emit(emptyList()) },+ observeContinueWatching(liveProviderIds.toSet()).onStart { emit(ContinueWatchingShelf()) },movieShelf.onStart { emit(emptyList()) },seriesShelf.onStart { emit(emptyList()) }- ) { favoriteChannels, recentChannels, continueWatching, recentMovies, recentSeries ->+ ) { favoriteChannels, recentChannels, continueWatchingShelf, recentMovies, recentSeries ->DashboardContentShelves(favoriteChannels = favoriteChannels,recentChannels = recentChannels,- continueWatching = continueWatching,+ continueWatching = continueWatchingShelf.items,+ continueWatchingDegraded = continueWatchingShelf.isDegraded,recentMovies = recentMovies,recentSeries = recentSeries)@@ -222,6 +224,7 @@ class DashboardViewModel @Inject constructor(favoriteChannels = snapshot.shelves.favoriteChannels,recentChannels = snapshot.shelves.recentChannels,continueWatching = snapshot.shelves.continueWatching,+ continueWatchingDegraded = snapshot.shelves.continueWatchingDegraded,recentMovies = snapshot.shelves.recentMovies,recentSeries = snapshot.shelves.recentSeries,lastLiveCategory = snapshot.liveContext.lastVisitedCategory,@@ -239,6 +242,7 @@ class DashboardViewModel @Inject constructor(providerName = provider.name,recentChannels = snapshot.shelves.recentChannels,continueWatching = snapshot.shelves.continueWatching,+ continueWatchingDegraded = snapshot.shelves.continueWatchingDegraded,recentMovies = snapshot.shelves.recentMovies,recentSeries = snapshot.shelves.recentSeries),@@ -285,12 +289,17 @@ class DashboardViewModel @Inject constructor() { isAdult || isUserProtected }}- private fun observeContinueWatching(providerId: Long): Flow<List<PlaybackHistory>> =+ private fun observeContinueWatching(providerIds: Set<Long>): Flow<ContinueWatchingShelf> =getContinueWatching(- providerId = providerId,+ providerIds = providerIds,limit = CONTINUE_WATCHING_LIMIT,scope = ContinueWatchingScope.ALL_VOD- )+ ).map { result ->+ when (result) {+ is ContinueWatchingResult.Items -> ContinueWatchingShelf(items = result.items)+ ContinueWatchingResult.Degraded -> ContinueWatchingShelf(isDegraded = true)+ }+ }private fun buildLiveContext(providerIds: List<Long>,@@ -434,9 +443,21 @@ class DashboardViewModel @Inject constructor(providerName: String,recentChannels: List<Channel>,continueWatching: List<PlaybackHistory>,+ continueWatchingDegraded: Boolean,recentMovies: List<Movie>,recentSeries: List<Series>): DashboardFeature {+ // When continue-watching is empty due to a transient IO failure, do not silently+ // fall through to an unrelated hero — surface an explicit degraded state instead.+ if (continueWatching.isEmpty() && continueWatchingDegraded) {+ return DashboardFeature(+ title = appContext.getString(R.string.dashboard_resume_unavailable),+ summary = appContext.getString(R.string.dashboard_resume_unavailable_detail),+ artworkUrl = null,+ actionLabel = appContext.getString(R.string.dashboard_continue_watching),+ actionType = DashboardFeatureAction.CONTINUE_WATCHING+ )+ }val resumeItem = continueWatching.firstOrNull()if (resumeItem != null) {val detail = when (resumeItem.contentType) {@@ -581,10 +602,16 @@ private data class DashboardLiveContext(val shortcuts: List<DashboardLiveShortcut>)+private data class ContinueWatchingShelf(+ val items: List<PlaybackHistory> = emptyList(),+ val isDegraded: Boolean = false+)+private data class DashboardContentShelves(val favoriteChannels: List<Channel>,val recentChannels: List<Channel>,val continueWatching: List<PlaybackHistory>,+ val continueWatchingDegraded: Boolean = false,val recentMovies: List<Movie>,val recentSeries: List<Series>)@@ -603,6 +630,7 @@ data class DashboardUiState(val favoriteChannels: List<Channel> = emptyList(),val recentChannels: List<Channel> = emptyList(),val continueWatching: List<PlaybackHistory> = emptyList(),+ val continueWatchingDegraded: Boolean = false,val recentMovies: List<Movie> = emptyList(),val recentSeries: List<Series> = emptyList(),val lastLiveCategory: Category? = null,diff --git a/app/src/main/java/com/streamvault/app/ui/screens/epg/EpgControlComponents.kt b/app/src/main/java/com/streamvault/app/ui/screens/epg/EpgControlComponents.ktindex 314a0cd8..093c3282 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/epg/EpgControlComponents.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/epg/EpgControlComponents.kt@@ -67,9 +67,10 @@ import com.streamvault.app.ui.theme.Primaryimport com.streamvault.app.ui.theme.SurfaceElevatedimport com.streamvault.app.ui.theme.SurfaceHighlightimport java.text.SimpleDateFormat-import java.util.Calendarimport java.util.Dateimport java.util.Locale+import java.time.LocalDate+import java.time.ZoneIdimport kotlinx.coroutines.delayimport kotlinx.coroutines.launch@@ -524,7 +525,7 @@ internal fun GuideDayRow(val dayFormat = remember { SimpleDateFormat("EEE d MMM", Locale.getDefault()) }val dayAnchors = remember(selectedDayStart) {(-1L..3L).map { offset ->- selectedDayStart + (offset * EpgViewModel.DAY_SHIFT_MS)+ shiftGuideDayStart(selectedDayStart, offset)}}@@ -700,23 +701,17 @@ internal fun GuideShortcutChip(}internal fun startOfDay(timestamp: Long): Long {- val calendar = Calendar.getInstance().apply {- timeInMillis = timestamp- set(Calendar.HOUR_OF_DAY, 0)- set(Calendar.MINUTE, 0)- set(Calendar.SECOND, 0)- set(Calendar.MILLISECOND, 0)- }- return calendar.timeInMillis+ return startOfGuideDay(timestamp)}@Composableprivate fun dayRelativeLabel(dayStart: Long): String {- val todayStart = remember { startOfDay(System.currentTimeMillis()) }- return when (dayStart) {- todayStart - EpgViewModel.DAY_SHIFT_MS -> stringResource(R.string.epg_day_yesterday)- todayStart -> stringResource(R.string.epg_day_today)- todayStart + EpgViewModel.DAY_SHIFT_MS -> stringResource(R.string.epg_day_tomorrow)+ val zoneId = remember { ZoneId.systemDefault() }+ val today = remember { LocalDate.now(zoneId) }+ return when (dayRelativeOffset(dayStart, today, zoneId)) {+ -1L -> stringResource(R.string.epg_day_yesterday)+ 0L -> stringResource(R.string.epg_day_today)+ 1L -> stringResource(R.string.epg_day_tomorrow)else -> {val format = remember { SimpleDateFormat("EEE", Locale.getDefault()) }format.format(Date(dayStart))diff --git a/app/src/main/java/com/streamvault/app/ui/screens/epg/EpgHeroComponents.kt b/app/src/main/java/com/streamvault/app/ui/screens/epg/EpgHeroComponents.ktindex 618fb469..2677c2cc 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/epg/EpgHeroComponents.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/epg/EpgHeroComponents.kt@@ -34,6 +34,7 @@ import androidx.tv.material3.SurfaceDefaultsimport androidx.tv.material3.Textimport com.streamvault.app.Rimport com.streamvault.app.ui.components.ChannelLogoBadge+import com.streamvault.app.ui.model.isArchivePlayableimport com.streamvault.app.ui.interaction.TvClickableSurfaceimport com.streamvault.app.ui.model.guideLookupKeyimport com.streamvault.app.ui.time.LocalAppTimeFormat@@ -243,9 +244,9 @@ internal fun ImmersiveGuideHero(if (isRefreshing) {GuideHeroBadge(text = stringResource(R.string.epg_loading))}- if (selection?.program?.hasArchive == true || selection?.channel?.catchUpSupported == true) {+ if (selection?.program != null && selection.channel.isArchivePlayable(selection.program, currentGuideNow())) {GuideHeroBadge(- text = if (selection.program?.hasArchive == true) {+ text = if (selection.program.hasArchive) {stringResource(R.string.epg_program_replay_ready)} else {stringResource(R.string.epg_program_replay_partial)diff --git a/app/src/main/java/com/streamvault/app/ui/screens/epg/EpgScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/epg/EpgScreen.ktindex deca0c76..85b95830 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/epg/EpgScreen.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/epg/EpgScreen.kt@@ -1,6 +1,7 @@package com.streamvault.app.ui.screens.epgimport android.view.inputmethod.InputMethodManager+import com.streamvault.app.ui.model.isArchivePlayableimport com.streamvault.app.ui.model.guideLookupKeyimport androidx.compose.foundation.BorderStrokeimport androidx.compose.foundation.background@@ -88,6 +89,7 @@ import com.streamvault.app.Rimport com.streamvault.app.device.rememberIsTelevisionDeviceimport com.streamvault.app.ui.components.ChannelLogoBadgeimport com.streamvault.app.navigation.Routes+import com.streamvault.app.ui.notifications.rememberNotificationPermissionGateimport com.streamvault.app.ui.components.SelectionChipimport com.streamvault.app.ui.components.SelectionChipRowimport kotlinx.coroutines.launch@@ -155,6 +157,13 @@ fun FullEpgScreen(var pendingLockedAction by remember { mutableStateOf<LockedGuideAction?>(null) }val scope = rememberCoroutineScope()val context = LocalContext.current+ val notificationPermissionGate = rememberNotificationPermissionGate(+ onNotificationsBlocked = { message ->+ android.widget.Toast.makeText(context, message, android.widget.Toast.LENGTH_SHORT).show()+ },+ reminderBlockedMessage = stringResource(R.string.notification_permission_reminder_required),+ recordingBlockedMessage = stringResource(R.string.notification_permission_recording_alert_required)+ )val returnRoute = remember(uiState.selectedCategoryId, uiState.guideAnchorTime, uiState.showFavoritesOnly) {Routes.epg(categoryId = uiState.selectedCategoryId.takeIf { it != ChannelRepository.ALL_CHANNELS_ID },@@ -240,7 +249,13 @@ fun FullEpgScreen()},confirmButton = {- androidx.compose.material3.TextButton(onClick = { viewModel.forceScheduleRecording() }) {+ androidx.compose.material3.TextButton(+ onClick = {+ notificationPermissionGate.runRecordingAction {+ viewModel.forceScheduleRecording()+ }+ }+ ) {androidx.compose.material3.Text(text = stringResource(R.string.epg_recording_conflict_replace),color = com.streamvault.app.ui.theme.Primary@@ -582,6 +597,7 @@ fun FullEpgScreen(} else {null}+ val canWatchArchive = channel.isArchivePlayable(program, currentGuideNow())CompactGuideProgramDialog(channel = channel,program = program,@@ -602,7 +618,7 @@ fun FullEpgScreen()}},- onWatchArchive = if (program.hasArchive || channel.catchUpSupported) {+ onWatchArchive = if (canWatchArchive) {{selectedProgram = nullif (isGuideChannelLocked(channel, categoriesById, uiState.parentalControlLevel)) {@@ -623,20 +639,40 @@ fun FullEpgScreen(},reminderButtonLabel = reminderButtonLabel,onToggleReminder = reminderButtonLabel?.let {- { viewModel.toggleProgramReminder(channel, program) }+ {+ if (reminderStateMatches && programReminderUiState.isScheduled) {+ viewModel.toggleProgramReminder(channel, program)+ } else {+ notificationPermissionGate.runReminderAction {+ viewModel.toggleProgramReminder(channel, program)+ }+ }+ }},onScheduleRecording = if (channel.streamUrl.isNotBlank() && program.endTime > currentGuideNow()) {- { viewModel.scheduleRecording(channel, program) }+ {+ notificationPermissionGate.runRecordingAction {+ viewModel.scheduleRecording(channel, program)+ }+ }} else {null},onScheduleDailyRecording = if (channel.streamUrl.isNotBlank() && program.endTime > currentGuideNow()) {- { viewModel.scheduleRecording(channel, program, com.streamvault.domain.model.RecordingRecurrence.DAILY) }+ {+ notificationPermissionGate.runRecordingAction {+ viewModel.scheduleRecording(channel, program, com.streamvault.domain.model.RecordingRecurrence.DAILY)+ }+ }} else {null},onScheduleWeeklyRecording = if (channel.streamUrl.isNotBlank() && program.endTime > currentGuideNow()) {- { viewModel.scheduleRecording(channel, program, com.streamvault.domain.model.RecordingRecurrence.WEEKLY) }+ {+ notificationPermissionGate.runRecordingAction {+ viewModel.scheduleRecording(channel, program, com.streamvault.domain.model.RecordingRecurrence.WEEKLY)+ }+ }} else {null}diff --git a/app/src/main/java/com/streamvault/app/ui/screens/epg/EpgViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/epg/EpgViewModel.ktindex 4bc2ddc0..27b9b110 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@@ -1,5 +1,6 @@package com.streamvault.app.ui.screens.epg+import com.streamvault.app.ui.model.isArchivePlayableimport com.streamvault.app.ui.model.guideLookupKeyimport androidx.lifecycle.ViewModelimport androidx.lifecycle.viewModelScope@@ -407,7 +408,7 @@ class EpgViewModel @Inject constructor(private fun schedulePrefetchNextPage(snapshot: GuideBaseSnapshot) {if (!snapshot.hasMoreChannels) return- prefetchJob = viewModelScope.async<GuidePrefetchedPage?>(Dispatchers.IO) {+ prefetchJob = viewModelScope.async<GuidePrefetchedPage?> {val channels = fetchGuideChannelPage(providerId = snapshot.providerId,categoryId = snapshot.selectedCategoryId,@@ -440,16 +441,15 @@ class EpgViewModel @Inject constructor(favoriteChannelIds: Set<Long>): List<Channel> {if (providerId <= 0L) return emptyList()- // Favorites and virtual group categories aren't offset-pageable; All Channels is a negative sentinel but is pageable.- if (categoryId != ChannelRepository.ALL_CHANNELS_ID &&+ if (+ categoryId != ChannelRepository.ALL_CHANNELS_ID &&(categoryId == VirtualCategoryIds.FAVORITES || categoryId < 0L)) return emptyList()val withoutErrors = channelRepository.getChannelsWithoutErrorsPageOffset(providerId, categoryId, MAX_CHANNELS, offset)val raw = withoutErrors.ifEmpty {channelRepository.getChannelsByCategoryPageOffset(providerId, categoryId, MAX_CHANNELS, offset)}- val filtered = if (hiddenCategoryIds.isEmpty()) raw- else raw.filterNot { it.categoryId in hiddenCategoryIds }+ val filtered = if (hiddenCategoryIds.isEmpty()) raw else raw.filterNot { it.categoryId in hiddenCategoryIds }return if (favoritesOnly) filtered.filter { it.id in favoriteChannelIds } else filtered}@@ -687,27 +687,23 @@ class EpgViewModel @Inject constructor(}fun jumpToTomorrow() {- updateGuideAnchorTime(System.currentTimeMillis() + DAY_SHIFT_MS)+ updateGuideAnchorTime(shiftGuideAnchorByDays(System.currentTimeMillis(), 1))}fun jumpToPrimeTime() {- val selectedDayStart = (guideAnchorTime.value / DAY_SHIFT_MS) * DAY_SHIFT_MS- updateGuideAnchorTime(selectedDayStart + (PRIME_TIME_HOUR * 60 * 60 * 1000L))+ updateGuideAnchorTime(guidePrimeTimeAnchor(guideAnchorTime.value, PRIME_TIME_HOUR))}fun jumpToPreviousDay() {- updateGuideAnchorTime((guideAnchorTime.value - DAY_SHIFT_MS).coerceAtLeast(0L))+ updateGuideAnchorTime(shiftGuideAnchorByDays(guideAnchorTime.value, -1).coerceAtLeast(0L))}fun jumpToNextDay() {- updateGuideAnchorTime(guideAnchorTime.value + DAY_SHIFT_MS)+ updateGuideAnchorTime(shiftGuideAnchorByDays(guideAnchorTime.value, 1))}fun jumpToDay(dayStartMillis: Long) {- val currentTimeOfDay = guideAnchorTime.value- .mod(DAY_SHIFT_MS)- .let { if (it < 0L) it + DAY_SHIFT_MS else it }- updateGuideAnchorTime(dayStartMillis + currentTimeOfDay)+ updateGuideAnchorTime(jumpGuideAnchorToDay(guideAnchorTime.value, dayStartMillis))}fun toggleScheduledOnly() {@@ -764,9 +760,7 @@ class EpgViewModel @Inject constructor(providerRepository.getActiveProvider()) { activeSource, activeProvider ->Pair(activeSource ?: activeProvider?.id?.let { ActiveLiveSource.ProviderSource(it) }, activeProvider)- }.distinctUntilChanged { old, new ->- old.first == new.first && old.second?.id == new.second?.id- }.collectLatest { (activeSource, activeProvider) ->+ }.distinctUntilChanged().collectLatest { (activeSource, activeProvider) ->if (activeSource == null && activeProvider == null) {guideFallbackJob?.cancel()baseGuideSnapshot.value = null@@ -1047,11 +1041,18 @@ class EpgViewModel @Inject constructor(}}- private fun combinedGuideChannels(profileId: Long, categoryId: Long, providerIds: List<Long>) =- if (categoryId == ChannelRepository.ALL_CHANNELS_ID) {+ private fun combinedGuideChannels(+ profileId: Long,+ categoryId: Long,+ providerIds: List<Long>+ ): Flow<List<Channel>> {+ return if (categoryId == ChannelRepository.ALL_CHANNELS_ID) {val flows = combinedCategoriesById.values.map { combinedM3uRepository.getCombinedChannels(profileId, it) }- if (flows.isEmpty()) kotlinx.coroutines.flow.flowOf(emptyList())- else combine(flows) { arrays -> arrays.toList().flatMap { it } }+ if (flows.isEmpty()) {+ kotlinx.coroutines.flow.flowOf(emptyList<Channel>())+ } else {+ combine(flows) { arrays: Array<List<Channel>> -> arrays.toList().flatMap { it } }+ }} else if (categoryId == VirtualCategoryIds.FAVORITES) {observeLiveFavorites(providerIds).map { favorites -> favorites.sortedBy { it.position }.map { it.contentId } }@@ -1062,9 +1063,13 @@ class EpgViewModel @Inject constructor(.flatMapLatest(::loadGuideChannelsByOrderedIds)} else {val combinedCategory = combinedCategoriesById[categoryId]- if (combinedCategory == null) kotlinx.coroutines.flow.flowOf(emptyList())- else combinedM3uRepository.getCombinedChannels(profileId, combinedCategory)+ if (combinedCategory == null) {+ kotlinx.coroutines.flow.flowOf(emptyList<Channel>())+ } else {+ combinedM3uRepository.getCombinedChannels(profileId, combinedCategory)+ }}+ }private fun guideSelectionSeedFlow(): Flow<GuideSelectionSeed> =combine(@@ -1197,14 +1202,12 @@ class EpgViewModel @Inject constructor(return@collectLatest}- val displaySnapshot = withContext(Dispatchers.Default) {- buildGuideDisplaySnapshot(- baseSnapshot = baseSnapshot,- searchQuery = presentation.searchQuery,- scheduledOnly = presentation.scheduledOnly,- channelMode = presentation.channelMode- )- }+ val displaySnapshot = buildGuideDisplaySnapshot(+ baseSnapshot = baseSnapshot,+ searchQuery = presentation.searchQuery,+ scheduledOnly = presentation.scheduledOnly,+ channelMode = presentation.channelMode+ )_uiState.update {it.copy(@@ -1351,16 +1354,29 @@ class EpgViewModel @Inject constructor(providerId: Long,categoryId: Long,favoritesOnly: Boolean- ): Flow<List<Channel>> = combine(- channelRepository.getChannelsByCategoryPage(providerId, categoryId, MAX_CHANNELS),- channelRepository.getChannelsWithoutErrorsPage(providerId, categoryId, MAX_CHANNELS),+ ): Flow<List<Channel>> = if (favoritesOnly) {favoriteRepository.getFavorites(providerId, ContentType.LIVE)- ) { channelsByNumber, healthyChannels, favorites ->- val favoriteIds = favorites.map { it.contentId }.toSet()- if (favoritesOnly) {- healthyChannels.filter { it.id in favoriteIds }- .ifEmpty { channelsByNumber.filter { it.id in favoriteIds } }- } else {+ .map { favorites -> favorites.sortedBy { it.position }.map { it.contentId } }+ .flatMapLatest { favoriteIds ->+ val favoriteChannels = loadGuideChannelsByOrderedIds(favoriteIds, providerId)+ if (categoryId == ChannelRepository.ALL_CHANNELS_ID) {+ favoriteChannels+ } else {+ combine(+ favoriteChannels,+ channelRepository.getChannelsByCategory(providerId, categoryId)+ ) { orderedFavorites, categoryChannels ->+ val categoryChannelIds = categoryChannels.map(Channel::id).toSet()+ orderedFavorites.filter { it.id in categoryChannelIds }+ }+ }+ }+ } else {+ combine(+ channelRepository.getChannelsByCategoryPage(providerId, categoryId, MAX_CHANNELS),+ channelRepository.getChannelsWithoutErrorsPage(providerId, categoryId, MAX_CHANNELS),+ favoriteRepository.getFavorites(providerId, ContentType.LIVE)+ ) { channelsByNumber, healthyChannels, _ ->healthyChannels.ifEmpty { channelsByNumber }}}@@ -1401,43 +1417,36 @@ class EpgViewModel @Inject constructor(windowStart: Long,windowEnd: Long): GuideProgramsResult {- return withContext(Dispatchers.IO) {- if (channels.isEmpty()) {- return@withContext GuideProgramsResult(emptyMap(), failedCount = 0)- }+ if (channels.isEmpty()) {+ return GuideProgramsResult(emptyMap(), failedCount = 0)+ }- val guideKeys = channels.mapNotNull(Channel::guideLookupKey).distinct()+ // 1. Try the multi-source resolved path first.+ val channelIds = channels.map { it.id }+ val resolvedPrograms: Map<String, List<Program>> = runCatching {+ epgRepository.getResolvedProgramsForChannels(providerId, channelIds, windowStart, windowEnd)+ }.getOrElse { emptyMap() }- // 1. Try the multi-source resolved path first- val channelIds = channels.map { it.id }- val resolvedPrograms = runCatching {- epgRepository.getResolvedProgramsForChannels(providerId, channelIds, windowStart, windowEnd)+ // 2. For channels not covered by resolution, fall back to legacy provider-native query.+ val unresolvedChannels = channels.filter { channel ->+ val key = channel.guideLookupKey()+ key == null || resolvedPrograms[key].isNullOrEmpty()+ }+ val legacyPrograms: Map<String, List<Program>> = if (unresolvedChannels.isNotEmpty()) {+ val fallbackGuideKeys = unresolvedChannels.mapNotNull(Channel::guideLookupKey).distinct()+ runCatching {+ if (fallbackGuideKeys.isEmpty()) emptyMap()+ else epgRepository.getProgramsForChannelsSnapshot(providerId, fallbackGuideKeys, windowStart, windowEnd)}.getOrElse { emptyMap() }-- // 2. For channels not covered by resolution, fall back to legacy provider-native query- val unresolvedChannels = channels.filter { channel ->- val key = channel.guideLookupKey()- key == null || resolvedPrograms[key].isNullOrEmpty()- }- val legacyPrograms = if (unresolvedChannels.isNotEmpty()) {- val xmltvKeys = unresolvedChannels.mapNotNull {- it.epgChannelId?.trim()?.takeIf(String::isNotEmpty)- }.distinct()- runCatching {- if (xmltvKeys.isEmpty()) emptyMap()- else epgRepository.getProgramsForChannelsSnapshot(providerId, xmltvKeys, windowStart, windowEnd)- }.getOrElse { emptyMap() }- } else {- emptyMap()- }-- val programsByChannel = resolvedPrograms + legacyPrograms-- GuideProgramsResult(- programsByChannel = programsByChannel,- failedCount = countMissingGuideEntries(channels, programsByChannel)- )+ } else {+ emptyMap()}++ val programsByChannel = resolvedPrograms + legacyPrograms+ return GuideProgramsResult(+ programsByChannel = programsByChannel,+ failedCount = countMissingGuideEntries(channels, programsByChannel)+ )}private suspend fun loadCombinedGuidePrograms(@@ -1630,7 +1639,9 @@ class EpgViewModel @Inject constructor(GuideChannelMode.ANCHORED -> programs.any { program ->baseSnapshot.guideAnchorTime in program.startTime until program.endTime}- GuideChannelMode.ARCHIVE_READY -> channel.catchUpSupported || programs.any { it.hasArchive }+ GuideChannelMode.ARCHIVE_READY -> programs.any { program ->+ channel.isArchivePlayable(program, baseSnapshot.guideAnchorTime)+ }}matchesScheduled && matchesMode}@@ -1656,23 +1667,91 @@ class EpgViewModel @Inject constructor(baseSnapshot: GuideBaseSnapshot,searchQuery: String): Pair<List<Channel>, Map<String, List<Program>>> {- val matchedProgramsByChannel = baseSnapshot.baseProgramsByChannel- .mapValues { (_, programs) ->- programs.filter { program ->- program.title.contains(searchQuery, ignoreCase = true) ||- program.description.contains(searchQuery, ignoreCase = true)+ val scopedChannels = loadGuideSearchScopeChannels(baseSnapshot)+ val scopedChannelsByLookup = scopedChannels.mapNotNull { channel ->+ channel.guideLookupKey()?.let { lookupKey -> lookupKey to channel }+ }.toMap()++ val metadataMatchedLookupKeys = scopedChannels.filter { channel ->+ channel.matchesGuideMetadataSearch(searchQuery)+ }.mapNotNull(Channel::guideLookupKey).toSet()++ val repositoryMatchedPrograms = epgRepository.searchPrograms(+ providerId = baseSnapshot.providerId,+ query = searchQuery,+ startTime = baseSnapshot.guideWindowStart,+ endTime = baseSnapshot.guideWindowEnd,+ categoryId = baseSnapshot.selectedCategoryId.takeIf { it >= 0L }+ ).first().groupBy { it.channelId }++ val repositoryMatchedLookupKeys = repositoryMatchedPrograms.keys+ val matchedLookupKeys = buildList {+ scopedChannels.forEach { channel ->+ val lookupKey = channel.guideLookupKey() ?: return@forEach+ if (lookupKey in metadataMatchedLookupKeys || lookupKey in repositoryMatchedLookupKeys) {+ add(lookupKey)}}- .filterValues { it.isNotEmpty() }-- val matchedChannels = baseSnapshot.visibleChannels.filter { channel ->- channel.name.contains(searchQuery, ignoreCase = true) ||- channel.categoryName?.contains(searchQuery, ignoreCase = true) == true ||- channel.guideLookupKey()?.let(matchedProgramsByChannel::containsKey) == true}.take(MAX_CHANNELS)- val matchedChannelKeys = matchedChannels.mapNotNull(Channel::guideLookupKey).toSet()- return matchedChannels to matchedProgramsByChannel.filterKeys { it in matchedChannelKeys }+ val missingMetadataLookupKeys = matchedLookupKeys.filter { lookupKey ->+ lookupKey in metadataMatchedLookupKeys && lookupKey !in baseSnapshot.baseProgramsByChannel+ }+ val missingMetadataPrograms = if (missingMetadataLookupKeys.isEmpty()) {+ emptyMap()+ } else {+ epgRepository.getProgramsForChannelsSnapshot(+ providerId = baseSnapshot.providerId,+ channelIds = missingMetadataLookupKeys,+ startTime = baseSnapshot.guideWindowStart,+ endTime = baseSnapshot.guideWindowEnd+ )+ }++ val matchedChannels = matchedLookupKeys.mapNotNull(scopedChannelsByLookup::get)+ val matchedPrograms = matchedLookupKeys.associateWith { lookupKey ->+ if (lookupKey in metadataMatchedLookupKeys) {+ baseSnapshot.baseProgramsByChannel[lookupKey]+ ?: missingMetadataPrograms[lookupKey]+ ?: emptyList()+ } else {+ repositoryMatchedPrograms[lookupKey].orEmpty()+ }+ }+ return matchedChannels to matchedPrograms+ }++ private suspend fun loadGuideSearchScopeChannels(baseSnapshot: GuideBaseSnapshot): List<Channel> {+ val rawChannels = when {+ baseSnapshot.showFavoritesOnly || baseSnapshot.selectedCategoryId < 0L -> baseSnapshot.allChannels+ baseSnapshot.selectedCategoryId == ChannelRepository.ALL_CHANNELS_ID ->+ channelRepository.getChannels(baseSnapshot.providerId).first()+ else -> channelRepository.getChannelsByCategory(baseSnapshot.providerId, baseSnapshot.selectedCategoryId).first()+ }+ if (baseSnapshot.selectedCategoryId != ChannelRepository.ALL_CHANNELS_ID) {+ return rawChannels.filterNot { channel ->+ channel.categoryId != null && channel.categoryId in baseSnapshot.hiddenCategoryIds+ }+ }++ val accessibleCategoryIds = baseSnapshot.categories.filter { category ->+ isGuideCategoryAccessible(+ category = category,+ parentalControlLevel = baseSnapshot.parentalControlLevel,+ unlockedCategoryIds = emptySet()+ )+ }.map(Category::id).toSet()++ return rawChannels.filterNot { channel ->+ channel.categoryId != null && channel.categoryId in baseSnapshot.hiddenCategoryIds+ }.filter { channel ->+ channel.categoryId == null || channel.categoryId in accessibleCategoryIds+ }+ }++ private fun Channel.matchesGuideMetadataSearch(searchQuery: String): Boolean {+ return name.contains(searchQuery, ignoreCase = true) ||+ categoryName?.contains(searchQuery, ignoreCase = true) == true}private fun resolveGuideCategorySelection(diff --git a/app/src/main/java/com/streamvault/app/ui/screens/epg/GuideDateTime.kt b/app/src/main/java/com/streamvault/app/ui/screens/epg/GuideDateTime.ktnew file mode 100644index 00000000..ab75e4d5--- /dev/null+++ b/app/src/main/java/com/streamvault/app/ui/screens/epg/GuideDateTime.kt@@ -0,0 +1,57 @@+package com.streamvault.app.ui.screens.epg++import java.time.Instant+import java.time.LocalDate+import java.time.ZoneId++internal fun startOfGuideDay(timestamp: Long, zoneId: ZoneId = ZoneId.systemDefault()): Long {+ val localDate = Instant.ofEpochMilli(timestamp).atZone(zoneId).toLocalDate()+ return localDate.atStartOfDay(zoneId).toInstant().toEpochMilli()+}++internal fun shiftGuideDayStart(+ dayStartMillis: Long,+ days: Long,+ zoneId: ZoneId = ZoneId.systemDefault()+): Long {+ val localDate = Instant.ofEpochMilli(dayStartMillis).atZone(zoneId).toLocalDate().plusDays(days)+ return localDate.atStartOfDay(zoneId).toInstant().toEpochMilli()+}++internal fun shiftGuideAnchorByDays(+ anchorTimeMillis: Long,+ days: Long,+ zoneId: ZoneId = ZoneId.systemDefault()+): Long = Instant.ofEpochMilli(anchorTimeMillis)+ .atZone(zoneId)+ .plusDays(days)+ .toInstant()+ .toEpochMilli()++internal fun guidePrimeTimeAnchor(+ anchorTimeMillis: Long,+ primeTimeHour: Int,+ zoneId: ZoneId = ZoneId.systemDefault()+): Long {+ val localDate = Instant.ofEpochMilli(anchorTimeMillis).atZone(zoneId).toLocalDate()+ return localDate.atTime(primeTimeHour, 0).atZone(zoneId).toInstant().toEpochMilli()+}++internal fun jumpGuideAnchorToDay(+ anchorTimeMillis: Long,+ dayStartMillis: Long,+ zoneId: ZoneId = ZoneId.systemDefault()+): Long {+ val anchorDateTime = Instant.ofEpochMilli(anchorTimeMillis).atZone(zoneId)+ val targetDate = Instant.ofEpochMilli(dayStartMillis).atZone(zoneId).toLocalDate()+ return targetDate.atTime(anchorDateTime.toLocalTime()).atZone(zoneId).toInstant().toEpochMilli()+}++internal fun dayRelativeOffset(+ dayStartMillis: Long,+ today: LocalDate,+ zoneId: ZoneId = ZoneId.systemDefault()+): Long {+ val day = Instant.ofEpochMilli(dayStartMillis).atZone(zoneId).toLocalDate()+ return day.toEpochDay() - today.toEpochDay()+}\ No newline at end of filediff --git a/app/src/main/java/com/streamvault/app/ui/screens/favorites/FavoritesScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/favorites/FavoritesScreen.ktindex d8928b68..16583aa2 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/favorites/FavoritesScreen.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/favorites/FavoritesScreen.kt@@ -270,6 +270,9 @@ fun FavoritesScreen(}}}+ val hasVisibleContent = remember(filteredSections, visibleContinueWatching, visibleRecentLive) {+ filteredSections.isNotEmpty() || visibleContinueWatching.isNotEmpty() || visibleRecentLive.isNotEmpty()+ }val sectionBaseIndex = 5 +(if (visibleContinueWatching.isNotEmpty()) 1 else 0) +(if (visibleRecentLive.isNotEmpty()) 1 else 0)@@ -378,7 +381,7 @@ fun FavoritesScreen(}}- uiState.sections.isEmpty() -> {+ !hasVisibleContent -> {Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {Column(horizontalAlignment = Alignment.CenterHorizontally) {Text(diff --git a/app/src/main/java/com/streamvault/app/ui/screens/favorites/FavoritesViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/favorites/FavoritesViewModel.ktindex 4345ea1f..46a3ae57 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@@ -5,9 +5,12 @@ import androidx.lifecycle.ViewModelimport androidx.lifecycle.viewModelScopeimport com.streamvault.app.Rimport com.streamvault.app.ui.model.associateByAnyRawId+import com.streamvault.domain.model.Channelimport com.streamvault.domain.model.ContentTypeimport com.streamvault.domain.model.Favoriteimport com.streamvault.domain.model.PlaybackHistory+import com.streamvault.domain.model.Provider+import com.streamvault.domain.model.Resultimport com.streamvault.domain.model.VirtualCategoryIdsimport com.streamvault.domain.model.VirtualGroupimport com.streamvault.domain.repository.ChannelRepository@@ -16,6 +19,7 @@ import com.streamvault.domain.repository.MovieRepositoryimport com.streamvault.domain.repository.PlaybackHistoryRepositoryimport com.streamvault.domain.repository.ProviderRepositoryimport com.streamvault.domain.repository.SeriesRepository+import com.streamvault.domain.usecase.ContinueWatchingResultimport com.streamvault.domain.usecase.ContinueWatchingScopeimport com.streamvault.domain.usecase.GetContinueWatchingimport com.streamvault.data.preferences.PreferencesRepository@@ -27,6 +31,7 @@ import kotlinx.coroutines.flow.MutableStateFlowimport kotlinx.coroutines.flow.StateFlowimport kotlinx.coroutines.flow.asStateFlowimport kotlinx.coroutines.flow.combine+import kotlinx.coroutines.flow.distinctUntilChangedimport kotlinx.coroutines.flow.flatMapLatestimport kotlinx.coroutines.flow.flowOfimport kotlinx.coroutines.flow.first@@ -167,7 +172,7 @@ class FavoritesViewModel @Inject constructor(val liveGroupManagementFlow = providerIdsFlow.flatMapLatest { providerIds ->combine(favoriteRepository.getGroups(providerIds, ContentType.LIVE),- favoriteRepository.getFavorites(providerIds, ContentType.LIVE).map(::countFavoritesByGroup),+ favoriteRepository.getGroupFavoriteCounts(providerIds, ContentType.LIVE),preferencesRepository.promotedLiveGroupIds) { liveGroups, liveCounts, promotedLiveGroupIds ->liveGroups.map { group ->@@ -183,7 +188,7 @@ class FavoritesViewModel @Inject constructor(val movieGroupManagementFlow = providerIdsFlow.flatMapLatest { providerIds ->combine(favoriteRepository.getGroups(providerIds, ContentType.MOVIE),- favoriteRepository.getFavorites(providerIds, ContentType.MOVIE).map(::countFavoritesByGroup)+ favoriteRepository.getGroupFavoriteCounts(providerIds, ContentType.MOVIE)) { movieGroups, movieCounts ->movieGroups.map { group ->SavedGroupManagementUiModel(@@ -198,7 +203,7 @@ class FavoritesViewModel @Inject constructor(val seriesGroupManagementFlow = providerIdsFlow.flatMapLatest { providerIds ->combine(favoriteRepository.getGroups(providerIds, ContentType.SERIES),- favoriteRepository.getFavorites(providerIds, ContentType.SERIES).map(::countFavoritesByGroup)+ favoriteRepository.getGroupFavoriteCounts(providerIds, ContentType.SERIES)) { seriesGroups, seriesCounts ->seriesGroups.map { group ->SavedGroupManagementUiModel(@@ -225,6 +230,21 @@ class FavoritesViewModel @Inject constructor()}+ val activeProviderFlow = providerRepository.getActiveProvider()+ val selectedProviderScopeFlow = uiState+ .map { state -> state.selectedProviderScope }+ .distinctUntilChanged()+ val historyProviderIdsFlow: Flow<Set<Long>> = combine(+ providerIdsFlow,+ activeProviderFlow,+ selectedProviderScopeFlow+ ) { providerIds: List<Long>, activeProvider: Provider?, selectedProviderScope: SavedLibraryProviderScope ->+ when (selectedProviderScope) {+ SavedLibraryProviderScope.CURRENT_PROVIDER -> activeProvider?.id?.let(::setOf).orEmpty()+ SavedLibraryProviderScope.ALL_PROVIDERS -> providerIds.toSet()+ }+ }+val groupedSectionsFlow = allGroupsFlow.flatMapLatest { groups ->if (groups.isEmpty()) {flowOf(emptyList())@@ -248,81 +268,10 @@ class FavoritesViewModel @Inject constructor(}}- val savedHistoryFlow = providerRepository.getActiveProvider().flatMapLatest { provider ->- if (provider == null) {- flowOf(SavedHistorySnapshot())- } else {- combine(- getContinueWatching(- providerId = provider.id,- limit = 8,- scope = ContinueWatchingScope.ALL_VOD,- requireResumePosition = true- ),- playbackHistoryRepository.getRecentlyWatchedByProvider(provider.id, limit = 18)- ) { continueWatching, history ->- continueWatching to history- }.flatMapLatest { (continueWatching, history) ->- val recentLiveHistory = history- .asSequence()- .filter { it.contentType == ContentType.LIVE }- .distinctBy { it.contentId }- .take(10)- .toList()-- val recentLiveIds = recentLiveHistory.map { it.contentId }- val recentLiveFlow = if (recentLiveIds.isEmpty()) {- flowOf(emptyList())- } else {- channelRepository.getChannelsByIds(recentLiveIds)- }-- recentLiveFlow.map { liveChannels ->- val liveById = liveChannels.associateByAnyRawId()- SavedHistorySnapshot(- continueWatching = continueWatching.map { entry ->- SavedHistoryUiModel(- history = entry,- title = entry.title,- subtitle = when (entry.contentType) {- ContentType.MOVIE -> appContext.getString(R.string.favorites_content_type_movie)- ContentType.SERIES -> appContext.getString(R.string.favorites_content_type_series)- ContentType.SERIES_EPISODE -> buildString {- val s = entry.seasonNumber- val e = entry.episodeNumber- if (s != null && e != null) {- append(appContext.getString(R.string.favorites_content_type_episode_format, s, e))- } else {- append(appContext.getString(R.string.favorites_content_type_episode))- entry.seasonNumber?.let { append(" S$it") }- entry.episodeNumber?.let { append("E$it") }- }- }- ContentType.LIVE -> appContext.getString(R.string.favorites_content_type_live)- },- providerId = entry.providerId- )- },- recentLive = recentLiveHistory.mapIndexedNotNull { index, entry ->- val channel = liveById[entry.contentId] ?: return@mapIndexedNotNull null- SavedHistoryUiModel(- history = entry,- title = channel.name,- subtitle = "Channel ${index + 1}",- providerId = channel.providerId,- categoryId = channel.categoryId,- epgChannelId = channel.epgChannelId,- launchIsVirtual = false- )- }- )- }- }- }+ val savedHistoryFlow: Flow<SavedHistorySnapshot> = historyProviderIdsFlow.flatMapLatest { providerIds: Set<Long> ->+ observeSavedHistory(providerIds)}- val activeProviderFlow = providerRepository.getActiveProvider()-viewModelScope.launch {combine(combine(globalSectionFlow, groupedSectionsFlow) { globalSection, groupedSections ->@@ -471,24 +420,26 @@ class FavoritesViewModel @Inject constructor(fun moveItemToGroup(item: FavoriteUiModel, targetGroupId: Long) {viewModelScope.launch {- favoriteRepository.addFavorite(- providerId = item.favorite.providerId,- contentId = item.favorite.contentId,- contentType = item.favorite.contentType,- groupId = targetGroupId- )- favoriteRepository.removeFavorite(+ when (val result = favoriteRepository.moveFavoriteToGroup(providerId = item.favorite.providerId,contentId = item.favorite.contentId,contentType = item.favorite.contentType,- groupId = item.favorite.groupId- )- _uiState.update {- it.copy(- itemDialogItem = null,- itemMoveTargets = emptyList(),- userMessage = "Moved ${item.title} to the selected group."- )+ fromGroupId = item.favorite.groupId,+ targetGroupId = targetGroupId+ )) {+ is Result.Success -> _uiState.update {+ it.copy(+ itemDialogItem = null,+ itemMoveTargets = emptyList(),+ userMessage = "Moved ${item.title} to the selected group."+ )+ }++ is Result.Error -> _uiState.update {+ it.copy(userMessage = "Unable to move ${item.title}: ${result.errorMessageOrNull() ?: "Unknown error"}")+ }++ Result.Loading -> Unit}}}@@ -557,33 +508,27 @@ class FavoritesViewModel @Inject constructor(fun mergeGroupInto(targetGroupId: Long) {val source = _uiState.value.mergeSourceGroup ?: returnviewModelScope.launch {- val items = favoriteRepository.getFavoritesByGroup(source.group.id).first()- items.forEach { favorite ->- favoriteRepository.addFavorite(- providerId = favorite.providerId,- contentId = favorite.contentId,- contentType = favorite.contentType,- groupId = targetGroupId- )- favoriteRepository.removeFavorite(- providerId = favorite.providerId,- contentId = favorite.contentId,- contentType = favorite.contentType,- groupId = source.group.id- )- }- favoriteRepository.deleteGroup(source.group.id)- if (source.group.contentType == ContentType.LIVE) {- val currentPromoted = preferencesRepository.promotedLiveGroupIds.first()- preferencesRepository.setPromotedLiveGroupIds(currentPromoted - source.group.id)- }- _uiState.update {- it.copy(- managedGroupDialog = null,- mergeSourceGroup = null,- mergeTargetCandidates = emptyList(),- userMessage = appContext.getString(R.string.favorites_merged_group, source.group.name)- )+ when (val result = favoriteRepository.mergeGroupInto(source.group.id, targetGroupId)) {+ is Result.Success -> {+ if (source.group.contentType == ContentType.LIVE) {+ val currentPromoted = preferencesRepository.promotedLiveGroupIds.first()+ preferencesRepository.setPromotedLiveGroupIds(currentPromoted - source.group.id)+ }+ _uiState.update {+ it.copy(+ managedGroupDialog = null,+ mergeSourceGroup = null,+ mergeTargetCandidates = emptyList(),+ userMessage = appContext.getString(R.string.favorites_merged_group, source.group.name)+ )+ }+ }++ is Result.Error -> _uiState.update {+ it.copy(userMessage = "Unable to merge ${source.group.name}: ${result.errorMessageOrNull() ?: "Unknown error"}")+ }++ Result.Loading -> Unit}}}@@ -621,8 +566,13 @@ class FavoritesViewModel @Inject constructor(val section = state.sections.firstOrNull { it.key == sectionKey } ?: returnviewModelScope.launch {- favoriteRepository.reorderFavorites(section.items.map { it.favorite })- exitReorderMode()+ when (val result = favoriteRepository.reorderFavorites(section.items.map { it.favorite })) {+ is Result.Success -> exitReorderMode()+ is Result.Error -> _uiState.update {+ it.copy(userMessage = "Unable to save reorder: ${result.errorMessageOrNull() ?: "Unknown error"}")+ }+ Result.Loading -> Unit+ }}}@@ -691,6 +641,91 @@ class FavoritesViewModel @Inject constructor(}}+ private fun observeSavedHistory(providerIds: Set<Long>): Flow<SavedHistorySnapshot> {+ if (providerIds.isEmpty()) {+ return flowOf(SavedHistorySnapshot())+ }++ val recentHistoryLimit = 18+ val historyFlow: Flow<List<PlaybackHistory>> = if (providerIds.size == 1) {+ playbackHistoryRepository.getRecentlyWatchedByProvider(providerIds.first(), limit = recentHistoryLimit)+ } else {+ playbackHistoryRepository.getRecentlyWatched(limit = recentHistoryLimit)+ .map { history -> history.filter { entry -> entry.providerId in providerIds } }+ }++ return combine(+ getContinueWatching(+ providerIds,+ limit = 8,+ scope = ContinueWatchingScope.ALL_VOD,+ requireResumePosition = true+ ),+ historyFlow+ ) { continueWatchingResult, history ->+ val continueWatching = when (continueWatchingResult) {+ is ContinueWatchingResult.Items -> continueWatchingResult.items+ ContinueWatchingResult.Degraded -> emptyList()+ }+ continueWatching to history+ }.flatMapLatest { (continueWatching, history) ->+ val recentLiveHistory = history+ .asSequence()+ .filter { it.contentType == ContentType.LIVE }+ .distinctBy { it.providerId to it.contentId }+ .take(10)+ .toList()++ val recentLiveIds = recentLiveHistory.map { it.contentId }.distinct()+ val recentLiveFlow: Flow<List<Channel>> = if (recentLiveIds.isEmpty()) {+ flowOf(emptyList<Channel>())+ } else {+ channelRepository.getChannelsByIds(recentLiveIds)+ }++ recentLiveFlow.map { liveChannels ->+ val liveByProviderAndId = liveChannels.associateByProviderAndAnyRawId()+ SavedHistorySnapshot(+ continueWatching = continueWatching.map { entry ->+ SavedHistoryUiModel(+ history = entry,+ title = entry.title,+ subtitle = when (entry.contentType) {+ ContentType.MOVIE -> appContext.getString(R.string.favorites_content_type_movie)+ ContentType.SERIES -> appContext.getString(R.string.favorites_content_type_series)+ ContentType.SERIES_EPISODE -> buildString {+ val s = entry.seasonNumber+ val e = entry.episodeNumber+ if (s != null && e != null) {+ append(appContext.getString(R.string.favorites_content_type_episode_format, s, e))+ } else {+ append(appContext.getString(R.string.favorites_content_type_episode))+ entry.seasonNumber?.let { append(" S$it") }+ entry.episodeNumber?.let { append("E$it") }+ }+ }+ ContentType.LIVE -> appContext.getString(R.string.favorites_content_type_live)+ },+ providerId = entry.providerId+ )+ },+ recentLive = recentLiveHistory.mapIndexedNotNull { index, entry ->+ val channel = liveByProviderAndId[entry.providerId to entry.contentId] ?: return@mapIndexedNotNull null+ SavedHistoryUiModel(+ history = entry,+ title = channel.name,+ subtitle = "Channel ${index + 1}",+ providerId = channel.providerId,+ categoryId = channel.categoryId,+ epgChannelId = channel.epgChannelId,+ launchIsVirtual = false+ )+ }+ )+ }+ }+ }+private fun FavoritesUiState.applyReorderPreview(incomingSections: List<FavoriteSectionUiModel>): List<FavoriteSectionUiModel> {@@ -717,12 +752,14 @@ class FavoritesViewModel @Inject constructor(private fun sectionKeyForGroup(groupId: Long): String = "group:$groupId"- private fun countFavoritesByGroup(favorites: List<Favorite>): Map<Long, Int> =- favorites- .asSequence()- .mapNotNull(Favorite::groupId)- .groupingBy { it }- .eachCount()+ private fun List<Channel>.associateByProviderAndAnyRawId(): Map<Pair<Long, Long>, Channel> = buildMap {+ [email protected] { channel ->+ channel.allVariantRawIds().forEach { rawId ->+ putIfAbsent(channel.providerId to rawId, channel)+ }+ }+ }+}}diff --git a/app/src/main/java/com/streamvault/app/ui/screens/home/HomeScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/home/HomeScreen.ktindex dd075f4a..2c3b18e8 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@@ -499,7 +499,7 @@ fun HomeScreen(val canRestoreChannel = lastFocusedChannelId != null &&uiState.filteredChannels.any { it.id == lastFocusedChannelId }val canRestoreCategory = lastFocusedCategoryId != null &&- uiState.categories.any { it.id == lastFocusedCategoryId }+ visibleCategories.any { it.id == lastFocusedCategoryId }val restoreTarget = runCatching {FocusRestoreTarget.valueOf(preferredRestoreTarget)}.getOrDefault(FocusRestoreTarget.CHANNEL)@@ -509,7 +509,7 @@ fun HomeScreen(canRestoreChannel -> FocusRestoreTarget.CHANNELcanRestoreCategory -> FocusRestoreTarget.CATEGORYuiState.filteredChannels.isNotEmpty() -> FocusRestoreTarget.CHANNEL- uiState.categories.isNotEmpty() -> FocusRestoreTarget.CATEGORY+ visibleCategories.isNotEmpty() -> FocusRestoreTarget.CATEGORYelse -> null}if (pendingRestoreTarget != null) {@@ -531,12 +531,12 @@ fun HomeScreen(if (fallbackChannelId != null) {requestChannelFocus(fallbackChannelId)} else {- val fallbackCategoryId = uiState.categories.firstOrNull()?.id+ val fallbackCategoryId = (unlockedVisibleCategories.firstOrNull() ?: visibleCategories.firstOrNull())?.idrequestCategoryFocus(fallbackCategoryId)}}FocusRestoreTarget.CATEGORY -> {- val fallbackCategoryId = uiState.categories.firstOrNull()?.id+ val fallbackCategoryId = (unlockedVisibleCategories.firstOrNull() ?: visibleCategories.firstOrNull())?.idrequestCategoryFocus(fallbackCategoryId)}}@@ -554,14 +554,14 @@ fun HomeScreen(val canRestoreChannel = lastFocusedChannelId != null &&uiState.filteredChannels.any { it.id == lastFocusedChannelId }val canRestoreCategory = lastFocusedCategoryId != null &&- uiState.categories.any { it.id == lastFocusedCategoryId }+ visibleCategories.any { it.id == lastFocusedCategoryId }pendingRestoreTarget = when {restoreTarget == FocusRestoreTarget.CATEGORY && canRestoreCategory -> FocusRestoreTarget.CATEGORYcanRestoreChannel -> FocusRestoreTarget.CHANNELcanRestoreCategory -> FocusRestoreTarget.CATEGORYuiState.filteredChannels.isNotEmpty() -> FocusRestoreTarget.CHANNEL- uiState.categories.isNotEmpty() -> FocusRestoreTarget.CATEGORY+ visibleCategories.isNotEmpty() -> FocusRestoreTarget.CATEGORYelse -> null}if (pendingRestoreTarget != null) {diff --git a/app/src/main/java/com/streamvault/app/ui/screens/home/HomeScreenDialogs.kt b/app/src/main/java/com/streamvault/app/ui/screens/home/HomeScreenDialogs.ktindex 5dc2850c..de271d64 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/home/HomeScreenDialogs.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/home/HomeScreenDialogs.kt@@ -23,6 +23,7 @@ import com.streamvault.app.ui.components.dialogs.PremiumDialogFooterButtonimport com.streamvault.app.ui.components.dialogs.RenameGroupDialogimport com.streamvault.app.ui.screens.multiview.MultiViewPlannerDialogimport com.streamvault.app.ui.screens.multiview.MultiViewViewModel+import com.streamvault.domain.model.ActiveLiveSourceimport com.streamvault.domain.model.Categoryimport com.streamvault.domain.model.Channelimport com.streamvault.domain.model.Provider@@ -99,7 +100,8 @@ internal fun HomeDialogsHost(pendingUnlockChannel?.let { channel ->viewModel.clearPreview()- onChannelClick(channel, uiState.selectedCategory, resolveProviderForChannel(channel), null, null)+ val combinedProfileId = (uiState.activeLiveSource as? ActiveLiveSource.CombinedM3uSource)?.profileId+ onChannelClick(channel, uiState.selectedCategory, resolveProviderForChannel(channel), combinedProfileId, uiState.selectedCombinedSourceProviderId)onPendingUnlockChannelChange(null)}@@ -241,7 +243,11 @@ internal fun HomeDialogsHost(},onAddToGroup = { group -> viewModel.addToGroup(channel, group) },onRemoveFromGroup = { group -> viewModel.removeFromGroup(channel, group) },- onCreateGroup = { name -> viewModel.createCustomGroup(name) },+ onCreateGroup = if (+ uiState.isCombinedLiveSource &&+ uiState.selectedCombinedSourceProviderId == null &&+ uiState.currentCombinedProfileMembers.count { it.enabled } > 1+ ) null else { name -> viewModel.createCustomGroup(name) },isQueuedForSplitScreen = multiViewViewModel.isQueued(channel.id),onOpenSplitScreenPlanner = { onPendingSplitPlannerChannelChange(channel) },onRemoveFromRecent = if (uiState.selectedCategory?.id == VirtualCategoryIds.RECENT) {diff --git a/app/src/main/java/com/streamvault/app/ui/screens/home/HomeViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/home/HomeViewModel.ktindex 6d55b336..7b3eeced 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@@ -153,7 +153,10 @@ class HomeViewModel @Inject constructor(selectedCombinedSourceProviderId = null)}+ recentChannelsJob?.cancel()+ recentChannelsJob = null_localChannels.value = emptyList()+ observeCombinedRecentChannels(currentCombinedProviderIds())loadCombinedCategoriesAndChannels(activeSource.profileId)}is ActiveLiveSource.ProviderSource -> {@@ -187,6 +190,8 @@ class HomeViewModel @Inject constructor(preferencesRepository.setLastActiveProviderId(provider.id)}null -> {+ recentChannelsJob?.cancel()+ recentChannelsJob = nullcombinedCategoriesById = emptyMap()_localChannels.value = emptyList()_uiState.update {@@ -294,10 +299,22 @@ class HomeViewModel @Inject constructor(}viewModelScope.launch {- providerRepository.getActiveProvider()- .filterNotNull()- .flatMapLatest { provider ->- parentalControlManager.unlockedCategoriesForProvider(provider.id)+ _uiState+ .map { state ->+ if (state.isCombinedLiveSource)+ state.currentCombinedProfileMembers.filter { it.enabled }.map { it.providerId }+ else+ state.provider?.id?.let(::listOf).orEmpty()+ }+ .distinctUntilChanged()+ .flatMapLatest { providerIds ->+ when (providerIds.size) {+ 0 -> flowOf(emptySet())+ 1 -> parentalControlManager.unlockedCategoriesForProvider(providerIds.first())+ else -> combine(+ providerIds.map { id -> parentalControlManager.unlockedCategoriesForProvider(id) }+ ) { arrays -> arrays.toList().flatten().toSet() }+ }}.collectLatest { unlockedIds ->_uiState.update { it.copy(unlockedCategoryIds = unlockedIds) }@@ -548,7 +565,7 @@ class HomeViewModel @Inject constructor(name = "Recent",type = ContentType.LIVE,isVirtual = true,- count = 0+ count = _uiState.value.recentChannels.size)val allChannelsCategory = Category(id = ChannelRepository.ALL_CHANNELS_ID,@@ -826,6 +843,18 @@ class HomeViewModel @Inject constructor(})}+ if (query.isNotBlank()) {+ val state = _uiState.value+ val selectedId = state.selectedCategory?.id+ if (selectedId != null) {+ val visibleCategoryIds = state.categories+ .filter { it.name.contains(query, ignoreCase = true) }+ .map { it.id }.toSet()+ if (selectedId !in visibleCategoryIds) {+ clearVisibleChannelsForFilteredCategories()+ }+ }+ }}fun applySavedCategoryFilter(filter: String) {@@ -837,6 +866,19 @@ class HomeViewModel @Inject constructor(activeCategoryFilter = if (shouldClear) null else filter)}+ val state = _uiState.value+ val query = state.categorySearchQuery+ if (query.isNotBlank()) {+ val selectedId = state.selectedCategory?.id+ if (selectedId != null) {+ val visibleCategoryIds = state.categories+ .filter { it.name.contains(query, ignoreCase = true) }+ .map { it.id }.toSet()+ if (selectedId !in visibleCategoryIds) {+ clearVisibleChannelsForFilteredCategories()+ }+ }+ }}fun clearCategorySearchQuery() {@@ -998,7 +1040,6 @@ class HomeViewModel @Inject constructor(if (_uiState.value.previewChannelId != channel.id) return falseif (!livePreviewHandoffManager.beginFullscreenHandoff(channel.id, engine)) return false- engine.clearRenderBinding()previewSessionVersion++previewPlaybackJob?.cancel()previewErrorJob?.cancel()@@ -1190,7 +1231,7 @@ class HomeViewModel @Inject constructor(viewModelScope.launch {val providerId = resolveLiveWriteProviderId()if (providerId == null) {- _uiState.update { it.copy(userMessage = appContext.getString(R.string.home_error_load_failed)) }+ _uiState.update { it.copy(userMessage = appContext.getString(R.string.home_group_requires_provider_scope)) }return@launch}favoriteRepository.createGroup(providerId, trimmed, contentType = ContentType.LIVE)@@ -1198,6 +1239,24 @@ class HomeViewModel @Inject constructor(}}+ private fun observeCombinedRecentChannels(providerIds: List<Long>) {+ recentChannelsJob?.cancel()+ recentChannelsJob = viewModelScope.launch {+ combine(+ observeRecentLiveIds(providerIds, limit = 12)+ .flatMapLatest(::loadChannelsByOrderedIds),+ preferencesRepository.parentalControlLevel+ ) { channels, level ->+ AdultContentVisibilityPolicy.filterForAggregatedSurface(+ channels, level+ ) { isAdult || isUserProtected }+ }.collect { visible ->+ _uiState.update { it.copy(recentChannels = visible) }+ updateRecentCategoryCount(visible.size)+ }+ }+ }+private fun observeRecentChannels(providerId: Long) {recentChannelsJob?.cancel()recentChannelsJob = viewModelScope.launch {@@ -1407,6 +1466,7 @@ class HomeViewModel @Inject constructor(suspend fun unlockCategoryWithPin(category: Category, pin: String): Result<Unit> {val providerId = _uiState.value.provider?.id+ ?: combinedCategoriesById[category.id]?.bindings?.firstOrNull()?.providerId?: return Result.error("Locked category context is unavailable.")val result = unlockParentalCategory(UnlockParentalCategoryCommand(diff --git a/app/src/main/java/com/streamvault/app/ui/screens/movies/MovieDetailScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/movies/MovieDetailScreen.ktindex 62e8181f..fd36fd10 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/movies/MovieDetailScreen.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/movies/MovieDetailScreen.kt@@ -17,7 +17,12 @@ import androidx.compose.foundation.layout.heightimport androidx.compose.foundation.layout.paddingimport androidx.compose.foundation.layout.widthimport androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.LazyRow+import androidx.compose.foundation.lazy.itemsimport androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.material.icons.Icons+import androidx.compose.material.icons.filled.Favorite+import androidx.compose.material.icons.outlined.FavoriteBorderimport androidx.compose.runtime.Composableimport androidx.compose.runtime.LaunchedEffectimport androidx.compose.runtime.getValue@@ -39,6 +44,7 @@ import androidx.compose.runtime.rememberimport androidx.tv.material3.Borderimport androidx.tv.material3.Buttonimport androidx.tv.material3.ButtonDefaults+import androidx.tv.material3.Iconimport androidx.tv.material3.MaterialThemeimport androidx.tv.material3.Textimport coil3.compose.AsyncImage@@ -100,7 +106,10 @@ fun MovieDetailScreen(resumePositionMs = uiState.resumePositionMs,externalRatings = uiState.externalRatings,isLoadingExternalRatings = uiState.isLoadingExternalRatings,+ relatedContent = uiState.relatedContent,onPlay = { onPlay(movie) },+ onToggleFavorite = viewModel::toggleFavorite,+ onRelatedClick = onPlay,onBack = onBack)}@@ -114,7 +123,10 @@ private fun MovieDetailContent(resumePositionMs: Long,externalRatings: ExternalRatings,isLoadingExternalRatings: Boolean,+ relatedContent: List<Movie>,onPlay: () -> Unit,+ onToggleFavorite: () -> Unit,+ onRelatedClick: (Movie) -> Unit,onBack: () -> Unit) {val context = LocalContext.current@@ -198,6 +210,7 @@ private fun MovieDetailContent(externalRatings = externalRatings,isLoadingExternalRatings = isLoadingExternalRatings,onPlay = onPlay,+ onToggleFavorite = onToggleFavorite,playButtonFocusRequester = playButtonFocusRequester,onPlayTrailer = {resolveTrailerUrl(movie.youtubeTrailer)?.let { trailerUrl ->@@ -221,6 +234,7 @@ private fun MovieDetailContent(externalRatings = externalRatings,isLoadingExternalRatings = isLoadingExternalRatings,onPlay = onPlay,+ onToggleFavorite = onToggleFavorite,playButtonFocusRequester = playButtonFocusRequester,onPlayTrailer = {resolveTrailerUrl(movie.youtubeTrailer)?.let { trailerUrl ->@@ -234,6 +248,52 @@ private fun MovieDetailContent(}}}++ if (relatedContent.isNotEmpty()) {+ item {+ Text(+ text = stringResource(R.string.movie_detail_related),+ style = MaterialTheme.typography.titleMedium,+ color = AppColors.TextPrimary+ )+ }+ item {+ LazyRow(+ horizontalArrangement = Arrangement.spacedBy(12.dp)+ ) {+ items(relatedContent, key = { it.id }) { related ->+ TvClickableSurface(+ onClick = { onRelatedClick(related) },+ modifier = Modifier.width(120.dp)+ ) {+ Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {+ Box(+ modifier = Modifier+ .fillMaxWidth()+ .aspectRatio(2f / 3f)+ .clip(RoundedCornerShape(12.dp))+ .background(AppColors.SurfaceElevated)+ ) {+ AsyncImage(+ model = rememberCrossfadeImageModel(related.posterUrl ?: related.backdropUrl),+ contentDescription = related.name,+ modifier = Modifier.fillMaxSize(),+ contentScale = ContentScale.Crop+ )+ }+ Text(+ text = related.name,+ style = MaterialTheme.typography.labelMedium,+ color = AppColors.TextPrimary,+ maxLines = 2,+ overflow = TextOverflow.Ellipsis+ )+ }+ }+ }+ }+ }+ }}}}@@ -267,6 +327,7 @@ private fun MovieDetailHeroText(externalRatings: ExternalRatings,isLoadingExternalRatings: Boolean,onPlay: () -> Unit,+ onToggleFavorite: () -> Unit,playButtonFocusRequester: FocusRequester,onPlayTrailer: () -> Unit,modifier: Modifier = Modifier@@ -341,6 +402,20 @@ private fun MovieDetailHeroText(Text(stringResource(R.string.movie_detail_trailer))}}+ TvIconButton(+ onClick = onToggleFavorite,+ colors = ButtonDefaults.colors(+ containerColor = if (movie.isFavorite) AppColors.Brand else AppColors.SurfaceEmphasis,+ contentColor = if (movie.isFavorite) Color.White else AppColors.TextSecondary+ )+ ) {+ Icon(+ imageVector = if (movie.isFavorite) Icons.Filled.Favorite else Icons.Outlined.FavoriteBorder,+ contentDescription = stringResource(+ if (movie.isFavorite) R.string.favorites_remove else R.string.favorites_add+ )+ )+ }}Text(diff --git a/app/src/main/java/com/streamvault/app/ui/screens/movies/MovieDetailViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/movies/MovieDetailViewModel.ktindex c71f3fce..2d55f882 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/movies/MovieDetailViewModel.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/movies/MovieDetailViewModel.kt@@ -4,12 +4,13 @@ import androidx.lifecycle.SavedStateHandleimport androidx.lifecycle.ViewModelimport androidx.lifecycle.viewModelScopeimport com.streamvault.app.util.isPlaybackComplete+import com.streamvault.domain.model.ContentTypeimport com.streamvault.domain.model.ExternalRatingsimport com.streamvault.domain.model.ExternalRatingsLookupimport com.streamvault.domain.model.Movie-import com.streamvault.domain.model.ContentTypeimport com.streamvault.domain.model.Resultimport com.streamvault.domain.repository.ExternalRatingsRepository+import com.streamvault.domain.repository.FavoriteRepositoryimport com.streamvault.domain.repository.MovieRepositoryimport com.streamvault.domain.repository.PlaybackHistoryRepositoryimport com.streamvault.domain.repository.ProviderRepository@@ -28,7 +29,8 @@ class MovieDetailViewModel @Inject constructor(private val movieRepository: MovieRepository,private val providerRepository: ProviderRepository,private val playbackHistoryRepository: PlaybackHistoryRepository,- private val externalRatingsRepository: ExternalRatingsRepository+ private val externalRatingsRepository: ExternalRatingsRepository,+ private val favoriteRepository: FavoriteRepository) : ViewModel() {private val movieId: Long = checkNotNull(@@ -48,19 +50,25 @@ class MovieDetailViewModel @Inject constructor(try {_uiState.update { it.copy(isLoading = true) }- val provider = providerRepository.getActiveProvider().first()- if (provider == null) {- _uiState.update { it.copy(isLoading = false, error = "No active provider") }- return@launch- }+ // Derive the provider from the movie's own row so detail/history remain+ // correct even when the globally active provider differs from the opened movie.+ val movieRow = movieRepository.getMovie(movieId)+ val effectiveProviderId = movieRow?.providerId?.takeIf { it > 0L }+ ?: providerRepository.getActiveProvider().first()?.id+ ?: run {+ _uiState.update { it.copy(isLoading = false, error = "No active provider") }+ return@launch+ }val playbackHistory = playbackHistoryRepository.getPlaybackHistory(contentId = movieId,contentType = ContentType.MOVIE,- providerId = provider.id+ providerId = effectiveProviderId)- when (val result = movieRepository.getMovieDetails(provider.id, movieId)) {+ val isFavorite = favoriteRepository.isFavorite(effectiveProviderId, movieId, ContentType.MOVIE)++ when (val result = movieRepository.getMovieDetails(effectiveProviderId, movieId)) {is Result.Success -> _uiState.update {val movie = result.dataval movieDurationMs = movie.durationSeconds.takeIf { it > 0 }?.times(1000L) ?: 0L@@ -69,13 +77,16 @@ class MovieDetailViewModel @Inject constructor(progressMs = resumePositionMs,totalDurationMs = playbackHistory?.totalDurationMs?.takeIf { it > 0L } ?: movieDurationMs)- it.copy(isLoading = false, movie = result.data, error = null)- .copy(- hasResume = hasResume,- resumePositionMs = if (hasResume) resumePositionMs else 0L- )+ it.copy(+ isLoading = false,+ movie = result.data.copy(isFavorite = isFavorite),+ error = null,+ hasResume = hasResume,+ resumePositionMs = if (hasResume) resumePositionMs else 0L+ )}.also {loadExternalRatings(result.data)+ loadRelatedContent(effectiveProviderId)}is Result.Error -> _uiState.update {it.copy(isLoading = false, error = result.message)@@ -92,6 +103,19 @@ class MovieDetailViewModel @Inject constructor(}}+ fun toggleFavorite() {+ val movie = _uiState.value.movie ?: return+ viewModelScope.launch {+ val newState = !movie.isFavorite+ if (newState) {+ favoriteRepository.addFavorite(movie.providerId, movie.id, ContentType.MOVIE)+ } else {+ favoriteRepository.removeFavorite(movie.providerId, movie.id, ContentType.MOVIE)+ }+ _uiState.update { it.copy(movie = movie.copy(isFavorite = newState)) }+ }+ }+private fun loadExternalRatings(movie: Movie) {viewModelScope.launch {_uiState.update { it.copy(isLoadingExternalRatings = true) }@@ -118,6 +142,13 @@ class MovieDetailViewModel @Inject constructor(}}}++ private fun loadRelatedContent(providerId: Long) {+ viewModelScope.launch {+ val related = movieRepository.getRelatedContent(providerId, movieId, limit = 10).first()+ _uiState.update { it.copy(relatedContent = related) }+ }+ }}data class MovieDetailUiState(@@ -127,5 +158,6 @@ data class MovieDetailUiState(val hasResume: Boolean = false,val resumePositionMs: Long = 0L,val isLoadingExternalRatings: Boolean = false,- val externalRatings: ExternalRatings = ExternalRatings.unavailable()+ val externalRatings: ExternalRatings = ExternalRatings.unavailable(),+ val relatedContent: List<Movie> = emptyList())diff --git a/app/src/main/java/com/streamvault/app/ui/screens/movies/MoviesScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/movies/MoviesScreen.ktindex 8c52110d..612b092e 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/movies/MoviesScreen.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/movies/MoviesScreen.kt@@ -53,6 +53,7 @@ import com.streamvault.domain.model.Categoryimport com.streamvault.domain.model.LibraryFilterTypeimport com.streamvault.domain.model.LibrarySortByimport com.streamvault.domain.model.Movie+import com.streamvault.domain.model.PlaybackHistoryimport kotlinx.coroutines.launchimport androidx.compose.ui.res.stringResourceimport com.streamvault.app.R@@ -95,6 +96,7 @@ import kotlinx.coroutines.delay@Composablefun MoviesScreen(onMovieClick: (Movie) -> Unit,+ onContinueWatchingPlay: (PlaybackHistory) -> Unit,onNavigate: (String) -> Unit,currentRoute: String,viewModel: MoviesViewModel = hiltViewModel()@@ -220,6 +222,7 @@ fun MoviesScreen(searchQuery = uiState.searchQuery,onSearchQueryChange = viewModel::setSearchQuery,onMovieClick = onMovieClick,+ onContinueWatchingPlay = onContinueWatchingPlay,onProtectedMovieClick = { movie ->pendingCategory = nullpendingMovie = movie@@ -332,6 +335,7 @@ private fun MoviesVodContent(searchQuery: String,onSearchQueryChange: (String) -> Unit,onMovieClick: (Movie) -> Unit,+ onContinueWatchingPlay: (PlaybackHistory) -> Unit,onProtectedMovieClick: (Movie) -> Unit,onProtectedCategoryClick: (Category) -> Unit,onShowDialog: (Movie) -> Unit,@@ -586,17 +590,7 @@ private fun MoviesVodContent(item(key = "continue_watching") {ContinueWatchingRow(items = continueWatching,- onItemClick = { history ->- onMovieClick(- Movie(- id = history.contentId,- name = history.title,- posterUrl = history.posterUrl,- streamUrl = history.streamUrl,- providerId = history.providerId- )- )- }+ onItemClick = onContinueWatchingPlay)}}@@ -1155,7 +1149,7 @@ private fun MoviesVodClassicContent()LazyVerticalGrid(state = classicGridState,- columns = GridCells.Adaptive(minSize = 136.dp),+ columns = GridCells.Adaptive(minSize = 68.dp),modifier = Modifier.fillMaxWidth().weight(1f)diff --git a/app/src/main/java/com/streamvault/app/ui/screens/movies/MoviesViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/movies/MoviesViewModel.ktindex 39345f00..26523ba8 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@@ -21,6 +21,7 @@ import com.streamvault.domain.repository.FavoriteRepositoryimport com.streamvault.domain.repository.MovieRepositoryimport com.streamvault.domain.repository.PlaybackHistoryRepositoryimport com.streamvault.domain.repository.ProviderRepository+import com.streamvault.domain.usecase.ContinueWatchingResultimport com.streamvault.domain.usecase.ContinueWatchingScopeimport com.streamvault.domain.usecase.GetContinueWatchingimport com.streamvault.domain.usecase.GetCustomCategories@@ -376,9 +377,14 @@ class MoviesViewModel @Inject constructor(limit = 20,scope = ContinueWatchingScope.MOVIES)- .collect { history ->+ .collect { result ->_uiState.update {- it.copy(continueWatching = history)+ it.copy(+ continueWatching = when (result) {+ is ContinueWatchingResult.Items -> result.items+ ContinueWatchingResult.Degraded -> emptyList()+ }+ )}}}@@ -1048,7 +1054,7 @@ class MoviesViewModel @Inject constructor()Triple(filteredItems.take(request.loadLimit),- if (fetchIds === ids) filteredItems.size else ids.size,+ if (fetchIds.size == ids.size) filteredItems.size else ids.size,false)}@@ -1081,7 +1087,7 @@ class MoviesViewModel @Inject constructor()Triple(filteredItems.take(request.loadLimit),- if (fetchIds === ids) filteredItems.size else ids.size,+ if (fetchIds.size == ids.size) filteredItems.size else ids.size,false)} else {@@ -1160,7 +1166,7 @@ class MoviesViewModel @Inject constructor()}LibraryFilterType.UNWATCHED -> searched.filter { it.watchProgress <= 0L }- LibraryFilterType.RECENTLY_UPDATED -> searched.sortedByDescending(::movieReleaseScore)+ LibraryFilterType.RECENTLY_UPDATED -> searched.filter { movieReleaseScore(it) > 0L }LibraryFilterType.TOP_RATED -> searched.filter { it.rating > 0f }}return when (sortBy) {diff --git a/app/src/main/java/com/streamvault/app/ui/screens/multiview/EnhancedMultiViewControlHud.kt b/app/src/main/java/com/streamvault/app/ui/screens/multiview/EnhancedMultiViewControlHud.ktindex 2f5d92b8..cab21a88 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/multiview/EnhancedMultiViewControlHud.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/multiview/EnhancedMultiViewControlHud.kt@@ -164,7 +164,7 @@ internal fun EnhancedMultiViewControlHud(} else {TvButton(onClick = onPinAudioToFocusedSlot,- enabled = focused != null && !focused.isEmpty,+ enabled = focused != null && !focused.isEmpty && focused.performanceBlockedReason == null,colors = ButtonDefaults.colors(containerColor = Color(0xFF203A5C),contentColor = Color.White,diff --git a/app/src/main/java/com/streamvault/app/ui/screens/multiview/MultiViewManager.kt b/app/src/main/java/com/streamvault/app/ui/screens/multiview/MultiViewManager.ktindex 0c520fa2..695bce86 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/multiview/MultiViewManager.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/multiview/MultiViewManager.kt@@ -4,6 +4,7 @@ import com.streamvault.domain.model.Channelimport kotlinx.coroutines.flow.MutableStateFlowimport kotlinx.coroutines.flow.StateFlowimport kotlinx.coroutines.flow.asStateFlow+import kotlinx.coroutines.flow.updateimport javax.inject.Injectimport javax.inject.Singleton@@ -23,25 +24,33 @@ class MultiViewManager @Inject constructor() {/** Place a channel in a specific slot index (0–3). Replaces whatever was there. */fun setChannel(slotIndex: Int, channel: Channel) {if (slotIndex !in 0 until MAX_SLOTS) return- _slots.value = _slots.value.toMutableList().also { slots ->- slots.indices.forEach { index ->- if (index != slotIndex && slots[index]?.id == channel.id) {- slots[index] = null+ _slots.update { current ->+ current.toMutableList().also { slots ->+ slots.indices.forEach { index ->+ if (index != slotIndex && slots[index]?.id == channel.id) {+ slots[index] = null+ }}+ slots[slotIndex] = channel}- slots[slotIndex] = channel}}/** Clear a specific slot. */fun clearSlot(slotIndex: Int) {if (slotIndex !in 0 until MAX_SLOTS) return- _slots.value = _slots.value.toMutableList().also { it[slotIndex] = null }+ _slots.update { current -> current.toMutableList().also { it[slotIndex] = null } }}/** Clear all slots. */fun clearAll() {- _slots.value = List(MAX_SLOTS) { null }+ _slots.update { List(MAX_SLOTS) { null } }+ }++ /** Atomically replace all slot assignments. `plan` must have exactly MAX_SLOTS entries. */+ fun setSlots(plan: List<Channel?>) {+ require(plan.size == MAX_SLOTS)+ _slots.update { plan.toList() }}/** Returns true if the given channel is in any slot. */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.ktindex 6a2eb351..e15bd8eb 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@@ -57,7 +57,9 @@ fun MultiViewPlannerDialog(onLaunch: () -> Unit,viewModel: MultiViewViewModel = hiltViewModel()) {+ val uiState by viewModel.uiState.collectAsStateWithLifecycle()val slots by viewModel.slotsFlow.collectAsStateWithLifecycle()+ val centeredTwoSlotLayout = uiState.centerTwoSlotLayoutval isPickerMode = pendingChannel != nullval hasAny = slots.any { it != null }val channelPlaced = pendingChannel != null && slots.any { it?.id == pendingChannel.id }@@ -68,6 +70,12 @@ fun MultiViewPlannerDialog(runCatching { firstSlotFocusRequester.requestFocus() }}+ LaunchedEffect(centeredTwoSlotLayout) {+ if (centeredTwoSlotLayout) {+ viewModel.normalizeCenteredTwoSlotLayoutIfNeeded()+ }+ }+val subtitle = when {isPickerMode && !channelPlaced ->stringResource(R.string.multiview_planner_pick_slot, pendingChannel!!.name)@@ -97,13 +105,17 @@ fun MultiViewPlannerDialog(}Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {- for (row in 0 until 2) {+ val plannerRows = if (centeredTwoSlotLayout) {+ listOf(listOf(0, 1))+ } else {+ listOf(listOf(0, 1), listOf(2, 3))+ }+ plannerRows.forEachIndexed { rowIndex, rowSlots ->Row(modifier = Modifier.fillMaxWidth(),horizontalArrangement = Arrangement.spacedBy(12.dp)) {- for (col in 0 until 2) {- val slotIndex = row * 2 + col+ rowSlots.forEachIndexed { colIndex, slotIndex ->val occupant = slots.getOrNull(slotIndex)MultiViewSlotCard(slotIndex = slotIndex,@@ -112,7 +124,7 @@ fun MultiViewPlannerDialog(modifier = Modifier.weight(1f).then(- if (slotIndex == 0) Modifier.focusRequester(firstSlotFocusRequester)+ if (rowIndex == 0 && colIndex == 0) Modifier.focusRequester(firstSlotFocusRequester)else Modifier),onSlotClick = {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.ktindex 23b7af4f..22a22bf8 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@@ -12,6 +12,7 @@ import androidx.compose.animation.fadeOutimport androidx.compose.animation.core.tweenimport androidx.compose.foundation.backgroundimport androidx.compose.foundation.border+import androidx.compose.foundation.layout.aspectRatioimport androidx.compose.foundation.lazy.LazyColumnimport androidx.compose.foundation.lazy.itemsimport androidx.compose.foundation.text.BasicTextField@@ -100,6 +101,10 @@ fun MultiViewScreen(val firstControlFocusRequester = remember { FocusRequester() }var showReplacementPicker by remember { mutableStateOf(false) }var showControls by rememberSaveable { mutableStateOf(false) }+ val occupiedSlots = remember(uiState.slots) { uiState.slots.filterNot { it.isEmpty } }+ val useCenteredTwoSlotLayout = uiState.centerTwoSlotLayout && occupiedSlots.size == 2+ val visibleSlots = if (useCenteredTwoSlotLayout) occupiedSlots else uiState.slots+ val firstVisibleSlotIndex = visibleSlots.firstOrNull()?.index ?: 0BackHandler(enabled = showReplacementPicker) {if (uiState.pickerState.selectedCategory != null) {@@ -112,8 +117,8 @@ fun MultiViewScreen(BackHandler(enabled = showControls) { showControls = false }BackHandler(enabled = !showReplacementPicker && !showControls) { onBack() }+ // initSlots() is driven by the ON_START lifecycle observer below; do not call it here.LaunchedEffect(Unit) {- viewModel.initSlots()try {kotlinx.coroutines.delay(100)firstSlotFocusRequester.requestFocus()@@ -133,6 +138,12 @@ fun MultiViewScreen(}}+ LaunchedEffect(useCenteredTwoSlotLayout, firstVisibleSlotIndex, uiState.focusedSlotIndex) {+ if (useCenteredTwoSlotLayout && visibleSlots.none { it.index == uiState.focusedSlotIndex }) {+ viewModel.setFocus(firstVisibleSlotIndex)+ }+ }+DisposableEffect(Unit) {onDispose {viewModel.releasePlayersForBackground()@@ -212,65 +223,27 @@ fun MultiViewScreen(}Column(modifier = Modifier.fillMaxSize()) {- Row(modifier = Modifier.weight(1f)) {- PlayerCell(- slot = uiState.slots.getOrNull(0),- isFocused = uiState.focusedSlotIndex == 0,+ if (useCenteredTwoSlotLayout) {+ CenteredTwoSlotLayout(+ slots = visibleSlots,+ focusedSlotIndex = uiState.focusedSlotIndex,showSelectionBorder = uiState.showSelectionBorder,- onClick = { showControls = !showControls },- modifier = Modifier- .weight(1f)- .fillMaxHeight()- .focusRequester(firstSlotFocusRequester)- .focusProperties {- canFocus = !showControls- if (showControls) down = firstControlFocusRequester- },- onFocused = { viewModel.setFocus(0) }- )- PlayerCell(- slot = uiState.slots.getOrNull(1),- isFocused = uiState.focusedSlotIndex == 1,- showSelectionBorder = uiState.showSelectionBorder,- onClick = { showControls = !showControls },- modifier = Modifier- .weight(1f)- .fillMaxHeight()- .focusProperties {- canFocus = !showControls- if (showControls) down = firstControlFocusRequester- },- onFocused = { viewModel.setFocus(1) }- )- }- Row(modifier = Modifier.weight(1f)) {- PlayerCell(- slot = uiState.slots.getOrNull(2),- isFocused = uiState.focusedSlotIndex == 2,- showSelectionBorder = uiState.showSelectionBorder,- onClick = { showControls = !showControls },- modifier = Modifier- .weight(1f)- .fillMaxHeight()- .focusProperties {- canFocus = !showControls- if (showControls) down = firstControlFocusRequester- },- onFocused = { viewModel.setFocus(2) }+ showControls = showControls,+ firstSlotFocusRequester = firstSlotFocusRequester,+ firstControlFocusRequester = firstControlFocusRequester,+ onSlotClick = { showControls = !showControls },+ onSlotFocused = viewModel::setFocus)- PlayerCell(- slot = uiState.slots.getOrNull(3),- isFocused = uiState.focusedSlotIndex == 3,+ } else {+ StandardMultiViewGrid(+ slots = uiState.slots,+ focusedSlotIndex = uiState.focusedSlotIndex,showSelectionBorder = uiState.showSelectionBorder,- onClick = { showControls = !showControls },- modifier = Modifier- .weight(1f)- .fillMaxHeight()- .focusProperties {- canFocus = !showControls- if (showControls) down = firstControlFocusRequester- },- onFocused = { viewModel.setFocus(3) }+ showControls = showControls,+ firstSlotFocusRequester = firstSlotFocusRequester,+ firstControlFocusRequester = firstControlFocusRequester,+ onSlotClick = { showControls = !showControls },+ onSlotFocused = viewModel::setFocus)}}@@ -313,6 +286,150 @@ fun MultiViewScreen(}}+@Composable+private fun StandardMultiViewGrid(+ slots: List<MultiViewSlot>,+ focusedSlotIndex: Int,+ showSelectionBorder: Boolean,+ showControls: Boolean,+ firstSlotFocusRequester: FocusRequester,+ firstControlFocusRequester: FocusRequester,+ onSlotClick: () -> Unit,+ onSlotFocused: (Int) -> Unit+) {+ Column(modifier = Modifier.fillMaxSize()) {+ Row(modifier = Modifier.weight(1f)) {+ GridPlayerCell(+ slot = slots.getOrNull(0),+ slotIndex = 0,+ focusedSlotIndex = focusedSlotIndex,+ showSelectionBorder = showSelectionBorder,+ showControls = showControls,+ onClick = onSlotClick,+ onFocused = onSlotFocused,+ firstSlotFocusRequester = firstSlotFocusRequester,+ firstControlFocusRequester = firstControlFocusRequester,+ modifier = Modifier+ .weight(1f)+ .fillMaxHeight()+ )+ GridPlayerCell(+ slot = slots.getOrNull(1),+ slotIndex = 1,+ focusedSlotIndex = focusedSlotIndex,+ showSelectionBorder = showSelectionBorder,+ showControls = showControls,+ onClick = onSlotClick,+ onFocused = onSlotFocused,+ firstSlotFocusRequester = null,+ firstControlFocusRequester = firstControlFocusRequester,+ modifier = Modifier+ .weight(1f)+ .fillMaxHeight()+ )+ }+ Row(modifier = Modifier.weight(1f)) {+ GridPlayerCell(+ slot = slots.getOrNull(2),+ slotIndex = 2,+ focusedSlotIndex = focusedSlotIndex,+ showSelectionBorder = showSelectionBorder,+ showControls = showControls,+ onClick = onSlotClick,+ onFocused = onSlotFocused,+ firstSlotFocusRequester = null,+ firstControlFocusRequester = firstControlFocusRequester,+ modifier = Modifier+ .weight(1f)+ .fillMaxHeight()+ )+ GridPlayerCell(+ slot = slots.getOrNull(3),+ slotIndex = 3,+ focusedSlotIndex = focusedSlotIndex,+ showSelectionBorder = showSelectionBorder,+ showControls = showControls,+ onClick = onSlotClick,+ onFocused = onSlotFocused,+ firstSlotFocusRequester = null,+ firstControlFocusRequester = firstControlFocusRequester,+ modifier = Modifier+ .weight(1f)+ .fillMaxHeight()+ )+ }+ }+}++@Composable+private fun CenteredTwoSlotLayout(+ slots: List<MultiViewSlot>,+ focusedSlotIndex: Int,+ showSelectionBorder: Boolean,+ showControls: Boolean,+ firstSlotFocusRequester: FocusRequester,+ firstControlFocusRequester: FocusRequester,+ onSlotClick: () -> Unit,+ onSlotFocused: (Int) -> Unit+) {+ Column(+ modifier = Modifier.fillMaxSize(),+ verticalArrangement = Arrangement.Center+ ) {+ Row(+ modifier = Modifier+ .fillMaxWidth()+ .padding(horizontal = 72.dp),+ horizontalArrangement = Arrangement.spacedBy(12.dp)+ ) {+ slots.forEachIndexed { index, slot ->+ GridPlayerCell(+ slot = slot,+ slotIndex = slot.index,+ focusedSlotIndex = focusedSlotIndex,+ showSelectionBorder = showSelectionBorder,+ showControls = showControls,+ onClick = onSlotClick,+ onFocused = onSlotFocused,+ firstSlotFocusRequester = if (index == 0) firstSlotFocusRequester else null,+ firstControlFocusRequester = firstControlFocusRequester,+ modifier = Modifier+ .weight(1f)+ .aspectRatio(16f / 9f)+ )+ }+ }+ }+}++@Composable+private fun GridPlayerCell(+ slot: MultiViewSlot?,+ slotIndex: Int,+ focusedSlotIndex: Int,+ showSelectionBorder: Boolean,+ showControls: Boolean,+ onClick: () -> Unit,+ onFocused: (Int) -> Unit,+ firstSlotFocusRequester: FocusRequester?,+ firstControlFocusRequester: FocusRequester,+ modifier: Modifier+) {+ PlayerCell(+ slot = slot,+ isFocused = focusedSlotIndex == slotIndex,+ showSelectionBorder = showSelectionBorder,+ onClick = onClick,+ modifier = modifier+ .then(if (firstSlotFocusRequester != null) Modifier.focusRequester(firstSlotFocusRequester) else Modifier)+ .focusProperties {+ canFocus = !showControls+ if (showControls) down = firstControlFocusRequester+ },+ onFocused = { onFocused(slotIndex) }+ )+}+@OptIn(UnstableApi::class)@Composableprivate fun PlayerCell(diff --git a/app/src/main/java/com/streamvault/app/ui/screens/multiview/MultiViewState.kt b/app/src/main/java/com/streamvault/app/ui/screens/multiview/MultiViewState.ktindex 2ff03cdd..df84c164 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/multiview/MultiViewState.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/multiview/MultiViewState.kt@@ -71,6 +71,7 @@ data class MultiViewUiState(val focusedSlotIndex: Int = 0,val isLaunching: Boolean = false,val showSelectionBorder: Boolean = true,+ val centerTwoSlotLayout: Boolean = false,val presets: List<MultiViewPresetUiModel> = emptyList(),val pinnedAudioSlotIndex: Int? = null,val replacementCandidates: List<Channel> = emptyList(),diff --git a/app/src/main/java/com/streamvault/app/ui/screens/multiview/MultiViewViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/multiview/MultiViewViewModel.ktindex 134f3613..19e1b11b 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/multiview/MultiViewViewModel.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/multiview/MultiViewViewModel.kt@@ -26,6 +26,7 @@ import dagger.hilt.android.qualifiers.ApplicationContextimport kotlinx.coroutines.flow.MutableStateFlowimport kotlinx.coroutines.flow.StateFlowimport kotlinx.coroutines.flow.asStateFlow+import kotlinx.coroutines.flow.collectLatestimport kotlinx.coroutines.flow.firstimport kotlinx.coroutines.flow.combineimport kotlinx.coroutines.isActive@@ -66,9 +67,11 @@ class MultiViewViewModel @Inject constructor(private val lastDroppedFramesBySlot = mutableMapOf<Int, Int>()private val slotStartupJobs = mutableMapOf<Int, kotlinx.coroutines.Job>()private val slotErrorJobs = mutableMapOf<Int, kotlinx.coroutines.Job>()+ private val slotGenerations = mutableMapOf<Int, Long>()private var slotInitVersion: Long = 0Lprivate var playbackSessionActive: Boolean = falseprivate var currentProviderId: Long? = null+ private var lastPerformanceMode: MultiViewPerformanceMode? = null/** Flow of the current 4 slot channels from the manager */val slotsFlow = multiViewManager.slots@@ -86,19 +89,28 @@ class MultiViewViewModel @Inject constructor(preferencesRepository.getMultiViewPreset(0),preferencesRepository.getMultiViewPreset(1),preferencesRepository.getMultiViewPreset(2),- preferencesRepository.multiViewPerformanceMode- ) { preset1, preset2, preset3, performanceMode ->- listOf(preset1, preset2, preset3) to performanceMode+ preferencesRepository.multiViewPerformanceMode,+ preferencesRepository.multiViewCenterTwoSlotLayout+ ) { preset1, preset2, preset3, performanceMode, centerTwoSlotLayout ->+ Triple(listOf(preset1, preset2, preset3), performanceMode, centerTwoSlotLayout)}.collect { presets ->val presetList = presets.firstval mode = presets.second?.let { saved -> MultiViewPerformanceMode.entries.firstOrNull { it.name == saved } }?: MultiViewPerformanceMode.AUTOval policy = resolvePolicy(mode, detectedTier)- runtimeActiveSlotLimit = runtimeActiveSlotLimit- .coerceAtLeast(1)- .coerceAtMost(policy.maxActiveSlots)+ val modeChanged = lastPerformanceMode != null && lastPerformanceMode != mode+ lastPerformanceMode = mode+ runtimeActiveSlotLimit = if (modeChanged &&+ thermalStatus != MultiViewThermalStatus.SEVERE &&+ thermalStatus != MultiViewThermalStatus.CRITICAL+ ) {+ policy.maxActiveSlots+ } else {+ runtimeActiveSlotLimit.coerceAtLeast(1).coerceAtMost(policy.maxActiveSlots)+ }_uiState.value = _uiState.value.copy(+ centerTwoSlotLayout = presets.third,presets = presetList.mapIndexed { index, ids ->MultiViewPresetUiModel(index = index,@@ -159,12 +171,15 @@ class MultiViewViewModel @Inject constructor(fun releasePlayersForBackground() {playbackSessionActive = false+ telemetryJob?.cancel()+ telemetryJob = nullreleaseActivePlayers()}/** Called when MultiViewScreen is opened — spins up player engines for occupied slots */fun initSlots() {playbackSessionActive = true+ normalizeCenteredTwoSlotLayoutIfNeeded()val initVersion = ++slotInitVersiontelemetryJob?.cancel()cancelSlotStartupJobs()@@ -179,10 +194,13 @@ class MultiViewViewModel @Inject constructor(val maxActiveSlots = providerConnectionLimit?.let { deviceActiveSlotLimit.coerceAtMost(it) }?: deviceActiveSlotLimit+ var occupiedCount = 0val slots = channels.mapIndexed { index, channel ->if (channel != null) {+ val isActive = occupiedCount < maxActiveSlots+ occupiedCount++val performanceBlockedReason = when {- index < maxActiveSlots -> null+ isActive -> nullproviderConnectionLimit != null && providerConnectionLimit < deviceActiveSlotLimit ->"Held back by the provider connection limit (${providerConnectionLimit} stream(s) max)."else ->@@ -193,7 +211,7 @@ class MultiViewViewModel @Inject constructor(channel = channel,streamUrl = channel.streamUrl,title = channel.name,- isLoading = index < maxActiveSlots,+ isLoading = isActive,isAudioPinned = pinnedAudioSlotIndex == index,performanceBlockedReason = performanceBlockedReason)@@ -223,65 +241,82 @@ class MultiViewViewModel @Inject constructor(// Start all occupied enginesslots.forEachIndexed { index, slot ->if (!slot.isEmpty) {- if (index >= maxActiveSlots) {+ if (slot.performanceBlockedReason != null) {updateSlot(index) { it.copy(isLoading = false, playerEngine = null) }return@forEachIndexed}val startupJob = viewModelScope.launch {kotlinx.coroutines.delay(index * _uiState.value.performancePolicy.startupDelayMs)if (initVersion != slotInitVersion) return@launch+ val slotGen = slotGenerations.getOrDefault(index, 0L)+ var localEngine: PlayerEngine? = null+ var enginePublished = falsetry {- val engine = playerEngineProvider.get()+ localEngine = playerEngineProvider.get()// Cap each multi-view slot to 720p so slots don't compete for 4K bandwidth- (engine as? com.streamvault.player.Media3PlayerEngine)+ (localEngine as? com.streamvault.player.Media3PlayerEngine)?.let {it.constrainResolutionForMultiView = trueit.bypassAudioFocus = trueit.enableMediaSession = false}- if (initVersion != slotInitVersion) {- engine.release()+ if (initVersion != slotInitVersion || slotGen != slotGenerations.getOrDefault(index, 0L)) {return@launch}- playerEngines[index] = engine- observeSlotErrors(index, engine, initVersion)+ observeSlotErrors(index, localEngine, initVersion)val channel = slot.channel?: throw IllegalStateException("Missing channel for slot ${slot.index}")- engine.setAudioVideoOffsetMs(effectiveAudioVideoOffsetForChannel(channel.id))+ localEngine.setAudioVideoOffsetMs(effectiveAudioVideoOffsetForChannel(channel.id))val streamInfo = when (val result = channelRepository.getStreamInfo(channel)) {is Result.Success -> result.datais Result.Error -> throw IllegalStateException(result.message)Result.Loading -> throw IllegalStateException("Stream info still loading for ${slot.title}")}- engine.prepare(streamInfo)- engine.play()-+ if (initVersion != slotInitVersion || slotGen != slotGenerations.getOrDefault(index, 0L)) {+ return@launch+ }+ localEngine.prepare(streamInfo)+ localEngine.play()++ // Success: publish engine+ playerEngines[index] = localEngine+ enginePublished = true+// Copy the engine into the slot UI state as wellupdateSlot(index) {it.copy(isLoading = false,hasError = false,errorMessage = null,- playerEngine = engine+ playerEngine = localEngine)}-+// Re-apply audio to make sure the focused one is audibleapplyFocusAudio(_uiState.value.focusedSlotIndex)} catch (e: Exception) {- if (initVersion == slotInitVersion) {- updateSlot(index) {- it.copy(- isLoading = false,- hasError = true,- errorMessage = e.message,- playerEngine = playerEngines[index]- )+ val isCancellation = e is kotlinx.coroutines.CancellationException+ if (!isCancellation) {+ slotErrorJobs.remove(index)?.cancel()+ if (initVersion == slotInitVersion) {+ updateSlot(index) {+ it.copy(+ isLoading = false,+ hasError = true,+ errorMessage = e.message,+ playerEngine = null+ )+ }}}+ if (isCancellation) throw e} finally {+ if (!enginePublished) {+ runCatching { localEngine?.stop() }+ runCatching { localEngine?.release() }+ }slotStartupJobs.remove(index)}}@@ -312,8 +347,10 @@ class MultiViewViewModel @Inject constructor(}private fun applyFocusAudio(focusedIndex: Int) {+ val audibleIndex = pinnedAudioSlotIndex+ ?.takeIf { playerEngines.containsKey(it) }+ ?: focusedIndexplayerEngines.forEach { (index, engine) ->- val audibleIndex = pinnedAudioSlotIndex ?: focusedIndexif (index == audibleIndex) engine.setVolume(1f) else engine.setVolume(0f)}}@@ -321,11 +358,21 @@ class MultiViewViewModel @Inject constructor(/** Assign a channel to a specific slot (0–3). Called from dialog or AddToGroupDialog. */fun assignChannelToSlot(slotIndex: Int, channel: Channel) {multiViewManager.setChannel(slotIndex, channel)+ normalizeCenteredTwoSlotLayoutIfNeeded()}/** Clear a specific slot */fun clearSlot(slotIndex: Int) {slotStartupJobs.remove(slotIndex)?.cancel()+ slotErrorJobs.remove(slotIndex)?.cancel()+ slotGenerations[slotIndex] = (slotGenerations.getOrDefault(slotIndex, 0L) + 1L)+ if (playbackSessionActive) {+ playerEngines.remove(slotIndex)?.let { engine ->+ runCatching { engine.stop() }+ runCatching { engine.release() }+ }+ updateSlot(slotIndex) { it.copy(isLoading = false, playerEngine = null) }+ }multiViewManager.clearSlot(slotIndex)if (pinnedAudioSlotIndex == slotIndex) {pinnedAudioSlotIndex = null@@ -353,12 +400,14 @@ class MultiViewViewModel @Inject constructor(}fun pinAudioToFocusedSlot() {- pinnedAudioSlotIndex = _uiState.value.focusedSlotIndex+ val focusedIndex = _uiState.value.focusedSlotIndex+ if (!playerEngines.containsKey(focusedIndex)) return // Cannot pin audio to a slot without an active engine+ pinnedAudioSlotIndex = focusedIndex_uiState.value = _uiState.value.copy(pinnedAudioSlotIndex = pinnedAudioSlotIndex,slots = _uiState.value.slots.mapIndexed { index, slot -> slot.copy(isAudioPinned = index == pinnedAudioSlotIndex) })- applyFocusAudio(_uiState.value.focusedSlotIndex)+ applyFocusAudio(focusedIndex)}fun clearPinnedAudio() {@@ -372,7 +421,8 @@ class MultiViewViewModel @Inject constructor(fun saveCurrentAsPreset(presetIndex: Int) {viewModelScope.launch {- val channelIds = multiViewManager.slots.value.mapNotNull { it?.id }+ // Save as a fixed-size list (one entry per slot); 0L marks an empty slot so positions are preserved.+ val channelIds = multiViewManager.slots.value.map { it?.id ?: 0L }preferencesRepository.setMultiViewPreset(presetIndex, channelIds)}}@@ -387,21 +437,34 @@ class MultiViewViewModel @Inject constructor(fun loadPreset(presetIndex: Int) {viewModelScope.launch {val channelIds = preferencesRepository.getMultiViewPreset(presetIndex).first()- if (channelIds.isEmpty()) return@launch- val channels = channelRepository.getChannelsByIds(channelIds).first()+ if (channelIds.isEmpty() || channelIds.all { it <= 0L }) return@launch+ val validIds = channelIds.filter { it > 0L }+ val channels = channelRepository.getChannelsByIds(validIds).first().associateByAnyRawId()- multiViewManager.clearAll()- channelIds.forEachIndexed { index, channelId ->- channels[channelId]?.let { channel ->- multiViewManager.setChannel(index, channel)- }+ // Rebuild a fixed-size plan preserving slot positions; 0L entries become empty slots.+ val plan: List<com.streamvault.domain.model.Channel?> = List(MultiViewManager.MAX_SLOTS) { index ->+ val id = channelIds.getOrNull(index) ?: 0L+ if (id > 0L) channels[id] else null}+ multiViewManager.setSlots(plan)restartPlaybackIfActive()}}fun isQueued(channelId: Long): Boolean = multiViewManager.isQueued(channelId)+ fun normalizeCenteredTwoSlotLayoutIfNeeded() {+ if (!_uiState.value.centerTwoSlotLayout) return+ val current = multiViewManager.slots.value+ val normalized = buildCenteredTwoSlotPlan(current)+ if (normalized == current) return+ multiViewManager.setSlots(normalized)+ if (pinnedAudioSlotIndex != null && normalized.getOrNull(pinnedAudioSlotIndex ?: -1) == null) {+ pinnedAudioSlotIndex = null+ _uiState.value = _uiState.value.copy(pinnedAudioSlotIndex = null)+ }+ }+private fun updateSlot(index: Int, transform: (MultiViewSlot) -> MultiViewSlot) {val updated = _uiState.value.slots.toMutableList()if (index < updated.size) {@@ -416,6 +479,13 @@ class MultiViewViewModel @Inject constructor(}}+ private fun buildCenteredTwoSlotPlan(slots: List<Channel?>): List<Channel?> {+ val firstTwoPopulated = slots.filterNotNull().take(2)+ return List(MultiViewManager.MAX_SLOTS) { index ->+ firstTwoPopulated.getOrNull(index)+ }+ }+private fun releaseActivePlayers() {cancelSlotStartupJobs()cancelSlotErrorJobs()@@ -504,10 +574,11 @@ class MultiViewViewModel @Inject constructor(private fun observeReplacementCandidates() {viewModelScope.launch {- preferencesRepository.lastActiveProviderId.collect { providerId ->+ preferencesRepository.lastActiveProviderId.collectLatest { providerId ->if (providerId == null || providerId <= 0L) {+ currentProviderId = null_uiState.value = _uiState.value.copy(replacementCandidates = emptyList())- return@collect+ return@collectLatest}currentProviderId = providerIdcombine(@@ -798,7 +869,26 @@ class MultiViewViewModel @Inject constructor(if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q || thermalListener != null) returnval manager = powerManager ?: returnthermalListener = PowerManager.OnThermalStatusChangedListener { status ->- thermalStatus = mapThermalStatus(status)+ val newStatus = mapThermalStatus(status)+ val wasBelow = thermalStatus != MultiViewThermalStatus.SEVERE &&+ thermalStatus != MultiViewThermalStatus.CRITICAL+ thermalStatus = newStatus+ if ((newStatus == MultiViewThermalStatus.SEVERE || newStatus == MultiViewThermalStatus.CRITICAL) && wasBelow) {+ // Immediately cap admission and update UI without waiting for next telemetry tick+ runtimeActiveSlotLimit = (runtimeActiveSlotLimit - 1).coerceAtLeast(1)+ lastPolicyAdjustmentAt = System.currentTimeMillis()+ _uiState.value = _uiState.value.copy(+ telemetry = _uiState.value.telemetry.copy(+ thermalStatus = newStatus,+ throttledReason = "Thermal pressure forced Split Screen to hold extra slots in standby."+ )+ )+ restartPlaybackIfActive()+ } else {+ _uiState.value = _uiState.value.copy(+ telemetry = _uiState.value.telemetry.copy(thermalStatus = newStatus)+ )+ }}manager.addThermalStatusListener(context.mainExecutor, thermalListener!!)}diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerAlternateStreamActions.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerAlternateStreamActions.ktindex 23df4e51..d6253509 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerAlternateStreamActions.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerAlternateStreamActions.kt@@ -69,7 +69,6 @@ internal fun PlayerViewModel.tryAlternateStreamInternal(channel: Channel): BoolecontentType = ContentType.LIVE) ?: return@launchif (!isActivePlaybackSession(requestVersion, nextVariant.streamUrl)) return@launch- recordLivePlayback(updatedChannel)requestEpg(providerId = updatedChannel.providerId,epgChannelId = updatedChannel.epgChannelId,@@ -131,10 +130,16 @@ internal fun PlayerViewModel.tryNextCatchUpVariantInternal(): Boolean {currentStreamUrl = nextStreamupdateStreamClass("Catch-up")viewModelScope.launch {- val streamInfo = resolvePlaybackStreamInfo(nextStream, currentContentId, currentProviderId, ContentType.LIVE)+ val streamInfo = resolveCatchUpStreamInfo(+ candidateUrl = nextStream,+ title = currentTitle,+ currentContentId = currentContentId,+ currentProviderId = currentProviderId,+ resolveStreamInfo = ::resolvePlaybackStreamInfo+ )?: return@launchif (!isActivePlaybackSession(requestVersion, nextStream)) return@launch- if (!preparePlayer(streamInfo.copy(title = streamInfo.title ?: currentTitle), requestVersion)) return@launch+ if (!preparePlayer(streamInfo, requestVersion)) return@launchplayerEngine.play()}return truediff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerCatchUpActions.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerCatchUpActions.ktindex 92a90f4e..a2230433 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerCatchUpActions.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerCatchUpActions.kt@@ -1,12 +1,22 @@package com.streamvault.app.ui.screens.playerimport androidx.lifecycle.viewModelScope+import com.streamvault.app.ui.model.isArchivePlayableimport com.streamvault.data.security.CredentialDecryptionException+import com.streamvault.domain.model.ContentTypeimport com.streamvault.domain.model.Programimport com.streamvault.domain.model.StreamInfo-import com.streamvault.domain.model.StreamTypeimport kotlinx.coroutines.launch+internal suspend fun resolveCatchUpStreamInfo(+ candidateUrl: String,+ title: String,+ currentContentId: Long,+ currentProviderId: Long,+ resolveStreamInfo: suspend (String, Long, Long, ContentType) -> StreamInfo?+): StreamInfo? = resolveStreamInfo(candidateUrl, currentContentId, currentProviderId, ContentType.LIVE)+ ?.copy(title = title)+internal suspend fun PlayerViewModel.startCatchUpPlayback(urls: List<String>,title: String,@@ -30,11 +40,13 @@ internal suspend fun PlayerViewModel.startCatchUpPlayback(updateStreamClass("Catch-up")appendRecoveryAction(recoveryAction)- val catchupStream = StreamInfo(- url = primaryUrl,+ val catchupStream = resolveCatchUpStreamInfo(+ candidateUrl = primaryUrl,title = currentTitle,- streamType = StreamType.UNKNOWN- )+ currentContentId = currentContentId,+ currentProviderId = currentProviderId,+ resolveStreamInfo = ::resolvePlaybackStreamInfo+ ) ?: returnif (!preparePlayer(catchupStream, requestVersion)) returnplayerEngine.play()}@@ -42,9 +54,13 @@ internal suspend fun PlayerViewModel.startCatchUpPlayback(fun PlayerViewModel.playCatchUp(program: Program) {viewModelScope.launch {val requestVersion = prepareRequestVersion+ val channel = currentChannelFlow.value+ if (channel == null || !channel.isArchivePlayable(program)) {+ return@launch+ }val start = program.startTime / 1000Lval end = program.endTime / 1000L- val streamId = currentChannelFlow.value?.id ?: 0L+ val streamId = channel.idval providerId = currentProviderIdif (providerId == -1L || streamId == 0L) {@@ -73,12 +89,12 @@ fun PlayerViewModel.playCatchUp(program: Program) {if (catchUpUrls.isNotEmpty()) {startCatchUpPlayback(urls = catchUpUrls,- title = "${currentChannelFlow.value?.name ?: ""}: ${program.title}",+ title = "${channel.name}: ${program.title}",recoveryAction = "Started program replay")} else {val reason = resolveCatchUpFailureMessage(- currentChannelFlow.value,+ channel,archiveRequested = true,programHasArchive = program.hasArchive)diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerLifecycleActions.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerLifecycleActions.ktindex c75374e2..cfe98cd4 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerLifecycleActions.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerLifecycleActions.kt@@ -57,6 +57,7 @@ internal fun PlayerViewModel.startTokenRenewalMonitoring(expirationTime: Long?)) ?: return@launchif (!isActivePlaybackSession(requestVersion)) return@launchcurrentResolvedPlaybackUrl = refreshed.url+ currentResolvedStreamInfo = refreshedplayerEngine.renewStreamUrl(refreshed)startTokenRenewalMonitoring(refreshed.expirationTime)return@launch@@ -117,7 +118,6 @@ fun PlayerViewModel.handOffPlaybackToMultiView() {}playerEngine.stopLiveTimeshift()livePreviewHandoffManager.clear(playerEngine)- playerEngine.release()}internal fun PlayerViewModel.cleanupAfterCleared(mainPlayerEngine: PlayerEngine) {@@ -138,10 +138,15 @@ internal fun PlayerViewModel.cleanupAfterCleared(mainPlayerEngine: PlayerEngine)aspectRatioJob?.cancel()recentChannelsJob?.cancel()lastVisitedCategoryJob?.cancel()+ thumbnailPreloadJob?.cancel()+ inFlightThumbnailPreloadKey = null+ lastCompletedThumbnailPreloadKey = nullseekThumbnailProvider.clearCache()livePreviewHandoffManager.clear(playerEngine)- playerEngine.release()- if (mainPlayerEngine !== playerEngine) {- mainPlayerEngine.release()+ if (playerEngine === mainPlayerEngine) {+ mainPlayerEngine.resetForReuse()+ } else {+ playerEngine.release()+ mainPlayerEngine.resetForReuse()}}\ No newline at end of filediff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerNoticeActions.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerNoticeActions.ktindex 64cdd242..7d9861c2 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerNoticeActions.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerNoticeActions.kt@@ -1,6 +1,7 @@package com.streamvault.app.ui.screens.playerimport androidx.lifecycle.viewModelScope+import com.streamvault.app.ui.model.isArchivePlayableimport com.streamvault.domain.model.ContentTypeimport kotlinx.coroutines.delayimport kotlinx.coroutines.launch@@ -77,7 +78,8 @@ internal fun PlayerViewModel.showRetryNotice(status: com.streamvault.player.Playfun PlayerViewModel.restartCurrentProgram() {val program = currentProgram.value ?: return- if (program.hasArchive || (currentChannelFlow.value?.catchUpSupported == true)) {+ val channel = currentChannelFlow.value ?: return+ if (channel.isArchivePlayable(program)) {playCatchUp(program)}}diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerPlaybackPreferenceActions.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerPlaybackPreferenceActions.ktindex 33c92290..f510e275 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerPlaybackPreferenceActions.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerPlaybackPreferenceActions.kt@@ -13,6 +13,54 @@ import kotlinx.coroutines.ensureActiveimport kotlinx.coroutines.flow.firstimport kotlinx.coroutines.flow.updateimport kotlinx.coroutines.launch+import kotlin.collections.LinkedHashSet++private const val THUMBNAIL_PRELOAD_BUCKET_MS = 10_000L+private const val THUMBNAIL_PRELOAD_FRAME_BUDGET = 6++internal fun buildThumbnailPreloadPositions(+ durationMs: Long,+ currentPositionMs: Long,+ bucketMs: Long = THUMBNAIL_PRELOAD_BUCKET_MS,+ frameBudget: Int = THUMBNAIL_PRELOAD_FRAME_BUDGET+): List<Long> {+ if (durationMs <= 0L || bucketMs <= 0L || frameBudget <= 0) return emptyList()++ val maxPositionMs = durationMs.coerceAtLeast(0L)+ val anchorPositionMs = (currentPositionMs.coerceIn(0L, maxPositionMs) / bucketMs) * bucketMs+ val plannedPositions = LinkedHashSet<Long>()+ var offsetMs = 0L++ while (plannedPositions.size < frameBudget) {+ val forwardPositionMs = anchorPositionMs + offsetMs+ if (forwardPositionMs <= maxPositionMs) {+ plannedPositions += forwardPositionMs+ }+ if (plannedPositions.size >= frameBudget) break++ if (offsetMs > 0L) {+ val backwardPositionMs = anchorPositionMs - offsetMs+ if (backwardPositionMs >= 0L) {+ plannedPositions += backwardPositionMs+ }+ }++ if (forwardPositionMs > maxPositionMs && anchorPositionMs - offsetMs < 0L) {+ break+ }+ offsetMs += bucketMs+ }++ return plannedPositions.toList()+}++internal fun shouldStartThumbnailPreload(+ preloadKey: String,+ lastCompletedPreloadKey: String?,+ inFlightPreloadKey: String?+): Boolean = preloadKey.isNotBlank() &&+ preloadKey != lastCompletedPreloadKey &&+ preloadKey != inFlightPreloadKeyfun PlayerViewModel.selectAudioTrack(trackId: String) {playerEngine.selectAudioTrack(trackId)@@ -68,7 +116,6 @@ fun PlayerViewModel.selectLiveVariant(rawChannelId: Long) {) ?: return@launchif (!isActivePlaybackSession(requestVersion, updatedChannel.streamUrl)) return@launchif (currentContentType == ContentType.LIVE) {- recordLivePlayback(updatedChannel)requestEpg(providerId = updatedChannel.providerId,epgChannelId = updatedChannel.epgChannelId,@@ -233,18 +280,30 @@ fun PlayerViewModel.updateSeekPreview(positionMs: Long?) {}internal fun PlayerViewModel.startThumbnailPreload() {- thumbnailPreloadJob?.cancel()val url = currentResolvedPlaybackUrl.ifBlank { currentStreamUrl }if (url.isBlank() || !seekThumbnailProvider.supportsFrameExtraction(url)) return+ if (!shouldStartThumbnailPreload(url, lastCompletedThumbnailPreloadKey, inFlightThumbnailPreloadKey)) returnval durationMs = playerEngine.duration.valueif (durationMs <= 0L) return+ val preloadPositions = buildThumbnailPreloadPositions(+ durationMs = durationMs,+ currentPositionMs = playerEngine.currentPosition.value+ )+ if (preloadPositions.isEmpty()) return++ thumbnailPreloadJob?.cancel()+ inFlightThumbnailPreloadKey = urlthumbnailPreloadJob = viewModelScope.launch(Dispatchers.Default) {- val bucketMs = 10_000L- var pos = 0L- while (pos <= durationMs) {- ensureActive()- seekThumbnailProvider.loadFrame(url, pos)- pos += bucketMs+ try {+ preloadPositions.forEach { positionMs ->+ ensureActive()+ seekThumbnailProvider.loadFrame(url, positionMs)+ }+ lastCompletedThumbnailPreloadKey = url+ } finally {+ if (inFlightThumbnailPreloadKey == url) {+ inFlightThumbnailPreloadKey = null+ }}}}diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerPlaybackUrlSupport.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerPlaybackUrlSupport.ktindex e257062e..01430939 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerPlaybackUrlSupport.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerPlaybackUrlSupport.kt@@ -1,10 +1,39 @@package com.streamvault.app.ui.screens.player+import com.streamvault.domain.model.StreamInfo+internal fun String?.safeTrimmedOrNull(): String? {val value = this ?: return nullreturn value.trim().takeIf { it.isNotEmpty() }}+internal fun resolveTimeshiftStreamInfo(+ streamInfoOverride: StreamInfo?,+ currentResolvedStreamInfo: StreamInfo?,+ currentResolvedPlaybackUrl: String,+ currentStreamUrl: String,+ playbackTitle: String,+ currentTitle: String+): StreamInfo? {+ val resolvedTitle = playbackTitle.ifBlank { currentTitle }+ streamInfoOverride?.let { override ->+ return override.copy(title = override.title ?: resolvedTitle)+ }+ currentResolvedStreamInfo?.let { resolved ->+ val resolvedUrl = resolved.url.safeTrimmedOrNull()+ if (resolvedUrl != null) {+ return resolved.copy(+ url = resolvedUrl,+ title = resolved.title ?: resolvedTitle+ )+ }+ }+ val fallbackUrl = currentResolvedPlaybackUrl.safeTrimmedOrNull()+ ?: currentStreamUrl.safeTrimmedOrNull()+ ?: return null+ return StreamInfo(url = fallbackUrl, title = resolvedTitle)+}+internal fun resolvePlaybackIdentityUrl(currentResolvedPlaybackUrl: String,currentStreamUrl: Stringdiff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerPreparationContextActions.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerPreparationContextActions.ktindex 813a5c13..a7aa0e4a 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerPreparationContextActions.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerPreparationContextActions.kt@@ -116,7 +116,6 @@ internal fun PlayerViewModel.finalizePreparedPlaybackContext(})if (currentContentType == ContentType.LIVE) {- recordLivePlayback(channel)requestEpg(providerId = currentProviderId,epgChannelId = channel.epgChannelId,diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerPreparationSetupActions.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerPreparationSetupActions.ktindex 86244584..58c5da33 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerPreparationSetupActions.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerPreparationSetupActions.kt@@ -3,9 +3,46 @@ package com.streamvault.app.ui.screens.playerimport androidx.lifecycle.viewModelScopeimport com.streamvault.domain.model.ContentTypeimport com.streamvault.domain.model.DecoderMode+import com.streamvault.domain.model.Episodeimport com.streamvault.domain.model.PlayerSurfaceModeimport kotlinx.coroutines.launch+internal data class ResolvedSeriesEpisodeIdentity(+ val seriesId: Long,+ val seasonNumber: Int?,+ val episodeNumber: Int?+)++internal suspend fun resolveSeriesEpisodeIdentity(+ providerId: Long,+ internalChannelId: Long,+ seriesId: Long?,+ seasonNumber: Int?,+ episodeNumber: Int?,+ lookupEpisode: suspend (Long) -> Episode?+): ResolvedSeriesEpisodeIdentity? {+ val normalizedSeriesId = seriesId?.takeIf { it > 0L }+ if (normalizedSeriesId != null) {+ return ResolvedSeriesEpisodeIdentity(+ seriesId = normalizedSeriesId,+ seasonNumber = seasonNumber,+ episodeNumber = episodeNumber+ )+ }+ if (providerId <= 0L || internalChannelId <= 0L) return null++ val persistedEpisode = lookupEpisode(internalChannelId)+ ?.takeIf { it.providerId == providerId }+ ?.takeIf { it.seriesId > 0L }+ ?: return null++ return ResolvedSeriesEpisodeIdentity(+ seriesId = persistedEpisode.seriesId,+ seasonNumber = seasonNumber ?: persistedEpisode.seasonNumber,+ episodeNumber = episodeNumber ?: persistedEpisode.episodeNumber+ )+}+internal fun PlayerViewModel.applyPrepareSessionState(streamUrl: String,internalChannelId: Long,@@ -19,6 +56,7 @@ internal fun PlayerViewModel.applyPrepareSessionState(seriesId: Long?,seasonNumber: Int?,episodeNumber: Int?,+ episodeId: Long?,hasArchiveRequest: Boolean,preferredDecoderMode: DecoderMode,preferredSurfaceMode: PlayerSurfaceMode@@ -37,6 +75,7 @@ internal fun PlayerViewModel.applyPrepareSessionState(clearSeekPreview()currentResolvedPlaybackUrl = ""+ currentResolvedStreamInfo = nullcurrentStreamUrl = streamUrlcurrentContentId = internalChannelIdcurrentTitle = title@@ -53,6 +92,7 @@ internal fun PlayerViewModel.applyPrepareSessionState(currentSeriesId = seriesId?.takeIf { it > 0L }currentSeasonNumber = seasonNumbercurrentEpisodeNumber = episodeNumber+ currentStableEpisodeId = episodeId?.takeIf { it > 0L }val streamClassLabel = if (hasArchiveRequest) "Catch-up" else "Primary"applyDefaultPlaybackTimersIfNeeded()diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerScreen.ktindex d631f973..6edf0f02 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@@ -79,6 +79,7 @@ import com.streamvault.app.MainActivityimport com.streamvault.app.cast.CastConnectionStateimport com.streamvault.app.ui.components.PlayerRenderViewimport com.streamvault.app.ui.design.requestFocusSafely+import com.streamvault.app.ui.notifications.rememberNotificationPermissionGateimport com.streamvault.app.ui.screens.player.overlay.ChannelInfoOverlayimport com.streamvault.app.ui.screens.player.overlay.ChannelVariantSelectionDialogimport com.streamvault.app.ui.screens.player.overlay.CategoryListOverlay@@ -126,6 +127,7 @@ fun PlayerScreen(seriesId: Long? = null,seasonNumber: Int? = null,episodeNumber: Int? = null,+ episodeId: Long? = null,returnRoute: String? = null,onBack: () -> Unit,onNavigate: ((String) -> Unit)? = null,@@ -148,6 +150,11 @@ fun PlayerScreen(400.dp}val mainActivity = LocalContext.current.findMainActivity()+ val notificationPermissionGate = rememberNotificationPermissionGate(+ onNotificationsBlocked = { message -> viewModel.showPlayerNotice(message = message) },+ reminderBlockedMessage = stringResource(R.string.notification_permission_reminder_required),+ recordingBlockedMessage = stringResource(R.string.notification_permission_recording_alert_required)+ )val isInPictureInPictureMode = mainActivity?.pictureInPictureModeFlow?.collectAsState(initial = mainActivity.isInPictureInPictureMode)@@ -388,7 +395,21 @@ fun PlayerScreen()}- LaunchedEffect(streamUrl, epgChannelId, internalChannelId, categoryId, providerId, isVirtual, combinedProfileId, combinedSourceFilterProviderId, contentType, archiveStartMs, archiveEndMs, archiveTitle, seriesId, seasonNumber, episodeNumber) {+ val prepareIdentity = buildPlayerPrepareIdentity(+ streamUrl = streamUrl,+ epgChannelId = epgChannelId,+ internalChannelId = internalChannelId,+ categoryId = categoryId,+ providerId = providerId,+ isVirtual = isVirtual,+ combinedProfileId = combinedProfileId,+ combinedSourceFilterProviderId = combinedSourceFilterProviderId,+ contentType = contentType,+ archiveStartMs = archiveStartMs,+ archiveEndMs = archiveEndMs+ )++ LaunchedEffect(prepareIdentity) {viewModel.prepare(streamUrl = streamUrl,epgChannelId = epgChannelId,@@ -406,6 +427,23 @@ fun PlayerScreen(archiveTitle = archiveTitle,seriesId = seriesId,seasonNumber = seasonNumber,+ episodeNumber = episodeNumber,+ episodeId = episodeId+ )+ }++ LaunchedEffect(title, artworkUrl, archiveTitle, seriesId, seasonNumber, episodeNumber, prepareIdentity) {+ viewModel.updatePreparedRouteMetadata(+ title = title,+ artworkUrl = artworkUrl,+ contentType = contentType,+ providerId = providerId ?: -1L,+ internalChannelId = internalChannelId,+ archiveStartMs = archiveStartMs,+ archiveEndMs = archiveEndMs,+ archiveTitle = archiveTitle,+ seriesId = seriesId,+ seasonNumber = seasonNumber,episodeNumber = episodeNumber)}@@ -958,11 +996,27 @@ fun PlayerScreen(onSeekForward = viewModel::seekForward,onRestartProgram = viewModel::restartCurrentProgram,onOpenArchive = { showProgramHistory = true },- onStartRecording = viewModel::startManualRecording,+ onStartRecording = {+ notificationPermissionGate.runRecordingAction {+ viewModel.startManualRecording()+ }+ },onStopRecording = viewModel::stopCurrentRecording,- onScheduleRecording = viewModel::scheduleRecording,- onScheduleDailyRecording = viewModel::scheduleDailyRecording,- onScheduleWeeklyRecording = viewModel::scheduleWeeklyRecording,+ onScheduleRecording = {+ notificationPermissionGate.runRecordingAction {+ viewModel.scheduleRecording()+ }+ },+ onScheduleDailyRecording = {+ notificationPermissionGate.runRecordingAction {+ viewModel.scheduleDailyRecording()+ }+ },+ onScheduleWeeklyRecording = {+ notificationPermissionGate.runRecordingAction {+ viewModel.scheduleWeeklyRecording()+ }+ },onToggleAspectRatio = viewModel::toggleAspectRatio,onOpenSubtitleTracks = { showTrackSelection = TrackType.TEXT },onOpenAudioTracks = { showTrackSelection = TrackType.AUDIO },@@ -1236,11 +1290,27 @@ fun PlayerScreen(viewModel.openLastVisitedCategory()},currentRecordingStatus = currentChannelRecording?.status,- onStartRecording = viewModel::startManualRecording,+ onStartRecording = {+ notificationPermissionGate.runRecordingAction {+ viewModel.startManualRecording()+ }+ },onStopRecording = viewModel::stopCurrentRecording,- onScheduleRecording = viewModel::scheduleRecording,- onScheduleDailyRecording = viewModel::scheduleDailyRecording,- onScheduleWeeklyRecording = viewModel::scheduleWeeklyRecording,+ onScheduleRecording = {+ notificationPermissionGate.runRecordingAction {+ viewModel.scheduleRecording()+ }+ },+ onScheduleDailyRecording = {+ notificationPermissionGate.runRecordingAction {+ viewModel.scheduleDailyRecording()+ }+ },+ onScheduleWeeklyRecording = {+ notificationPermissionGate.runRecordingAction {+ viewModel.scheduleWeeklyRecording()+ }+ },onRestartProgram = { viewModel.restartCurrentProgram() },onOpenArchive = { showProgramHistory = true },onToggleAspectRatio = { viewModel.toggleAspectRatio() },diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModel.ktindex 30ab9e87..8d83ad32 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@@ -236,8 +236,10 @@ class PlayerViewModel @Inject constructor(private var currentStreamClassLabel: String = "Primary"internal var lastRecordedVariantObservationSignature: String? = nullinternal var prepareRequestVersion: Long = 0L+ internal var readySideEffectsRequestVersion: Long? = nullinternal var currentArtworkUrl: String? = nullinternal var currentResolvedPlaybackUrl: String = ""+ internal var currentResolvedStreamInfo: StreamInfo? = nullinternal var pendingCatchUpUrls: List<String> = emptyList()internal var channelNumberingMode: ChannelNumberingMode = ChannelNumberingMode.GROUPset(value) {@@ -291,6 +293,7 @@ class PlayerViewModel @Inject constructor(internal var currentSeriesId: Long? = nullinternal var currentSeasonNumber: Int? = nullinternal var currentEpisodeNumber: Int? = null+ internal var currentStableEpisodeId: Long? = nullinternal var isVirtualCategory: Boolean = falseinternal var currentCombinedProfileMembers: List<CombinedM3uProfileMember> = emptyList()internal var combinedCategoriesById: Map<Long, CombinedCategory> = emptyMap()@@ -303,6 +306,8 @@ class PlayerViewModel @Inject constructor(internal var controlsHideJob: Job? = nullinternal var seekPreviewJob: Job? = nullinternal var thumbnailPreloadJob: Job? = null+ internal var inFlightThumbnailPreloadKey: String? = null+ internal var lastCompletedThumbnailPreloadKey: String? = nullprivate var lowBandwidthMonitorJob: Job? = nullinternal var progressTrackingJob: Job? = nullinternal var tokenRenewalJob: Job? = null@@ -388,9 +393,14 @@ class PlayerViewModel @Inject constructor(playerEngine.stopLiveTimeshift()return}- val resolvedCandidate = currentResolvedPlaybackUrl.safeTrimmedOrNull()- val currentCandidate = currentStreamUrl.safeTrimmedOrNull()- val fallbackUrl = resolvedCandidate ?: currentCandidate ?: run {+ val streamInfo = resolveTimeshiftStreamInfo(+ streamInfoOverride = streamInfoOverride,+ currentResolvedStreamInfo = currentResolvedStreamInfo,+ currentResolvedPlaybackUrl = currentResolvedPlaybackUrl,+ currentStreamUrl = currentStreamUrl,+ playbackTitle = playbackTitleFlow.value,+ currentTitle = currentTitle+ ) ?: run {playerEngine.stopLiveTimeshift()_timeshiftUiState.update {it.copy(@@ -401,10 +411,7 @@ class PlayerViewModel @Inject constructor(}return}- val streamInfo = streamInfoOverride ?: StreamInfo(- url = fallbackUrl,- title = playbackTitleFlow.value.ifBlank { currentTitle }- )+ val fallbackUrl = streamInfo.urlval channelKey = currentChannel.value?.id?.toString()?: currentContentId.takeIf { it > 0L }?.toString()?: fallbackUrl@@ -434,10 +441,11 @@ class PlayerViewModel @Inject constructor(handlePlaybackEnded()}lastObservedPlaybackState = state- if (state == PlaybackState.READY) {+ if (state == PlaybackState.READY && readySideEffectsRequestVersion == prepareRequestVersion) {zapBufferWatchdogJob?.cancel()dismissRecoveredNoticeIfPresent()if (currentContentType == ContentType.LIVE) {+ recordActiveLivePlayback()currentChannelFlow.value?.sanitizedForPlayer()?.let { channel ->if (channel.errorCount > 0) {logRepositoryFailure(@@ -851,6 +859,8 @@ class PlayerViewModel @Inject constructor(thumbnailPreloadJob?.cancel()hasRetriedXtreamAuthRefresh = falselastRecordedVariantObservationSignature = null+ readySideEffectsRequestVersion = null+ playerEngine.setScrubbingMode(false)return ++prepareRequestVersion}@@ -858,6 +868,7 @@ class PlayerViewModel @Inject constructor(currentSeriesId = nullcurrentSeasonNumber = nullcurrentEpisodeNumber = null+ currentStableEpisodeId = null_currentSeries.value = null_currentEpisode.value = null_nextEpisode.value = null@@ -894,6 +905,11 @@ class PlayerViewModel @Inject constructor(currentArtworkUrl = resolution.resolvedArtworkUrlcurrentTitle = resolution.resolvedTitle ?: currentTitleplaybackTitleFlow.value = currentTitle+ resolution.resolvedEpisode.id.takeIf { it > 0L }?.let { resolvedId ->+ if (currentContentId != resolvedId) {+ currentContentId = resolvedId+ }+ }}resolution.resolvedEpisode}@@ -1006,6 +1022,8 @@ class PlayerViewModel @Inject constructor(val adoptedEngine = session.enginereturn runCatching {+ // Detach the Home preview surface before Player binds its own.+ adoptedEngine.clearRenderBinding()// Media3 requires a globally unique session ID. Release the main engine's// session before the adopted live engine enables its own replacement.mainPlayerEngine.setMediaSessionEnabled(false)@@ -1022,6 +1040,8 @@ class PlayerViewModel @Inject constructor(false} else {currentResolvedPlaybackUrl = session.streamInfo.url+ currentResolvedStreamInfo = session.streamInfo+ readySideEffectsRequestVersion = requestVersionprobePassedPlaybackKeys.add(resolvePlaybackProbeCacheKey(currentStreamUrl = currentStreamUrl,@@ -1084,6 +1104,8 @@ class PlayerViewModel @Inject constructor(applyPlaybackPreferences()if (!isActivePlaybackSession(requestVersion)) return falsecurrentResolvedPlaybackUrl = streamInfo.url+ currentResolvedStreamInfo = streamInfo+ readySideEffectsRequestVersion = requestVersionplayerEngine.prepare(streamInfo)startTokenRenewalMonitoring(streamInfo.expirationTime)return true@@ -1149,13 +1171,14 @@ class PlayerViewModel @Inject constructor(seriesId: Long? = null,seasonNumber: Int? = null,episodeNumber: Int? = null,+ episodeId: Long? = null,showResumePrompt: Boolean = true) {- val hasArchiveRequest = archiveStartMs != null &&- archiveEndMs != null &&- archiveStartMs > 0L &&- archiveEndMs > archiveStartMs &&- try { ContentType.valueOf(contentType) } catch (e: Exception) { ContentType.LIVE } == ContentType.LIVE+ val hasArchiveRequest = hasArchivePlaybackIdentity(+ contentType = contentType,+ archiveStartMs = archiveStartMs,+ archiveEndMs = archiveEndMs+ )val requestVersion = beginPlaybackSession()val shouldReloadPlaylist = applyPrepareSessionState(streamUrl = streamUrl,@@ -1170,6 +1193,7 @@ class PlayerViewModel @Inject constructor(seriesId = seriesId,seasonNumber = seasonNumber,episodeNumber = episodeNumber,+ episodeId = episodeId,hasArchiveRequest = hasArchiveRequest,preferredDecoderMode = preferredDecoderMode,preferredSurfaceMode = preferredSurfaceMode@@ -1191,7 +1215,7 @@ class PlayerViewModel @Inject constructor(requestVersion = requestVersion,providerId = providerId,seriesId = currentSeriesId ?: -1L,- episodeId = internalChannelId,+ episodeId = currentStableEpisodeId?.takeIf { it > 0 } ?: internalChannelId,seasonNumber = seasonNumber,episodeNumber = episodeNumber)@@ -1208,7 +1232,7 @@ class PlayerViewModel @Inject constructor(requestVersion = requestVersion,providerId = providerId,seriesId = currentSeriesId ?: -1L,- episodeId = internalChannelId,+ episodeId = currentStableEpisodeId?.takeIf { it > 0 } ?: internalChannelId,seasonNumber = seasonNumber,episodeNumber = episodeNumber)@@ -1236,7 +1260,14 @@ class PlayerViewModel @Inject constructor(// Doing this after preparePlayer ensures pause() acts on the live player instance,// not a stale one that may have already been replaced by prepareInternal().if (showResumePrompt && currentContentType != ContentType.LIVE && currentContentId != -1L && currentProviderId != -1L) {- val history = playbackHistoryRepository.getPlaybackHistory(currentContentId, currentContentType, currentProviderId)+ val history = playbackHistoryRepository.getPlaybackHistory(+ contentId = currentContentId,+ contentType = currentContentType,+ providerId = currentProviderId,+ seriesId = currentSeriesId,+ seasonNumber = currentSeasonNumber,+ episodeNumber = currentEpisodeNumber+ )if (isActivePlaybackSession(requestVersion, playbackLogicalUrl)) {if (history != null && history.resumePositionMs > 5000L && !isPlaybackComplete(history.resumePositionMs, history.totalDurationMs)) {playerEngine.pause()@@ -1291,6 +1322,69 @@ class PlayerViewModel @Inject constructor()}+ fun updatePreparedRouteMetadata(+ title: String,+ artworkUrl: String?,+ contentType: String,+ providerId: Long,+ internalChannelId: Long,+ archiveStartMs: Long?,+ archiveEndMs: Long?,+ archiveTitle: String?,+ seriesId: Long?,+ seasonNumber: Int?,+ episodeNumber: Int?+ ) {+ currentTitle = resolveRouteDisplayTitle(+ title = title,+ contentType = contentType,+ archiveStartMs = archiveStartMs,+ archiveEndMs = archiveEndMs,+ archiveTitle = archiveTitle+ )+ playbackTitleFlow.value = currentTitle+ currentArtworkUrl = artworkUrl++ if (prepareRequestVersion <= 0L) return++ val normalizedSeriesId = seriesId?.takeIf { it > 0L }+ val resolvedContentType = try {+ ContentType.valueOf(contentType)+ } catch (_: Exception) {+ ContentType.LIVE+ }+ if (resolvedContentType != ContentType.SERIES_EPISODE || providerId <= 0L || internalChannelId <= 0L) {+ return+ }++ val requestVersion = prepareRequestVersion+ viewModelScope.launch {+ val identity = resolveSeriesEpisodeIdentity(+ providerId = providerId,+ internalChannelId = internalChannelId,+ seriesId = normalizedSeriesId,+ seasonNumber = seasonNumber,+ episodeNumber = episodeNumber,+ lookupEpisode = seriesRepository::getEpisodeById+ ) ?: return@launch+ if (+ identity.seriesId == currentSeriesId &&+ identity.seasonNumber == currentSeasonNumber &&+ identity.episodeNumber == currentEpisodeNumber+ ) {+ return@launch+ }+ loadSeriesEpisodeContext(+ requestVersion = requestVersion,+ providerId = providerId,+ seriesId = identity.seriesId,+ episodeId = internalChannelId,+ seasonNumber = identity.seasonNumber,+ episodeNumber = identity.episodeNumber+ )+ }+ }+internal fun applyProgramTimeline(programs: List<Program>, now: Long) {val timeline = buildProgramTimeline(programs = programs,diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModelModels.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModelModels.ktindex caf5edcd..4080b64f 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModelModels.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModelModels.kt@@ -3,6 +3,7 @@ package com.streamvault.app.ui.screens.playerimport android.graphics.Bitmapimport com.streamvault.domain.model.Channelimport com.streamvault.domain.model.ChannelQualityOption+import com.streamvault.domain.model.ContentTypeimport com.streamvault.domain.model.Episodeimport com.streamvault.domain.model.Seasonimport com.streamvault.domain.model.Series@@ -103,6 +104,78 @@ data class AutoPlayCountdownUiState(val secondsRemaining: Int)+data class PlayerPrepareIdentity(+ val streamUrl: String,+ val epgChannelId: String?,+ val internalChannelId: Long,+ val categoryId: Long,+ val providerId: Long,+ val isVirtual: Boolean,+ val combinedProfileId: Long?,+ val combinedSourceFilterProviderId: Long?,+ val contentType: String,+ val archiveStartMs: Long?,+ val archiveEndMs: Long?+)++internal fun buildPlayerPrepareIdentity(+ streamUrl: String,+ epgChannelId: String?,+ internalChannelId: Long,+ categoryId: Long?,+ providerId: Long?,+ isVirtual: Boolean,+ combinedProfileId: Long?,+ combinedSourceFilterProviderId: Long?,+ contentType: String,+ archiveStartMs: Long?,+ archiveEndMs: Long?+): PlayerPrepareIdentity = PlayerPrepareIdentity(+ streamUrl = streamUrl,+ epgChannelId = epgChannelId,+ internalChannelId = internalChannelId,+ categoryId = categoryId?.takeIf { it > 0L } ?: -1L,+ providerId = providerId?.takeIf { it > 0L } ?: -1L,+ isVirtual = isVirtual,+ combinedProfileId = combinedProfileId?.takeIf { it > 0L },+ combinedSourceFilterProviderId = combinedSourceFilterProviderId?.takeIf { it > 0L },+ contentType = contentType,+ archiveStartMs = archiveStartMs,+ archiveEndMs = archiveEndMs+)++internal fun hasArchivePlaybackIdentity(+ contentType: String,+ archiveStartMs: Long?,+ archiveEndMs: Long?+): Boolean = archiveStartMs != null &&+ archiveEndMs != null &&+ archiveStartMs > 0L &&+ archiveEndMs > archiveStartMs &&+ try {+ ContentType.valueOf(contentType)+ } catch (_: Exception) {+ ContentType.LIVE+ } == ContentType.LIVE++internal fun resolveRouteDisplayTitle(+ title: String,+ contentType: String,+ archiveStartMs: Long?,+ archiveEndMs: Long?,+ archiveTitle: String?+): String = if (+ hasArchivePlaybackIdentity(+ contentType = contentType,+ archiveStartMs = archiveStartMs,+ archiveEndMs = archiveEndMs+ )+) {+ archiveTitle?.takeIf { it.isNotBlank() } ?: title+} else {+ title+}+enum class PlayerRecoveryType {NETWORK,SOURCE,diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerZapActions.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerZapActions.ktindex 9233a303..ca5daebf 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerZapActions.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerZapActions.kt@@ -1,13 +1,14 @@package com.streamvault.app.ui.screens.playerimport androidx.lifecycle.viewModelScope+import com.streamvault.domain.model.Channelimport com.streamvault.domain.model.ChannelNumberingModeimport com.streamvault.domain.model.ContentTypeimport com.streamvault.domain.model.PlaybackHistoryimport kotlinx.coroutines.delayimport kotlinx.coroutines.flow.updateimport kotlinx.coroutines.flow.filter-import kotlinx.coroutines.flow.take+import kotlinx.coroutines.flow.firstimport kotlinx.coroutines.launchinternal const val MAX_NUMERIC_CHANNEL_INPUT_DIGITS = 6@@ -21,6 +22,63 @@ internal fun appendNumericChannelDigit(currentBuffer: String, digit: Int): Strin}}+internal data class LivePlaybackRecordCandidate(+ val playbackKey: Pair<Long, Long>,+ val history: PlaybackHistory+)++internal fun buildLivePlaybackRecordCandidate(+ currentProviderId: Long,+ currentContentType: ContentType,+ currentContentId: Long,+ currentTitle: String,+ currentResolvedPlaybackUrl: String,+ currentStreamUrl: String,+ channel: Channel?+): LivePlaybackRecordCandidate? {+ if (currentProviderId <= 0L || currentContentType != ContentType.LIVE) return null++ channel?.let {+ return LivePlaybackRecordCandidate(+ playbackKey = currentProviderId to it.id,+ history = PlaybackHistory(+ contentId = it.id,+ contentType = ContentType.LIVE,+ providerId = currentProviderId,+ title = it.name,+ streamUrl = it.streamUrl,+ lastWatchedAt = System.currentTimeMillis()+ )+ )+ }++ val contentId = currentContentId.takeIf { it > 0L } ?: return null+ val streamUrl = currentResolvedPlaybackUrl.ifBlank { currentStreamUrl }.takeIf { it.isNotBlank() } ?: return null+ return LivePlaybackRecordCandidate(+ playbackKey = currentProviderId to contentId,+ history = PlaybackHistory(+ contentId = contentId,+ contentType = ContentType.LIVE,+ providerId = currentProviderId,+ title = currentTitle,+ streamUrl = streamUrl,+ lastWatchedAt = System.currentTimeMillis()+ )+ )+}++internal suspend fun <T> withScopedScrubbingMode(+ setScrubbingMode: (Boolean) -> Unit,+ block: suspend () -> T+): T {+ setScrubbingMode(true)+ return try {+ block()+ } finally {+ setScrubbingMode(false)+ }+}+fun PlayerViewModel.playNext() {clearNumericChannelInput()if (channelList.isEmpty()) return@@ -144,23 +202,21 @@ internal fun PlayerViewModel.changeChannel(index: Int, isAutoFallback: Boolean =displayChannelNumberFlow.value = resolveChannelNumber(channel, index)recentChannelsFlow.update { channels -> channels.filterNot { it.id == channel.id } }- playerEngine.setScrubbingMode(true)-viewModelScope.launch {- val streamInfo = resolvePlaybackStreamInfo(channel.streamUrl, channel.id, channel.providerId, ContentType.LIVE)- ?: return@launch- if (!isActivePlaybackSession(requestVersion, channel.streamUrl)) return@launch- if (!preparePlayer(streamInfo, requestVersion)) return@launch- playerEngine.play()-- playerEngine.playbackState- .filter { it == com.streamvault.player.PlaybackState.READY }- .take(1)- .collect {- if (isActivePlaybackSession(requestVersion, channel.streamUrl)) {- playerEngine.setScrubbingMode(false)+ withScopedScrubbingMode(playerEngine::setScrubbingMode) {+ val streamInfo = resolvePlaybackStreamInfo(channel.streamUrl, channel.id, channel.providerId, ContentType.LIVE)+ ?: return@withScopedScrubbingMode+ if (!isActivePlaybackSession(requestVersion, channel.streamUrl)) return@withScopedScrubbingMode+ if (!preparePlayer(streamInfo, requestVersion)) return@withScopedScrubbingMode+ playerEngine.play()++ playerEngine.playbackState+ .filter {+ it == com.streamvault.player.PlaybackState.READY ||+ !isActivePlaybackSession(requestVersion, channel.streamUrl)}- }+ .first()+ }}preloadAdjacentChannel(index)@@ -178,10 +234,7 @@ internal fun PlayerViewModel.changeChannel(index: Int, isAutoFallback: Boolean =triedAlternativeStreams.clear()triedAlternativeStreams.add(channel.streamUrl)- if (currentContentType == ContentType.LIVE) {- recordLivePlayback(channel)- if (!isAutoFallback) scheduleZapBufferWatchdog(index)- }+ if (currentContentType == ContentType.LIVE && !isAutoFallback) scheduleZapBufferWatchdog(index)}internal fun PlayerViewModel.preloadAdjacentChannel(currentIndex: Int) {@@ -200,25 +253,27 @@ internal fun PlayerViewModel.preloadAdjacentChannel(currentIndex: Int) {}internal fun PlayerViewModel.recordLivePlayback(channel: com.streamvault.domain.model.Channel) {- if (currentProviderId <= 0 || currentContentType != ContentType.LIVE) return+ recordActiveLivePlayback(channel)+}- val playbackKey = currentProviderId to channel.id- if (lastRecordedLivePlaybackKey == playbackKey) return- lastRecordedLivePlaybackKey = playbackKey+internal fun PlayerViewModel.recordActiveLivePlayback(channel: Channel? = currentChannelFlow.value?.sanitizedForPlayer()) {+ val candidate = buildLivePlaybackRecordCandidate(+ currentProviderId = currentProviderId,+ currentContentType = currentContentType,+ currentContentId = currentContentId,+ currentTitle = currentTitle,+ currentResolvedPlaybackUrl = currentResolvedPlaybackUrl,+ currentStreamUrl = currentStreamUrl,+ channel = channel+ ) ?: return++ if (lastRecordedLivePlaybackKey == candidate.playbackKey) return+ lastRecordedLivePlaybackKey = candidate.playbackKeyviewModelScope.launch {logRepositoryFailure(operation = "Record live playback",- result = playbackHistoryRepository.recordPlayback(- PlaybackHistory(- contentId = channel.id,- contentType = ContentType.LIVE,- providerId = currentProviderId,- title = channel.name,- streamUrl = channel.streamUrl,- lastWatchedAt = System.currentTimeMillis()- )- )+ result = playbackHistoryRepository.recordPlayback(candidate.history))}}diff --git a/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupScreen.ktindex 4b371b61..9d899d7b 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@@ -65,6 +65,7 @@ import com.streamvault.app.device.rememberIsTelevisionDeviceimport com.streamvault.app.ui.components.dialogs.PremiumDialogimport com.streamvault.app.ui.components.dialogs.PremiumDialogFooterButtonimport com.streamvault.app.ui.components.shell.StatusPill+import com.streamvault.app.ui.screens.settings.BackupImportPreviewDialogimport com.streamvault.app.ui.theme.*import com.streamvault.data.util.ProviderInputSanitizerimport com.streamvault.domain.model.ProviderEpgSyncMode@@ -156,6 +157,10 @@ fun ProviderSetupScreen(contract = ActivityResultContracts.OpenDocument()) { uri: android.net.Uri? -> if (uri != null) importM3uUri(uri) }+ val backupImportLauncher = rememberLauncherForActivityResult(+ contract = ActivityResultContracts.OpenDocument()+ ) { uri: android.net.Uri? -> uri?.let { viewModel.inspectBackup(it.toString()) } }+// ?? Effects ???????????????????????????????????????????????????????????????LaunchedEffect(knownLocalM3uUrls) {cleanupOldImportedM3uFilesAsync(context.filesDir, knownLocalM3uUrls, 20)@@ -170,8 +175,8 @@ fun ProviderSetupScreen(runCatching { android.net.Uri.parse(importUri) }.getOrNull()?.let(::importM3uUri)}- LaunchedEffect(uiState.loginSuccess) {- if (uiState.loginSuccess) {+ LaunchedEffect(uiState.loginSuccess, uiState.completionWarning) {+ if (uiState.loginSuccess && uiState.completionWarning == null) {val previousLocal = uiState.m3uUrl.takeIf { it.startsWith("file://") }val selectedLocal = m3uUrl.takeIf { it.startsWith("file://") }val protectedUris = buildSet {@@ -185,6 +190,25 @@ fun ProviderSetupScreen(}}+ LaunchedEffect(uiState.backupImportSuccess) {+ if (uiState.backupImportSuccess) {+ onProviderAdded()+ }+ }++ if (uiState.loginSuccess && uiState.completionWarning != null) {+ androidx.compose.material3.AlertDialog(+ onDismissRequest = { viewModel.dismissCompletionWarning() },+ title = { Text("Provider Saved") },+ text = { Text(uiState.completionWarning ?: "") },+ confirmButton = {+ TextButton(onClick = { viewModel.dismissCompletionWarning() }) {+ Text("Continue", color = Primary)+ }+ }+ )+ }+if (uiState.pendingCombinedAttachProfileId != null) {androidx.compose.material3.AlertDialog(onDismissRequest = { viewModel.skipCreatedProviderCombinedAttach() },@@ -332,6 +356,9 @@ fun ProviderSetupScreen(onToggleFastSync = { viewModel.updateXtreamFastSyncEnabled(!uiState.xtreamFastSyncEnabled) },onToggleM3uVodClassification = { viewModel.updateM3uVodClassificationEnabled(!uiState.m3uVodClassificationEnabled) },onSelectEpgSyncMode = viewModel::updateEpgSyncMode,+ showImportBackupButton = !uiState.isEditing,+ isImportingBackup = uiState.isImportingBackup || uiState.syncProgress != null,+ onImportBackup = { backupImportLauncher.launch(arrayOf("application/json")) },modifier = Modifier.weight(1f).fillMaxHeight())}@@ -366,6 +393,9 @@ fun ProviderSetupScreen(onToggleFastSync = { viewModel.updateXtreamFastSyncEnabled(!uiState.xtreamFastSyncEnabled) },onToggleM3uVodClassification = { viewModel.updateM3uVodClassificationEnabled(!uiState.m3uVodClassificationEnabled) },onSelectEpgSyncMode = viewModel::updateEpgSyncMode,+ showImportBackupButton = !uiState.isEditing,+ isImportingBackup = uiState.isImportingBackup || uiState.syncProgress != null,+ onImportBackup = { backupImportLauncher.launch(arrayOf("application/json")) },modifier = Modifier.weight(1f).fillMaxWidth())}@@ -377,6 +407,24 @@ fun ProviderSetupScreen(SyncProgressDialog(message = uiState.syncProgress!!)}+ val backupPreview = uiState.backupPreview+ if (backupPreview != null && uiState.pendingBackupUri != null) {+ BackupImportPreviewDialog(+ preview = backupPreview,+ plan = uiState.backupImportPlan,+ onDismiss = { viewModel.dismissBackupPreview() },+ onStrategySelected = { viewModel.setBackupConflictStrategy(it) },+ onImportPreferencesChanged = { viewModel.setImportPreferences(it) },+ onImportProvidersChanged = { viewModel.setImportProviders(it) },+ onImportSavedLibraryChanged = { viewModel.setImportSavedLibrary(it) },+ onImportPlaybackHistoryChanged = { viewModel.setImportPlaybackHistory(it) },+ onImportMultiViewChanged = { viewModel.setImportMultiViewPresets(it) },+ onImportRecordingSchedulesChanged = { viewModel.setImportRecordingSchedules(it) },+ isImporting = uiState.isImportingBackup,+ onConfirm = { viewModel.confirmBackupImport() }+ )+ }+if (showDiscardDraftDialog) {PremiumDialog(title = stringResource(R.string.setup_discard_draft_title),@@ -425,6 +473,9 @@ private fun ProviderFormContent(onToggleFastSync: () -> Unit,onToggleM3uVodClassification: () -> Unit,onSelectEpgSyncMode: (ProviderEpgSyncMode) -> Unit,+ showImportBackupButton: Boolean,+ isImportingBackup: Boolean,+ onImportBackup: () -> Unit,modifier: Modifier = Modifier) {val scrollState = rememberScrollState()@@ -624,6 +675,13 @@ private fun ProviderFormContent()}}+ if (showImportBackupButton) {+ SmallActionButton(+ text = androidx.compose.ui.res.stringResource(R.string.setup_import_backup),+ isLoading = isImportingBackup,+ onClick = onImportBackup+ )+ }}}}@@ -982,7 +1040,6 @@ private fun SourceTypeSelectorPanel(style = MaterialTheme.typography.bodySmall,color = OnSurfaceDim)- Spacer(modifier = Modifier.height(4.dp))Text(text = androidx.compose.ui.res.stringResource(R.string.setup_source_type_label),style = MaterialTheme.typography.labelSmall,@@ -1452,6 +1509,7 @@ fun SyncProgressDialog(message: String) {subtitle = androidx.compose.ui.res.stringResource(R.string.settings_syncing_subtitle),onDismissRequest = {},widthFraction = 0.32f,+ heightFraction = null,content = {Column(modifier = Modifier.fillMaxWidth(),@@ -1481,6 +1539,35 @@ private fun ActionButton(text: String,isLoading: Boolean = false,onClick: () -> Unit+) {+ ProviderActionButton(+ text = text,+ height = 52.dp,+ isLoading = isLoading,+ onClick = onClick+ )+}++@Composable+private fun SmallActionButton(+ text: String,+ isLoading: Boolean = false,+ onClick: () -> Unit+) {+ ProviderActionButton(+ text = text,+ height = 40.dp,+ isLoading = isLoading,+ onClick = onClick+ )+}++@Composable+private fun ProviderActionButton(+ text: String,+ height: androidx.compose.ui.unit.Dp,+ isLoading: Boolean = false,+ onClick: () -> Unit) {var isFocused by remember { mutableStateOf(false) }val scale by animateFloatAsState(if (isFocused) 1.03f else 1f, tween(150), label = "scale")@@ -1489,7 +1576,7 @@ private fun ActionButton(onClick = { if (!isLoading) onClick() },modifier = Modifier.fillMaxWidth()- .height(52.dp)+ .height(height).scale(scale).onFocusEvent { isFocused = it.hasFocus }.mouseClickable(enabled = !isLoading, onClick = onClick),@@ -1626,7 +1713,10 @@ private fun cleanupOldImportedM3uFiles(.toSet()val importedFiles = filesDir- .listFiles { file -> file.isFile && file.name.startsWith("m3u_") && file.name.endsWith(".m3u") }+ .listFiles { file ->+ file.isFile && file.name.startsWith("m3u_") &&+ (file.name.endsWith(".m3u") || file.name.endsWith(".m3u8"))+ }?.sortedByDescending { it.lastModified() }?: returndiff --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.ktindex ad4a7faf..abe3313d 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@@ -8,11 +8,19 @@ import com.streamvault.data.remote.xtream.XtreamParsingExceptionimport com.streamvault.data.remote.xtream.XtreamRequestExceptionimport com.streamvault.data.remote.xtream.XtreamResponseTooLargeExceptionimport com.streamvault.data.security.CredentialDecryptionException+import com.streamvault.domain.manager.BackupConflictStrategy+import com.streamvault.domain.manager.BackupImportPlan+import com.streamvault.domain.manager.BackupPreviewimport com.streamvault.domain.model.ActiveLiveSourceimport com.streamvault.domain.model.ProviderEpgSyncModeimport com.streamvault.domain.model.ProviderTypeimport com.streamvault.domain.repository.CombinedM3uRepositoryimport com.streamvault.domain.repository.ProviderRepository+import com.streamvault.domain.usecase.ImportBackup+import com.streamvault.domain.usecase.ImportBackupCommand+import com.streamvault.domain.usecase.ImportBackupResult+import com.streamvault.domain.usecase.InspectBackupCommand+import com.streamvault.domain.usecase.InspectBackupResultimport com.streamvault.domain.usecase.M3uProviderSetupCommandimport com.streamvault.domain.usecase.StalkerProviderSetupCommandimport com.streamvault.domain.usecase.ValidateAndAddProvider@@ -39,7 +47,8 @@ import javax.net.ssl.SSLPeerUnverifiedExceptionclass ProviderSetupViewModel @Inject constructor(private val providerRepository: ProviderRepository,private val combinedM3uRepository: CombinedM3uRepository,- private val validateAndAddProvider: ValidateAndAddProvider+ private val validateAndAddProvider: ValidateAndAddProvider,+ private val importBackup: ImportBackup) : ViewModel() {enum class SetupSourceType {@@ -141,7 +150,7 @@ class ProviderSetupViewModel @Inject constructor(timezone: String,locale: String) {- _uiState.update { it.copy(validationError = null, error = null) }+ _uiState.update { it.copy(validationError = null, error = null, completionWarning = null) }viewModelScope.launch {_uiState.update { it.copy(isLoading = true, validationError = null, syncProgress = "Connecting...") }@@ -172,6 +181,19 @@ class ProviderSetupViewModel @Inject constructor()}}+ is ValidateAndAddProviderResult.SavedWithWarning -> {+ _uiState.update {+ it.copy(+ isLoading = false,+ loginSuccess = true,+ createdProviderId = result.provider.id,+ error = null,+ validationError = null,+ completionWarning = result.warning,+ syncProgress = null+ )+ }+ }is ValidateAndAddProviderResult.ValidationError -> {_uiState.update {it.copy(isLoading = false, validationError = result.message, error = null, syncProgress = null)@@ -181,7 +203,7 @@ class ProviderSetupViewModel @Inject constructor(_uiState.update {it.copy(isLoading = false,- error = result.message,+ error = mapStalkerLoginError(result),validationError = null,syncProgress = null)@@ -192,7 +214,7 @@ class ProviderSetupViewModel @Inject constructor(}fun loginXtream(serverUrl: String, username: String, password: String, name: String) {- _uiState.update { it.copy(validationError = null, error = null) }+ _uiState.update { it.copy(validationError = null, error = null, completionWarning = null) }viewModelScope.launch {_uiState.update { it.copy(isLoading = true, validationError = null, syncProgress = "Connecting...") }@@ -222,6 +244,19 @@ class ProviderSetupViewModel @Inject constructor()}}+ is ValidateAndAddProviderResult.SavedWithWarning -> {+ _uiState.update {+ it.copy(+ isLoading = false,+ loginSuccess = true,+ createdProviderId = result.provider.id,+ error = null,+ validationError = null,+ completionWarning = result.warning,+ syncProgress = null+ )+ }+ }is ValidateAndAddProviderResult.ValidationError -> {_uiState.update {it.copy(isLoading = false, validationError = result.message, error = null, syncProgress = null)@@ -242,7 +277,7 @@ class ProviderSetupViewModel @Inject constructor(}fun addM3u(url: String, name: String) {- _uiState.update { it.copy(validationError = null, error = null) }+ _uiState.update { it.copy(validationError = null, error = null, completionWarning = null) }if (url.isBlank()) {_uiState.update {@@ -266,8 +301,15 @@ class ProviderSetupViewModel @Inject constructor(onProgress = { msg -> _uiState.update { it.copy(syncProgress = msg) } })) {is ValidateAndAddProviderResult.Success -> {- val activeCombinedProfileId = (combinedM3uRepository.getActiveLiveSource().first()- as? ActiveLiveSource.CombinedM3uSource)?.profileId+ // Only prompt to attach to the active combined profile for newly created+ // providers; edits should never re-trigger the attach dialog because the+ // decision was already made when the provider was first onboarded.+ val activeCombinedProfileId = if (existingId == null) {+ (combinedM3uRepository.getActiveLiveSource().first()+ as? ActiveLiveSource.CombinedM3uSource)?.profileId+ } else {+ null+ }val activeCombinedProfileName = activeCombinedProfileId?.let { profileId ->combinedM3uRepository.getProfile(profileId)?.name}@@ -285,6 +327,32 @@ class ProviderSetupViewModel @Inject constructor()}}+ is ValidateAndAddProviderResult.SavedWithWarning -> {+ // Same combined-attach guard: only for new providers, not edits.+ val activeCombinedProfileId = if (existingId == null) {+ (combinedM3uRepository.getActiveLiveSource().first()+ as? ActiveLiveSource.CombinedM3uSource)?.profileId+ } else {+ null+ }+ val activeCombinedProfileName = activeCombinedProfileId?.let { profileId ->+ combinedM3uRepository.getProfile(profileId)?.name+ }+ _uiState.update {+ it.copy(+ isLoading = false,+ loginSuccess = activeCombinedProfileId == null,+ createdProviderId = result.provider.id,+ createdProviderName = result.provider.name,+ pendingCombinedAttachProfileId = activeCombinedProfileId,+ pendingCombinedAttachProfileName = activeCombinedProfileName,+ error = null,+ validationError = null,+ completionWarning = result.warning,+ syncProgress = null+ )+ }+ }is ValidateAndAddProviderResult.ValidationError -> {_uiState.update {it.copy(isLoading = false, validationError = result.message, error = null, syncProgress = null)@@ -294,7 +362,7 @@ class ProviderSetupViewModel @Inject constructor(_uiState.update {it.copy(isLoading = false,- error = "Could not validate playlist: ${result.message}",+ error = mapM3uSetupError(result),validationError = null,syncProgress = null)@@ -304,6 +372,121 @@ class ProviderSetupViewModel @Inject constructor(}}+ fun inspectBackup(uriString: String) {+ viewModelScope.launch {+ _uiState.update {+ it.copy(+ syncProgress = "Reading backup...",+ validationError = null,+ error = null+ )+ }+ val result = importBackup.inspect(InspectBackupCommand(uriString))+ _uiState.update { state ->+ when (result) {+ is InspectBackupResult.Error -> state.copy(+ syncProgress = null,+ error = "Import failed: ${result.message}"+ )++ is InspectBackupResult.Success -> state.copy(+ syncProgress = null,+ pendingBackupUri = result.uriString,+ backupPreview = result.preview,+ backupImportPlan = result.defaultPlan+ )+ }+ }+ }+ }++ fun dismissBackupPreview() {+ _uiState.update {+ it.copy(+ backupPreview = null,+ pendingBackupUri = null,+ backupImportPlan = BackupImportPlan()+ )+ }+ }++ fun setBackupConflictStrategy(strategy: BackupConflictStrategy) {+ _uiState.update { it.copy(backupImportPlan = it.backupImportPlan.copy(conflictStrategy = strategy)) }+ }++ fun setImportPreferences(enabled: Boolean) {+ _uiState.update { it.copy(backupImportPlan = it.backupImportPlan.copy(importPreferences = enabled)) }+ }++ fun setImportProviders(enabled: Boolean) {+ _uiState.update { it.copy(backupImportPlan = it.backupImportPlan.copy(importProviders = enabled)) }+ }++ fun setImportSavedLibrary(enabled: Boolean) {+ _uiState.update { it.copy(backupImportPlan = it.backupImportPlan.copy(importSavedLibrary = enabled)) }+ }++ fun setImportPlaybackHistory(enabled: Boolean) {+ _uiState.update { it.copy(backupImportPlan = it.backupImportPlan.copy(importPlaybackHistory = enabled)) }+ }++ fun setImportMultiViewPresets(enabled: Boolean) {+ _uiState.update { it.copy(backupImportPlan = it.backupImportPlan.copy(importMultiViewPresets = enabled)) }+ }++ fun setImportRecordingSchedules(enabled: Boolean) {+ _uiState.update { it.copy(backupImportPlan = it.backupImportPlan.copy(importRecordingSchedules = enabled)) }+ }++ fun confirmBackupImport() {+ var capturedUri: String? = null+ var capturedPlan: BackupImportPlan? = null+ _uiState.update { state ->+ if (state.isImportingBackup || state.pendingBackupUri == null) return@update state+ val plan = state.backupImportPlan+ if (!plan.importPreferences && !plan.importProviders && !plan.importSavedLibrary &&+ !plan.importPlaybackHistory && !plan.importMultiViewPresets && !plan.importRecordingSchedules+ ) {+ return@update state.copy(error = "Select at least one section to import")+ }+ capturedUri = state.pendingBackupUri+ capturedPlan = plan+ state.copy(+ isImportingBackup = true,+ syncProgress = null,+ validationError = null,+ error = null+ )+ }+ val uriString = capturedUri ?: return+ val plan = capturedPlan ?: return+ viewModelScope.launch {+ val result = importBackup.confirm(ImportBackupCommand(uriString, plan))+ val hasProviders = if (result is ImportBackupResult.Success) {+ providerRepository.getProviders().first().isNotEmpty()+ } else {+ false+ }+ _uiState.update { state ->+ state.copy(+ isImportingBackup = false,+ syncProgress = null,+ backupPreview = null,+ pendingBackupUri = null,+ backupImportPlan = BackupImportPlan(),+ backupImportSuccess = hasProviders,+ error = if (result is ImportBackupResult.Error) {+ "Import failed: ${result.message}"+ } else if (!hasProviders) {+ "Backup imported, but it did not add any providers."+ } else {+ null+ }+ )+ }+ }+ }+fun attachCreatedProviderToCombined() {val profileId = _uiState.value.pendingCombinedAttachProfileId ?: returnval providerId = _uiState.value.createdProviderId ?: return@@ -330,6 +513,10 @@ class ProviderSetupViewModel @Inject constructor(}}+ fun dismissCompletionWarning() {+ _uiState.update { it.copy(completionWarning = null) }+ }+private fun mapXtreamLoginError(result: ValidateAndAddProviderResult.Error): String {val failure = result.exceptionreturn when {@@ -375,6 +562,53 @@ class ProviderSetupViewModel @Inject constructor(}}+ /**+ * Maps M3U setup errors to user-friendly messages. Handles both the case where the playlist+ * was stored but the initial sync failed (saved-with-error path, distinct from the Xtream+ * sync failure prefix) and delegates to [mapXtreamLoginError] for errors that originated+ * from an auto-converted Xtream playlist URL.+ */+ private fun mapM3uSetupError(result: ValidateAndAddProviderResult.Error): String {+ if (result.message.startsWith(M3U_PLAYLIST_SYNC_FAILED_PREFIX, ignoreCase = true)) {+ return "Playlist saved, but the initial sync failed while loading the content"+ }+ // Auto-converted Xtream playlist URLs go through loginXtream internally, so the+ // same Xtream exception types apply.+ return mapXtreamLoginError(result)+ }++ /**+ * Maps Stalker portal setup errors to user-friendly messages consistent with the+ * Xtream error mapping. The Stalker stack throws [java.io.IOException] for network and+ * portal errors, so the same transport exception checks apply.+ */+ private fun mapStalkerLoginError(result: ValidateAndAddProviderResult.Error): String {+ if (result.message.startsWith(PROVIDER_LOGIN_SYNC_FAILED_PREFIX, ignoreCase = true)) {+ return "Login succeeded, but the initial sync failed while loading the channel list"+ }+ val failure = result.exception+ return when {+ failure.hasCause<CredentialDecryptionException>() ->+ failure.findCause<CredentialDecryptionException>()?.message+ ?: CredentialDecryptionException.MESSAGE++ failure.hasCause<SSLPeerUnverifiedException>() ||+ failure.hasCause<CertificateException>() ||+ failure.hasCause<SSLException>() ->+ "Secure connection failed - the server's TLS certificate is not trusted on this device"++ failure.hasCause<SocketTimeoutException>() ||+ failure.hasCause<InterruptedIOException>() ||+ failure.hasCause<UnknownHostException>() ||+ failure.hasCause<ConnectException>() ||+ failure.hasCause<NoRouteToHostException>() ->+ "Cannot reach portal - check your internet connection and portal URL"++ else -> result.message+ }+ }++private inline fun <reified T : Throwable> Throwable?.findCause(): T? {return generateSequence(this) { it.cause }.filterIsInstance<T>()@@ -387,15 +621,19 @@ class ProviderSetupViewModel @Inject constructor(private companion object {private const val PROVIDER_LOGIN_SYNC_FAILED_PREFIX ="Provider login succeeded, but initial sync failed"+ private const val M3U_PLAYLIST_SYNC_FAILED_PREFIX =+ "Playlist saved, but initial sync failed"}}data class ProviderSetupState(val isLoading: Boolean = false,val loginSuccess: Boolean = false,+ val backupImportSuccess: Boolean = false,val hasExistingProvider: Boolean = false,val error: String? = null,val validationError: String? = null,+ val completionWarning: String? = null,val syncProgress: String? = null,val isEditing: Boolean = false,val existingProviderId: Long? = null,@@ -414,6 +652,10 @@ data class ProviderSetupState(val createdProviderName: String? = null,val pendingCombinedAttachProfileId: Long? = null,val pendingCombinedAttachProfileName: String? = null,+ val isImportingBackup: Boolean = false,+ val backupPreview: BackupPreview? = null,+ val pendingBackupUri: String? = null,+ val backupImportPlan: BackupImportPlan = BackupImportPlan(),val epgSyncMode: ProviderEpgSyncMode = ProviderEpgSyncMode.BACKGROUND,val hasCustomizedEpgSyncMode: Boolean = false,val xtreamFastSyncEnabled: Boolean = true,diff --git a/app/src/main/java/com/streamvault/app/ui/screens/search/SearchScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/search/SearchScreen.ktindex fa4aa679..f0228735 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@@ -161,12 +161,13 @@ class SearchViewModel @Inject constructor(val level = params.levelval unlockedIds = params.unlockedCategoryIds- if (provider == null || query.length < 2) {+ val trimmedQueryLength = query.trim().length+ if (provider == null || trimmedQueryLength < 2) {flowOf(SearchUiState(parentalControlLevel = level,hasActiveProvider = provider != null,- queryLength = query.length,+ queryLength = trimmedQueryLength,unlockedCategoryIds = unlockedIds))@@ -190,9 +191,10 @@ class SearchViewModel @Inject constructor(else results.series,isLoading = false,hasSearched = true,+ hasSearchError = results.isPartialResult,parentalControlLevel = level,hasActiveProvider = true,- queryLength = query.length,+ queryLength = trimmedQueryLength,unlockedCategoryIds = unlockedIds)}@@ -326,6 +328,7 @@ data class SearchUiState(val series: List<Series> = emptyList(),val isLoading: Boolean = false,val hasSearched: Boolean = false,+ val hasSearchError: Boolean = false,val parentalControlLevel: Int = 0,val hasActiveProvider: Boolean = false,val queryLength: Int = 0,@@ -564,6 +567,15 @@ fun SearchScreen(}}+ uiState.isEmpty && uiState.hasSearchError -> {+ item {+ SearchMessageState(+ title = stringResource(R.string.search_error_title),+ subtitle = stringResource(R.string.search_error_subtitle)+ )+ }+ }+uiState.isEmpty -> {item {SearchMessageState(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.ktindex 69953ea2..1083730c 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@@ -16,6 +16,7 @@ import com.streamvault.domain.repository.SeriesRepositoryimport com.streamvault.domain.repository.ProviderRepositoryimport com.streamvault.domain.util.isPlaybackCompleteimport dagger.hilt.android.lifecycle.HiltViewModel+import kotlinx.coroutines.Jobimport kotlinx.coroutines.flow.MutableStateFlowimport kotlinx.coroutines.flow.StateFlowimport kotlinx.coroutines.flow.asStateFlow@@ -41,53 +42,65 @@ class SeriesDetailViewModel @Inject constructor(private val _uiState = MutableStateFlow(SeriesDetailUiState())val uiState: StateFlow<SeriesDetailUiState> = _uiState.asStateFlow()- init {- loadSeriesDetails()- }+ private var providerDetailJob: Job? = null- private fun loadSeriesDetails() {+ init {viewModelScope.launch {- try {- _uiState.update { it.copy(isLoading = true, error = null) }-- val provider = providerRepository.getActiveProvider().first()+ providerRepository.getActiveProvider().collect { provider ->+ providerDetailJob?.cancel()+ _uiState.value = SeriesDetailUiState(isLoading = true)if (provider == null) {_uiState.update { it.copy(isLoading = false, error = "No active provider") }- return@launch+ return@collect}-- observeUnwatchedCount(provider.id)-- when (val result = seriesRepository.getSeriesDetails(provider.id, seriesId)) {- is Result.Success -> {- loadExternalRatings(result.data)- _uiState.update {- it.copy(- isLoading = false,- series = result.data,- selectedSeason = result.data.seasons.firstOrNull(),- resumeEpisode = findResumeEpisode(result.data),- error = null- )+ providerDetailJob = launch {+ launch {+ playbackHistoryRepository.getUnwatchedCount(+ providerId = provider.id,+ seriesId = seriesId+ ).collect { count ->+ _uiState.update { it.copy(unwatchedEpisodeCount = count) }}}- is Result.Error -> {- _uiState.update {- it.copy(isLoading = false, error = result.message)- }+ loadSeriesDetailsForProvider(provider.id)+ }+ }+ }+ }++ private suspend fun loadSeriesDetailsForProvider(providerId: Long) {+ try {+ _uiState.update { it.copy(isLoading = true, error = null) }++ when (val result = seriesRepository.getSeriesDetails(providerId, seriesId)) {+ is Result.Success -> {+ loadExternalRatings(result.data)+ _uiState.update {+ it.copy(+ isLoading = false,+ series = result.data,+ selectedSeason = result.data.seasons.firstOrNull(),+ resumeEpisode = findResumeEpisode(result.data),+ error = null+ )}- is Result.Loading -> {- _uiState.update { it.copy(isLoading = true) }+ }+ is Result.Error -> {+ _uiState.update {+ it.copy(isLoading = false, error = result.message)}}- } catch (e: Exception) {- _uiState.update {- it.copy(- isLoading = false,- error = e.message ?: "Failed to load series details"- )+ is Result.Loading -> {+ _uiState.update { it.copy(isLoading = true) }}}+ } catch (e: Exception) {+ _uiState.update {+ it.copy(+ isLoading = false,+ error = e.message ?: "Failed to load series details"+ )+ }}}@@ -118,14 +131,6 @@ class SeriesDetailViewModel @Inject constructor(}}- private fun observeUnwatchedCount(providerId: Long) {- viewModelScope.launch {- playbackHistoryRepository.getUnwatchedCount(providerId = providerId, seriesId = seriesId).collect { count ->- _uiState.update { it.copy(unwatchedEpisodeCount = count) }- }- }- }-fun selectSeason(season: Season) {_uiState.update { it.copy(selectedSeason = season) }}diff --git a/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesScreen.ktindex 95d251e7..38cc93e4 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesScreen.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesScreen.kt@@ -1141,7 +1141,7 @@ private fun SeriesVodClassicContent()LazyVerticalGrid(state = classicGridState,- columns = GridCells.Adaptive(minSize = 136.dp),+ columns = GridCells.Adaptive(minSize = 68.dp),modifier = Modifier.fillMaxWidth().weight(1f)diff --git a/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesViewModel.ktindex 7021f7ea..f2d2f01b 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@@ -21,6 +21,7 @@ import com.streamvault.domain.repository.FavoriteRepositoryimport com.streamvault.domain.repository.PlaybackHistoryRepositoryimport com.streamvault.domain.repository.ProviderRepositoryimport com.streamvault.domain.repository.SeriesRepository+import com.streamvault.domain.usecase.ContinueWatchingResultimport com.streamvault.domain.usecase.ContinueWatchingScopeimport com.streamvault.domain.usecase.GetContinueWatchingimport com.streamvault.domain.usecase.GetCustomCategories@@ -379,9 +380,14 @@ class SeriesViewModel @Inject constructor(limit = 20,scope = ContinueWatchingScope.SERIES)- .collect { history ->+ .collect { result ->_uiState.update {- it.copy(continueWatching = history)+ it.copy(+ continueWatching = when (result) {+ is ContinueWatchingResult.Items -> result.items+ ContinueWatchingResult.Degraded -> emptyList()+ }+ )}}}@@ -1149,6 +1155,13 @@ class SeriesViewModel @Inject constructor(query: String): List<Series> {val historyKeys = history.mapTo(mutableSetOf()) { it.seriesId ?: it.contentId }+ val completedSeriesIds = history+ .filter { ph ->+ ph.contentType == ContentType.SERIES_EPISODE &&+ ph.totalDurationMs > 0 &&+ ph.resumePositionMs >= (ph.totalDurationMs * 0.95f).toLong()+ }+ .mapNotNullTo(mutableSetOf()) { it.seriesId }val watchCounts = history.groupingBy { it.seriesId ?: it.contentId }.eachCount()val normalizedQuery = query.trim().lowercase()val searched = if (normalizedQuery.isBlank()) {@@ -1164,7 +1177,7 @@ class SeriesViewModel @Inject constructor(LibraryFilterType.ALL -> searchedLibraryFilterType.FAVORITES -> searched.filter { it.isFavorite }LibraryFilterType.IN_PROGRESS -> searched.filter { it.id in historyKeys }- LibraryFilterType.UNWATCHED -> searched.filter { it.id !in historyKeys }+ LibraryFilterType.UNWATCHED -> searched.filter { it.id !in completedSeriesIds }LibraryFilterType.RECENTLY_UPDATED -> searched.filter { seriesFreshnessScore(it) > 0L }LibraryFilterType.TOP_RATED -> searched.filter { it.rating > 0f }}diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsBackupActions.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsBackupActions.ktindex bcb0451c..3b120c5c 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsBackupActions.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsBackupActions.kt@@ -97,13 +97,30 @@ internal class SettingsBackupActions(}fun confirmBackupImport(scope: CoroutineScope) {- val uriString = uiState.value.pendingBackupUri ?: return- val plan = uiState.value.backupImportPlan+ // Atomically capture uri+plan and mark in-flight so rapid double-taps cannot both+ // pass the guard before the flag is written. MutableStateFlow.update {} is a CAS+ // loop, so only one call wins the transition isImportingBackup=false→true.+ var capturedUri: String? = null+ var capturedPlan: BackupImportPlan? = null+ uiState.update { state ->+ if (state.isImportingBackup || state.pendingBackupUri == null) return@update state+ val plan = state.backupImportPlan+ if (!plan.importPreferences && !plan.importProviders && !plan.importSavedLibrary &&+ !plan.importPlaybackHistory && !plan.importMultiViewPresets && !plan.importRecordingSchedules+ ) {+ return@update state.copy(userMessage = "Select at least one section to import")+ }+ capturedUri = state.pendingBackupUri+ capturedPlan = plan+ state.copy(isImportingBackup = true)+ }+ val uriString = capturedUri ?: return+ val plan = capturedPlan ?: returnscope.launch {- uiState.update { it.copy(isSyncing = true) }val result = importBackup.confirm(ImportBackupCommand(uriString, plan))uiState.update { state ->state.copy(+ isImportingBackup = false,isSyncing = false,userMessage = if (result is ImportBackupResult.Error) {"Import failed: ${result.message}"diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsBackupImportPreviewDialog.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsBackupImportPreviewDialog.ktindex d77d7baf..1d33fe41 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsBackupImportPreviewDialog.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsBackupImportPreviewDialog.kt@@ -40,12 +40,15 @@ internal fun BackupImportPreviewDialog(onImportPlaybackHistoryChanged: (Boolean) -> Unit,onImportMultiViewChanged: (Boolean) -> Unit,onImportRecordingSchedulesChanged: (Boolean) -> Unit,+ isImporting: Boolean = false,onConfirm: () -> Unit) {+ val anyEnabled = plan.importPreferences || plan.importProviders || plan.importSavedLibrary ||+ plan.importPlaybackHistory || plan.importMultiViewPresets || plan.importRecordingSchedulesPremiumDialog(title = stringResource(R.string.settings_backup_preview_title),subtitle = stringResource(R.string.settings_backup_preview_subtitle, preview.version),- onDismissRequest = onDismiss,+ onDismissRequest = if (isImporting) ({}) else onDismiss,widthFraction = 0.58f,content = {BackupPreviewRow(stringResource(R.string.settings_backup_section_preferences), preview.preferenceCount, 0)@@ -86,12 +89,14 @@ internal fun BackupImportPreviewDialog(footer = {PremiumDialogFooterButton(label = stringResource(R.string.settings_cancel),- onClick = onDismiss+ onClick = onDismiss,+ enabled = !isImporting)PremiumDialogFooterButton(label = stringResource(R.string.settings_backup_import_confirm),onClick = onConfirm,- emphasized = true+ emphasized = true,+ enabled = anyEnabled && !isImporting)})diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsCombinedM3uComponents.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsCombinedM3uComponents.ktindex 1c53df8d..2eaa3938 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsCombinedM3uComponents.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsCombinedM3uComponents.kt@@ -126,6 +126,7 @@ internal fun CombinedM3uProfilesCard(CompactSettingsActionChip(label = "Use For Live TV",accent = Primary,+ enabled = selectedProfile.members.any { it.enabled },onClick = { onActivateProfile(selectedProfile.id) })CompactSettingsActionChip(@@ -218,6 +219,7 @@ internal fun CombinedM3uProfilesCard(@Composableinternal fun RenameCombinedM3uDialog(profile: CombinedM3uProfile,+ isSubmitting: Boolean = false,onDismiss: () -> Unit,onRename: (String) -> Unit) {@@ -238,12 +240,13 @@ internal fun RenameCombinedM3uDialog(footer = {PremiumDialogFooterButton(label = stringResource(R.string.settings_cancel),- onClick = onDismiss+ onClick = onDismiss,+ enabled = !isSubmitting)PremiumDialogFooterButton(label = "Save",onClick = { onRename(name.trim()) },- enabled = name.isNotBlank(),+ enabled = name.isNotBlank() && !isSubmitting,emphasized = true)}@@ -253,6 +256,7 @@ internal fun RenameCombinedM3uDialog(@Composableinternal fun CreateCombinedM3uDialog(providers: List<Provider>,+ isSubmitting: Boolean = false,onDismiss: () -> Unit,onCreate: (String, List<Long>) -> Unit) {@@ -353,12 +357,13 @@ internal fun CreateCombinedM3uDialog(footer = {PremiumDialogFooterButton(label = stringResource(R.string.settings_cancel),- onClick = onDismiss+ onClick = onDismiss,+ enabled = !isSubmitting)PremiumDialogFooterButton(label = "Create",onClick = { onCreate(effectiveName, selectedProviderIds.toList()) },- enabled = selectedProviderIds.isNotEmpty() && effectiveName.isNotBlank(),+ enabled = selectedProviderIds.isNotEmpty() && effectiveName.isNotBlank() && !isSubmitting,emphasized = true)}@@ -369,6 +374,7 @@ internal fun CreateCombinedM3uDialog(internal fun AddCombinedProviderDialog(profile: CombinedM3uProfile,availableProviders: List<Provider>,+ isSubmitting: Boolean = false,onDismiss: () -> Unit,onAddProvider: (Long) -> Unit) {@@ -447,12 +453,13 @@ internal fun AddCombinedProviderDialog(footer = {PremiumDialogFooterButton(label = stringResource(R.string.settings_cancel),- onClick = onDismiss+ onClick = onDismiss,+ enabled = !isSubmitting)PremiumDialogFooterButton(label = "Add",onClick = { selectedProviderId?.let(onAddProvider) },- enabled = selectedProviderId != null && candidateProviders.isNotEmpty(),+ enabled = selectedProviderId != null && candidateProviders.isNotEmpty() && !isSubmitting,emphasized = true)}diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsEpgActions.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsEpgActions.ktindex 8bae524e..e03ab101 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsEpgActions.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsEpgActions.kt@@ -39,17 +39,21 @@ internal class SettingsEpgActions(}}- fun addEpgSource(scope: CoroutineScope, name: String, url: String) {+ fun addEpgSource(scope: CoroutineScope, name: String, url: String, onSuccess: () -> Unit = {}, onError: () -> Unit = {}) {scope.launch {try {val result = epgSourceRepository.addSource(name, url)if (result is Result.Error) {uiState.update { it.copy(userMessage = result.message) }+ onError()+ } else {+ onSuccess()}} catch (cancelled: CancellationException) {throw cancelled} catch (error: Exception) {showUnexpectedError(error, "Failed to add EPG source")+ onError()}}}@@ -91,7 +95,9 @@ internal class SettingsEpgActions(scope.launch {uiState.update { it.copy(refreshingEpgSourceIds = it.refreshingEpgSourceIds + sourceId) }try {- val affectedProviders = loadedProvidersForSource(sourceId)+ // Query from the repository BEFORE refresh so all assigned providers are+ // updated, not just those already loaded into the UI state.+ val affectedProviders = epgSourceRepository.getProviderIdsForSource(sourceId)val result = epgSourceRepository.refreshSource(sourceId)if (result !is Result.Error) {refreshLoadedResolutionSummaries(affectedProviders)@@ -195,6 +201,23 @@ internal class SettingsEpgActions(}}+ /**+ * Cancels the assignment collector job for each provider in [removedIds] and purges their+ * entries from [SettingsUiState]. Called when the provider list shrinks so that the+ * [assignmentJobs] map doesn't grow unboundedly for providers that no longer exist.+ */+ fun cleanupEpgAssignmentsFor(removedIds: Set<Long>) {+ for (id in removedIds) {+ assignmentJobs.remove(id)?.cancel()+ }+ uiState.update { state ->+ state.copy(+ epgSourceAssignments = state.epgSourceAssignments - removedIds,+ epgResolutionSummaries = state.epgResolutionSummaries - removedIds+ )+ }+ }+private fun loadedProvidersForSource(sourceId: Long): List<Long> =uiState.value.epgSourceAssignments.filterValues { assignments -> assignments.any { it.epgSourceId == sourceId } }diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsEpgSourceComponents.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsEpgSourceComponents.ktindex 7e97906b..f8dde059 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsEpgSourceComponents.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsEpgSourceComponents.kt@@ -148,6 +148,7 @@ internal fun EpgSourceCard(internal fun AddEpgSourceCard(viewModel: SettingsViewModel) {var newName by remember { mutableStateOf("") }var newUrl by remember { mutableStateOf("") }+ var isSubmitting by remember { mutableStateOf(false) }val context = LocalContext.currentval filePickerLauncher = rememberLauncherForActivityResult(contract = ActivityResultContracts.OpenDocument()@@ -198,12 +199,21 @@ internal fun AddEpgSourceCard(viewModel: SettingsViewModel) {val addSourceShape = RoundedCornerShape(8.dp)TvClickableSurface(onClick = {- if (newName.isNotBlank() && newUrl.isNotBlank()) {- viewModel.addEpgSource(newName.trim(), newUrl.trim())- newName = ""- newUrl = ""+ if (!isSubmitting && newName.isNotBlank() && newUrl.isNotBlank()) {+ val nameToSubmit = newName.trim()+ val urlToSubmit = newUrl.trim()+ isSubmitting = true+ viewModel.addEpgSource(nameToSubmit, urlToSubmit,+ onSuccess = {+ newName = ""+ newUrl = ""+ isSubmitting = false+ },+ onError = { isSubmitting = false }+ )}},+ enabled = newName.isNotBlank() && newUrl.isNotBlank() && !isSubmitting,shape = ClickableSurfaceDefaults.shape(addSourceShape),colors = ClickableSurfaceDefaults.colors(containerColor = Color(0xFF66BB6A).copy(alpha = 0.2f),diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsInternetSpeedTestCard.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsInternetSpeedTestCard.ktindex 0ebe59c6..1bc3fb64 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsInternetSpeedTestCard.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsInternetSpeedTestCard.kt@@ -44,6 +44,7 @@ internal fun InternetSpeedTestCard(val focusRequester = remember { FocusRequester() }TvClickableSurface(onClick = onRunTest,+ enabled = !isRunning,shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(12.dp)),colors = ClickableSurfaceDefaults.colors(containerColor = SurfaceElevated,@@ -55,6 +56,7 @@ internal fun InternetSpeedTestCard(.padding(top = 8.dp).focusRequester(focusRequester).mouseClickable(+ enabled = !isRunning,focusRequester = focusRequester,onClick = onRunTest)diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsPlaybackSection.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsPlaybackSection.ktindex da5caeb2..6036504f 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsPlaybackSection.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsPlaybackSection.kt@@ -227,6 +227,29 @@ internal fun LazyListScope.settingsPlaybackSection(value = audioVideoOffsetLabel,onClick = { onShowAudioVideoOffsetDialogChange(true) })+ HorizontalDivider(color = Color.White.copy(alpha = 0.07f), modifier = Modifier.padding(vertical = 4.dp))+ TvClickableSurface(+ onClick = { viewModel.setCenterTwoSlotMultiviewLayout(!uiState.centerTwoSlotMultiviewLayout) },+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(8.dp)),+ colors = ClickableSurfaceDefaults.colors(+ containerColor = Color.Transparent,+ focusedContainerColor = Primary.copy(alpha = 0.15f)+ ),+ scale = ClickableSurfaceDefaults.scale(focusedScale = 1f),+ modifier = Modifier.fillMaxWidth()+ ) {+ Row(+ modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp, vertical = 12.dp),+ horizontalArrangement = Arrangement.SpaceBetween,+ verticalAlignment = Alignment.CenterVertically+ ) {+ Column(modifier = Modifier.weight(1f)) {+ Text(text = stringResource(R.string.settings_multiview_center_two_slot_layout), style = MaterialTheme.typography.bodyMedium, color = OnSurface)+ Text(text = stringResource(R.string.settings_multiview_center_two_slot_layout_subtitle), style = MaterialTheme.typography.bodySmall, color = OnBackground.copy(alpha = 0.6f))+ }+ Switch(checked = uiState.centerTwoSlotMultiviewLayout, onCheckedChange = { viewModel.setCenterTwoSlotMultiviewLayout(it) })+ }+ }ClickableSettingsRow(label = stringResource(R.string.settings_player_controls_timeout),value = controlsTimeoutLabel,@@ -292,4 +315,4 @@ internal fun LazyListScope.settingsPlaybackSection(onApplyEthernet = viewModel::applySpeedTestRecommendationToEthernet)}-}\ No newline at end of file+}diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsPreferenceModels.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsPreferenceModels.ktindex b916f3b3..bd193ed5 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsPreferenceModels.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsPreferenceModels.kt@@ -43,6 +43,7 @@ internal data class SettingsPreferenceSnapshot(val playerSurfaceMode: PlayerSurfaceMode,val playerPlaybackSpeed: Float,val playerAudioVideoOffsetMs: Int,+ val centerTwoSlotMultiviewLayout: Boolean,val playerControlsTimeoutSeconds: Int,val playerLiveOverlayTimeoutSeconds: Int,val playerNoticeTimeoutSeconds: Int,@@ -99,4 +100,4 @@ internal fun ProviderSyncSelection.label(application: Application): String = wheProviderSyncSelection.MOVIES -> application.getString(R.string.settings_sync_option_movies)ProviderSyncSelection.SERIES -> application.getString(R.string.settings_sync_option_series)ProviderSyncSelection.EPG -> application.getString(R.string.settings_sync_option_epg)-}\ No newline at end of file+}diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsPreferenceSnapshotMapper.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsPreferenceSnapshotMapper.ktindex 3da833cb..c090bb7c 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsPreferenceSnapshotMapper.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsPreferenceSnapshotMapper.kt@@ -15,6 +15,7 @@ internal fun SettingsUiState.applyPreferenceSnapshot(snapshot: SettingsPreferencplayerSurfaceMode = snapshot.playerSurfaceMode,playerPlaybackSpeed = snapshot.playerPlaybackSpeed,playerAudioVideoOffsetMs = snapshot.playerAudioVideoOffsetMs,+ centerTwoSlotMultiviewLayout = snapshot.centerTwoSlotMultiviewLayout,playerControlsTimeoutSeconds = snapshot.playerControlsTimeoutSeconds,playerLiveOverlayTimeoutSeconds = snapshot.playerLiveOverlayTimeoutSeconds,playerNoticeTimeoutSeconds = snapshot.playerNoticeTimeoutSeconds,@@ -65,4 +66,4 @@ internal fun SettingsUiState.applyPreferenceSnapshot(snapshot: SettingsPreferencerrorMessage = appUpdate.errorMessage))-}\ No newline at end of file+}diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsPrivacySection.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsPrivacySection.ktindex a5b5ef93..7dfdb6ae 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsPrivacySection.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsPrivacySection.kt@@ -82,7 +82,7 @@ internal fun LazyListScope.settingsPrivacySection(Text(text = stringResource(R.string.settings_incognito_mode), style = MaterialTheme.typography.bodyMedium, color = OnSurface)Text(text = stringResource(R.string.settings_incognito_mode_subtitle), style = MaterialTheme.typography.bodySmall, color = OnBackground.copy(alpha = 0.6f))}- Switch(checked = uiState.isIncognitoMode, onCheckedChange = { viewModel.toggleIncognitoMode() })+ Switch(checked = uiState.isIncognitoMode, onCheckedChange = null)}}Spacer(Modifier.height(2.dp))@@ -105,7 +105,7 @@ internal fun LazyListScope.settingsPrivacySection(Text(text = stringResource(R.string.settings_xtream_text_classification), style = MaterialTheme.typography.bodyMedium, color = OnSurface)Text(text = stringResource(R.string.settings_xtream_text_classification_subtitle), style = MaterialTheme.typography.bodySmall, color = OnBackground.copy(alpha = 0.6f))}- Switch(checked = uiState.useXtreamTextClassification, onCheckedChange = { viewModel.toggleXtreamTextClassification() })+ Switch(checked = uiState.useXtreamTextClassification, onCheckedChange = null)}}Spacer(Modifier.height(2.dp))@@ -128,7 +128,7 @@ internal fun LazyListScope.settingsPrivacySection(Text(text = stringResource(R.string.settings_xtream_base64_compatibility), style = MaterialTheme.typography.bodyMedium, color = OnSurface)Text(text = stringResource(R.string.settings_xtream_base64_compatibility_subtitle), style = MaterialTheme.typography.bodySmall, color = OnBackground.copy(alpha = 0.6f))}- Switch(checked = uiState.xtreamBase64TextCompatibility, onCheckedChange = { viewModel.toggleXtreamBase64TextCompatibility() })+ Switch(checked = uiState.xtreamBase64TextCompatibility, onCheckedChange = null)}}Spacer(Modifier.height(2.dp))diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsProviderActions.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsProviderActions.ktindex ee879a7e..f924056d 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsProviderActions.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsProviderActions.kt@@ -1,5 +1,7 @@package com.streamvault.app.ui.screens.settings+import com.streamvault.app.tv.LauncherRecommendationsManager+import com.streamvault.app.tv.WatchNextManagerimport com.streamvault.app.tvinput.TvInputChannelSyncManagerimport com.streamvault.domain.model.ActiveLiveSourceimport com.streamvault.domain.model.ProviderEpgSyncMode@@ -27,6 +29,8 @@ internal class SettingsProviderActions(private val syncProvider: SyncProvider,private val syncManager: SyncManager,private val syncMetadataRepository: SyncMetadataRepository,+ private val watchNextManager: WatchNextManager,+ private val launcherRecommendationsManager: LauncherRecommendationsManager,private val tvInputChannelSyncManager: TvInputChannelSyncManager,private val uiState: MutableStateFlow<SettingsUiState>) {@@ -36,43 +40,77 @@ internal class SettingsProviderActions(fun setActiveProvider(scope: CoroutineScope, providerId: Long) {scope.launch {+ // Validate the provider exists before writing any preferences.+ val provider = providerRepository.getProvider(providerId)+ if (provider == null) {+ uiState.update { it.copy(userMessage = "Could not activate provider: provider not found") }+ return@launch+ }+ // Write to the repository first; only persist UI-layer preferences on success.+ when (val result = providerRepository.setActiveProvider(providerId)) {+ is Result.Error -> {+ uiState.update { it.copy(userMessage = "Could not activate provider: ${result.message}") }+ return@launch+ }+ else -> Unit+ }+ // Repository write succeeded – now persist the UI-layer preferences and refresh.preferencesRepository.setLastActiveProviderId(providerId)combinedM3uRepository.setActiveLiveSource(ActiveLiveSource.ProviderSource(providerId))- providerRepository.setActiveProvider(providerId)- val provider = providerRepository.getProvider(providerId)- val shouldAutoSync = provider?.let { currentProvider ->- val lastSyncedAt = currentProvider.lastSyncedAt- lastSyncedAt <= 0L || System.currentTimeMillis() - lastSyncedAt >= AUTO_SWITCH_SYNC_STALE_AFTER_MS- } ?: false+ watchNextManager.refreshWatchNext()+ launcherRecommendationsManager.refreshRecommendations(force = true)+ tvInputChannelSyncManager.refreshTvInputCatalog()+ val lastSyncedAt = provider.lastSyncedAt+ val shouldAutoSync = lastSyncedAt <= 0L ||+ System.currentTimeMillis() - lastSyncedAt >= AUTO_SWITCH_SYNC_STALE_AFTER_MSif (shouldAutoSync) {refreshProvider(scope = scope,providerId = providerId,syncMode = SettingsProviderSyncMode.QUICK,- progressPrefix = "Refreshing ${provider?.name ?: "provider"}..."+ progressPrefix = "Refreshing ${provider.name}...")+ } else {+ uiState.update { it.copy(userMessage = "Connected to ${provider.name}") }}}}fun setActiveCombinedProfile(scope: CoroutineScope, profileId: Long) {scope.launch {- when (combinedM3uRepository.setActiveLiveSource(ActiveLiveSource.CombinedM3uSource(profileId))) {- is Result.Success -> uiState.update { it.copy(userMessage = "Combined M3U source activated") }- is Result.Error -> uiState.update { it.copy(userMessage = "Could not activate combined source") }- Result.Loading -> Unit+ // Validate the profile exists and has at least one enabled member before activating.+ val profile = combinedM3uRepository.getProfile(profileId)+ when {+ profile == null ->+ uiState.update { it.copy(userMessage = "Could not activate combined source: profile not found") }+ profile.members.isEmpty() ->+ uiState.update { it.copy(userMessage = "Add at least one playlist to this combined source before activating it") }+ profile.members.none { it.enabled } ->+ uiState.update { it.copy(userMessage = "Enable at least one playlist in this combined source before activating it") }+ else -> when (combinedM3uRepository.setActiveLiveSource(ActiveLiveSource.CombinedM3uSource(profileId))) {+ is Result.Success -> {+ launcherRecommendationsManager.refreshRecommendations(force = true)+ uiState.update { it.copy(userMessage = "Combined M3U source activated") }+ }+ is Result.Error -> uiState.update { it.copy(userMessage = "Could not activate combined source") }+ Result.Loading -> Unit+ }}}}- fun createCombinedProfile(scope: CoroutineScope, name: String, providerIds: List<Long>) {+ fun createCombinedProfile(scope: CoroutineScope, name: String, providerIds: List<Long>, onSuccess: () -> Unit = {}, onError: () -> Unit = {}) {scope.launch {when (val result = combinedM3uRepository.createProfile(name, providerIds)) {is Result.Success -> {combinedM3uRepository.setActiveLiveSource(ActiveLiveSource.CombinedM3uSource(result.data.id))uiState.update { it.copy(userMessage = "Combined M3U source created") }+ onSuccess()+ }+ is Result.Error -> {+ uiState.update { it.copy(userMessage = result.message) }+ onError()}- is Result.Error -> uiState.update { it.copy(userMessage = result.message) }Result.Loading -> Unit}}@@ -88,21 +126,33 @@ internal class SettingsProviderActions(}}- fun addProviderToCombinedProfile(scope: CoroutineScope, profileId: Long, providerId: Long) {+ fun addProviderToCombinedProfile(scope: CoroutineScope, profileId: Long, providerId: Long, onSuccess: () -> Unit = {}, onError: () -> Unit = {}) {scope.launch {when (val result = combinedM3uRepository.addProvider(profileId, providerId)) {- is Result.Success -> uiState.update { it.copy(userMessage = "Playlist added to combined source") }- is Result.Error -> uiState.update { it.copy(userMessage = result.message) }+ is Result.Success -> {+ uiState.update { it.copy(userMessage = "Playlist added to combined source") }+ onSuccess()+ }+ is Result.Error -> {+ uiState.update { it.copy(userMessage = result.message) }+ onError()+ }Result.Loading -> Unit}}}- fun renameCombinedProfile(scope: CoroutineScope, profileId: Long, name: String) {+ fun renameCombinedProfile(scope: CoroutineScope, profileId: Long, name: String, onSuccess: () -> Unit = {}, onError: () -> Unit = {}) {scope.launch {when (val result = combinedM3uRepository.updateProfileName(profileId, name)) {- is Result.Success -> uiState.update { it.copy(userMessage = "Combined M3U source renamed") }- is Result.Error -> uiState.update { it.copy(userMessage = result.message) }+ is Result.Success -> {+ uiState.update { it.copy(userMessage = "Combined M3U source renamed") }+ onSuccess()+ }+ is Result.Error -> {+ uiState.update { it.copy(userMessage = result.message) }+ onError()+ }Result.Loading -> Unit}}@@ -110,6 +160,17 @@ internal class SettingsProviderActions(fun removeProviderFromCombinedProfile(scope: CoroutineScope, profileId: Long, providerId: Long) {scope.launch {+ val profile = uiState.value.combinedProfiles.firstOrNull { it.id == profileId } ?: return@launch+ val activeSource = uiState.value.activeLiveSource+ if (activeSource is ActiveLiveSource.CombinedM3uSource && activeSource.profileId == profileId) {+ val memberToRemove = profile.members.firstOrNull { it.providerId == providerId }+ val removingEnabledMember = memberToRemove?.enabled == true+ val remainingEnabled = profile.members.count { it.providerId != providerId && it.enabled }+ if (removingEnabledMember && remainingEnabled == 0) {+ uiState.update { it.copy(userMessage = "Cannot remove the last active playlist from the current live source") }+ return@launch+ }+ }when (val result = combinedM3uRepository.removeProvider(profileId, providerId)) {is Result.Success -> uiState.update { it.copy(userMessage = "Playlist removed from combined source") }is Result.Error -> uiState.update { it.copy(userMessage = result.message) }@@ -137,6 +198,20 @@ internal class SettingsProviderActions(fun setCombinedProviderEnabled(scope: CoroutineScope, profileId: Long, providerId: Long, enabled: Boolean) {scope.launch {+ if (!enabled) {+ val profile = uiState.value.combinedProfiles.firstOrNull { it.id == profileId }+ val activeSource = uiState.value.activeLiveSource+ if (profile != null &&+ activeSource is ActiveLiveSource.CombinedM3uSource &&+ activeSource.profileId == profileId+ ) {+ val remainingEnabled = profile.members.count { it.providerId != providerId && it.enabled }+ if (remainingEnabled == 0) {+ uiState.update { it.copy(userMessage = "Cannot disable the last active playlist in the current live source") }+ return@launch+ }+ }+ }when (val result = combinedM3uRepository.setMemberEnabled(profileId, providerId, enabled)) {is Result.Success -> uiState.update {it.copy(userMessage = if (enabled) "Playlist enabled in combined source" else "Playlist disabled in combined source")@@ -346,9 +421,20 @@ internal class SettingsProviderActions(else -> message}- fun deleteProvider(scope: CoroutineScope, providerId: Long) {+ fun deleteProvider(scope: CoroutineScope, providerId: Long, onSuccess: () -> Unit = {}) {scope.launch {- providerRepository.deleteProvider(providerId)+ uiState.update { it.copy(isDeletingProvider = true) }+ when (val result = providerRepository.deleteProvider(providerId)) {+ is Result.Success -> {+ watchNextManager.refreshWatchNext()+ launcherRecommendationsManager.refreshRecommendations(force = true)+ tvInputChannelSyncManager.refreshTvInputCatalog()+ uiState.update { it.copy(isDeletingProvider = false, userMessage = "Provider deleted") }+ onSuccess()+ }+ is Result.Error -> uiState.update { it.copy(isDeletingProvider = false, userMessage = "Could not delete provider: ${result.message}") }+ Result.Loading -> Unit+ }}}}diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsProviderManagementDialogs.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsProviderManagementDialogs.ktindex 9ca92d1e..4fdf71a8 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsProviderManagementDialogs.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsProviderManagementDialogs.kt@@ -1,6 +1,14 @@package com.streamvault.app.ui.screens.settingsimport 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 com.streamvault.app.ui.components.dialogs.PremiumDialog+import com.streamvault.app.ui.components.dialogs.PremiumDialogFooterButton+import androidx.compose.ui.res.stringResource+import com.streamvault.app.R@Composableinternal fun SettingsProviderManagementDialogs(@@ -13,12 +21,17 @@ internal fun SettingsProviderManagementDialogs(}if (providerState.showCreateCombinedDialog) {+ var isCreating by remember { mutableStateOf(false) }CreateCombinedM3uDialog(providers = uiState.availableM3uProviders,+ isSubmitting = isCreating,onDismiss = { providerState.showCreateCombinedDialog = false },onCreate = { name, providerIds ->- providerState.showCreateCombinedDialog = false- viewModel.createCombinedProfile(name, providerIds)+ isCreating = true+ viewModel.createCombinedProfile(name, providerIds,+ onSuccess = { providerState.showCreateCombinedDialog = false },+ onError = { isCreating = false }+ )})}@@ -26,12 +39,17 @@ internal fun SettingsProviderManagementDialogs(if (providerState.showRenameCombinedDialog) {val selectedProfile = uiState.combinedProfiles.firstOrNull { it.id == providerState.selectedCombinedProfileId }if (selectedProfile != null) {+ var isRenaming by remember(selectedProfile.id) { mutableStateOf(false) }RenameCombinedM3uDialog(profile = selectedProfile,+ isSubmitting = isRenaming,onDismiss = { providerState.showRenameCombinedDialog = false },onRename = { name ->- providerState.showRenameCombinedDialog = false- viewModel.renameCombinedProfile(selectedProfile.id, name)+ isRenaming = true+ viewModel.renameCombinedProfile(selectedProfile.id, name,+ onSuccess = { providerState.showRenameCombinedDialog = false },+ onError = { isRenaming = false }+ )})}@@ -40,13 +58,18 @@ internal fun SettingsProviderManagementDialogs(if (providerState.showAddCombinedMemberDialog) {val selectedProfile = uiState.combinedProfiles.firstOrNull { it.id == providerState.selectedCombinedProfileId }if (selectedProfile != null) {+ var isAddingMember by remember(selectedProfile.id) { mutableStateOf(false) }AddCombinedProviderDialog(profile = selectedProfile,availableProviders = uiState.availableM3uProviders,+ isSubmitting = isAddingMember,onDismiss = { providerState.showAddCombinedMemberDialog = false },onAddProvider = { providerId ->- providerState.showAddCombinedMemberDialog = false- viewModel.addProviderToCombinedProfile(selectedProfile.id, providerId)+ isAddingMember = true+ viewModel.addProviderToCombinedProfile(selectedProfile.id, providerId,+ onSuccess = { providerState.showAddCombinedMemberDialog = false },+ onError = { isAddingMember = false }+ )})}@@ -94,4 +117,34 @@ internal fun SettingsProviderManagementDialogs(})}++ val pendingDeleteProviderId = providerState.pendingDeleteProviderId+ if (pendingDeleteProviderId != null) {+ val providerToDelete = uiState.providers.firstOrNull { it.id == pendingDeleteProviderId }+ val providerName = providerToDelete?.name ?: "this provider"+ PremiumDialog(+ title = "Delete Provider",+ subtitle = "Delete \"$providerName\"? This will permanently remove all its channels, programs, and sync data.",+ onDismissRequest = { if (!uiState.isDeletingProvider) providerState.pendingDeleteProviderId = null },+ widthFraction = 0.48f,+ content = {},+ footer = {+ PremiumDialogFooterButton(+ label = stringResource(R.string.settings_cancel),+ onClick = { providerState.pendingDeleteProviderId = null },+ enabled = !uiState.isDeletingProvider+ )+ PremiumDialogFooterButton(+ label = "Delete",+ onClick = {+ viewModel.deleteProvider(pendingDeleteProviderId,+ onSuccess = { providerState.pendingDeleteProviderId = null }+ )+ },+ enabled = !uiState.isDeletingProvider,+ destructive = true+ )+ }+ )+ }}\ No newline at end of filediff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsProviderSection.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsProviderSection.ktindex f636406e..6c69cd30 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsProviderSection.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsProviderSection.kt@@ -104,7 +104,7 @@ internal fun LazyListScope.providerSection(}providerState.showProviderSyncDialog = true},- onDelete = { viewModel.deleteProvider(selectedProvider.id) },+ onDelete = { providerState.pendingDeleteProviderId = selectedProvider.id },onEdit = { onEditProvider(selectedProvider) },onParentalControl = { onNavigateToParentalControl(selectedProvider.id) },onToggleM3uVodClassification = { enabled ->diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsRecordingActions.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsRecordingActions.ktindex 93c81179..f9a58848 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsRecordingActions.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsRecordingActions.kt@@ -9,12 +9,19 @@ import kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.flow.MutableStateFlowimport kotlinx.coroutines.flow.updateimport kotlinx.coroutines.launch+import kotlinx.coroutines.sync.Mutex+import kotlinx.coroutines.sync.withLockinternal class SettingsRecordingActions(private val appContext: Application,private val recordingManager: RecordingManager,private val uiState: MutableStateFlow<SettingsUiState>) {+ // Serializes all storage-config updates so that a concurrent read-modify-write+ // (e.g. folder + retention changed close together) always builds from the latest+ // committed RecordingStorageState rather than two stale copies of the same snapshot.+ private val storageConfigMutex = Mutex()+fun stopRecording(scope: CoroutineScope, recordingId: String) {scope.launch {val result = recordingManager.stopRecording(recordingId)@@ -125,96 +132,108 @@ internal class SettingsRecordingActions(fun updateRecordingFolder(scope: CoroutineScope, treeUri: String?, displayName: String?) {scope.launch {- val current = uiState.value.recordingStorageState- val result = recordingManager.updateStorageConfig(- RecordingStorageConfig(- treeUri = treeUri,- displayName = displayName,- fileNamePattern = current.fileNamePattern,- retentionDays = current.retentionDays,- maxSimultaneousRecordings = current.maxSimultaneousRecordings- )- )- uiState.update {- it.copy(- userMessage = if (result is Result.Error) {- appContext.getString(R.string.settings_recording_storage_update_failed, result.message)- } else {- appContext.getString(R.string.settings_recording_storage_updated)- }+ storageConfigMutex.withLock {+ val current = uiState.value.recordingStorageState+ val result = recordingManager.updateStorageConfig(+ RecordingStorageConfig(+ treeUri = treeUri,+ displayName = displayName,+ fileNamePattern = current.fileNamePattern,+ retentionDays = current.retentionDays,+ maxSimultaneousRecordings = current.maxSimultaneousRecordings+ ))+ uiState.update { state ->+ state.copy(+ recordingStorageState = if (result is Result.Success) result.data else state.recordingStorageState,+ userMessage = if (result is Result.Error) {+ appContext.getString(R.string.settings_recording_storage_update_failed, result.message)+ } else {+ appContext.getString(R.string.settings_recording_storage_updated)+ }+ )+ }}}}fun updateRecordingFileNamePattern(scope: CoroutineScope, pattern: String) {scope.launch {- val current = uiState.value.recordingStorageState- val result = recordingManager.updateStorageConfig(- RecordingStorageConfig(- treeUri = current.treeUri,- displayName = current.displayName,- fileNamePattern = pattern,- retentionDays = current.retentionDays,- maxSimultaneousRecordings = current.maxSimultaneousRecordings- )- )- uiState.update {- it.copy(- userMessage = if (result is Result.Error) {- appContext.getString(R.string.settings_recording_pattern_failed, result.message)- } else {- appContext.getString(R.string.settings_recording_pattern_saved)- }+ storageConfigMutex.withLock {+ val current = uiState.value.recordingStorageState+ val result = recordingManager.updateStorageConfig(+ RecordingStorageConfig(+ treeUri = current.treeUri,+ displayName = current.displayName,+ fileNamePattern = pattern,+ retentionDays = current.retentionDays,+ maxSimultaneousRecordings = current.maxSimultaneousRecordings+ ))+ uiState.update { state ->+ state.copy(+ recordingStorageState = if (result is Result.Success) result.data else state.recordingStorageState,+ userMessage = if (result is Result.Error) {+ appContext.getString(R.string.settings_recording_pattern_failed, result.message)+ } else {+ appContext.getString(R.string.settings_recording_pattern_saved)+ }+ )+ }}}}fun updateRecordingRetentionDays(scope: CoroutineScope, retentionDays: Int?) {scope.launch {- val current = uiState.value.recordingStorageState- val result = recordingManager.updateStorageConfig(- RecordingStorageConfig(- treeUri = current.treeUri,- displayName = current.displayName,- fileNamePattern = current.fileNamePattern,- retentionDays = retentionDays,- maxSimultaneousRecordings = current.maxSimultaneousRecordings- )- )- uiState.update {- it.copy(- userMessage = if (result is Result.Error) {- appContext.getString(R.string.settings_recording_retention_failed, result.message)- } else {- appContext.getString(R.string.settings_recording_retention_saved)- }+ storageConfigMutex.withLock {+ val current = uiState.value.recordingStorageState+ val result = recordingManager.updateStorageConfig(+ RecordingStorageConfig(+ treeUri = current.treeUri,+ displayName = current.displayName,+ fileNamePattern = current.fileNamePattern,+ retentionDays = retentionDays,+ maxSimultaneousRecordings = current.maxSimultaneousRecordings+ ))+ uiState.update { state ->+ state.copy(+ recordingStorageState = if (result is Result.Success) result.data else state.recordingStorageState,+ userMessage = if (result is Result.Error) {+ appContext.getString(R.string.settings_recording_retention_failed, result.message)+ } else {+ appContext.getString(R.string.settings_recording_retention_saved)+ }+ )+ }}}}fun updateRecordingMaxSimultaneous(scope: CoroutineScope, maxSimultaneousRecordings: Int) {scope.launch {- val current = uiState.value.recordingStorageState- val result = recordingManager.updateStorageConfig(- RecordingStorageConfig(- treeUri = current.treeUri,- displayName = current.displayName,- fileNamePattern = current.fileNamePattern,- retentionDays = current.retentionDays,- maxSimultaneousRecordings = maxSimultaneousRecordings- )- )- uiState.update {- it.copy(- userMessage = if (result is Result.Error) {- appContext.getString(R.string.settings_recording_concurrency_failed, result.message)- } else {- appContext.getString(R.string.settings_recording_concurrency_saved)- }+ storageConfigMutex.withLock {+ val current = uiState.value.recordingStorageState+ val result = recordingManager.updateStorageConfig(+ RecordingStorageConfig(+ treeUri = current.treeUri,+ displayName = current.displayName,+ fileNamePattern = current.fileNamePattern,+ retentionDays = current.retentionDays,+ maxSimultaneousRecordings = maxSimultaneousRecordings+ ))+ uiState.update { state ->+ state.copy(+ recordingStorageState = if (result is Result.Success) result.data else state.recordingStorageState,+ userMessage = if (result is Result.Error) {+ appContext.getString(R.string.settings_recording_concurrency_failed, result.message)+ } else {+ appContext.getString(R.string.settings_recording_concurrency_saved)+ }+ )+ }}}}diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsScreenDialogState.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsScreenDialogState.ktindex 428d0a0c..d5120bf2 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsScreenDialogState.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsScreenDialogState.kt@@ -58,7 +58,8 @@ internal class SettingsScreenDialogState(private val selectedCategoryState: MutableState<Int>,private val pinErrorState: MutableState<String?>,private val pendingActionState: MutableState<ParentalAction?>,- private val pendingProtectionLevelState: MutableState<Int?>+ private val pendingProtectionLevelState: MutableState<Int?>,+ private val pendingDeleteProviderIdState: MutableState<Long?>) {var showPinDialog by showPinDialogStatevar showLevelDialog by showLevelDialogState@@ -110,6 +111,7 @@ internal class SettingsScreenDialogState(var pinError by pinErrorStatevar pendingAction by pendingActionStatevar pendingProtectionLevel by pendingProtectionLevelState+ var pendingDeleteProviderId by pendingDeleteProviderIdState}internal class SettingsProviderSectionState(@@ -162,6 +164,12 @@ internal class SettingsProviderSectionState(set(value) {dialogState.customSyncSelections = value}++ var pendingDeleteProviderId: Long?+ get() = dialogState.pendingDeleteProviderId+ set(value) {+ dialogState.pendingDeleteProviderId = value+ }}@Composable@@ -231,6 +239,7 @@ internal fun rememberSettingsScreenDialogState(): SettingsScreenDialogState {val pinErrorState = rememberSaveable { mutableStateOf<String?>(null) }val pendingActionState = remember { mutableStateOf<ParentalAction?>(null) }val pendingProtectionLevelState = rememberSaveable { mutableStateOf<Int?>(null) }+ val pendingDeleteProviderIdState = rememberSaveable { mutableStateOf<Long?>(null) }return SettingsScreenDialogState(showPinDialogState = showPinDialogState,@@ -282,6 +291,7 @@ internal fun rememberSettingsScreenDialogState(): SettingsScreenDialogState {selectedCategoryState = selectedCategoryState,pinErrorState = pinErrorState,pendingActionState = pendingActionState,- pendingProtectionLevelState = pendingProtectionLevelState+ pendingProtectionLevelState = pendingProtectionLevelState,+ pendingDeleteProviderIdState = pendingDeleteProviderIdState)}\ No newline at end of filediff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsScreenDialogs.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsScreenDialogs.ktindex 6a8dfc2f..d576712b 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsScreenDialogs.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsScreenDialogs.kt@@ -199,6 +199,7 @@ internal fun SettingsScreenDialogs(onImportPlaybackHistoryChanged = { viewModel.setImportPlaybackHistory(it) },onImportMultiViewChanged = { viewModel.setImportMultiViewPresets(it) },onImportRecordingSchedulesChanged = { viewModel.setImportRecordingSchedules(it) },+ isImporting = uiState.isImportingBackup,onConfirm = { viewModel.confirmBackupImport() })}diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsStateBindings.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsStateBindings.ktindex 9eca48df..b8ae3ff8 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsStateBindings.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsStateBindings.kt@@ -42,6 +42,7 @@ internal fun observeSettingsPreferenceSnapshot(playerSurfaceMode = com.streamvault.domain.model.PlayerSurfaceMode.AUTO,playerPlaybackSpeed = 1f,playerAudioVideoOffsetMs = 0,+ centerTwoSlotMultiviewLayout = false,playerControlsTimeoutSeconds = 5,playerLiveOverlayTimeoutSeconds = 4,playerNoticeTimeoutSeconds = 6,@@ -106,6 +107,8 @@ internal fun observeSettingsPreferenceSnapshot(snapshot.copy(playerPlaybackSpeed = playerPlaybackSpeed)}.combine(preferencesRepository.playerAudioVideoOffsetMs) { snapshot, playerAudioVideoOffsetMs ->snapshot.copy(playerAudioVideoOffsetMs = playerAudioVideoOffsetMs)+ }.combine(preferencesRepository.multiViewCenterTwoSlotLayout) { snapshot, centerTwoSlotLayout ->+ snapshot.copy(centerTwoSlotMultiviewLayout = centerTwoSlotLayout)}.combine(preferencesRepository.playerControlsTimeoutSeconds) { snapshot, timeoutSeconds ->snapshot.copy(playerControlsTimeoutSeconds = timeoutSeconds)}.combine(preferencesRepository.playerLiveOverlayTimeoutSeconds) { snapshot, timeoutSeconds ->diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsUiStateModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsUiStateModel.ktindex c6e745b7..029eeb3b 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsUiStateModel.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsUiStateModel.kt@@ -45,6 +45,7 @@ data class SettingsUiState(val playerSurfaceMode: PlayerSurfaceMode = PlayerSurfaceMode.AUTO,val playerPlaybackSpeed: Float = 1f,val playerAudioVideoOffsetMs: Int = 0,+ val centerTwoSlotMultiviewLayout: Boolean = false,val playerControlsTimeoutSeconds: Int = 5,val playerLiveOverlayTimeoutSeconds: Int = 4,val playerNoticeTimeoutSeconds: Int = 6,@@ -60,6 +61,8 @@ data class SettingsUiState(val defaultIdleStandbyTimerMinutes: Int = 0,val lastSpeedTest: InternetSpeedTestUiModel? = null,val isRunningInternetSpeedTest: Boolean = false,+ val isDeletingProvider: Boolean = false,+ val isImportingBackup: Boolean = false,val backupPreview: BackupPreview? = null,val pendingBackupUri: String? = null,val backupImportPlan: BackupImportPlan = BackupImportPlan(),@@ -99,4 +102,4 @@ data class SettingsUiState(val autoDownloadAppUpdates: Boolean = false,val isCheckingForUpdates: Boolean = false,val appUpdate: AppUpdateUiModel = AppUpdateUiModel()-)\ No newline at end of file+)diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsViewModel.ktindex ee212d04..be05ead2 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@@ -5,6 +5,8 @@ import androidx.lifecycle.ViewModelimport androidx.lifecycle.viewModelScopeimport com.streamvault.app.Rimport com.streamvault.app.BuildConfig+import com.streamvault.app.tv.LauncherRecommendationsManager+import com.streamvault.app.tv.WatchNextManagerimport com.streamvault.app.tvinput.TvInputChannelSyncManagerimport com.streamvault.app.ui.model.LiveTvChannelModeimport com.streamvault.app.ui.model.LiveTvQuickFilterVisibilityMode@@ -81,6 +83,8 @@ class SettingsViewModel @Inject constructor(private val syncManager: SyncManager,private val syncMetadataRepository: SyncMetadataRepository,private val playbackHistoryRepository: com.streamvault.domain.repository.PlaybackHistoryRepository,+ private val watchNextManager: WatchNextManager,+ private val launcherRecommendationsManager: LauncherRecommendationsManager,private val tvInputChannelSyncManager: TvInputChannelSyncManager,private val syncProvider: SyncProvider,private val epgSourceRepository: com.streamvault.domain.repository.EpgSourceRepository,@@ -119,6 +123,8 @@ class SettingsViewModel @Inject constructor(syncProvider = syncProvider,syncManager = syncManager,syncMetadataRepository = syncMetadataRepository,+ watchNextManager = watchNextManager,+ launcherRecommendationsManager = launcherRecommendationsManager,tvInputChannelSyncManager = tvInputChannelSyncManager,uiState = _uiState)@@ -181,7 +187,13 @@ class SettingsViewModel @Inject constructor(activeProviderIdFlow = activeProviderIdFlow,preferencesRepository = preferencesRepository).collect { snapshot ->+ val previousProviderIds = _uiState.value.providers.map { it.id }.toSet()_uiState.update { it.applyPreferenceSnapshot(snapshot) }+ val currentProviderIds = snapshot.providers.map { it.id }.toSet()+ val removedIds = previousProviderIds - currentProviderIds+ if (removedIds.isNotEmpty()) {+ epgActions.cleanupEpgAssignmentsFor(removedIds)+ }}}}@@ -194,20 +206,20 @@ class SettingsViewModel @Inject constructor(providerActions.setActiveCombinedProfile(viewModelScope, profileId)}- fun createCombinedProfile(name: String, providerIds: List<Long>) {- providerActions.createCombinedProfile(viewModelScope, name, providerIds)+ fun createCombinedProfile(name: String, providerIds: List<Long>, onSuccess: () -> Unit = {}, onError: () -> Unit = {}) {+ providerActions.createCombinedProfile(viewModelScope, name, providerIds, onSuccess, onError)}fun deleteCombinedProfile(profileId: Long) {providerActions.deleteCombinedProfile(viewModelScope, profileId)}- fun addProviderToCombinedProfile(profileId: Long, providerId: Long) {- providerActions.addProviderToCombinedProfile(viewModelScope, profileId, providerId)+ fun addProviderToCombinedProfile(profileId: Long, providerId: Long, onSuccess: () -> Unit = {}, onError: () -> Unit = {}) {+ providerActions.addProviderToCombinedProfile(viewModelScope, profileId, providerId, onSuccess, onError)}- fun renameCombinedProfile(profileId: Long, name: String) {- providerActions.renameCombinedProfile(viewModelScope, profileId, name)+ fun renameCombinedProfile(profileId: Long, name: String, onSuccess: () -> Unit = {}, onError: () -> Unit = {}) {+ providerActions.renameCombinedProfile(viewModelScope, profileId, name, onSuccess, onError)}fun removeProviderFromCombinedProfile(profileId: Long, providerId: Long) {@@ -433,6 +445,12 @@ class SettingsViewModel @Inject constructor(}}+ fun setCenterTwoSlotMultiviewLayout(enabled: Boolean) {+ viewModelScope.launch {+ preferencesRepository.setMultiViewCenterTwoSlotLayout(enabled)+ }+ }+fun setPlayerMediaSessionEnabled(enabled: Boolean) {viewModelScope.launch {preferencesRepository.setPlayerMediaSessionEnabled(enabled)@@ -560,6 +578,7 @@ class SettingsViewModel @Inject constructor(}fun runInternetSpeedTest() {+ if (_uiState.value.isRunningInternetSpeedTest) returnviewModelScope.launch {_uiState.update { it.copy(isRunningInternetSpeedTest = true) }when (val result = internetSpeedTestRunner.run()) {@@ -687,8 +706,8 @@ class SettingsViewModel @Inject constructor(syncActions.retryWarningAction(viewModelScope, providerId, action)}- fun deleteProvider(providerId: Long) {- providerActions.deleteProvider(viewModelScope, providerId)+ fun deleteProvider(providerId: Long, onSuccess: () -> Unit = {}) {+ providerActions.deleteProvider(viewModelScope, providerId, onSuccess)}fun userMessageShown() {@@ -789,8 +808,8 @@ class SettingsViewModel @Inject constructor(epgActions.loadEpgAssignments(viewModelScope, providerId)}- fun addEpgSource(name: String, url: String) {- epgActions.addEpgSource(viewModelScope, name, url)+ fun addEpgSource(name: String, url: String, onSuccess: () -> Unit = {}, onError: () -> Unit = {}) {+ epgActions.addEpgSource(viewModelScope, name, url, onSuccess, onError)}fun setPendingDeleteEpgSource(id: Long?) {diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xmlindex c5fd437b..39998428 100644--- a/app/src/main/res/values/strings.xml+++ b/app/src/main/res/values/strings.xml@@ -89,6 +89,7 @@<string name="home_group_name_reserved">Cannot create group named \'Favorites\'</string><string name="home_group_name_duplicate">Group \'%1$s\' already exists</string><string name="home_group_name_invalid">Enter a group name</string>+ <string name="home_group_requires_provider_scope">Select a single provider source to create groups</string><string name="dashboard_title">Your Library, Ready</string>@@ -376,6 +377,8 @@<string name="settings_default_playback_speed">Default Playback Speed</string><string name="settings_audio_video_sync_default">A/V Sync Default</string><string name="settings_audio_video_sync_default_subtitle">Positive values delay audio relative to video.</string>+ <string name="settings_multiview_center_two_slot_layout">Center 2-Channel Multiview</string>+ <string name="settings_multiview_center_two_slot_layout_subtitle">When exactly two multiview slots are active, place them side by side in the middle of the screen instead of using the top row of the 2x2 grid.</string><string name="settings_media_session">System Media Session</string><string name="settings_media_session_subtitle">Expose playback to Android system media controls. Disable this if playback crashes on a specific device when opening the player.</string><string name="settings_live_timeshift">Enable Local Live Rewind</string>@@ -802,6 +805,8 @@<string name="search_type_to_search">Type at least 2 characters to search</string><string name="search_no_results">No results found for \'%1$s\'</string><string name="search_no_results_title">No matches</string>+ <string name="search_error_title">Search unavailable</string>+ <string name="search_error_subtitle">Some results could not be loaded. Try again.</string><string name="search_ready_title">Search the library</string><string name="search_no_provider_title">No active provider</string><string name="search_no_provider_subtitle">Add or activate a provider before searching the library.</string>@@ -851,6 +856,7 @@<string name="setup_info_m3u_body">Use a playlist link or import a local file.</string><string name="setup_info_manage_title">You can manage providers later</string><string name="setup_info_manage_body">Refresh, edit, or replace it later from Settings.</string>+ <string name="setup_import_backup">Import Backup</string><string name="badge_beta">Beta</string><string name="setup_xtream">Xtream Codes</string><string name="setup_stalker">Stalker</string>@@ -1077,6 +1083,8 @@<string name="epg_recording_conflict_cancel">Cancel</string><string name="epg_program_reminder_cancel">Cancel Reminder</string><string name="epg_program_reminder_loading">Updating Reminder...</string>+ <string name="notification_permission_reminder_required">Enable notifications for StreamVault to receive program reminders.</string>+ <string name="notification_permission_recording_alert_required">Enable notifications for StreamVault to receive recording failure alerts.</string><string name="epg_hero_no_schedule_hint">This channel has no guide entries in the current window.</string><string name="epg_hero_no_program_description">Program details are limited for this entry.</string><string name="epg_filter_label">Guide Filter</string>@@ -1238,6 +1246,9 @@<string name="movie_detail_play">Play</string><string name="movie_detail_resume_from">Resume from %1$s</string><string name="movie_detail_trailer">Trailer</string>+ <string name="movie_detail_related">More Like This</string>+ <string name="favorites_add">Add to favourites</string>+ <string name="favorites_remove">Remove from favourites</string><string name="movie_plot_fallback">No plot available</string><string name="movie_detail_director">Directed By:</string><string name="movie_detail_release_date">Release Date:</string>@@ -1380,6 +1391,8 @@<string name="dashboard_open_series">Open Series</string><string name="dashboard_library_ready">Your IPTV library is ready</string><string name="dashboard_open_live_tv">Open Live TV</string>+ <string name="dashboard_resume_unavailable">Watch history temporarily unavailable</string>+ <string name="dashboard_resume_unavailable_detail">Resume content could not be loaded. It will restore automatically.</string><string name="dashboard_pinned_channels_format">Pinned · %1$d channels</string><string name="dashboard_channels_format">%1$d channels</string>diff --git a/app/src/test/java/com/streamvault/app/navigation/ExternalDestinationTest.kt b/app/src/test/java/com/streamvault/app/navigation/ExternalDestinationTest.ktnew file mode 100644index 00000000..f10749d7--- /dev/null+++ b/app/src/test/java/com/streamvault/app/navigation/ExternalDestinationTest.kt@@ -0,0 +1,30 @@+package com.streamvault.app.navigation++import com.google.common.truth.Truth.assertThat+import org.junit.Test++class ExternalDestinationTest {++ @Test+ fun fromLegacyRoute_parsesSupportedRoutes() {+ assertThat(ExternalDestination.fromLegacyRoute("home"))+ .isEqualTo(ExternalDestination.Home)+ assertThat(ExternalDestination.fromLegacyRoute("provider_setup?providerId=-1&importUri="))+ .isEqualTo(ExternalDestination.ProviderSetup())+ assertThat(+ ExternalDestination.fromLegacyRoute(+ "series_detail/42?returnRoute=home"+ )+ ).isEqualTo(+ ExternalDestination.SeriesDetail(seriesId = 42L, returnRoute = "home")+ )+ }++ @Test+ fun fromLegacyRoute_rejectsUnsupportedRoutes() {+ assertThat(ExternalDestination.fromLegacyRoute("settings"))+ .isNull()+ assertThat(ExternalDestination.fromLegacyRoute("series_detail/not-a-number"))+ .isNull()+ }+}\ No newline at end of filediff --git a/app/src/test/java/com/streamvault/app/navigation/PlaybackHistoryNavigationTest.kt b/app/src/test/java/com/streamvault/app/navigation/PlaybackHistoryNavigationTest.ktnew file mode 100644index 00000000..a9891405--- /dev/null+++ b/app/src/test/java/com/streamvault/app/navigation/PlaybackHistoryNavigationTest.kt@@ -0,0 +1,33 @@+package com.streamvault.app.navigation++import com.google.common.truth.Truth.assertThat+import com.streamvault.domain.model.ContentType+import com.streamvault.domain.model.PlaybackHistory+import org.junit.Test++class PlaybackHistoryNavigationTest {++ @Test+ fun toPlayerNavigationRequest_preservesSeriesEpisodeIdentity() {+ val history = PlaybackHistory(+ contentId = 77L,+ contentType = ContentType.SERIES_EPISODE,+ providerId = 9L,+ title = "Episode",+ posterUrl = "https://example.com/poster.jpg",+ streamUrl = "https://example.com/episode.m3u8",+ seriesId = 12L,+ seasonNumber = 3,+ episodeNumber = 4+ )++ val request = history.toPlayerNavigationRequest()++ assertThat(request.internalId).isEqualTo(77L)+ assertThat(request.providerId).isEqualTo(9L)+ assertThat(request.contentType).isEqualTo(ContentType.SERIES_EPISODE.name)+ assertThat(request.seriesId).isEqualTo(12L)+ assertThat(request.seasonNumber).isEqualTo(3)+ assertThat(request.episodeNumber).isEqualTo(4)+ }+}\ No newline at end of filediff --git a/app/src/test/java/com/streamvault/app/player/PlaybackProgressGuardrailTest.kt b/app/src/test/java/com/streamvault/app/player/PlaybackProgressGuardrailTest.ktnew file mode 100644index 00000000..e5c91271--- /dev/null+++ b/app/src/test/java/com/streamvault/app/player/PlaybackProgressGuardrailTest.kt@@ -0,0 +1,56 @@+package com.streamvault.app.player++import com.google.common.truth.Truth.assertThat+import java.nio.file.Files+import java.nio.file.Path+import org.junit.Test++class PlaybackProgressGuardrailTest {++ @Test+ fun `app and player sources do not call direct repository progress apis`() {+ val projectRoot = resolveProjectRoot()+ val violations = buildList {+ addAll(findViolations(projectRoot, "app/src/main", ".updateWatchProgress("))+ addAll(findViolations(projectRoot, "app/src/main", ".updateEpisodeWatchProgress("))+ addAll(findViolations(projectRoot, "player/src/main", ".updateWatchProgress("))+ addAll(findViolations(projectRoot, "player/src/main", ".updateEpisodeWatchProgress("))+ }++ assertThat(violations).isEmpty()+ }++ private fun resolveProjectRoot(): Path {+ val cwd = Path.of(System.getProperty("user.dir")).toAbsolutePath().normalize()+ if (Files.exists(cwd.resolve("app/src/main"))) {+ return cwd+ }+ val parent = cwd.parent+ check(parent != null && Files.exists(parent.resolve("app/src/main"))) {+ "Could not resolve project root from $cwd"+ }+ return parent+ }++ private fun findViolations(projectRoot: Path, relativeSourceDir: String, token: String): List<String> {+ val sourceRoot = projectRoot.resolve(relativeSourceDir)+ if (!Files.exists(sourceRoot)) {+ return emptyList()+ }++ val violations = mutableListOf<String>()+ Files.walk(sourceRoot).use { paths ->+ paths+ .filter { Files.isRegularFile(it) }+ .filter { it.toString().endsWith(".kt") || it.toString().endsWith(".java") }+ .forEach { path ->+ Files.readAllLines(path).forEachIndexed { index, line ->+ if (line.contains(token)) {+ violations += "${projectRoot.relativize(path)}:${index + 1}: ${line.trim()}"+ }+ }+ }+ }+ return violations+ }+}\ No newline at end of filediff --git a/app/src/test/java/com/streamvault/app/tv/WatchNextManagerTest.kt b/app/src/test/java/com/streamvault/app/tv/WatchNextManagerTest.ktnew file mode 100644index 00000000..4472bf5d--- /dev/null+++ b/app/src/test/java/com/streamvault/app/tv/WatchNextManagerTest.kt@@ -0,0 +1,45 @@+package com.streamvault.app.tv++import com.google.common.truth.Truth.assertThat+import com.streamvault.domain.model.ContentType+import com.streamvault.domain.model.PlaybackHistory+import org.junit.Test++class WatchNextManagerTest {++ @Test+ fun selectWatchNextHistoryEntries_keepsOnlyActiveProviderRows() {+ val rows = selectWatchNextHistoryEntries(+ activeProviderId = 1L,+ historyEntries = listOf(+ history(contentId = 10L, providerId = 1L, lastWatchedAt = 300L),+ history(contentId = 11L, providerId = 2L, lastWatchedAt = 400L),+ history(contentId = 12L, providerId = 1L, lastWatchedAt = 200L)+ )+ )++ assertThat(rows.map { it.providerId }).containsExactly(1L, 1L)+ assertThat(rows.map { it.contentId }).containsExactly(10L, 12L).inOrder()+ }++ @Test+ fun selectWatchNextHistoryEntries_returnsEmptyWithoutActiveProvider() {+ val rows = selectWatchNextHistoryEntries(+ activeProviderId = null,+ historyEntries = listOf(history(contentId = 10L, providerId = 1L, lastWatchedAt = 300L))+ )++ assertThat(rows).isEmpty()+ }++ private fun history(contentId: Long, providerId: Long, lastWatchedAt: Long): PlaybackHistory = PlaybackHistory(+ contentId = contentId,+ contentType = ContentType.SERIES_EPISODE,+ providerId = providerId,+ title = "Episode $contentId",+ streamUrl = "https://example.com/$contentId.m3u8",+ resumePositionMs = 1_000L,+ totalDurationMs = 10_000L,+ lastWatchedAt = lastWatchedAt+ )+}\ No newline at end of filediff --git a/app/src/test/java/com/streamvault/app/tvinput/TvInputChannelSyncManagerTest.kt b/app/src/test/java/com/streamvault/app/tvinput/TvInputChannelSyncManagerTest.ktnew file mode 100644index 00000000..0d92a6af--- /dev/null+++ b/app/src/test/java/com/streamvault/app/tvinput/TvInputChannelSyncManagerTest.kt@@ -0,0 +1,53 @@+package com.streamvault.app.tvinput++import com.google.common.truth.Truth.assertThat+import com.streamvault.domain.model.Channel+import com.streamvault.domain.model.Program+import org.junit.Test++class TvInputChannelSyncManagerTest {++ @Test+ fun shouldReplaceTvPrograms_preservesGuideWhenMappedChannelHasEmptySnapshot() {+ val channel = Channel(+ id = 1L,+ name = "News",+ providerId = 2L,+ epgChannelId = "news-hd"+ )++ assertThat(shouldReplaceTvPrograms(channel, emptyList())).isFalse()+ }++ @Test+ fun shouldReplaceTvPrograms_allowsReplacementWhenFreshProgramsExist() {+ val channel = Channel(+ id = 1L,+ name = "News",+ providerId = 2L,+ epgChannelId = "news-hd"+ )+ val programs = listOf(+ Program(+ channelId = "news-hd",+ title = "Morning News",+ startTime = 1_000L,+ endTime = 2_000L+ )+ )++ assertThat(shouldReplaceTvPrograms(channel, programs)).isTrue()+ }++ @Test+ fun shouldReplaceTvPrograms_allowsClearingWhenChannelHasNoGuideIdentity() {+ val channel = Channel(+ id = 1L,+ name = "No EPG",+ providerId = 2L,+ epgChannelId = null+ )++ assertThat(shouldReplaceTvPrograms(channel, emptyList())).isTrue()+ }+}\ No newline at end of filediff --git a/app/src/test/java/com/streamvault/app/ui/model/ArchivePlaybackTest.kt b/app/src/test/java/com/streamvault/app/ui/model/ArchivePlaybackTest.ktnew file mode 100644index 00000000..6ccfb081--- /dev/null+++ b/app/src/test/java/com/streamvault/app/ui/model/ArchivePlaybackTest.kt@@ -0,0 +1,87 @@+package com.streamvault.app.ui.model++import com.google.common.truth.Truth.assertThat+import com.streamvault.domain.model.Channel+import com.streamvault.domain.model.Program+import org.junit.Test++class ArchivePlaybackTest {++ @Test+ fun `catch-up channel does not allow future program replay`() {+ val now = 1_000_000L+ val channel = Channel(+ id = 42L,+ name = "News",+ providerId = 7L,+ catchUpSupported = true,+ catchUpDays = 2+ )+ val program = Program(+ channelId = "news",+ title = "Late Bulletin",+ startTime = now + 60_000L,+ endTime = now + 120_000L+ )++ assertThat(channel.isArchivePlayable(program, now)).isFalse()+ }++ @Test+ fun `catch-up channel allows completed program inside catch-up window`() {+ val now = 3 * 86_400_000L+ val channel = Channel(+ id = 42L,+ name = "News",+ providerId = 7L,+ catchUpSupported = true,+ catchUpDays = 2+ )+ val program = Program(+ channelId = "news",+ title = "Morning Update",+ startTime = now - 86_400_000L,+ endTime = now - 30_000L+ )++ assertThat(channel.isArchivePlayable(program, now)).isTrue()+ }++ @Test+ fun `provider archive flag keeps replay enabled without catch-up support`() {+ val channel = Channel(+ id = 42L,+ name = "News",+ providerId = 7L+ )+ val program = Program(+ channelId = "news",+ title = "Curated Replay",+ startTime = 100_000L,+ endTime = 200_000L,+ hasArchive = true+ )++ assertThat(channel.isArchivePlayable(program, now = 150_000L)).isTrue()+ }++ @Test+ fun `catch-up window excludes expired programs`() {+ val now = 5 * 86_400_000L+ val channel = Channel(+ id = 42L,+ name = "News",+ providerId = 7L,+ catchUpSupported = true,+ catchUpDays = 2+ )+ val program = Program(+ channelId = "news",+ title = "Old Bulletin",+ startTime = now - (3 * 86_400_000L),+ endTime = now - (3 * 86_400_000L) + 60_000L+ )++ assertThat(channel.isArchivePlayable(program, now)).isFalse()+ }+}\ No newline at end of filediff --git a/app/src/test/java/com/streamvault/app/ui/screens/epg/EpgViewModelTest.kt b/app/src/test/java/com/streamvault/app/ui/screens/epg/EpgViewModelTest.ktindex 144020b5..20350c9f 100644--- a/app/src/test/java/com/streamvault/app/ui/screens/epg/EpgViewModelTest.kt+++ b/app/src/test/java/com/streamvault/app/ui/screens/epg/EpgViewModelTest.kt@@ -34,6 +34,7 @@ import kotlinx.coroutines.ExperimentalCoroutinesApiimport kotlinx.coroutines.flow.flowOfimport kotlinx.coroutines.runBlockingimport kotlinx.coroutines.test.StandardTestDispatcher+import kotlinx.coroutines.test.advanceTimeByimport kotlinx.coroutines.test.advanceUntilIdleimport kotlinx.coroutines.test.resetMainimport kotlinx.coroutines.test.runTest@@ -42,6 +43,7 @@ import org.junit.Afterimport org.junit.Beforeimport org.junit.Testimport org.mockito.kotlin.any+import org.mockito.kotlin.anyOrNullimport org.mockito.kotlin.eqimport org.mockito.kotlin.mockimport org.mockito.kotlin.atLeastOnce@@ -81,6 +83,7 @@ class EpgViewModelTest {whenever(epgRepository.getResolvedProgramsForChannels(any(), any(), any(), any())).thenReturn(emptyMap())whenever(epgRepository.getProgramsForChannelsSnapshot(any(), any(), any(), any())).thenReturn(emptyMap())whenever(epgRepository.getProgramsForChannels(any(), any(), any(), any())).thenReturn(flowOf(emptyMap()))+ whenever(epgRepository.searchPrograms(any(), any(), any(), any(), anyOrNull(), any())).thenReturn(flowOf(emptyList()))}whenever(favoriteRepository.getGroups(any<Long>(), eq(ContentType.LIVE))).thenReturn(flowOf(emptyList()))whenever(favoriteRepository.getGroups(any<List<Long>>(), eq(ContentType.LIVE))).thenReturn(flowOf(emptyList()))@@ -157,6 +160,7 @@ class EpgViewModelTest {whenever(favoriteRepository.getFavorites(provider.id, ContentType.LIVE)).thenReturn(flowOf(emptyList()))whenever(preferencesRepository.guideDensity).thenReturn(flowOf(null))whenever(preferencesRepository.guideChannelMode).thenReturn(flowOf(null))+ whenever(preferencesRepository.guideDefaultCategoryId).thenReturn(flowOf(ChannelRepository.ALL_CHANNELS_ID))whenever(preferencesRepository.guideFavoritesOnly).thenReturn(flowOf(false))whenever(preferencesRepository.guideScheduledOnly).thenReturn(flowOf(false))whenever(preferencesRepository.guideAnchorTime).thenReturn(flowOf(null))@@ -189,16 +193,194 @@ class EpgViewModelTest {}@Test- fun `guide search uses repository program search within selected category`() = runTest {+ fun `guide fallback loads native programs keyed by stream id`() = runTest {val provider = Provider(id = 1L,name = "Provider",type = ProviderType.M3U,serverUrl = "https://provider.example.com")+ val streamId = 101Lval channels = listOf(- Channel(id = 1L, name = "One", providerId = provider.id, epgChannelId = "one", categoryId = 10L),- Channel(id = 2L, name = "Two", providerId = provider.id, epgChannelId = "two", categoryId = 10L)+ Channel(id = 1L, name = "One", providerId = provider.id, streamId = streamId)+ )+ whenever(providerRepository.getActiveProvider()).thenReturn(flowOf(provider))+ whenever(preferencesRepository.getHiddenCategoryIds(provider.id, ContentType.LIVE)).thenReturn(flowOf(emptySet()))+ whenever(preferencesRepository.getCategorySortMode(provider.id, ContentType.LIVE)).thenReturn(flowOf(CategorySortMode.DEFAULT))+ whenever(parentalControlManager.unlockedCategoriesForProvider(provider.id)).thenReturn(flowOf(emptySet()))+ whenever(channelRepository.getCategories(provider.id)).thenReturn(flowOf(listOf(Category(id = 10L, name = "News"))))+ whenever(channelRepository.getChannels(provider.id)).thenReturn(flowOf(channels))+ whenever(channelRepository.getChannelsByCategoryPage(provider.id, ChannelRepository.ALL_CHANNELS_ID, EpgViewModel.MAX_CHANNELS)).thenReturn(flowOf(channels))+ whenever(channelRepository.getChannelsWithoutErrorsPage(provider.id, ChannelRepository.ALL_CHANNELS_ID, EpgViewModel.MAX_CHANNELS)).thenReturn(flowOf(channels))+ whenever(favoriteRepository.getFavorites(provider.id, ContentType.LIVE)).thenReturn(flowOf(emptyList()))+ whenever(preferencesRepository.guideDensity).thenReturn(flowOf(null))+ whenever(preferencesRepository.guideChannelMode).thenReturn(flowOf(null))+ whenever(preferencesRepository.guideDefaultCategoryId).thenReturn(flowOf(ChannelRepository.ALL_CHANNELS_ID))+ whenever(preferencesRepository.guideFavoritesOnly).thenReturn(flowOf(false))+ whenever(preferencesRepository.guideScheduledOnly).thenReturn(flowOf(false))+ whenever(preferencesRepository.guideAnchorTime).thenReturn(flowOf(null))+ whenever(epgRepository.getResolvedProgramsForChannels(eq(provider.id), any(), any(), any())).thenReturn(emptyMap())+ whenever(epgRepository.getProgramsForChannelsSnapshot(eq(provider.id), eq(listOf(streamId.toString())), any(), any())).thenReturn(+ mapOf(+ streamId.toString() to listOf(+ Program(+ id = 1L,+ channelId = streamId.toString(),+ title = "Headline",+ startTime = System.currentTimeMillis() - 60_000L,+ endTime = System.currentTimeMillis() + 60_000L,+ providerId = provider.id+ )+ )+ )+ )++ val viewModel = createViewModel()++ advanceUntilIdle()+ waitForUiState { viewModel.uiState.value.programsByChannel[streamId.toString()].orEmpty().isNotEmpty() }++ assertThat(viewModel.uiState.value.programsByChannel.keys).containsExactly(streamId.toString())+ verify(epgRepository, atLeastOnce()).getProgramsForChannelsSnapshot(eq(provider.id), eq(listOf(streamId.toString())), any(), any())+ }++ @Test+ fun `guide updates provider metadata when active provider id stays the same`() = runTest {+ val originalProvider = Provider(+ id = 1L,+ name = "Provider One",+ type = ProviderType.M3U,+ serverUrl = "https://provider.example.com"+ )+ val renamedProvider = originalProvider.copy(name = "Provider Renamed")++ whenever(providerRepository.getActiveProvider()).thenReturn(flowOf(originalProvider, renamedProvider))+ whenever(preferencesRepository.getHiddenCategoryIds(originalProvider.id, ContentType.LIVE)).thenReturn(flowOf(emptySet()))+ whenever(preferencesRepository.getCategorySortMode(originalProvider.id, ContentType.LIVE)).thenReturn(flowOf(CategorySortMode.DEFAULT))+ whenever(parentalControlManager.unlockedCategoriesForProvider(originalProvider.id)).thenReturn(flowOf(emptySet()))+ whenever(channelRepository.getCategories(originalProvider.id)).thenReturn(flowOf(listOf(Category(id = 10L, name = "News"))))+ whenever(channelRepository.getChannelsByCategoryPage(originalProvider.id, ChannelRepository.ALL_CHANNELS_ID, EpgViewModel.MAX_CHANNELS)).thenReturn(flowOf(emptyList()))+ whenever(channelRepository.getChannelsWithoutErrorsPage(originalProvider.id, ChannelRepository.ALL_CHANNELS_ID, EpgViewModel.MAX_CHANNELS)).thenReturn(flowOf(emptyList()))+ whenever(favoriteRepository.getFavorites(originalProvider.id, ContentType.LIVE)).thenReturn(flowOf(emptyList()))+ whenever(preferencesRepository.guideDensity).thenReturn(flowOf(null))+ whenever(preferencesRepository.guideChannelMode).thenReturn(flowOf(null))+ whenever(preferencesRepository.guideFavoritesOnly).thenReturn(flowOf(false))+ whenever(preferencesRepository.guideScheduledOnly).thenReturn(flowOf(false))+ whenever(preferencesRepository.guideAnchorTime).thenReturn(flowOf(null))+ whenever(epgRepository.getResolvedProgramsForChannels(eq(originalProvider.id), any(), any(), any())).thenReturn(emptyMap())+ whenever(epgRepository.getProgramsForChannelsSnapshot(eq(originalProvider.id), any(), any(), any())).thenReturn(emptyMap())++ val viewModel = createViewModel()++ advanceUntilIdle()+ waitForUiState { viewModel.uiState.value.currentProviderName == renamedProvider.name }++ assertThat(viewModel.uiState.value.currentProviderName).isEqualTo(renamedProvider.name)+ }++ @Test+ fun `guide search finds matching program beyond initially loaded category page`() = runTest {+ val provider = Provider(+ id = 1L,+ name = "Provider",+ type = ProviderType.M3U,+ serverUrl = "https://provider.example.com"+ )+ val loadedChannel = Channel(id = 1L, name = "One", providerId = provider.id, epgChannelId = "one", categoryId = 10L)+ val laterChannel = Channel(id = 2L, name = "Two", providerId = provider.id, epgChannelId = "two", categoryId = 10L)+ val channels = listOf(+ loadedChannel,+ laterChannel+ )+ whenever(providerRepository.getActiveProvider()).thenReturn(flowOf(provider))+ whenever(preferencesRepository.getHiddenCategoryIds(provider.id, ContentType.LIVE)).thenReturn(flowOf(emptySet()))+ whenever(preferencesRepository.getCategorySortMode(provider.id, ContentType.LIVE)).thenReturn(flowOf(CategorySortMode.DEFAULT))+ whenever(parentalControlManager.unlockedCategoriesForProvider(provider.id)).thenReturn(flowOf(emptySet()))+ whenever(channelRepository.getCategories(provider.id)).thenReturn(flowOf(listOf(Category(id = 10L, name = "News"))))+ whenever(channelRepository.getChannels(provider.id)).thenReturn(flowOf(channels))+ whenever(channelRepository.getChannelsByCategory(provider.id, 10L)).thenReturn(flowOf(channels))+ whenever(channelRepository.getChannelsByCategoryPage(provider.id, ChannelRepository.ALL_CHANNELS_ID, EpgViewModel.MAX_CHANNELS)).thenReturn(flowOf(listOf(loadedChannel)))+ whenever(channelRepository.getChannelsByCategoryPage(provider.id, 10L, EpgViewModel.MAX_CHANNELS)).thenReturn(flowOf(listOf(loadedChannel)))+ whenever(channelRepository.getChannelsWithoutErrorsPage(provider.id, ChannelRepository.ALL_CHANNELS_ID, EpgViewModel.MAX_CHANNELS)).thenReturn(flowOf(listOf(loadedChannel)))+ whenever(channelRepository.getChannelsWithoutErrorsPage(provider.id, 10L, EpgViewModel.MAX_CHANNELS)).thenReturn(flowOf(listOf(loadedChannel)))+ whenever(favoriteRepository.getFavorites(provider.id, ContentType.LIVE)).thenReturn(flowOf(emptyList()))+ whenever(preferencesRepository.guideDensity).thenReturn(flowOf(null))+ whenever(preferencesRepository.guideChannelMode).thenReturn(flowOf(null))+ whenever(preferencesRepository.guideDefaultCategoryId).thenReturn(flowOf(ChannelRepository.ALL_CHANNELS_ID))+ whenever(preferencesRepository.guideFavoritesOnly).thenReturn(flowOf(false))+ whenever(preferencesRepository.guideScheduledOnly).thenReturn(flowOf(false))+ whenever(preferencesRepository.guideAnchorTime).thenReturn(flowOf(null))+ whenever(epgRepository.getResolvedProgramsForChannels(eq(provider.id), any(), any(), any())).thenReturn(emptyMap())+ whenever(epgRepository.getProgramsForChannelsSnapshot(eq(provider.id), eq(listOf("one")), any(), any())).thenReturn(+ mapOf(+ "one" to listOf(+ Program(+ id = 1L,+ channelId = "one",+ title = "Headline",+ startTime = System.currentTimeMillis() - 60_000L,+ endTime = System.currentTimeMillis() + 60_000L,+ providerId = provider.id+ )+ )+ )+ )+ whenever(epgRepository.searchPrograms(eq(provider.id), eq("Headline"), any(), any(), eq(10L), any())).thenReturn(+ flowOf(+ listOf(+ Program(+ id = 2L,+ channelId = "two",+ title = "Headline Update",+ startTime = System.currentTimeMillis() - 60_000L,+ endTime = System.currentTimeMillis() + 60_000L,+ providerId = provider.id+ )+ )+ )+ )++ val viewModel = createViewModel()++ advanceUntilIdle()+ waitForUiState {+ viewModel.uiState.value.selectedCategoryId == ChannelRepository.ALL_CHANNELS_ID &&+ !viewModel.uiState.value.isRefreshing+ }+ viewModel.selectCategory(10L)+ waitForUiState {+ viewModel.uiState.value.selectedCategoryId == 10L &&+ !viewModel.uiState.value.isRefreshing &&+ viewModel.uiState.value.channels.map { it.id } == listOf(1L) &&+ viewModel.uiState.value.programsByChannel.keys == setOf("one")+ }+ viewModel.updateProgramSearchQuery("Headline")+ testDispatcher.scheduler.advanceTimeBy(200L)+ advanceUntilIdle()+ waitForUiState {+ viewModel.uiState.value.programSearchQuery == "Headline" &&+ viewModel.uiState.value.channels.map { it.id } == listOf(2L) &&+ viewModel.uiState.value.programsByChannel.keys == setOf("two")+ }++ assertThat(viewModel.uiState.value.channels.map { it.id }).containsExactly(2L)+ assertThat(viewModel.uiState.value.programsByChannel.keys).containsExactly("two")+ assertThat(viewModel.uiState.value.programSearchQuery).isEqualTo("Headline")+ verify(epgRepository).searchPrograms(eq(provider.id), eq("Headline"), any(), any(), eq(10L), any())+ verify(epgRepository, never()).getProgramsForChannel(any(), any(), any(), any())+ }++ @Test+ fun `guide search by channel name preserves loaded schedule`() = runTest {+ val provider = Provider(+ id = 1L,+ name = "Provider",+ type = ProviderType.M3U,+ serverUrl = "https://provider.example.com"+ )+ val channels = listOf(+ Channel(id = 1L, name = "BBC One", providerId = provider.id, epgChannelId = "one", categoryId = 10L, categoryName = "News"),+ Channel(id = 2L, name = "Sports Two", providerId = provider.id, epgChannelId = "two", categoryId = 10L, categoryName = "News"))whenever(providerRepository.getActiveProvider()).thenReturn(flowOf(provider))whenever(preferencesRepository.getHiddenCategoryIds(provider.id, ContentType.LIVE)).thenReturn(flowOf(emptySet()))@@ -214,6 +396,7 @@ class EpgViewModelTest {whenever(favoriteRepository.getFavorites(provider.id, ContentType.LIVE)).thenReturn(flowOf(emptyList()))whenever(preferencesRepository.guideDensity).thenReturn(flowOf(null))whenever(preferencesRepository.guideChannelMode).thenReturn(flowOf(null))+ whenever(preferencesRepository.guideDefaultCategoryId).thenReturn(flowOf(ChannelRepository.ALL_CHANNELS_ID))whenever(preferencesRepository.guideFavoritesOnly).thenReturn(flowOf(false))whenever(preferencesRepository.guideScheduledOnly).thenReturn(flowOf(false))whenever(preferencesRepository.guideAnchorTime).thenReturn(flowOf(null))@@ -224,17 +407,25 @@ class EpgViewModelTest {Program(id = 1L,channelId = "one",- title = "Headline",+ title = "Breakfast",startTime = System.currentTimeMillis() - 60_000L,endTime = System.currentTimeMillis() + 60_000L,providerId = provider.id+ ),+ Program(+ id = 2L,+ channelId = "one",+ title = "Midday Update",+ startTime = System.currentTimeMillis() + 60_000L,+ endTime = System.currentTimeMillis() + 120_000L,+ providerId = provider.id)),"two" to listOf(Program(- id = 2L,+ id = 3L,channelId = "two",- title = "Weather",+ title = "Scoreboard",startTime = System.currentTimeMillis() - 60_000L,endTime = System.currentTimeMillis() + 60_000L,providerId = provider.id@@ -246,18 +437,30 @@ class EpgViewModelTest {val viewModel = createViewModel()advanceUntilIdle()+ waitForUiState {+ viewModel.uiState.value.selectedCategoryId == ChannelRepository.ALL_CHANNELS_ID &&+ !viewModel.uiState.value.isRefreshing+ }viewModel.selectCategory(10L)- viewModel.updateProgramSearchQuery("Headline")+ waitForUiState {+ viewModel.uiState.value.selectedCategoryId == 10L &&+ !viewModel.uiState.value.isRefreshing &&+ viewModel.uiState.value.channels.map { it.id } == listOf(1L, 2L) &&+ viewModel.uiState.value.programsByChannel.keys == setOf("one", "two")+ }+ viewModel.updateProgramSearchQuery("BBC")+ testDispatcher.scheduler.advanceTimeBy(200L)advanceUntilIdle()waitForUiState {- viewModel.uiState.value.channels.map { it.id } == listOf(1L) &&- viewModel.uiState.value.programsByChannel.keys == setOf("one")+ viewModel.uiState.value.programSearchQuery == "BBC" &&+ viewModel.uiState.value.channels.map { it.id } == listOf(1L) &&+ viewModel.uiState.value.programsByChannel["one"]?.size == 2}assertThat(viewModel.uiState.value.channels.map { it.id }).containsExactly(1L)- assertThat(viewModel.uiState.value.programsByChannel.keys).containsExactly("one")- assertThat(viewModel.uiState.value.programSearchQuery).isEqualTo("Headline")- verify(epgRepository, never()).getProgramsForChannel(any(), any(), any(), any())+ assertThat(viewModel.uiState.value.programsByChannel["one"]?.map(Program::title))+ .containsExactly("Breakfast", "Midday Update")+ assertThat(viewModel.uiState.value.programSearchQuery).isEqualTo("BBC")}@Test@@ -303,6 +506,9 @@ class EpgViewModelTest {whenever(channelRepository.getChannelsWithoutErrorsPage(provider.id, 10L, EpgViewModel.MAX_CHANNELS)).thenReturn(flowOf(listOf(healthyChannel)))+ whenever(channelRepository.getChannelsByIds(listOf(unhealthyFavorite.id))).thenReturn(+ flowOf(listOf(unhealthyFavorite))+ )whenever(favoriteRepository.getFavorites(provider.id, ContentType.LIVE)).thenReturn(flowOf(listOf(Favorite(providerId = provider.id, contentId = unhealthyFavorite.id, contentType = ContentType.LIVE))))@@ -324,6 +530,91 @@ class EpgViewModelTest {assertThat(viewModel.uiState.value.channels.map { it.id }).containsExactly(unhealthyFavorite.id)}+ @Test+ fun `guide favorites only loads favorite channels outside first category page`() = runTest {+ val provider = Provider(+ id = 1L,+ name = "Provider",+ type = ProviderType.M3U,+ serverUrl = "https://provider.example.com"+ )+ val firstPageChannel = Channel(+ id = 1L,+ name = "Paged Channel",+ providerId = provider.id,+ epgChannelId = "paged",+ number = 1,+ categoryId = 10L+ )+ val favoriteOutsidePage = Channel(+ id = 2L,+ name = "Favorite Outside Page",+ providerId = provider.id,+ epgChannelId = "favorite",+ number = 99,+ categoryId = 10L+ )++ whenever(providerRepository.getActiveProvider()).thenReturn(flowOf(provider))+ whenever(preferencesRepository.getHiddenCategoryIds(provider.id, ContentType.LIVE)).thenReturn(flowOf(emptySet()))+ whenever(preferencesRepository.getCategorySortMode(provider.id, ContentType.LIVE)).thenReturn(flowOf(CategorySortMode.DEFAULT))+ whenever(parentalControlManager.unlockedCategoriesForProvider(provider.id)).thenReturn(flowOf(emptySet()))+ whenever(channelRepository.getCategories(provider.id)).thenReturn(flowOf(listOf(Category(id = 10L, name = "News"))))+ whenever(channelRepository.getChannelsByCategoryPage(provider.id, ChannelRepository.ALL_CHANNELS_ID, EpgViewModel.MAX_CHANNELS)).thenReturn(+ flowOf(listOf(firstPageChannel))+ )+ whenever(channelRepository.getChannelsWithoutErrorsPage(provider.id, ChannelRepository.ALL_CHANNELS_ID, EpgViewModel.MAX_CHANNELS)).thenReturn(+ flowOf(listOf(firstPageChannel))+ )+ whenever(channelRepository.getChannelsByCategoryPage(provider.id, 10L, EpgViewModel.MAX_CHANNELS)).thenReturn(+ flowOf(listOf(firstPageChannel))+ )+ whenever(channelRepository.getChannelsWithoutErrorsPage(provider.id, 10L, EpgViewModel.MAX_CHANNELS)).thenReturn(+ flowOf(listOf(firstPageChannel))+ )+ whenever(channelRepository.getChannelsByCategory(provider.id, 10L)).thenReturn(+ flowOf(listOf(firstPageChannel, favoriteOutsidePage))+ )+ whenever(channelRepository.getChannelsByIds(listOf(favoriteOutsidePage.id))).thenReturn(+ flowOf(listOf(favoriteOutsidePage))+ )+ whenever(favoriteRepository.getFavorites(provider.id, ContentType.LIVE)).thenReturn(+ flowOf(listOf(Favorite(providerId = provider.id, contentId = favoriteOutsidePage.id, contentType = ContentType.LIVE)))+ )+ whenever(preferencesRepository.guideDensity).thenReturn(flowOf(null))+ whenever(preferencesRepository.guideChannelMode).thenReturn(flowOf(null))+ whenever(preferencesRepository.guideDefaultCategoryId).thenReturn(flowOf(ChannelRepository.ALL_CHANNELS_ID))+ whenever(preferencesRepository.guideFavoritesOnly).thenReturn(flowOf(false))+ whenever(preferencesRepository.guideScheduledOnly).thenReturn(flowOf(false))+ whenever(preferencesRepository.guideAnchorTime).thenReturn(flowOf(null))+ whenever(epgRepository.getResolvedProgramsForChannels(eq(provider.id), any(), any(), any())).thenReturn(emptyMap())+ whenever(epgRepository.getProgramsForChannelsSnapshot(eq(provider.id), any(), any(), any())).thenReturn(emptyMap())++ val viewModel = createViewModel()++ advanceUntilIdle()+ waitForUiState {+ viewModel.uiState.value.selectedCategoryId == ChannelRepository.ALL_CHANNELS_ID &&+ !viewModel.uiState.value.isRefreshing+ }+ viewModel.selectCategory(10L)+ waitForUiState {+ viewModel.uiState.value.selectedCategoryId == 10L &&+ !viewModel.uiState.value.isRefreshing &&+ viewModel.uiState.value.channels.map { it.id } == listOf(firstPageChannel.id)+ }+ viewModel.toggleFavoritesOnly()+ advanceUntilIdle()+ waitForUiState {+ viewModel.uiState.value.showFavoritesOnly &&+ !viewModel.uiState.value.isRefreshing &&+ viewModel.uiState.value.channels.map { it.id } == listOf(favoriteOutsidePage.id)+ }++ assertThat(viewModel.uiState.value.channels.map { it.id }).containsExactly(favoriteOutsidePage.id)+ verify(channelRepository, atLeastOnce()).getChannelsByIds(listOf(favoriteOutsidePage.id))+ }+@Testfun `guide defaults to all channels when favorite startup category is empty`() = runTest {val provider = Provider(diff --git a/app/src/test/java/com/streamvault/app/ui/screens/epg/GuideDateTimeTest.kt b/app/src/test/java/com/streamvault/app/ui/screens/epg/GuideDateTimeTest.ktnew file mode 100644index 00000000..3c60198c--- /dev/null+++ b/app/src/test/java/com/streamvault/app/ui/screens/epg/GuideDateTimeTest.kt@@ -0,0 +1,57 @@+package com.streamvault.app.ui.screens.epg++import com.google.common.truth.Truth.assertThat+import java.time.Instant+import java.time.LocalDate+import java.time.LocalDateTime+import java.time.ZoneId+import org.junit.Test++class GuideDateTimeTest {++ @Test+ fun `guide prime time anchor uses selected local day`() {+ val zoneId = ZoneId.of("America/New_York")+ val anchor = LocalDateTime.of(2026, 5, 2, 10, 0)+ .atZone(zoneId)+ .toInstant()+ .toEpochMilli()++ val primeTime = guidePrimeTimeAnchor(anchor, EpgViewModel.PRIME_TIME_HOUR, zoneId)+ val localPrimeTime = Instant.ofEpochMilli(primeTime).atZone(zoneId).toLocalDateTime()++ assertThat(localPrimeTime).isEqualTo(LocalDateTime.of(2026, 5, 2, 20, 0))+ }++ @Test+ fun `jump guide anchor to day preserves local time across dst transition`() {+ val zoneId = ZoneId.of("America/New_York")+ val anchor = LocalDateTime.of(2026, 3, 7, 23, 30)+ .atZone(zoneId)+ .toInstant()+ .toEpochMilli()+ val targetDayStart = LocalDate.of(2026, 3, 8)+ .atStartOfDay(zoneId)+ .toInstant()+ .toEpochMilli()++ val jumpedAnchor = jumpGuideAnchorToDay(anchor, targetDayStart, zoneId)+ val localJumpedAnchor = Instant.ofEpochMilli(jumpedAnchor).atZone(zoneId).toLocalDateTime()++ assertThat(localJumpedAnchor).isEqualTo(LocalDateTime.of(2026, 3, 8, 23, 30))+ }++ @Test+ fun `shift guide day start advances by local calendar day across dst`() {+ val zoneId = ZoneId.of("America/New_York")+ val dayStart = LocalDate.of(2026, 3, 8)+ .atStartOfDay(zoneId)+ .toInstant()+ .toEpochMilli()++ val shiftedDayStart = shiftGuideDayStart(dayStart, 1, zoneId)+ val shiftedLocalDate = Instant.ofEpochMilli(shiftedDayStart).atZone(zoneId).toLocalDate()++ assertThat(shiftedLocalDate).isEqualTo(LocalDate.of(2026, 3, 9))+ }+}\ No newline at end of filediff --git a/app/src/test/java/com/streamvault/app/ui/screens/player/PlayerCatchUpActionsTest.kt b/app/src/test/java/com/streamvault/app/ui/screens/player/PlayerCatchUpActionsTest.ktnew file mode 100644index 00000000..ab367290--- /dev/null+++ b/app/src/test/java/com/streamvault/app/ui/screens/player/PlayerCatchUpActionsTest.kt@@ -0,0 +1,44 @@+package com.streamvault.app.ui.screens.player++import com.google.common.truth.Truth.assertThat+import com.streamvault.domain.model.ContentType+import com.streamvault.domain.model.StreamInfo+import com.streamvault.domain.model.StreamType+import kotlinx.coroutines.test.runTest+import org.junit.Test++class PlayerCatchUpActionsTest {++ @Test+ fun `resolveCatchUpStreamInfo uses shared playback resolver metadata`() = runTest {+ var requestedUrl: String? = null+ var requestedContentType: ContentType? = null+ val resolved = StreamInfo(+ url = "https://provider.example/archive.ts",+ title = null,+ headers = mapOf("Authorization" to "Bearer token"),+ userAgent = "StreamVaultTest",+ streamType = StreamType.HLS,+ containerExtension = "m3u8",+ expirationTime = 123_456L+ )++ val result = resolveCatchUpStreamInfo(+ candidateUrl = "https://provider.example/archive.ts",+ title = "Replay title",+ currentContentId = 42L,+ currentProviderId = 7L+ ) { url, _, _, contentType ->+ requestedUrl = url+ requestedContentType = contentType+ resolved+ }++ assertThat(requestedUrl).isEqualTo("https://provider.example/archive.ts")+ assertThat(requestedContentType).isEqualTo(ContentType.LIVE)+ assertThat(result).isEqualTo(resolved.copy(title = "Replay title"))+ assertThat(result?.headers).containsEntry("Authorization", "Bearer token")+ assertThat(result?.userAgent).isEqualTo("StreamVaultTest")+ assertThat(result?.expirationTime).isEqualTo(123_456L)+ }+}\ No newline at end of filediff --git a/app/src/test/java/com/streamvault/app/ui/screens/player/PlayerPlaybackPreferenceActionsTest.kt b/app/src/test/java/com/streamvault/app/ui/screens/player/PlayerPlaybackPreferenceActionsTest.ktnew file mode 100644index 00000000..0fa75ab9--- /dev/null+++ b/app/src/test/java/com/streamvault/app/ui/screens/player/PlayerPlaybackPreferenceActionsTest.kt@@ -0,0 +1,58 @@+package com.streamvault.app.ui.screens.player++import com.google.common.truth.Truth.assertThat+import org.junit.Test++class PlayerPlaybackPreferenceActionsTest {++ @Test+ fun `buildThumbnailPreloadPositions bounds preload near current position`() {+ val positions = buildThumbnailPreloadPositions(+ durationMs = 7 * 60 * 1000L,+ currentPositionMs = 95_000L,+ bucketMs = 10_000L,+ frameBudget = 6+ )++ assertThat(positions).containsExactly(90_000L, 100_000L, 80_000L, 110_000L, 70_000L, 120_000L).inOrder()+ }++ @Test+ fun `buildThumbnailPreloadPositions caps at media bounds`() {+ val positions = buildThumbnailPreloadPositions(+ durationMs = 25_000L,+ currentPositionMs = 0L,+ bucketMs = 10_000L,+ frameBudget = 6+ )++ assertThat(positions).containsExactly(0L, 10_000L, 20_000L).inOrder()+ }++ @Test+ fun `shouldStartThumbnailPreload rejects completed and in flight keys`() {+ assertThat(+ shouldStartThumbnailPreload(+ preloadKey = "media-a",+ lastCompletedPreloadKey = "media-a",+ inFlightPreloadKey = null+ )+ ).isFalse()++ assertThat(+ shouldStartThumbnailPreload(+ preloadKey = "media-a",+ lastCompletedPreloadKey = null,+ inFlightPreloadKey = "media-a"+ )+ ).isFalse()++ assertThat(+ shouldStartThumbnailPreload(+ preloadKey = "media-b",+ lastCompletedPreloadKey = "media-a",+ inFlightPreloadKey = null+ )+ ).isTrue()+ }+}diff --git a/app/src/test/java/com/streamvault/app/ui/screens/player/PlayerPlaybackUrlSupportTest.kt b/app/src/test/java/com/streamvault/app/ui/screens/player/PlayerPlaybackUrlSupportTest.ktnew file mode 100644index 00000000..399909e0--- /dev/null+++ b/app/src/test/java/com/streamvault/app/ui/screens/player/PlayerPlaybackUrlSupportTest.kt@@ -0,0 +1,52 @@+package com.streamvault.app.ui.screens.player++import com.google.common.truth.Truth.assertThat+import com.streamvault.domain.model.StreamInfo+import org.junit.Test++class PlayerPlaybackUrlSupportTest {++ @Test+ fun `resolveTimeshiftStreamInfo prefers resolved metadata for restart`() {+ val resolved = StreamInfo(+ url = "https://resolved.example/live.m3u8",+ title = "Resolved title",+ headers = mapOf("Authorization" to "Bearer token"),+ userAgent = "StreamVaultTest",+ expirationTime = 123_456L+ )++ val result = resolveTimeshiftStreamInfo(+ streamInfoOverride = null,+ currentResolvedStreamInfo = resolved,+ currentResolvedPlaybackUrl = resolved.url,+ currentStreamUrl = "stalker://logical",+ playbackTitle = "Playback title",+ currentTitle = "Fallback title"+ )++ assertThat(result).isEqualTo(resolved)+ assertThat(result?.headers).containsEntry("Authorization", "Bearer token")+ assertThat(result?.userAgent).isEqualTo("StreamVaultTest")+ assertThat(result?.expirationTime).isEqualTo(123_456L)+ }++ @Test+ fun `resolveTimeshiftStreamInfo falls back to url when metadata is unavailable`() {+ val result = resolveTimeshiftStreamInfo(+ streamInfoOverride = null,+ currentResolvedStreamInfo = null,+ currentResolvedPlaybackUrl = " https://fallback.example/live.ts ",+ currentStreamUrl = "logical://stream",+ playbackTitle = "",+ currentTitle = "Fallback title"+ )++ assertThat(result).isEqualTo(+ StreamInfo(+ url = "https://fallback.example/live.ts",+ title = "Fallback title"+ )+ )+ }+}\ No newline at end of filediff --git a/app/src/test/java/com/streamvault/app/ui/screens/player/PlayerPreparationSetupActionsTest.kt b/app/src/test/java/com/streamvault/app/ui/screens/player/PlayerPreparationSetupActionsTest.ktnew file mode 100644index 00000000..728cae13--- /dev/null+++ b/app/src/test/java/com/streamvault/app/ui/screens/player/PlayerPreparationSetupActionsTest.kt@@ -0,0 +1,51 @@+package com.streamvault.app.ui.screens.player++import com.google.common.truth.Truth.assertThat+import com.streamvault.domain.model.Episode+import kotlinx.coroutines.test.runTest+import org.junit.Test++class PlayerPreparationSetupActionsTest {++ @Test+ fun `resolveSeriesEpisodeIdentity uses explicit series id when present`() = runTest {+ val identity = resolveSeriesEpisodeIdentity(+ providerId = 5L,+ internalChannelId = 11L,+ seriesId = 22L,+ seasonNumber = 3,+ episodeNumber = 4,+ lookupEpisode = { error("should not lookup persisted episode") }+ )++ assertThat(identity).isEqualTo(+ ResolvedSeriesEpisodeIdentity(seriesId = 22L, seasonNumber = 3, episodeNumber = 4)+ )+ }++ @Test+ fun `resolveSeriesEpisodeIdentity falls back to persisted episode metadata`() = runTest {+ val identity = resolveSeriesEpisodeIdentity(+ providerId = 5L,+ internalChannelId = 11L,+ seriesId = null,+ seasonNumber = null,+ episodeNumber = null,+ lookupEpisode = {+ Episode(+ id = 11L,+ title = "Episode",+ episodeNumber = 7,+ seasonNumber = 2,+ streamUrl = "https://example.com/episode.m3u8",+ seriesId = 22L,+ providerId = 5L+ )+ }+ )++ assertThat(identity).isEqualTo(+ ResolvedSeriesEpisodeIdentity(seriesId = 22L, seasonNumber = 2, episodeNumber = 7)+ )+ }+}\ No newline at end of filediff --git a/app/src/test/java/com/streamvault/app/ui/screens/player/PlayerPrepareIdentityTest.kt b/app/src/test/java/com/streamvault/app/ui/screens/player/PlayerPrepareIdentityTest.ktnew file mode 100644index 00000000..cbed8910--- /dev/null+++ b/app/src/test/java/com/streamvault/app/ui/screens/player/PlayerPrepareIdentityTest.kt@@ -0,0 +1,86 @@+package com.streamvault.app.ui.screens.player++import com.google.common.truth.Truth.assertThat+import org.junit.Test++class PlayerPrepareIdentityTest {++ @Test+ fun `buildPlayerPrepareIdentity ignores display metadata changes`() {+ val baseline = buildPlayerPrepareIdentity(+ streamUrl = "https://example.com/stream",+ epgChannelId = "epg-1",+ internalChannelId = 100L,+ categoryId = 10L,+ providerId = 20L,+ isVirtual = false,+ combinedProfileId = null,+ combinedSourceFilterProviderId = null,+ contentType = "SERIES_EPISODE",+ archiveStartMs = null,+ archiveEndMs = null+ )++ val sameIdentity = buildPlayerPrepareIdentity(+ streamUrl = "https://example.com/stream",+ epgChannelId = "epg-1",+ internalChannelId = 100L,+ categoryId = 10L,+ providerId = 20L,+ isVirtual = false,+ combinedProfileId = null,+ combinedSourceFilterProviderId = null,+ contentType = "SERIES_EPISODE",+ archiveStartMs = null,+ archiveEndMs = null+ )++ assertThat(sameIdentity).isEqualTo(baseline)+ }++ @Test+ fun `buildPlayerPrepareIdentity changes when archive window changes`() {+ val baseline = buildPlayerPrepareIdentity(+ streamUrl = "https://example.com/stream",+ epgChannelId = "epg-1",+ internalChannelId = 100L,+ categoryId = 10L,+ providerId = 20L,+ isVirtual = false,+ combinedProfileId = null,+ combinedSourceFilterProviderId = null,+ contentType = "LIVE",+ archiveStartMs = 1_000L,+ archiveEndMs = 2_000L+ )++ val changedWindow = buildPlayerPrepareIdentity(+ streamUrl = "https://example.com/stream",+ epgChannelId = "epg-1",+ internalChannelId = 100L,+ categoryId = 10L,+ providerId = 20L,+ isVirtual = false,+ combinedProfileId = null,+ combinedSourceFilterProviderId = null,+ contentType = "LIVE",+ archiveStartMs = 2_000L,+ archiveEndMs = 3_000L+ )++ assertThat(changedWindow).isNotEqualTo(baseline)+ }++ @Test+ fun `resolveRouteDisplayTitle prefers archive title for live archive playback`() {+ assertThat(+ resolveRouteDisplayTitle(+ title = "Channel",+ contentType = "LIVE",+ archiveStartMs = 1_000L,+ archiveEndMs = 2_000L,+ archiveTitle = "Morning News"+ )+ ).isEqualTo("Morning News")+ }+}diff --git a/app/src/test/java/com/streamvault/app/ui/screens/player/PlayerZapActionsLivePlaybackTest.kt b/app/src/test/java/com/streamvault/app/ui/screens/player/PlayerZapActionsLivePlaybackTest.ktnew file mode 100644index 00000000..64ae9a9d--- /dev/null+++ b/app/src/test/java/com/streamvault/app/ui/screens/player/PlayerZapActionsLivePlaybackTest.kt@@ -0,0 +1,69 @@+package com.streamvault.app.ui.screens.player++import com.google.common.truth.Truth.assertThat+import com.streamvault.domain.model.Channel+import com.streamvault.domain.model.ContentType+import org.junit.Test++class PlayerZapActionsLivePlaybackTest {++ @Test+ fun `buildLivePlaybackRecordCandidate uses channel metadata when available`() {+ val channel = Channel(+ id = 42L,+ name = "News HD",+ streamUrl = "https://example.com/live/news.m3u8",+ providerId = 9L+ )++ val candidate = buildLivePlaybackRecordCandidate(+ currentProviderId = 9L,+ currentContentType = ContentType.LIVE,+ currentContentId = 7L,+ currentTitle = "Fallback title",+ currentResolvedPlaybackUrl = "https://example.com/fallback",+ currentStreamUrl = "https://example.com/fallback-raw",+ channel = channel+ )++ assertThat(candidate).isNotNull()+ assertThat(candidate!!.playbackKey).isEqualTo(9L to 42L)+ assertThat(candidate.history.contentId).isEqualTo(42L)+ assertThat(candidate.history.title).isEqualTo("News HD")+ assertThat(candidate.history.streamUrl).isEqualTo("https://example.com/live/news.m3u8")+ }++ @Test+ fun `buildLivePlaybackRecordCandidate falls back to active playback session`() {+ val candidate = buildLivePlaybackRecordCandidate(+ currentProviderId = 11L,+ currentContentType = ContentType.LIVE,+ currentContentId = 77L,+ currentTitle = "Channel 77",+ currentResolvedPlaybackUrl = "https://example.com/resolved",+ currentStreamUrl = "https://example.com/raw",+ channel = null+ )++ assertThat(candidate).isNotNull()+ assertThat(candidate!!.playbackKey).isEqualTo(11L to 77L)+ assertThat(candidate.history.contentId).isEqualTo(77L)+ assertThat(candidate.history.title).isEqualTo("Channel 77")+ assertThat(candidate.history.streamUrl).isEqualTo("https://example.com/resolved")+ }++ @Test+ fun `buildLivePlaybackRecordCandidate rejects non live sessions`() {+ val candidate = buildLivePlaybackRecordCandidate(+ currentProviderId = 11L,+ currentContentType = ContentType.MOVIE,+ currentContentId = 77L,+ currentTitle = "Movie",+ currentResolvedPlaybackUrl = "https://example.com/resolved",+ currentStreamUrl = "https://example.com/raw",+ channel = null+ )++ assertThat(candidate).isNull()+ }+}\ No newline at end of filediff --git a/app/src/test/java/com/streamvault/app/ui/screens/player/PlayerZapActionsTest.kt b/app/src/test/java/com/streamvault/app/ui/screens/player/PlayerZapActionsTest.ktindex 81c981d9..640aceb0 100644--- a/app/src/test/java/com/streamvault/app/ui/screens/player/PlayerZapActionsTest.kt+++ b/app/src/test/java/com/streamvault/app/ui/screens/player/PlayerZapActionsTest.kt@@ -1,6 +1,7 @@package com.streamvault.app.ui.screens.playerimport com.google.common.truth.Truth.assertThat+import kotlinx.coroutines.test.runTestimport org.junit.Testclass PlayerZapActionsTest {@@ -27,4 +28,28 @@ class PlayerZapActionsTest {assertThat(buffer).isEqualTo("7")}++ @Test+ fun `withScopedScrubbingMode disables scrubbing after success`() = runTest {+ val states = mutableListOf<Boolean>()++ withScopedScrubbingMode(states::add) {+ "done"+ }++ assertThat(states).containsExactly(true, false).inOrder()+ }++ @Test+ fun `withScopedScrubbingMode disables scrubbing after failure`() = runTest {+ val states = mutableListOf<Boolean>()++ runCatching {+ withScopedScrubbingMode(states::add) {+ error("boom")+ }+ }++ assertThat(states).containsExactly(true, false).inOrder()+ }}\ No newline at end of filediff --git a/app/src/test/java/com/streamvault/app/ui/screens/provider/ProviderSetupViewModelTest.kt b/app/src/test/java/com/streamvault/app/ui/screens/provider/ProviderSetupViewModelTest.ktindex ef7da264..31ccde0b 100644--- a/app/src/test/java/com/streamvault/app/ui/screens/provider/ProviderSetupViewModelTest.kt+++ b/app/src/test/java/com/streamvault/app/ui/screens/provider/ProviderSetupViewModelTest.kt@@ -8,6 +8,10 @@ import com.streamvault.domain.model.ProviderEpgSyncModeimport com.streamvault.domain.model.ProviderTypeimport com.streamvault.domain.repository.CombinedM3uRepositoryimport com.streamvault.domain.repository.ProviderRepository+import com.streamvault.domain.manager.BackupImportPlan+import com.streamvault.domain.manager.BackupImportResult+import com.streamvault.domain.usecase.ImportBackup+import com.streamvault.domain.usecase.ImportBackupResultimport com.streamvault.domain.usecase.ValidateAndAddProviderimport com.streamvault.domain.usecase.ValidateAndAddProviderResultimport kotlinx.coroutines.Dispatchers@@ -33,6 +37,7 @@ class ProviderSetupViewModelTest {private val providerRepository: ProviderRepository = mock()private val combinedM3uRepository: CombinedM3uRepository = mock()private val validateAndAddProvider: ValidateAndAddProvider = mock()+ private val importBackup: ImportBackup = mock()private val testDispatcher = StandardTestDispatcher()@Before@@ -70,7 +75,8 @@ class ProviderSetupViewModelTest {val viewModel = ProviderSetupViewModel(providerRepository = providerRepository,combinedM3uRepository = combinedM3uRepository,- validateAndAddProvider = validateAndAddProvider+ validateAndAddProvider = validateAndAddProvider,+ importBackup = importBackup)viewModel.addM3u("https://example.com/list.m3u", "Playlist 7")@@ -82,12 +88,80 @@ class ProviderSetupViewModelTest {assertThat(viewModel.uiState.value.loginSuccess).isFalse()}+ @Test+ fun `login xtream saved with sync warning completes onboarding with warning state`() = runTest {+ val createdProvider = Provider(+ id = 8L,+ name = "Premium",+ type = ProviderType.XTREAM_CODES,+ serverUrl = "https://example.com"+ )+ whenever(validateAndAddProvider.loginXtream(any(), any())).thenReturn(+ ValidateAndAddProviderResult.SavedWithWarning(+ provider = createdProvider,+ warning = "Provider login succeeded, but initial sync failed. The provider was saved and can be retried from Settings: timeout"+ )+ )++ val viewModel = ProviderSetupViewModel(+ providerRepository = providerRepository,+ combinedM3uRepository = combinedM3uRepository,+ validateAndAddProvider = validateAndAddProvider,+ importBackup = importBackup+ )++ viewModel.loginXtream("https://example.com", "alice", "secret", "Premium")+ advanceUntilIdle()++ assertThat(viewModel.uiState.value.loginSuccess).isTrue()+ assertThat(viewModel.uiState.value.createdProviderId).isEqualTo(8L)+ assertThat(viewModel.uiState.value.completionWarning).contains("initial sync failed")+ assertThat(viewModel.uiState.value.error).isNull()+ }++ @Test+ fun `confirm backup import completes onboarding when providers are restored`() = runTest {+ val importedProvider = Provider(+ id = 9L,+ name = "Restored",+ type = ProviderType.XTREAM_CODES,+ serverUrl = "https://example.com"+ )+ whenever(providerRepository.getProviders()).thenReturn(flowOf(listOf(importedProvider)))+ whenever(importBackup.confirm(any())).thenReturn(+ ImportBackupResult.Success(BackupImportResult(importedSections = listOf("Providers")))+ )++ val viewModel = ProviderSetupViewModel(+ providerRepository = providerRepository,+ combinedM3uRepository = combinedM3uRepository,+ validateAndAddProvider = validateAndAddProvider,+ importBackup = importBackup+ )+ val field = ProviderSetupViewModel::class.java.getDeclaredField("_uiState").apply { isAccessible = true }+ @Suppress("UNCHECKED_CAST")+ val stateFlow = field.get(viewModel) as kotlinx.coroutines.flow.MutableStateFlow<ProviderSetupState>+ stateFlow.value = stateFlow.value.copy(+ pendingBackupUri = "content://backup.json",+ backupImportPlan = BackupImportPlan()+ )++ viewModel.confirmBackupImport()+ advanceUntilIdle()++ assertThat(viewModel.uiState.value.backupImportSuccess).isTrue()+ assertThat(viewModel.uiState.value.pendingBackupUri).isNull()+ assertThat(viewModel.uiState.value.isImportingBackup).isFalse()+ assertThat(viewModel.uiState.value.error).isNull()+ }+@Testfun `attach created provider to combined keeps combined source active`() = runTest {val viewModel = ProviderSetupViewModel(providerRepository = providerRepository,combinedM3uRepository = combinedM3uRepository,- validateAndAddProvider = validateAndAddProvider+ validateAndAddProvider = validateAndAddProvider,+ importBackup = importBackup)val seededState = viewModel.uiState.value.copy(@@ -113,7 +187,8 @@ class ProviderSetupViewModelTest {val viewModel = ProviderSetupViewModel(providerRepository = providerRepository,combinedM3uRepository = combinedM3uRepository,- validateAndAddProvider = validateAndAddProvider+ validateAndAddProvider = validateAndAddProvider,+ importBackup = importBackup)viewModel.applySourceDefaults(ProviderSetupViewModel.SetupSourceType.STALKER)@@ -128,7 +203,8 @@ class ProviderSetupViewModelTest {val viewModel = ProviderSetupViewModel(providerRepository = providerRepository,combinedM3uRepository = combinedM3uRepository,- validateAndAddProvider = validateAndAddProvider+ validateAndAddProvider = validateAndAddProvider,+ importBackup = importBackup)viewModel.applySourceDefaults(ProviderSetupViewModel.SetupSourceType.XTREAM)@@ -143,7 +219,8 @@ class ProviderSetupViewModelTest {val viewModel = ProviderSetupViewModel(providerRepository = providerRepository,combinedM3uRepository = combinedM3uRepository,- validateAndAddProvider = validateAndAddProvider+ validateAndAddProvider = validateAndAddProvider,+ importBackup = importBackup)viewModel.applySourceDefaults(ProviderSetupViewModel.SetupSourceType.M3U)@@ -158,7 +235,8 @@ class ProviderSetupViewModelTest {val viewModel = ProviderSetupViewModel(providerRepository = providerRepository,combinedM3uRepository = combinedM3uRepository,- validateAndAddProvider = validateAndAddProvider+ validateAndAddProvider = validateAndAddProvider,+ importBackup = importBackup)viewModel.updateEpgSyncMode(ProviderEpgSyncMode.SKIP)@@ -168,4 +246,94 @@ class ProviderSetupViewModelTest {assertThat(viewModel.uiState.value.epgSyncMode).isEqualTo(ProviderEpgSyncMode.SKIP)assertThat(viewModel.uiState.value.hasCustomizedEpgSyncMode).isTrue()}++ @Test+ fun `editing m3u provider while combined source is active does not re-prompt for combined attach`() = runTest {+ val editedProvider = Provider(+ id = 7L,+ name = "Playlist 7",+ type = ProviderType.M3U,+ serverUrl = "https://example.com",+ m3uUrl = "https://example.com/list.m3u"+ )+ whenever(combinedM3uRepository.getActiveLiveSource()).thenReturn(+ flowOf(ActiveLiveSource.CombinedM3uSource(44L))+ )+ whenever(validateAndAddProvider.addM3u(any(), any())).thenReturn(+ ValidateAndAddProviderResult.Success(editedProvider)+ )++ val viewModel = ProviderSetupViewModel(+ providerRepository = providerRepository,+ combinedM3uRepository = combinedM3uRepository,+ validateAndAddProvider = validateAndAddProvider,+ importBackup = importBackup+ )++ // Simulate being in edit mode for provider 7.+ val field = ProviderSetupViewModel::class.java.getDeclaredField("_uiState").apply { isAccessible = true }+ @Suppress("UNCHECKED_CAST")+ val stateFlow = field.get(viewModel) as kotlinx.coroutines.flow.MutableStateFlow<ProviderSetupState>+ stateFlow.value = stateFlow.value.copy(isEditing = true, existingProviderId = 7L)++ viewModel.addM3u("https://example.com/list.m3u", "Playlist 7")+ advanceUntilIdle()++ // Edit flows must complete directly without the combined-attach dialog.+ assertThat(viewModel.uiState.value.pendingCombinedAttachProfileId).isNull()+ assertThat(viewModel.uiState.value.loginSuccess).isTrue()+ }++ @Test+ fun `m3u sync failure error does not include could not validate playlist prefix`() = runTest {+ whenever(validateAndAddProvider.addM3u(any(), any())).thenReturn(+ ValidateAndAddProviderResult.Error(+ message = "Playlist saved, but initial sync failed. The provider was saved and can be retried from Settings: timeout"+ )+ )++ val viewModel = ProviderSetupViewModel(+ providerRepository = providerRepository,+ combinedM3uRepository = combinedM3uRepository,+ validateAndAddProvider = validateAndAddProvider,+ importBackup = importBackup+ )++ viewModel.addM3u("https://example.com/list.m3u", "Playlist")+ advanceUntilIdle()++ val error = viewModel.uiState.value.error+ assertThat(error).doesNotContain("Could not validate playlist")+ assertThat(error).contains("saved")+ }++ @Test+ fun `stalker error maps sync failure to user friendly message`() = runTest {+ whenever(validateAndAddProvider.loginStalker(any(), any())).thenReturn(+ ValidateAndAddProviderResult.Error(+ message = "Provider login succeeded, but initial sync failed. The provider was saved and can be retried from Settings: timeout"+ )+ )++ val viewModel = ProviderSetupViewModel(+ providerRepository = providerRepository,+ combinedM3uRepository = combinedM3uRepository,+ validateAndAddProvider = validateAndAddProvider,+ importBackup = importBackup+ )++ viewModel.loginStalker(+ portalUrl = "https://portal.example.com",+ macAddress = "00:1A:79:12:34:56",+ name = "MAG",+ deviceProfile = "MAG250",+ timezone = "UTC",+ locale = "en"+ )+ advanceUntilIdle()++ val error = viewModel.uiState.value.error+ assertThat(error).doesNotContain("initial sync failed. The provider was saved")+ assertThat(error).contains("sync failed")+ }}diff --git a/app/src/test/java/com/streamvault/app/ui/screens/settings/SettingsProviderActionsTest.kt b/app/src/test/java/com/streamvault/app/ui/screens/settings/SettingsProviderActionsTest.ktnew file mode 100644index 00000000..f4a4ffb3--- /dev/null+++ b/app/src/test/java/com/streamvault/app/ui/screens/settings/SettingsProviderActionsTest.kt@@ -0,0 +1,93 @@+package com.streamvault.app.ui.screens.settings++import com.google.common.truth.Truth.assertThat+import com.streamvault.app.tv.LauncherRecommendationsManager+import com.streamvault.app.tv.WatchNextManager+import com.streamvault.app.tvinput.TvInputChannelSyncManager+import com.streamvault.data.preferences.PreferencesRepository+import com.streamvault.data.sync.SyncManager+import com.streamvault.domain.model.ActiveLiveSource+import com.streamvault.domain.model.Provider+import com.streamvault.domain.model.ProviderType+import com.streamvault.domain.model.Result+import com.streamvault.domain.repository.CombinedM3uRepository+import com.streamvault.domain.repository.ProviderRepository+import com.streamvault.domain.repository.SyncMetadataRepository+import com.streamvault.domain.usecase.SyncProvider+import kotlinx.coroutines.ExperimentalCoroutinesApi+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.test.StandardTestDispatcher+import kotlinx.coroutines.test.advanceUntilIdle+import kotlinx.coroutines.test.runTest+import org.junit.Test+import org.mockito.kotlin.any+import org.mockito.kotlin.eq+import org.mockito.kotlin.mock+import org.mockito.kotlin.never+import org.mockito.kotlin.verify+import org.mockito.kotlin.whenever++@OptIn(ExperimentalCoroutinesApi::class)+class SettingsProviderActionsTest {++ private val providerRepository: ProviderRepository = mock()+ private val combinedM3uRepository: CombinedM3uRepository = mock()+ private val preferencesRepository: PreferencesRepository = mock()+ private val syncProvider: SyncProvider = mock()+ private val syncManager: SyncManager = mock()+ private val syncMetadataRepository: SyncMetadataRepository = mock()+ private val watchNextManager: WatchNextManager = mock()+ private val launcherRecommendationsManager: LauncherRecommendationsManager = mock()+ private val tvInputChannelSyncManager: TvInputChannelSyncManager = mock()+ private val uiState = MutableStateFlow(SettingsUiState())++ private val actions = SettingsProviderActions(+ providerRepository = providerRepository,+ combinedM3uRepository = combinedM3uRepository,+ preferencesRepository = preferencesRepository,+ syncProvider = syncProvider,+ syncManager = syncManager,+ syncMetadataRepository = syncMetadataRepository,+ watchNextManager = watchNextManager,+ launcherRecommendationsManager = launcherRecommendationsManager,+ tvInputChannelSyncManager = tvInputChannelSyncManager,+ uiState = uiState+ )++ @Test+ fun setActiveProvider_refreshesProviderScopedTvSurfaces() = runTest(StandardTestDispatcher()) {+ val provider = Provider(+ id = 7L,+ name = "Provider Seven",+ type = ProviderType.M3U,+ serverUrl = "https://example.com",+ lastSyncedAt = System.currentTimeMillis()+ )+ whenever(providerRepository.getProvider(7L)).thenReturn(provider)++ actions.setActiveProvider(this, 7L)+ advanceUntilIdle()++ verify(preferencesRepository).setLastActiveProviderId(7L)+ verify(combinedM3uRepository).setActiveLiveSource(ActiveLiveSource.ProviderSource(7L))+ verify(providerRepository).setActiveProvider(7L)+ verify(watchNextManager).refreshWatchNext()+ verify(launcherRecommendationsManager).refreshRecommendations(force = true)+ verify(tvInputChannelSyncManager).refreshTvInputCatalog()+ verify(syncProvider, never()).invoke(any(), any())+ }++ @Test+ fun deleteProvider_refreshesProviderScopedTvSurfaces() = runTest(StandardTestDispatcher()) {+ whenever(providerRepository.deleteProvider(7L)).thenReturn(Result.success(Unit))++ actions.deleteProvider(this, 7L)+ advanceUntilIdle()++ verify(providerRepository).deleteProvider(7L)+ verify(watchNextManager).refreshWatchNext()+ verify(launcherRecommendationsManager).refreshRecommendations(force = true)+ verify(tvInputChannelSyncManager).refreshTvInputCatalog()+ assertThat(uiState.value.userMessage).isNull()+ }+}\ No newline at end of filediff --git a/data/schemas/com.streamvault.data.local.StreamVaultDatabase/45.json b/data/schemas/com.streamvault.data.local.StreamVaultDatabase/45.jsonnew file mode 100644index 00000000..b62b756e--- /dev/null+++ b/data/schemas/com.streamvault.data.local.StreamVaultDatabase/45.json@@ -0,0 +1,4283 @@+{+ "formatVersion": 1,+ "database": {+ "version": 45,+ "identityHash": "814bf0f9472a0c1a7853429ad42d6a30",+ "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, `stalker_mac_address` TEXT NOT NULL, `stalker_device_profile` TEXT NOT NULL, `stalker_device_timezone` TEXT NOT NULL, `stalker_device_locale` TEXT NOT NULL, `is_active` INTEGER NOT NULL, `max_connections` INTEGER NOT NULL, `expiration_date` INTEGER, `api_version` TEXT, `allowed_output_formats_json` TEXT NOT NULL, `epg_sync_mode` TEXT NOT NULL, `xtream_fast_sync_enabled` INTEGER NOT NULL, `m3u_vod_classification_enabled` INTEGER NOT NULL, `status` TEXT NOT NULL, `last_synced_at` INTEGER NOT NULL, `created_at` INTEGER NOT NULL)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "type",+ "columnName": "type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "serverUrl",+ "columnName": "server_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "username",+ "columnName": "username",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "password",+ "columnName": "password",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "m3uUrl",+ "columnName": "m3u_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "epgUrl",+ "columnName": "epg_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerMacAddress",+ "columnName": "stalker_mac_address",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerDeviceProfile",+ "columnName": "stalker_device_profile",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerDeviceTimezone",+ "columnName": "stalker_device_timezone",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerDeviceLocale",+ "columnName": "stalker_device_locale",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "isActive",+ "columnName": "is_active",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "maxConnections",+ "columnName": "max_connections",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "expirationDate",+ "columnName": "expiration_date",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "apiVersion",+ "columnName": "api_version",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "allowedOutputFormatsJson",+ "columnName": "allowed_output_formats_json",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "epgSyncMode",+ "columnName": "epg_sync_mode",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "xtreamFastSyncEnabled",+ "columnName": "xtream_fast_sync_enabled",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "m3uVodClassificationEnabled",+ "columnName": "m3u_vod_classification_enabled",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "status",+ "columnName": "status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "lastSyncedAt",+ "columnName": "last_synced_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_providers_server_url_username_stalker_mac_address",+ "unique": true,+ "columnNames": [+ "server_url",+ "username",+ "stalker_mac_address"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_providers_server_url_username_stalker_mac_address` ON `${TABLE_NAME}` (`server_url`, `username`, `stalker_mac_address`)"+ }+ ]+ },+ {+ "tableName": "channels",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `stream_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `logo_url` TEXT, `group_title` TEXT, `category_id` INTEGER, `category_name` TEXT, `stream_url` TEXT NOT NULL, `epg_channel_id` TEXT, `number` INTEGER NOT NULL, `catch_up_supported` INTEGER NOT NULL, `catch_up_days` INTEGER NOT NULL, `catchUpSource` TEXT, `provider_id` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, `logical_group_id` TEXT NOT NULL, `error_count` INTEGER NOT NULL, `quality_options_json` TEXT, `sync_fingerprint` TEXT NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "streamId",+ "columnName": "stream_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "logoUrl",+ "columnName": "logo_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "groupTitle",+ "columnName": "group_title",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "categoryName",+ "columnName": "category_name",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "epgChannelId",+ "columnName": "epg_channel_id",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "number",+ "columnName": "number",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "catchUpSupported",+ "columnName": "catch_up_supported",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "catchUpDays",+ "columnName": "catch_up_days",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "catchUpSource",+ "columnName": "catchUpSource",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isUserProtected",+ "columnName": "is_user_protected",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "logicalGroupId",+ "columnName": "logical_group_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "errorCount",+ "columnName": "error_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "qualityOptionsJson",+ "columnName": "quality_options_json",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "syncFingerprint",+ "columnName": "sync_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_channels_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_channels_provider_id_category_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "category_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_provider_id_category_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`)"+ },+ {+ "name": "index_channels_provider_id_stream_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "stream_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_channels_provider_id_stream_id` ON `${TABLE_NAME}` (`provider_id`, `stream_id`)"+ },+ {+ "name": "index_channels_logical_group_id",+ "unique": false,+ "columnNames": [+ "logical_group_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_logical_group_id` ON `${TABLE_NAME}` (`logical_group_id`)"+ },+ {+ "name": "index_channels_provider_id_category_id_logical_group_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "category_id",+ "logical_group_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_provider_id_category_id_logical_group_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`, `logical_group_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "channel_preferences",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `channel_id` INTEGER NOT NULL, `aspect_ratio` TEXT, `audio_video_offset_ms` INTEGER, `updated_at` INTEGER NOT NULL, FOREIGN KEY(`channel_id`) REFERENCES `channels`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelId",+ "columnName": "channel_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "aspectRatio",+ "columnName": "aspect_ratio",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "audioVideoOffsetMs",+ "columnName": "audio_video_offset_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_channel_preferences_channel_id",+ "unique": true,+ "columnNames": [+ "channel_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_channel_preferences_channel_id` ON `${TABLE_NAME}` (`channel_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "channels",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "channel_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "channels_fts",+ "createSql": "CREATE VIRTUAL TABLE IF NOT EXISTS `${TABLE_NAME}` USING FTS4(`name` TEXT NOT NULL, content=`channels`)",+ "fields": [+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": []+ },+ "ftsVersion": "FTS4",+ "ftsOptions": {+ "tokenizer": "simple",+ "tokenizerArgs": [],+ "contentTable": "channels",+ "languageIdColumnName": "",+ "matchInfo": "FTS4",+ "notIndexedColumns": [],+ "prefixSizes": [],+ "preferredOrder": "ASC"+ },+ "contentSyncTriggers": [+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_BEFORE_UPDATE BEFORE UPDATE ON `channels` BEGIN DELETE FROM `channels_fts` WHERE `docid`=OLD.`rowid`; END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_BEFORE_DELETE BEFORE DELETE ON `channels` BEGIN DELETE FROM `channels_fts` WHERE `docid`=OLD.`rowid`; END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_AFTER_UPDATE AFTER UPDATE ON `channels` BEGIN INSERT INTO `channels_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_AFTER_INSERT AFTER INSERT ON `channels` BEGIN INSERT INTO `channels_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END"+ ]+ },+ {+ "tableName": "movies",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `stream_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `poster_url` TEXT, `backdrop_url` TEXT, `category_id` INTEGER, `category_name` TEXT, `stream_url` TEXT NOT NULL, `container_extension` TEXT, `plot` TEXT, `cast` TEXT, `director` TEXT, `genre` TEXT, `release_date` TEXT, `duration` TEXT, `duration_seconds` INTEGER NOT NULL, `rating` REAL NOT NULL, `year` TEXT, `tmdb_id` INTEGER, `youtube_trailer` TEXT, `provider_id` INTEGER NOT NULL, `watch_progress` INTEGER NOT NULL, `watch_count` INTEGER NOT NULL, `last_watched_at` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, `added_at` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "streamId",+ "columnName": "stream_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "posterUrl",+ "columnName": "poster_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "backdropUrl",+ "columnName": "backdrop_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "categoryName",+ "columnName": "category_name",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "containerExtension",+ "columnName": "container_extension",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "plot",+ "columnName": "plot",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "cast",+ "columnName": "cast",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "director",+ "columnName": "director",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "genre",+ "columnName": "genre",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "releaseDate",+ "columnName": "release_date",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "duration",+ "columnName": "duration",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "durationSeconds",+ "columnName": "duration_seconds",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "rating",+ "columnName": "rating",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "year",+ "columnName": "year",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "tmdbId",+ "columnName": "tmdb_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "youtubeTrailer",+ "columnName": "youtube_trailer",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "watchProgress",+ "columnName": "watch_progress",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "watchCount",+ "columnName": "watch_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastWatchedAt",+ "columnName": "last_watched_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isUserProtected",+ "columnName": "is_user_protected",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "syncFingerprint",+ "columnName": "sync_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "addedAt",+ "columnName": "added_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_movies_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_movies_provider_id_category_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "category_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id_category_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`)"+ },+ {+ "name": "index_movies_provider_id_stream_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "stream_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_movies_provider_id_stream_id` ON `${TABLE_NAME}` (`provider_id`, `stream_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "movies_fts",+ "createSql": "CREATE VIRTUAL TABLE IF NOT EXISTS `${TABLE_NAME}` USING FTS4(`name` TEXT NOT NULL, content=`movies`)",+ "fields": [+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": []+ },+ "ftsVersion": "FTS4",+ "ftsOptions": {+ "tokenizer": "simple",+ "tokenizerArgs": [],+ "contentTable": "movies",+ "languageIdColumnName": "",+ "matchInfo": "FTS4",+ "notIndexedColumns": [],+ "prefixSizes": [],+ "preferredOrder": "ASC"+ },+ "contentSyncTriggers": [+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_movies_fts_BEFORE_UPDATE BEFORE UPDATE ON `movies` BEGIN DELETE FROM `movies_fts` WHERE `docid`=OLD.`rowid`; END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_movies_fts_BEFORE_DELETE BEFORE DELETE ON `movies` BEGIN DELETE FROM `movies_fts` WHERE `docid`=OLD.`rowid`; END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_movies_fts_AFTER_UPDATE AFTER UPDATE ON `movies` BEGIN INSERT INTO `movies_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_movies_fts_AFTER_INSERT AFTER INSERT ON `movies` BEGIN INSERT INTO `movies_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END"+ ]+ },+ {+ "tableName": "series",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `series_id` INTEGER NOT NULL, `provider_series_id` TEXT, `name` TEXT NOT NULL, `poster_url` TEXT, `backdrop_url` TEXT, `category_id` INTEGER, `category_name` TEXT, `plot` TEXT, `cast` TEXT, `director` TEXT, `genre` TEXT, `release_date` TEXT, `rating` REAL NOT NULL, `tmdb_id` INTEGER, `youtube_trailer` TEXT, `episode_run_time` TEXT, `last_modified` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "seriesId",+ "columnName": "series_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerSeriesId",+ "columnName": "provider_series_id",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "posterUrl",+ "columnName": "poster_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "backdropUrl",+ "columnName": "backdrop_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "categoryName",+ "columnName": "category_name",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "plot",+ "columnName": "plot",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "cast",+ "columnName": "cast",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "director",+ "columnName": "director",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "genre",+ "columnName": "genre",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "releaseDate",+ "columnName": "release_date",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "rating",+ "columnName": "rating",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "tmdbId",+ "columnName": "tmdb_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "youtubeTrailer",+ "columnName": "youtube_trailer",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "episodeRunTime",+ "columnName": "episode_run_time",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lastModified",+ "columnName": "last_modified",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isUserProtected",+ "columnName": "is_user_protected",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "syncFingerprint",+ "columnName": "sync_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_series_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_series_provider_id_category_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "category_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_provider_id_category_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`)"+ },+ {+ "name": "index_series_provider_id_series_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "series_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_series_provider_id_series_id` ON `${TABLE_NAME}` (`provider_id`, `series_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "series_fts",+ "createSql": "CREATE VIRTUAL TABLE IF NOT EXISTS `${TABLE_NAME}` USING FTS4(`name` TEXT NOT NULL, content=`series`)",+ "fields": [+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": []+ },+ "ftsVersion": "FTS4",+ "ftsOptions": {+ "tokenizer": "simple",+ "tokenizerArgs": [],+ "contentTable": "series",+ "languageIdColumnName": "",+ "matchInfo": "FTS4",+ "notIndexedColumns": [],+ "prefixSizes": [],+ "preferredOrder": "ASC"+ },+ "contentSyncTriggers": [+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_series_fts_BEFORE_UPDATE BEFORE UPDATE ON `series` BEGIN DELETE FROM `series_fts` WHERE `docid`=OLD.`rowid`; END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_series_fts_BEFORE_DELETE BEFORE DELETE ON `series` BEGIN DELETE FROM `series_fts` WHERE `docid`=OLD.`rowid`; END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_series_fts_AFTER_UPDATE AFTER UPDATE ON `series` BEGIN INSERT INTO `series_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_series_fts_AFTER_INSERT AFTER INSERT ON `series` BEGIN INSERT INTO `series_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END"+ ]+ },+ {+ "tableName": "episodes",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `episode_id` INTEGER NOT NULL, `title` TEXT NOT NULL, `episode_number` INTEGER NOT NULL, `season_number` INTEGER NOT NULL, `stream_url` TEXT NOT NULL, `container_extension` TEXT, `cover_url` TEXT, `plot` TEXT, `duration` TEXT, `duration_seconds` INTEGER NOT NULL, `rating` REAL NOT NULL, `release_date` TEXT, `series_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `watch_progress` INTEGER NOT NULL, `last_watched_at` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`series_id`) REFERENCES `series`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "episodeId",+ "columnName": "episode_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "title",+ "columnName": "title",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "episodeNumber",+ "columnName": "episode_number",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "seasonNumber",+ "columnName": "season_number",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "containerExtension",+ "columnName": "container_extension",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "coverUrl",+ "columnName": "cover_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "plot",+ "columnName": "plot",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "duration",+ "columnName": "duration",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "durationSeconds",+ "columnName": "duration_seconds",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "rating",+ "columnName": "rating",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "releaseDate",+ "columnName": "release_date",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "seriesId",+ "columnName": "series_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "watchProgress",+ "columnName": "watch_progress",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastWatchedAt",+ "columnName": "last_watched_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isUserProtected",+ "columnName": "is_user_protected",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_episodes_series_id",+ "unique": false,+ "columnNames": [+ "series_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_episodes_series_id` ON `${TABLE_NAME}` (`series_id`)"+ },+ {+ "name": "index_episodes_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_episodes_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_episodes_provider_id_episode_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "episode_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_episodes_provider_id_episode_id` ON `${TABLE_NAME}` (`provider_id`, `episode_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ },+ {+ "table": "series",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "series_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "categories",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `category_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `parent_id` INTEGER, `type` TEXT NOT NULL, `provider_id` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "parentId",+ "columnName": "parent_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "type",+ "columnName": "type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isUserProtected",+ "columnName": "is_user_protected",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "syncFingerprint",+ "columnName": "sync_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_categories_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_categories_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_categories_provider_id_type",+ "unique": false,+ "columnNames": [+ "provider_id",+ "type"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_categories_provider_id_type` ON `${TABLE_NAME}` (`provider_id`, `type`)"+ },+ {+ "name": "index_categories_provider_id_category_id_type",+ "unique": true,+ "columnNames": [+ "provider_id",+ "category_id",+ "type"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_categories_provider_id_category_id_type` ON `${TABLE_NAME}` (`provider_id`, `category_id`, `type`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "channel_import_stage",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`session_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `stream_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `logo_url` TEXT, `group_title` TEXT, `category_id` INTEGER, `category_name` TEXT, `stream_url` TEXT NOT NULL, `epg_channel_id` TEXT, `number` INTEGER NOT NULL, `catch_up_supported` INTEGER NOT NULL, `catch_up_days` INTEGER NOT NULL, `catchUpSource` TEXT, `is_adult` INTEGER NOT NULL, `logical_group_id` TEXT NOT NULL, `error_count` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, PRIMARY KEY(`session_id`, `provider_id`, `stream_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "sessionId",+ "columnName": "session_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "streamId",+ "columnName": "stream_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "logoUrl",+ "columnName": "logo_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "groupTitle",+ "columnName": "group_title",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "categoryName",+ "columnName": "category_name",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "epgChannelId",+ "columnName": "epg_channel_id",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "number",+ "columnName": "number",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "catchUpSupported",+ "columnName": "catch_up_supported",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "catchUpDays",+ "columnName": "catch_up_days",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "catchUpSource",+ "columnName": "catchUpSource",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "logicalGroupId",+ "columnName": "logical_group_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "errorCount",+ "columnName": "error_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "syncFingerprint",+ "columnName": "sync_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "session_id",+ "provider_id",+ "stream_id"+ ]+ },+ "indices": [+ {+ "name": "index_channel_import_stage_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channel_import_stage_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_channel_import_stage_session_id_provider_id",+ "unique": false,+ "columnNames": [+ "session_id",+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channel_import_stage_session_id_provider_id` ON `${TABLE_NAME}` (`session_id`, `provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "movie_import_stage",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`session_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `stream_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `poster_url` TEXT, `backdrop_url` TEXT, `category_id` INTEGER, `category_name` TEXT, `stream_url` TEXT NOT NULL, `container_extension` TEXT, `plot` TEXT, `cast` TEXT, `director` TEXT, `genre` TEXT, `release_date` TEXT, `duration` TEXT, `duration_seconds` INTEGER NOT NULL, `rating` REAL NOT NULL, `year` TEXT, `tmdb_id` INTEGER, `youtube_trailer` TEXT, `is_adult` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, `added_at` INTEGER NOT NULL, PRIMARY KEY(`session_id`, `provider_id`, `stream_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "sessionId",+ "columnName": "session_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "streamId",+ "columnName": "stream_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "posterUrl",+ "columnName": "poster_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "backdropUrl",+ "columnName": "backdrop_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "categoryName",+ "columnName": "category_name",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "containerExtension",+ "columnName": "container_extension",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "plot",+ "columnName": "plot",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "cast",+ "columnName": "cast",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "director",+ "columnName": "director",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "genre",+ "columnName": "genre",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "releaseDate",+ "columnName": "release_date",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "duration",+ "columnName": "duration",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "durationSeconds",+ "columnName": "duration_seconds",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "rating",+ "columnName": "rating",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "year",+ "columnName": "year",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "tmdbId",+ "columnName": "tmdb_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "youtubeTrailer",+ "columnName": "youtube_trailer",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "syncFingerprint",+ "columnName": "sync_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "addedAt",+ "columnName": "added_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "session_id",+ "provider_id",+ "stream_id"+ ]+ },+ "indices": [+ {+ "name": "index_movie_import_stage_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movie_import_stage_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_movie_import_stage_session_id_provider_id",+ "unique": false,+ "columnNames": [+ "session_id",+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movie_import_stage_session_id_provider_id` ON `${TABLE_NAME}` (`session_id`, `provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "series_import_stage",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`session_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `series_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `poster_url` TEXT, `backdrop_url` TEXT, `category_id` INTEGER, `category_name` TEXT, `plot` TEXT, `cast` TEXT, `director` TEXT, `genre` TEXT, `release_date` TEXT, `rating` REAL NOT NULL, `tmdb_id` INTEGER, `youtube_trailer` TEXT, `episode_run_time` TEXT, `last_modified` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, PRIMARY KEY(`session_id`, `provider_id`, `series_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "sessionId",+ "columnName": "session_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "seriesId",+ "columnName": "series_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "posterUrl",+ "columnName": "poster_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "backdropUrl",+ "columnName": "backdrop_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "categoryName",+ "columnName": "category_name",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "plot",+ "columnName": "plot",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "cast",+ "columnName": "cast",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "director",+ "columnName": "director",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "genre",+ "columnName": "genre",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "releaseDate",+ "columnName": "release_date",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "rating",+ "columnName": "rating",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "tmdbId",+ "columnName": "tmdb_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "youtubeTrailer",+ "columnName": "youtube_trailer",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "episodeRunTime",+ "columnName": "episode_run_time",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lastModified",+ "columnName": "last_modified",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "syncFingerprint",+ "columnName": "sync_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "session_id",+ "provider_id",+ "series_id"+ ]+ },+ "indices": [+ {+ "name": "index_series_import_stage_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_import_stage_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_series_import_stage_session_id_provider_id",+ "unique": false,+ "columnNames": [+ "session_id",+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_import_stage_session_id_provider_id` ON `${TABLE_NAME}` (`session_id`, `provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "category_import_stage",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`session_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `category_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `parent_id` INTEGER, `type` TEXT NOT NULL, `is_adult` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, PRIMARY KEY(`session_id`, `provider_id`, `category_id`, `type`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "sessionId",+ "columnName": "session_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "parentId",+ "columnName": "parent_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "type",+ "columnName": "type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "syncFingerprint",+ "columnName": "sync_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "session_id",+ "provider_id",+ "category_id",+ "type"+ ]+ },+ "indices": [+ {+ "name": "index_category_import_stage_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_category_import_stage_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_category_import_stage_session_id_provider_id",+ "unique": false,+ "columnNames": [+ "session_id",+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_category_import_stage_session_id_provider_id` ON `${TABLE_NAME}` (`session_id`, `provider_id`)"+ },+ {+ "name": "index_category_import_stage_provider_id_type",+ "unique": false,+ "columnNames": [+ "provider_id",+ "type"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_category_import_stage_provider_id_type` ON `${TABLE_NAME}` (`provider_id`, `type`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "programs",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `channel_id` TEXT NOT NULL, `title` TEXT NOT NULL, `description` TEXT NOT NULL, `start_time` INTEGER NOT NULL, `end_time` INTEGER NOT NULL, `lang` TEXT NOT NULL, `rating` TEXT, `image_url` TEXT, `genre` TEXT, `category` TEXT, `has_archive` INTEGER NOT NULL)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelId",+ "columnName": "channel_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "title",+ "columnName": "title",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "description",+ "columnName": "description",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "startTime",+ "columnName": "start_time",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "endTime",+ "columnName": "end_time",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lang",+ "columnName": "lang",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "rating",+ "columnName": "rating",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "imageUrl",+ "columnName": "image_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "genre",+ "columnName": "genre",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "category",+ "columnName": "category",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "hasArchive",+ "columnName": "has_archive",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_programs_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_programs_provider_id_channel_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "channel_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_channel_id` ON `${TABLE_NAME}` (`provider_id`, `channel_id`)"+ },+ {+ "name": "index_programs_provider_id_end_time_channel_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "end_time",+ "channel_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_end_time_channel_id` ON `${TABLE_NAME}` (`provider_id`, `end_time`, `channel_id`)"+ },+ {+ "name": "index_programs_provider_id_start_time_end_time",+ "unique": false,+ "columnNames": [+ "provider_id",+ "start_time",+ "end_time"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_start_time_end_time` ON `${TABLE_NAME}` (`provider_id`, `start_time`, `end_time`)"+ },+ {+ "name": "index_programs_start_time",+ "unique": false,+ "columnNames": [+ "start_time"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_start_time` ON `${TABLE_NAME}` (`start_time`)"+ },+ {+ "name": "index_programs_provider_id_channel_id_start_time",+ "unique": false,+ "columnNames": [+ "provider_id",+ "channel_id",+ "start_time"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_channel_id_start_time` ON `${TABLE_NAME}` (`provider_id`, `channel_id`, `start_time`)"+ },+ {+ "name": "index_programs_provider_id_channel_id_start_time_end_time",+ "unique": true,+ "columnNames": [+ "provider_id",+ "channel_id",+ "start_time",+ "end_time"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_programs_provider_id_channel_id_start_time_end_time` ON `${TABLE_NAME}` (`provider_id`, `channel_id`, `start_time`, `end_time`)"+ }+ ]+ },+ {+ "tableName": "favorites",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `content_id` INTEGER NOT NULL, `content_type` TEXT NOT NULL, `position` INTEGER NOT NULL, `group_id` INTEGER, `group_key` INTEGER NOT NULL, `added_at` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`group_id`) REFERENCES `virtual_groups`(`id`) ON UPDATE NO ACTION ON DELETE SET NULL )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentId",+ "columnName": "content_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentType",+ "columnName": "content_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "position",+ "columnName": "position",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "groupId",+ "columnName": "group_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "groupKey",+ "columnName": "group_key",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "addedAt",+ "columnName": "added_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_favorites_provider_id_content_id_content_type_group_key",+ "unique": true,+ "columnNames": [+ "provider_id",+ "content_id",+ "content_type",+ "group_key"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_favorites_provider_id_content_id_content_type_group_key` ON `${TABLE_NAME}` (`provider_id`, `content_id`, `content_type`, `group_key`)"+ },+ {+ "name": "index_favorites_provider_id_content_type_group_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "content_type",+ "group_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_favorites_provider_id_content_type_group_id` ON `${TABLE_NAME}` (`provider_id`, `content_type`, `group_id`)"+ },+ {+ "name": "index_favorites_group_id_position",+ "unique": false,+ "columnNames": [+ "group_id",+ "position"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_favorites_group_id_position` ON `${TABLE_NAME}` (`group_id`, `position`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ },+ {+ "table": "virtual_groups",+ "onDelete": "SET NULL",+ "onUpdate": "NO ACTION",+ "columns": [+ "group_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "virtual_groups",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `icon_emoji` TEXT, `position` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `content_type` TEXT NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "iconEmoji",+ "columnName": "icon_emoji",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "position",+ "columnName": "position",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentType",+ "columnName": "content_type",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_virtual_groups_provider_id_content_type",+ "unique": false,+ "columnNames": [+ "provider_id",+ "content_type"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_virtual_groups_provider_id_content_type` ON `${TABLE_NAME}` (`provider_id`, `content_type`)"+ },+ {+ "name": "index_virtual_groups_position",+ "unique": false,+ "columnNames": [+ "position"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_virtual_groups_position` ON `${TABLE_NAME}` (`position`)"+ },+ {+ "name": "index_virtual_groups_content_type",+ "unique": false,+ "columnNames": [+ "content_type"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_virtual_groups_content_type` ON `${TABLE_NAME}` (`content_type`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "playback_history",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `content_id` INTEGER NOT NULL, `content_type` TEXT NOT NULL, `provider_id` INTEGER NOT NULL, `title` TEXT NOT NULL, `poster_url` TEXT, `stream_url` TEXT NOT NULL, `resume_position_ms` INTEGER NOT NULL, `total_duration_ms` INTEGER NOT NULL, `last_watched_at` INTEGER NOT NULL, `watch_count` INTEGER NOT NULL, `watched_status` TEXT NOT NULL, `series_id` INTEGER, `season_number` INTEGER, `episode_number` INTEGER, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentId",+ "columnName": "content_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentType",+ "columnName": "content_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "title",+ "columnName": "title",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "posterUrl",+ "columnName": "poster_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "resumePositionMs",+ "columnName": "resume_position_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "totalDurationMs",+ "columnName": "total_duration_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastWatchedAt",+ "columnName": "last_watched_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "watchCount",+ "columnName": "watch_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "watchedStatus",+ "columnName": "watched_status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "seriesId",+ "columnName": "series_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "seasonNumber",+ "columnName": "season_number",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "episodeNumber",+ "columnName": "episode_number",+ "affinity": "INTEGER"+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_playback_history_content_id_content_type_provider_id",+ "unique": true,+ "columnNames": [+ "content_id",+ "content_type",+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_playback_history_content_id_content_type_provider_id` ON `${TABLE_NAME}` (`content_id`, `content_type`, `provider_id`)"+ },+ {+ "name": "index_playback_history_last_watched_at",+ "unique": false,+ "columnNames": [+ "last_watched_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_history_last_watched_at` ON `${TABLE_NAME}` (`last_watched_at`)"+ },+ {+ "name": "index_playback_history_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_history_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "tmdb_identity",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`tmdb_id` INTEGER NOT NULL, `content_type` TEXT NOT NULL, `canonical_provider_id` INTEGER NOT NULL, `first_seen_at` INTEGER NOT NULL, PRIMARY KEY(`tmdb_id`, `content_type`), FOREIGN KEY(`canonical_provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "tmdbId",+ "columnName": "tmdb_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentType",+ "columnName": "content_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "canonicalProviderId",+ "columnName": "canonical_provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "firstSeenAt",+ "columnName": "first_seen_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "tmdb_id",+ "content_type"+ ]+ },+ "indices": [+ {+ "name": "index_tmdb_identity_content_type",+ "unique": false,+ "columnNames": [+ "content_type"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_tmdb_identity_content_type` ON `${TABLE_NAME}` (`content_type`)"+ },+ {+ "name": "index_tmdb_identity_canonical_provider_id",+ "unique": false,+ "columnNames": [+ "canonical_provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_tmdb_identity_canonical_provider_id` ON `${TABLE_NAME}` (`canonical_provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "canonical_provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "search_history",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `query` TEXT NOT NULL, `content_scope` TEXT NOT NULL, `provider_id` INTEGER NOT NULL, `used_at` INTEGER NOT NULL, `use_count` INTEGER NOT NULL)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "query",+ "columnName": "query",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "contentScope",+ "columnName": "content_scope",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "usedAt",+ "columnName": "used_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "useCount",+ "columnName": "use_count",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_search_history_content_scope_provider_id_used_at",+ "unique": false,+ "columnNames": [+ "content_scope",+ "provider_id",+ "used_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_search_history_content_scope_provider_id_used_at` ON `${TABLE_NAME}` (`content_scope`, `provider_id`, `used_at`)"+ },+ {+ "name": "index_search_history_used_at",+ "unique": false,+ "columnNames": [+ "used_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_search_history_used_at` ON `${TABLE_NAME}` (`used_at`)"+ },+ {+ "name": "index_search_history_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_search_history_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_search_history_query_content_scope_provider_id",+ "unique": true,+ "columnNames": [+ "query",+ "content_scope",+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_search_history_query_content_scope_provider_id` ON `${TABLE_NAME}` (`query`, `content_scope`, `provider_id`)"+ }+ ]+ },+ {+ "tableName": "sync_metadata",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `last_live_sync` INTEGER NOT NULL, `last_live_success` INTEGER NOT NULL, `last_movie_sync` INTEGER NOT NULL, `last_series_sync` INTEGER NOT NULL, `last_series_success` INTEGER NOT NULL, `last_epg_sync` INTEGER NOT NULL, `last_epg_success` INTEGER NOT NULL, `last_movie_attempt` INTEGER NOT NULL, `last_movie_success` INTEGER NOT NULL, `last_movie_partial` INTEGER NOT NULL, `live_count` INTEGER NOT NULL, `movie_count` INTEGER NOT NULL, `series_count` INTEGER NOT NULL, `epg_count` INTEGER NOT NULL, `last_sync_status` TEXT NOT NULL, `movie_sync_mode` TEXT NOT NULL, `movie_warnings_count` INTEGER NOT NULL, `movie_catalog_stale` INTEGER NOT NULL, `live_avoid_full_until` INTEGER NOT NULL, `movie_avoid_full_until` INTEGER NOT NULL, `series_avoid_full_until` INTEGER NOT NULL, `live_sequential_failures_remembered` INTEGER NOT NULL, `live_healthy_sync_streak` INTEGER NOT NULL, `movie_parallel_failures_remembered` INTEGER NOT NULL, `movie_healthy_sync_streak` INTEGER NOT NULL, `series_sequential_failures_remembered` INTEGER NOT NULL, `series_healthy_sync_streak` INTEGER NOT NULL, PRIMARY KEY(`provider_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastLiveSync",+ "columnName": "last_live_sync",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastLiveSuccess",+ "columnName": "last_live_success",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastMovieSync",+ "columnName": "last_movie_sync",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastSeriesSync",+ "columnName": "last_series_sync",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastSeriesSuccess",+ "columnName": "last_series_success",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastEpgSync",+ "columnName": "last_epg_sync",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastEpgSuccess",+ "columnName": "last_epg_success",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastMovieAttempt",+ "columnName": "last_movie_attempt",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastMovieSuccess",+ "columnName": "last_movie_success",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastMoviePartial",+ "columnName": "last_movie_partial",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "liveCount",+ "columnName": "live_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "movieCount",+ "columnName": "movie_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "seriesCount",+ "columnName": "series_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "epgCount",+ "columnName": "epg_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastSyncStatus",+ "columnName": "last_sync_status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "movieSyncMode",+ "columnName": "movie_sync_mode",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "movieWarningsCount",+ "columnName": "movie_warnings_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "movieCatalogStale",+ "columnName": "movie_catalog_stale",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "liveAvoidFullUntil",+ "columnName": "live_avoid_full_until",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "movieAvoidFullUntil",+ "columnName": "movie_avoid_full_until",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "seriesAvoidFullUntil",+ "columnName": "series_avoid_full_until",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "liveSequentialFailuresRemembered",+ "columnName": "live_sequential_failures_remembered",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "liveHealthySyncStreak",+ "columnName": "live_healthy_sync_streak",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "movieParallelFailuresRemembered",+ "columnName": "movie_parallel_failures_remembered",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "movieHealthySyncStreak",+ "columnName": "movie_healthy_sync_streak",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "seriesSequentialFailuresRemembered",+ "columnName": "series_sequential_failures_remembered",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "seriesHealthySyncStreak",+ "columnName": "series_healthy_sync_streak",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "provider_id"+ ]+ },+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "movie_category_hydration",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `category_id` INTEGER NOT NULL, `last_hydrated_at` INTEGER NOT NULL, `item_count` INTEGER NOT NULL, `last_status` TEXT NOT NULL, `last_error` TEXT, `last_loaded_page` INTEGER NOT NULL, `total_pages` INTEGER NOT NULL, `is_complete` INTEGER NOT NULL, `page_size` INTEGER NOT NULL, PRIMARY KEY(`provider_id`, `category_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastHydratedAt",+ "columnName": "last_hydrated_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "itemCount",+ "columnName": "item_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastStatus",+ "columnName": "last_status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "lastError",+ "columnName": "last_error",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lastLoadedPage",+ "columnName": "last_loaded_page",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "totalPages",+ "columnName": "total_pages",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isComplete",+ "columnName": "is_complete",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "pageSize",+ "columnName": "page_size",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "provider_id",+ "category_id"+ ]+ },+ "indices": [+ {+ "name": "index_movie_category_hydration_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movie_category_hydration_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "series_category_hydration",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `category_id` INTEGER NOT NULL, `last_hydrated_at` INTEGER NOT NULL, `item_count` INTEGER NOT NULL, `last_status` TEXT NOT NULL, `last_error` TEXT, `last_loaded_page` INTEGER NOT NULL, `total_pages` INTEGER NOT NULL, `is_complete` INTEGER NOT NULL, `page_size` INTEGER NOT NULL, PRIMARY KEY(`provider_id`, `category_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastHydratedAt",+ "columnName": "last_hydrated_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "itemCount",+ "columnName": "item_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastStatus",+ "columnName": "last_status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "lastError",+ "columnName": "last_error",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lastLoadedPage",+ "columnName": "last_loaded_page",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "totalPages",+ "columnName": "total_pages",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isComplete",+ "columnName": "is_complete",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "pageSize",+ "columnName": "page_size",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "provider_id",+ "category_id"+ ]+ },+ "indices": [+ {+ "name": "index_series_category_hydration_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_category_hydration_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "epg_sources",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `url` TEXT NOT NULL, `enabled` INTEGER NOT NULL, `last_refresh_at` INTEGER NOT NULL, `last_success_at` INTEGER NOT NULL, `last_error` TEXT, `priority` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, `etag` TEXT, `last_modified_header` TEXT)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "url",+ "columnName": "url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "enabled",+ "columnName": "enabled",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastRefreshAt",+ "columnName": "last_refresh_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastSuccessAt",+ "columnName": "last_success_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastError",+ "columnName": "last_error",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "priority",+ "columnName": "priority",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "etag",+ "columnName": "etag",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lastModifiedHeader",+ "columnName": "last_modified_header",+ "affinity": "TEXT"+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_epg_sources_url",+ "unique": true,+ "columnNames": [+ "url"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_epg_sources_url` ON `${TABLE_NAME}` (`url`)"+ }+ ]+ },+ {+ "tableName": "provider_epg_sources",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `epg_source_id` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `enabled` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`epg_source_id`) REFERENCES `epg_sources`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "epgSourceId",+ "columnName": "epg_source_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "priority",+ "columnName": "priority",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "enabled",+ "columnName": "enabled",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_provider_epg_sources_provider_id_epg_source_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "epg_source_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_provider_epg_sources_provider_id_epg_source_id` ON `${TABLE_NAME}` (`provider_id`, `epg_source_id`)"+ },+ {+ "name": "index_provider_epg_sources_epg_source_id",+ "unique": false,+ "columnNames": [+ "epg_source_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_provider_epg_sources_epg_source_id` ON `${TABLE_NAME}` (`epg_source_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ },+ {+ "table": "epg_sources",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "epg_source_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "epg_channels",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `epg_source_id` INTEGER NOT NULL, `xmltv_channel_id` TEXT NOT NULL, `display_name` TEXT NOT NULL, `normalized_name` TEXT NOT NULL, `icon_url` TEXT, FOREIGN KEY(`epg_source_id`) REFERENCES `epg_sources`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "epgSourceId",+ "columnName": "epg_source_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "xmltvChannelId",+ "columnName": "xmltv_channel_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "displayName",+ "columnName": "display_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "normalizedName",+ "columnName": "normalized_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "iconUrl",+ "columnName": "icon_url",+ "affinity": "TEXT"+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_epg_channels_epg_source_id_xmltv_channel_id",+ "unique": true,+ "columnNames": [+ "epg_source_id",+ "xmltv_channel_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_epg_channels_epg_source_id_xmltv_channel_id` ON `${TABLE_NAME}` (`epg_source_id`, `xmltv_channel_id`)"+ },+ {+ "name": "index_epg_channels_epg_source_id",+ "unique": false,+ "columnNames": [+ "epg_source_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_channels_epg_source_id` ON `${TABLE_NAME}` (`epg_source_id`)"+ },+ {+ "name": "index_epg_channels_normalized_name",+ "unique": false,+ "columnNames": [+ "normalized_name"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_channels_normalized_name` ON `${TABLE_NAME}` (`normalized_name`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "epg_sources",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "epg_source_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "epg_programmes",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `epg_source_id` INTEGER NOT NULL, `xmltv_channel_id` TEXT NOT NULL, `start_time` INTEGER NOT NULL, `end_time` INTEGER NOT NULL, `title` TEXT NOT NULL, `subtitle` TEXT, `description` TEXT NOT NULL, `category` TEXT, `lang` TEXT NOT NULL, `rating` TEXT, `image_url` TEXT, `episode_info` TEXT, FOREIGN KEY(`epg_source_id`) REFERENCES `epg_sources`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "epgSourceId",+ "columnName": "epg_source_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "xmltvChannelId",+ "columnName": "xmltv_channel_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "startTime",+ "columnName": "start_time",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "endTime",+ "columnName": "end_time",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "title",+ "columnName": "title",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "subtitle",+ "columnName": "subtitle",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "description",+ "columnName": "description",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "category",+ "columnName": "category",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lang",+ "columnName": "lang",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "rating",+ "columnName": "rating",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "imageUrl",+ "columnName": "image_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "episodeInfo",+ "columnName": "episode_info",+ "affinity": "TEXT"+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_epg_programmes_epg_source_id_xmltv_channel_id_start_time",+ "unique": false,+ "columnNames": [+ "epg_source_id",+ "xmltv_channel_id",+ "start_time"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_programmes_epg_source_id_xmltv_channel_id_start_time` ON `${TABLE_NAME}` (`epg_source_id`, `xmltv_channel_id`, `start_time`)"+ },+ {+ "name": "index_epg_programmes_epg_source_id_xmltv_channel_id_start_time_end_time",+ "unique": true,+ "columnNames": [+ "epg_source_id",+ "xmltv_channel_id",+ "start_time",+ "end_time"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_epg_programmes_epg_source_id_xmltv_channel_id_start_time_end_time` ON `${TABLE_NAME}` (`epg_source_id`, `xmltv_channel_id`, `start_time`, `end_time`)"+ },+ {+ "name": "index_epg_programmes_epg_source_id",+ "unique": false,+ "columnNames": [+ "epg_source_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_programmes_epg_source_id` ON `${TABLE_NAME}` (`epg_source_id`)"+ },+ {+ "name": "index_epg_programmes_start_time",+ "unique": false,+ "columnNames": [+ "start_time"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_programmes_start_time` ON `${TABLE_NAME}` (`start_time`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "epg_sources",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "epg_source_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "channel_epg_mappings",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_channel_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `source_type` TEXT NOT NULL, `epg_source_id` INTEGER, `xmltv_channel_id` TEXT, `match_type` TEXT, `confidence` REAL NOT NULL, `matched_at` INTEGER NOT NULL, `failed_attempts` INTEGER NOT NULL, `source` TEXT, `is_manual_override` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerChannelId",+ "columnName": "provider_channel_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "sourceType",+ "columnName": "source_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "epgSourceId",+ "columnName": "epg_source_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "xmltvChannelId",+ "columnName": "xmltv_channel_id",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "matchType",+ "columnName": "match_type",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "confidence",+ "columnName": "confidence",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "matchedAt",+ "columnName": "matched_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "failedAttempts",+ "columnName": "failed_attempts",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "source",+ "columnName": "source",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "isManualOverride",+ "columnName": "is_manual_override",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_channel_epg_mappings_provider_id_provider_channel_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "provider_channel_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_channel_epg_mappings_provider_id_provider_channel_id` ON `${TABLE_NAME}` (`provider_id`, `provider_channel_id`)"+ },+ {+ "name": "index_channel_epg_mappings_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channel_epg_mappings_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "combined_m3u_profiles",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `enabled` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "enabled",+ "columnName": "enabled",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ }+ },+ {+ "tableName": "combined_m3u_profile_members",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `profile_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `enabled` INTEGER NOT NULL, FOREIGN KEY(`profile_id`) REFERENCES `combined_m3u_profiles`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "profileId",+ "columnName": "profile_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "priority",+ "columnName": "priority",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "enabled",+ "columnName": "enabled",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_combined_m3u_profile_members_profile_id",+ "unique": false,+ "columnNames": [+ "profile_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_combined_m3u_profile_members_profile_id` ON `${TABLE_NAME}` (`profile_id`)"+ },+ {+ "name": "index_combined_m3u_profile_members_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_combined_m3u_profile_members_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_combined_m3u_profile_members_profile_id_provider_id",+ "unique": true,+ "columnNames": [+ "profile_id",+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_combined_m3u_profile_members_profile_id_provider_id` ON `${TABLE_NAME}` (`profile_id`, `provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "combined_m3u_profiles",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "profile_id"+ ],+ "referencedColumns": [+ "id"+ ]+ },+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "recording_schedules",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, `channel_name` TEXT NOT NULL, `stream_url` TEXT NOT NULL, `program_title` TEXT, `requested_start_ms` INTEGER NOT NULL, `requested_end_ms` INTEGER NOT NULL, `recurrence` TEXT NOT NULL, `recurring_rule_id` TEXT, `enabled` INTEGER NOT NULL, `is_manual` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelId",+ "columnName": "channel_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelName",+ "columnName": "channel_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "programTitle",+ "columnName": "program_title",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "requestedStartMs",+ "columnName": "requested_start_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "requestedEndMs",+ "columnName": "requested_end_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "recurrence",+ "columnName": "recurrence",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "recurringRuleId",+ "columnName": "recurring_rule_id",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "enabled",+ "columnName": "enabled",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isManual",+ "columnName": "is_manual",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "priority",+ "columnName": "priority",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_recording_schedules_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_schedules_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_recording_schedules_enabled_requested_start_ms",+ "unique": false,+ "columnNames": [+ "enabled",+ "requested_start_ms"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_schedules_enabled_requested_start_ms` ON `${TABLE_NAME}` (`enabled`, `requested_start_ms`)"+ },+ {+ "name": "index_recording_schedules_recurring_rule_id",+ "unique": false,+ "columnNames": [+ "recurring_rule_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_schedules_recurring_rule_id` ON `${TABLE_NAME}` (`recurring_rule_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "recording_runs",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `schedule_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, `channel_name` TEXT NOT NULL, `stream_url` TEXT NOT NULL, `program_title` TEXT, `scheduled_start_ms` INTEGER NOT NULL, `scheduled_end_ms` INTEGER NOT NULL, `recurrence` TEXT NOT NULL, `recurring_rule_id` TEXT, `status` TEXT NOT NULL, `source_type` TEXT NOT NULL, `resolved_url` TEXT, `headers_json` TEXT NOT NULL, `user_agent` TEXT, `expiration_time` INTEGER, `provider_label` TEXT, `output_uri` TEXT, `output_display_path` TEXT, `bytes_written` INTEGER NOT NULL, `average_throughput_bps` INTEGER NOT NULL, `retry_count` INTEGER NOT NULL, `last_progress_at_ms` INTEGER, `failure_category` TEXT NOT NULL, `failure_reason` TEXT, `terminal_at_ms` INTEGER, `started_at_ms` INTEGER, `ended_at_ms` INTEGER, `schedule_enabled` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `alarm_start_at_ms` INTEGER, `alarm_stop_at_ms` INTEGER, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`schedule_id`) REFERENCES `recording_schedules`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "scheduleId",+ "columnName": "schedule_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelId",+ "columnName": "channel_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelName",+ "columnName": "channel_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "programTitle",+ "columnName": "program_title",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "scheduledStartMs",+ "columnName": "scheduled_start_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "scheduledEndMs",+ "columnName": "scheduled_end_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "recurrence",+ "columnName": "recurrence",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "recurringRuleId",+ "columnName": "recurring_rule_id",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "status",+ "columnName": "status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "sourceType",+ "columnName": "source_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "resolvedUrl",+ "columnName": "resolved_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "headersJson",+ "columnName": "headers_json",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "userAgent",+ "columnName": "user_agent",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "expirationTime",+ "columnName": "expiration_time",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "providerLabel",+ "columnName": "provider_label",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "outputUri",+ "columnName": "output_uri",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "outputDisplayPath",+ "columnName": "output_display_path",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "bytesWritten",+ "columnName": "bytes_written",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "averageThroughputBytesPerSecond",+ "columnName": "average_throughput_bps",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "retryCount",+ "columnName": "retry_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastProgressAtMs",+ "columnName": "last_progress_at_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "failureCategory",+ "columnName": "failure_category",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "failureReason",+ "columnName": "failure_reason",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "terminalAtMs",+ "columnName": "terminal_at_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "startedAtMs",+ "columnName": "started_at_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "endedAtMs",+ "columnName": "ended_at_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "scheduleEnabled",+ "columnName": "schedule_enabled",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "priority",+ "columnName": "priority",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "alarmStartAtMs",+ "columnName": "alarm_start_at_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "alarmStopAtMs",+ "columnName": "alarm_stop_at_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_recording_runs_schedule_id",+ "unique": false,+ "columnNames": [+ "schedule_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_schedule_id` ON `${TABLE_NAME}` (`schedule_id`)"+ },+ {+ "name": "index_recording_runs_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_recording_runs_status_scheduled_start_ms",+ "unique": false,+ "columnNames": [+ "status",+ "scheduled_start_ms"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_status_scheduled_start_ms` ON `${TABLE_NAME}` (`status`, `scheduled_start_ms`)"+ },+ {+ "name": "index_recording_runs_alarm_start_at_ms",+ "unique": false,+ "columnNames": [+ "alarm_start_at_ms"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_alarm_start_at_ms` ON `${TABLE_NAME}` (`alarm_start_at_ms`)"+ },+ {+ "name": "index_recording_runs_alarm_stop_at_ms",+ "unique": false,+ "columnNames": [+ "alarm_stop_at_ms"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_alarm_stop_at_ms` ON `${TABLE_NAME}` (`alarm_stop_at_ms`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "recording_schedules",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "schedule_id"+ ],+ "referencedColumns": [+ "id"+ ]+ },+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "program_reminders",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `channel_id` TEXT NOT NULL, `channel_name` TEXT NOT NULL, `program_title` TEXT NOT NULL, `program_start_time` INTEGER NOT NULL, `remind_at` INTEGER NOT NULL, `lead_time_minutes` INTEGER NOT NULL, `is_dismissed` INTEGER NOT NULL, `notified_at` INTEGER, `created_at` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelId",+ "columnName": "channel_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "channelName",+ "columnName": "channel_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "programTitle",+ "columnName": "program_title",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "programStartTime",+ "columnName": "program_start_time",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "remindAt",+ "columnName": "remind_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "leadTimeMinutes",+ "columnName": "lead_time_minutes",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isDismissed",+ "columnName": "is_dismissed",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "notifiedAt",+ "columnName": "notified_at",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_program_reminders_provider_id_remind_at",+ "unique": false,+ "columnNames": [+ "provider_id",+ "remind_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_program_reminders_provider_id_remind_at` ON `${TABLE_NAME}` (`provider_id`, `remind_at`)"+ },+ {+ "name": "index_program_reminders_is_dismissed_notified_at_remind_at",+ "unique": false,+ "columnNames": [+ "is_dismissed",+ "notified_at",+ "remind_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_program_reminders_is_dismissed_notified_at_remind_at` ON `${TABLE_NAME}` (`is_dismissed`, `notified_at`, `remind_at`)"+ },+ {+ "name": "index_program_reminders_provider_id_channel_id_program_start_time",+ "unique": false,+ "columnNames": [+ "provider_id",+ "channel_id",+ "program_start_time"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_program_reminders_provider_id_channel_id_program_start_time` ON `${TABLE_NAME}` (`provider_id`, `channel_id`, `program_start_time`)"+ },+ {+ "name": "index_program_reminders_provider_id_channel_id_program_title_program_start_time",+ "unique": true,+ "columnNames": [+ "provider_id",+ "channel_id",+ "program_title",+ "program_start_time"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_program_reminders_provider_id_channel_id_program_title_program_start_time` ON `${TABLE_NAME}` (`provider_id`, `channel_id`, `program_title`, `program_start_time`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "recording_storage",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER NOT NULL, `tree_uri` TEXT, `display_name` TEXT, `output_directory` TEXT, `available_bytes` INTEGER, `is_writable` INTEGER NOT NULL, `file_name_pattern` TEXT NOT NULL, `retention_days` INTEGER, `max_simultaneous_recordings` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, PRIMARY KEY(`id`))",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "treeUri",+ "columnName": "tree_uri",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "displayName",+ "columnName": "display_name",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "outputDirectory",+ "columnName": "output_directory",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "availableBytes",+ "columnName": "available_bytes",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "isWritable",+ "columnName": "is_writable",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "fileNamePattern",+ "columnName": "file_name_pattern",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "retentionDays",+ "columnName": "retention_days",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "maxSimultaneousRecordings",+ "columnName": "max_simultaneous_recordings",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "id"+ ]+ }+ },+ {+ "tableName": "playback_compatibility_records",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `device_fingerprint` TEXT NOT NULL, `device_model` TEXT NOT NULL, `android_sdk` INTEGER NOT NULL, `stream_type` TEXT NOT NULL, `video_mime_type` TEXT NOT NULL, `resolution_bucket` TEXT NOT NULL, `decoder_name` TEXT NOT NULL, `surface_type` TEXT NOT NULL, `failure_type` TEXT NOT NULL, `last_failed_at` INTEGER NOT NULL, `last_succeeded_at` INTEGER NOT NULL, `failure_count` INTEGER NOT NULL, `success_count` INTEGER NOT NULL)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "deviceFingerprint",+ "columnName": "device_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "deviceModel",+ "columnName": "device_model",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "androidSdk",+ "columnName": "android_sdk",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "streamType",+ "columnName": "stream_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "videoMimeType",+ "columnName": "video_mime_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "resolutionBucket",+ "columnName": "resolution_bucket",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "decoderName",+ "columnName": "decoder_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "surfaceType",+ "columnName": "surface_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "failureType",+ "columnName": "failure_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "lastFailedAt",+ "columnName": "last_failed_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastSucceededAt",+ "columnName": "last_succeeded_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "failureCount",+ "columnName": "failure_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "successCount",+ "columnName": "success_count",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_playback_compatibility_records_device_fingerprint_stream_type_video_mime_type_resolution_bucket_decoder_name_surface_type",+ "unique": true,+ "columnNames": [+ "device_fingerprint",+ "stream_type",+ "video_mime_type",+ "resolution_bucket",+ "decoder_name",+ "surface_type"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_playback_compatibility_records_device_fingerprint_stream_type_video_mime_type_resolution_bucket_decoder_name_surface_type` ON `${TABLE_NAME}` (`device_fingerprint`, `stream_type`, `video_mime_type`, `resolution_bucket`, `decoder_name`, `surface_type`)"+ },+ {+ "name": "index_playback_compatibility_records_device_fingerprint_stream_type_video_mime_type_resolution_bucket",+ "unique": false,+ "columnNames": [+ "device_fingerprint",+ "stream_type",+ "video_mime_type",+ "resolution_bucket"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_compatibility_records_device_fingerprint_stream_type_video_mime_type_resolution_bucket` ON `${TABLE_NAME}` (`device_fingerprint`, `stream_type`, `video_mime_type`, `resolution_bucket`)"+ },+ {+ "name": "index_playback_compatibility_records_last_failed_at",+ "unique": false,+ "columnNames": [+ "last_failed_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_compatibility_records_last_failed_at` ON `${TABLE_NAME}` (`last_failed_at`)"+ },+ {+ "name": "index_playback_compatibility_records_last_succeeded_at",+ "unique": false,+ "columnNames": [+ "last_succeeded_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_compatibility_records_last_succeeded_at` ON `${TABLE_NAME}` (`last_succeeded_at`)"+ }+ ]+ }+ ],+ "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, '814bf0f9472a0c1a7853429ad42d6a30')"+ ]+ }+}\ No newline at end of filediff --git a/data/schemas/com.streamvault.data.local.StreamVaultDatabase/46.json b/data/schemas/com.streamvault.data.local.StreamVaultDatabase/46.jsonnew file mode 100644index 00000000..6e230dbb--- /dev/null+++ b/data/schemas/com.streamvault.data.local.StreamVaultDatabase/46.json@@ -0,0 +1,4294 @@+{+ "formatVersion": 1,+ "database": {+ "version": 46,+ "identityHash": "2f7a029188a49532c28f79b6815544d1",+ "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, `stalker_mac_address` TEXT NOT NULL, `stalker_device_profile` TEXT NOT NULL, `stalker_device_timezone` TEXT NOT NULL, `stalker_device_locale` TEXT NOT NULL, `is_active` INTEGER NOT NULL, `max_connections` INTEGER NOT NULL, `expiration_date` INTEGER, `api_version` TEXT, `allowed_output_formats_json` TEXT NOT NULL, `epg_sync_mode` TEXT NOT NULL, `xtream_fast_sync_enabled` INTEGER NOT NULL, `m3u_vod_classification_enabled` INTEGER NOT NULL, `status` TEXT NOT NULL, `last_synced_at` INTEGER NOT NULL, `created_at` INTEGER NOT NULL)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "type",+ "columnName": "type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "serverUrl",+ "columnName": "server_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "username",+ "columnName": "username",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "password",+ "columnName": "password",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "m3uUrl",+ "columnName": "m3u_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "epgUrl",+ "columnName": "epg_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerMacAddress",+ "columnName": "stalker_mac_address",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerDeviceProfile",+ "columnName": "stalker_device_profile",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerDeviceTimezone",+ "columnName": "stalker_device_timezone",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerDeviceLocale",+ "columnName": "stalker_device_locale",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "isActive",+ "columnName": "is_active",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "maxConnections",+ "columnName": "max_connections",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "expirationDate",+ "columnName": "expiration_date",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "apiVersion",+ "columnName": "api_version",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "allowedOutputFormatsJson",+ "columnName": "allowed_output_formats_json",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "epgSyncMode",+ "columnName": "epg_sync_mode",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "xtreamFastSyncEnabled",+ "columnName": "xtream_fast_sync_enabled",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "m3uVodClassificationEnabled",+ "columnName": "m3u_vod_classification_enabled",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "status",+ "columnName": "status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "lastSyncedAt",+ "columnName": "last_synced_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_providers_server_url_username_stalker_mac_address",+ "unique": true,+ "columnNames": [+ "server_url",+ "username",+ "stalker_mac_address"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_providers_server_url_username_stalker_mac_address` ON `${TABLE_NAME}` (`server_url`, `username`, `stalker_mac_address`)"+ }+ ]+ },+ {+ "tableName": "channels",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `stream_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `logo_url` TEXT, `group_title` TEXT, `category_id` INTEGER, `category_name` TEXT, `stream_url` TEXT NOT NULL, `epg_channel_id` TEXT, `number` INTEGER NOT NULL, `catch_up_supported` INTEGER NOT NULL, `catch_up_days` INTEGER NOT NULL, `catchUpSource` TEXT, `provider_id` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, `logical_group_id` TEXT NOT NULL, `error_count` INTEGER NOT NULL, `quality_options_json` TEXT, `sync_fingerprint` TEXT NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "streamId",+ "columnName": "stream_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "logoUrl",+ "columnName": "logo_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "groupTitle",+ "columnName": "group_title",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "categoryName",+ "columnName": "category_name",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "epgChannelId",+ "columnName": "epg_channel_id",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "number",+ "columnName": "number",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "catchUpSupported",+ "columnName": "catch_up_supported",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "catchUpDays",+ "columnName": "catch_up_days",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "catchUpSource",+ "columnName": "catchUpSource",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isUserProtected",+ "columnName": "is_user_protected",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "logicalGroupId",+ "columnName": "logical_group_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "errorCount",+ "columnName": "error_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "qualityOptionsJson",+ "columnName": "quality_options_json",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "syncFingerprint",+ "columnName": "sync_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_channels_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_channels_provider_id_category_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "category_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_provider_id_category_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`)"+ },+ {+ "name": "index_channels_provider_id_stream_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "stream_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_channels_provider_id_stream_id` ON `${TABLE_NAME}` (`provider_id`, `stream_id`)"+ },+ {+ "name": "index_channels_logical_group_id",+ "unique": false,+ "columnNames": [+ "logical_group_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_logical_group_id` ON `${TABLE_NAME}` (`logical_group_id`)"+ },+ {+ "name": "index_channels_provider_id_category_id_logical_group_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "category_id",+ "logical_group_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_provider_id_category_id_logical_group_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`, `logical_group_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "channel_preferences",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `channel_id` INTEGER NOT NULL, `aspect_ratio` TEXT, `audio_video_offset_ms` INTEGER, `updated_at` INTEGER NOT NULL, FOREIGN KEY(`channel_id`) REFERENCES `channels`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelId",+ "columnName": "channel_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "aspectRatio",+ "columnName": "aspect_ratio",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "audioVideoOffsetMs",+ "columnName": "audio_video_offset_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_channel_preferences_channel_id",+ "unique": true,+ "columnNames": [+ "channel_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_channel_preferences_channel_id` ON `${TABLE_NAME}` (`channel_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "channels",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "channel_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "channels_fts",+ "createSql": "CREATE VIRTUAL TABLE IF NOT EXISTS `${TABLE_NAME}` USING FTS4(`name` TEXT NOT NULL, content=`channels`)",+ "fields": [+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": []+ },+ "ftsVersion": "FTS4",+ "ftsOptions": {+ "tokenizer": "simple",+ "tokenizerArgs": [],+ "contentTable": "channels",+ "languageIdColumnName": "",+ "matchInfo": "FTS4",+ "notIndexedColumns": [],+ "prefixSizes": [],+ "preferredOrder": "ASC"+ },+ "contentSyncTriggers": [+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_BEFORE_UPDATE BEFORE UPDATE ON `channels` BEGIN DELETE FROM `channels_fts` WHERE `docid`=OLD.`rowid`; END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_BEFORE_DELETE BEFORE DELETE ON `channels` BEGIN DELETE FROM `channels_fts` WHERE `docid`=OLD.`rowid`; END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_AFTER_UPDATE AFTER UPDATE ON `channels` BEGIN INSERT INTO `channels_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_AFTER_INSERT AFTER INSERT ON `channels` BEGIN INSERT INTO `channels_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END"+ ]+ },+ {+ "tableName": "movies",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `stream_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `poster_url` TEXT, `backdrop_url` TEXT, `category_id` INTEGER, `category_name` TEXT, `stream_url` TEXT NOT NULL, `container_extension` TEXT, `plot` TEXT, `cast` TEXT, `director` TEXT, `genre` TEXT, `release_date` TEXT, `duration` TEXT, `duration_seconds` INTEGER NOT NULL, `rating` REAL NOT NULL, `year` TEXT, `tmdb_id` INTEGER, `youtube_trailer` TEXT, `provider_id` INTEGER NOT NULL, `watch_progress` INTEGER NOT NULL, `watch_count` INTEGER NOT NULL, `last_watched_at` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, `added_at` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "streamId",+ "columnName": "stream_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "posterUrl",+ "columnName": "poster_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "backdropUrl",+ "columnName": "backdrop_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "categoryName",+ "columnName": "category_name",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "containerExtension",+ "columnName": "container_extension",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "plot",+ "columnName": "plot",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "cast",+ "columnName": "cast",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "director",+ "columnName": "director",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "genre",+ "columnName": "genre",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "releaseDate",+ "columnName": "release_date",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "duration",+ "columnName": "duration",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "durationSeconds",+ "columnName": "duration_seconds",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "rating",+ "columnName": "rating",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "year",+ "columnName": "year",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "tmdbId",+ "columnName": "tmdb_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "youtubeTrailer",+ "columnName": "youtube_trailer",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "watchProgress",+ "columnName": "watch_progress",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "watchCount",+ "columnName": "watch_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastWatchedAt",+ "columnName": "last_watched_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isUserProtected",+ "columnName": "is_user_protected",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "syncFingerprint",+ "columnName": "sync_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "addedAt",+ "columnName": "added_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_movies_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_movies_provider_id_category_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "category_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id_category_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`)"+ },+ {+ "name": "index_movies_provider_id_stream_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "stream_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_movies_provider_id_stream_id` ON `${TABLE_NAME}` (`provider_id`, `stream_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "movies_fts",+ "createSql": "CREATE VIRTUAL TABLE IF NOT EXISTS `${TABLE_NAME}` USING FTS4(`name` TEXT NOT NULL, content=`movies`)",+ "fields": [+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": []+ },+ "ftsVersion": "FTS4",+ "ftsOptions": {+ "tokenizer": "simple",+ "tokenizerArgs": [],+ "contentTable": "movies",+ "languageIdColumnName": "",+ "matchInfo": "FTS4",+ "notIndexedColumns": [],+ "prefixSizes": [],+ "preferredOrder": "ASC"+ },+ "contentSyncTriggers": [+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_movies_fts_BEFORE_UPDATE BEFORE UPDATE ON `movies` BEGIN DELETE FROM `movies_fts` WHERE `docid`=OLD.`rowid`; END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_movies_fts_BEFORE_DELETE BEFORE DELETE ON `movies` BEGIN DELETE FROM `movies_fts` WHERE `docid`=OLD.`rowid`; END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_movies_fts_AFTER_UPDATE AFTER UPDATE ON `movies` BEGIN INSERT INTO `movies_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_movies_fts_AFTER_INSERT AFTER INSERT ON `movies` BEGIN INSERT INTO `movies_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END"+ ]+ },+ {+ "tableName": "series",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `series_id` INTEGER NOT NULL, `provider_series_id` TEXT, `name` TEXT NOT NULL, `poster_url` TEXT, `backdrop_url` TEXT, `category_id` INTEGER, `category_name` TEXT, `plot` TEXT, `cast` TEXT, `director` TEXT, `genre` TEXT, `release_date` TEXT, `rating` REAL NOT NULL, `tmdb_id` INTEGER, `youtube_trailer` TEXT, `episode_run_time` TEXT, `last_modified` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "seriesId",+ "columnName": "series_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerSeriesId",+ "columnName": "provider_series_id",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "posterUrl",+ "columnName": "poster_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "backdropUrl",+ "columnName": "backdrop_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "categoryName",+ "columnName": "category_name",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "plot",+ "columnName": "plot",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "cast",+ "columnName": "cast",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "director",+ "columnName": "director",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "genre",+ "columnName": "genre",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "releaseDate",+ "columnName": "release_date",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "rating",+ "columnName": "rating",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "tmdbId",+ "columnName": "tmdb_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "youtubeTrailer",+ "columnName": "youtube_trailer",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "episodeRunTime",+ "columnName": "episode_run_time",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lastModified",+ "columnName": "last_modified",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isUserProtected",+ "columnName": "is_user_protected",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "syncFingerprint",+ "columnName": "sync_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_series_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_series_provider_id_category_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "category_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_provider_id_category_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`)"+ },+ {+ "name": "index_series_provider_id_series_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "series_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_series_provider_id_series_id` ON `${TABLE_NAME}` (`provider_id`, `series_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "series_fts",+ "createSql": "CREATE VIRTUAL TABLE IF NOT EXISTS `${TABLE_NAME}` USING FTS4(`name` TEXT NOT NULL, content=`series`)",+ "fields": [+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": []+ },+ "ftsVersion": "FTS4",+ "ftsOptions": {+ "tokenizer": "simple",+ "tokenizerArgs": [],+ "contentTable": "series",+ "languageIdColumnName": "",+ "matchInfo": "FTS4",+ "notIndexedColumns": [],+ "prefixSizes": [],+ "preferredOrder": "ASC"+ },+ "contentSyncTriggers": [+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_series_fts_BEFORE_UPDATE BEFORE UPDATE ON `series` BEGIN DELETE FROM `series_fts` WHERE `docid`=OLD.`rowid`; END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_series_fts_BEFORE_DELETE BEFORE DELETE ON `series` BEGIN DELETE FROM `series_fts` WHERE `docid`=OLD.`rowid`; END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_series_fts_AFTER_UPDATE AFTER UPDATE ON `series` BEGIN INSERT INTO `series_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_series_fts_AFTER_INSERT AFTER INSERT ON `series` BEGIN INSERT INTO `series_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END"+ ]+ },+ {+ "tableName": "episodes",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `episode_id` INTEGER NOT NULL, `title` TEXT NOT NULL, `episode_number` INTEGER NOT NULL, `season_number` INTEGER NOT NULL, `stream_url` TEXT NOT NULL, `container_extension` TEXT, `cover_url` TEXT, `plot` TEXT, `duration` TEXT, `duration_seconds` INTEGER NOT NULL, `rating` REAL NOT NULL, `release_date` TEXT, `series_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `watch_progress` INTEGER NOT NULL, `last_watched_at` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`series_id`) REFERENCES `series`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "episodeId",+ "columnName": "episode_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "title",+ "columnName": "title",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "episodeNumber",+ "columnName": "episode_number",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "seasonNumber",+ "columnName": "season_number",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "containerExtension",+ "columnName": "container_extension",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "coverUrl",+ "columnName": "cover_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "plot",+ "columnName": "plot",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "duration",+ "columnName": "duration",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "durationSeconds",+ "columnName": "duration_seconds",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "rating",+ "columnName": "rating",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "releaseDate",+ "columnName": "release_date",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "seriesId",+ "columnName": "series_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "watchProgress",+ "columnName": "watch_progress",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastWatchedAt",+ "columnName": "last_watched_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isUserProtected",+ "columnName": "is_user_protected",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_episodes_series_id",+ "unique": false,+ "columnNames": [+ "series_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_episodes_series_id` ON `${TABLE_NAME}` (`series_id`)"+ },+ {+ "name": "index_episodes_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_episodes_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_episodes_provider_id_episode_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "episode_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_episodes_provider_id_episode_id` ON `${TABLE_NAME}` (`provider_id`, `episode_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ },+ {+ "table": "series",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "series_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "categories",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `category_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `parent_id` INTEGER, `type` TEXT NOT NULL, `provider_id` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "parentId",+ "columnName": "parent_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "type",+ "columnName": "type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isUserProtected",+ "columnName": "is_user_protected",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "syncFingerprint",+ "columnName": "sync_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_categories_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_categories_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_categories_provider_id_type",+ "unique": false,+ "columnNames": [+ "provider_id",+ "type"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_categories_provider_id_type` ON `${TABLE_NAME}` (`provider_id`, `type`)"+ },+ {+ "name": "index_categories_provider_id_category_id_type",+ "unique": true,+ "columnNames": [+ "provider_id",+ "category_id",+ "type"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_categories_provider_id_category_id_type` ON `${TABLE_NAME}` (`provider_id`, `category_id`, `type`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "channel_import_stage",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`session_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `stream_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `logo_url` TEXT, `group_title` TEXT, `category_id` INTEGER, `category_name` TEXT, `stream_url` TEXT NOT NULL, `epg_channel_id` TEXT, `number` INTEGER NOT NULL, `catch_up_supported` INTEGER NOT NULL, `catch_up_days` INTEGER NOT NULL, `catchUpSource` TEXT, `is_adult` INTEGER NOT NULL, `logical_group_id` TEXT NOT NULL, `error_count` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, PRIMARY KEY(`session_id`, `provider_id`, `stream_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "sessionId",+ "columnName": "session_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "streamId",+ "columnName": "stream_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "logoUrl",+ "columnName": "logo_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "groupTitle",+ "columnName": "group_title",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "categoryName",+ "columnName": "category_name",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "epgChannelId",+ "columnName": "epg_channel_id",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "number",+ "columnName": "number",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "catchUpSupported",+ "columnName": "catch_up_supported",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "catchUpDays",+ "columnName": "catch_up_days",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "catchUpSource",+ "columnName": "catchUpSource",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "logicalGroupId",+ "columnName": "logical_group_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "errorCount",+ "columnName": "error_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "syncFingerprint",+ "columnName": "sync_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "session_id",+ "provider_id",+ "stream_id"+ ]+ },+ "indices": [+ {+ "name": "index_channel_import_stage_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channel_import_stage_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_channel_import_stage_session_id_provider_id",+ "unique": false,+ "columnNames": [+ "session_id",+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channel_import_stage_session_id_provider_id` ON `${TABLE_NAME}` (`session_id`, `provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "movie_import_stage",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`session_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `stream_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `poster_url` TEXT, `backdrop_url` TEXT, `category_id` INTEGER, `category_name` TEXT, `stream_url` TEXT NOT NULL, `container_extension` TEXT, `plot` TEXT, `cast` TEXT, `director` TEXT, `genre` TEXT, `release_date` TEXT, `duration` TEXT, `duration_seconds` INTEGER NOT NULL, `rating` REAL NOT NULL, `year` TEXT, `tmdb_id` INTEGER, `youtube_trailer` TEXT, `is_adult` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, `added_at` INTEGER NOT NULL, PRIMARY KEY(`session_id`, `provider_id`, `stream_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "sessionId",+ "columnName": "session_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "streamId",+ "columnName": "stream_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "posterUrl",+ "columnName": "poster_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "backdropUrl",+ "columnName": "backdrop_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "categoryName",+ "columnName": "category_name",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "containerExtension",+ "columnName": "container_extension",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "plot",+ "columnName": "plot",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "cast",+ "columnName": "cast",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "director",+ "columnName": "director",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "genre",+ "columnName": "genre",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "releaseDate",+ "columnName": "release_date",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "duration",+ "columnName": "duration",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "durationSeconds",+ "columnName": "duration_seconds",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "rating",+ "columnName": "rating",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "year",+ "columnName": "year",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "tmdbId",+ "columnName": "tmdb_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "youtubeTrailer",+ "columnName": "youtube_trailer",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "syncFingerprint",+ "columnName": "sync_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "addedAt",+ "columnName": "added_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "session_id",+ "provider_id",+ "stream_id"+ ]+ },+ "indices": [+ {+ "name": "index_movie_import_stage_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movie_import_stage_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_movie_import_stage_session_id_provider_id",+ "unique": false,+ "columnNames": [+ "session_id",+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movie_import_stage_session_id_provider_id` ON `${TABLE_NAME}` (`session_id`, `provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "series_import_stage",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`session_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `series_id` INTEGER NOT NULL, `provider_series_id` TEXT, `provider_series_key` TEXT NOT NULL, `name` TEXT NOT NULL, `poster_url` TEXT, `backdrop_url` TEXT, `category_id` INTEGER, `category_name` TEXT, `plot` TEXT, `cast` TEXT, `director` TEXT, `genre` TEXT, `release_date` TEXT, `rating` REAL NOT NULL, `tmdb_id` INTEGER, `youtube_trailer` TEXT, `episode_run_time` TEXT, `last_modified` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, PRIMARY KEY(`session_id`, `provider_id`, `provider_series_key`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "sessionId",+ "columnName": "session_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "seriesId",+ "columnName": "series_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerSeriesId",+ "columnName": "provider_series_id",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "providerSeriesKey",+ "columnName": "provider_series_key",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "posterUrl",+ "columnName": "poster_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "backdropUrl",+ "columnName": "backdrop_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "categoryName",+ "columnName": "category_name",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "plot",+ "columnName": "plot",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "cast",+ "columnName": "cast",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "director",+ "columnName": "director",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "genre",+ "columnName": "genre",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "releaseDate",+ "columnName": "release_date",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "rating",+ "columnName": "rating",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "tmdbId",+ "columnName": "tmdb_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "youtubeTrailer",+ "columnName": "youtube_trailer",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "episodeRunTime",+ "columnName": "episode_run_time",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lastModified",+ "columnName": "last_modified",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "syncFingerprint",+ "columnName": "sync_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "session_id",+ "provider_id",+ "provider_series_key"+ ]+ },+ "indices": [+ {+ "name": "index_series_import_stage_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_import_stage_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_series_import_stage_session_id_provider_id",+ "unique": false,+ "columnNames": [+ "session_id",+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_import_stage_session_id_provider_id` ON `${TABLE_NAME}` (`session_id`, `provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "category_import_stage",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`session_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `category_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `parent_id` INTEGER, `type` TEXT NOT NULL, `is_adult` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, PRIMARY KEY(`session_id`, `provider_id`, `category_id`, `type`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "sessionId",+ "columnName": "session_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "parentId",+ "columnName": "parent_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "type",+ "columnName": "type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "syncFingerprint",+ "columnName": "sync_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "session_id",+ "provider_id",+ "category_id",+ "type"+ ]+ },+ "indices": [+ {+ "name": "index_category_import_stage_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_category_import_stage_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_category_import_stage_session_id_provider_id",+ "unique": false,+ "columnNames": [+ "session_id",+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_category_import_stage_session_id_provider_id` ON `${TABLE_NAME}` (`session_id`, `provider_id`)"+ },+ {+ "name": "index_category_import_stage_provider_id_type",+ "unique": false,+ "columnNames": [+ "provider_id",+ "type"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_category_import_stage_provider_id_type` ON `${TABLE_NAME}` (`provider_id`, `type`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "programs",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `channel_id` TEXT NOT NULL, `title` TEXT NOT NULL, `description` TEXT NOT NULL, `start_time` INTEGER NOT NULL, `end_time` INTEGER NOT NULL, `lang` TEXT NOT NULL, `rating` TEXT, `image_url` TEXT, `genre` TEXT, `category` TEXT, `has_archive` INTEGER NOT NULL)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelId",+ "columnName": "channel_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "title",+ "columnName": "title",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "description",+ "columnName": "description",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "startTime",+ "columnName": "start_time",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "endTime",+ "columnName": "end_time",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lang",+ "columnName": "lang",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "rating",+ "columnName": "rating",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "imageUrl",+ "columnName": "image_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "genre",+ "columnName": "genre",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "category",+ "columnName": "category",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "hasArchive",+ "columnName": "has_archive",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_programs_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_programs_provider_id_channel_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "channel_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_channel_id` ON `${TABLE_NAME}` (`provider_id`, `channel_id`)"+ },+ {+ "name": "index_programs_provider_id_end_time_channel_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "end_time",+ "channel_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_end_time_channel_id` ON `${TABLE_NAME}` (`provider_id`, `end_time`, `channel_id`)"+ },+ {+ "name": "index_programs_provider_id_start_time_end_time",+ "unique": false,+ "columnNames": [+ "provider_id",+ "start_time",+ "end_time"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_start_time_end_time` ON `${TABLE_NAME}` (`provider_id`, `start_time`, `end_time`)"+ },+ {+ "name": "index_programs_start_time",+ "unique": false,+ "columnNames": [+ "start_time"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_start_time` ON `${TABLE_NAME}` (`start_time`)"+ },+ {+ "name": "index_programs_provider_id_channel_id_start_time",+ "unique": false,+ "columnNames": [+ "provider_id",+ "channel_id",+ "start_time"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_channel_id_start_time` ON `${TABLE_NAME}` (`provider_id`, `channel_id`, `start_time`)"+ },+ {+ "name": "index_programs_provider_id_channel_id_start_time_end_time",+ "unique": true,+ "columnNames": [+ "provider_id",+ "channel_id",+ "start_time",+ "end_time"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_programs_provider_id_channel_id_start_time_end_time` ON `${TABLE_NAME}` (`provider_id`, `channel_id`, `start_time`, `end_time`)"+ }+ ]+ },+ {+ "tableName": "favorites",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `content_id` INTEGER NOT NULL, `content_type` TEXT NOT NULL, `position` INTEGER NOT NULL, `group_id` INTEGER, `group_key` INTEGER NOT NULL, `added_at` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`group_id`) REFERENCES `virtual_groups`(`id`) ON UPDATE NO ACTION ON DELETE SET NULL )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentId",+ "columnName": "content_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentType",+ "columnName": "content_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "position",+ "columnName": "position",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "groupId",+ "columnName": "group_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "groupKey",+ "columnName": "group_key",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "addedAt",+ "columnName": "added_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_favorites_provider_id_content_id_content_type_group_key",+ "unique": true,+ "columnNames": [+ "provider_id",+ "content_id",+ "content_type",+ "group_key"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_favorites_provider_id_content_id_content_type_group_key` ON `${TABLE_NAME}` (`provider_id`, `content_id`, `content_type`, `group_key`)"+ },+ {+ "name": "index_favorites_provider_id_content_type_group_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "content_type",+ "group_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_favorites_provider_id_content_type_group_id` ON `${TABLE_NAME}` (`provider_id`, `content_type`, `group_id`)"+ },+ {+ "name": "index_favorites_group_id_position",+ "unique": false,+ "columnNames": [+ "group_id",+ "position"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_favorites_group_id_position` ON `${TABLE_NAME}` (`group_id`, `position`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ },+ {+ "table": "virtual_groups",+ "onDelete": "SET NULL",+ "onUpdate": "NO ACTION",+ "columns": [+ "group_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "virtual_groups",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `icon_emoji` TEXT, `position` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `content_type` TEXT NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "iconEmoji",+ "columnName": "icon_emoji",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "position",+ "columnName": "position",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentType",+ "columnName": "content_type",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_virtual_groups_provider_id_content_type",+ "unique": false,+ "columnNames": [+ "provider_id",+ "content_type"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_virtual_groups_provider_id_content_type` ON `${TABLE_NAME}` (`provider_id`, `content_type`)"+ },+ {+ "name": "index_virtual_groups_position",+ "unique": false,+ "columnNames": [+ "position"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_virtual_groups_position` ON `${TABLE_NAME}` (`position`)"+ },+ {+ "name": "index_virtual_groups_content_type",+ "unique": false,+ "columnNames": [+ "content_type"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_virtual_groups_content_type` ON `${TABLE_NAME}` (`content_type`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "playback_history",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `content_id` INTEGER NOT NULL, `content_type` TEXT NOT NULL, `provider_id` INTEGER NOT NULL, `title` TEXT NOT NULL, `poster_url` TEXT, `stream_url` TEXT NOT NULL, `resume_position_ms` INTEGER NOT NULL, `total_duration_ms` INTEGER NOT NULL, `last_watched_at` INTEGER NOT NULL, `watch_count` INTEGER NOT NULL, `watched_status` TEXT NOT NULL, `series_id` INTEGER, `season_number` INTEGER, `episode_number` INTEGER, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentId",+ "columnName": "content_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentType",+ "columnName": "content_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "title",+ "columnName": "title",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "posterUrl",+ "columnName": "poster_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "resumePositionMs",+ "columnName": "resume_position_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "totalDurationMs",+ "columnName": "total_duration_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastWatchedAt",+ "columnName": "last_watched_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "watchCount",+ "columnName": "watch_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "watchedStatus",+ "columnName": "watched_status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "seriesId",+ "columnName": "series_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "seasonNumber",+ "columnName": "season_number",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "episodeNumber",+ "columnName": "episode_number",+ "affinity": "INTEGER"+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_playback_history_content_id_content_type_provider_id",+ "unique": true,+ "columnNames": [+ "content_id",+ "content_type",+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_playback_history_content_id_content_type_provider_id` ON `${TABLE_NAME}` (`content_id`, `content_type`, `provider_id`)"+ },+ {+ "name": "index_playback_history_last_watched_at",+ "unique": false,+ "columnNames": [+ "last_watched_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_history_last_watched_at` ON `${TABLE_NAME}` (`last_watched_at`)"+ },+ {+ "name": "index_playback_history_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_history_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "tmdb_identity",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`tmdb_id` INTEGER NOT NULL, `content_type` TEXT NOT NULL, `canonical_provider_id` INTEGER NOT NULL, `first_seen_at` INTEGER NOT NULL, PRIMARY KEY(`tmdb_id`, `content_type`), FOREIGN KEY(`canonical_provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "tmdbId",+ "columnName": "tmdb_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentType",+ "columnName": "content_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "canonicalProviderId",+ "columnName": "canonical_provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "firstSeenAt",+ "columnName": "first_seen_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "tmdb_id",+ "content_type"+ ]+ },+ "indices": [+ {+ "name": "index_tmdb_identity_content_type",+ "unique": false,+ "columnNames": [+ "content_type"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_tmdb_identity_content_type` ON `${TABLE_NAME}` (`content_type`)"+ },+ {+ "name": "index_tmdb_identity_canonical_provider_id",+ "unique": false,+ "columnNames": [+ "canonical_provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_tmdb_identity_canonical_provider_id` ON `${TABLE_NAME}` (`canonical_provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "canonical_provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "search_history",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `query` TEXT NOT NULL, `content_scope` TEXT NOT NULL, `provider_id` INTEGER NOT NULL, `used_at` INTEGER NOT NULL, `use_count` INTEGER NOT NULL)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "query",+ "columnName": "query",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "contentScope",+ "columnName": "content_scope",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "usedAt",+ "columnName": "used_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "useCount",+ "columnName": "use_count",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_search_history_content_scope_provider_id_used_at",+ "unique": false,+ "columnNames": [+ "content_scope",+ "provider_id",+ "used_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_search_history_content_scope_provider_id_used_at` ON `${TABLE_NAME}` (`content_scope`, `provider_id`, `used_at`)"+ },+ {+ "name": "index_search_history_used_at",+ "unique": false,+ "columnNames": [+ "used_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_search_history_used_at` ON `${TABLE_NAME}` (`used_at`)"+ },+ {+ "name": "index_search_history_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_search_history_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_search_history_query_content_scope_provider_id",+ "unique": true,+ "columnNames": [+ "query",+ "content_scope",+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_search_history_query_content_scope_provider_id` ON `${TABLE_NAME}` (`query`, `content_scope`, `provider_id`)"+ }+ ]+ },+ {+ "tableName": "sync_metadata",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `last_live_sync` INTEGER NOT NULL, `last_live_success` INTEGER NOT NULL, `last_movie_sync` INTEGER NOT NULL, `last_series_sync` INTEGER NOT NULL, `last_series_success` INTEGER NOT NULL, `last_epg_sync` INTEGER NOT NULL, `last_epg_success` INTEGER NOT NULL, `last_movie_attempt` INTEGER NOT NULL, `last_movie_success` INTEGER NOT NULL, `last_movie_partial` INTEGER NOT NULL, `live_count` INTEGER NOT NULL, `movie_count` INTEGER NOT NULL, `series_count` INTEGER NOT NULL, `epg_count` INTEGER NOT NULL, `last_sync_status` TEXT NOT NULL, `movie_sync_mode` TEXT NOT NULL, `movie_warnings_count` INTEGER NOT NULL, `movie_catalog_stale` INTEGER NOT NULL, `live_avoid_full_until` INTEGER NOT NULL, `movie_avoid_full_until` INTEGER NOT NULL, `series_avoid_full_until` INTEGER NOT NULL, `live_sequential_failures_remembered` INTEGER NOT NULL, `live_healthy_sync_streak` INTEGER NOT NULL, `movie_parallel_failures_remembered` INTEGER NOT NULL, `movie_healthy_sync_streak` INTEGER NOT NULL, `series_sequential_failures_remembered` INTEGER NOT NULL, `series_healthy_sync_streak` INTEGER NOT NULL, PRIMARY KEY(`provider_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastLiveSync",+ "columnName": "last_live_sync",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastLiveSuccess",+ "columnName": "last_live_success",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastMovieSync",+ "columnName": "last_movie_sync",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastSeriesSync",+ "columnName": "last_series_sync",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastSeriesSuccess",+ "columnName": "last_series_success",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastEpgSync",+ "columnName": "last_epg_sync",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastEpgSuccess",+ "columnName": "last_epg_success",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastMovieAttempt",+ "columnName": "last_movie_attempt",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastMovieSuccess",+ "columnName": "last_movie_success",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastMoviePartial",+ "columnName": "last_movie_partial",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "liveCount",+ "columnName": "live_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "movieCount",+ "columnName": "movie_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "seriesCount",+ "columnName": "series_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "epgCount",+ "columnName": "epg_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastSyncStatus",+ "columnName": "last_sync_status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "movieSyncMode",+ "columnName": "movie_sync_mode",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "movieWarningsCount",+ "columnName": "movie_warnings_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "movieCatalogStale",+ "columnName": "movie_catalog_stale",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "liveAvoidFullUntil",+ "columnName": "live_avoid_full_until",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "movieAvoidFullUntil",+ "columnName": "movie_avoid_full_until",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "seriesAvoidFullUntil",+ "columnName": "series_avoid_full_until",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "liveSequentialFailuresRemembered",+ "columnName": "live_sequential_failures_remembered",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "liveHealthySyncStreak",+ "columnName": "live_healthy_sync_streak",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "movieParallelFailuresRemembered",+ "columnName": "movie_parallel_failures_remembered",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "movieHealthySyncStreak",+ "columnName": "movie_healthy_sync_streak",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "seriesSequentialFailuresRemembered",+ "columnName": "series_sequential_failures_remembered",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "seriesHealthySyncStreak",+ "columnName": "series_healthy_sync_streak",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "provider_id"+ ]+ },+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "movie_category_hydration",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `category_id` INTEGER NOT NULL, `last_hydrated_at` INTEGER NOT NULL, `item_count` INTEGER NOT NULL, `last_status` TEXT NOT NULL, `last_error` TEXT, `last_loaded_page` INTEGER NOT NULL, `total_pages` INTEGER NOT NULL, `is_complete` INTEGER NOT NULL, `page_size` INTEGER NOT NULL, PRIMARY KEY(`provider_id`, `category_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastHydratedAt",+ "columnName": "last_hydrated_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "itemCount",+ "columnName": "item_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastStatus",+ "columnName": "last_status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "lastError",+ "columnName": "last_error",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lastLoadedPage",+ "columnName": "last_loaded_page",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "totalPages",+ "columnName": "total_pages",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isComplete",+ "columnName": "is_complete",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "pageSize",+ "columnName": "page_size",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "provider_id",+ "category_id"+ ]+ },+ "indices": [+ {+ "name": "index_movie_category_hydration_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movie_category_hydration_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "series_category_hydration",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `category_id` INTEGER NOT NULL, `last_hydrated_at` INTEGER NOT NULL, `item_count` INTEGER NOT NULL, `last_status` TEXT NOT NULL, `last_error` TEXT, `last_loaded_page` INTEGER NOT NULL, `total_pages` INTEGER NOT NULL, `is_complete` INTEGER NOT NULL, `page_size` INTEGER NOT NULL, PRIMARY KEY(`provider_id`, `category_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastHydratedAt",+ "columnName": "last_hydrated_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "itemCount",+ "columnName": "item_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastStatus",+ "columnName": "last_status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "lastError",+ "columnName": "last_error",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lastLoadedPage",+ "columnName": "last_loaded_page",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "totalPages",+ "columnName": "total_pages",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isComplete",+ "columnName": "is_complete",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "pageSize",+ "columnName": "page_size",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "provider_id",+ "category_id"+ ]+ },+ "indices": [+ {+ "name": "index_series_category_hydration_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_category_hydration_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "epg_sources",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `url` TEXT NOT NULL, `enabled` INTEGER NOT NULL, `last_refresh_at` INTEGER NOT NULL, `last_success_at` INTEGER NOT NULL, `last_error` TEXT, `priority` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, `etag` TEXT, `last_modified_header` TEXT)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "url",+ "columnName": "url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "enabled",+ "columnName": "enabled",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastRefreshAt",+ "columnName": "last_refresh_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastSuccessAt",+ "columnName": "last_success_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastError",+ "columnName": "last_error",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "priority",+ "columnName": "priority",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "etag",+ "columnName": "etag",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lastModifiedHeader",+ "columnName": "last_modified_header",+ "affinity": "TEXT"+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_epg_sources_url",+ "unique": true,+ "columnNames": [+ "url"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_epg_sources_url` ON `${TABLE_NAME}` (`url`)"+ }+ ]+ },+ {+ "tableName": "provider_epg_sources",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `epg_source_id` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `enabled` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`epg_source_id`) REFERENCES `epg_sources`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "epgSourceId",+ "columnName": "epg_source_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "priority",+ "columnName": "priority",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "enabled",+ "columnName": "enabled",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_provider_epg_sources_provider_id_epg_source_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "epg_source_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_provider_epg_sources_provider_id_epg_source_id` ON `${TABLE_NAME}` (`provider_id`, `epg_source_id`)"+ },+ {+ "name": "index_provider_epg_sources_epg_source_id",+ "unique": false,+ "columnNames": [+ "epg_source_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_provider_epg_sources_epg_source_id` ON `${TABLE_NAME}` (`epg_source_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ },+ {+ "table": "epg_sources",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "epg_source_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "epg_channels",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `epg_source_id` INTEGER NOT NULL, `xmltv_channel_id` TEXT NOT NULL, `display_name` TEXT NOT NULL, `normalized_name` TEXT NOT NULL, `icon_url` TEXT, FOREIGN KEY(`epg_source_id`) REFERENCES `epg_sources`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "epgSourceId",+ "columnName": "epg_source_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "xmltvChannelId",+ "columnName": "xmltv_channel_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "displayName",+ "columnName": "display_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "normalizedName",+ "columnName": "normalized_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "iconUrl",+ "columnName": "icon_url",+ "affinity": "TEXT"+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_epg_channels_epg_source_id_xmltv_channel_id",+ "unique": true,+ "columnNames": [+ "epg_source_id",+ "xmltv_channel_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_epg_channels_epg_source_id_xmltv_channel_id` ON `${TABLE_NAME}` (`epg_source_id`, `xmltv_channel_id`)"+ },+ {+ "name": "index_epg_channels_epg_source_id",+ "unique": false,+ "columnNames": [+ "epg_source_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_channels_epg_source_id` ON `${TABLE_NAME}` (`epg_source_id`)"+ },+ {+ "name": "index_epg_channels_normalized_name",+ "unique": false,+ "columnNames": [+ "normalized_name"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_channels_normalized_name` ON `${TABLE_NAME}` (`normalized_name`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "epg_sources",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "epg_source_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "epg_programmes",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `epg_source_id` INTEGER NOT NULL, `xmltv_channel_id` TEXT NOT NULL, `start_time` INTEGER NOT NULL, `end_time` INTEGER NOT NULL, `title` TEXT NOT NULL, `subtitle` TEXT, `description` TEXT NOT NULL, `category` TEXT, `lang` TEXT NOT NULL, `rating` TEXT, `image_url` TEXT, `episode_info` TEXT, FOREIGN KEY(`epg_source_id`) REFERENCES `epg_sources`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "epgSourceId",+ "columnName": "epg_source_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "xmltvChannelId",+ "columnName": "xmltv_channel_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "startTime",+ "columnName": "start_time",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "endTime",+ "columnName": "end_time",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "title",+ "columnName": "title",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "subtitle",+ "columnName": "subtitle",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "description",+ "columnName": "description",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "category",+ "columnName": "category",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lang",+ "columnName": "lang",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "rating",+ "columnName": "rating",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "imageUrl",+ "columnName": "image_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "episodeInfo",+ "columnName": "episode_info",+ "affinity": "TEXT"+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_epg_programmes_epg_source_id_xmltv_channel_id_start_time",+ "unique": false,+ "columnNames": [+ "epg_source_id",+ "xmltv_channel_id",+ "start_time"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_programmes_epg_source_id_xmltv_channel_id_start_time` ON `${TABLE_NAME}` (`epg_source_id`, `xmltv_channel_id`, `start_time`)"+ },+ {+ "name": "index_epg_programmes_epg_source_id_xmltv_channel_id_start_time_end_time",+ "unique": true,+ "columnNames": [+ "epg_source_id",+ "xmltv_channel_id",+ "start_time",+ "end_time"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_epg_programmes_epg_source_id_xmltv_channel_id_start_time_end_time` ON `${TABLE_NAME}` (`epg_source_id`, `xmltv_channel_id`, `start_time`, `end_time`)"+ },+ {+ "name": "index_epg_programmes_epg_source_id",+ "unique": false,+ "columnNames": [+ "epg_source_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_programmes_epg_source_id` ON `${TABLE_NAME}` (`epg_source_id`)"+ },+ {+ "name": "index_epg_programmes_start_time",+ "unique": false,+ "columnNames": [+ "start_time"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_programmes_start_time` ON `${TABLE_NAME}` (`start_time`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "epg_sources",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "epg_source_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "channel_epg_mappings",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_channel_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `source_type` TEXT NOT NULL, `epg_source_id` INTEGER, `xmltv_channel_id` TEXT, `match_type` TEXT, `confidence` REAL NOT NULL, `matched_at` INTEGER NOT NULL, `failed_attempts` INTEGER NOT NULL, `source` TEXT, `is_manual_override` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerChannelId",+ "columnName": "provider_channel_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "sourceType",+ "columnName": "source_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "epgSourceId",+ "columnName": "epg_source_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "xmltvChannelId",+ "columnName": "xmltv_channel_id",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "matchType",+ "columnName": "match_type",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "confidence",+ "columnName": "confidence",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "matchedAt",+ "columnName": "matched_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "failedAttempts",+ "columnName": "failed_attempts",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "source",+ "columnName": "source",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "isManualOverride",+ "columnName": "is_manual_override",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_channel_epg_mappings_provider_id_provider_channel_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "provider_channel_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_channel_epg_mappings_provider_id_provider_channel_id` ON `${TABLE_NAME}` (`provider_id`, `provider_channel_id`)"+ },+ {+ "name": "index_channel_epg_mappings_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channel_epg_mappings_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "combined_m3u_profiles",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `enabled` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "enabled",+ "columnName": "enabled",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ }+ },+ {+ "tableName": "combined_m3u_profile_members",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `profile_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `enabled` INTEGER NOT NULL, FOREIGN KEY(`profile_id`) REFERENCES `combined_m3u_profiles`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "profileId",+ "columnName": "profile_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "priority",+ "columnName": "priority",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "enabled",+ "columnName": "enabled",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_combined_m3u_profile_members_profile_id",+ "unique": false,+ "columnNames": [+ "profile_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_combined_m3u_profile_members_profile_id` ON `${TABLE_NAME}` (`profile_id`)"+ },+ {+ "name": "index_combined_m3u_profile_members_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_combined_m3u_profile_members_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_combined_m3u_profile_members_profile_id_provider_id",+ "unique": true,+ "columnNames": [+ "profile_id",+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_combined_m3u_profile_members_profile_id_provider_id` ON `${TABLE_NAME}` (`profile_id`, `provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "combined_m3u_profiles",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "profile_id"+ ],+ "referencedColumns": [+ "id"+ ]+ },+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "recording_schedules",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, `channel_name` TEXT NOT NULL, `stream_url` TEXT NOT NULL, `program_title` TEXT, `requested_start_ms` INTEGER NOT NULL, `requested_end_ms` INTEGER NOT NULL, `recurrence` TEXT NOT NULL, `recurring_rule_id` TEXT, `enabled` INTEGER NOT NULL, `is_manual` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelId",+ "columnName": "channel_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelName",+ "columnName": "channel_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "programTitle",+ "columnName": "program_title",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "requestedStartMs",+ "columnName": "requested_start_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "requestedEndMs",+ "columnName": "requested_end_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "recurrence",+ "columnName": "recurrence",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "recurringRuleId",+ "columnName": "recurring_rule_id",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "enabled",+ "columnName": "enabled",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isManual",+ "columnName": "is_manual",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "priority",+ "columnName": "priority",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_recording_schedules_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_schedules_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_recording_schedules_enabled_requested_start_ms",+ "unique": false,+ "columnNames": [+ "enabled",+ "requested_start_ms"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_schedules_enabled_requested_start_ms` ON `${TABLE_NAME}` (`enabled`, `requested_start_ms`)"+ },+ {+ "name": "index_recording_schedules_recurring_rule_id",+ "unique": false,+ "columnNames": [+ "recurring_rule_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_schedules_recurring_rule_id` ON `${TABLE_NAME}` (`recurring_rule_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "recording_runs",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `schedule_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, `channel_name` TEXT NOT NULL, `stream_url` TEXT NOT NULL, `program_title` TEXT, `scheduled_start_ms` INTEGER NOT NULL, `scheduled_end_ms` INTEGER NOT NULL, `recurrence` TEXT NOT NULL, `recurring_rule_id` TEXT, `status` TEXT NOT NULL, `source_type` TEXT NOT NULL, `resolved_url` TEXT, `headers_json` TEXT NOT NULL, `user_agent` TEXT, `expiration_time` INTEGER, `provider_label` TEXT, `output_uri` TEXT, `output_display_path` TEXT, `bytes_written` INTEGER NOT NULL, `average_throughput_bps` INTEGER NOT NULL, `retry_count` INTEGER NOT NULL, `last_progress_at_ms` INTEGER, `failure_category` TEXT NOT NULL, `failure_reason` TEXT, `terminal_at_ms` INTEGER, `started_at_ms` INTEGER, `ended_at_ms` INTEGER, `schedule_enabled` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `alarm_start_at_ms` INTEGER, `alarm_stop_at_ms` INTEGER, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`schedule_id`) REFERENCES `recording_schedules`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "scheduleId",+ "columnName": "schedule_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelId",+ "columnName": "channel_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelName",+ "columnName": "channel_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "programTitle",+ "columnName": "program_title",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "scheduledStartMs",+ "columnName": "scheduled_start_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "scheduledEndMs",+ "columnName": "scheduled_end_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "recurrence",+ "columnName": "recurrence",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "recurringRuleId",+ "columnName": "recurring_rule_id",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "status",+ "columnName": "status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "sourceType",+ "columnName": "source_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "resolvedUrl",+ "columnName": "resolved_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "headersJson",+ "columnName": "headers_json",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "userAgent",+ "columnName": "user_agent",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "expirationTime",+ "columnName": "expiration_time",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "providerLabel",+ "columnName": "provider_label",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "outputUri",+ "columnName": "output_uri",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "outputDisplayPath",+ "columnName": "output_display_path",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "bytesWritten",+ "columnName": "bytes_written",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "averageThroughputBytesPerSecond",+ "columnName": "average_throughput_bps",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "retryCount",+ "columnName": "retry_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastProgressAtMs",+ "columnName": "last_progress_at_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "failureCategory",+ "columnName": "failure_category",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "failureReason",+ "columnName": "failure_reason",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "terminalAtMs",+ "columnName": "terminal_at_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "startedAtMs",+ "columnName": "started_at_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "endedAtMs",+ "columnName": "ended_at_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "scheduleEnabled",+ "columnName": "schedule_enabled",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "priority",+ "columnName": "priority",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "alarmStartAtMs",+ "columnName": "alarm_start_at_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "alarmStopAtMs",+ "columnName": "alarm_stop_at_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_recording_runs_schedule_id",+ "unique": false,+ "columnNames": [+ "schedule_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_schedule_id` ON `${TABLE_NAME}` (`schedule_id`)"+ },+ {+ "name": "index_recording_runs_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_recording_runs_status_scheduled_start_ms",+ "unique": false,+ "columnNames": [+ "status",+ "scheduled_start_ms"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_status_scheduled_start_ms` ON `${TABLE_NAME}` (`status`, `scheduled_start_ms`)"+ },+ {+ "name": "index_recording_runs_alarm_start_at_ms",+ "unique": false,+ "columnNames": [+ "alarm_start_at_ms"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_alarm_start_at_ms` ON `${TABLE_NAME}` (`alarm_start_at_ms`)"+ },+ {+ "name": "index_recording_runs_alarm_stop_at_ms",+ "unique": false,+ "columnNames": [+ "alarm_stop_at_ms"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_alarm_stop_at_ms` ON `${TABLE_NAME}` (`alarm_stop_at_ms`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "recording_schedules",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "schedule_id"+ ],+ "referencedColumns": [+ "id"+ ]+ },+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "program_reminders",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `channel_id` TEXT NOT NULL, `channel_name` TEXT NOT NULL, `program_title` TEXT NOT NULL, `program_start_time` INTEGER NOT NULL, `remind_at` INTEGER NOT NULL, `lead_time_minutes` INTEGER NOT NULL, `is_dismissed` INTEGER NOT NULL, `notified_at` INTEGER, `created_at` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelId",+ "columnName": "channel_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "channelName",+ "columnName": "channel_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "programTitle",+ "columnName": "program_title",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "programStartTime",+ "columnName": "program_start_time",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "remindAt",+ "columnName": "remind_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "leadTimeMinutes",+ "columnName": "lead_time_minutes",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isDismissed",+ "columnName": "is_dismissed",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "notifiedAt",+ "columnName": "notified_at",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_program_reminders_provider_id_remind_at",+ "unique": false,+ "columnNames": [+ "provider_id",+ "remind_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_program_reminders_provider_id_remind_at` ON `${TABLE_NAME}` (`provider_id`, `remind_at`)"+ },+ {+ "name": "index_program_reminders_is_dismissed_notified_at_remind_at",+ "unique": false,+ "columnNames": [+ "is_dismissed",+ "notified_at",+ "remind_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_program_reminders_is_dismissed_notified_at_remind_at` ON `${TABLE_NAME}` (`is_dismissed`, `notified_at`, `remind_at`)"+ },+ {+ "name": "index_program_reminders_provider_id_channel_id_program_start_time",+ "unique": false,+ "columnNames": [+ "provider_id",+ "channel_id",+ "program_start_time"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_program_reminders_provider_id_channel_id_program_start_time` ON `${TABLE_NAME}` (`provider_id`, `channel_id`, `program_start_time`)"+ },+ {+ "name": "index_program_reminders_provider_id_channel_id_program_title_program_start_time",+ "unique": true,+ "columnNames": [+ "provider_id",+ "channel_id",+ "program_title",+ "program_start_time"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_program_reminders_provider_id_channel_id_program_title_program_start_time` ON `${TABLE_NAME}` (`provider_id`, `channel_id`, `program_title`, `program_start_time`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "recording_storage",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER NOT NULL, `tree_uri` TEXT, `display_name` TEXT, `output_directory` TEXT, `available_bytes` INTEGER, `is_writable` INTEGER NOT NULL, `file_name_pattern` TEXT NOT NULL, `retention_days` INTEGER, `max_simultaneous_recordings` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, PRIMARY KEY(`id`))",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "treeUri",+ "columnName": "tree_uri",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "displayName",+ "columnName": "display_name",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "outputDirectory",+ "columnName": "output_directory",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "availableBytes",+ "columnName": "available_bytes",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "isWritable",+ "columnName": "is_writable",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "fileNamePattern",+ "columnName": "file_name_pattern",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "retentionDays",+ "columnName": "retention_days",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "maxSimultaneousRecordings",+ "columnName": "max_simultaneous_recordings",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "id"+ ]+ }+ },+ {+ "tableName": "playback_compatibility_records",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `device_fingerprint` TEXT NOT NULL, `device_model` TEXT NOT NULL, `android_sdk` INTEGER NOT NULL, `stream_type` TEXT NOT NULL, `video_mime_type` TEXT NOT NULL, `resolution_bucket` TEXT NOT NULL, `decoder_name` TEXT NOT NULL, `surface_type` TEXT NOT NULL, `failure_type` TEXT NOT NULL, `last_failed_at` INTEGER NOT NULL, `last_succeeded_at` INTEGER NOT NULL, `failure_count` INTEGER NOT NULL, `success_count` INTEGER NOT NULL)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "deviceFingerprint",+ "columnName": "device_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "deviceModel",+ "columnName": "device_model",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "androidSdk",+ "columnName": "android_sdk",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "streamType",+ "columnName": "stream_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "videoMimeType",+ "columnName": "video_mime_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "resolutionBucket",+ "columnName": "resolution_bucket",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "decoderName",+ "columnName": "decoder_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "surfaceType",+ "columnName": "surface_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "failureType",+ "columnName": "failure_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "lastFailedAt",+ "columnName": "last_failed_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastSucceededAt",+ "columnName": "last_succeeded_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "failureCount",+ "columnName": "failure_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "successCount",+ "columnName": "success_count",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_playback_compatibility_records_device_fingerprint_stream_type_video_mime_type_resolution_bucket_decoder_name_surface_type",+ "unique": true,+ "columnNames": [+ "device_fingerprint",+ "stream_type",+ "video_mime_type",+ "resolution_bucket",+ "decoder_name",+ "surface_type"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_playback_compatibility_records_device_fingerprint_stream_type_video_mime_type_resolution_bucket_decoder_name_surface_type` ON `${TABLE_NAME}` (`device_fingerprint`, `stream_type`, `video_mime_type`, `resolution_bucket`, `decoder_name`, `surface_type`)"+ },+ {+ "name": "index_playback_compatibility_records_device_fingerprint_stream_type_video_mime_type_resolution_bucket",+ "unique": false,+ "columnNames": [+ "device_fingerprint",+ "stream_type",+ "video_mime_type",+ "resolution_bucket"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_compatibility_records_device_fingerprint_stream_type_video_mime_type_resolution_bucket` ON `${TABLE_NAME}` (`device_fingerprint`, `stream_type`, `video_mime_type`, `resolution_bucket`)"+ },+ {+ "name": "index_playback_compatibility_records_last_failed_at",+ "unique": false,+ "columnNames": [+ "last_failed_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_compatibility_records_last_failed_at` ON `${TABLE_NAME}` (`last_failed_at`)"+ },+ {+ "name": "index_playback_compatibility_records_last_succeeded_at",+ "unique": false,+ "columnNames": [+ "last_succeeded_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_compatibility_records_last_succeeded_at` ON `${TABLE_NAME}` (`last_succeeded_at`)"+ }+ ]+ }+ ],+ "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, '2f7a029188a49532c28f79b6815544d1')"+ ]+ }+}\ No newline at end of filediff --git a/data/schemas/com.streamvault.data.local.StreamVaultDatabase/47.json b/data/schemas/com.streamvault.data.local.StreamVaultDatabase/47.jsonnew file mode 100644index 00000000..f1a1d9e7--- /dev/null+++ b/data/schemas/com.streamvault.data.local.StreamVaultDatabase/47.json@@ -0,0 +1,4411 @@+{+ "formatVersion": 1,+ "database": {+ "version": 47,+ "identityHash": "42b2a09f506226f1fb519e90fc827010",+ "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, `stalker_mac_address` TEXT NOT NULL, `stalker_device_profile` TEXT NOT NULL, `stalker_device_timezone` TEXT NOT NULL, `stalker_device_locale` TEXT NOT NULL, `is_active` INTEGER NOT NULL, `max_connections` INTEGER NOT NULL, `expiration_date` INTEGER, `api_version` TEXT, `allowed_output_formats_json` TEXT NOT NULL, `epg_sync_mode` TEXT NOT NULL, `xtream_fast_sync_enabled` INTEGER NOT NULL, `m3u_vod_classification_enabled` INTEGER NOT NULL, `status` TEXT NOT NULL, `last_synced_at` INTEGER NOT NULL, `created_at` INTEGER NOT NULL)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "type",+ "columnName": "type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "serverUrl",+ "columnName": "server_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "username",+ "columnName": "username",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "password",+ "columnName": "password",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "m3uUrl",+ "columnName": "m3u_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "epgUrl",+ "columnName": "epg_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerMacAddress",+ "columnName": "stalker_mac_address",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerDeviceProfile",+ "columnName": "stalker_device_profile",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerDeviceTimezone",+ "columnName": "stalker_device_timezone",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerDeviceLocale",+ "columnName": "stalker_device_locale",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "isActive",+ "columnName": "is_active",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "maxConnections",+ "columnName": "max_connections",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "expirationDate",+ "columnName": "expiration_date",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "apiVersion",+ "columnName": "api_version",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "allowedOutputFormatsJson",+ "columnName": "allowed_output_formats_json",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "epgSyncMode",+ "columnName": "epg_sync_mode",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "xtreamFastSyncEnabled",+ "columnName": "xtream_fast_sync_enabled",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "m3uVodClassificationEnabled",+ "columnName": "m3u_vod_classification_enabled",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "status",+ "columnName": "status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "lastSyncedAt",+ "columnName": "last_synced_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_providers_server_url_username_stalker_mac_address",+ "unique": true,+ "columnNames": [+ "server_url",+ "username",+ "stalker_mac_address"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_providers_server_url_username_stalker_mac_address` ON `${TABLE_NAME}` (`server_url`, `username`, `stalker_mac_address`)"+ }+ ]+ },+ {+ "tableName": "channels",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `stream_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `logo_url` TEXT, `group_title` TEXT, `category_id` INTEGER, `category_name` TEXT, `stream_url` TEXT NOT NULL, `epg_channel_id` TEXT, `number` INTEGER NOT NULL, `catch_up_supported` INTEGER NOT NULL, `catch_up_days` INTEGER NOT NULL, `catchUpSource` TEXT, `provider_id` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, `logical_group_id` TEXT NOT NULL, `error_count` INTEGER NOT NULL, `quality_options_json` TEXT, `sync_fingerprint` TEXT NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "streamId",+ "columnName": "stream_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "logoUrl",+ "columnName": "logo_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "groupTitle",+ "columnName": "group_title",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "categoryName",+ "columnName": "category_name",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "epgChannelId",+ "columnName": "epg_channel_id",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "number",+ "columnName": "number",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "catchUpSupported",+ "columnName": "catch_up_supported",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "catchUpDays",+ "columnName": "catch_up_days",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "catchUpSource",+ "columnName": "catchUpSource",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isUserProtected",+ "columnName": "is_user_protected",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "logicalGroupId",+ "columnName": "logical_group_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "errorCount",+ "columnName": "error_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "qualityOptionsJson",+ "columnName": "quality_options_json",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "syncFingerprint",+ "columnName": "sync_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_channels_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_channels_provider_id_category_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "category_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_provider_id_category_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`)"+ },+ {+ "name": "index_channels_provider_id_stream_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "stream_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_channels_provider_id_stream_id` ON `${TABLE_NAME}` (`provider_id`, `stream_id`)"+ },+ {+ "name": "index_channels_logical_group_id",+ "unique": false,+ "columnNames": [+ "logical_group_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_logical_group_id` ON `${TABLE_NAME}` (`logical_group_id`)"+ },+ {+ "name": "index_channels_provider_id_category_id_logical_group_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "category_id",+ "logical_group_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_provider_id_category_id_logical_group_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`, `logical_group_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "channel_preferences",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `channel_id` INTEGER NOT NULL, `aspect_ratio` TEXT, `audio_video_offset_ms` INTEGER, `updated_at` INTEGER NOT NULL, FOREIGN KEY(`channel_id`) REFERENCES `channels`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelId",+ "columnName": "channel_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "aspectRatio",+ "columnName": "aspect_ratio",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "audioVideoOffsetMs",+ "columnName": "audio_video_offset_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_channel_preferences_channel_id",+ "unique": true,+ "columnNames": [+ "channel_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_channel_preferences_channel_id` ON `${TABLE_NAME}` (`channel_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "channels",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "channel_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "channels_fts",+ "createSql": "CREATE VIRTUAL TABLE IF NOT EXISTS `${TABLE_NAME}` USING FTS4(`name` TEXT NOT NULL, content=`channels`)",+ "fields": [+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": []+ },+ "ftsVersion": "FTS4",+ "ftsOptions": {+ "tokenizer": "simple",+ "tokenizerArgs": [],+ "contentTable": "channels",+ "languageIdColumnName": "",+ "matchInfo": "FTS4",+ "notIndexedColumns": [],+ "prefixSizes": [],+ "preferredOrder": "ASC"+ },+ "contentSyncTriggers": [+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_BEFORE_UPDATE BEFORE UPDATE ON `channels` BEGIN DELETE FROM `channels_fts` WHERE `docid`=OLD.`rowid`; END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_BEFORE_DELETE BEFORE DELETE ON `channels` BEGIN DELETE FROM `channels_fts` WHERE `docid`=OLD.`rowid`; END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_AFTER_UPDATE AFTER UPDATE ON `channels` BEGIN INSERT INTO `channels_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_AFTER_INSERT AFTER INSERT ON `channels` BEGIN INSERT INTO `channels_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END"+ ]+ },+ {+ "tableName": "movies",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `stream_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `poster_url` TEXT, `backdrop_url` TEXT, `category_id` INTEGER, `category_name` TEXT, `stream_url` TEXT NOT NULL, `container_extension` TEXT, `plot` TEXT, `cast` TEXT, `director` TEXT, `genre` TEXT, `release_date` TEXT, `duration` TEXT, `duration_seconds` INTEGER NOT NULL, `rating` REAL NOT NULL, `year` TEXT, `tmdb_id` INTEGER, `youtube_trailer` TEXT, `provider_id` INTEGER NOT NULL, `watch_progress` INTEGER NOT NULL, `watch_count` INTEGER NOT NULL, `last_watched_at` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, `added_at` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "streamId",+ "columnName": "stream_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "posterUrl",+ "columnName": "poster_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "backdropUrl",+ "columnName": "backdrop_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "categoryName",+ "columnName": "category_name",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "containerExtension",+ "columnName": "container_extension",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "plot",+ "columnName": "plot",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "cast",+ "columnName": "cast",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "director",+ "columnName": "director",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "genre",+ "columnName": "genre",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "releaseDate",+ "columnName": "release_date",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "duration",+ "columnName": "duration",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "durationSeconds",+ "columnName": "duration_seconds",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "rating",+ "columnName": "rating",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "year",+ "columnName": "year",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "tmdbId",+ "columnName": "tmdb_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "youtubeTrailer",+ "columnName": "youtube_trailer",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "watchProgress",+ "columnName": "watch_progress",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "watchCount",+ "columnName": "watch_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastWatchedAt",+ "columnName": "last_watched_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isUserProtected",+ "columnName": "is_user_protected",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "syncFingerprint",+ "columnName": "sync_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "addedAt",+ "columnName": "added_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_movies_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_movies_provider_id_category_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "category_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id_category_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`)"+ },+ {+ "name": "index_movies_provider_id_stream_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "stream_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_movies_provider_id_stream_id` ON `${TABLE_NAME}` (`provider_id`, `stream_id`)"+ },+ {+ "name": "index_movies_provider_id_name_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "name",+ "id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id_name_id` ON `${TABLE_NAME}` (`provider_id`, `name`, `id`)"+ },+ {+ "name": "index_movies_provider_id_category_id_name_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "category_id",+ "name",+ "id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id_category_id_name_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`, `name`, `id`)"+ },+ {+ "name": "index_movies_provider_id_rating_name_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "rating",+ "name",+ "id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id_rating_name_id` ON `${TABLE_NAME}` (`provider_id`, `rating`, `name`, `id`)"+ },+ {+ "name": "index_movies_provider_id_added_at_release_date_name_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "added_at",+ "release_date",+ "name",+ "id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id_added_at_release_date_name_id` ON `${TABLE_NAME}` (`provider_id`, `added_at`, `release_date`, `name`, `id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "movies_fts",+ "createSql": "CREATE VIRTUAL TABLE IF NOT EXISTS `${TABLE_NAME}` USING FTS4(`name` TEXT NOT NULL, content=`movies`)",+ "fields": [+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": []+ },+ "ftsVersion": "FTS4",+ "ftsOptions": {+ "tokenizer": "simple",+ "tokenizerArgs": [],+ "contentTable": "movies",+ "languageIdColumnName": "",+ "matchInfo": "FTS4",+ "notIndexedColumns": [],+ "prefixSizes": [],+ "preferredOrder": "ASC"+ },+ "contentSyncTriggers": [+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_movies_fts_BEFORE_UPDATE BEFORE UPDATE ON `movies` BEGIN DELETE FROM `movies_fts` WHERE `docid`=OLD.`rowid`; END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_movies_fts_BEFORE_DELETE BEFORE DELETE ON `movies` BEGIN DELETE FROM `movies_fts` WHERE `docid`=OLD.`rowid`; END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_movies_fts_AFTER_UPDATE AFTER UPDATE ON `movies` BEGIN INSERT INTO `movies_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_movies_fts_AFTER_INSERT AFTER INSERT ON `movies` BEGIN INSERT INTO `movies_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END"+ ]+ },+ {+ "tableName": "series",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `series_id` INTEGER NOT NULL, `provider_series_id` TEXT, `name` TEXT NOT NULL, `poster_url` TEXT, `backdrop_url` TEXT, `category_id` INTEGER, `category_name` TEXT, `plot` TEXT, `cast` TEXT, `director` TEXT, `genre` TEXT, `release_date` TEXT, `rating` REAL NOT NULL, `tmdb_id` INTEGER, `youtube_trailer` TEXT, `episode_run_time` TEXT, `last_modified` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "seriesId",+ "columnName": "series_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerSeriesId",+ "columnName": "provider_series_id",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "posterUrl",+ "columnName": "poster_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "backdropUrl",+ "columnName": "backdrop_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "categoryName",+ "columnName": "category_name",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "plot",+ "columnName": "plot",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "cast",+ "columnName": "cast",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "director",+ "columnName": "director",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "genre",+ "columnName": "genre",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "releaseDate",+ "columnName": "release_date",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "rating",+ "columnName": "rating",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "tmdbId",+ "columnName": "tmdb_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "youtubeTrailer",+ "columnName": "youtube_trailer",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "episodeRunTime",+ "columnName": "episode_run_time",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lastModified",+ "columnName": "last_modified",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isUserProtected",+ "columnName": "is_user_protected",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "syncFingerprint",+ "columnName": "sync_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_series_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_series_provider_id_category_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "category_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_provider_id_category_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`)"+ },+ {+ "name": "index_series_provider_id_series_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "series_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_series_provider_id_series_id` ON `${TABLE_NAME}` (`provider_id`, `series_id`)"+ },+ {+ "name": "index_series_provider_id_name_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "name",+ "id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_provider_id_name_id` ON `${TABLE_NAME}` (`provider_id`, `name`, `id`)"+ },+ {+ "name": "index_series_provider_id_category_id_name_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "category_id",+ "name",+ "id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_provider_id_category_id_name_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`, `name`, `id`)"+ },+ {+ "name": "index_series_provider_id_rating_name_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "rating",+ "name",+ "id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_provider_id_rating_name_id` ON `${TABLE_NAME}` (`provider_id`, `rating`, `name`, `id`)"+ },+ {+ "name": "index_series_provider_id_last_modified_name_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "last_modified",+ "name",+ "id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_provider_id_last_modified_name_id` ON `${TABLE_NAME}` (`provider_id`, `last_modified`, `name`, `id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "series_fts",+ "createSql": "CREATE VIRTUAL TABLE IF NOT EXISTS `${TABLE_NAME}` USING FTS4(`name` TEXT NOT NULL, content=`series`)",+ "fields": [+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": []+ },+ "ftsVersion": "FTS4",+ "ftsOptions": {+ "tokenizer": "simple",+ "tokenizerArgs": [],+ "contentTable": "series",+ "languageIdColumnName": "",+ "matchInfo": "FTS4",+ "notIndexedColumns": [],+ "prefixSizes": [],+ "preferredOrder": "ASC"+ },+ "contentSyncTriggers": [+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_series_fts_BEFORE_UPDATE BEFORE UPDATE ON `series` BEGIN DELETE FROM `series_fts` WHERE `docid`=OLD.`rowid`; END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_series_fts_BEFORE_DELETE BEFORE DELETE ON `series` BEGIN DELETE FROM `series_fts` WHERE `docid`=OLD.`rowid`; END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_series_fts_AFTER_UPDATE AFTER UPDATE ON `series` BEGIN INSERT INTO `series_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_series_fts_AFTER_INSERT AFTER INSERT ON `series` BEGIN INSERT INTO `series_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END"+ ]+ },+ {+ "tableName": "episodes",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `episode_id` INTEGER NOT NULL, `title` TEXT NOT NULL, `episode_number` INTEGER NOT NULL, `season_number` INTEGER NOT NULL, `stream_url` TEXT NOT NULL, `container_extension` TEXT, `cover_url` TEXT, `plot` TEXT, `duration` TEXT, `duration_seconds` INTEGER NOT NULL, `rating` REAL NOT NULL, `release_date` TEXT, `series_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `watch_progress` INTEGER NOT NULL, `last_watched_at` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`series_id`) REFERENCES `series`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "episodeId",+ "columnName": "episode_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "title",+ "columnName": "title",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "episodeNumber",+ "columnName": "episode_number",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "seasonNumber",+ "columnName": "season_number",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "containerExtension",+ "columnName": "container_extension",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "coverUrl",+ "columnName": "cover_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "plot",+ "columnName": "plot",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "duration",+ "columnName": "duration",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "durationSeconds",+ "columnName": "duration_seconds",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "rating",+ "columnName": "rating",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "releaseDate",+ "columnName": "release_date",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "seriesId",+ "columnName": "series_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "watchProgress",+ "columnName": "watch_progress",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastWatchedAt",+ "columnName": "last_watched_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isUserProtected",+ "columnName": "is_user_protected",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_episodes_series_id",+ "unique": false,+ "columnNames": [+ "series_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_episodes_series_id` ON `${TABLE_NAME}` (`series_id`)"+ },+ {+ "name": "index_episodes_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_episodes_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_episodes_provider_id_episode_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "episode_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_episodes_provider_id_episode_id` ON `${TABLE_NAME}` (`provider_id`, `episode_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ },+ {+ "table": "series",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "series_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "categories",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `category_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `parent_id` INTEGER, `type` TEXT NOT NULL, `provider_id` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "parentId",+ "columnName": "parent_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "type",+ "columnName": "type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isUserProtected",+ "columnName": "is_user_protected",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "syncFingerprint",+ "columnName": "sync_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_categories_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_categories_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_categories_provider_id_type",+ "unique": false,+ "columnNames": [+ "provider_id",+ "type"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_categories_provider_id_type` ON `${TABLE_NAME}` (`provider_id`, `type`)"+ },+ {+ "name": "index_categories_provider_id_category_id_type",+ "unique": true,+ "columnNames": [+ "provider_id",+ "category_id",+ "type"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_categories_provider_id_category_id_type` ON `${TABLE_NAME}` (`provider_id`, `category_id`, `type`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "channel_import_stage",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`session_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `stream_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `logo_url` TEXT, `group_title` TEXT, `category_id` INTEGER, `category_name` TEXT, `stream_url` TEXT NOT NULL, `epg_channel_id` TEXT, `number` INTEGER NOT NULL, `catch_up_supported` INTEGER NOT NULL, `catch_up_days` INTEGER NOT NULL, `catchUpSource` TEXT, `is_adult` INTEGER NOT NULL, `logical_group_id` TEXT NOT NULL, `error_count` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, PRIMARY KEY(`session_id`, `provider_id`, `stream_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "sessionId",+ "columnName": "session_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "streamId",+ "columnName": "stream_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "logoUrl",+ "columnName": "logo_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "groupTitle",+ "columnName": "group_title",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "categoryName",+ "columnName": "category_name",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "epgChannelId",+ "columnName": "epg_channel_id",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "number",+ "columnName": "number",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "catchUpSupported",+ "columnName": "catch_up_supported",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "catchUpDays",+ "columnName": "catch_up_days",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "catchUpSource",+ "columnName": "catchUpSource",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "logicalGroupId",+ "columnName": "logical_group_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "errorCount",+ "columnName": "error_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "syncFingerprint",+ "columnName": "sync_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "session_id",+ "provider_id",+ "stream_id"+ ]+ },+ "indices": [+ {+ "name": "index_channel_import_stage_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channel_import_stage_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_channel_import_stage_session_id_provider_id",+ "unique": false,+ "columnNames": [+ "session_id",+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channel_import_stage_session_id_provider_id` ON `${TABLE_NAME}` (`session_id`, `provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "movie_import_stage",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`session_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `stream_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `poster_url` TEXT, `backdrop_url` TEXT, `category_id` INTEGER, `category_name` TEXT, `stream_url` TEXT NOT NULL, `container_extension` TEXT, `plot` TEXT, `cast` TEXT, `director` TEXT, `genre` TEXT, `release_date` TEXT, `duration` TEXT, `duration_seconds` INTEGER NOT NULL, `rating` REAL NOT NULL, `year` TEXT, `tmdb_id` INTEGER, `youtube_trailer` TEXT, `is_adult` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, `added_at` INTEGER NOT NULL, PRIMARY KEY(`session_id`, `provider_id`, `stream_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "sessionId",+ "columnName": "session_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "streamId",+ "columnName": "stream_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "posterUrl",+ "columnName": "poster_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "backdropUrl",+ "columnName": "backdrop_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "categoryName",+ "columnName": "category_name",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "containerExtension",+ "columnName": "container_extension",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "plot",+ "columnName": "plot",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "cast",+ "columnName": "cast",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "director",+ "columnName": "director",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "genre",+ "columnName": "genre",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "releaseDate",+ "columnName": "release_date",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "duration",+ "columnName": "duration",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "durationSeconds",+ "columnName": "duration_seconds",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "rating",+ "columnName": "rating",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "year",+ "columnName": "year",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "tmdbId",+ "columnName": "tmdb_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "youtubeTrailer",+ "columnName": "youtube_trailer",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "syncFingerprint",+ "columnName": "sync_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "addedAt",+ "columnName": "added_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "session_id",+ "provider_id",+ "stream_id"+ ]+ },+ "indices": [+ {+ "name": "index_movie_import_stage_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movie_import_stage_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_movie_import_stage_session_id_provider_id",+ "unique": false,+ "columnNames": [+ "session_id",+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movie_import_stage_session_id_provider_id` ON `${TABLE_NAME}` (`session_id`, `provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "series_import_stage",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`session_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `series_id` INTEGER NOT NULL, `provider_series_id` TEXT, `provider_series_key` TEXT NOT NULL, `name` TEXT NOT NULL, `poster_url` TEXT, `backdrop_url` TEXT, `category_id` INTEGER, `category_name` TEXT, `plot` TEXT, `cast` TEXT, `director` TEXT, `genre` TEXT, `release_date` TEXT, `rating` REAL NOT NULL, `tmdb_id` INTEGER, `youtube_trailer` TEXT, `episode_run_time` TEXT, `last_modified` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, PRIMARY KEY(`session_id`, `provider_id`, `provider_series_key`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "sessionId",+ "columnName": "session_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "seriesId",+ "columnName": "series_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerSeriesId",+ "columnName": "provider_series_id",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "providerSeriesKey",+ "columnName": "provider_series_key",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "posterUrl",+ "columnName": "poster_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "backdropUrl",+ "columnName": "backdrop_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "categoryName",+ "columnName": "category_name",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "plot",+ "columnName": "plot",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "cast",+ "columnName": "cast",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "director",+ "columnName": "director",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "genre",+ "columnName": "genre",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "releaseDate",+ "columnName": "release_date",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "rating",+ "columnName": "rating",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "tmdbId",+ "columnName": "tmdb_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "youtubeTrailer",+ "columnName": "youtube_trailer",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "episodeRunTime",+ "columnName": "episode_run_time",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lastModified",+ "columnName": "last_modified",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "syncFingerprint",+ "columnName": "sync_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "session_id",+ "provider_id",+ "provider_series_key"+ ]+ },+ "indices": [+ {+ "name": "index_series_import_stage_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_import_stage_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_series_import_stage_session_id_provider_id",+ "unique": false,+ "columnNames": [+ "session_id",+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_import_stage_session_id_provider_id` ON `${TABLE_NAME}` (`session_id`, `provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "category_import_stage",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`session_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `category_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `parent_id` INTEGER, `type` TEXT NOT NULL, `is_adult` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, PRIMARY KEY(`session_id`, `provider_id`, `category_id`, `type`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "sessionId",+ "columnName": "session_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "parentId",+ "columnName": "parent_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "type",+ "columnName": "type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "syncFingerprint",+ "columnName": "sync_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "session_id",+ "provider_id",+ "category_id",+ "type"+ ]+ },+ "indices": [+ {+ "name": "index_category_import_stage_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_category_import_stage_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_category_import_stage_session_id_provider_id",+ "unique": false,+ "columnNames": [+ "session_id",+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_category_import_stage_session_id_provider_id` ON `${TABLE_NAME}` (`session_id`, `provider_id`)"+ },+ {+ "name": "index_category_import_stage_provider_id_type",+ "unique": false,+ "columnNames": [+ "provider_id",+ "type"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_category_import_stage_provider_id_type` ON `${TABLE_NAME}` (`provider_id`, `type`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "programs",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `channel_id` TEXT NOT NULL, `title` TEXT NOT NULL, `description` TEXT NOT NULL, `start_time` INTEGER NOT NULL, `end_time` INTEGER NOT NULL, `lang` TEXT NOT NULL, `rating` TEXT, `image_url` TEXT, `genre` TEXT, `category` TEXT, `has_archive` INTEGER NOT NULL)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelId",+ "columnName": "channel_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "title",+ "columnName": "title",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "description",+ "columnName": "description",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "startTime",+ "columnName": "start_time",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "endTime",+ "columnName": "end_time",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lang",+ "columnName": "lang",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "rating",+ "columnName": "rating",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "imageUrl",+ "columnName": "image_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "genre",+ "columnName": "genre",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "category",+ "columnName": "category",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "hasArchive",+ "columnName": "has_archive",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_programs_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_programs_provider_id_channel_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "channel_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_channel_id` ON `${TABLE_NAME}` (`provider_id`, `channel_id`)"+ },+ {+ "name": "index_programs_provider_id_end_time_channel_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "end_time",+ "channel_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_end_time_channel_id` ON `${TABLE_NAME}` (`provider_id`, `end_time`, `channel_id`)"+ },+ {+ "name": "index_programs_provider_id_start_time_end_time",+ "unique": false,+ "columnNames": [+ "provider_id",+ "start_time",+ "end_time"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_start_time_end_time` ON `${TABLE_NAME}` (`provider_id`, `start_time`, `end_time`)"+ },+ {+ "name": "index_programs_start_time",+ "unique": false,+ "columnNames": [+ "start_time"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_start_time` ON `${TABLE_NAME}` (`start_time`)"+ },+ {+ "name": "index_programs_provider_id_channel_id_start_time",+ "unique": false,+ "columnNames": [+ "provider_id",+ "channel_id",+ "start_time"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_channel_id_start_time` ON `${TABLE_NAME}` (`provider_id`, `channel_id`, `start_time`)"+ },+ {+ "name": "index_programs_provider_id_channel_id_start_time_end_time",+ "unique": true,+ "columnNames": [+ "provider_id",+ "channel_id",+ "start_time",+ "end_time"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_programs_provider_id_channel_id_start_time_end_time` ON `${TABLE_NAME}` (`provider_id`, `channel_id`, `start_time`, `end_time`)"+ }+ ]+ },+ {+ "tableName": "favorites",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `content_id` INTEGER NOT NULL, `content_type` TEXT NOT NULL, `position` INTEGER NOT NULL, `group_id` INTEGER, `group_key` INTEGER NOT NULL, `added_at` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`group_id`) REFERENCES `virtual_groups`(`id`) ON UPDATE NO ACTION ON DELETE SET NULL )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentId",+ "columnName": "content_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentType",+ "columnName": "content_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "position",+ "columnName": "position",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "groupId",+ "columnName": "group_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "groupKey",+ "columnName": "group_key",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "addedAt",+ "columnName": "added_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_favorites_provider_id_content_id_content_type_group_key",+ "unique": true,+ "columnNames": [+ "provider_id",+ "content_id",+ "content_type",+ "group_key"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_favorites_provider_id_content_id_content_type_group_key` ON `${TABLE_NAME}` (`provider_id`, `content_id`, `content_type`, `group_key`)"+ },+ {+ "name": "index_favorites_provider_id_content_type_group_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "content_type",+ "group_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_favorites_provider_id_content_type_group_id` ON `${TABLE_NAME}` (`provider_id`, `content_type`, `group_id`)"+ },+ {+ "name": "index_favorites_group_id_position",+ "unique": false,+ "columnNames": [+ "group_id",+ "position"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_favorites_group_id_position` ON `${TABLE_NAME}` (`group_id`, `position`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ },+ {+ "table": "virtual_groups",+ "onDelete": "SET NULL",+ "onUpdate": "NO ACTION",+ "columns": [+ "group_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "virtual_groups",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `icon_emoji` TEXT, `position` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `content_type` TEXT NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "iconEmoji",+ "columnName": "icon_emoji",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "position",+ "columnName": "position",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentType",+ "columnName": "content_type",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_virtual_groups_provider_id_content_type",+ "unique": false,+ "columnNames": [+ "provider_id",+ "content_type"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_virtual_groups_provider_id_content_type` ON `${TABLE_NAME}` (`provider_id`, `content_type`)"+ },+ {+ "name": "index_virtual_groups_position",+ "unique": false,+ "columnNames": [+ "position"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_virtual_groups_position` ON `${TABLE_NAME}` (`position`)"+ },+ {+ "name": "index_virtual_groups_content_type",+ "unique": false,+ "columnNames": [+ "content_type"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_virtual_groups_content_type` ON `${TABLE_NAME}` (`content_type`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "playback_history",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `content_id` INTEGER NOT NULL, `content_type` TEXT NOT NULL, `provider_id` INTEGER NOT NULL, `title` TEXT NOT NULL, `poster_url` TEXT, `stream_url` TEXT NOT NULL, `resume_position_ms` INTEGER NOT NULL, `total_duration_ms` INTEGER NOT NULL, `last_watched_at` INTEGER NOT NULL, `watch_count` INTEGER NOT NULL, `watched_status` TEXT NOT NULL, `series_id` INTEGER, `season_number` INTEGER, `episode_number` INTEGER, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentId",+ "columnName": "content_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentType",+ "columnName": "content_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "title",+ "columnName": "title",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "posterUrl",+ "columnName": "poster_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "resumePositionMs",+ "columnName": "resume_position_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "totalDurationMs",+ "columnName": "total_duration_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastWatchedAt",+ "columnName": "last_watched_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "watchCount",+ "columnName": "watch_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "watchedStatus",+ "columnName": "watched_status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "seriesId",+ "columnName": "series_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "seasonNumber",+ "columnName": "season_number",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "episodeNumber",+ "columnName": "episode_number",+ "affinity": "INTEGER"+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_playback_history_content_id_content_type_provider_id",+ "unique": true,+ "columnNames": [+ "content_id",+ "content_type",+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_playback_history_content_id_content_type_provider_id` ON `${TABLE_NAME}` (`content_id`, `content_type`, `provider_id`)"+ },+ {+ "name": "index_playback_history_last_watched_at",+ "unique": false,+ "columnNames": [+ "last_watched_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_history_last_watched_at` ON `${TABLE_NAME}` (`last_watched_at`)"+ },+ {+ "name": "index_playback_history_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_history_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_playback_history_provider_id_content_type_content_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "content_type",+ "content_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_history_provider_id_content_type_content_id` ON `${TABLE_NAME}` (`provider_id`, `content_type`, `content_id`)"+ },+ {+ "name": "index_playback_history_provider_id_content_type_last_watched_at",+ "unique": false,+ "columnNames": [+ "provider_id",+ "content_type",+ "last_watched_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_history_provider_id_content_type_last_watched_at` ON `${TABLE_NAME}` (`provider_id`, `content_type`, `last_watched_at`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "tmdb_identity",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`tmdb_id` INTEGER NOT NULL, `content_type` TEXT NOT NULL, `canonical_provider_id` INTEGER NOT NULL, `first_seen_at` INTEGER NOT NULL, PRIMARY KEY(`tmdb_id`, `content_type`), FOREIGN KEY(`canonical_provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "tmdbId",+ "columnName": "tmdb_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentType",+ "columnName": "content_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "canonicalProviderId",+ "columnName": "canonical_provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "firstSeenAt",+ "columnName": "first_seen_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "tmdb_id",+ "content_type"+ ]+ },+ "indices": [+ {+ "name": "index_tmdb_identity_content_type",+ "unique": false,+ "columnNames": [+ "content_type"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_tmdb_identity_content_type` ON `${TABLE_NAME}` (`content_type`)"+ },+ {+ "name": "index_tmdb_identity_canonical_provider_id",+ "unique": false,+ "columnNames": [+ "canonical_provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_tmdb_identity_canonical_provider_id` ON `${TABLE_NAME}` (`canonical_provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "canonical_provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "search_history",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `query` TEXT NOT NULL, `content_scope` TEXT NOT NULL, `provider_id` INTEGER NOT NULL, `used_at` INTEGER NOT NULL, `use_count` INTEGER NOT NULL)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "query",+ "columnName": "query",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "contentScope",+ "columnName": "content_scope",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "usedAt",+ "columnName": "used_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "useCount",+ "columnName": "use_count",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_search_history_content_scope_provider_id_used_at",+ "unique": false,+ "columnNames": [+ "content_scope",+ "provider_id",+ "used_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_search_history_content_scope_provider_id_used_at` ON `${TABLE_NAME}` (`content_scope`, `provider_id`, `used_at`)"+ },+ {+ "name": "index_search_history_used_at",+ "unique": false,+ "columnNames": [+ "used_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_search_history_used_at` ON `${TABLE_NAME}` (`used_at`)"+ },+ {+ "name": "index_search_history_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_search_history_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_search_history_query_content_scope_provider_id",+ "unique": true,+ "columnNames": [+ "query",+ "content_scope",+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_search_history_query_content_scope_provider_id` ON `${TABLE_NAME}` (`query`, `content_scope`, `provider_id`)"+ }+ ]+ },+ {+ "tableName": "sync_metadata",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `last_live_sync` INTEGER NOT NULL, `last_live_success` INTEGER NOT NULL, `last_movie_sync` INTEGER NOT NULL, `last_series_sync` INTEGER NOT NULL, `last_series_success` INTEGER NOT NULL, `last_epg_sync` INTEGER NOT NULL, `last_epg_success` INTEGER NOT NULL, `last_movie_attempt` INTEGER NOT NULL, `last_movie_success` INTEGER NOT NULL, `last_movie_partial` INTEGER NOT NULL, `live_count` INTEGER NOT NULL, `movie_count` INTEGER NOT NULL, `series_count` INTEGER NOT NULL, `epg_count` INTEGER NOT NULL, `last_sync_status` TEXT NOT NULL, `movie_sync_mode` TEXT NOT NULL, `movie_warnings_count` INTEGER NOT NULL, `movie_catalog_stale` INTEGER NOT NULL, `live_avoid_full_until` INTEGER NOT NULL, `movie_avoid_full_until` INTEGER NOT NULL, `series_avoid_full_until` INTEGER NOT NULL, `live_sequential_failures_remembered` INTEGER NOT NULL, `live_healthy_sync_streak` INTEGER NOT NULL, `movie_parallel_failures_remembered` INTEGER NOT NULL, `movie_healthy_sync_streak` INTEGER NOT NULL, `series_sequential_failures_remembered` INTEGER NOT NULL, `series_healthy_sync_streak` INTEGER NOT NULL, PRIMARY KEY(`provider_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastLiveSync",+ "columnName": "last_live_sync",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastLiveSuccess",+ "columnName": "last_live_success",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastMovieSync",+ "columnName": "last_movie_sync",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastSeriesSync",+ "columnName": "last_series_sync",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastSeriesSuccess",+ "columnName": "last_series_success",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastEpgSync",+ "columnName": "last_epg_sync",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastEpgSuccess",+ "columnName": "last_epg_success",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastMovieAttempt",+ "columnName": "last_movie_attempt",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastMovieSuccess",+ "columnName": "last_movie_success",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastMoviePartial",+ "columnName": "last_movie_partial",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "liveCount",+ "columnName": "live_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "movieCount",+ "columnName": "movie_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "seriesCount",+ "columnName": "series_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "epgCount",+ "columnName": "epg_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastSyncStatus",+ "columnName": "last_sync_status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "movieSyncMode",+ "columnName": "movie_sync_mode",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "movieWarningsCount",+ "columnName": "movie_warnings_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "movieCatalogStale",+ "columnName": "movie_catalog_stale",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "liveAvoidFullUntil",+ "columnName": "live_avoid_full_until",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "movieAvoidFullUntil",+ "columnName": "movie_avoid_full_until",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "seriesAvoidFullUntil",+ "columnName": "series_avoid_full_until",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "liveSequentialFailuresRemembered",+ "columnName": "live_sequential_failures_remembered",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "liveHealthySyncStreak",+ "columnName": "live_healthy_sync_streak",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "movieParallelFailuresRemembered",+ "columnName": "movie_parallel_failures_remembered",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "movieHealthySyncStreak",+ "columnName": "movie_healthy_sync_streak",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "seriesSequentialFailuresRemembered",+ "columnName": "series_sequential_failures_remembered",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "seriesHealthySyncStreak",+ "columnName": "series_healthy_sync_streak",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "provider_id"+ ]+ },+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "movie_category_hydration",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `category_id` INTEGER NOT NULL, `last_hydrated_at` INTEGER NOT NULL, `item_count` INTEGER NOT NULL, `last_status` TEXT NOT NULL, `last_error` TEXT, `last_loaded_page` INTEGER NOT NULL, `total_pages` INTEGER NOT NULL, `is_complete` INTEGER NOT NULL, `page_size` INTEGER NOT NULL, PRIMARY KEY(`provider_id`, `category_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastHydratedAt",+ "columnName": "last_hydrated_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "itemCount",+ "columnName": "item_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastStatus",+ "columnName": "last_status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "lastError",+ "columnName": "last_error",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lastLoadedPage",+ "columnName": "last_loaded_page",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "totalPages",+ "columnName": "total_pages",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isComplete",+ "columnName": "is_complete",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "pageSize",+ "columnName": "page_size",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "provider_id",+ "category_id"+ ]+ },+ "indices": [+ {+ "name": "index_movie_category_hydration_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movie_category_hydration_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "series_category_hydration",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `category_id` INTEGER NOT NULL, `last_hydrated_at` INTEGER NOT NULL, `item_count` INTEGER NOT NULL, `last_status` TEXT NOT NULL, `last_error` TEXT, `last_loaded_page` INTEGER NOT NULL, `total_pages` INTEGER NOT NULL, `is_complete` INTEGER NOT NULL, `page_size` INTEGER NOT NULL, PRIMARY KEY(`provider_id`, `category_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastHydratedAt",+ "columnName": "last_hydrated_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "itemCount",+ "columnName": "item_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastStatus",+ "columnName": "last_status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "lastError",+ "columnName": "last_error",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lastLoadedPage",+ "columnName": "last_loaded_page",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "totalPages",+ "columnName": "total_pages",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isComplete",+ "columnName": "is_complete",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "pageSize",+ "columnName": "page_size",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "provider_id",+ "category_id"+ ]+ },+ "indices": [+ {+ "name": "index_series_category_hydration_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_category_hydration_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "epg_sources",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `url` TEXT NOT NULL, `enabled` INTEGER NOT NULL, `last_refresh_at` INTEGER NOT NULL, `last_success_at` INTEGER NOT NULL, `last_error` TEXT, `priority` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, `etag` TEXT, `last_modified_header` TEXT)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "url",+ "columnName": "url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "enabled",+ "columnName": "enabled",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastRefreshAt",+ "columnName": "last_refresh_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastSuccessAt",+ "columnName": "last_success_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastError",+ "columnName": "last_error",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "priority",+ "columnName": "priority",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "etag",+ "columnName": "etag",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lastModifiedHeader",+ "columnName": "last_modified_header",+ "affinity": "TEXT"+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_epg_sources_url",+ "unique": true,+ "columnNames": [+ "url"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_epg_sources_url` ON `${TABLE_NAME}` (`url`)"+ }+ ]+ },+ {+ "tableName": "provider_epg_sources",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `epg_source_id` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `enabled` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`epg_source_id`) REFERENCES `epg_sources`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "epgSourceId",+ "columnName": "epg_source_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "priority",+ "columnName": "priority",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "enabled",+ "columnName": "enabled",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_provider_epg_sources_provider_id_epg_source_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "epg_source_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_provider_epg_sources_provider_id_epg_source_id` ON `${TABLE_NAME}` (`provider_id`, `epg_source_id`)"+ },+ {+ "name": "index_provider_epg_sources_epg_source_id",+ "unique": false,+ "columnNames": [+ "epg_source_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_provider_epg_sources_epg_source_id` ON `${TABLE_NAME}` (`epg_source_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ },+ {+ "table": "epg_sources",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "epg_source_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "epg_channels",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `epg_source_id` INTEGER NOT NULL, `xmltv_channel_id` TEXT NOT NULL, `display_name` TEXT NOT NULL, `normalized_name` TEXT NOT NULL, `icon_url` TEXT, FOREIGN KEY(`epg_source_id`) REFERENCES `epg_sources`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "epgSourceId",+ "columnName": "epg_source_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "xmltvChannelId",+ "columnName": "xmltv_channel_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "displayName",+ "columnName": "display_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "normalizedName",+ "columnName": "normalized_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "iconUrl",+ "columnName": "icon_url",+ "affinity": "TEXT"+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_epg_channels_epg_source_id_xmltv_channel_id",+ "unique": true,+ "columnNames": [+ "epg_source_id",+ "xmltv_channel_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_epg_channels_epg_source_id_xmltv_channel_id` ON `${TABLE_NAME}` (`epg_source_id`, `xmltv_channel_id`)"+ },+ {+ "name": "index_epg_channels_epg_source_id",+ "unique": false,+ "columnNames": [+ "epg_source_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_channels_epg_source_id` ON `${TABLE_NAME}` (`epg_source_id`)"+ },+ {+ "name": "index_epg_channels_normalized_name",+ "unique": false,+ "columnNames": [+ "normalized_name"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_channels_normalized_name` ON `${TABLE_NAME}` (`normalized_name`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "epg_sources",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "epg_source_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "epg_programmes",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `epg_source_id` INTEGER NOT NULL, `xmltv_channel_id` TEXT NOT NULL, `start_time` INTEGER NOT NULL, `end_time` INTEGER NOT NULL, `title` TEXT NOT NULL, `subtitle` TEXT, `description` TEXT NOT NULL, `category` TEXT, `lang` TEXT NOT NULL, `rating` TEXT, `image_url` TEXT, `episode_info` TEXT, FOREIGN KEY(`epg_source_id`) REFERENCES `epg_sources`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "epgSourceId",+ "columnName": "epg_source_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "xmltvChannelId",+ "columnName": "xmltv_channel_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "startTime",+ "columnName": "start_time",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "endTime",+ "columnName": "end_time",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "title",+ "columnName": "title",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "subtitle",+ "columnName": "subtitle",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "description",+ "columnName": "description",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "category",+ "columnName": "category",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lang",+ "columnName": "lang",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "rating",+ "columnName": "rating",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "imageUrl",+ "columnName": "image_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "episodeInfo",+ "columnName": "episode_info",+ "affinity": "TEXT"+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_epg_programmes_epg_source_id_xmltv_channel_id_start_time",+ "unique": false,+ "columnNames": [+ "epg_source_id",+ "xmltv_channel_id",+ "start_time"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_programmes_epg_source_id_xmltv_channel_id_start_time` ON `${TABLE_NAME}` (`epg_source_id`, `xmltv_channel_id`, `start_time`)"+ },+ {+ "name": "index_epg_programmes_epg_source_id_xmltv_channel_id_start_time_end_time",+ "unique": true,+ "columnNames": [+ "epg_source_id",+ "xmltv_channel_id",+ "start_time",+ "end_time"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_epg_programmes_epg_source_id_xmltv_channel_id_start_time_end_time` ON `${TABLE_NAME}` (`epg_source_id`, `xmltv_channel_id`, `start_time`, `end_time`)"+ },+ {+ "name": "index_epg_programmes_epg_source_id",+ "unique": false,+ "columnNames": [+ "epg_source_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_programmes_epg_source_id` ON `${TABLE_NAME}` (`epg_source_id`)"+ },+ {+ "name": "index_epg_programmes_start_time",+ "unique": false,+ "columnNames": [+ "start_time"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_programmes_start_time` ON `${TABLE_NAME}` (`start_time`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "epg_sources",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "epg_source_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "channel_epg_mappings",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_channel_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `source_type` TEXT NOT NULL, `epg_source_id` INTEGER, `xmltv_channel_id` TEXT, `match_type` TEXT, `confidence` REAL NOT NULL, `matched_at` INTEGER NOT NULL, `failed_attempts` INTEGER NOT NULL, `source` TEXT, `is_manual_override` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerChannelId",+ "columnName": "provider_channel_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "sourceType",+ "columnName": "source_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "epgSourceId",+ "columnName": "epg_source_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "xmltvChannelId",+ "columnName": "xmltv_channel_id",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "matchType",+ "columnName": "match_type",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "confidence",+ "columnName": "confidence",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "matchedAt",+ "columnName": "matched_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "failedAttempts",+ "columnName": "failed_attempts",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "source",+ "columnName": "source",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "isManualOverride",+ "columnName": "is_manual_override",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_channel_epg_mappings_provider_id_provider_channel_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "provider_channel_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_channel_epg_mappings_provider_id_provider_channel_id` ON `${TABLE_NAME}` (`provider_id`, `provider_channel_id`)"+ },+ {+ "name": "index_channel_epg_mappings_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channel_epg_mappings_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "combined_m3u_profiles",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `enabled` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "enabled",+ "columnName": "enabled",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ }+ },+ {+ "tableName": "combined_m3u_profile_members",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `profile_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `enabled` INTEGER NOT NULL, FOREIGN KEY(`profile_id`) REFERENCES `combined_m3u_profiles`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "profileId",+ "columnName": "profile_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "priority",+ "columnName": "priority",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "enabled",+ "columnName": "enabled",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_combined_m3u_profile_members_profile_id",+ "unique": false,+ "columnNames": [+ "profile_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_combined_m3u_profile_members_profile_id` ON `${TABLE_NAME}` (`profile_id`)"+ },+ {+ "name": "index_combined_m3u_profile_members_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_combined_m3u_profile_members_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_combined_m3u_profile_members_profile_id_provider_id",+ "unique": true,+ "columnNames": [+ "profile_id",+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_combined_m3u_profile_members_profile_id_provider_id` ON `${TABLE_NAME}` (`profile_id`, `provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "combined_m3u_profiles",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "profile_id"+ ],+ "referencedColumns": [+ "id"+ ]+ },+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "recording_schedules",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, `channel_name` TEXT NOT NULL, `stream_url` TEXT NOT NULL, `program_title` TEXT, `requested_start_ms` INTEGER NOT NULL, `requested_end_ms` INTEGER NOT NULL, `recurrence` TEXT NOT NULL, `recurring_rule_id` TEXT, `enabled` INTEGER NOT NULL, `is_manual` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelId",+ "columnName": "channel_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelName",+ "columnName": "channel_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "programTitle",+ "columnName": "program_title",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "requestedStartMs",+ "columnName": "requested_start_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "requestedEndMs",+ "columnName": "requested_end_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "recurrence",+ "columnName": "recurrence",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "recurringRuleId",+ "columnName": "recurring_rule_id",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "enabled",+ "columnName": "enabled",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isManual",+ "columnName": "is_manual",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "priority",+ "columnName": "priority",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_recording_schedules_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_schedules_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_recording_schedules_enabled_requested_start_ms",+ "unique": false,+ "columnNames": [+ "enabled",+ "requested_start_ms"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_schedules_enabled_requested_start_ms` ON `${TABLE_NAME}` (`enabled`, `requested_start_ms`)"+ },+ {+ "name": "index_recording_schedules_recurring_rule_id",+ "unique": false,+ "columnNames": [+ "recurring_rule_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_schedules_recurring_rule_id` ON `${TABLE_NAME}` (`recurring_rule_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "recording_runs",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `schedule_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, `channel_name` TEXT NOT NULL, `stream_url` TEXT NOT NULL, `program_title` TEXT, `scheduled_start_ms` INTEGER NOT NULL, `scheduled_end_ms` INTEGER NOT NULL, `recurrence` TEXT NOT NULL, `recurring_rule_id` TEXT, `status` TEXT NOT NULL, `source_type` TEXT NOT NULL, `resolved_url` TEXT, `headers_json` TEXT NOT NULL, `user_agent` TEXT, `expiration_time` INTEGER, `provider_label` TEXT, `output_uri` TEXT, `output_display_path` TEXT, `bytes_written` INTEGER NOT NULL, `average_throughput_bps` INTEGER NOT NULL, `retry_count` INTEGER NOT NULL, `last_progress_at_ms` INTEGER, `failure_category` TEXT NOT NULL, `failure_reason` TEXT, `terminal_at_ms` INTEGER, `started_at_ms` INTEGER, `ended_at_ms` INTEGER, `schedule_enabled` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `alarm_start_at_ms` INTEGER, `alarm_stop_at_ms` INTEGER, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`schedule_id`) REFERENCES `recording_schedules`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "scheduleId",+ "columnName": "schedule_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelId",+ "columnName": "channel_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelName",+ "columnName": "channel_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "programTitle",+ "columnName": "program_title",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "scheduledStartMs",+ "columnName": "scheduled_start_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "scheduledEndMs",+ "columnName": "scheduled_end_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "recurrence",+ "columnName": "recurrence",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "recurringRuleId",+ "columnName": "recurring_rule_id",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "status",+ "columnName": "status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "sourceType",+ "columnName": "source_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "resolvedUrl",+ "columnName": "resolved_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "headersJson",+ "columnName": "headers_json",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "userAgent",+ "columnName": "user_agent",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "expirationTime",+ "columnName": "expiration_time",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "providerLabel",+ "columnName": "provider_label",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "outputUri",+ "columnName": "output_uri",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "outputDisplayPath",+ "columnName": "output_display_path",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "bytesWritten",+ "columnName": "bytes_written",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "averageThroughputBytesPerSecond",+ "columnName": "average_throughput_bps",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "retryCount",+ "columnName": "retry_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastProgressAtMs",+ "columnName": "last_progress_at_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "failureCategory",+ "columnName": "failure_category",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "failureReason",+ "columnName": "failure_reason",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "terminalAtMs",+ "columnName": "terminal_at_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "startedAtMs",+ "columnName": "started_at_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "endedAtMs",+ "columnName": "ended_at_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "scheduleEnabled",+ "columnName": "schedule_enabled",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "priority",+ "columnName": "priority",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "alarmStartAtMs",+ "columnName": "alarm_start_at_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "alarmStopAtMs",+ "columnName": "alarm_stop_at_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_recording_runs_schedule_id",+ "unique": false,+ "columnNames": [+ "schedule_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_schedule_id` ON `${TABLE_NAME}` (`schedule_id`)"+ },+ {+ "name": "index_recording_runs_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_recording_runs_status_scheduled_start_ms",+ "unique": false,+ "columnNames": [+ "status",+ "scheduled_start_ms"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_status_scheduled_start_ms` ON `${TABLE_NAME}` (`status`, `scheduled_start_ms`)"+ },+ {+ "name": "index_recording_runs_alarm_start_at_ms",+ "unique": false,+ "columnNames": [+ "alarm_start_at_ms"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_alarm_start_at_ms` ON `${TABLE_NAME}` (`alarm_start_at_ms`)"+ },+ {+ "name": "index_recording_runs_alarm_stop_at_ms",+ "unique": false,+ "columnNames": [+ "alarm_stop_at_ms"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_alarm_stop_at_ms` ON `${TABLE_NAME}` (`alarm_stop_at_ms`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "recording_schedules",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "schedule_id"+ ],+ "referencedColumns": [+ "id"+ ]+ },+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "program_reminders",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `channel_id` TEXT NOT NULL, `channel_name` TEXT NOT NULL, `program_title` TEXT NOT NULL, `program_start_time` INTEGER NOT NULL, `remind_at` INTEGER NOT NULL, `lead_time_minutes` INTEGER NOT NULL, `is_dismissed` INTEGER NOT NULL, `notified_at` INTEGER, `created_at` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelId",+ "columnName": "channel_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "channelName",+ "columnName": "channel_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "programTitle",+ "columnName": "program_title",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "programStartTime",+ "columnName": "program_start_time",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "remindAt",+ "columnName": "remind_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "leadTimeMinutes",+ "columnName": "lead_time_minutes",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isDismissed",+ "columnName": "is_dismissed",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "notifiedAt",+ "columnName": "notified_at",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_program_reminders_provider_id_remind_at",+ "unique": false,+ "columnNames": [+ "provider_id",+ "remind_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_program_reminders_provider_id_remind_at` ON `${TABLE_NAME}` (`provider_id`, `remind_at`)"+ },+ {+ "name": "index_program_reminders_is_dismissed_notified_at_remind_at",+ "unique": false,+ "columnNames": [+ "is_dismissed",+ "notified_at",+ "remind_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_program_reminders_is_dismissed_notified_at_remind_at` ON `${TABLE_NAME}` (`is_dismissed`, `notified_at`, `remind_at`)"+ },+ {+ "name": "index_program_reminders_provider_id_channel_id_program_start_time",+ "unique": false,+ "columnNames": [+ "provider_id",+ "channel_id",+ "program_start_time"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_program_reminders_provider_id_channel_id_program_start_time` ON `${TABLE_NAME}` (`provider_id`, `channel_id`, `program_start_time`)"+ },+ {+ "name": "index_program_reminders_provider_id_channel_id_program_title_program_start_time",+ "unique": true,+ "columnNames": [+ "provider_id",+ "channel_id",+ "program_title",+ "program_start_time"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_program_reminders_provider_id_channel_id_program_title_program_start_time` ON `${TABLE_NAME}` (`provider_id`, `channel_id`, `program_title`, `program_start_time`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "recording_storage",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER NOT NULL, `tree_uri` TEXT, `display_name` TEXT, `output_directory` TEXT, `available_bytes` INTEGER, `is_writable` INTEGER NOT NULL, `file_name_pattern` TEXT NOT NULL, `retention_days` INTEGER, `max_simultaneous_recordings` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, PRIMARY KEY(`id`))",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "treeUri",+ "columnName": "tree_uri",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "displayName",+ "columnName": "display_name",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "outputDirectory",+ "columnName": "output_directory",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "availableBytes",+ "columnName": "available_bytes",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "isWritable",+ "columnName": "is_writable",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "fileNamePattern",+ "columnName": "file_name_pattern",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "retentionDays",+ "columnName": "retention_days",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "maxSimultaneousRecordings",+ "columnName": "max_simultaneous_recordings",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "id"+ ]+ }+ },+ {+ "tableName": "playback_compatibility_records",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `device_fingerprint` TEXT NOT NULL, `device_model` TEXT NOT NULL, `android_sdk` INTEGER NOT NULL, `stream_type` TEXT NOT NULL, `video_mime_type` TEXT NOT NULL, `resolution_bucket` TEXT NOT NULL, `decoder_name` TEXT NOT NULL, `surface_type` TEXT NOT NULL, `failure_type` TEXT NOT NULL, `last_failed_at` INTEGER NOT NULL, `last_succeeded_at` INTEGER NOT NULL, `failure_count` INTEGER NOT NULL, `success_count` INTEGER NOT NULL)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "deviceFingerprint",+ "columnName": "device_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "deviceModel",+ "columnName": "device_model",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "androidSdk",+ "columnName": "android_sdk",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "streamType",+ "columnName": "stream_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "videoMimeType",+ "columnName": "video_mime_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "resolutionBucket",+ "columnName": "resolution_bucket",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "decoderName",+ "columnName": "decoder_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "surfaceType",+ "columnName": "surface_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "failureType",+ "columnName": "failure_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "lastFailedAt",+ "columnName": "last_failed_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastSucceededAt",+ "columnName": "last_succeeded_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "failureCount",+ "columnName": "failure_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "successCount",+ "columnName": "success_count",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_playback_compatibility_records_device_fingerprint_stream_type_video_mime_type_resolution_bucket_decoder_name_surface_type",+ "unique": true,+ "columnNames": [+ "device_fingerprint",+ "stream_type",+ "video_mime_type",+ "resolution_bucket",+ "decoder_name",+ "surface_type"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_playback_compatibility_records_device_fingerprint_stream_type_video_mime_type_resolution_bucket_decoder_name_surface_type` ON `${TABLE_NAME}` (`device_fingerprint`, `stream_type`, `video_mime_type`, `resolution_bucket`, `decoder_name`, `surface_type`)"+ },+ {+ "name": "index_playback_compatibility_records_device_fingerprint_stream_type_video_mime_type_resolution_bucket",+ "unique": false,+ "columnNames": [+ "device_fingerprint",+ "stream_type",+ "video_mime_type",+ "resolution_bucket"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_compatibility_records_device_fingerprint_stream_type_video_mime_type_resolution_bucket` ON `${TABLE_NAME}` (`device_fingerprint`, `stream_type`, `video_mime_type`, `resolution_bucket`)"+ },+ {+ "name": "index_playback_compatibility_records_last_failed_at",+ "unique": false,+ "columnNames": [+ "last_failed_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_compatibility_records_last_failed_at` ON `${TABLE_NAME}` (`last_failed_at`)"+ },+ {+ "name": "index_playback_compatibility_records_last_succeeded_at",+ "unique": false,+ "columnNames": [+ "last_succeeded_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_compatibility_records_last_succeeded_at` ON `${TABLE_NAME}` (`last_succeeded_at`)"+ }+ ]+ }+ ],+ "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, '42b2a09f506226f1fb519e90fc827010')"+ ]+ }+}\ No newline at end of filediff --git a/data/src/androidTest/java/com/streamvault/data/local/BrowseQueryPlanTest.kt b/data/src/androidTest/java/com/streamvault/data/local/BrowseQueryPlanTest.ktnew file mode 100644index 00000000..07ff0898--- /dev/null+++ b/data/src/androidTest/java/com/streamvault/data/local/BrowseQueryPlanTest.kt@@ -0,0 +1,150 @@+package com.streamvault.data.local++import android.content.Context+import androidx.room.Room+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.google.common.truth.Truth.assertThat+import com.streamvault.data.local.entity.MovieEntity+import com.streamvault.data.local.entity.PlaybackHistoryEntity+import com.streamvault.data.local.entity.ProviderEntity+import com.streamvault.data.local.entity.SeriesEntity+import com.streamvault.domain.model.ContentType+import com.streamvault.domain.model.ProviderType+import kotlinx.coroutines.test.runTest+import org.junit.After+import org.junit.Before+import org.junit.Test+import org.junit.runner.RunWith+import java.io.IOException++@RunWith(AndroidJUnit4::class)+class BrowseQueryPlanTest {+ private lateinit var db: StreamVaultDatabase++ @Before+ fun createDb() {+ val context = ApplicationProvider.getApplicationContext<Context>()+ db = Room.inMemoryDatabaseBuilder(context, StreamVaultDatabase::class.java).build()+ }++ @After+ @Throws(IOException::class)+ fun closeDb() {+ db.close()+ }++ @Test+ fun explainQueryPlan_usesMovieBrowseAndPlaybackHistoryIndexes() = runTest {+ seedProviderCatalog()++ val browsePlan = explainQueryPlan(+ "SELECT * FROM movies WHERE provider_id = 1 ORDER BY name ASC, id ASC LIMIT 25"+ )+ assertUsesIndex(browsePlan, "index_movies_provider_id_name_id")+ assertNoTempSort(browsePlan)++ val inProgressPlan = explainQueryPlan(+ """+ SELECT movies.* FROM movies+ WHERE movies.provider_id = 1+ AND EXISTS (+ SELECT 1 FROM playback_history+ WHERE playback_history.provider_id = movies.provider_id+ AND playback_history.content_type = 'MOVIE'+ AND playback_history.content_id = movies.id+ AND playback_history.resume_position_ms > 0+ AND (+ playback_history.total_duration_ms <= 0+ OR playback_history.resume_position_ms < CAST(playback_history.total_duration_ms * 0.95 AS INTEGER)+ )+ )+ ORDER BY movies.name ASC+ LIMIT 25 OFFSET 0+ """.trimIndent()+ )+ assertUsesIndex(inProgressPlan, "index_movies_provider_id_name_id")+ assertUsesIndex(inProgressPlan, "index_playback_history_provider_id_content_type_content_id")+ assertNoTempSort(inProgressPlan)+ }++ @Test+ fun explainQueryPlan_usesSeriesLastModifiedBrowseIndex() = runTest {+ seedProviderCatalog()++ val plan = explainQueryPlan(+ "SELECT * FROM series WHERE provider_id = 1 ORDER BY last_modified DESC, name ASC, id ASC LIMIT 25"+ )++ assertUsesIndex(plan, "index_series_provider_id_last_modified_name_id")+ assertNoTempSort(plan)+ }++ private suspend fun seedProviderCatalog() {+ db.providerDao().insert(+ ProviderEntity(+ id = 1L,+ name = "Provider",+ type = ProviderType.XTREAM_CODES,+ serverUrl = "https://provider.example.com"+ )+ )+ db.movieDao().insertAll(+ List(40) { index ->+ MovieEntity(+ id = index + 1L,+ streamId = 10_000L + index,+ name = "Movie %02d".format(index),+ streamUrl = "https://provider.example.com/movies/$index.mp4",+ providerId = 1L,+ rating = (index % 5).toFloat(),+ addedAt = 1_000L + index,+ releaseDate = "2026-01-%02d".format((index % 28) + 1)+ )+ }+ )+ db.seriesDao().insertAll(+ List(40) { index ->+ SeriesEntity(+ id = index + 1L,+ seriesId = 20_000L + index,+ name = "Series %02d".format(index),+ providerId = 1L,+ rating = (index % 5).toFloat(),+ lastModified = 2_000L + index+ )+ }+ )+ db.playbackHistoryDao().insertOrUpdate(+ PlaybackHistoryEntity(+ contentId = 1L,+ contentType = ContentType.MOVIE,+ providerId = 1L,+ title = "Movie 00",+ streamUrl = "https://provider.example.com/movies/0.mp4",+ resumePositionMs = 60_000L,+ totalDurationMs = 120_000L,+ lastWatchedAt = 5_000L,+ watchCount = 1+ )+ )+ }++ private fun explainQueryPlan(sql: String): List<String> {+ val plan = mutableListOf<String>()+ db.openHelper.writableDatabase.query("EXPLAIN QUERY PLAN $sql").use { cursor ->+ while (cursor.moveToNext()) {+ plan += cursor.getString(3)+ }+ }+ return plan+ }++ private fun assertUsesIndex(plan: List<String>, indexName: String) {+ assertThat(plan.any { it.contains(indexName) }).isTrue()+ }++ private fun assertNoTempSort(plan: List<String>) {+ assertThat(plan.none { it.contains("USE TEMP B-TREE FOR ORDER BY") }).isTrue()+ }+}\ No newline at end of filediff --git a/data/src/androidTest/java/com/streamvault/data/local/CatalogSyncDaoSeriesStageTest.kt b/data/src/androidTest/java/com/streamvault/data/local/CatalogSyncDaoSeriesStageTest.ktnew file mode 100644index 00000000..52957b56--- /dev/null+++ b/data/src/androidTest/java/com/streamvault/data/local/CatalogSyncDaoSeriesStageTest.kt@@ -0,0 +1,112 @@+package com.streamvault.data.local++import android.content.Context+import androidx.room.Room+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.google.common.truth.Truth.assertThat+import com.streamvault.data.local.dao.CatalogSyncDao+import com.streamvault.data.local.dao.ProviderDao+import com.streamvault.data.local.dao.SeriesDao+import com.streamvault.data.local.entity.ProviderEntity+import com.streamvault.data.local.entity.SeriesEntity+import com.streamvault.data.local.entity.SeriesImportStageEntity+import com.streamvault.domain.model.ProviderType+import kotlinx.coroutines.test.runTest+import org.junit.After+import org.junit.Before+import org.junit.Test+import org.junit.runner.RunWith+import java.io.IOException++@RunWith(AndroidJUnit4::class)+class CatalogSyncDaoSeriesStageTest {+ private lateinit var db: StreamVaultDatabase+ private lateinit var providerDao: ProviderDao+ private lateinit var seriesDao: SeriesDao+ private lateinit var catalogSyncDao: CatalogSyncDao++ @Before+ fun createDb() {+ val context = ApplicationProvider.getApplicationContext<Context>()+ db = Room.inMemoryDatabaseBuilder(context, StreamVaultDatabase::class.java).build()+ providerDao = db.providerDao()+ seriesDao = db.seriesDao()+ catalogSyncDao = db.catalogSyncDao()+ }++ @After+ @Throws(IOException::class)+ fun closeDb() {+ db.close()+ }++ @Test+ fun insertMissingSeriesFromStage_preservesProviderSeriesId() = runTest {+ providerDao.insert(provider(1L))+ catalogSyncDao.insertSeriesStages(+ listOf(+ SeriesImportStageEntity(+ sessionId = 10L,+ providerId = 1L,+ seriesId = 256103980L,+ providerSeriesId = "55000:55000",+ providerSeriesKey = "55000:55000",+ name = "Composite Series",+ syncFingerprint = "fp-new"+ )+ )+ )++ catalogSyncDao.insertMissingSeriesFromStage(providerId = 1L, sessionId = 10L)++ val inserted = seriesDao.getByProviderSeriesId(1L, "55000:55000")++ assertThat(inserted).isNotNull()+ assertThat(inserted?.providerSeriesId).isEqualTo("55000:55000")+ assertThat(inserted?.seriesId).isEqualTo(256103980L)+ }++ @Test+ fun updateChangedSeriesFromStage_backfillsProviderSeriesIdForExistingSeries() = runTest {+ providerDao.insert(provider(1L))+ seriesDao.insertAll(+ listOf(+ SeriesEntity(+ seriesId = 256103980L,+ providerSeriesId = null,+ name = "Composite Series",+ providerId = 1L,+ syncFingerprint = "old-fingerprint"+ )+ )+ )+ catalogSyncDao.insertSeriesStages(+ listOf(+ SeriesImportStageEntity(+ sessionId = 11L,+ providerId = 1L,+ seriesId = 256103980L,+ providerSeriesId = "55000:55000",+ providerSeriesKey = "55000:55000",+ name = "Composite Series",+ syncFingerprint = "new-fingerprint"+ )+ )+ )++ catalogSyncDao.updateChangedSeriesFromStage(providerId = 1L, sessionId = 11L)++ val updated = seriesDao.getBySeriesId(1L, 256103980L)++ assertThat(updated?.providerSeriesId).isEqualTo("55000:55000")+ assertThat(updated?.syncFingerprint).isEqualTo("new-fingerprint")+ }++ private fun provider(id: Long) = ProviderEntity(+ id = id,+ name = "Provider $id",+ type = ProviderType.STALKER_PORTAL,+ serverUrl = "https://provider$id.example.com"+ )+}\ No newline at end of filediff --git a/data/src/androidTest/java/com/streamvault/data/local/EpisodeDaoTest.kt b/data/src/androidTest/java/com/streamvault/data/local/EpisodeDaoTest.ktindex 7d347f6f..f840f8b3 100644--- a/data/src/androidTest/java/com/streamvault/data/local/EpisodeDaoTest.kt+++ b/data/src/androidTest/java/com/streamvault/data/local/EpisodeDaoTest.kt@@ -72,4 +72,67 @@ class EpisodeDaoTest {assertThat(episode?.watchProgress).isEqualTo(18_000L)assertThat(episode?.lastWatchedAt).isEqualTo(27_000L)}++ @Test+ fun syncWatchProgressFromHistoryByProvider_updatesMatchingEpisodesAndClearsStaleRows() = runTest {+ episodeDao.insertAll(+ listOf(+ EpisodeEntity(+ id = 11L,+ episodeId = 201L,+ title = "Episode 1",+ episodeNumber = 1,+ seasonNumber = 1,+ seriesId = 91L,+ providerId = 5L,+ watchProgress = 0L,+ lastWatchedAt = 0L+ ),+ EpisodeEntity(+ id = 12L,+ episodeId = 202L,+ title = "Episode 2",+ episodeNumber = 2,+ seasonNumber = 1,+ seriesId = 91L,+ providerId = 5L,+ watchProgress = 13_000L,+ lastWatchedAt = 14_000L+ ),+ EpisodeEntity(+ id = 21L,+ episodeId = 301L,+ title = "Other Provider Episode",+ episodeNumber = 1,+ seasonNumber = 1,+ seriesId = 101L,+ providerId = 6L,+ watchProgress = 3_000L,+ lastWatchedAt = 4_000L+ )+ )+ )+ historyDao.insertOrUpdate(+ PlaybackHistoryEntity(+ contentId = 11L,+ contentType = ContentType.SERIES_EPISODE,+ providerId = 5L,+ resumePositionMs = 18_000L,+ lastWatchedAt = 27_000L+ )+ )++ episodeDao.syncWatchProgressFromHistoryByProvider(5L)++ val watchedEpisode = episodeDao.getById(11L)+ val staleEpisode = episodeDao.getById(12L)+ val otherProviderEpisode = episodeDao.getById(21L)++ assertThat(watchedEpisode?.watchProgress).isEqualTo(18_000L)+ assertThat(watchedEpisode?.lastWatchedAt).isEqualTo(27_000L)+ assertThat(staleEpisode?.watchProgress).isEqualTo(0L)+ assertThat(staleEpisode?.lastWatchedAt).isEqualTo(0L)+ assertThat(otherProviderEpisode?.watchProgress).isEqualTo(3_000L)+ assertThat(otherProviderEpisode?.lastWatchedAt).isEqualTo(4_000L)+ }}\ No newline at end of filediff --git a/data/src/androidTest/java/com/streamvault/data/local/FavoriteDaoTest.kt b/data/src/androidTest/java/com/streamvault/data/local/FavoriteDaoTest.ktnew file mode 100644index 00000000..e7b766ad--- /dev/null+++ b/data/src/androidTest/java/com/streamvault/data/local/FavoriteDaoTest.kt@@ -0,0 +1,195 @@+package com.streamvault.data.local++import android.content.Context+import androidx.room.Room+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.google.common.truth.Truth.assertThat+import com.streamvault.data.local.dao.FavoriteDao+import com.streamvault.data.local.dao.ProviderDao+import com.streamvault.data.local.dao.VirtualGroupDao+import com.streamvault.data.local.entity.FavoriteEntity+import com.streamvault.data.local.entity.ProviderEntity+import com.streamvault.data.local.entity.VirtualGroupEntity+import com.streamvault.domain.model.ContentType+import com.streamvault.domain.model.ProviderType+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.test.runTest+import org.junit.After+import org.junit.Before+import org.junit.Test+import org.junit.runner.RunWith+import java.io.IOException++@RunWith(AndroidJUnit4::class)+class FavoriteDaoTest {+ private lateinit var db: StreamVaultDatabase+ private lateinit var providerDao: ProviderDao+ private lateinit var favoriteDao: FavoriteDao+ private lateinit var virtualGroupDao: VirtualGroupDao++ @Before+ fun createDb() {+ val context = ApplicationProvider.getApplicationContext<Context>()+ db = Room.inMemoryDatabaseBuilder(context, StreamVaultDatabase::class.java).build()+ providerDao = db.providerDao()+ favoriteDao = db.favoriteDao()+ virtualGroupDao = db.virtualGroupDao()+ }++ @After+ @Throws(IOException::class)+ fun closeDb() {+ db.close()+ }++ @Test+ fun getByGroup_hidesFavoritesWhoseProviderOrTypeNoLongerMatchesTheGroup() = runTest {+ providerDao.insert(provider(id = 1L, name = "Live Provider"))+ providerDao.insert(provider(id = 2L, name = "Movie Provider"))++ val liveGroupId = virtualGroupDao.insert(+ VirtualGroupEntity(+ providerId = 1L,+ name = "Live Group",+ contentType = ContentType.LIVE+ )+ )++ favoriteDao.insert(+ FavoriteEntity(+ providerId = 1L,+ contentId = 100L,+ contentType = ContentType.LIVE,+ position = 0,+ groupId = liveGroupId+ )+ )+ favoriteDao.insert(+ FavoriteEntity(+ providerId = 2L,+ contentId = 200L,+ contentType = ContentType.LIVE,+ position = 1,+ groupId = liveGroupId+ )+ )+ favoriteDao.insert(+ FavoriteEntity(+ providerId = 1L,+ contentId = 300L,+ contentType = ContentType.MOVIE,+ position = 2,+ groupId = liveGroupId+ )+ )++ val favorites = favoriteDao.getByGroup(liveGroupId).first()++ assertThat(favorites.map(FavoriteEntity::contentId)).containsExactly(100L)+ }++ @Test+ fun insert_replacesDuplicateGlobalFavoriteInsteadOfCreatingTwoRows() = runTest {+ providerDao.insert(provider(id = 1L, name = "Provider"))++ favoriteDao.insert(+ FavoriteEntity(+ providerId = 1L,+ contentId = 100L,+ contentType = ContentType.MOVIE,+ position = 0,+ groupId = null,+ addedAt = 10L+ )+ )+ favoriteDao.insert(+ FavoriteEntity(+ providerId = 1L,+ contentId = 100L,+ contentType = ContentType.MOVIE,+ position = 99,+ groupId = null,+ addedAt = 20L+ )+ )++ val favorites = favoriteDao.getGlobalByType(1L, ContentType.MOVIE.name).first()++ assertThat(favorites).hasSize(1)+ assertThat(favorites.single().contentId).isEqualTo(100L)+ }++ @Test+ fun insert_rejectsFavoriteGroupOwnedByAnotherProvider() = runTest {+ providerDao.insert(provider(id = 1L, name = "Provider"))+ providerDao.insert(provider(id = 2L, name = "Other Provider"))++ val foreignGroupId = virtualGroupDao.insert(+ VirtualGroupEntity(+ providerId = 2L,+ name = "Foreign Group",+ contentType = ContentType.LIVE+ )+ )++ val failure = try {+ favoriteDao.insert(+ FavoriteEntity(+ providerId = 1L,+ contentId = 100L,+ contentType = ContentType.LIVE,+ position = 0,+ groupId = foreignGroupId+ )+ )+ null+ } catch (error: IllegalArgumentException) {+ error+ }++ assertThat(failure).isNotNull()+ assertThat(failure!!.message).contains("belongs to provider 2, not 1")+ assertThat(favoriteDao.getAllByType(1L, ContentType.LIVE.name).first()).isEmpty()+ }++ @Test+ fun updateGroup_rejectsFavoriteGroupWithWrongContentType() = runTest {+ providerDao.insert(provider(id = 1L, name = "Provider"))+ val movieGroupId = virtualGroupDao.insert(+ VirtualGroupEntity(+ providerId = 1L,+ name = "Movie Group",+ contentType = ContentType.MOVIE+ )+ )+ favoriteDao.insert(+ FavoriteEntity(+ id = 5L,+ providerId = 1L,+ contentId = 100L,+ contentType = ContentType.LIVE,+ position = 0,+ groupId = null+ )+ )++ val failure = try {+ favoriteDao.updateGroup(5L, movieGroupId)+ null+ } catch (error: IllegalArgumentException) {+ error+ }++ assertThat(failure).isNotNull()+ assertThat(failure!!.message).contains("accepts MOVIE, not LIVE")+ assertThat(favoriteDao.get(1L, 100L, ContentType.LIVE.name, null)?.groupId).isNull()+ }++ private fun provider(id: Long, name: String) = ProviderEntity(+ id = id,+ name = name,+ type = ProviderType.M3U,+ serverUrl = "https://$name.example.com"+ )+}\ No newline at end of filediff --git a/data/src/androidTest/java/com/streamvault/data/local/MovieDaoTest.kt b/data/src/androidTest/java/com/streamvault/data/local/MovieDaoTest.ktindex aa3c5e5f..4150c109 100644--- a/data/src/androidTest/java/com/streamvault/data/local/MovieDaoTest.kt+++ b/data/src/androidTest/java/com/streamvault/data/local/MovieDaoTest.kt@@ -87,4 +87,56 @@ class MovieDaoTest {assertThat(movie?.watchProgress).isEqualTo(0L)assertThat(movie?.lastWatchedAt).isEqualTo(0L)}++ @Test+ fun syncWatchProgressFromHistoryByProvider_updatesMatchingMoviesAndClearsStaleRows() = runTest {+ movieDao.insertAll(+ listOf(+ MovieEntity(+ id = 7L,+ name = "Watched Movie",+ providerId = 3L,+ watchProgress = 0L,+ lastWatchedAt = 0L+ ),+ MovieEntity(+ id = 8L,+ name = "Stale Movie",+ providerId = 3L,+ watchProgress = 9_000L,+ lastWatchedAt = 12_000L+ ),+ MovieEntity(+ id = 9L,+ name = "Other Provider",+ providerId = 4L,+ watchProgress = 4_000L,+ lastWatchedAt = 5_000L+ )+ )+ )+ historyDao.insertOrUpdate(+ PlaybackHistoryEntity(+ contentId = 7L,+ contentType = ContentType.MOVIE,+ providerId = 3L,+ resumePositionMs = 18_000L,+ lastWatchedAt = 27_000L,+ watchCount = 2+ )+ )++ movieDao.syncWatchProgressFromHistoryByProvider(3L)++ val watchedMovie = movieDao.getById(7L)+ val staleMovie = movieDao.getById(8L)+ val otherProviderMovie = movieDao.getById(9L)++ assertThat(watchedMovie?.watchProgress).isEqualTo(18_000L)+ assertThat(watchedMovie?.lastWatchedAt).isEqualTo(27_000L)+ assertThat(staleMovie?.watchProgress).isEqualTo(0L)+ assertThat(staleMovie?.lastWatchedAt).isEqualTo(0L)+ assertThat(otherProviderMovie?.watchProgress).isEqualTo(4_000L)+ assertThat(otherProviderMovie?.lastWatchedAt).isEqualTo(5_000L)+ }}diff --git a/data/src/androidTest/java/com/streamvault/data/local/ProgramDaoTest.kt b/data/src/androidTest/java/com/streamvault/data/local/ProgramDaoTest.ktindex 5a4b66af..be15fcba 100644--- a/data/src/androidTest/java/com/streamvault/data/local/ProgramDaoTest.kt+++ b/data/src/androidTest/java/com/streamvault/data/local/ProgramDaoTest.kt@@ -53,6 +53,43 @@ class ProgramDaoTest {assertThat(byChannel[0].title).isEqualTo("Test Program")}+ @Test+ fun browseQueriesPreserveStoredProgramMetadata() = runTest {+ val program = ProgramEntity(+ providerId = 1L,+ channelId = "channel1",+ title = "Metadata Program",+ description = "Sports coverage",+ startTime = 1_000L,+ endTime = 2_000L,+ lang = "en",+ rating = "PG",+ imageUrl = "https://example.com/poster.png",+ genre = "Sports",+ category = "Highlights",+ hasArchive = true+ )+ programDao.insertAll(listOf(program))++ val byChannel = programDao.getForChannel(1L, "channel1", 0L, 3_000L).first().single()+ val search = programDao.searchPrograms(1L, "%Sports%", 0L, 3_000L, null, 10).first().single()+ val nowPlaying = programDao.getNowPlaying(1L, "channel1", 1_500L).first()++ assertThat(byChannel.rating).isEqualTo("PG")+ assertThat(byChannel.imageUrl).isEqualTo("https://example.com/poster.png")+ assertThat(byChannel.genre).isEqualTo("Sports")+ assertThat(byChannel.category).isEqualTo("Highlights")+ assertThat(search.rating).isEqualTo("PG")+ assertThat(search.imageUrl).isEqualTo("https://example.com/poster.png")+ assertThat(search.genre).isEqualTo("Sports")+ assertThat(search.category).isEqualTo("Highlights")+ assertThat(nowPlaying).isNotNull()+ assertThat(nowPlaying?.rating).isEqualTo("PG")+ assertThat(nowPlaying?.imageUrl).isEqualTo("https://example.com/poster.png")+ assertThat(nowPlaying?.genre).isEqualTo("Sports")+ assertThat(nowPlaying?.category).isEqualTo("Highlights")+ }+@Testfun deleteOldPrograms() = runTest {val program1 = ProgramEntity(diff --git a/data/src/androidTest/java/com/streamvault/data/local/ProviderDaoTest.kt b/data/src/androidTest/java/com/streamvault/data/local/ProviderDaoTest.ktnew file mode 100644index 00000000..a715c803--- /dev/null+++ b/data/src/androidTest/java/com/streamvault/data/local/ProviderDaoTest.kt@@ -0,0 +1,79 @@+package com.streamvault.data.local++import android.content.Context+import androidx.room.Room+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.google.common.truth.Truth.assertThat+import com.streamvault.data.local.dao.ProviderDao+import com.streamvault.data.local.entity.ProviderEntity+import com.streamvault.domain.model.ProviderType+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.test.runTest+import org.junit.After+import org.junit.Before+import org.junit.Test+import org.junit.runner.RunWith+import java.io.IOException++@RunWith(AndroidJUnit4::class)+class ProviderDaoTest {+ private lateinit var db: StreamVaultDatabase+ private lateinit var providerDao: ProviderDao++ @Before+ fun createDb() {+ val context = ApplicationProvider.getApplicationContext<Context>()+ db = Room.inMemoryDatabaseBuilder(context, StreamVaultDatabase::class.java).build()+ providerDao = db.providerDao()+ }++ @After+ @Throws(IOException::class)+ fun closeDb() {+ db.close()+ }++ @Test+ fun setActive_keepsExactlyOneActiveProviderAcrossRepeatedSwitches() = runTest {+ providerDao.insert(provider(id = 1L, name = "One", isActive = true))+ providerDao.insert(provider(id = 2L, name = "Two", isActive = false))+ providerDao.insert(provider(id = 3L, name = "Three", isActive = true))++ providerDao.setActive(2L)++ var providers = providerDao.getAllSync()+ assertThat(providers.filter(ProviderEntity::isActive).map(ProviderEntity::id)).containsExactly(2L)+ assertThat(providerDao.getActive().first()?.id).isEqualTo(2L)++ providerDao.setActive(3L)++ providers = providerDao.getAllSync()+ assertThat(providers.filter(ProviderEntity::isActive).map(ProviderEntity::id)).containsExactly(3L)+ assertThat(providerDao.getActive().first()?.id).isEqualTo(3L)+ }++ @Test+ fun insertAndUpdate_normalizeActiveProviderUniqueness() = runTest {+ providerDao.insert(provider(id = 1L, name = "One", isActive = true))+ providerDao.insert(provider(id = 2L, name = "Two", isActive = true))++ var providers = providerDao.getAllSync()+ assertThat(providers.filter(ProviderEntity::isActive).map(ProviderEntity::id)).containsExactly(2L)++ providerDao.update(provider(id = 1L, name = "One", isActive = true))++ providers = providerDao.getAllSync()+ assertThat(providers.filter(ProviderEntity::isActive).map(ProviderEntity::id)).containsExactly(1L)+ assertThat(providerDao.getActive().first()?.id).isEqualTo(1L)+ }++ private fun provider(id: Long, name: String, isActive: Boolean) = ProviderEntity(+ id = id,+ name = name,+ type = ProviderType.M3U,+ serverUrl = "https://example.com/$id.m3u",+ m3uUrl = "https://example.com/$id.m3u",+ isActive = isActive+ )+}\ No newline at end of filediff --git a/data/src/androidTest/java/com/streamvault/data/local/StreamVaultDatabaseMigrationTest.kt b/data/src/androidTest/java/com/streamvault/data/local/StreamVaultDatabaseMigrationTest.ktindex 85d85b4e..cb31d21e 100644--- a/data/src/androidTest/java/com/streamvault/data/local/StreamVaultDatabaseMigrationTest.kt+++ b/data/src/androidTest/java/com/streamvault/data/local/StreamVaultDatabaseMigrationTest.kt@@ -392,6 +392,181 @@ class StreamVaultDatabaseMigrationTest {migratedDb.close()}+ @Test+ fun migrate44To45_dedupesGlobalFavoritesAndAddsNullSafeUniqueKey() {+ migrationTestHelper.createDatabase("streamvault-44-45-test", 44).apply {+ execSQL(+ """+ INSERT INTO providers (+ id, name, type, server_url, username, password, m3u_url, epg_url,+ is_active, max_connections, allowed_output_formats_json, epg_sync_mode,+ xtream_fast_sync_enabled, m3u_vod_classification_enabled, status,+ last_synced_at, created_at+ ) VALUES (1, 'Provider', 'M3U', 'https://provider.example.com', '', '', '', '', 1, 1, '[]', 'UPFRONT', 0, 0, 'ACTIVE', 0, 0)+ """.trimIndent()+ )+ execSQL(+ """+ INSERT INTO favorites (id, provider_id, content_id, content_type, position, group_id, added_at)+ VALUES (1, 1, 10, 'MOVIE', 400, NULL, 200)+ """.trimIndent()+ )+ execSQL(+ """+ INSERT INTO favorites (id, provider_id, content_id, content_type, position, group_id, added_at)+ VALUES (2, 1, 10, 'MOVIE', 100, NULL, 100)+ """.trimIndent()+ )+ close()+ }++ val migratedDb = migrationTestHelper.runMigrationsAndValidate(+ "streamvault-44-45-test",+ 45,+ true,+ StreamVaultDatabase.MIGRATION_44_45+ )++ assertEquals(1, countRows(migratedDb, "SELECT COUNT(*) FROM favorites WHERE provider_id = 1 AND content_id = 10 AND content_type = 'MOVIE' AND group_id IS NULL"))+ assertEquals(100, countRows(migratedDb, "SELECT position FROM favorites WHERE provider_id = 1 AND content_id = 10 AND content_type = 'MOVIE' AND group_id IS NULL"))+ assertEquals(100, countRows(migratedDb, "SELECT added_at FROM favorites WHERE provider_id = 1 AND content_id = 10 AND content_type = 'MOVIE' AND group_id IS NULL"))+ assertEquals(0, countRows(migratedDb, "SELECT group_key FROM favorites WHERE provider_id = 1 AND content_id = 10 AND content_type = 'MOVIE' AND group_id IS NULL"))+ assertEquals(+ 1,+ countRows(+ migratedDb,+ "SELECT COUNT(*) FROM sqlite_master WHERE type = 'index' AND name = 'index_favorites_provider_id_content_id_content_type_group_key'"+ )+ )++ migratedDb.close()+ }++ @Test+ fun migrate45To46_rebuildsSeriesStageWithProviderSeriesKey() {+ migrationTestHelper.createDatabase("streamvault-45-46-test", 45).apply {+ execSQL(+ """+ INSERT INTO providers (+ id, name, type, server_url, username, password, m3u_url, epg_url,+ is_active, max_connections, allowed_output_formats_json, epg_sync_mode,+ xtream_fast_sync_enabled, m3u_vod_classification_enabled, status,+ last_synced_at, created_at+ ) VALUES (1, 'Provider', 'STALKER_PORTAL', 'https://provider.example.com', '', '', '', '', 1, 1, '[]', 'UPFRONT', 0, 0, 'ACTIVE', 0, 0)+ """.trimIndent()+ )+ execSQL(+ """+ INSERT INTO series_import_stage (+ session_id, provider_id, 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,+ is_adult, sync_fingerprint+ ) VALUES (10, 1, 256103980, 'Series', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL, 0, 0, 'fp')+ """.trimIndent()+ )+ close()+ }++ val migratedDb = migrationTestHelper.runMigrationsAndValidate(+ "streamvault-45-46-test",+ 46,+ true,+ StreamVaultDatabase.MIGRATION_45_46+ )++ assertEquals(1, countRows(migratedDb, "SELECT COUNT(*) FROM pragma_table_info('series_import_stage') WHERE name = 'provider_series_id'"))+ assertEquals(1, countRows(migratedDb, "SELECT COUNT(*) FROM pragma_table_info('series_import_stage') WHERE name = 'provider_series_key'"))+ assertEquals(256103980, countRows(migratedDb, "SELECT CAST(provider_series_key AS INTEGER) FROM series_import_stage WHERE session_id = 10 AND provider_id = 1"))++ migratedDb.close()+ }++ @Test+ fun migrate46To47_createsBrowseQueryIndexes() {+ migrationTestHelper.createDatabase("streamvault-46-47-test", 46).close()++ val migratedDb = migrationTestHelper.runMigrationsAndValidate(+ "streamvault-46-47-test",+ 47,+ true,+ StreamVaultDatabase.MIGRATION_46_47+ )++ assertEquals(+ 1,+ countRows(+ migratedDb,+ "SELECT COUNT(*) FROM sqlite_master WHERE type = 'index' AND name = 'index_movies_provider_id_name_id'"+ )+ )+ assertEquals(+ 1,+ countRows(+ migratedDb,+ "SELECT COUNT(*) FROM sqlite_master WHERE type = 'index' AND name = 'index_movies_provider_id_category_id_name_id'"+ )+ )+ assertEquals(+ 1,+ countRows(+ migratedDb,+ "SELECT COUNT(*) FROM sqlite_master WHERE type = 'index' AND name = 'index_movies_provider_id_rating_name_id'"+ )+ )+ assertEquals(+ 1,+ countRows(+ migratedDb,+ "SELECT COUNT(*) FROM sqlite_master WHERE type = 'index' AND name = 'index_movies_provider_id_added_at_release_date_name_id'"+ )+ )+ assertEquals(+ 1,+ countRows(+ migratedDb,+ "SELECT COUNT(*) FROM sqlite_master WHERE type = 'index' AND name = 'index_series_provider_id_name_id'"+ )+ )+ assertEquals(+ 1,+ countRows(+ migratedDb,+ "SELECT COUNT(*) FROM sqlite_master WHERE type = 'index' AND name = 'index_series_provider_id_category_id_name_id'"+ )+ )+ assertEquals(+ 1,+ countRows(+ migratedDb,+ "SELECT COUNT(*) FROM sqlite_master WHERE type = 'index' AND name = 'index_series_provider_id_rating_name_id'"+ )+ )+ assertEquals(+ 1,+ countRows(+ migratedDb,+ "SELECT COUNT(*) FROM sqlite_master WHERE type = 'index' AND name = 'index_series_provider_id_last_modified_name_id'"+ )+ )+ assertEquals(+ 1,+ countRows(+ migratedDb,+ "SELECT COUNT(*) FROM sqlite_master WHERE type = 'index' AND name = 'index_playback_history_provider_id_content_type_content_id'"+ )+ )+ assertEquals(+ 1,+ countRows(+ migratedDb,+ "SELECT COUNT(*) FROM sqlite_master WHERE type = 'index' AND name = 'index_playback_history_provider_id_content_type_last_watched_at'"+ )+ )++ migratedDb.close()+ }+@Testfun migrate34To35_createsSearchHistoryTable() {migrationTestHelper.createDatabase("streamvault-34-35-test", 34).close()diff --git a/data/src/main/AndroidManifest.xml b/data/src/main/AndroidManifest.xmlindex 5fb4d58c..e0a7c31b 100644--- a/data/src/main/AndroidManifest.xml+++ b/data/src/main/AndroidManifest.xml@@ -20,7 +20,6 @@android:exported="true"><intent-filter><action android:name="android.intent.action.BOOT_COMPLETED" />- <action android:name="android.intent.action.LOCKED_BOOT_COMPLETED" /><action android:name="android.intent.action.MY_PACKAGE_REPLACED" /></intent-filter></receiver>@@ -31,7 +30,6 @@android:exported="true"><intent-filter><action android:name="android.intent.action.BOOT_COMPLETED" />- <action android:name="android.intent.action.LOCKED_BOOT_COMPLETED" /><action android:name="android.intent.action.MY_PACKAGE_REPLACED" /></intent-filter></receiver>diff --git a/data/src/main/java/com/streamvault/data/epg/EpgResolutionEngine.kt b/data/src/main/java/com/streamvault/data/epg/EpgResolutionEngine.ktindex 0e8eacdd..3ef01c51 100644--- a/data/src/main/java/com/streamvault/data/epg/EpgResolutionEngine.kt+++ b/data/src/main/java/com/streamvault/data/epg/EpgResolutionEngine.kt@@ -97,10 +97,10 @@ class EpgResolutionEngine @Inject constructor(// Check which channels have provider-native EPG dataval providerEpgChannelIds = channels.mapNotNull { it.epgChannelId?.trim()?.takeIf(String::isNotEmpty) }- val providerHasEpg = if (providerEpgChannelIds.isNotEmpty()) {- programDao.countByProvider(providerId) > 0+ val providerNativeChannelIds = if (providerEpgChannelIds.isNotEmpty()) {+ programDao.getChannelIdsWithPrograms(providerId, providerEpgChannelIds).toHashSet()} else {- false+ emptySet()}// Preserve existing manual overrides@@ -181,7 +181,7 @@ class EpgResolutionEngine @Inject constructor(}// 4. Fall back to provider-native EPG- if (providerHasEpg && channelEpgId != null) {+ if (channelEpgId != null && channelEpgId in providerNativeChannelIds) {providerNativeMatches++return@map ChannelEpgMappingEntity(providerChannelId = channel.id,diff --git a/data/src/main/java/com/streamvault/data/local/RoomEnumConverters.kt b/data/src/main/java/com/streamvault/data/local/RoomEnumConverters.ktindex d30d6ede..378ba884 100644--- a/data/src/main/java/com/streamvault/data/local/RoomEnumConverters.kt+++ b/data/src/main/java/com/streamvault/data/local/RoomEnumConverters.kt@@ -5,29 +5,75 @@ import com.streamvault.domain.model.ContentTypeimport com.streamvault.domain.model.ProviderEpgSyncModeimport com.streamvault.domain.model.ProviderStatusimport com.streamvault.domain.model.ProviderType+import java.util.logging.Loggerclass RoomEnumConverters {+ private companion object {+ val logger: Logger = Logger.getLogger(RoomEnumConverters::class.java.name)+ }+@TypeConverterfun fromProviderType(value: ProviderType?): String? = value?.name@TypeConverter- fun toProviderType(value: String?): ProviderType? = value?.let(ProviderType::valueOf)+ fun toProviderType(value: String?): ProviderType? =+ enumValueOrDefault(value, ProviderType.M3U, providerTypeAliases())@TypeConverterfun fromProviderStatus(value: ProviderStatus?): String? = value?.name@TypeConverter- fun toProviderStatus(value: String?): ProviderStatus? = value?.let(ProviderStatus::valueOf)+ fun toProviderStatus(value: String?): ProviderStatus? = enumValueOrDefault(value, ProviderStatus.UNKNOWN)@TypeConverterfun fromProviderEpgSyncMode(value: ProviderEpgSyncMode?): String? = value?.name@TypeConverter- fun toProviderEpgSyncMode(value: String?): ProviderEpgSyncMode? = value?.let(ProviderEpgSyncMode::valueOf)+ fun toProviderEpgSyncMode(value: String?): ProviderEpgSyncMode? =+ enumValueOrDefault(value, ProviderEpgSyncMode.SKIP, providerEpgSyncModeAliases())@TypeConverterfun fromContentType(value: ContentType?): String? = value?.name@TypeConverter- fun toContentType(value: String?): ContentType? = value?.let(ContentType::valueOf)+ fun toContentType(value: String?): ContentType? =+ enumValueOrDefault(value, ContentType.LIVE, contentTypeAliases())++ private inline fun <reified T : Enum<T>> enumValueOrDefault(+ value: String?,+ defaultValue: T,+ aliases: Map<String, T> = emptyMap()+ ): T? {+ if (value == null) return null+ val normalizedValue = value.trim()+ aliases[normalizedValue.uppercase()]?.let { return it }+ return enumValues<T>().firstOrNull { candidate ->+ candidate.name.equals(normalizedValue, ignoreCase = true)+ } ?: defaultValue.also {+ logger.warning(+ "Unknown ${T::class.java.simpleName} value '$value'; defaulting to ${defaultValue.name}"+ )+ }+ }++ private fun providerTypeAliases(): Map<String, ProviderType> = mapOf(+ "XTREAM" to ProviderType.XTREAM_CODES,+ "XTREAM_CODES_API" to ProviderType.XTREAM_CODES,+ "STALKER" to ProviderType.STALKER_PORTAL,+ "STB" to ProviderType.STALKER_PORTAL,+ "PLAYLIST" to ProviderType.M3U+ )++ private fun providerEpgSyncModeAliases(): Map<String, ProviderEpgSyncMode> = mapOf(+ "DISABLED" to ProviderEpgSyncMode.SKIP,+ "OFF" to ProviderEpgSyncMode.SKIP,+ "FOREGROUND" to ProviderEpgSyncMode.UPFRONT+ )++ private fun contentTypeAliases(): Map<String, ContentType> = mapOf(+ "EPISODE" to ContentType.SERIES_EPISODE,+ "SHOW" to ContentType.SERIES,+ "VOD" to ContentType.MOVIE,+ "CHANNEL" to ContentType.LIVE+ )}\ No newline at end of filediff --git a/data/src/main/java/com/streamvault/data/local/StreamVaultDatabase.kt b/data/src/main/java/com/streamvault/data/local/StreamVaultDatabase.ktindex 69b9ed06..890627da 100644--- a/data/src/main/java/com/streamvault/data/local/StreamVaultDatabase.kt+++ b/data/src/main/java/com/streamvault/data/local/StreamVaultDatabase.kt@@ -46,7 +46,7 @@ import com.streamvault.data.local.entity.*RecordingStorageEntity::class,PlaybackCompatibilityRecordEntity::class],- version = 44,+ version = 47,exportSchema = true // ← was false; schema JSON now tracked in version control)@TypeConverters(RoomEnumConverters::class)@@ -1980,5 +1980,176 @@ abstract class StreamVaultDatabase : RoomDatabase() {)}}++ /**+ * Migration 44 -> 45: make favorite uniqueness null-safe by materializing a non-null+ * group scope key and deduping any pre-existing global favorite collisions.+ */+ val MIGRATION_44_45 = object : Migration(44, 45) {+ override fun migrate(database: SupportSQLiteDatabase) {+ database.execSQL("ALTER TABLE favorites ADD COLUMN group_key INTEGER NOT NULL DEFAULT 0")+ database.execSQL("UPDATE favorites SET group_key = COALESCE(group_id, 0)")+ database.execSQL(+ """+ UPDATE favorites+ SET position = (+ SELECT MIN(dupe.position)+ FROM favorites AS dupe+ WHERE dupe.group_id IS NULL+ AND dupe.provider_id = favorites.provider_id+ AND dupe.content_id = favorites.content_id+ AND dupe.content_type = favorites.content_type+ ),+ added_at = (+ SELECT MIN(dupe.added_at)+ FROM favorites AS dupe+ WHERE dupe.group_id IS NULL+ AND dupe.provider_id = favorites.provider_id+ AND dupe.content_id = favorites.content_id+ AND dupe.content_type = favorites.content_type+ )+ WHERE favorites.group_id IS NULL+ AND favorites.id IN (+ SELECT MIN(id)+ FROM favorites+ WHERE group_id IS NULL+ GROUP BY provider_id, content_id, content_type+ HAVING COUNT(*) > 1+ )+ """.trimIndent()+ )+ database.execSQL(+ """+ DELETE FROM favorites+ WHERE group_id IS NULL+ AND id NOT IN (+ SELECT MIN(id)+ FROM favorites+ WHERE group_id IS NULL+ GROUP BY provider_id, content_id, content_type+ )+ """.trimIndent()+ )+ database.execSQL(+ "CREATE UNIQUE INDEX IF NOT EXISTS index_favorites_provider_id_content_id_content_type_group_key ON favorites(provider_id, content_id, content_type, group_key)"+ )+ validateForeignKeys(database, "favorites")+ }+ }++ /**+ * Migration 45 -> 46: preserve provider-native series IDs through staging by storing both+ * the raw provider ID and a non-null remote key used for staged apply matching.+ */+ val MIGRATION_45_46 = object : Migration(45, 46) {+ override fun migrate(database: SupportSQLiteDatabase) {+ database.execSQL(+ """+ CREATE TABLE IF NOT EXISTS series_import_stage_new (+ session_id INTEGER NOT NULL,+ provider_id INTEGER NOT NULL,+ series_id INTEGER NOT NULL,+ provider_series_id TEXT,+ provider_series_key TEXT NOT NULL,+ name TEXT NOT NULL,+ poster_url TEXT,+ backdrop_url TEXT,+ category_id INTEGER,+ category_name TEXT,+ plot TEXT,+ cast TEXT,+ director TEXT,+ genre TEXT,+ release_date TEXT,+ rating REAL NOT NULL,+ tmdb_id INTEGER,+ youtube_trailer TEXT,+ episode_run_time TEXT,+ last_modified INTEGER NOT NULL,+ is_adult INTEGER NOT NULL,+ sync_fingerprint TEXT NOT NULL,+ PRIMARY KEY(session_id, provider_id, provider_series_key),+ FOREIGN KEY(provider_id) REFERENCES providers(id) ON DELETE CASCADE+ )+ """.trimIndent()+ )+ database.execSQL(+ """+ INSERT INTO series_import_stage_new (+ session_id,+ provider_id,+ series_id,+ provider_series_id,+ provider_series_key,+ 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,+ is_adult,+ sync_fingerprint+ )+ SELECT+ session_id,+ provider_id,+ series_id,+ NULL,+ CAST(series_id AS TEXT),+ 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,+ is_adult,+ sync_fingerprint+ FROM series_import_stage+ """.trimIndent()+ )+ database.execSQL("DROP TABLE series_import_stage")+ database.execSQL("ALTER TABLE series_import_stage_new RENAME TO series_import_stage")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_series_import_stage_provider_id ON series_import_stage(provider_id)")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_series_import_stage_session_id_provider_id ON series_import_stage(session_id, provider_id)")+ validateForeignKeys(database, "series_import_stage")+ }+ }++ /**+ * Migration 46 -> 47: add provider-leading browse indexes so large-provider cursor pages,+ * category/rating sorts, and correlated playback-history filters avoid wide scans.+ */+ val MIGRATION_46_47 = object : Migration(46, 47) {+ override fun migrate(database: SupportSQLiteDatabase) {+ database.execSQL("CREATE INDEX IF NOT EXISTS index_movies_provider_id_name_id ON movies(provider_id, name, id)")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_movies_provider_id_category_id_name_id ON movies(provider_id, category_id, name, id)")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_movies_provider_id_rating_name_id ON movies(provider_id, rating, name, id)")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_movies_provider_id_added_at_release_date_name_id ON movies(provider_id, added_at, release_date, name, id)")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_series_provider_id_name_id ON series(provider_id, name, id)")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_series_provider_id_category_id_name_id ON series(provider_id, category_id, name, id)")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_series_provider_id_rating_name_id ON series(provider_id, rating, name, id)")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_series_provider_id_last_modified_name_id ON series(provider_id, last_modified, name, id)")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_playback_history_provider_id_content_type_content_id ON playback_history(provider_id, content_type, content_id)")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_playback_history_provider_id_content_type_last_watched_at ON playback_history(provider_id, content_type, last_watched_at)")+ }+ }}}diff --git a/data/src/main/java/com/streamvault/data/local/dao/CatalogSyncDao.kt b/data/src/main/java/com/streamvault/data/local/dao/CatalogSyncDao.ktindex 3b40cca9..d4d3b915 100644--- a/data/src/main/java/com/streamvault/data/local/dao/CatalogSyncDao.kt+++ b/data/src/main/java/com/streamvault/data/local/dao/CatalogSyncDao.kt@@ -603,119 +603,126 @@ interface CatalogSyncDao {FROM series_import_stage AS stageWHERE stage.session_id = :sessionIdAND stage.provider_id = :providerId- AND stage.series_id = series.series_id+ AND stage.provider_series_key = COALESCE(NULLIF(series.provider_series_id, ''), CAST(series.series_id AS TEXT))),poster_url = (SELECT stage.poster_urlFROM series_import_stage AS stageWHERE stage.session_id = :sessionIdAND stage.provider_id = :providerId- AND stage.series_id = series.series_id+ AND stage.provider_series_key = COALESCE(NULLIF(series.provider_series_id, ''), CAST(series.series_id AS TEXT))),backdrop_url = (SELECT stage.backdrop_urlFROM series_import_stage AS stageWHERE stage.session_id = :sessionIdAND stage.provider_id = :providerId- AND stage.series_id = series.series_id+ AND stage.provider_series_key = COALESCE(NULLIF(series.provider_series_id, ''), CAST(series.series_id AS TEXT))),category_id = (SELECT stage.category_idFROM series_import_stage AS stageWHERE stage.session_id = :sessionIdAND stage.provider_id = :providerId- AND stage.series_id = series.series_id+ AND stage.provider_series_key = COALESCE(NULLIF(series.provider_series_id, ''), CAST(series.series_id AS TEXT))),category_name = (SELECT stage.category_nameFROM series_import_stage AS stageWHERE stage.session_id = :sessionIdAND stage.provider_id = :providerId- AND stage.series_id = series.series_id+ AND stage.provider_series_key = COALESCE(NULLIF(series.provider_series_id, ''), CAST(series.series_id AS TEXT))),plot = (SELECT stage.plotFROM series_import_stage AS stageWHERE stage.session_id = :sessionIdAND stage.provider_id = :providerId- AND stage.series_id = series.series_id+ AND stage.provider_series_key = COALESCE(NULLIF(series.provider_series_id, ''), CAST(series.series_id AS TEXT))),cast = (SELECT stage.castFROM series_import_stage AS stageWHERE stage.session_id = :sessionIdAND stage.provider_id = :providerId- AND stage.series_id = series.series_id+ AND stage.provider_series_key = COALESCE(NULLIF(series.provider_series_id, ''), CAST(series.series_id AS TEXT))),director = (SELECT stage.directorFROM series_import_stage AS stageWHERE stage.session_id = :sessionIdAND stage.provider_id = :providerId- AND stage.series_id = series.series_id+ AND stage.provider_series_key = COALESCE(NULLIF(series.provider_series_id, ''), CAST(series.series_id AS TEXT))),genre = (SELECT stage.genreFROM series_import_stage AS stageWHERE stage.session_id = :sessionIdAND stage.provider_id = :providerId- AND stage.series_id = series.series_id+ AND stage.provider_series_key = COALESCE(NULLIF(series.provider_series_id, ''), CAST(series.series_id AS TEXT))),release_date = (SELECT stage.release_dateFROM series_import_stage AS stageWHERE stage.session_id = :sessionIdAND stage.provider_id = :providerId- AND stage.series_id = series.series_id+ AND stage.provider_series_key = COALESCE(NULLIF(series.provider_series_id, ''), CAST(series.series_id AS TEXT))),rating = (SELECT stage.ratingFROM series_import_stage AS stageWHERE stage.session_id = :sessionIdAND stage.provider_id = :providerId- AND stage.series_id = series.series_id+ AND stage.provider_series_key = COALESCE(NULLIF(series.provider_series_id, ''), CAST(series.series_id AS TEXT))),tmdb_id = (SELECT stage.tmdb_idFROM series_import_stage AS stageWHERE stage.session_id = :sessionIdAND stage.provider_id = :providerId- AND stage.series_id = series.series_id+ AND stage.provider_series_key = COALESCE(NULLIF(series.provider_series_id, ''), CAST(series.series_id AS TEXT))),youtube_trailer = (SELECT stage.youtube_trailerFROM series_import_stage AS stageWHERE stage.session_id = :sessionIdAND stage.provider_id = :providerId- AND stage.series_id = series.series_id+ AND stage.provider_series_key = COALESCE(NULLIF(series.provider_series_id, ''), CAST(series.series_id AS TEXT))),episode_run_time = (SELECT stage.episode_run_timeFROM series_import_stage AS stageWHERE stage.session_id = :sessionIdAND stage.provider_id = :providerId- AND stage.series_id = series.series_id+ AND stage.provider_series_key = COALESCE(NULLIF(series.provider_series_id, ''), CAST(series.series_id AS TEXT))),last_modified = (SELECT stage.last_modifiedFROM series_import_stage AS stageWHERE stage.session_id = :sessionIdAND stage.provider_id = :providerId- AND stage.series_id = series.series_id+ AND stage.provider_series_key = COALESCE(NULLIF(series.provider_series_id, ''), CAST(series.series_id AS TEXT))+ ),+ provider_series_id = (+ SELECT stage.provider_series_id+ FROM series_import_stage AS stage+ WHERE stage.session_id = :sessionId+ AND stage.provider_id = :providerId+ AND stage.provider_series_key = COALESCE(NULLIF(series.provider_series_id, ''), CAST(series.series_id AS TEXT))),is_adult = (SELECT stage.is_adultFROM series_import_stage AS stageWHERE stage.session_id = :sessionIdAND stage.provider_id = :providerId- AND stage.series_id = series.series_id+ AND stage.provider_series_key = COALESCE(NULLIF(series.provider_series_id, ''), CAST(series.series_id AS TEXT))),sync_fingerprint = (SELECT stage.sync_fingerprintFROM series_import_stage AS stageWHERE stage.session_id = :sessionIdAND stage.provider_id = :providerId- AND stage.series_id = series.series_id+ AND stage.provider_series_key = COALESCE(NULLIF(series.provider_series_id, ''), CAST(series.series_id AS TEXT)))WHERE provider_id = :providerIdAND EXISTS (@@ -723,7 +730,7 @@ interface CatalogSyncDao {FROM series_import_stage AS stageWHERE stage.session_id = :sessionIdAND stage.provider_id = :providerId- AND stage.series_id = series.series_id+ AND stage.provider_series_key = COALESCE(NULLIF(series.provider_series_id, ''), CAST(series.series_id AS TEXT))AND series.sync_fingerprint != stage.sync_fingerprint)"""@@ -734,6 +741,7 @@ interface CatalogSyncDao {"""INSERT INTO series (series_id,+ provider_series_id,name,poster_url,backdrop_url,@@ -756,6 +764,7 @@ interface CatalogSyncDao {)SELECTstage.series_id,+ stage.provider_series_id,stage.name,stage.poster_url,stage.backdrop_url,@@ -782,7 +791,7 @@ interface CatalogSyncDao {SELECT 1FROM series AS existingWHERE existing.provider_id = stage.provider_id- AND existing.series_id = stage.series_id+ AND COALESCE(NULLIF(existing.provider_series_id, ''), CAST(existing.series_id AS TEXT)) = stage.provider_series_key)""")@@ -797,7 +806,7 @@ interface CatalogSyncDao {FROM series_import_stage AS stageWHERE stage.session_id = :sessionIdAND stage.provider_id = :providerId- AND stage.series_id = series.series_id+ AND stage.provider_series_key = COALESCE(NULLIF(series.provider_series_id, ''), CAST(series.series_id AS TEXT)))""")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.ktindex 76ad2d74..f4f09aea 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@@ -43,10 +43,10 @@ abstract class ProviderDao {abstract suspend fun getByIds(ids: List<Long>): List<ProviderEntity>@Insert(onConflict = OnConflictStrategy.REPLACE)- abstract suspend fun insert(provider: ProviderEntity): Long+ protected abstract suspend fun insertDirect(provider: ProviderEntity): Long@Update- abstract suspend fun update(provider: ProviderEntity)+ protected abstract suspend fun updateDirect(provider: ProviderEntity)@Query("DELETE FROM providers WHERE id = :id")abstract suspend fun delete(id: Long)@@ -63,6 +63,22 @@ abstract class ProviderDao {@Query("UPDATE providers SET epg_url = :epgUrl WHERE id = :id")abstract suspend fun updateEpgUrl(id: Long, epgUrl: String)+ @Transaction+ open suspend fun insert(provider: ProviderEntity): Long {+ if (provider.isActive) {+ deactivateAll()+ }+ return insertDirect(provider)+ }++ @Transaction+ open suspend fun update(provider: ProviderEntity) {+ if (provider.isActive) {+ deactivateAll()+ }+ updateDirect(provider)+ }+/** Atomically deactivates all providers then activates the given one. */@Transactionopen suspend fun setActive(id: Long) {@@ -250,6 +266,24 @@ abstract class ChannelDao {)abstract fun search(providerId: Long, query: String, limit: Int): Flow<List<ChannelBrowseEntity>>+ @Query(+ """+ SELECT c.id, c.stream_id, c.name, c.logo_url, c.group_title, c.category_id, c.category_name, c.stream_url,+ c.epg_channel_id, c.number, c.catch_up_supported, c.catch_up_days, c.catchUpSource,+ c.provider_id, c.is_adult, c.is_user_protected, c.logical_group_id, c.error_count+ FROM channels c+ WHERE c.provider_id = :providerId+ AND (+ c.name LIKE :queryLike ESCAPE '\\'+ OR COALESCE(c.group_title, '') LIKE :queryLike ESCAPE '\\'+ OR COALESCE(c.category_name, '') LIKE :queryLike ESCAPE '\\'+ )+ ORDER BY c.name ASC+ LIMIT :limit+ """+ )+ abstract fun searchFallback(providerId: Long, queryLike: String, limit: Int): Flow<List<ChannelBrowseEntity>>+@Query("""SELECT c.id, c.stream_id, c.name, c.logo_url, c.group_title, c.category_id, c.category_name, c.stream_url,@@ -266,6 +300,25 @@ abstract class ChannelDao {)abstract fun searchByCategory(providerId: Long, categoryId: Long, query: String, limit: Int): Flow<List<ChannelBrowseEntity>>+ @Query(+ """+ SELECT c.id, c.stream_id, c.name, c.logo_url, c.group_title, c.category_id, c.category_name, c.stream_url,+ c.epg_channel_id, c.number, c.catch_up_supported, c.catch_up_days, c.catchUpSource,+ c.provider_id, c.is_adult, c.is_user_protected, c.logical_group_id, c.error_count+ FROM channels c+ WHERE c.provider_id = :providerId+ AND c.category_id = :categoryId+ AND (+ c.name LIKE :queryLike ESCAPE '\\'+ OR COALESCE(c.group_title, '') LIKE :queryLike ESCAPE '\\'+ OR COALESCE(c.category_name, '') LIKE :queryLike ESCAPE '\\'+ )+ ORDER BY c.name ASC+ LIMIT :limit+ """+ )+ abstract fun searchByCategoryFallback(providerId: Long, categoryId: Long, queryLike: String, limit: Int): Flow<List<ChannelBrowseEntity>>+@Query("SELECT * FROM channels WHERE id = :id")abstract suspend fun getById(id: Long): ChannelEntity?@@ -963,16 +1016,20 @@ interface MovieDao {@Query("SELECT * FROM movies WHERE provider_id = :providerId AND category_id = :categoryId ORDER BY name ASC LIMIT :limit")fun getByCategoryPreview(providerId: Long, categoryId: Long, limit: Int): Flow<List<MovieBrowseEntity>>- @Query("SELECT * FROM movies WHERE provider_id = :providerId ORDER BY rating DESC, name ASC LIMIT :limit")+ @Query("SELECT * FROM movies WHERE provider_id = :providerId AND rating > 0 ORDER BY rating DESC, name ASC LIMIT :limit")fun getTopRatedPreview(providerId: Long, limit: Int): Flow<List<MovieBrowseEntity>>- @Query("SELECT * FROM movies WHERE provider_id = :providerId ORDER BY rating DESC, name ASC, id ASC LIMIT :limit")+ @Query("SELECT COUNT(*) FROM movies WHERE provider_id = :providerId AND rating > 0")+ fun getTopRatedCountByProvider(providerId: Long): Flow<Int>++ @Query("SELECT * FROM movies WHERE provider_id = :providerId AND rating > 0 ORDER BY rating DESC, name ASC, id ASC LIMIT :limit")suspend fun getTopRatedCursorPage(providerId: Long, limit: Int): List<MovieBrowseEntity>@Query("""SELECT * FROM moviesWHERE provider_id = :providerId+ AND rating > 0AND (rating < :lastRatingOR (rating = :lastRating AND (name > :lastName OR (name = :lastName AND id > :lastId)))@@ -989,10 +1046,13 @@ interface MovieDao {limit: Int): List<MovieBrowseEntity>- @Query("SELECT * FROM movies WHERE provider_id = :providerId AND category_id = :categoryId ORDER BY rating DESC, name ASC LIMIT :limit")+ @Query("SELECT * FROM movies WHERE provider_id = :providerId AND category_id = :categoryId AND rating > 0 ORDER BY rating DESC, name ASC LIMIT :limit")fun getTopRatedByCategoryPreview(providerId: Long, categoryId: Long, limit: Int): Flow<List<MovieBrowseEntity>>- @Query("SELECT * FROM movies WHERE provider_id = :providerId AND category_id = :categoryId ORDER BY rating DESC, name ASC, id ASC LIMIT :limit")+ @Query("SELECT COUNT(*) FROM movies WHERE provider_id = :providerId AND category_id = :categoryId AND rating > 0")+ fun getTopRatedCountByCategory(providerId: Long, categoryId: Long): Flow<Int>++ @Query("SELECT * FROM movies WHERE provider_id = :providerId AND category_id = :categoryId AND rating > 0 ORDER BY rating DESC, name ASC, id ASC LIMIT :limit")suspend fun getTopRatedByCategoryCursorPage(providerId: Long, categoryId: Long, limit: Int): List<MovieBrowseEntity>@Query(@@ -1000,6 +1060,7 @@ interface MovieDao {SELECT * FROM moviesWHERE provider_id = :providerIdAND category_id = :categoryId+ AND rating > 0AND (rating < :lastRatingOR (rating = :lastRating AND (name > :lastName OR (name = :lastName AND id > :lastId)))@@ -1017,16 +1078,30 @@ interface MovieDao {limit: Int): List<MovieBrowseEntity>- @Query("SELECT * FROM movies WHERE provider_id = :providerId ORDER BY added_at DESC, release_date DESC, name ASC LIMIT :limit")+ @Query("SELECT * FROM movies WHERE provider_id = :providerId AND (added_at > 0 OR COALESCE(release_date, '') != '' OR COALESCE(year, '') != '') ORDER BY added_at DESC, release_date DESC, name ASC LIMIT :limit")fun getFreshPreview(providerId: Long, limit: Int): Flow<List<MovieBrowseEntity>>- @Query("SELECT * FROM movies WHERE provider_id = :providerId ORDER BY added_at DESC, release_date DESC, name ASC, id ASC LIMIT :limit")+ @Query(+ """+ SELECT COUNT(*) FROM movies+ WHERE provider_id = :providerId+ AND (+ added_at > 0+ OR COALESCE(release_date, '') != ''+ OR COALESCE(year, '') != ''+ )+ """+ )+ fun getFreshCountByProvider(providerId: Long): Flow<Int>++ @Query("SELECT * FROM movies WHERE provider_id = :providerId AND (added_at > 0 OR COALESCE(release_date, '') != '' OR COALESCE(year, '') != '') ORDER BY added_at DESC, release_date DESC, name ASC, id ASC LIMIT :limit")suspend fun getFreshCursorPage(providerId: Long, limit: Int): List<MovieBrowseEntity>@Query("""SELECT * FROM moviesWHERE provider_id = :providerId+ AND (added_at > 0 OR COALESCE(release_date, '') != '' OR COALESCE(year, '') != '')AND (added_at < :lastAddedAtOR (@@ -1053,10 +1128,24 @@ interface MovieDao {limit: Int): List<MovieBrowseEntity>- @Query("SELECT * FROM movies WHERE provider_id = :providerId AND category_id = :categoryId ORDER BY added_at DESC, release_date DESC, name ASC LIMIT :limit")+ @Query("SELECT * FROM movies WHERE provider_id = :providerId AND category_id = :categoryId AND (added_at > 0 OR COALESCE(release_date, '') != '' OR COALESCE(year, '') != '') ORDER BY added_at DESC, release_date DESC, name ASC LIMIT :limit")fun getFreshByCategoryPreview(providerId: Long, categoryId: Long, limit: Int): Flow<List<MovieBrowseEntity>>- @Query("SELECT * FROM movies WHERE provider_id = :providerId AND category_id = :categoryId ORDER BY added_at DESC, release_date DESC, name ASC, id ASC LIMIT :limit")+ @Query(+ """+ SELECT COUNT(*) FROM movies+ WHERE provider_id = :providerId+ AND category_id = :categoryId+ AND (+ added_at > 0+ OR COALESCE(release_date, '') != ''+ OR COALESCE(year, '') != ''+ )+ """+ )+ fun getFreshCountByCategory(providerId: Long, categoryId: Long): Flow<Int>++ @Query("SELECT * FROM movies WHERE provider_id = :providerId AND category_id = :categoryId AND (added_at > 0 OR COALESCE(release_date, '') != '' OR COALESCE(year, '') != '') ORDER BY added_at DESC, release_date DESC, name ASC, id ASC LIMIT :limit")suspend fun getFreshByCategoryCursorPage(providerId: Long, categoryId: Long, limit: Int): List<MovieBrowseEntity>@Query(@@ -1064,6 +1153,7 @@ interface MovieDao {SELECT * FROM moviesWHERE provider_id = :providerIdAND category_id = :categoryId+ AND (added_at > 0 OR COALESCE(release_date, '') != '' OR COALESCE(year, '') != '')AND (added_at < :lastAddedAtOR (@@ -1103,6 +1193,22 @@ interface MovieDao {)fun search(providerId: Long, query: String, limit: Int): Flow<List<MovieBrowseEntity>>+ @Query(+ """+ SELECT m.* FROM movies m+ WHERE m.provider_id = :providerId+ AND (+ m.name LIKE :queryLike ESCAPE '\\'+ OR COALESCE(m.genre, '') LIKE :queryLike ESCAPE '\\'+ OR COALESCE(m.category_name, '') LIKE :queryLike ESCAPE '\\'+ OR COALESCE(m.year, '') LIKE :queryLike ESCAPE '\\'+ )+ ORDER BY m.name ASC+ LIMIT :limit+ """+ )+ fun searchFallback(providerId: Long, queryLike: String, limit: Int): Flow<List<MovieBrowseEntity>>+@Query("""SELECT m.* FROM movies m@@ -1116,6 +1222,23 @@ interface MovieDao {)fun searchByCategory(providerId: Long, categoryId: Long, query: String, limit: Int): Flow<List<MovieBrowseEntity>>+ @Query(+ """+ SELECT m.* FROM movies m+ WHERE m.provider_id = :providerId+ AND m.category_id = :categoryId+ AND (+ m.name LIKE :queryLike ESCAPE '\\'+ OR COALESCE(m.genre, '') LIKE :queryLike ESCAPE '\\'+ OR COALESCE(m.category_name, '') LIKE :queryLike ESCAPE '\\'+ OR COALESCE(m.year, '') LIKE :queryLike ESCAPE '\\'+ )+ ORDER BY m.name ASC+ LIMIT :limit+ """+ )+ fun searchByCategoryFallback(providerId: Long, categoryId: Long, queryLike: String, limit: Int): Flow<List<MovieBrowseEntity>>+@Query("SELECT * FROM movies WHERE id = :id")suspend fun getById(id: Long): MovieEntity?@@ -1146,9 +1269,6 @@ interface MovieDao {@Updatesuspend fun updateAll(movies: List<MovieEntity>)- @Query("UPDATE movies SET watch_progress = :progress, last_watched_at = :timestamp WHERE id = :id")- suspend fun updateWatchProgress(id: Long, progress: Long, timestamp: Long = System.currentTimeMillis())-@Query("""UPDATE movies@@ -1444,20 +1564,25 @@ interface SeriesDao {"""SELECT series.* FROM seriesWHERE series.provider_id = :providerId- AND NOT EXISTS (- SELECT 1 FROM playback_history- WHERE playback_history.provider_id = series.provider_id- AND (- (playback_history.content_type = 'SERIES' AND playback_history.content_id = series.id)- OR (- playback_history.content_type = 'SERIES_EPISODE'- AND EXISTS (- SELECT 1 FROM episodes- WHERE episodes.id = playback_history.content_id- AND episodes.series_id = series.id- )+ AND (+ NOT EXISTS (+ SELECT 1 FROM episodes+ WHERE episodes.series_id = series.id+ AND episodes.provider_id = series.provider_id+ )+ OR EXISTS (+ SELECT 1 FROM episodes e+ WHERE e.series_id = series.id+ AND e.provider_id = series.provider_id+ AND NOT EXISTS (+ SELECT 1 FROM playback_history ph+ WHERE ph.content_id = e.id+ AND ph.content_type = 'SERIES_EPISODE'+ AND ph.provider_id = series.provider_id+ AND ph.total_duration_ms > 0+ AND ph.resume_position_ms >= CAST(ph.total_duration_ms * 0.95 AS INTEGER))- )+ ))ORDER BY series.name ASCLIMIT :limit OFFSET :offset@@ -1470,20 +1595,25 @@ interface SeriesDao {SELECT COUNT(*)FROM seriesWHERE provider_id = :providerId- AND NOT EXISTS (- SELECT 1 FROM playback_history- WHERE playback_history.provider_id = series.provider_id- AND (- (playback_history.content_type = 'SERIES' AND playback_history.content_id = series.id)- OR (- playback_history.content_type = 'SERIES_EPISODE'- AND EXISTS (- SELECT 1 FROM episodes- WHERE episodes.id = playback_history.content_id- AND episodes.series_id = series.id- )+ AND (+ NOT EXISTS (+ SELECT 1 FROM episodes+ WHERE episodes.series_id = series.id+ AND episodes.provider_id = :providerId+ )+ OR EXISTS (+ SELECT 1 FROM episodes e+ WHERE e.series_id = series.id+ AND e.provider_id = :providerId+ AND NOT EXISTS (+ SELECT 1 FROM playback_history ph+ WHERE ph.content_id = e.id+ AND ph.content_type = 'SERIES_EPISODE'+ AND ph.provider_id = :providerId+ AND ph.total_duration_ms > 0+ AND ph.resume_position_ms >= CAST(ph.total_duration_ms * 0.95 AS INTEGER))- )+ ))""")@@ -1711,20 +1841,25 @@ interface SeriesDao {SELECT series.* FROM seriesWHERE series.provider_id = :providerIdAND series.category_id = :categoryId- AND NOT EXISTS (- SELECT 1 FROM playback_history- WHERE playback_history.provider_id = series.provider_id- AND (- (playback_history.content_type = 'SERIES' AND playback_history.content_id = series.id)- OR (- playback_history.content_type = 'SERIES_EPISODE'- AND EXISTS (- SELECT 1 FROM episodes- WHERE episodes.id = playback_history.content_id- AND episodes.series_id = series.id- )+ AND (+ NOT EXISTS (+ SELECT 1 FROM episodes+ WHERE episodes.series_id = series.id+ AND episodes.provider_id = series.provider_id+ )+ OR EXISTS (+ SELECT 1 FROM episodes e+ WHERE e.series_id = series.id+ AND e.provider_id = series.provider_id+ AND NOT EXISTS (+ SELECT 1 FROM playback_history ph+ WHERE ph.content_id = e.id+ AND ph.content_type = 'SERIES_EPISODE'+ AND ph.provider_id = series.provider_id+ AND ph.total_duration_ms > 0+ AND ph.resume_position_ms >= CAST(ph.total_duration_ms * 0.95 AS INTEGER))- )+ ))ORDER BY series.name ASCLIMIT :limit OFFSET :offset@@ -1738,20 +1873,25 @@ interface SeriesDao {FROM seriesWHERE provider_id = :providerIdAND category_id = :categoryId- AND NOT EXISTS (- SELECT 1 FROM playback_history- WHERE playback_history.provider_id = series.provider_id- AND (- (playback_history.content_type = 'SERIES' AND playback_history.content_id = series.id)- OR (- playback_history.content_type = 'SERIES_EPISODE'- AND EXISTS (- SELECT 1 FROM episodes- WHERE episodes.id = playback_history.content_id- AND episodes.series_id = series.id- )+ AND (+ NOT EXISTS (+ SELECT 1 FROM episodes+ WHERE episodes.series_id = series.id+ AND episodes.provider_id = :providerId+ )+ OR EXISTS (+ SELECT 1 FROM episodes e+ WHERE e.series_id = series.id+ AND e.provider_id = :providerId+ AND NOT EXISTS (+ SELECT 1 FROM playback_history ph+ WHERE ph.content_id = e.id+ AND ph.content_type = 'SERIES_EPISODE'+ AND ph.provider_id = :providerId+ AND ph.total_duration_ms > 0+ AND ph.resume_position_ms >= CAST(ph.total_duration_ms * 0.95 AS INTEGER))- )+ ))""")@@ -1813,6 +1953,9 @@ interface SeriesDao {@Query("SELECT * FROM series WHERE provider_id = :providerId ORDER BY rating DESC, name ASC LIMIT :limit")fun getTopRatedPreview(providerId: Long, limit: Int): Flow<List<SeriesBrowseEntity>>+ @Query("SELECT COUNT(*) FROM series WHERE provider_id = :providerId AND rating > 0")+ fun getTopRatedCountByProvider(providerId: Long): Flow<Int>+@Query("SELECT * FROM series WHERE provider_id = :providerId ORDER BY rating DESC, name ASC, id ASC LIMIT :limit")suspend fun getTopRatedCursorPage(providerId: Long, limit: Int): List<SeriesBrowseEntity>@@ -1839,6 +1982,9 @@ interface SeriesDao {@Query("SELECT * FROM series WHERE provider_id = :providerId AND category_id = :categoryId ORDER BY rating DESC, name ASC LIMIT :limit")fun getTopRatedByCategoryPreview(providerId: Long, categoryId: Long, limit: Int): Flow<List<SeriesBrowseEntity>>+ @Query("SELECT COUNT(*) FROM series WHERE provider_id = :providerId AND category_id = :categoryId AND rating > 0")+ fun getTopRatedCountByCategory(providerId: Long, categoryId: Long): Flow<Int>+@Query("SELECT * FROM series WHERE provider_id = :providerId AND category_id = :categoryId ORDER BY rating DESC, name ASC, id ASC LIMIT :limit")suspend fun getTopRatedByCategoryCursorPage(providerId: Long, categoryId: Long, limit: Int): List<SeriesBrowseEntity>@@ -1867,6 +2013,18 @@ interface SeriesDao {@Query("SELECT * FROM series WHERE provider_id = :providerId ORDER BY last_modified DESC, name ASC LIMIT :limit")fun getFreshPreview(providerId: Long, limit: Int): Flow<List<SeriesBrowseEntity>>+ @Query(+ """+ SELECT COUNT(*) FROM series+ WHERE provider_id = :providerId+ AND (+ last_modified > 0+ OR COALESCE(release_date, '') != ''+ )+ """+ )+ fun getFreshCountByProvider(providerId: Long): Flow<Int>+@Query("SELECT * FROM series WHERE provider_id = :providerId ORDER BY last_modified DESC, name ASC, id ASC LIMIT :limit")suspend fun getFreshCursorPage(providerId: Long, limit: Int): List<SeriesBrowseEntity>@@ -1893,6 +2051,19 @@ interface SeriesDao {@Query("SELECT * FROM series WHERE provider_id = :providerId AND category_id = :categoryId ORDER BY last_modified DESC, name ASC LIMIT :limit")fun getFreshByCategoryPreview(providerId: Long, categoryId: Long, limit: Int): Flow<List<SeriesBrowseEntity>>+ @Query(+ """+ SELECT COUNT(*) FROM series+ WHERE provider_id = :providerId+ AND category_id = :categoryId+ AND (+ last_modified > 0+ OR COALESCE(release_date, '') != ''+ )+ """+ )+ fun getFreshCountByCategory(providerId: Long, categoryId: Long): Flow<Int>+@Query("SELECT * FROM series WHERE provider_id = :providerId AND category_id = :categoryId ORDER BY last_modified DESC, name ASC, id ASC LIMIT :limit")suspend fun getFreshByCategoryCursorPage(providerId: Long, categoryId: Long, limit: Int): List<SeriesBrowseEntity>@@ -1930,6 +2101,21 @@ interface SeriesDao {)fun search(providerId: Long, query: String, limit: Int): Flow<List<SeriesBrowseEntity>>+ @Query(+ """+ SELECT s.* FROM series s+ WHERE s.provider_id = :providerId+ AND (+ s.name LIKE :queryLike ESCAPE '\\'+ OR COALESCE(s.genre, '') LIKE :queryLike ESCAPE '\\'+ OR COALESCE(s.category_name, '') LIKE :queryLike ESCAPE '\\'+ )+ ORDER BY s.name ASC+ LIMIT :limit+ """+ )+ fun searchFallback(providerId: Long, queryLike: String, limit: Int): Flow<List<SeriesBrowseEntity>>+@Query("""SELECT s.* FROM series s@@ -1943,6 +2129,22 @@ interface SeriesDao {)fun searchByCategory(providerId: Long, categoryId: Long, query: String, limit: Int): Flow<List<SeriesBrowseEntity>>+ @Query(+ """+ SELECT s.* FROM series s+ WHERE s.provider_id = :providerId+ AND s.category_id = :categoryId+ AND (+ s.name LIKE :queryLike ESCAPE '\\'+ OR COALESCE(s.genre, '') LIKE :queryLike ESCAPE '\\'+ OR COALESCE(s.category_name, '') LIKE :queryLike ESCAPE '\\'+ )+ ORDER BY s.name ASC+ LIMIT :limit+ """+ )+ fun searchByCategoryFallback(providerId: Long, categoryId: Long, queryLike: String, limit: Int): Flow<List<SeriesBrowseEntity>>+@Query("SELECT * FROM series WHERE id = :id")suspend fun getById(id: Long): SeriesEntity?@@ -2101,9 +2303,6 @@ interface EpisodeDao {@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())-@Query("""UPDATE episodes@@ -2248,10 +2447,10 @@ interface ProgramDao {start_time,end_time,lang,- NULL AS rating,- NULL AS image_url,- NULL AS genre,- NULL AS category,+ rating,+ image_url,+ genre,+ category,has_archiveFROM programsWHERE provider_id = :providerId@@ -2277,10 +2476,10 @@ interface ProgramDao {start_time,end_time,lang,- NULL AS rating,- NULL AS image_url,- NULL AS genre,- NULL AS category,+ rating,+ image_url,+ genre,+ category,has_archiveFROM programsWHERE provider_id = :providerId@@ -2306,10 +2505,10 @@ interface ProgramDao {programs.start_time,programs.end_time,programs.lang,- NULL AS rating,- NULL AS image_url,- NULL AS genre,- NULL AS category,+ programs.rating,+ programs.image_url,+ programs.genre,+ programs.category,programs.has_archiveFROM programsINNER JOIN channels@@ -2341,10 +2540,10 @@ interface ProgramDao {programs.start_time,programs.end_time,programs.lang,- NULL AS rating,- NULL AS image_url,- NULL AS genre,- NULL AS category,+ programs.rating,+ programs.image_url,+ programs.genre,+ programs.category,programs.has_archiveFROM programsWHERE programs.provider_id = :providerId@@ -2393,10 +2592,10 @@ interface ProgramDao {start_time,end_time,lang,- NULL AS rating,- NULL AS image_url,- NULL AS genre,- NULL AS category,+ rating,+ image_url,+ genre,+ category,has_archiveFROM programsWHERE provider_id = :providerId@@ -2406,7 +2605,7 @@ interface ProgramDao {LIMIT 1""")- fun getNowPlaying(providerId: Long, channelId: String, now: Long = System.currentTimeMillis()): Flow<ProgramBrowseEntity?>+ fun getNowPlaying(providerId: Long, channelId: String, now: Long): Flow<ProgramBrowseEntity?>@Query("""@@ -2422,10 +2621,10 @@ interface ProgramDao {start_time,end_time,lang,- NULL AS rating,- NULL AS image_url,- NULL AS genre,- NULL AS category,+ rating,+ image_url,+ genre,+ category,has_archiveFROM programsWHERE provider_id = :providerId@@ -2434,7 +2633,7 @@ interface ProgramDao {AND end_time > :now""")- fun getNowPlayingForChannels(providerId: Long, channelIds: List<String>, now: Long = System.currentTimeMillis()): Flow<List<ProgramBrowseEntity>>+ fun getNowPlayingForChannels(providerId: Long, channelIds: List<String>, now: Long): Flow<List<ProgramBrowseEntity>>@Query("""@@ -2450,10 +2649,10 @@ interface ProgramDao {start_time,end_time,lang,- NULL AS rating,- NULL AS image_url,- NULL AS genre,- NULL AS category,+ rating,+ image_url,+ genre,+ category,has_archiveFROM programsWHERE provider_id = :providerId@@ -2462,7 +2661,7 @@ interface ProgramDao {AND end_time > :now""")- suspend fun getNowPlayingForChannelsSync(providerId: Long, channelIds: List<String>, now: Long = System.currentTimeMillis()): List<ProgramBrowseEntity>+ suspend fun getNowPlayingForChannelsSync(providerId: Long, channelIds: List<String>, now: Long): List<ProgramBrowseEntity>@Query("""@@ -2478,10 +2677,10 @@ interface ProgramDao {start_time,end_time,lang,- NULL AS rating,- NULL AS image_url,- NULL AS genre,- NULL AS category,+ rating,+ image_url,+ genre,+ category,has_archiveFROM programsWHERE provider_id = :providerId@@ -2496,6 +2695,16 @@ interface ProgramDao {@Insert(onConflict = OnConflictStrategy.REPLACE)suspend fun insertAll(programs: List<ProgramEntity>)+ @Query(+ """+ SELECT DISTINCT channel_id+ FROM programs+ WHERE provider_id = :providerId+ AND channel_id IN (:channelIds)+ """+ )+ suspend fun getChannelIdsWithPrograms(providerId: Long, channelIds: List<String>): List<String>+@Query("SELECT COUNT(*) FROM programs WHERE provider_id = :providerId")suspend fun countByProvider(providerId: Long): Int@@ -2512,61 +2721,127 @@ interface ProgramDao {suspend fun deleteForChannel(providerId: Long, channelId: String)}+data class FavoriteGroupConstraint(+ @ColumnInfo(name = "provider_id") val providerId: Long,+ @ColumnInfo(name = "content_type") val contentType: String+)+@Dao-interface FavoriteDao {+abstract class FavoriteDao {@Query("SELECT * FROM favorites WHERE provider_id = :providerId AND group_id IS NULL ORDER BY position ASC")- fun getAllGlobal(providerId: Long): Flow<List<FavoriteEntity>>+ abstract fun getAllGlobal(providerId: Long): Flow<List<FavoriteEntity>>@Query("SELECT * FROM favorites WHERE provider_id IN (:providerIds) AND group_id IS NULL ORDER BY provider_id ASC, position ASC")- fun getAllGlobalByProviders(providerIds: List<Long>): Flow<List<FavoriteEntity>>+ abstract fun getAllGlobalByProviders(providerIds: List<Long>): Flow<List<FavoriteEntity>>@Query("SELECT * FROM favorites WHERE provider_id = :providerId AND content_type = :contentType AND group_id IS NULL ORDER BY position ASC")- fun getGlobalByType(providerId: Long, contentType: String): Flow<List<FavoriteEntity>>+ abstract fun getGlobalByType(providerId: Long, contentType: String): Flow<List<FavoriteEntity>>@Query("SELECT * FROM favorites WHERE provider_id IN (:providerIds) AND content_type = :contentType AND group_id IS NULL ORDER BY provider_id ASC, position ASC")- fun getGlobalByTypeForProviders(providerIds: List<Long>, contentType: String): Flow<List<FavoriteEntity>>+ abstract fun getGlobalByTypeForProviders(providerIds: List<Long>, contentType: String): Flow<List<FavoriteEntity>>@Query("SELECT * FROM favorites WHERE provider_id = :providerId AND content_type = :contentType ORDER BY position ASC")- fun getAllByType(providerId: Long, contentType: String): Flow<List<FavoriteEntity>>+ abstract fun getAllByType(providerId: Long, contentType: String): Flow<List<FavoriteEntity>>- @Query("SELECT * FROM favorites WHERE group_id = :groupId ORDER BY position ASC")- fun getByGroup(groupId: Long): Flow<List<FavoriteEntity>>+ @Query(+ """+ SELECT f.*+ FROM favorites AS f+ INNER JOIN virtual_groups AS g+ ON g.id = f.group_id+ AND g.provider_id = f.provider_id+ AND g.content_type = f.content_type+ WHERE g.id = :groupId+ ORDER BY f.position ASC+ """+ )+ abstract fun getByGroup(groupId: Long): Flow<List<FavoriteEntity>>@Query("SELECT * FROM favorites WHERE provider_id = :providerId AND content_id = :contentId AND content_type = :contentType AND (:groupId IS NULL AND group_id IS NULL OR group_id = :groupId) LIMIT 1")- suspend fun get(providerId: Long, contentId: Long, contentType: String, groupId: Long?): FavoriteEntity?+ abstract suspend fun get(providerId: Long, contentId: Long, contentType: String, groupId: Long?): FavoriteEntity?@Query("SELECT COUNT(*) FROM favorites WHERE provider_id = :providerId AND group_id IS NULL AND content_type = :contentType")- fun getGlobalFavoriteCount(providerId: Long, contentType: String): Flow<Int>+ abstract fun getGlobalFavoriteCount(providerId: Long, contentType: String): Flow<Int>@Query("SELECT group_id as category_id, COUNT(*) as item_count FROM favorites WHERE provider_id = :providerId AND group_id IS NOT NULL AND content_type = :contentType GROUP BY group_id")- fun getGroupFavoriteCounts(providerId: Long, contentType: String): Flow<List<CategoryCount>>+ abstract fun getGroupFavoriteCounts(providerId: Long, contentType: String): Flow<List<CategoryCount>>++ @Query("SELECT group_id as category_id, COUNT(*) as item_count FROM favorites WHERE provider_id IN (:providerIds) AND group_id IS NOT NULL AND content_type = :contentType GROUP BY group_id")+ abstract fun getGroupFavoriteCountsForProviders(providerIds: List<Long>, contentType: String): Flow<List<CategoryCount>>@Query("SELECT group_id FROM favorites WHERE provider_id = :providerId AND content_id = :contentId AND content_type = :contentType AND group_id IS NOT NULL")- suspend fun getGroupMemberships(providerId: Long, contentId: Long, contentType: String): List<Long>+ abstract suspend fun getGroupMemberships(providerId: Long, contentId: Long, contentType: String): List<Long>@Query("SELECT MAX(position) FROM favorites WHERE provider_id = :providerId AND (:groupId IS NULL AND group_id IS NULL OR group_id = :groupId)")- suspend fun getMaxPosition(providerId: Long, groupId: Long?): Int?+ abstract suspend fun getMaxPosition(providerId: Long, groupId: Long?): Int?@Insert(onConflict = OnConflictStrategy.REPLACE)- suspend fun insert(favorite: FavoriteEntity)+ protected abstract suspend fun insertDirect(favorite: FavoriteEntity)@Update- suspend fun updateAll(favorites: List<FavoriteEntity>)+ abstract suspend fun updateAll(favorites: List<FavoriteEntity>)@Query("DELETE FROM favorites WHERE provider_id = :providerId AND content_id = :contentId AND content_type = :contentType AND (:groupId IS NULL AND group_id IS NULL OR group_id = :groupId)")- suspend fun delete(providerId: Long, contentId: Long, contentType: String, groupId: Long?)+ abstract suspend fun delete(providerId: Long, contentId: Long, contentType: String, groupId: Long?)@Query("DELETE FROM favorites WHERE content_type = 'LIVE' AND content_id NOT IN (SELECT id FROM channels)")- suspend fun deleteMissingLiveFavorites(): Int+ abstract suspend fun deleteMissingLiveFavorites(): Int@Query("DELETE FROM favorites WHERE content_type = 'MOVIE' AND content_id NOT IN (SELECT id FROM movies)")- suspend fun deleteMissingMovieFavorites(): Int+ abstract suspend fun deleteMissingMovieFavorites(): Int@Query("DELETE FROM favorites WHERE content_type = 'SERIES' AND content_id NOT IN (SELECT id FROM series)")- suspend fun deleteMissingSeriesFavorites(): Int+ abstract suspend fun deleteMissingSeriesFavorites(): Int++ @Query("SELECT * FROM favorites WHERE id = :favoriteId LIMIT 1")+ protected abstract suspend fun getById(favoriteId: Long): FavoriteEntity?- @Query("UPDATE favorites SET group_id = :groupId WHERE id = :favoriteId")- suspend fun updateGroup(favoriteId: Long, groupId: Long?)+ @Query("SELECT provider_id, content_type FROM virtual_groups WHERE id = :groupId LIMIT 1")+ protected abstract suspend fun getGroupConstraint(groupId: Long): FavoriteGroupConstraint?++ @Query("UPDATE favorites SET group_id = :groupId, group_key = COALESCE(:groupId, 0) WHERE id = :favoriteId")+ protected abstract suspend fun updateGroupDirect(favoriteId: Long, groupId: Long?)++ @Transaction+ open suspend fun insert(favorite: FavoriteEntity) {+ validateGroupAssignment(+ providerId = favorite.providerId,+ contentType = favorite.contentType.name,+ groupId = favorite.groupId+ )+ insertDirect(favorite)+ }++ @Transaction+ open suspend fun updateGroup(favoriteId: Long, groupId: Long?) {+ if (groupId == null) {+ updateGroupDirect(favoriteId, null)+ return+ }++ val favorite = getById(favoriteId)+ ?: throw IllegalArgumentException("Favorite $favoriteId does not exist")++ validateGroupAssignment(+ providerId = favorite.providerId,+ contentType = favorite.contentType.name,+ groupId = groupId+ )+ updateGroupDirect(favoriteId, groupId)+ }++ private suspend fun validateGroupAssignment(providerId: Long, contentType: String, groupId: Long?) {+ val targetGroupId = groupId ?: return+ val group = getGroupConstraint(targetGroupId)+ ?: throw IllegalArgumentException("Favorite group $targetGroupId does not exist")++ require(group.providerId == providerId) {+ "Favorite group $targetGroupId belongs to provider ${group.providerId}, not $providerId"+ }+ require(group.contentType == contentType) {+ "Favorite group $targetGroupId accepts ${group.contentType}, not $contentType"+ }+ }}@Dao@@ -2577,6 +2852,12 @@ interface VirtualGroupDao {@Query("SELECT * FROM virtual_groups WHERE provider_id IN (:providerIds) AND content_type = :contentType ORDER BY provider_id ASC, position ASC")fun getByTypeForProviders(providerIds: List<Long>, contentType: String): Flow<List<VirtualGroupEntity>>+ @Query("SELECT * FROM virtual_groups WHERE id = :id")+ suspend fun getById(id: Long): VirtualGroupEntity?++ @Query("SELECT MAX(position) FROM virtual_groups WHERE provider_id = :providerId AND content_type = :contentType")+ suspend fun getMaxPosition(providerId: Long, contentType: String): Int?+@Insert(onConflict = OnConflictStrategy.REPLACE)suspend fun insert(group: VirtualGroupEntity): Long@@ -2596,6 +2877,9 @@ interface PlaybackHistoryDao {@Query("SELECT * FROM playback_history WHERE provider_id = :providerId ORDER BY last_watched_at DESC LIMIT :limit")fun getRecentlyWatchedByProvider(providerId: Long, limit: Int = 100): Flow<List<PlaybackHistoryLiteEntity>>+ @Query("SELECT * FROM playback_history WHERE provider_id IN (:providerIds) ORDER BY last_watched_at DESC LIMIT :limit")+ fun getRecentlyWatchedByProviders(providerIds: Set<Long>, limit: Int = 100): Flow<List<PlaybackHistoryLiteEntity>>+@Query("SELECT * FROM playback_history WHERE provider_id = :providerId ORDER BY last_watched_at DESC")fun getByProvider(providerId: Long): Flow<List<PlaybackHistoryLiteEntity>>@@ -2652,6 +2936,25 @@ interface PlaybackHistoryDao {)suspend fun getLatestSeriesHistoryBySharedTmdb(seriesId: Long, providerId: Long): PlaybackHistoryEntity?+ @Query(+ """+ SELECT * FROM playback_history+ WHERE content_type = 'SERIES_EPISODE'+ AND provider_id = :providerId+ AND series_id = :seriesId+ AND season_number = :seasonNumber+ AND episode_number = :episodeNumber+ ORDER BY last_watched_at DESC+ LIMIT 1+ """+ )+ suspend fun getLatestEpisodeHistoryByCoordinates(+ providerId: Long,+ seriesId: Long,+ seasonNumber: Int,+ episodeNumber: Int+ ): PlaybackHistoryEntity?+@Insert(onConflict = OnConflictStrategy.REPLACE)suspend fun insertOrUpdate(history: PlaybackHistoryEntity)@@ -2751,10 +3054,10 @@ interface SeriesCategoryHydrationDao {@Daointerface EpgSourceDao {- @Query("SELECT * FROM epg_sources ORDER BY priority ASC, name ASC")+ @Query("SELECT * FROM epg_sources WHERE id > 0 ORDER BY priority ASC, name ASC")fun getAll(): Flow<List<EpgSourceEntity>>- @Query("SELECT * FROM epg_sources ORDER BY priority ASC, name ASC")+ @Query("SELECT * FROM epg_sources WHERE id > 0 ORDER BY priority ASC, name ASC")suspend fun getAllSync(): List<EpgSourceEntity>@Query("SELECT * FROM epg_sources WHERE id = :id")@@ -2763,7 +3066,7 @@ interface EpgSourceDao {@Query("SELECT * FROM epg_sources WHERE url = :url LIMIT 1")suspend fun getByUrl(url: String): EpgSourceEntity?- @Query("SELECT * FROM epg_sources WHERE enabled = 1 ORDER BY priority ASC, name ASC")+ @Query("SELECT * FROM epg_sources WHERE id > 0 AND enabled = 1 ORDER BY priority ASC, name ASC")suspend fun getEnabled(): List<EpgSourceEntity>@Insert(onConflict = OnConflictStrategy.ABORT)@@ -2930,7 +3233,7 @@ interface EpgProgrammeDao {AND xmltv_channel_id = :channelIdAND end_time > :now""")- suspend fun countUpcomingForChannel(sourceId: Long, channelId: String, now: Long = System.currentTimeMillis()): Int+ suspend fun countUpcomingForChannel(sourceId: Long, channelId: String, now: Long): Int}@Daodiff --git a/data/src/main/java/com/streamvault/data/local/dao/RecordingDaos.kt b/data/src/main/java/com/streamvault/data/local/dao/RecordingDaos.ktindex e50debde..8c29715e 100644--- a/data/src/main/java/com/streamvault/data/local/dao/RecordingDaos.kt+++ b/data/src/main/java/com/streamvault/data/local/dao/RecordingDaos.kt@@ -30,6 +30,9 @@ interface RecordingScheduleDao {@Daointerface RecordingRunDao {+ @Query("SELECT id FROM recording_runs WHERE provider_id = :providerId")+ suspend fun getIdsByProvider(providerId: Long): List<String>+@Query("""SELECT@@ -156,15 +159,17 @@ interface RecordingStorageDao {@Daointerface ProgramReminderDao {+ @Query("SELECT id FROM program_reminders WHERE provider_id = :providerId")+ suspend fun getIdsByProvider(providerId: Long): List<Long>+@Query("""SELECT * FROM program_remindersWHERE is_dismissed = 0- AND program_start_time >= :nowORDER BY remind_at ASC, program_start_time ASC""")- fun observeUpcoming(now: Long = System.currentTimeMillis()): Flow<List<ProgramReminderEntity>>+ fun observeUpcoming(): Flow<List<ProgramReminderEntity>>@Query("""diff --git a/data/src/main/java/com/streamvault/data/local/entity/Entities.kt b/data/src/main/java/com/streamvault/data/local/entity/Entities.ktindex a79664fa..632734b6 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@@ -182,7 +182,11 @@ data class PlaybackCompatibilityRecordEntity(indices = [Index(value = ["provider_id"]),Index(value = ["provider_id", "category_id"]),- Index(value = ["provider_id", "stream_id"], unique = true)+ Index(value = ["provider_id", "stream_id"], unique = true),+ Index(name = "index_movies_provider_id_name_id", value = ["provider_id", "name", "id"]),+ Index(name = "index_movies_provider_id_category_id_name_id", value = ["provider_id", "category_id", "name", "id"]),+ Index(name = "index_movies_provider_id_rating_name_id", value = ["provider_id", "rating", "name", "id"]),+ Index(name = "index_movies_provider_id_added_at_release_date_name_id", value = ["provider_id", "added_at", "release_date", "name", "id"])])data class MovieEntity(@@ -250,7 +254,11 @@ data class MovieBrowseEntity(indices = [Index(value = ["provider_id"]),Index(value = ["provider_id", "category_id"]),- Index(value = ["provider_id", "series_id"], unique = true)+ Index(value = ["provider_id", "series_id"], unique = true),+ Index(name = "index_series_provider_id_name_id", value = ["provider_id", "name", "id"]),+ Index(name = "index_series_provider_id_category_id_name_id", value = ["provider_id", "category_id", "name", "id"]),+ Index(name = "index_series_provider_id_rating_name_id", value = ["provider_id", "rating", "name", "id"]),+ Index(name = "index_series_provider_id_last_modified_name_id", value = ["provider_id", "last_modified", "name", "id"])])data class SeriesEntity(@@ -486,7 +494,7 @@ data class MovieImportStageEntity(@Entity(tableName = "series_import_stage",- primaryKeys = ["session_id", "provider_id", "series_id"],+ primaryKeys = ["session_id", "provider_id", "provider_series_key"],foreignKeys = [ForeignKey(entity = ProviderEntity::class,parentColumns = ["id"],@@ -502,6 +510,8 @@ data class SeriesImportStageEntity(@ColumnInfo(name = "session_id") val sessionId: Long,@ColumnInfo(name = "provider_id") val providerId: Long,@ColumnInfo(name = "series_id") val seriesId: Long,+ @ColumnInfo(name = "provider_series_id") val providerSeriesId: String? = null,+ @ColumnInfo(name = "provider_series_key") val providerSeriesKey: String = providerSeriesId?.takeIf { it.isNotBlank() } ?: seriesId.toString(),val name: String,@ColumnInfo(name = "poster_url") val posterUrl: String? = null,@ColumnInfo(name = "backdrop_url") val backdropUrl: String? = null,@@ -609,7 +619,7 @@ data class ProgramBrowseEntity()],indices = [- Index(value = ["provider_id", "content_id", "content_type", "group_id"], unique = true),+ Index(value = ["provider_id", "content_id", "content_type", "group_key"], unique = true),Index(value = ["provider_id", "content_type", "group_id"]),Index(value = ["group_id", "position"])]@@ -622,6 +632,7 @@ data class FavoriteEntity(@ColumnInfo(name = "content_type") val contentType: ContentType,val position: Int = 0,@ColumnInfo(name = "group_id") val groupId: Long? = null,+ @ColumnInfo(name = "group_key") val groupKey: Long = groupId ?: 0L,@ColumnInfo(name = "added_at") val addedAt: Long = System.currentTimeMillis())@@ -666,7 +677,9 @@ data class CategoryCount(indices = [Index(value = ["content_id", "content_type", "provider_id"], unique = true),Index(value = ["last_watched_at"]),- Index(value = ["provider_id"])+ Index(value = ["provider_id"]),+ Index(name = "index_playback_history_provider_id_content_type_content_id", value = ["provider_id", "content_type", "content_id"]),+ Index(name = "index_playback_history_provider_id_content_type_last_watched_at", value = ["provider_id", "content_type", "last_watched_at"])])data class PlaybackHistoryEntity(diff --git a/data/src/main/java/com/streamvault/data/manager/BackupManagerImpl.kt b/data/src/main/java/com/streamvault/data/manager/BackupManagerImpl.ktindex 409a614e..23efde8c 100644--- a/data/src/main/java/com/streamvault/data/manager/BackupManagerImpl.kt+++ b/data/src/main/java/com/streamvault/data/manager/BackupManagerImpl.kt@@ -5,13 +5,16 @@ import android.net.Uriimport com.google.gson.Gsonimport com.google.gson.reflect.TypeTokenimport com.google.gson.stream.JsonWriter+import com.streamvault.data.local.DatabaseTransactionRunnerimport com.streamvault.data.local.dao.EpisodeDaoimport com.streamvault.data.local.dao.FavoriteDaoimport com.streamvault.data.local.dao.MovieDaoimport com.streamvault.data.local.dao.PlaybackHistoryDaoimport com.streamvault.data.local.dao.ProviderDao+import com.streamvault.data.local.dao.RecordingScheduleDaoimport com.streamvault.data.local.dao.VirtualGroupDaoimport com.streamvault.data.local.entity.ProviderEntity+import com.streamvault.data.local.entity.RecordingScheduleEntityimport com.streamvault.data.mapper.toDomainimport com.streamvault.data.mapper.toEntityimport com.streamvault.data.preferences.ParentalPinBackupData@@ -23,6 +26,9 @@ import com.streamvault.domain.manager.BackupImportPlanimport com.streamvault.domain.manager.BackupImportResultimport com.streamvault.domain.manager.BackupManagerimport com.streamvault.domain.manager.BackupPreview+import com.streamvault.domain.manager.RecordingScheduleImportDisposition+import com.streamvault.domain.manager.RecordingScheduleImportOutcome+import com.streamvault.domain.manager.RecordingScheduleImportSummaryimport com.streamvault.domain.manager.ProtectedCategoryBackupimport com.streamvault.domain.manager.RecordingManagerimport com.streamvault.domain.manager.ScheduledRecordingBackup@@ -57,7 +63,9 @@ class BackupManagerImpl @Inject constructor(private val movieDao: MovieDao,private val episodeDao: EpisodeDao,private val categoryRepository: CategoryRepository,+ private val recordingScheduleDao: RecordingScheduleDao,private val recordingManager: RecordingManager,+ private val transactionRunner: DatabaseTransactionRunner,private val gson: Gson) : BackupManager {@@ -152,22 +160,15 @@ class BackupManagerImpl @Inject constructor(.filter { it.status == RecordingStatus.SCHEDULED && it.scheduledEndMs > System.currentTimeMillis() }.mapNotNull { item ->val provider = providersById[item.providerId] ?: return@mapNotNull null- ScheduledRecordingBackup(- providerServerUrl = provider.serverUrl,- providerUsername = provider.username,- providerStalkerMacAddress = provider.stalkerMacAddress.takeIf { it.isNotBlank() },- channelId = item.channelId,- channelName = item.channelName,- streamUrl = item.streamUrl,- scheduledStartMs = item.scheduledStartMs,- scheduledEndMs = item.scheduledEndMs,- programTitle = item.programTitle,- recurrence = item.recurrence+ item.toScheduledRecordingBackup(+ provider = provider,+ schedule = item.scheduleId?.let { scheduleId -> recordingScheduleDao.getById(scheduleId) })}+ .normalizedRecurringBackups()val backupData = BackupData(- version = 5,+ version = CURRENT_BACKUP_VERSION,preferences = prefs,providers = providers,favorites = allFavorites,@@ -198,7 +199,7 @@ class BackupManagerImpl @Inject constructor(try {val backupData = readBackupData(uriString)?: return@withContext Result.error("Failed to open input stream")- if (backupData.version > 5) {+ if (backupData.version > CURRENT_BACKUP_VERSION) {return@withContext Result.error("Unsupported backup version")}if (!verifyChecksum(backupData)) {@@ -266,7 +267,7 @@ class BackupManagerImpl @Inject constructor(type == incoming.type}}- val recordingConflicts = backupData.scheduledRecordings.orEmpty().count { incoming ->+ val recordingConflicts = backupData.scheduledRecordings.orEmpty().normalizedRecurringBackups().count { incoming ->val provider = existingProviders.findMatchingProvider(serverUrl = incoming.providerServerUrl,username = incoming.providerUsername,@@ -289,7 +290,7 @@ class BackupManagerImpl @Inject constructor(multiViewPresetCount = backupData.multiViewPresets.orEmpty().count { it.value.isNotEmpty() },preferenceCount = backupData.preferences.orEmpty().size,protectedCategoryCount = backupData.protectedCategories.orEmpty().size,- scheduledRecordingCount = backupData.scheduledRecordings.orEmpty().size,+ scheduledRecordingCount = backupData.scheduledRecordings.orEmpty().normalizedRecurringBackups().size,providerConflicts = providerConflicts,favoriteConflicts = favoriteConflicts,groupConflicts = groupConflicts,@@ -311,7 +312,7 @@ class BackupManagerImpl @Inject constructor(val backupData = readBackupData(uriString)?: return@withContext com.streamvault.domain.model.Result.error("Failed to open input stream")- if (backupData.version > 5) {+ if (backupData.version > CURRENT_BACKUP_VERSION) {return@withContext com.streamvault.domain.model.Result.error("Unsupported backup version")}if (!verifyChecksum(backupData)) {@@ -323,234 +324,25 @@ class BackupManagerImpl @Inject constructor(val importedSections = mutableListOf<String>()val skippedSections = mutableListOf<String>()- // 2. Restore Preferences- if (plan.importPreferences) {- backupData.preferences?.let { prefs ->- prefs["parentalControlLevel"]?.toIntOrNull()?.let {- preferencesRepository.setParentalControlLevel(it)- }- preferencesRepository.restoreParentalPinBackup(- ParentalPinBackupData(- hash = prefs["parentalPinHash"].orEmpty(),- saltBase64 = prefs["parentalPinSalt"].orEmpty()- ).takeIf { it.hash.isNotBlank() && it.saltBase64.isNotBlank() }- )- prefs["appLanguage"]?.takeIf { it.isNotBlank() }?.let { preferencesRepository.setAppLanguage(it) }- prefs["liveTvCategoryFilters"]?.let { preferencesRepository.setLiveTvCategoryFilters(it.split('\n')) }- prefs["liveTvQuickFilterVisibility"]?.takeIf { it.isNotBlank() }- ?.let { preferencesRepository.setLiveTvQuickFilterVisibility(it) }- prefs["playerMediaSessionEnabled"]?.toBooleanStrictOrNull()- ?.let { preferencesRepository.setPlayerMediaSessionEnabled(it) }- prefs["playerDecoderMode"]?.takeIf { it.isNotBlank() }?.let { savedMode ->- val decoderMode = com.streamvault.domain.model.DecoderMode.entries- .firstOrNull { entry -> entry.name == savedMode }- if (decoderMode != null) {- preferencesRepository.setPlayerDecoderMode(decoderMode)- }- }- prefs["playerSurfaceMode"]?.takeIf { it.isNotBlank() }?.let { savedMode ->- val surfaceMode = com.streamvault.domain.model.PlayerSurfaceMode.entries- .firstOrNull { entry -> entry.name == savedMode }- if (surfaceMode != null) {- preferencesRepository.setPlayerSurfaceMode(surfaceMode)- }- }- prefs["playerPlaybackSpeed"]?.toFloatOrNull()?.let { preferencesRepository.setPlayerPlaybackSpeed(it) }- prefs["playerAudioVideoOffsetMs"]?.toIntOrNull()?.let {- preferencesRepository.setPlayerAudioVideoOffsetMs(it)- }- preferencesRepository.setPreferredAudioLanguage(prefs["preferredAudioLanguage"])- prefs["playerSubtitleTextScale"]?.toFloatOrNull()?.let { preferencesRepository.setPlayerSubtitleTextScale(it) }- prefs["playerSubtitleTextColor"]?.toIntOrNull()?.let { preferencesRepository.setPlayerSubtitleTextColor(it) }- prefs["playerSubtitleBackgroundColor"]?.toIntOrNull()?.let { preferencesRepository.setPlayerSubtitleBackgroundColor(it) }- preferencesRepository.setPlayerWifiMaxVideoHeight(prefs["playerWifiMaxVideoHeight"]?.toIntOrNull()?.takeIf { it > 0 })- preferencesRepository.setPlayerEthernetMaxVideoHeight(prefs["playerEthernetMaxVideoHeight"]?.toIntOrNull()?.takeIf { it > 0 })- prefs["guideDensity"]?.takeIf { it.isNotBlank() }?.let { preferencesRepository.setGuideDensity(it) }- prefs["guideChannelMode"]?.takeIf { it.isNotBlank() }?.let { preferencesRepository.setGuideChannelMode(it) }- prefs["guideDefaultCategoryId"]?.toLongOrNull()?.takeIf { it != 0L }?.let {- preferencesRepository.setGuideDefaultCategoryId(it)- }- prefs["guideFavoritesOnly"]?.toBooleanStrictOrNull()?.let { preferencesRepository.setGuideFavoritesOnly(it) }- prefs["guideAnchorTime"]?.toLongOrNull()?.takeIf { it > 0L }?.let { preferencesRepository.setGuideAnchorTime(it) }- prefs["promotedLiveGroupIds"]?.let { token ->- preferencesRepository.setPromotedLiveGroupIds(- token.split(",").mapNotNull { it.toLongOrNull() }.toSet()- )- }- importedSections += "Preferences"- } ?: run { skippedSections += "Preferences" }- } else {+ val importedPreferences = if (plan.importPreferences) backupData.preferences else null+ if (!plan.importPreferences) {skippedSections += "Preferences"}- if (plan.importProviders) {- backupData.providers?.let { providers ->- providers.forEach { provider ->- val existing = storedProviders.findMatchingProvider(- serverUrl = provider.serverUrl,- username = provider.username,- stalkerMacAddress = provider.stalkerMacAddress- )- if (existing != null && plan.conflictStrategy == BackupConflictStrategy.KEEP_EXISTING) {- return@forEach- }- val entity = provider.copy(- id = existing?.id ?: 0L // 0 = let Room auto-assign PK; avoids ID collision on import- ).toSecureEntityForBackup(credentialCrypto)- providerDao.insert(entity)- }- storedProviders = providerDao.getAllSync()- val providerIdMap = backupData.providers.orEmpty().mapNotNull { provider ->- storedProviders.findMatchingProvider(- serverUrl = provider.serverUrl,- username = provider.username,- stalkerMacAddress = provider.stalkerMacAddress- )?.let { stored ->- provider.id to stored.id- }- }.toMap()- backupData.preferences- ?.get("lastActiveProviderId")- ?.toLongOrNull()- ?.let { backupProviderId ->- providerIdMap[backupProviderId]- }- ?.let { resolvedProviderId ->- providerDao.setActive(resolvedProviderId)- }- importedSections += "Providers"- } ?: run { skippedSections += "Providers" }- } else {- skippedSections += "Providers"- }-- // 3. Restore Virtual Groups- if (plan.importSavedLibrary) {- val providerIdMap = backupData.providers.orEmpty().mapNotNull { provider ->- storedProviders.findMatchingProvider(- serverUrl = provider.serverUrl,- username = provider.username,- stalkerMacAddress = provider.stalkerMacAddress- )?.let { stored ->- provider.id to stored.id- }- }.toMap()- val groupIdMap = mutableMapOf<Long, Long>()- backupData.virtualGroups?.let { groups ->- val existingGroups = buildList {- providerIdMap.values.distinct().forEach { providerId ->- addAll(virtualGroupDao.getByType(providerId, "LIVE").first())- addAll(virtualGroupDao.getByType(providerId, "MOVIE").first())- addAll(virtualGroupDao.getByType(providerId, "SERIES").first())- }- }- groups.forEach { group ->- val resolvedProviderId = providerIdMap[group.providerId] ?: return@forEach- val conflict = existingGroups.firstOrNull {- it.providerId == resolvedProviderId &&- it.name.equals(group.name, ignoreCase = true) &&- it.contentType == group.contentType- }- if (conflict != null && plan.conflictStrategy == BackupConflictStrategy.KEEP_EXISTING) {- groupIdMap[group.id] = conflict.id- return@forEach- }- val insertedId = virtualGroupDao.insert(- group.copy(id = 0L, providerId = resolvedProviderId).toEntity()- )- groupIdMap[group.id] = insertedId- }- } ?: run { skippedSections += "Saved Library" }-- // 4. Restore Favorites- backupData.favorites?.let { favs ->- favs.forEach { fav ->- val resolvedProviderId = providerIdMap[fav.providerId] ?: return@forEach- val resolvedGroupId = fav.groupId?.let { groupIdMap[it] }- val existing = favoriteDao.get(- providerId = resolvedProviderId,- contentId = fav.contentId,- contentType = fav.contentType.name,- groupId = resolvedGroupId- )- if (existing != null && plan.conflictStrategy == BackupConflictStrategy.KEEP_EXISTING) {- return@forEach- }- favoriteDao.insert(- fav.copy(- id = 0L,- providerId = resolvedProviderId,- groupId = resolvedGroupId- ).toEntity()- )- }- }- val categoriesByProviderId = mutableMapOf<Long, List<com.streamvault.domain.model.Category>>()- backupData.protectedCategories?.forEach { protectedCategory ->- val provider = storedProviders.findMatchingProvider(- serverUrl = protectedCategory.providerServerUrl,- username = protectedCategory.providerUsername,- stalkerMacAddress = protectedCategory.providerStalkerMacAddress- ) ?: return@forEach- val categories = categoriesByProviderId.getOrPut(provider.id) {- categoryRepository.getCategories(provider.id).first()- }- val resolvedCategory = categories.firstOrNull {- it.type == protectedCategory.type && it.id == protectedCategory.categoryId- } ?: categories.firstOrNull {- it.type == protectedCategory.type &&- it.name.equals(protectedCategory.categoryName, ignoreCase = true)- }- if (resolvedCategory == null) {- return@forEach- }- if (plan.conflictStrategy == BackupConflictStrategy.KEEP_EXISTING && resolvedCategory.isUserProtected) {- return@forEach- }- categoryRepository.setCategoryProtection(- providerId = provider.id,- categoryId = resolvedCategory.id,- type = resolvedCategory.type,- isProtected = true- )- }- importedSections += "Saved Library"- } else {- skippedSections += "Saved Library"- }+ val roomRestoreResult = restoreRoomBackedSections(+ backupData = backupData,+ plan = plan,+ initialStoredProviders = storedProviders+ )+ storedProviders = roomRestoreResult.storedProviders+ importedSections += roomRestoreResult.importedSections+ skippedSections += roomRestoreResult.skippedSections- if (plan.importPlaybackHistory) {- backupData.playbackHistory?.let { history ->- val providerIdMap = backupData.providers.orEmpty().mapNotNull { provider ->- storedProviders.findMatchingProvider(- serverUrl = provider.serverUrl,- username = provider.username,- stalkerMacAddress = provider.stalkerMacAddress- )?.let { stored ->- provider.id to stored.id- }- }.toMap()- if (plan.conflictStrategy == BackupConflictStrategy.REPLACE_EXISTING) {- playbackHistoryDao.deleteAll()- }- history.forEach { item ->- val resolvedProviderId = providerIdMap[item.providerId] ?: return@forEach- if (plan.conflictStrategy == BackupConflictStrategy.KEEP_EXISTING) {- val existing = playbackHistoryDao.get(- contentId = item.contentId,- contentType = item.contentType.name,- providerId = resolvedProviderId- )- if (existing != null) return@forEach- }- playbackHistoryDao.insertOrUpdate(item.copy(providerId = resolvedProviderId).toEntity())- }- movieDao.syncAllWatchProgressFromHistory()- episodeDao.syncAllWatchProgressFromHistory()- importedSections += "Playback History"- } ?: run { skippedSections += "Playback History" }- } else {- skippedSections += "Playback History"+ if (plan.importPreferences) {+ importedPreferences?.let { prefs ->+ restorePreferences(prefs)+ importedSections += "Preferences"+ } ?: run { skippedSections += "Preferences" }}if (plan.importMultiViewPresets) {@@ -564,50 +356,28 @@ class BackupManagerImpl @Inject constructor(skippedSections += "Split Screen Presets"}- if (plan.importRecordingSchedules) {+ val recordingScheduleImport = if (plan.importRecordingSchedules) {backupData.scheduledRecordings?.let { recordings ->- val existingSchedules = recordingManager.observeRecordingItems().first()- .filter { it.status == RecordingStatus.SCHEDULED }- .toMutableList()- recordings.forEach { scheduled ->- if (scheduled.scheduledEndMs <= System.currentTimeMillis()) {- return@forEach- }- val provider = storedProviders.findMatchingProvider(- serverUrl = scheduled.providerServerUrl,- username = scheduled.providerUsername,- stalkerMacAddress = scheduled.providerStalkerMacAddress- ) ?: return@forEach- val conflict = existingSchedules.firstOrNull {- it.providerId == provider.id &&- it.scheduledStartMs == scheduled.scheduledStartMs &&- (it.channelId == scheduled.channelId || it.streamUrl == scheduled.streamUrl)- }- if (conflict != null) {- if (plan.conflictStrategy == BackupConflictStrategy.KEEP_EXISTING) {- return@forEach- }- recordingManager.cancelRecording(conflict.id)- existingSchedules.remove(conflict)- }- val result = recordingManager.scheduleRecording(- RecordingRequest(- providerId = provider.id,- channelId = scheduled.channelId,- channelName = scheduled.channelName,- streamUrl = scheduled.streamUrl,- scheduledStartMs = scheduled.scheduledStartMs,- scheduledEndMs = scheduled.scheduledEndMs,- programTitle = scheduled.programTitle,- recurrence = scheduled.recurrence- )- )- if (result is Result.Success) {- existingSchedules += result.data- }- }- importedSections += "Recording Schedules"- } ?: run { skippedSections += "Recording Schedules" }+ importScheduledRecordingBackups(+ recordings = recordings.normalizedRecurringBackups(),+ storedProviders = storedProviders,+ existingSchedules = recordingManager.observeRecordingItems().first()+ .filter { it.status == RecordingStatus.SCHEDULED }+ .toMutableList(),+ conflictStrategy = plan.conflictStrategy,+ recordingManager = recordingManager+ )+ }+ } else {+ null+ }++ if (plan.importRecordingSchedules) {+ when {+ recordingScheduleImport == null -> skippedSections += "Recording Schedules"+ recordingScheduleImport.importedCount > 0 -> importedSections += "Recording Schedules"+ else -> skippedSections += "Recording Schedules"+ }} else {skippedSections += "Recording Schedules"}@@ -615,7 +385,8 @@ class BackupManagerImpl @Inject constructor(com.streamvault.domain.model.Result.success(BackupImportResult(importedSections = importedSections.distinct(),- skippedSections = skippedSections.distinct()+ skippedSections = skippedSections.distinct(),+ recordingScheduleImport = recordingScheduleImport))} catch (e: Exception) {@@ -707,8 +478,470 @@ class BackupManagerImpl @Inject constructor(}}}++ private suspend fun restorePreferences(prefs: Map<String, String>) {+ prefs["parentalControlLevel"]?.toIntOrNull()?.let {+ preferencesRepository.setParentalControlLevel(it)+ }+ preferencesRepository.restoreParentalPinBackup(+ ParentalPinBackupData(+ hash = prefs["parentalPinHash"].orEmpty(),+ saltBase64 = prefs["parentalPinSalt"].orEmpty()+ ).takeIf { it.hash.isNotBlank() && it.saltBase64.isNotBlank() }+ )+ prefs["appLanguage"]?.takeIf { it.isNotBlank() }?.let { preferencesRepository.setAppLanguage(it) }+ prefs["liveTvCategoryFilters"]?.let { preferencesRepository.setLiveTvCategoryFilters(it.split('\n')) }+ prefs["liveTvQuickFilterVisibility"]?.takeIf { it.isNotBlank() }+ ?.let { preferencesRepository.setLiveTvQuickFilterVisibility(it) }+ prefs["playerMediaSessionEnabled"]?.toBooleanStrictOrNull()+ ?.let { preferencesRepository.setPlayerMediaSessionEnabled(it) }+ prefs["playerDecoderMode"]?.takeIf { it.isNotBlank() }?.let { savedMode ->+ val decoderMode = com.streamvault.domain.model.DecoderMode.entries+ .firstOrNull { entry -> entry.name == savedMode }+ if (decoderMode != null) {+ preferencesRepository.setPlayerDecoderMode(decoderMode)+ }+ }+ prefs["playerSurfaceMode"]?.takeIf { it.isNotBlank() }?.let { savedMode ->+ val surfaceMode = com.streamvault.domain.model.PlayerSurfaceMode.entries+ .firstOrNull { entry -> entry.name == savedMode }+ if (surfaceMode != null) {+ preferencesRepository.setPlayerSurfaceMode(surfaceMode)+ }+ }+ prefs["playerPlaybackSpeed"]?.toFloatOrNull()?.let { preferencesRepository.setPlayerPlaybackSpeed(it) }+ prefs["playerAudioVideoOffsetMs"]?.toIntOrNull()?.let {+ preferencesRepository.setPlayerAudioVideoOffsetMs(it)+ }+ preferencesRepository.setPreferredAudioLanguage(prefs["preferredAudioLanguage"])+ prefs["playerSubtitleTextScale"]?.toFloatOrNull()?.let { preferencesRepository.setPlayerSubtitleTextScale(it) }+ prefs["playerSubtitleTextColor"]?.toIntOrNull()?.let { preferencesRepository.setPlayerSubtitleTextColor(it) }+ prefs["playerSubtitleBackgroundColor"]?.toIntOrNull()?.let { preferencesRepository.setPlayerSubtitleBackgroundColor(it) }+ preferencesRepository.setPlayerWifiMaxVideoHeight(prefs["playerWifiMaxVideoHeight"]?.toIntOrNull()?.takeIf { it > 0 })+ preferencesRepository.setPlayerEthernetMaxVideoHeight(prefs["playerEthernetMaxVideoHeight"]?.toIntOrNull()?.takeIf { it > 0 })+ prefs["guideDensity"]?.takeIf { it.isNotBlank() }?.let { preferencesRepository.setGuideDensity(it) }+ prefs["guideChannelMode"]?.takeIf { it.isNotBlank() }?.let { preferencesRepository.setGuideChannelMode(it) }+ prefs["guideDefaultCategoryId"]?.toLongOrNull()?.takeIf { it != 0L }?.let {+ preferencesRepository.setGuideDefaultCategoryId(it)+ }+ prefs["guideFavoritesOnly"]?.toBooleanStrictOrNull()?.let { preferencesRepository.setGuideFavoritesOnly(it) }+ prefs["guideAnchorTime"]?.toLongOrNull()?.takeIf { it > 0L }?.let { preferencesRepository.setGuideAnchorTime(it) }+ prefs["promotedLiveGroupIds"]?.let { token ->+ preferencesRepository.setPromotedLiveGroupIds(+ token.split(",").mapNotNull { it.toLongOrNull() }.toSet()+ )+ }+ }++ private suspend fun restoreRoomBackedSections(+ backupData: BackupData,+ plan: BackupImportPlan,+ initialStoredProviders: List<ProviderEntity>+ ): RoomRestoreResult {+ if (!plan.importProviders && !plan.importSavedLibrary && !plan.importPlaybackHistory) {+ return RoomRestoreResult(+ storedProviders = initialStoredProviders,+ importedSections = emptyList(),+ skippedSections = buildList {+ add("Providers")+ add("Saved Library")+ add("Playback History")+ }+ )+ }++ var storedProviders = initialStoredProviders+ val importedSections = mutableListOf<String>()+ val skippedSections = mutableListOf<String>()++ transactionRunner.inTransaction {+ if (plan.importProviders) {+ backupData.providers?.let { providers ->+ providers.forEach { provider ->+ val existing = storedProviders.findMatchingProvider(+ serverUrl = provider.serverUrl,+ username = provider.username,+ stalkerMacAddress = provider.stalkerMacAddress+ )+ if (existing != null && plan.conflictStrategy == BackupConflictStrategy.KEEP_EXISTING) {+ return@forEach+ }+ val entity = provider.copy(+ id = existing?.id ?: 0L+ ).toSecureEntityForBackup(credentialCrypto)+ providerDao.insert(entity)+ }+ storedProviders = providerDao.getAllSync()+ backupData.preferences+ ?.get("lastActiveProviderId")+ ?.toLongOrNull()+ ?.let { backupProviderId ->+ resolveProviderIdMap(storedProviders, providers)[backupProviderId]+ }+ ?.let { resolvedProviderId ->+ providerDao.setActive(resolvedProviderId)+ }+ importedSections += "Providers"+ } ?: run { skippedSections += "Providers" }+ } else {+ skippedSections += "Providers"+ }++ if (plan.importSavedLibrary) {+ restoreSavedLibrary(+ backupData = backupData,+ storedProviders = storedProviders,+ conflictStrategy = plan.conflictStrategy+ )+ importedSections += "Saved Library"+ } else {+ skippedSections += "Saved Library"+ }++ if (plan.importPlaybackHistory) {+ backupData.playbackHistory?.let { history ->+ restorePlaybackHistory(+ history = history,+ storedProviders = storedProviders,+ backupProviders = backupData.providers.orEmpty(),+ conflictStrategy = plan.conflictStrategy+ )+ importedSections += "Playback History"+ } ?: run { skippedSections += "Playback History" }+ } else {+ skippedSections += "Playback History"+ }+ }++ return RoomRestoreResult(+ storedProviders = storedProviders,+ importedSections = importedSections,+ skippedSections = skippedSections+ )+ }++ private suspend fun restoreSavedLibrary(+ backupData: BackupData,+ storedProviders: List<ProviderEntity>,+ conflictStrategy: BackupConflictStrategy+ ) {+ val providerIdMap = resolveProviderIdMap(storedProviders, backupData.providers.orEmpty())+ val groupIdMap = mutableMapOf<Long, Long>()+ backupData.virtualGroups?.let { groups ->+ val existingGroups = buildList {+ providerIdMap.values.distinct().forEach { providerId ->+ addAll(virtualGroupDao.getByType(providerId, "LIVE").first())+ addAll(virtualGroupDao.getByType(providerId, "MOVIE").first())+ addAll(virtualGroupDao.getByType(providerId, "SERIES").first())+ }+ }+ groups.forEach { group ->+ val resolvedProviderId = providerIdMap[group.providerId] ?: return@forEach+ val conflict = existingGroups.firstOrNull {+ it.providerId == resolvedProviderId &&+ it.name.equals(group.name, ignoreCase = true) &&+ it.contentType == group.contentType+ }+ if (conflict != null && conflictStrategy == BackupConflictStrategy.KEEP_EXISTING) {+ groupIdMap[group.id] = conflict.id+ return@forEach+ }+ val insertedId = virtualGroupDao.insert(+ group.copy(id = 0L, providerId = resolvedProviderId).toEntity()+ )+ groupIdMap[group.id] = insertedId+ }+ }++ backupData.favorites?.let { favorites ->+ favorites.forEach { favorite ->+ val resolvedProviderId = providerIdMap[favorite.providerId] ?: return@forEach+ val resolvedGroupId = favorite.groupId?.let { groupIdMap[it] }+ val existing = favoriteDao.get(+ providerId = resolvedProviderId,+ contentId = favorite.contentId,+ contentType = favorite.contentType.name,+ groupId = resolvedGroupId+ )+ if (existing != null && conflictStrategy == BackupConflictStrategy.KEEP_EXISTING) {+ return@forEach+ }+ favoriteDao.insert(+ favorite.copy(+ id = 0L,+ providerId = resolvedProviderId,+ groupId = resolvedGroupId+ ).toEntity()+ )+ }+ }++ val categoriesByProviderId = mutableMapOf<Long, List<com.streamvault.domain.model.Category>>()+ backupData.protectedCategories?.forEach { protectedCategory ->+ val provider = storedProviders.findMatchingProvider(+ serverUrl = protectedCategory.providerServerUrl,+ username = protectedCategory.providerUsername,+ stalkerMacAddress = protectedCategory.providerStalkerMacAddress+ ) ?: return@forEach+ val categories = categoriesByProviderId.getOrPut(provider.id) {+ categoryRepository.getCategories(provider.id).first()+ }+ val resolvedCategory = categories.firstOrNull {+ it.type == protectedCategory.type && it.id == protectedCategory.categoryId+ } ?: categories.firstOrNull {+ it.type == protectedCategory.type &&+ it.name.equals(protectedCategory.categoryName, ignoreCase = true)+ }+ if (resolvedCategory == null) {+ return@forEach+ }+ if (conflictStrategy == BackupConflictStrategy.KEEP_EXISTING && resolvedCategory.isUserProtected) {+ return@forEach+ }+ categoryRepository.setCategoryProtection(+ providerId = provider.id,+ categoryId = resolvedCategory.id,+ type = resolvedCategory.type,+ isProtected = true+ )+ }+ }++ private fun resolveProviderIdMap(+ storedProviders: List<ProviderEntity>,+ backupProviders: List<com.streamvault.domain.model.Provider>+ ): Map<Long, Long> = backupProviders.mapNotNull { provider ->+ storedProviders.findMatchingProvider(+ serverUrl = provider.serverUrl,+ username = provider.username,+ stalkerMacAddress = provider.stalkerMacAddress+ )?.let { stored ->+ provider.id to stored.id+ }+ }.toMap()++ private suspend fun restorePlaybackHistory(+ history: List<com.streamvault.domain.model.PlaybackHistory>,+ storedProviders: List<ProviderEntity>,+ backupProviders: List<com.streamvault.domain.model.Provider>,+ conflictStrategy: BackupConflictStrategy+ ) {+ val providerIdMap = resolveProviderIdMap(storedProviders, backupProviders)++ if (providerIdMap.isEmpty()) {+ return+ }++ val providersToResync = when (conflictStrategy) {+ BackupConflictStrategy.REPLACE_EXISTING -> providerIdMap.values.toMutableSet()+ BackupConflictStrategy.KEEP_EXISTING -> linkedSetOf()+ }++ if (conflictStrategy == BackupConflictStrategy.REPLACE_EXISTING) {+ providerIdMap.values.distinct().forEach { providerId ->+ playbackHistoryDao.deleteByProvider(providerId)+ }+ }++ history.forEach { item ->+ val resolvedProviderId = providerIdMap[item.providerId] ?: return@forEach+ if (conflictStrategy == BackupConflictStrategy.KEEP_EXISTING) {+ val existing = playbackHistoryDao.get(+ contentId = item.contentId,+ contentType = item.contentType.name,+ providerId = resolvedProviderId+ )+ if (existing != null) return@forEach+ }+ playbackHistoryDao.insertOrUpdate(item.copy(providerId = resolvedProviderId).toEntity())+ providersToResync += resolvedProviderId+ }++ providersToResync.forEach { providerId ->+ movieDao.syncWatchProgressFromHistoryByProvider(providerId)+ episodeDao.syncWatchProgressFromHistoryByProvider(providerId)+ }+ }++ private data class RoomRestoreResult(+ val storedProviders: List<ProviderEntity>,+ val importedSections: List<String>,+ val skippedSections: List<String>+ )}+internal fun com.streamvault.domain.model.RecordingItem.toScheduledRecordingBackup(+ provider: com.streamvault.domain.model.Provider,+ schedule: RecordingScheduleEntity?+): ScheduledRecordingBackup {+ val requestedStart = schedule?.requestedStartMs ?: scheduledStartMs+ val requestedEnd = schedule?.requestedEndMs ?: scheduledEndMs+ val paddingBeforeMs = (requestedStart - scheduledStartMs).coerceAtLeast(0L)+ val paddingAfterMs = (scheduledEndMs - requestedEnd).coerceAtLeast(0L)+ return ScheduledRecordingBackup(+ providerServerUrl = provider.serverUrl,+ providerUsername = provider.username,+ providerStalkerMacAddress = provider.stalkerMacAddress.takeIf { it.isNotBlank() },+ channelId = channelId,+ channelName = channelName,+ streamUrl = streamUrl,+ scheduledStartMs = scheduledStartMs,+ scheduledEndMs = scheduledEndMs,+ requestedStartMs = requestedStart,+ requestedEndMs = requestedEnd,+ paddingBeforeMs = paddingBeforeMs,+ paddingAfterMs = paddingAfterMs,+ programTitle = programTitle,+ recurrence = recurrence,+ recurringRuleId = schedule?.recurringRuleId ?: recurringRuleId+ )+}++internal fun ScheduledRecordingBackup.toRecordingRequest(providerId: Long): RecordingRequest {+ val restoredRequestedStartMs = requestedStartMs ?: scheduledStartMs+ val restoredRequestedEndMs = requestedEndMs ?: scheduledEndMs+ val restoredPaddingBeforeMs = paddingBeforeMs+ ?: requestedStartMs?.let { (it - scheduledStartMs).coerceAtLeast(0L) }+ ?: 0L+ val restoredPaddingAfterMs = paddingAfterMs+ ?: requestedEndMs?.let { (scheduledEndMs - it).coerceAtLeast(0L) }+ ?: 0L+ return RecordingRequest(+ providerId = providerId,+ channelId = channelId,+ channelName = channelName,+ streamUrl = streamUrl,+ scheduledStartMs = restoredRequestedStartMs,+ scheduledEndMs = restoredRequestedEndMs,+ programTitle = programTitle,+ recurrence = recurrence,+ recurringRuleId = recurringRuleId,+ paddingBeforeMs = restoredPaddingBeforeMs,+ paddingAfterMs = restoredPaddingAfterMs+ )+}++internal fun List<ScheduledRecordingBackup>.normalizedRecurringBackups(): List<ScheduledRecordingBackup> {+ if (isEmpty()) return emptyList()+ val oneShot = filterNot { it.hasStableRecurringIdentity() }+ val recurring = filter { it.hasStableRecurringIdentity() }+ .groupBy { it.recurringRuleId!! }+ .values+ .map { group ->+ group.minWithOrNull(compareBy<ScheduledRecordingBackup> { it.requestedStartMs ?: it.scheduledStartMs }+ .thenBy { it.requestedEndMs ?: it.scheduledEndMs }+ .thenBy { it.scheduledStartMs }) ?: group.first()+ }+ return (oneShot + recurring).sortedBy { it.requestedStartMs ?: it.scheduledStartMs }+}++internal suspend fun importScheduledRecordingBackups(+ recordings: List<ScheduledRecordingBackup>,+ storedProviders: List<ProviderEntity>,+ existingSchedules: MutableList<com.streamvault.domain.model.RecordingItem>,+ conflictStrategy: BackupConflictStrategy,+ recordingManager: RecordingManager,+ nowMs: Long = System.currentTimeMillis()+): RecordingScheduleImportSummary {+ val outcomes = mutableListOf<RecordingScheduleImportOutcome>()+ recordings.forEach { scheduled ->+ if (scheduled.scheduledEndMs <= nowMs) {+ outcomes += scheduled.toImportOutcome(+ disposition = RecordingScheduleImportDisposition.SKIPPED_EXPIRED,+ reason = "Recording window has already ended."+ )+ return@forEach+ }++ val provider = storedProviders.findMatchingProvider(+ serverUrl = scheduled.providerServerUrl,+ username = scheduled.providerUsername,+ stalkerMacAddress = scheduled.providerStalkerMacAddress+ )+ if (provider == null) {+ outcomes += scheduled.toImportOutcome(+ disposition = RecordingScheduleImportDisposition.SKIPPED_MISSING_PROVIDER,+ reason = "Matching provider was not found during import."+ )+ return@forEach+ }++ val conflict = existingSchedules.firstOrNull {+ it.providerId == provider.id &&+ it.scheduledStartMs == scheduled.scheduledStartMs &&+ (it.channelId == scheduled.channelId || it.streamUrl == scheduled.streamUrl)+ }+ if (conflict != null && conflictStrategy == BackupConflictStrategy.KEEP_EXISTING) {+ outcomes += scheduled.toImportOutcome(+ disposition = RecordingScheduleImportDisposition.SKIPPED_EXISTING,+ reason = "Keeping existing schedule for the same provider, start time, and channel/stream."+ )+ return@forEach+ }+ if (conflict != null && conflictStrategy == BackupConflictStrategy.REPLACE_EXISTING) {+ when (val cancelResult = recordingManager.cancelRecording(conflict.id)) {+ is Result.Success -> existingSchedules.remove(conflict)+ is Result.Error -> {+ outcomes += scheduled.toImportOutcome(+ disposition = RecordingScheduleImportDisposition.FAILED,+ reason = cancelResult.message+ )+ return@forEach+ }+ Result.Loading -> {+ outcomes += scheduled.toImportOutcome(+ disposition = RecordingScheduleImportDisposition.FAILED,+ reason = "Cancellation did not complete."+ )+ return@forEach+ }+ }+ }++ when (val result = recordingManager.scheduleRecording(scheduled.toRecordingRequest(provider.id))) {+ is Result.Success -> {+ existingSchedules += result.data+ outcomes += scheduled.toImportOutcome(+ disposition = if (conflict != null) {+ RecordingScheduleImportDisposition.REPLACED_EXISTING+ } else {+ RecordingScheduleImportDisposition.IMPORTED+ }+ )+ }+ is Result.Error -> {+ outcomes += scheduled.toImportOutcome(+ disposition = RecordingScheduleImportDisposition.FAILED,+ reason = result.message+ )+ }+ Result.Loading -> {+ outcomes += scheduled.toImportOutcome(+ disposition = RecordingScheduleImportDisposition.FAILED,+ reason = "Scheduling did not complete."+ )+ }+ }+ }+ return RecordingScheduleImportSummary(outcomes = outcomes)+}++private fun ScheduledRecordingBackup.toImportOutcome(+ disposition: RecordingScheduleImportDisposition,+ reason: String? = null+): RecordingScheduleImportOutcome = RecordingScheduleImportOutcome(+ channelName = channelName,+ programTitle = programTitle,+ scheduledStartMs = scheduledStartMs,+ scheduledEndMs = scheduledEndMs,+ recurrence = recurrence,+ disposition = disposition,+ reason = reason+)++private fun ScheduledRecordingBackup.hasStableRecurringIdentity(): Boolean =+ recurrence != RecordingRecurrence.NONE && !recurringRuleId.isNullOrBlank()+private fun com.streamvault.domain.model.Provider.toSecureEntityForBackup(credentialCrypto: CredentialCrypto) = copy(password = credentialCrypto.encryptIfNeeded(password)).toEntity()@@ -736,6 +969,7 @@ private fun Iterable<ProviderEntity>.findMatchingProvider(}private const val SHA256_PREFIX = "sha256:"+private const val CURRENT_BACKUP_VERSION = 7private val MAP_STRING_STRING_TYPE: Type = object : TypeToken<Map<String, String>>() {}.typeprivate val PROVIDER_LIST_TYPE: Type = object : TypeToken<List<com.streamvault.domain.model.Provider>>() {}.typeprivate val FAVORITE_LIST_TYPE: Type = object : TypeToken<List<com.streamvault.domain.model.Favorite>>() {}.typediff --git a/data/src/main/java/com/streamvault/data/manager/ProgramReminderManagerImpl.kt b/data/src/main/java/com/streamvault/data/manager/ProgramReminderManagerImpl.ktindex 75d9cfdd..b65a9016 100644--- a/data/src/main/java/com/streamvault/data/manager/ProgramReminderManagerImpl.kt+++ b/data/src/main/java/com/streamvault/data/manager/ProgramReminderManagerImpl.kt@@ -8,20 +8,65 @@ import com.streamvault.domain.manager.ProgramReminderManagerimport com.streamvault.domain.model.Programimport com.streamvault.domain.model.ProgramReminderimport com.streamvault.domain.model.Result+import kotlinx.coroutines.delay+import kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.combine+import kotlinx.coroutines.flow.flowimport javax.inject.Injectimport javax.inject.Singleton-import kotlinx.coroutines.flow.Flowimport kotlinx.coroutines.flow.map+private const val UPCOMING_REMINDER_REFRESH_MS = 15_000L+@Singleton-class ProgramReminderManagerImpl @Inject constructor(+class ProgramReminderManagerImpl private constructor(private val programReminderDao: ProgramReminderDao,private val alarmScheduler: ProgramReminderAlarmScheduler,- private val notifier: ProgramReminderNotifier+ private val notifier: ProgramReminderNotifier,+ private val nowProvider: () -> Long,+ private val upcomingTimeFlow: Flow<Long>) : ProgramReminderManager {+ @Inject+ constructor(+ programReminderDao: ProgramReminderDao,+ alarmScheduler: ProgramReminderAlarmScheduler,+ notifier: ProgramReminderNotifier+ ) : this(+ programReminderDao = programReminderDao,+ alarmScheduler = alarmScheduler,+ notifier = notifier,+ nowProvider = System::currentTimeMillis,+ upcomingTimeFlow = upcomingReminderTimeFlow()+ )++ internal companion object {+ const val REMINDER_STALE_GRACE_MS = 2 * 60_000L++ fun forTesting(+ programReminderDao: ProgramReminderDao,+ alarmScheduler: ProgramReminderAlarmScheduler,+ notifier: ProgramReminderNotifier,+ nowProvider: () -> Long,+ upcomingTimeFlow: Flow<Long>+ ): ProgramReminderManagerImpl = ProgramReminderManagerImpl(+ programReminderDao = programReminderDao,+ alarmScheduler = alarmScheduler,+ notifier = notifier,+ nowProvider = nowProvider,+ upcomingTimeFlow = upcomingTimeFlow+ )+ }+override fun observeUpcomingReminders(): Flow<List<ProgramReminder>> =- programReminderDao.observeUpcoming().map { reminders -> reminders.map { it.asDomain() } }+ programReminderDao.observeUpcoming()+ .combine(upcomingTimeFlow) { reminders, now ->+ reminders+ .asSequence()+ .filter { !it.isDismissed && it.programStartTime >= now }+ .map { it.asDomain() }+ .toList()+ }override suspend fun isReminderScheduled(providerId: Long,@@ -44,6 +89,9 @@ class ProgramReminderManagerImpl @Inject constructor(if (program.startTime <= System.currentTimeMillis()) {return Result.error("This program has already started.")}+ if (!alarmScheduler.canScheduleExactAlarms()) {+ return Result.error(ProgramReminderAlarmScheduler.EXACT_ALARM_PERMISSION_MESSAGE)+ }val now = System.currentTimeMillis()val remindAt = (program.startTime - leadTimeMinutes * 60_000L).coerceAtLeast(now + 1_000L)@@ -67,8 +115,16 @@ class ProgramReminderManagerImpl @Inject constructor(programReminderDao.update(reminder)existing.id}- alarmScheduler.schedule(reminderId, remindAt)- return Result.success(Unit)+ return when (val result = alarmScheduler.schedule(reminderId, remindAt)) {+ is Result.Success -> Result.success(Unit)+ is Result.Error -> {+ if (existing == null) {+ programReminderDao.deleteById(reminderId)+ }+ Result.error(result.message, result.exception)+ }+ Result.Loading -> Result.error("Unexpected reminder scheduling state")+ }}override suspend fun cancelReminder(@@ -87,15 +143,23 @@ class ProgramReminderManagerImpl @Inject constructor(override suspend fun restoreScheduledReminders() {val now = System.currentTimeMillis()programReminderDao.getPendingActive(now).forEach { reminder ->- alarmScheduler.schedule(reminder.id, reminder.remindAt.coerceAtLeast(now + 1_000L))+ when (val result = alarmScheduler.schedule(reminder.id, reminder.remindAt.coerceAtLeast(now + 1_000L))) {+ is Result.Error -> android.util.Log.w("ProgramReminderManager", "Unable to restore reminder ${reminder.id}: ${result.message}")+ else -> Unit+ }}}suspend fun deliverReminder(reminderId: Long) {val reminder = programReminderDao.getById(reminderId) ?: returnif (reminder.isDismissed || reminder.notifiedAt != null) return+ val now = System.currentTimeMillis()+ if (now - reminder.programStartTime > REMINDER_STALE_GRACE_MS) {+ programReminderDao.update(reminder.copy(isDismissed = true))+ return+ }notifier.showReminder(reminder)- programReminderDao.update(reminder.copy(notifiedAt = System.currentTimeMillis()))+ programReminderDao.update(reminder.copy(notifiedAt = now))}private fun ProgramReminderEntity.asDomain(): ProgramReminder = ProgramReminder(@@ -112,3 +176,11 @@ class ProgramReminderManagerImpl @Inject constructor(createdAt = createdAt)}++private fun upcomingReminderTimeFlow(refreshMs: Long = UPCOMING_REMINDER_REFRESH_MS): Flow<Long> = flow {+ emit(System.currentTimeMillis())+ while (true) {+ delay(refreshMs)+ emit(System.currentTimeMillis())+ }+}diff --git a/data/src/main/java/com/streamvault/data/manager/RecordingManagerImpl.kt b/data/src/main/java/com/streamvault/data/manager/RecordingManagerImpl.ktindex 2c6bb70c..ef7384e5 100644--- a/data/src/main/java/com/streamvault/data/manager/RecordingManagerImpl.kt+++ b/data/src/main/java/com/streamvault/data/manager/RecordingManagerImpl.kt@@ -6,6 +6,7 @@ import android.net.NetworkCapabilitiesimport android.util.Logimport com.google.gson.Gsonimport com.google.gson.reflect.TypeToken+import com.streamvault.data.local.DatabaseTransactionRunnerimport com.streamvault.data.local.dao.ProviderDaoimport com.streamvault.data.local.dao.RecordingRunDaoimport com.streamvault.data.local.dao.RecordingScheduleDao@@ -18,6 +19,7 @@ import com.streamvault.data.manager.recording.HlsLiveCaptureEngineimport com.streamvault.data.manager.recording.RecordingAlarmSchedulerimport com.streamvault.data.manager.recording.RecordingForegroundServiceimport com.streamvault.data.manager.recording.RecordingOutputTarget+import com.streamvault.data.manager.recording.RecordingServiceLauncherimport com.streamvault.data.manager.recording.RecordingSourceResolverimport com.streamvault.data.manager.recording.ResolvedRecordingSourceimport com.streamvault.data.manager.recording.TsPassThroughCaptureEngine@@ -74,6 +76,7 @@ private const val FAILURE_NOTIFICATION_ID_BASE = 5000class RecordingManagerImpl @Inject constructor(@ApplicationContext private val context: Context,private val gson: Gson,+ private val transactionRunner: DatabaseTransactionRunner,private val providerDao: ProviderDao,private val recordingScheduleDao: RecordingScheduleDao,private val recordingRunDao: RecordingRunDao,@@ -82,7 +85,8 @@ class RecordingManagerImpl @Inject constructor(private val tsPassThroughCaptureEngine: TsPassThroughCaptureEngine,private val hlsLiveCaptureEngine: HlsLiveCaptureEngine,private val alarmScheduler: RecordingAlarmScheduler,- private val preferencesRepository: PreferencesRepository+ private val preferencesRepository: PreferencesRepository,+ private val recordingServiceLauncher: RecordingServiceLauncher) : RecordingManager {private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)@@ -133,24 +137,8 @@ class RecordingManagerImpl @Inject constructor(if (!storage.isWritable) {return@withContext Result.error("Recording storage is not writable.")}-- val scheduleId = recordingScheduleDao.insert(- RecordingScheduleEntity(- providerId = request.providerId,- channelId = request.channelId,- channelName = request.channelName,- streamUrl = request.streamUrl,- programTitle = request.programTitle,- requestedStartMs = request.scheduledStartMs,- requestedEndMs = request.scheduledEndMs,- recurrence = RecordingRecurrence.NONE,- enabled = true,- isManual = true,- priority = request.priority- )- )-- val recordingId = UUID.randomUUID().toString()+ ensureExactRecordingAlarmsAvailableOrThrow()+ validateRecordingWindowOrThrow(request.scheduledStartMs, request.scheduledEndMs, request.providerId)val source = resolveRecordableSource(request.providerId, request.channelId, request.streamUrl)val outputTarget = createOutputTarget(context = context,@@ -162,50 +150,20 @@ class RecordingManagerImpl @Inject constructor(pattern = storage.fileNamePattern))- val (outputUri, outputDisplayPath) = outputTarget.asPersistenceValues()- val now = System.currentTimeMillis()- val run = RecordingRunEntity(- id = recordingId,- scheduleId = scheduleId,- providerId = request.providerId,- channelId = request.channelId,- channelName = request.channelName,- streamUrl = request.streamUrl,- programTitle = request.programTitle,- scheduledStartMs = request.scheduledStartMs,- scheduledEndMs = request.scheduledEndMs,- recurrence = RecordingRecurrence.NONE,- status = RecordingStatus.RECORDING,- sourceType = source.sourceType,- resolvedUrl = source.url,- headersJson = headersToJson(source.headers),- userAgent = source.userAgent,- expirationTime = source.expirationTime,- providerLabel = source.providerLabel,- outputUri = outputUri,- outputDisplayPath = outputDisplayPath,- startedAtMs = now,- scheduleEnabled = true,- priority = request.priority,- alarmStopAtMs = request.scheduledEndMs,- createdAt = now,- updatedAt = now- )-- recordingMutex.withLock {- validateRecordingWindow(request.scheduledStartMs, request.scheduledEndMs, request.providerId)- ?.let { return@withContext Result.error(it) }- recordingRunDao.insert(run)+ val run = try {+ persistManualRun(request, source, outputTarget)+ } catch (error: Throwable) {+ val (outputUri, outputDisplayPath) = outputTarget.asPersistenceValues()+ deleteOutputTarget(context, outputUri, outputDisplayPath)+ throw error}- alarmScheduler.scheduleStop(recordingId, request.scheduledEndMs)- when (val startResult = startCapture(run)) {- is Result.Success -> Unit- is Result.Error -> {- markRunFailed(run.id, startResult.message ?: "Capture failed to start.", inferFailureCategory(startResult.exception))- throw IllegalStateException(startResult.message, startResult.exception)- }- Result.Loading -> Unit+ scheduleStopAlarmOrFail(run.id, request.scheduledEndMs)+ try {+ recordingServiceLauncher.startCapture(context, run.id)+ } catch (error: Throwable) {+ markRunFailed(run.id, error.message ?: "Capture failed to start.", inferFailureCategory(error))+ throw IllegalStateException(error.message ?: "Capture failed to start.", error)}run.toStandaloneDomain()}.fold(@@ -220,37 +178,13 @@ class RecordingManagerImpl @Inject constructor(if (!storage.isWritable) {return@withContext Result.error("Recording storage is not writable.")}+ ensureExactRecordingAlarmsAvailableOrThrow()val recurringRuleId = request.recurringRuleId?: request.recurrence.takeIf { it != RecordingRecurrence.NONE }?.let { UUID.randomUUID().toString() }- val scheduleId = recordingScheduleDao.insert(- RecordingScheduleEntity(- providerId = request.providerId,- channelId = request.channelId,- channelName = request.channelName,- streamUrl = request.streamUrl,- programTitle = request.programTitle,- requestedStartMs = request.scheduledStartMs,- requestedEndMs = request.scheduledEndMs,- recurrence = request.recurrence,- recurringRuleId = recurringRuleId,- enabled = true,- isManual = false,- priority = request.priority- )- )- val run = createPendingRun(- scheduleId = scheduleId,- request = request.copy(recurringRuleId = recurringRuleId)- )-- recordingMutex.withLock {- validateRecordingWindow(request.scheduledStartMs, request.scheduledEndMs, request.providerId)- ?.let { return@withContext Result.error(it) }- recordingRunDao.insert(run)- }+ val run = persistScheduledRun(request, recurringRuleId)- alarmScheduler.scheduleStart(run.id, run.scheduledStartMs)+ scheduleStartAlarmOrFail(run.id, run.scheduledStartMs)run.toStandaloneDomain()}.fold(onSuccess = { Result.success(it) },@@ -348,6 +282,7 @@ class RecordingManagerImpl @Inject constructor(if (!storage.isWritable) {return@withContext Result.error("Recording storage is not writable.")}+ ensureExactRecordingAlarmsAvailableOrThrow()val recurringRuleId = request.recurringRuleId?: request.recurrence.takeIf { it != RecordingRecurrence.NONE }?.let { UUID.randomUUID().toString() }@@ -393,7 +328,7 @@ class RecordingManagerImpl @Inject constructor(recordingRunDao.insert(run)}- alarmScheduler.scheduleStart(run.id, run.scheduledStartMs)+ scheduleStartAlarmOrFail(run.id, run.scheduledStartMs)run.toStandaloneDomain()}.fold(onSuccess = { Result.success(it) },@@ -413,6 +348,7 @@ class RecordingManagerImpl @Inject constructor(override suspend fun retryRecording(recordingId: String): Result<Unit> = withContext(Dispatchers.IO) {runCatching {+ ensureExactRecordingAlarmsAvailableOrThrow()val run = recordingRunDao.getById(recordingId) ?: return@withContext Result.error("Recording not found")val schedule = recordingScheduleDao.getById(run.scheduleId) ?: return@withContext Result.error("Recording schedule not found")val now = System.currentTimeMillis()@@ -439,7 +375,7 @@ class RecordingManagerImpl @Inject constructor())recordingRunDao.insert(retriedRun)- alarmScheduler.scheduleStart(retriedRun.id, retriedRun.scheduledStartMs)+ scheduleStartAlarmOrFail(retriedRun.id, retriedRun.scheduledStartMs)} else {val retriedRun = createPendingRun(scheduleId = schedule.id,@@ -457,7 +393,7 @@ class RecordingManagerImpl @Inject constructor())recordingRunDao.insert(retriedRun)- alarmScheduler.scheduleStart(retriedRun.id, retriedRun.scheduledStartMs)+ scheduleStartAlarmOrFail(retriedRun.id, retriedRun.scheduledStartMs)}}.fold(onSuccess = { Result.success(Unit) },@@ -466,13 +402,16 @@ class RecordingManagerImpl @Inject constructor(}override suspend fun setScheduleEnabled(recordingId: String, enabled: Boolean): Result<Unit> = withContext(Dispatchers.IO) {+ if (enabled && !alarmScheduler.canScheduleExactAlarms()) {+ return@withContext Result.error(RecordingAlarmScheduler.EXACT_ALARM_PERMISSION_MESSAGE)+ }val run = recordingRunDao.getById(recordingId) ?: return@withContext Result.error("Recording not found")val schedule = recordingScheduleDao.getById(run.scheduleId) ?: return@withContext Result.error("Recording schedule not found")val now = System.currentTimeMillis()recordingScheduleDao.update(schedule.copy(enabled = enabled, updatedAt = now))recordingRunDao.update(run.copy(scheduleEnabled = enabled, updatedAt = now))if (enabled && run.status == RecordingStatus.SCHEDULED) {- alarmScheduler.scheduleStart(run.id, run.scheduledStartMs)+ scheduleStartAlarmOrFail(run.id, run.scheduledStartMs)} else {alarmScheduler.cancel(run.id)}@@ -515,14 +454,17 @@ class RecordingManagerImpl @Inject constructor(if (run.scheduledEndMs <= System.currentTimeMillis()) {markRunFailed(run.id, "Recording window expired before capture started.", RecordingFailureCategory.UNKNOWN)} else {- alarmScheduler.scheduleStart(run.id, run.scheduledStartMs)+ when (val result = alarmScheduler.scheduleStart(run.id, run.scheduledStartMs)) {+ is Result.Error -> markRunFailed(run.id, result.message, RecordingFailureCategory.UNKNOWN)+ else -> Unit+ }}}recordingRunDao.getRecordingRuns().forEach { run ->if (run.scheduledEndMs <= System.currentTimeMillis()) {stopRecording(run.id)} else if (!isActiveJob(run.id)) {- RecordingForegroundService.startCapture(context, run.id)+ markInterruptedRun(run)}}}.fold(@@ -532,10 +474,10 @@ class RecordingManagerImpl @Inject constructor(}override suspend fun promoteScheduledRecording(recordingId: String): Result<Unit> = withContext(Dispatchers.IO) {- recordingMutex.withLock {+ val runToStart = recordingMutex.withLock {val run = recordingRunDao.getById(recordingId) ?: return@withContext Result.error("Recording not found")when (run.status) {- RecordingStatus.RECORDING -> startCapture(run)+ RecordingStatus.RECORDING -> runRecordingStatus.SCHEDULED -> {val source = resolveRecordableSource(run.providerId, run.channelId, run.streamUrl)val storage = ensureStorageStateSync()@@ -577,19 +519,26 @@ class RecordingManagerImpl @Inject constructor(alarmStopAtMs = run.scheduledEndMs)recordingRunDao.update(updatedRun)- alarmScheduler.scheduleStop(updatedRun.id, updatedRun.scheduledEndMs)- recordingMutex.withLock { spawnNextRecurringRunIfNeeded(updatedRun) }- startCapture(updatedRun)+ when (val alarmResult = alarmScheduler.scheduleStop(updatedRun.id, updatedRun.scheduledEndMs)) {+ is Result.Error -> {+ markRunFailed(updatedRun.id, alarmResult.message, RecordingFailureCategory.UNKNOWN)+ return@withContext Result.error(alarmResult.message, alarmResult.exception)+ }+ else -> Unit+ }+ spawnNextRecurringRunIfNeeded(updatedRun)+ updatedRun}- else -> Result.error("Recording is no longer active.")+ else -> return@withContext Result.error("Recording is no longer active.")}}+ startCaptureOrFail(runToStart)}internal suspend fun onCaptureFinished(recordingId: String) {val remaining = observeActiveRecordingCountSync().coerceAtLeast(0)if (remaining == 0) {- RecordingForegroundService.stopIfIdle(context)+ recordingServiceLauncher.stopIfIdle(context)}}@@ -773,6 +722,20 @@ class RecordingManagerImpl @Inject constructor(alarmScheduler.cancel(recordingId)}+ private suspend fun startCaptureOrFail(run: RecordingRunEntity): Result<Unit> =+ when (val startResult = startCapture(run)) {+ is Result.Success -> Result.success(Unit)+ is Result.Error -> {+ markRunFailed(+ run.id,+ startResult.message ?: "Capture failed to start.",+ inferFailureCategory(startResult.exception)+ )+ Result.error(startResult.message ?: "Capture failed to start.", startResult.exception)+ }+ Result.Loading -> Result.success(Unit)+ }+private suspend fun markRunFailed(recordingId: String, reason: String, category: RecordingFailureCategory) {val run = recordingRunDao.getById(recordingId) ?: returnif (run.bytesWritten == 0L) {@@ -815,6 +778,115 @@ class RecordingManagerImpl @Inject constructor(notificationManager.notify(FAILURE_NOTIFICATION_ID_BASE + channelName.hashCode(), notification)}+ private suspend fun markInterruptedRun(run: RecordingRunEntity) {+ markRunFailed(+ recordingId = run.id,+ reason = "Recording was interrupted after the app process stopped. Capture was not resumed to avoid overwriting the existing recording.",+ category = RecordingFailureCategory.UNKNOWN+ )+ }++ private suspend fun persistManualRun(+ request: RecordingRequest,+ source: ResolvedRecordingSource,+ outputTarget: RecordingOutputTarget+ ): RecordingRunEntity = recordingMutex.withLock {+ validateRecordingWindowOrThrow(request.scheduledStartMs, request.scheduledEndMs, request.providerId)+ transactionRunner.inTransaction {+ val scheduleId = recordingScheduleDao.insert(+ buildScheduleEntity(+ request = request,+ recurrence = RecordingRecurrence.NONE,+ recurringRuleId = null,+ isManual = true+ )+ )+ val run = createManualRun(scheduleId, request, source, outputTarget)+ recordingRunDao.insert(run)+ run+ }+ }++ private suspend fun persistScheduledRun(+ request: RecordingRequest,+ recurringRuleId: String?+ ): RecordingRunEntity = recordingMutex.withLock {+ validateRecordingWindowOrThrow(request.scheduledStartMs, request.scheduledEndMs, request.providerId)+ transactionRunner.inTransaction {+ val scheduleId = recordingScheduleDao.insert(+ buildScheduleEntity(+ request = request,+ recurrence = request.recurrence,+ recurringRuleId = recurringRuleId,+ isManual = false+ )+ )+ val run = createPendingRun(+ scheduleId = scheduleId,+ request = request.copy(recurringRuleId = recurringRuleId)+ )+ recordingRunDao.insert(run)+ run+ }+ }++ private fun buildScheduleEntity(+ request: RecordingRequest,+ recurrence: RecordingRecurrence,+ recurringRuleId: String?,+ isManual: Boolean+ ): RecordingScheduleEntity = RecordingScheduleEntity(+ providerId = request.providerId,+ channelId = request.channelId,+ channelName = request.channelName,+ streamUrl = request.streamUrl,+ programTitle = request.programTitle,+ requestedStartMs = request.scheduledStartMs,+ requestedEndMs = request.scheduledEndMs,+ recurrence = recurrence,+ recurringRuleId = recurringRuleId,+ enabled = true,+ isManual = isManual,+ priority = request.priority+ )++ private fun createManualRun(+ scheduleId: Long,+ request: RecordingRequest,+ source: ResolvedRecordingSource,+ outputTarget: RecordingOutputTarget+ ): RecordingRunEntity {+ val (outputUri, outputDisplayPath) = outputTarget.asPersistenceValues()+ val now = System.currentTimeMillis()+ return RecordingRunEntity(+ id = UUID.randomUUID().toString(),+ scheduleId = scheduleId,+ providerId = request.providerId,+ channelId = request.channelId,+ channelName = request.channelName,+ streamUrl = request.streamUrl,+ programTitle = request.programTitle,+ scheduledStartMs = request.scheduledStartMs,+ scheduledEndMs = request.scheduledEndMs,+ recurrence = RecordingRecurrence.NONE,+ status = RecordingStatus.RECORDING,+ sourceType = source.sourceType,+ resolvedUrl = source.url,+ headersJson = headersToJson(source.headers),+ userAgent = source.userAgent,+ expirationTime = source.expirationTime,+ providerLabel = source.providerLabel,+ outputUri = outputUri,+ outputDisplayPath = outputDisplayPath,+ startedAtMs = now,+ scheduleEnabled = true,+ priority = request.priority,+ alarmStopAtMs = request.scheduledEndMs,+ createdAt = now,+ updatedAt = now+ )+ }+private suspend fun createPendingRun(scheduleId: Long, request: RecordingRequest): RecordingRunEntity {val now = System.currentTimeMillis()val paddingBeforeMs = if (request.paddingBeforeMs > 0) {@@ -915,7 +987,10 @@ class RecordingManagerImpl @Inject constructor(updatedAt = now)recordingRunDao.insert(nextRun)- alarmScheduler.scheduleStart(nextRun.id, nextRun.scheduledStartMs)+ when (val alarmResult = alarmScheduler.scheduleStart(nextRun.id, nextRun.scheduledStartMs)) {+ is Result.Error -> markRunFailed(nextRun.id, alarmResult.message, RecordingFailureCategory.UNKNOWN)+ else -> Unit+ }return}@@ -956,6 +1031,40 @@ class RecordingManagerImpl @Inject constructor(return null}+ private suspend fun validateRecordingWindowOrThrow(startMs: Long, endMs: Long, providerId: Long) {+ validateRecordingWindow(startMs, endMs, providerId)?.let { message ->+ throw IllegalStateException(message)+ }+ }++ private fun ensureExactRecordingAlarmsAvailableOrThrow() {+ if (!alarmScheduler.canScheduleExactAlarms()) {+ throw IllegalStateException(RecordingAlarmScheduler.EXACT_ALARM_PERMISSION_MESSAGE)+ }+ }++ private suspend fun scheduleStartAlarmOrFail(recordingId: String, whenMs: Long) {+ when (val result = alarmScheduler.scheduleStart(recordingId, whenMs)) {+ is Result.Success -> Unit+ is Result.Error -> {+ markRunFailed(recordingId, result.message, RecordingFailureCategory.UNKNOWN)+ throw IllegalStateException(result.message, result.exception)+ }+ Result.Loading -> Unit+ }+ }++ private suspend fun scheduleStopAlarmOrFail(recordingId: String, whenMs: Long) {+ when (val result = alarmScheduler.scheduleStop(recordingId, whenMs)) {+ is Result.Success -> Unit+ is Result.Error -> {+ markRunFailed(recordingId, result.message, RecordingFailureCategory.UNKNOWN)+ throw IllegalStateException(result.message, result.exception)+ }+ Result.Loading -> Unit+ }+ }+private suspend fun registerActiveJob(id: String, job: Job) {activeJobsMutex.withLock { activeJobs[id] = job }}diff --git a/data/src/main/java/com/streamvault/data/manager/recording/RecordingAlarmScheduler.kt b/data/src/main/java/com/streamvault/data/manager/recording/RecordingAlarmScheduler.ktindex 57b6f611..601ab7ce 100644--- a/data/src/main/java/com/streamvault/data/manager/recording/RecordingAlarmScheduler.kt+++ b/data/src/main/java/com/streamvault/data/manager/recording/RecordingAlarmScheduler.kt@@ -4,7 +4,9 @@ import android.app.AlarmManagerimport android.app.PendingIntentimport android.content.Contextimport android.content.Intent+import android.os.Buildimport androidx.core.app.AlarmManagerCompat+import com.streamvault.domain.model.Resultimport dagger.hilt.android.qualifiers.ApplicationContextimport javax.inject.Injectimport javax.inject.Singleton@@ -18,16 +20,21 @@ class RecordingAlarmScheduler @Inject constructor(context.getSystemService(AlarmManager::class.java)}- fun scheduleStart(recordingId: String, whenMs: Long) {- schedule(+ fun canScheduleExactAlarms(): Boolean {+ val manager = alarmManager ?: return false+ return Build.VERSION.SDK_INT < Build.VERSION_CODES.S || manager.canScheduleExactAlarms()+ }++ fun scheduleStart(recordingId: String, whenMs: Long): Result<Unit> {+ return schedule(action = RecordingAlarmReceiver.ACTION_START_RECORDING,recordingId = recordingId,whenMs = whenMs)}- fun scheduleStop(recordingId: String, whenMs: Long) {- schedule(+ fun scheduleStop(recordingId: String, whenMs: Long): Result<Unit> {+ return schedule(action = RecordingAlarmReceiver.ACTION_STOP_RECORDING,recordingId = recordingId,whenMs = whenMs@@ -51,29 +58,31 @@ class RecordingAlarmScheduler @Inject constructor()}- private fun schedule(action: String, recordingId: String, whenMs: Long) {+ private fun schedule(action: String, recordingId: String, whenMs: Long): Result<Unit> {val pendingIntent = buildPendingIntent(action = action,recordingId = recordingId,flags = PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)- val manager = alarmManager ?: return- runCatching {+ val manager = alarmManager ?: return Result.error(EXACT_ALARM_PERMISSION_MESSAGE)+ if (!canScheduleExactAlarms()) {+ return Result.error(EXACT_ALARM_PERMISSION_MESSAGE)+ }+ return runCatching {AlarmManagerCompat.setExactAndAllowWhileIdle(manager,AlarmManager.RTC_WAKEUP,whenMs,pendingIntent)+ Result.success(Unit)}.getOrElse { ex ->- android.util.Log.w("RecordingAlarmScheduler",- "Exact alarm denied (SCHEDULE_EXACT_ALARM may be revoked), falling back to inexact alarm for $recordingId", ex)- AlarmManagerCompat.setAndAllowWhileIdle(- manager,- AlarmManager.RTC_WAKEUP,- whenMs,- pendingIntent+ android.util.Log.w(+ "RecordingAlarmScheduler",+ "Exact alarm scheduling failed for $recordingId",+ ex)+ Result.error(EXACT_ALARM_PERMISSION_MESSAGE, ex)}}@@ -98,4 +107,8 @@ class RecordingAlarmScheduler @Inject constructor(}return 31 * action.hashCode() + idHash}++ companion object {+ const val EXACT_ALARM_PERMISSION_MESSAGE = "Exact alarm access is required for reliable DVR scheduling. Enable exact alarms for StreamVault in system settings and try again."+ }}diff --git a/data/src/main/java/com/streamvault/data/manager/recording/RecordingCaptureEngine.kt b/data/src/main/java/com/streamvault/data/manager/recording/RecordingCaptureEngine.ktindex 407af9f8..7d51a475 100644--- a/data/src/main/java/com/streamvault/data/manager/recording/RecordingCaptureEngine.kt+++ b/data/src/main/java/com/streamvault/data/manager/recording/RecordingCaptureEngine.kt@@ -191,7 +191,6 @@ class HlsLiveCaptureEngine @Inject constructor(playlist.segments.forEach { segment ->kotlinx.coroutines.currentCoroutineContext().ensureActive()if (segment.uri in seenSegments) return@forEach- seenSegments += segment.urival bytes = try {fetchBytes(segment.uri, headers)} catch (e: Throwable) {@@ -207,6 +206,7 @@ class HlsLiveCaptureEngine @Inject constructor(bytes}sink.write(payload)+ seenSegments += segment.uribytesWritten += payload.sizenewSegmentsThisRound = truelastDataAt = System.currentTimeMillis()diff --git a/data/src/main/java/com/streamvault/data/manager/recording/RecordingForegroundIdleGate.kt b/data/src/main/java/com/streamvault/data/manager/recording/RecordingForegroundIdleGate.ktnew file mode 100644index 00000000..6fbf80e1--- /dev/null+++ b/data/src/main/java/com/streamvault/data/manager/recording/RecordingForegroundIdleGate.kt@@ -0,0 +1,26 @@+package com.streamvault.data.manager.recording++internal class RecordingForegroundIdleGate {+ var activeRecordingCount: Int = 0+ private set++ var pendingCommandCount: Int = 0+ private set++ val hasPendingCommands: Boolean+ get() = pendingCommandCount > 0++ fun onCommandStarted() {+ pendingCommandCount += 1+ }++ fun onCommandFinished() {+ pendingCommandCount = (pendingCommandCount - 1).coerceAtLeast(0)+ }++ fun onActiveCountChanged(count: Int) {+ activeRecordingCount = count.coerceAtLeast(0)+ }++ fun shouldKeepAlive(): Boolean = hasPendingCommands || activeRecordingCount > 0+}\ No newline at end of filediff --git a/data/src/main/java/com/streamvault/data/manager/recording/RecordingForegroundService.kt b/data/src/main/java/com/streamvault/data/manager/recording/RecordingForegroundService.ktindex e58e538b..9a9a74e2 100644--- a/data/src/main/java/com/streamvault/data/manager/recording/RecordingForegroundService.kt+++ b/data/src/main/java/com/streamvault/data/manager/recording/RecordingForegroundService.kt@@ -23,6 +23,7 @@ import kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.Jobimport kotlinx.coroutines.SupervisorJobimport kotlinx.coroutines.cancel+import kotlinx.coroutines.delayimport kotlinx.coroutines.flow.collectLatestimport kotlinx.coroutines.launch@@ -35,6 +36,8 @@ class RecordingForegroundService : Service() {}private val serviceScope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)+ private val idleGate = RecordingForegroundIdleGate()+ private var idleStopJob: Job? = nullprivate var notificationJob: Job? = nulloverride fun onCreate() {@@ -43,8 +46,18 @@ class RecordingForegroundService : Service() {}override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {+ val action = intent?.action+ if (action == ACTION_START_CAPTURE || action == ACTION_STOP_CAPTURE || action == ACTION_RECONCILE) {+ beginPendingCommand()+ }runCatching {- startForeground(NOTIFICATION_ID, buildNotification(activeCount = 0))+ startForeground(+ NOTIFICATION_ID,+ buildNotification(+ activeCount = idleGate.activeRecordingCount,+ pendingCommand = idleGate.hasPendingCommands+ )+ )}.onFailure { error ->Log.e("RecordingFgService", "Unable to enter foreground", error)stopSelf(startId)@@ -52,23 +65,43 @@ class RecordingForegroundService : Service() {}ensureNotificationObserver()val manager = entryPoint().recordingManager()- when (intent?.action) {+ when (action) {ACTION_START_CAPTURE -> {val recordingId = intent.getStringExtra(EXTRA_RECORDING_ID).orEmpty()- serviceScope.launch { manager.promoteScheduledRecording(recordingId) }+ serviceScope.launch {+ try {+ manager.promoteScheduledRecording(recordingId)+ } finally {+ finishPendingCommand()+ }+ }}ACTION_STOP_CAPTURE -> {val recordingId = intent.getStringExtra(EXTRA_RECORDING_ID).orEmpty()- serviceScope.launch { manager.stopRecording(recordingId) }+ serviceScope.launch {+ try {+ manager.stopRecording(recordingId)+ } finally {+ finishPendingCommand()+ }+ }}ACTION_RECONCILE -> {- serviceScope.launch { manager.reconcileRecordingState() }+ serviceScope.launch {+ try {+ manager.reconcileRecordingState()+ } finally {+ finishPendingCommand()+ }+ }}+ else -> evaluateIdleState()}return START_STICKY}override fun onDestroy() {+ idleStopJob?.cancel()notificationJob?.cancel()serviceScope.cancel()super.onDestroy()@@ -80,20 +113,18 @@ class RecordingForegroundService : Service() {if (notificationJob != null) returnnotificationJob = serviceScope.launch {entryPoint().recordingManager().observeActiveRecordingCount().collectLatest { activeCount ->- val count = activeCount.coerceAtLeast(0)- val manager = getSystemService(NotificationManager::class.java)- manager.notify(NOTIFICATION_ID, buildNotification(count))- if (count == 0) {- stopForeground(STOP_FOREGROUND_REMOVE)- stopSelf()- }+ idleGate.onActiveCountChanged(activeCount)+ updateNotification()+ evaluateIdleState()}}}- private fun buildNotification(activeCount: Int): Notification {+ private fun buildNotification(activeCount: Int, pendingCommand: Boolean): Notification {val title = if (activeCount > 0) {"$activeCount recording${if (activeCount == 1) "" else "s"} in progress"+ } else if (pendingCommand) {+ "Starting recording service"} else {"Preparing recording service"}@@ -101,7 +132,7 @@ class RecordingForegroundService : Service() {.setSmallIcon(android.R.drawable.stat_sys_warning).setContentTitle("StreamVault DVR").setContentText(title)- .setOngoing(activeCount > 0)+ .setOngoing(activeCount > 0 || pendingCommand).setOnlyAlertOnce(true).setCategory(NotificationCompat.CATEGORY_SERVICE).setPriority(NotificationCompat.PRIORITY_LOW)@@ -135,12 +166,54 @@ class RecordingForegroundService : Service() {private fun entryPoint(): RecordingServiceEntryPoint =EntryPointAccessors.fromApplication(applicationContext, RecordingServiceEntryPoint::class.java)+ private fun beginPendingCommand() {+ idleGate.onCommandStarted()+ idleStopJob?.cancel()+ idleStopJob = null+ updateNotification()+ }++ private fun finishPendingCommand() {+ idleGate.onCommandFinished()+ updateNotification()+ evaluateIdleState()+ }++ private fun updateNotification() {+ val manager = getSystemService(NotificationManager::class.java) ?: return+ manager.notify(+ NOTIFICATION_ID,+ buildNotification(+ activeCount = idleGate.activeRecordingCount,+ pendingCommand = idleGate.hasPendingCommands+ )+ )+ }++ private fun evaluateIdleState() {+ if (idleGate.shouldKeepAlive()) {+ idleStopJob?.cancel()+ idleStopJob = null+ return+ }+ if (idleStopJob?.isActive == true) return+ idleStopJob = serviceScope.launch {+ delay(IDLE_GRACE_MS)+ if (!idleGate.shouldKeepAlive()) {+ stopForeground(STOP_FOREGROUND_REMOVE)+ stopSelf()+ }+ }+ }+companion object {private const val CHANNEL_ID = "streamvault_recording"private const val NOTIFICATION_ID = 4102+ private const val IDLE_GRACE_MS = 3_000Lprivate const val ACTION_START_CAPTURE = "com.streamvault.data.recording.service.START_CAPTURE"private const val ACTION_STOP_CAPTURE = "com.streamvault.data.recording.service.STOP_CAPTURE"private const val ACTION_RECONCILE = "com.streamvault.data.recording.service.RECONCILE"+ private const val ACTION_EVALUATE_IDLE = "com.streamvault.data.recording.service.EVALUATE_IDLE"private const val EXTRA_RECORDING_ID = "recording_id"fun startCapture(context: Context, recordingId: String) {@@ -164,7 +237,9 @@ class RecordingForegroundService : Service() {}fun stopIfIdle(context: Context) {- context.stopService(Intent(context, RecordingForegroundService::class.java))+ val intent = Intent(context, RecordingForegroundService::class.java)+ .setAction(ACTION_EVALUATE_IDLE)+ ContextCompat.startForegroundService(context, intent)}}}diff --git a/data/src/main/java/com/streamvault/data/manager/recording/RecordingRestoreReceiver.kt b/data/src/main/java/com/streamvault/data/manager/recording/RecordingRestoreReceiver.ktindex 0aae2993..7341683a 100644--- a/data/src/main/java/com/streamvault/data/manager/recording/RecordingRestoreReceiver.kt+++ b/data/src/main/java/com/streamvault/data/manager/recording/RecordingRestoreReceiver.kt@@ -3,7 +3,6 @@ package com.streamvault.data.manager.recordingimport android.content.BroadcastReceiverimport android.content.Contextimport android.content.Intent-import android.os.UserManagerclass RecordingRestoreReceiver : BroadcastReceiver() {@@ -14,13 +13,6 @@ class RecordingRestoreReceiver : BroadcastReceiver() {RecordingForegroundService.requestReconcile(context)RecordingReconcileWorker.enqueueOneShot(context)}- Intent.ACTION_LOCKED_BOOT_COMPLETED -> {- val userManager = context.getSystemService(Context.USER_SERVICE) as? UserManager- if (userManager?.isUserUnlocked == true) {- RecordingForegroundService.requestReconcile(context)- RecordingReconcileWorker.enqueueOneShot(context)- }- }}}}diff --git a/data/src/main/java/com/streamvault/data/manager/recording/RecordingServiceLauncher.kt b/data/src/main/java/com/streamvault/data/manager/recording/RecordingServiceLauncher.ktnew file mode 100644index 00000000..905d0aea--- /dev/null+++ b/data/src/main/java/com/streamvault/data/manager/recording/RecordingServiceLauncher.kt@@ -0,0 +1,24 @@+package com.streamvault.data.manager.recording++import android.content.Context+import javax.inject.Inject+import javax.inject.Singleton++@Singleton+open class RecordingServiceLauncher @Inject constructor() {+ open fun startCapture(context: Context, recordingId: String) {+ RecordingForegroundService.startCapture(context, recordingId)+ }++ open fun stopRecording(context: Context, recordingId: String) {+ RecordingForegroundService.stopRecording(context, recordingId)+ }++ open fun requestReconcile(context: Context) {+ RecordingForegroundService.requestReconcile(context)+ }++ open fun stopIfIdle(context: Context) {+ RecordingForegroundService.stopIfIdle(context)+ }+}\ No newline at end of filediff --git a/data/src/main/java/com/streamvault/data/manager/recording/RecordingSupport.kt b/data/src/main/java/com/streamvault/data/manager/recording/RecordingSupport.ktindex e732b203..bdb4ac29 100644--- a/data/src/main/java/com/streamvault/data/manager/recording/RecordingSupport.kt+++ b/data/src/main/java/com/streamvault/data/manager/recording/RecordingSupport.kt@@ -78,7 +78,7 @@ internal fun RecordingStorageConfig.toEntity(existing: RecordingStorageEntity?,internal fun headersToJson(headers: Map<String, String>): String {val obj = JSONObject()headers.forEach { (k, v) -> obj.put(k, v) }- return obj.toString()+ return obj.toString() ?: "{}"}internal fun headersFromJson(raw: String?): Map<String, String> {@@ -141,6 +141,8 @@ internal fun resolveStorageDetails(if (treeUriString.isNullOrBlank()) {val recordingsDir = defaultRecordingDirectory(context)val available = runCatching { StatFs(recordingsDir.absolutePath).availableBytes }.getOrNull()+ ?.takeIf { it > 0L }+ ?: recordingsDir.usableSpace.takeIf { it > 0L }return Triple(recordingsDir.absolutePath, available, recordingsDir.canWrite())}diff --git a/data/src/main/java/com/streamvault/data/manager/reminder/ProgramReminderAlarmScheduler.kt b/data/src/main/java/com/streamvault/data/manager/reminder/ProgramReminderAlarmScheduler.ktindex 5f61e43b..4ea9ab6e 100644--- a/data/src/main/java/com/streamvault/data/manager/reminder/ProgramReminderAlarmScheduler.kt+++ b/data/src/main/java/com/streamvault/data/manager/reminder/ProgramReminderAlarmScheduler.kt@@ -4,7 +4,10 @@ import android.app.AlarmManagerimport android.app.PendingIntentimport android.content.Contextimport android.content.Intent+import android.net.Uri+import android.os.Buildimport androidx.core.app.AlarmManagerCompat+import com.streamvault.domain.model.Resultimport dagger.hilt.android.qualifiers.ApplicationContextimport javax.inject.Injectimport javax.inject.Singleton@@ -18,26 +21,31 @@ class ProgramReminderAlarmScheduler @Inject constructor(context.getSystemService(AlarmManager::class.java)}- fun schedule(reminderId: Long, whenMs: Long) {- val manager = alarmManager ?: return+ fun canScheduleExactAlarms(): Boolean {+ val manager = alarmManager ?: return false+ return Build.VERSION.SDK_INT < Build.VERSION_CODES.S || manager.canScheduleExactAlarms()+ }++ fun schedule(reminderId: Long, whenMs: Long): Result<Unit> {+ val manager = alarmManager ?: return Result.error(EXACT_ALARM_PERMISSION_MESSAGE)+ if (!canScheduleExactAlarms()) {+ return Result.error(EXACT_ALARM_PERMISSION_MESSAGE)+ }val pendingIntent = buildPendingIntent(reminderId = reminderId,flags = PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)- runCatching {+ return runCatching {AlarmManagerCompat.setExactAndAllowWhileIdle(manager,AlarmManager.RTC_WAKEUP,whenMs,pendingIntent)- }.getOrElse {- AlarmManagerCompat.setAndAllowWhileIdle(- manager,- AlarmManager.RTC_WAKEUP,- whenMs,- pendingIntent- )+ Result.success(Unit)+ }.getOrElse { error ->+ android.util.Log.w("ProgramReminderScheduler", "Exact reminder alarm scheduling failed for $reminderId", error)+ Result.error(EXACT_ALARM_PERMISSION_MESSAGE, error)}}@@ -53,12 +61,23 @@ class ProgramReminderAlarmScheduler @Inject constructor(private fun buildPendingIntent(reminderId: Long, flags: Int): PendingIntent {val intent = Intent(context, ProgramReminderAlarmReceiver::class.java).setAction(ProgramReminderAlarmReceiver.ACTION_NOTIFY_REMINDER)+ .setData(reminderUri(reminderId)).putExtra(ProgramReminderAlarmReceiver.EXTRA_REMINDER_ID, reminderId)return PendingIntent.getBroadcast(context,- reminderId.hashCode(),+ 0,intent,flags)}++ private fun reminderUri(reminderId: Long): Uri = Uri.Builder()+ .scheme("streamvault")+ .authority("program-reminder")+ .appendPath(reminderId.toString())+ .build()++ companion object {+ const val EXACT_ALARM_PERMISSION_MESSAGE = "Exact alarm access is required for reliable program reminders. Enable exact alarms for StreamVault in system settings and try again."+ }}diff --git a/data/src/main/java/com/streamvault/data/manager/reminder/ProgramReminderNotifier.kt b/data/src/main/java/com/streamvault/data/manager/reminder/ProgramReminderNotifier.ktindex be1e83f5..804120b5 100644--- a/data/src/main/java/com/streamvault/data/manager/reminder/ProgramReminderNotifier.kt+++ b/data/src/main/java/com/streamvault/data/manager/reminder/ProgramReminderNotifier.kt@@ -37,10 +37,12 @@ class ProgramReminderNotifier @Inject constructor(.setContentIntent(buildLaunchPendingIntent()).build()runCatching {- NotificationManagerCompat.from(context).notify(reminder.id.hashCode(), notification)+ NotificationManagerCompat.from(context).notify(reminderNotificationTag(reminder.id), 0, notification)}}+ private fun reminderNotificationTag(reminderId: Long): String = "program-reminder:$reminderId"+private fun buildLaunchPendingIntent(): PendingIntent? {val launchIntent = context.packageManager.getLaunchIntentForPackage(context.packageName) ?: return nulllaunchIntent.addFlags(android.content.Intent.FLAG_ACTIVITY_CLEAR_TOP or android.content.Intent.FLAG_ACTIVITY_SINGLE_TOP)diff --git a/data/src/main/java/com/streamvault/data/manager/reminder/ProgramReminderRestoreReceiver.kt b/data/src/main/java/com/streamvault/data/manager/reminder/ProgramReminderRestoreReceiver.ktindex 784b0ff4..fe3386e2 100644--- a/data/src/main/java/com/streamvault/data/manager/reminder/ProgramReminderRestoreReceiver.kt+++ b/data/src/main/java/com/streamvault/data/manager/reminder/ProgramReminderRestoreReceiver.kt@@ -24,8 +24,7 @@ class ProgramReminderRestoreReceiver : BroadcastReceiver() {override fun onReceive(context: Context, intent: Intent) {when (intent.action) {Intent.ACTION_BOOT_COMPLETED,- Intent.ACTION_MY_PACKAGE_REPLACED,- Intent.ACTION_LOCKED_BOOT_COMPLETED -> {+ Intent.ACTION_MY_PACKAGE_REPLACED -> {val pendingResult = goAsync()val appContext = context.applicationContextCoroutineScope(SupervisorJob() + Dispatchers.IO).launch {diff --git a/data/src/main/java/com/streamvault/data/parser/M3uParser.kt b/data/src/main/java/com/streamvault/data/parser/M3uParser.ktindex 4acbb58d..43295964 100644--- a/data/src/main/java/com/streamvault/data/parser/M3uParser.kt+++ b/data/src/main/java/com/streamvault/data/parser/M3uParser.kt@@ -3,6 +3,7 @@ package com.streamvault.data.parserimport com.streamvault.domain.model.Channelimport com.streamvault.domain.model.Movieimport com.streamvault.domain.util.ChannelNormalizer+import com.streamvault.domain.util.StreamEntryUrlPolicyimport java.io.BufferedReaderimport java.io.InputStreamimport java.io.InputStreamReader@@ -160,11 +161,11 @@ class M3uParser {tvgId = extinf.tvgId,tvgName = extinf.tvgName,tvgLogo = extinf.tvgLogo,- tvgChno = extinf.tvgChno?.toIntOrNull(),+ tvgChno = extinf.tvgChno?.toIntOrNull()?.takeIf { it in 1..99999 },tvgLanguage = extinf.tvgLanguage,tvgCountry = extinf.tvgCountry,catchUp = extinf.catchUp,- catchUpDays = extinf.catchUpDays?.toIntOrNull(),+ catchUpDays = extinf.catchUpDays?.toIntOrNull()?.takeIf { it in 0..365 },catchUpSource = extinf.catchUpSource,timeshift = extinf.timeshift,url = url,@@ -293,11 +294,15 @@ class M3uParser {private fun findFirstUnquotedComma(value: String): Int {var inQuotes = false- for (i in value.indices) {- when (value[i]) {- '"' -> inQuotes = !inQuotes- ',' -> if (!inQuotes) return i+ var i = 0+ while (i < value.length) {+ when {+ // Backslash escape inside a quoted string: skip the next character entirely+ value[i] == '\\' && inQuotes && i + 1 < value.length -> i+++ value[i] == '"' -> inQuotes = !inQuotes+ value[i] == ',' && !inQuotes -> return i}+ i++}return -1}@@ -354,15 +359,21 @@ class M3uParser {val value = if (content[index] == '"') {index++- val valueStart = index+ val sb = StringBuilder()while (index < length && content[index] != '"') {+ if (content[index] == '\\' && index + 1 < length) {+ // Consume the backslash and include the next character literally+ index+++ sb.append(content[index])+ } else {+ sb.append(content[index])+ }index++}- val parsed = content.substring(valueStart, minOf(index, length))if (index < length && content[index] == '"') {index++}- parsed+ sb.toString()} else {// Unquoted value — consume until the next known attribute key or endval valueStart = index@@ -395,13 +406,17 @@ class M3uParser {return attributes}+ /**+ * Returns true if [url] is an acceptable stream entry URL.+ *+ * Delegates to the shared [StreamEntryUrlPolicy] (which detects control-separator+ * injection up to two encoding layers and enforces the allowed-scheme set) and+ * additionally rejects URLs that exceed the maximum safe length.+ */private fun isAllowedStreamUrl(url: String): Boolean {val trimmed = url.trim()if (trimmed.length > 8192) return false- val lower = trimmed.lowercase()- if (lower.contains("%0a") || lower.contains("%0d")) return false- val allowedPrefixes = listOf("http://", "https://", "rtsp://", "rtmp://", "mms://")- return allowedPrefixes.any { lower.startsWith(it) }+ return StreamEntryUrlPolicy.isAllowed(trimmed)}companion object {diff --git a/data/src/main/java/com/streamvault/data/parser/XmltvParser.kt b/data/src/main/java/com/streamvault/data/parser/XmltvParser.ktindex d9d40fcd..ba344765 100644--- a/data/src/main/java/com/streamvault/data/parser/XmltvParser.kt+++ b/data/src/main/java/com/streamvault/data/parser/XmltvParser.kt@@ -4,9 +4,11 @@ import com.streamvault.domain.model.Programimport org.xmlpull.v1.XmlPullParserimport org.xmlpull.v1.XmlPullParserFactoryimport java.io.InputStream+import java.io.PushbackInputStreamimport java.time.LocalDateimport java.time.LocalDateTimeimport java.time.OffsetDateTime+import java.time.ZoneIdimport java.time.ZoneOffsetimport java.time.format.DateTimeFormatterimport java.time.format.DateTimeFormatterBuilder@@ -54,10 +56,27 @@ class XmltvParser {private val logger = Logger.getLogger(XmltvParser::class.java.name)private val offsetDateFormats = listOf(+ // Space-separated numeric offset: "20250101120000 +0300"DateTimeFormatterBuilder().parseCaseInsensitive().appendPattern("yyyyMMddHHmmss xx").toFormatter(Locale.US),+ // No-space numeric offset: "20250101120000+0300"+ DateTimeFormatterBuilder()+ .parseCaseInsensitive()+ .appendPattern("yyyyMMddHHmmssxx")+ .toFormatter(Locale.US),+ // No-space colon offset: "20250101120000+03:00"+ DateTimeFormatterBuilder()+ .parseCaseInsensitive()+ .appendPattern("yyyyMMddHHmmssXXX")+ .toFormatter(Locale.US),+ // No-space short/Z offset: "20250101120000Z" or "20250101120000+03"+ DateTimeFormatterBuilder()+ .parseCaseInsensitive()+ .appendPattern("yyyyMMddHHmmssX")+ .toFormatter(Locale.US),+ // ISO-8601 with colon offsetDateTimeFormatterBuilder().parseCaseInsensitive().appendPattern("yyyy-MM-dd'T'HH:mm:ssXXX")@@ -95,8 +114,9 @@ class XmltvParser {message = "Loads all programs into memory. Use parseStreaming() for large EPG files.",replaceWith = ReplaceWith("parseStreaming(inputStream, onProgram)"))- fun parse(inputStream: InputStream): List<Program> {+ fun parse(inputStream: InputStream, timezoneId: String? = null): List<Program> {val programs = mutableListOf<Program>()+ val parsingZoneId = resolveParsingZoneId(timezoneId)try {val parser = newPullParser(inputStream)@@ -122,8 +142,8 @@ class XmltvParser {"programme" -> {inProgramme = truecurrentChannelId = parser.getAttributeValue(null, "channel")- currentStart = parseDate(parser.getAttributeValue(null, "start"))- currentEnd = parseDate(parser.getAttributeValue(null, "stop"))+ currentStart = parseDate(parser.getAttributeValue(null, "start"), parsingZoneId)+ currentEnd = parseDate(parser.getAttributeValue(null, "stop"), parsingZoneId)currentTitle = nullcurrentDescription = nullcurrentLang = ""@@ -173,11 +193,11 @@ class XmltvParser {inRating = false}if (parser.name == "programme" && inProgramme) {- if (currentChannelId != null && currentTitle != null) {+ if (isValidProgramme(currentChannelId, currentTitle, currentStart, currentEnd)) {programs.add(Program(- channelId = currentChannelId,- title = currentTitle,+ channelId = currentChannelId!!,+ title = currentTitle!!,description = currentDescription ?: "",startTime = currentStart,endTime = currentEnd,@@ -208,9 +228,11 @@ class XmltvParser {suspend fun parseStreaming(inputStream: InputStream,+ timezoneId: String? = null,onProgram: suspend (Program) -> Unit) {val parser = newPullParser(inputStream)+ val parsingZoneId = resolveParsingZoneId(timezoneId)var eventType = parser.eventTypevar currentChannelId: String? = null@@ -235,8 +257,8 @@ class XmltvParser {"programme" -> {inProgramme = truecurrentChannelId = parser.getAttributeValue(null, "channel")- currentStart = parseDate(parser.getAttributeValue(null, "start"))- currentEnd = parseDate(parser.getAttributeValue(null, "stop"))+ currentStart = parseDate(parser.getAttributeValue(null, "start"), parsingZoneId)+ currentEnd = parseDate(parser.getAttributeValue(null, "stop"), parsingZoneId)currentTitle = nullcurrentDescription = nullcurrentLang = ""@@ -286,11 +308,11 @@ class XmltvParser {inRating = false}if (parser.name == "programme" && inProgramme) {- if (currentChannelId != null && currentTitle != null) {+ if (isValidProgramme(currentChannelId, currentTitle, currentStart, currentEnd)) {onProgram(Program(- channelId = currentChannelId,- title = currentTitle,+ channelId = currentChannelId!!,+ title = currentTitle!!,description = currentDescription ?: "",startTime = currentStart,endTime = currentEnd,@@ -325,10 +347,12 @@ class XmltvParser {*/suspend fun parseStreamingWithChannels(inputStream: InputStream,+ timezoneId: String? = null,onChannel: suspend (XmltvChannel) -> Unit,onProgramme: suspend (XmltvProgramme) -> Unit) {val parser = newPullParser(inputStream)+ val parsingZoneId = resolveParsingZoneId(timezoneId)var eventType = parser.eventType// Channel state@@ -379,10 +403,12 @@ class XmltvParser {"programme" -> {inProgramme = truecurrentChannelId = parser.getAttributeValue(null, "channel")- currentStart = parseDate(parser.getAttributeValue(null, "start"))- currentEnd = parseDate(parser.getAttributeValue(null, "stop"))+ currentStart = parseDate(parser.getAttributeValue(null, "start"), parsingZoneId)+ currentEnd = parseDate(parser.getAttributeValue(null, "stop"), parsingZoneId)currentTitle = nullcurrentDescription = null+ currentSubtitle = null+ currentEpisodeNum = nullcurrentLang = ""currentImageUrl = nullcurrentCategories.clear()@@ -456,11 +482,11 @@ class XmltvParser {inRating = false}if (parser.name == "programme" && inProgramme) {- if (currentChannelId != null && currentTitle != null) {+ if (isValidProgramme(currentChannelId, currentTitle, currentStart, currentEnd)) {onProgramme(XmltvProgramme(- channelId = currentChannelId,- title = currentTitle,+ channelId = currentChannelId!!,+ title = currentTitle!!,subtitle = currentSubtitle,description = currentDescription ?: "",startTime = currentStart,@@ -492,17 +518,44 @@ class XmltvParser {}/**- * Wraps the input stream with GZIPInputStream if the URL ends in `.gz`.+ * Wraps the input stream with [GZIPInputStream] when gzip content is detected.+ *+ * Detection order:+ * 1. Peek the first two bytes for the gzip magic number `0x1F 0x8B` — this catches+ * correctly compressed streams served from URLs without a `.gz` suffix (e.g.+ * `/xmltv.php`, `/epg`), which is common with misconfigured IPTV panels.+ * 2. Fall back to a URL suffix hint (`.gz` / `.gzip`) only when magic-byte inspection+ * is inconclusive (fewer than 2 bytes available).+ *+ * A [PushbackInputStream] with a 2-byte buffer is used so that the peeked bytes are+ * transparently restored to the stream before being passed to the parser.+ *+ * @param url Retained for API compatibility and potential future use (e.g. logging,+ * content-type cross-checks). Content detection is based on magic bytes+ * and does not rely on the URL suffix.*/+ @Suppress("UNUSED_PARAMETER")fun maybeDecompressGzip(url: String, inputStream: InputStream): InputStream {- return if (url.lowercase(Locale.ROOT).let { it.endsWith(".gz") || it.endsWith(".gzip") }) {- GZIPInputStream(inputStream)- } else {- inputStream+ val pushback = PushbackInputStream(inputStream, 2)+ val magic = ByteArray(2)+ val bytesRead = pushback.read(magic)+ return when {+ bytesRead == 2 && magic[0] == 0x1F.toByte() && magic[1] == 0x8B.toByte() -> {+ // Gzip magic bytes detected — decompress regardless of URL suffix.+ pushback.unread(magic)+ GZIPInputStream(pushback)+ }+ else -> {+ // No magic bytes (or stream too short). Push back whatever was read and+ // return the stream as-is; the URL-suffix hint is no longer needed because+ // a valid gzip stream always starts with the magic bytes.+ if (bytesRead > 0) pushback.unread(magic, 0, bytesRead)+ pushback+ }}}- private fun parseDate(dateStr: String?): Long {+ private fun parseDate(dateStr: String?, parsingZoneId: ZoneId): Long {if (dateStr.isNullOrBlank()) return 0offsetDateFormats.firstNotNullOfOrNull { formatter ->@@ -510,21 +563,38 @@ class XmltvParser {}?.let { return it }localDateTimeFormats.firstNotNullOfOrNull { formatter ->- parseLocalDateTime(dateStr, formatter)+ parseLocalDateTime(dateStr, formatter, parsingZoneId)}?.let { return it }localDateFormats.firstNotNullOfOrNull { formatter ->- parseLocalDate(dateStr, formatter)+ parseLocalDate(dateStr, formatter, parsingZoneId)}?.let { return it }- // Last resort: try to extract just the timestamp portion+ // Last resort: extract the timestamp portion only if no timezone offset is detectable.+ //+ // '+' is unambiguous — it is always a timezone sign in a date string.+ // '-' at position > 12 is a timezone sign; at earlier positions it is a date+ // separator (e.g. "2025-01-01"). Using lastIndexOf avoids triggering on the+ // first '-' of an ISO date while still catching e.g. "2025-01-01 12:00:00-05:30".+ // 'Z' is the UTC designator.+ //+ // If a timezone marker is detected but the offset parsers above could not consume+ // the string, digit-stripping would silently discard the offset and shift the time;+ // we log and return 0 instead.try {- val cleaned = dateStr.replace("""[^\d]""".toRegex(), "")- if (cleaned.length >= 14) {- return parseLocalDateTime(- cleaned.substring(0, 14),- DateTimeFormatter.ofPattern("yyyyMMddHHmmss", Locale.US)- ) ?: 0+ val hasTimezoneMarker = dateStr.length > 8 &&+ (dateStr.contains('Z') || dateStr.contains('z') ||+ dateStr.contains('+') ||+ dateStr.lastIndexOf('-') > 12)+ if (!hasTimezoneMarker) {+ val cleaned = dateStr.replace("""[^\d]""".toRegex(), "")+ if (cleaned.length >= 14) {+ return parseLocalDateTime(+ cleaned.substring(0, 14),+ DateTimeFormatter.ofPattern("yyyyMMddHHmmss", Locale.US),+ parsingZoneId+ ) ?: 0+ }}} catch (_: Exception) {// Give up@@ -534,23 +604,48 @@ class XmltvParser {return 0}+ private fun isValidProgramme(+ channelId: String?,+ title: String?,+ startTime: Long,+ endTime: Long+ ): Boolean {+ return !channelId.isNullOrBlank() &&+ !title.isNullOrBlank() &&+ startTime > 0L &&+ endTime > startTime+ }+private fun parseOffsetDateTime(dateStr: String, formatter: DateTimeFormatter): Long? =runCatching {OffsetDateTime.parse(dateStr, formatter).toInstant().toEpochMilli()}.getOrNull()- private fun parseLocalDateTime(dateStr: String, formatter: DateTimeFormatter): Long? =+ private fun parseLocalDateTime(dateStr: String, formatter: DateTimeFormatter, parsingZoneId: ZoneId): Long? =runCatching {LocalDateTime.parse(dateStr, formatter)- .toInstant(ZoneOffset.UTC)+ .atZone(parsingZoneId)+ .toInstant().toEpochMilli()}.getOrNull()- private fun parseLocalDate(dateStr: String, formatter: DateTimeFormatter): Long? =+ private fun parseLocalDate(dateStr: String, formatter: DateTimeFormatter, parsingZoneId: ZoneId): Long? =runCatching {LocalDate.parse(dateStr, formatter)- .atStartOfDay()- .toInstant(ZoneOffset.UTC)+ .atStartOfDay(parsingZoneId)+ .toInstant().toEpochMilli()}.getOrNull()++ private fun resolveParsingZoneId(timezoneId: String?): ZoneId {+ val normalizedTimezoneId = timezoneId?.trim().orEmpty()+ if (normalizedTimezoneId.isBlank()) return ZoneId.systemDefault()++ return runCatching { ZoneId.of(normalizedTimezoneId) }+ .getOrElse {+ val fallbackZoneId = ZoneId.systemDefault()+ logger.warning("Invalid XMLTV timezone '$timezoneId'; defaulting to ${fallbackZoneId.id}")+ fallbackZoneId+ }+ }}diff --git a/data/src/main/java/com/streamvault/data/preferences/PreferencesRepository.kt b/data/src/main/java/com/streamvault/data/preferences/PreferencesRepository.ktindex 80fed44b..45059353 100644--- a/data/src/main/java/com/streamvault/data/preferences/PreferencesRepository.kt+++ b/data/src/main/java/com/streamvault/data/preferences/PreferencesRepository.kt@@ -112,6 +112,7 @@ class PreferencesRepository @Inject constructor(val MULTIVIEW_PRESET_2 = stringPreferencesKey("multiview_preset_2")val MULTIVIEW_PRESET_3 = stringPreferencesKey("multiview_preset_3")val MULTIVIEW_PERFORMANCE_MODE = stringPreferencesKey("multiview_performance_mode")+ val MULTIVIEW_CENTER_TWO_SLOT_LAYOUT = booleanPreferencesKey("multiview_center_two_slot_layout")val IS_INCOGNITO_MODE = booleanPreferencesKey("is_incognito_mode")val PLAYER_MUTED = booleanPreferencesKey("player_muted")val PLAYER_MEDIA_SESSION_ENABLED = booleanPreferencesKey("player_media_session_enabled")@@ -1493,6 +1494,16 @@ class PreferencesRepository @Inject constructor(}}+ val multiViewCenterTwoSlotLayout: Flow<Boolean> = context.dataStore.data.map { preferences ->+ preferences[PreferencesKeys.MULTIVIEW_CENTER_TWO_SLOT_LAYOUT] ?: false+ }++ suspend fun setMultiViewCenterTwoSlotLayout(enabled: Boolean) {+ context.dataStore.edit { preferences ->+ preferences[PreferencesKeys.MULTIVIEW_CENTER_TWO_SLOT_LAYOUT] = enabled+ }+ }+@OptIn(ExperimentalCoroutinesApi::class)fun getAspectRatioForChannel(channelId: Long): Flow<String?> {return channelPreferenceDao.observeAspectRatio(channelId).flatMapLatest { persistedRatio ->diff --git a/data/src/main/java/com/streamvault/data/remote/stalker/OkHttpStalkerApiService.kt b/data/src/main/java/com/streamvault/data/remote/stalker/OkHttpStalkerApiService.ktindex 4db779a8..90009cc7 100644--- a/data/src/main/java/com/streamvault/data/remote/stalker/OkHttpStalkerApiService.kt+++ b/data/src/main/java/com/streamvault/data/remote/stalker/OkHttpStalkerApiService.kt@@ -6,6 +6,8 @@ import com.google.gson.JsonParserimport com.google.gson.stream.JsonReaderimport com.google.gson.stream.JsonTokenimport com.streamvault.domain.model.Result+import com.streamvault.domain.util.StreamEntryUrlPolicy+import java.io.ByteArrayOutputStreamimport java.io.IOExceptionimport java.io.InputStreamimport java.io.InputStreamReader@@ -510,6 +512,12 @@ class OkHttpStalkerApiService @Inject constructor(?.substringAfter(' ', missingDelimiterValue = payload.findString("cmd").orEmpty())?.trim()?.takeIf { it.isNotBlank() }+ ?.let { resolved ->+ if (!StreamEntryUrlPolicy.isAllowed(resolved)) {+ throw IOException("Portal returned an unsupported playback URL scheme for create_link.")+ }+ resolved+ }?: throw IOException("Portal did not return a playable URL.")}@@ -628,19 +636,76 @@ class OkHttpStalkerApiService @Inject constructor(private fun executeJsonRequest(request: Request, action: String?): JsonElement {return okHttpClient.newCall(request).execute().use { response ->- val body = response.body?.string().orEmpty()if (!response.isSuccessful) {+ response.body?.close()throw IOException("Portal request failed with HTTP ${response.code}.")}- if (body.isBlank()) {+ val responseBody = response.body+ ?: throw IOException("Portal returned an empty response${actionSuffix(action)}.")+ val charset = responseBody.contentType()?.charset(Charsets.UTF_8) ?: Charsets.UTF_8+ val raw = readBodyBounded(+ stream = responseBody.byteStream(),+ charsetName = charset.name(),+ maxBytes = maxBodyBytesForAction(action),+ action = action+ )+ if (raw.isBlank()) {throw IOException("Portal returned an empty response${actionSuffix(action)}.")}- val parsed = parsePortalJson(body, action)+ val parsed = parsePortalJson(raw, action)parsed.ensureNoPortalError()parsed}}+ /**+ * Reads [stream] into a String, throwing [IOException] if the body exceeds [maxBytes].+ * This prevents unbounded heap allocation when portals return unexpectedly large responses.+ */+ private fun readBodyBounded(+ stream: InputStream,+ charsetName: String,+ maxBytes: Long,+ action: String?+ ): String {+ val out = ByteArrayOutputStream(16_384)+ var totalRead = 0L+ val chunk = ByteArray(8_192)+ while (true) {+ val n = stream.read(chunk)+ if (n < 0) break+ totalRead += n+ if (totalRead > maxBytes) {+ val limitKb = maxBytes / 1024+ throw IOException(+ "Portal response for '${action ?: "request"}' exceeded the ${limitKb}KB limit; " ++ "portal may be misbehaving."+ )+ }+ out.write(chunk, 0, n)+ }+ return try {+ out.toString(charsetName)+ } catch (_: java.io.UnsupportedEncodingException) {+ out.toString(Charsets.UTF_8.name())+ }+ }++ /**+ * Returns an appropriate response-body size ceiling for the given Stalker [action].+ * Smaller endpoints (auth, create_link) get tight limits; large catalog endpoints get+ * a generous but still bounded ceiling to prevent OOM from misbehaving portals.+ */+ private fun maxBodyBytesForAction(action: String?): Long = when (action?.trim()) {+ "handshake", "get_profile", "get_account_info" -> 512L * 1024 // 512 KB+ "create_link" -> 64L * 1024 // 64 KB+ "get_genres", "get_vod_categories", "get_series_categories",+ "get_categories", "get_live_categories" -> 2L * 1024 * 1024 // 2 MB+ "get_ordered_list", "get_vod_list", "get_series",+ "get_seasons", "get_series_info", "get_vod_info" -> 8L * 1024 * 1024 // 8 MB+ else -> 4L * 1024 * 1024 // 4 MB default+ }+private suspend fun requestStreamingItems(url: String,profile: StalkerDeviceProfile,@@ -693,11 +758,7 @@ class OkHttpStalkerApiService @Inject constructor(val reader = JsonReader(InputStreamReader(body.byteStream(), charset))reader.isLenient = truetry {- streamStalkerItems(reader, onItem).also { count ->- if (count == 0) {- throw IOException("Portal returned an empty response${actionSuffix(action)}.")- }- }+ streamStalkerItems(reader, onItem)} catch (error: IllegalStateException) {throw IOException("Portal returned unreadable JSON${actionSuffix(action)}.", error)}@@ -732,12 +793,30 @@ class OkHttpStalkerApiService @Inject constructor(when (reader.nextName()) {"error" -> {val error = reader.nextStringOrSkip()- if (!error.isNullOrBlank() && !error.equals("null", ignoreCase = true)) {+ // Use the same placeholder filter as ensureNoPortalError so that+ // "null", "0", "false", and "ok" from loose portals are not treated+ // as real errors in the streamed item path either.+ if (!error.isNullOrBlank() && !isPlaceholderErrorValue(error)) {throw IOException(error)}}"js", "data", "items" -> count += streamStalkerItems(reader, onItem)- else -> reader.skipValue()+ else -> {+ // Object-keyed catalogs (e.g. `{"data":{"100":{...},"200":{...}}}`) use+ // numeric string keys for each item. Attempt to parse any object value as+ // an item record before falling back to skip, so these catalogs are not+ // silently dropped on the streaming path.+ if (reader.peek() == JsonToken.BEGIN_OBJECT) {+ val element = JsonParser.parseReader(reader)+ val item = element.asJsonObjectOrNull()?.toItemRecord()+ if (item != null) {+ onItem(item)+ count+++ }+ } else {+ reader.skipValue()+ }+ }}}reader.endObject()@@ -983,11 +1062,23 @@ class OkHttpStalkerApiService @Inject constructor(}private fun JsonElement.ensureNoPortalError() {- val error = rootObjectOrNull()?.findString("error")+ val raw = rootObjectOrNull()?.findString("error")?: findString("error")- ?.takeIf { it.isNotBlank() && !it.equals("null", ignoreCase = true) }?: return- throw IOException(error)+ // Ignore well-known placeholder values that some portals emit even on success.+ if (raw.isBlank() || isPlaceholderErrorValue(raw)) return+ throw IOException(raw)+ }++ /**+ * Returns `true` for portal error strings that are not real errors.+ * Common examples: `"null"`, `"0"`, `"false"`, `"ok"`, empty strings.+ */+ private fun isPlaceholderErrorValue(value: String): Boolean {+ return when (value.lowercase(Locale.ROOT).trim()) {+ "null", "0", "false", "ok", "" -> true+ else -> false+ }}private suspend inline fun <T> runApiCall(@@ -1365,6 +1456,9 @@ class OkHttpStalkerApiService @Inject constructor(jsValue is JsonArray -> jsValue.toList()jsValue is JsonObject && jsValue["data"] is JsonArray -> jsValue["data"]!!.jsonArray.toList()jsValue is JsonObject && jsValue["items"] is JsonArray -> jsValue["items"]!!.jsonArray.toList()+ // Object-keyed catalogs: {"js":{"data":{"100":{...}}}} — use map values+ jsValue is JsonObject && jsValue["data"] is JsonObject -> jsValue["data"]!!.jsonObject.values.toList()+ jsValue is JsonObject && jsValue["items"] is JsonObject -> jsValue["items"]!!.jsonObject.values.toList()else -> emptyList()}}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.ktindex e8c84457..02e1fe8b 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@@ -36,6 +36,37 @@ class XtreamProvider() : IptvProvider {companion object {private const val TAG = "XtreamProvider"++ /**+ * Offset-aware formatters for Xtream EPG textual timestamps.+ * Only [OffsetDateTime] is attempted with these; we never fall back to+ * [LocalDateTime] on these formatters, which would silently drop the+ * timezone and produce a time that is wrong by several hours.+ */+ private val xtreamEpgOffsetFormats: List<DateTimeFormatter> = listOf(+ // ISO 8601 with colon offset: "2025-01-01T12:00:00+03:00"+ DateTimeFormatter.ISO_OFFSET_DATE_TIME,+ // Space-separated with colon offset: "2025-01-01 12:00:00+03:00"+ DateTimeFormatterBuilder()+ .parseCaseInsensitive()+ .appendPattern("yyyy-MM-dd HH:mm:ssXXX")+ .toFormatter(Locale.US),+ // Space-separated with numeric offset: "2025-01-01 12:00:00+0300"+ DateTimeFormatterBuilder()+ .parseCaseInsensitive()+ .appendPattern("yyyy-MM-dd HH:mm:ssxx")+ .toFormatter(Locale.US)+ )++ /**+ * Local (no timezone) formatters for Xtream EPG textual timestamps.+ * Values parsed with these are assumed to be UTC, which is the+ * convention used by Xtream Codes providers.+ */+ private val xtreamEpgLocalFormats: List<DateTimeFormatter> = listOf(+ DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss", Locale.US),+ DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss", Locale.US)+ )}private enum class XtreamTextDecodeMode {@@ -300,16 +331,19 @@ class XtreamProvider(val resolvedSeasonNumber = seasonNum.toIntOrNull() ?: episodes.firstNotNullOfOrNull { episode ->episode.season.takeIf { it > 0 }} ?: 0- val mappedEpisodes = episodes.mapNotNull { ep ->- val episodeId = ep.id.toLongOrNull()?.takeIf { it > 0 } ?: return@mapNotNull null+ val mappedEpisodes = episodes.mapIndexedNotNull { index, ep ->+ val episodeId = ep.id.toLongOrNull()?.takeIf { it > 0 }+ ?: ep.episodeNum.takeIf { it > 0 }?.let { resolvedSeasonNumber * 10000L + it }+ ?: ((index + 1).let { resolvedSeasonNumber * 10000L + it })+ val normalizedEpisodeNum = if (ep.episodeNum > 0) ep.episodeNum else index + 1val normalizedExtension = normalizeContainerExtension(ep.containerExtension)Episode(id = episodeId,title = decodeXtreamText(- ep.title.ifBlank { decodeXtreamNullableText(ep.info?.name, XtreamTextDecodeMode.RAW) ?: "Episode ${ep.episodeNum}" },+ ep.title.ifBlank { decodeXtreamNullableText(ep.info?.name, XtreamTextDecodeMode.RAW) ?: "Episode $normalizedEpisodeNum" },XtreamTextDecodeMode.RAW),- episodeNumber = ep.episodeNum,+ episodeNumber = normalizedEpisodeNum,seasonNumber = ep.season.takeIf { it > 0 } ?: resolvedSeasonNumber,containerExtension = normalizedExtension,coverUrl = sanitizeAssetValue(ep.info?.movieImage),@@ -372,7 +406,7 @@ class XtreamProvider(extraQueryParams = mapOf("stream_id" to streamId.toString())))- Result.success(response.epgListings.map { it.toDomain() })+ Result.success(response.epgListings.mapNotNull { it.toDomainOrNull() })} catch (e: Exception) {Result.error(XtreamErrorFormatter.message("Failed to load EPG", e), e)}@@ -391,7 +425,7 @@ class XtreamProvider()))- Result.success(response.epgListings.map { it.toDomain() })+ Result.success(response.epgListings.mapNotNull { it.toDomainOrNull() })} catch (e: Exception) {Result.error(XtreamErrorFormatter.message("Failed to load EPG", e), e)}@@ -663,7 +697,7 @@ class XtreamProvider(private fun XtreamStream.toChannel(adultCategoryIds: Set<Long>): Channel? {if (streamId <= 0) return null- val category = resolveXtreamCategory(ContentType.LIVE, categoryId, categoryName)+ val category = resolveXtreamCategory(ContentType.LIVE, primaryCategoryId(), categoryName)val primaryContainerExtension = preferredLiveContainerExtension(containerExtension)val resolvedName = decodeXtreamNullableText(name, XtreamTextDecodeMode.RAW)?.ifBlank { null } ?: "Channel $streamId"val sanitizedLogoUrl = sanitizeAssetValue(streamIcon)@@ -707,7 +741,7 @@ class XtreamProvider(private fun XtreamStream.toMovie(adultCategoryIds: Set<Long>): Movie? {if (streamId <= 0) return null- val category = resolveXtreamCategory(ContentType.MOVIE, categoryId, categoryName)+ val category = resolveXtreamCategory(ContentType.MOVIE, primaryCategoryId(), categoryName)val resolvedName = decodeXtreamNullableText(name, XtreamTextDecodeMode.RAW)?.ifBlank { null } ?: "Movie $streamId"val normalizedContainerExtension = normalizeContainerExtension(containerExtension)val sanitizedDirectSource = sanitizeAssetValue(directSource)@@ -871,7 +905,18 @@ class XtreamProvider()}- private fun XtreamEpgListing.toDomain(): Program {+ private fun XtreamEpgListing.toDomainOrNull(): Program? {+ // Resolve start and end independently: use the numeric timestamp when present+ // (> 0), otherwise fall back to the textual field. Using per-field resolution+ // prevents a valid numeric startTimestamp from being discarded just because+ // stopTimestamp is absent (some providers omit one but not the other).+ val resolvedStart = if (startTimestamp > 0L) startTimestamp * 1000L+ else parseXtreamEpgTimestamp(start)+ val resolvedEnd = if (stopTimestamp > 0L) stopTimestamp * 1000L+ else parseXtreamEpgTimestamp(end)+ // Skip silently rather than emitting an epoch-zero programme that corrupts the guide.+ if (resolvedStart <= 0L || resolvedEnd <= resolvedStart) return null+// Xtream sometimes base64-encodes title and descriptionval decodedTitle = decodeXtreamText(title, XtreamTextDecodeMode.EPG)val decodedDescription = decodeXtreamText(description, XtreamTextDecodeMode.EPG)@@ -881,8 +926,8 @@ class XtreamProvider(channelId = channelId,title = decodedTitle,description = decodedDescription,- startTime = startTimestamp * 1000L,- endTime = stopTimestamp * 1000L,+ startTime = resolvedStart,+ endTime = resolvedEnd,lang = lang,category = null,hasArchive = hasArchive == 1,@@ -891,6 +936,39 @@ class XtreamProvider()}+ /**+ * Parses an Xtream EPG time value which may be:+ * - A numeric epoch-seconds string (e.g. `"1735726800"`)+ * - An ISO-style date-time with timezone offset (e.g. `"2025-01-01T12:00:00+03:00"`)+ * - An ISO-style local date-time, assumed UTC (e.g. `"2025-01-01 12:00:00"`)+ *+ * Offset-aware formats are tried first so that a valid `+HH:mm` suffix is never+ * silently dropped. Local formats are only tried after all offset paths fail.+ *+ * Returns epoch-milliseconds, or 0 if the value cannot be parsed.+ */+ private fun parseXtreamEpgTimestamp(value: String): Long {+ if (value.isBlank()) return 0L+ val trimmed = value.trim()+ // Numeric string: epoch seconds (must be > 0 to exclude placeholder zeroes)+ trimmed.toLongOrNull()?.takeIf { it > 0L }?.let { return it * 1000L }+ // Offset-aware text timestamps: use OffsetDateTime only — never LocalDateTime+ // on these formatters, because LocalDateTime.from(OffsetDateTime) strips the+ // offset and would return a time that is wrong by the provider's UTC offset.+ xtreamEpgOffsetFormats.forEach { formatter ->+ runCatching {+ OffsetDateTime.parse(trimmed, formatter).toInstant().toEpochMilli()+ }.getOrNull()?.let { return it }+ }+ // Local text timestamps: UTC is assumed (Xtream convention)+ xtreamEpgLocalFormats.forEach { formatter ->+ runCatching {+ LocalDateTime.parse(trimmed, formatter).toInstant(ZoneOffset.UTC).toEpochMilli()+ }.getOrNull()?.let { return it }+ }+ return 0L+ }+private fun decodeXtreamNullableText(value: String?,mode: XtreamTextDecodeMode = XtreamTextDecodeMode.RAW@@ -954,6 +1032,23 @@ class XtreamProvider(}}+ private fun XtreamStream.primaryCategoryId(): String? {+ val normalizedCategoryId = categoryId.normalizedCategoryToken()+ val firstAlternateCategoryId = categoryIds.orEmpty()+ .mapNotNull { it.normalizedCategoryToken() }+ .firstOrNull { it != "0" }+ ?: categoryIds.orEmpty().firstNotNullOfOrNull { it.normalizedCategoryToken() }+ return when {+ normalizedCategoryId == null -> firstAlternateCategoryId+ normalizedCategoryId == "0" && firstAlternateCategoryId != null && firstAlternateCategoryId != "0" -> firstAlternateCategoryId+ else -> normalizedCategoryId+ }+ }++ private fun String?.normalizedCategoryToken(): String? = this+ ?.trim()+ ?.takeIf { it.isNotEmpty() && !it.equals("null", ignoreCase = true) }+private fun syntheticCategoryId(type: ContentType, seed: String): Long {val normalized = "$providerId/${type.name}/${seed.trim().lowercase(Locale.ROOT)}"return (normalized.hashCode().toLong() and 0x7fff_ffffL).coerceAtLeast(1L)diff --git a/data/src/main/java/com/streamvault/data/remote/xtream/XtreamUrlFactory.kt b/data/src/main/java/com/streamvault/data/remote/xtream/XtreamUrlFactory.ktindex 6a537270..70b52633 100644--- a/data/src/main/java/com/streamvault/data/remote/xtream/XtreamUrlFactory.kt+++ b/data/src/main/java/com/streamvault/data/remote/xtream/XtreamUrlFactory.kt@@ -1,6 +1,7 @@package com.streamvault.data.remote.xtreamimport com.streamvault.domain.model.ContentType+import com.streamvault.domain.util.StreamEntryUrlPolicyimport java.net.URIimport java.net.URLDecoderimport java.net.URLEncoder@@ -413,12 +414,17 @@ object XtreamUrlFactory {?.trim()?.removePrefix(".")?.lowercase(Locale.ROOT)- ?.takeIf { it.isNotEmpty() }+ // Allow-list: lowercase alphanumeric only, 1–12 chars.+ // Rejects path traversal chars, query chars, and control characters.+ ?.takeIf { it.matches(Regex("[a-z0-9]{1,12}")) }}private fun normalizeDirectSource(directSource: String?): String? {- return directSource- ?.trim()- ?.takeIf { it.isNotEmpty() }+ val trimmed = directSource?.trim()?.takeIf { it.isNotEmpty() } ?: return null+ // Cap length before storing in internal URLs/database to prevent oversized tokens.+ if (trimmed.length > 8192) return null+ // Validate the value is a permitted stream URL; rejected values are dropped here+ // rather than surfaced as a playback error later.+ return trimmed.takeIf { StreamEntryUrlPolicy.isAllowed(it) }}}diff --git a/data/src/main/java/com/streamvault/data/repository/ChannelRepositoryImpl.kt b/data/src/main/java/com/streamvault/data/repository/ChannelRepositoryImpl.ktindex b97e3bf0..543cebb7 100644--- a/data/src/main/java/com/streamvault/data/repository/ChannelRepositoryImpl.kt+++ b/data/src/main/java/com/streamvault/data/repository/ChannelRepositoryImpl.kt@@ -1,6 +1,7 @@package com.streamvault.data.repositoryimport android.database.sqlite.SQLiteException+import android.util.Logimport com.streamvault.data.local.dao.CategoryDaoimport com.streamvault.data.local.dao.ChannelDaoimport com.streamvault.data.local.dao.FavoriteDao@@ -35,6 +36,7 @@ import kotlinx.coroutines.withContextimport kotlinx.coroutines.flow.Flowimport kotlinx.coroutines.flow.catchimport kotlinx.coroutines.flow.combine+import kotlinx.coroutines.flow.emitAllimport kotlinx.coroutines.flow.firstimport kotlinx.coroutines.flow.flowOfimport kotlinx.coroutines.flow.flatMapLatest@@ -54,7 +56,8 @@ class ChannelRepositoryImpl @Inject constructor(private val xtreamStreamUrlResolver: XtreamStreamUrlResolver) : ChannelRepository {private companion object {- const val GLOBAL_SEARCH_LIMIT = 200+ const val TAG = "ChannelRepository"+ const val GLOBAL_SEARCH_LIMIT = 500const val CATEGORY_SEARCH_LIMIT = 300const val MIN_SEARCH_QUERY_LENGTH = 2}@@ -359,9 +362,17 @@ class ChannelRepositoryImpl @Inject constructor(if (ftsQuery.isNullOrBlank()) {flowOf(emptyList())} else if (categoryId == ChannelRepository.ALL_CHANNELS_ID) {- safeSearchFlow(channelDao.search(providerId, ftsQuery, limit))+ safeSearchFlow(+ source = channelDao.search(providerId, ftsQuery, limit),+ fallback = channelDao.searchFallback(providerId, query.trim().toSqlLikePattern(), limit),+ rawQuery = query.trim()+ )} else {- safeSearchFlow(channelDao.searchByCategory(providerId, categoryId, ftsQuery, limit))+ safeSearchFlow(+ source = channelDao.searchByCategory(providerId, categoryId, ftsQuery, limit),+ fallback = channelDao.searchByCategoryFallback(providerId, categoryId, query.trim().toSqlLikePattern(), limit),+ rawQuery = query.trim()+ )}}@@ -676,15 +687,32 @@ class ChannelRepositoryImpl @Inject constructor(channelDao.getByCategoryWithoutErrorsBrowsePage(providerId, categoryId, limit)}- private fun safeSearchFlow(source: Flow<List<ChannelBrowseEntity>>): Flow<List<ChannelBrowseEntity>> =+ private fun safeSearchFlow(+ source: Flow<List<ChannelBrowseEntity>>,+ fallback: Flow<List<ChannelBrowseEntity>>,+ rawQuery: String+ ): Flow<List<ChannelBrowseEntity>> =source.catch { error ->if (error is SQLiteException) {- emit(emptyList())+ Log.w(TAG, "FTS channel search failed for query '$rawQuery'; falling back to LIKE search", error)+ emitAll(fallback)} else {throw error}}+ private fun String.toSqlLikePattern(): String {+ val escaped = buildString(length) {+ [email protected] { char ->+ when (char) {+ '%', '_', '\\' -> append('\\')+ }+ append(char)+ }+ }+ return "%$escaped%"+ }+private fun channelGroupKey(entity: ChannelBrowseEntity): String =entity.logicalGroupId.takeIf(String::isNotBlank) ?: entity.id.toString()diff --git a/data/src/main/java/com/streamvault/data/repository/EpgRepositoryImpl.kt b/data/src/main/java/com/streamvault/data/repository/EpgRepositoryImpl.ktindex aa12f6bd..bce0cc0c 100644--- a/data/src/main/java/com/streamvault/data/repository/EpgRepositoryImpl.kt+++ b/data/src/main/java/com/streamvault/data/repository/EpgRepositoryImpl.kt@@ -2,6 +2,8 @@ package com.streamvault.data.repositoryimport com.streamvault.data.local.DatabaseTransactionRunnerimport com.streamvault.data.local.dao.ProgramDao+import com.streamvault.data.local.dao.ProviderDao+import com.streamvault.data.local.entity.ProgramBrowseEntityimport com.streamvault.data.local.entity.ProgramEntityimport com.streamvault.data.mapper.toDomainimport com.streamvault.data.mapper.toEntity@@ -45,6 +47,7 @@ import javax.inject.Singleton@OptIn(ExperimentalCoroutinesApi::class)class EpgRepositoryImpl @Inject constructor(private val programDao: ProgramDao,+ private val providerDao: ProviderDao,private val xmltvParser: XmltvParser,private val okHttpClient: OkHttpClient,private val transactionRunner: DatabaseTransactionRunner,@@ -161,20 +164,19 @@ class EpgRepositoryImpl @Inject constructor(override fun getNowPlayingForChannels(providerId: Long, channelIds: List<String>): Flow<Map<String, Program?>> {if (channelIds.isEmpty()) return flowOf(emptyMap())- val now = System.currentTimeMillis()+val chunks = channelIds.chunked(500)- if (chunks.size == 1) {- return programDao.getNowPlayingForChannels(providerId, channelIds, now)- .map { entities ->- val grouped = entities.map { it.toDomain() }.groupBy { it.channelId }- channelIds.associateWith { id -> grouped[id]?.firstOrNull() }+ return nowTicker.flatMapLatest { now ->+ if (chunks.size == 1) {+ programDao.getNowPlayingForChannels(providerId, channelIds, now)+ .map { entities -> mapNowPlayingByChannel(channelIds, entities) }+ } else {+ combine(chunks.map { chunk ->+ programDao.getNowPlayingForChannels(providerId, chunk, now)+ }) { arrays ->+ mapNowPlayingByChannel(channelIds, arrays.flatMap { it.toList() })}- }- return combine(chunks.map { chunk ->- programDao.getNowPlayingForChannels(providerId, chunk, now)- }) { arrays ->- val grouped = arrays.flatMap { it.toList() }.map { it.toDomain() }.groupBy { it.channelId }- channelIds.associateWith { id -> grouped[id]?.firstOrNull() }+ }}}@@ -217,6 +219,10 @@ class EpgRepositoryImpl @Inject constructor(withContext(Dispatchers.IO) {providerRefreshMutex(providerId).withLock {val stagingProviderId = -providerId+ val providerTimezoneId = providerDao.getById(providerId)+ ?.stalkerDeviceTimezone+ ?.trim()+ ?.takeIf(String::isNotEmpty)val batch = ArrayList<ProgramEntity>(EPG_PROGRAM_BATCH_SIZE)suspend fun flushBatch() {if (batch.isEmpty()) return@@ -278,7 +284,7 @@ class EpgRepositoryImpl @Inject constructor(xmltvParser.maybeDecompressGzip(epgUrl, limitedStream)}xmlInput.use {- xmltvParser.parseStreaming(xmlInput) { program ->+ xmltvParser.parseStreaming(xmlInput, timezoneId = providerTimezoneId) { program ->batch.add(program.copy(providerId = stagingProviderId).toEntity())if (batch.size >= EPG_PROGRAM_BATCH_SIZE) {flushBatch()@@ -361,6 +367,14 @@ class EpgRepositoryImpl @Inject constructor(}}.shareIn(externalScope, SharingStarted.WhileSubscribed(), replay = 1)+ private fun mapNowPlayingByChannel(+ channelIds: List<String>,+ entities: List<ProgramBrowseEntity>+ ): Map<String, Program?> {+ val grouped = entities.map { it.toDomain() }.groupBy { it.channelId }+ return channelIds.associateWith { id -> grouped[id]?.firstOrNull() }+ }+private fun providerRefreshMutex(providerId: Long): Mutex =providerRefreshMutexes.computeIfAbsent(providerId) { Mutex() }}diff --git a/data/src/main/java/com/streamvault/data/repository/EpgSourceRepositoryImpl.kt b/data/src/main/java/com/streamvault/data/repository/EpgSourceRepositoryImpl.ktindex 52ca297e..28f2e802 100644--- a/data/src/main/java/com/streamvault/data/repository/EpgSourceRepositoryImpl.kt+++ b/data/src/main/java/com/streamvault/data/repository/EpgSourceRepositoryImpl.kt@@ -10,6 +10,7 @@ import com.streamvault.data.local.dao.ChannelEpgMappingDaoimport com.streamvault.data.local.dao.EpgChannelDaoimport com.streamvault.data.local.dao.EpgProgrammeDaoimport com.streamvault.data.local.dao.EpgSourceDao+import com.streamvault.data.local.dao.ProviderDaoimport com.streamvault.data.local.dao.ProviderEpgSourceDaoimport com.streamvault.data.local.entity.ChannelEpgMappingEntityimport com.streamvault.data.local.entity.EpgChannelEntity@@ -17,12 +18,14 @@ import com.streamvault.data.local.entity.EpgProgrammeEntityimport com.streamvault.data.local.entity.EpgSourceEntityimport com.streamvault.data.local.entity.ProviderEpgSourceEntityimport com.streamvault.data.mapper.toDomain+import com.streamvault.data.preferences.PreferencesRepositoryimport com.streamvault.domain.model.EpgMatchTypeimport com.streamvault.domain.model.EpgOverrideCandidateimport com.streamvault.domain.model.EpgSourceTypeimport com.streamvault.data.parser.XmltvParserimport com.streamvault.data.util.UrlSecurityPolicyimport com.streamvault.domain.model.ChannelEpgMapping+import com.streamvault.domain.model.ContentTypeimport com.streamvault.domain.model.EpgResolutionSummaryimport com.streamvault.domain.model.EpgSourceimport com.streamvault.domain.model.Program@@ -31,6 +34,7 @@ import com.streamvault.domain.model.Resultimport com.streamvault.domain.repository.EpgSourceRepositoryimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.firstimport kotlinx.coroutines.flow.mapimport kotlinx.coroutines.sync.Muteximport kotlinx.coroutines.sync.withLock@@ -52,12 +56,14 @@ class EpgSourceRepositoryImpl @Inject constructor(@ApplicationContext private val context: Context,private val epgSourceDao: EpgSourceDao,private val providerEpgSourceDao: ProviderEpgSourceDao,+ private val providerDao: ProviderDao,private val channelEpgMappingDao: ChannelEpgMappingDao,private val epgChannelDao: EpgChannelDao,private val epgProgrammeDao: EpgProgrammeDao,private val xmltvParser: XmltvParser,private val okHttpClient: OkHttpClient,private val resolutionEngine: EpgResolutionEngine,+ private val preferencesRepository: PreferencesRepository,private val transactionRunner: DatabaseTransactionRunner) : EpgSourceRepository {@@ -162,20 +168,20 @@ class EpgSourceRepositoryImpl @Inject constructor(priority = priority))- resolveForProvider(providerId, emptySet())+ resolveProviderUsingPreferences(providerId)return Result.success(Unit)}override suspend fun unassignSourceFromProvider(providerId: Long, epgSourceId: Long) {providerEpgSourceDao.delete(providerId, epgSourceId)- resolveForProvider(providerId, emptySet())+ resolveProviderUsingPreferences(providerId)}override suspend fun updateAssignmentPriority(providerId: Long, epgSourceId: Long, priority: Int) {val assignments = providerEpgSourceDao.getForProviderSync(providerId)val target = assignments.find { it.epgSourceId == epgSourceId } ?: returnproviderEpgSourceDao.update(target.copy(priority = priority))- resolveForProvider(providerId, emptySet())+ resolveProviderUsingPreferences(providerId)}override suspend fun swapAssignmentPriorities(@@ -192,7 +198,7 @@ class EpgSourceRepositoryImpl @Inject constructor(target1.copy(priority = newPriority1),target2.copy(priority = newPriority2))- resolveForProvider(providerId, emptySet())+ resolveProviderUsingPreferences(providerId)}// ── Refresh / Ingestion ────────────────────────────────────────@@ -248,6 +254,9 @@ class EpgSourceRepositoryImpl @Inject constructor(response.close()val now = System.currentTimeMillis()epgSourceDao.updateRefreshSuccess(sourceId, now)+ if (resolveAffectedProviders) {+ resolveAffectedProviders(providerEpgSourceDao.getProviderIdsForSourceSync(sourceId))+ }return@withLock Result.success(Unit)}@@ -291,8 +300,8 @@ class EpgSourceRepositoryImpl @Inject constructor(// Stage new data under a negative source ID to avoid clobbering// live data during download/parse. Swap atomically on success.val stagingId = -sourceId- epgChannelDao.deleteBySource(stagingId)- epgProgrammeDao.deleteBySource(stagingId)+ val sourceTimezoneId = resolveSourceTimezoneId(sourceId)+ prepareStagingSource(source, stagingId)rawInputStream.use { raw ->val limited = object : FilterInputStream(raw) {@@ -309,6 +318,7 @@ class EpgSourceRepositoryImpl @Inject constructor(xmltvParser.maybeDecompressGzip(source.url, limited).use { decompressed ->xmltvParser.parseStreamingWithChannels(inputStream = decompressed,+ timezoneId = sourceTimezoneId,onChannel = { xmltvChannel ->channelBatch.add(EpgChannelEntity(@@ -366,6 +376,7 @@ class EpgSourceRepositoryImpl @Inject constructor(epgProgrammeDao.deleteBySource(sourceId)epgChannelDao.moveToSource(stagingId, sourceId)epgProgrammeDao.moveToSource(stagingId, sourceId)+ epgSourceDao.delete(stagingId)}epgSourceDao.updateRefreshSuccess(sourceId, System.currentTimeMillis())@@ -380,8 +391,11 @@ class EpgSourceRepositoryImpl @Inject constructor(// Clean up any staged rows on failureval stagingId = -sourceIdrunCatching {- epgChannelDao.deleteBySource(stagingId)- epgProgrammeDao.deleteBySource(stagingId)+ transactionRunner.inTransaction {+ epgProgrammeDao.deleteBySource(stagingId)+ epgChannelDao.deleteBySource(stagingId)+ epgSourceDao.delete(stagingId)+ }}val isOversizeError = e is IOException && e.message?.contains("too large", ignoreCase = true) == trueval statusMessage = if (isOversizeError) {@@ -506,7 +520,7 @@ class EpgSourceRepositoryImpl @Inject constructor(}// Delete the pinned row so the next resolution pass can auto-assign via ID/name match.channelEpgMappingDao.deleteForChannel(providerId, channelId)- resolveForProvider(providerId, emptySet())+ resolveProviderUsingPreferences(providerId)return Result.success(Unit)}@@ -526,7 +540,58 @@ class EpgSourceRepositoryImpl @Inject constructor(.filter { it > 0L }.distinct().forEach { providerId ->- resolveForProvider(providerId, emptySet())+ resolveProviderUsingPreferences(providerId)}}++ private suspend fun resolveProviderUsingPreferences(providerId: Long) {+ val hiddenLiveCategoryIds = preferencesRepository+ .getHiddenCategoryIds(providerId, ContentType.LIVE)+ .first()+ resolveForProvider(providerId, hiddenLiveCategoryIds)+ }++ private suspend fun prepareStagingSource(source: EpgSourceEntity, stagingId: Long) {+ val now = System.currentTimeMillis()+ transactionRunner.inTransaction {+ epgProgrammeDao.deleteBySource(stagingId)+ epgChannelDao.deleteBySource(stagingId)+ epgSourceDao.delete(stagingId)+ epgSourceDao.insert(+ EpgSourceEntity(+ id = stagingId,+ name = "${source.name} staging",+ url = "streamvault://epg-source-staging/${source.id}",+ enabled = false,+ priority = Int.MAX_VALUE,+ createdAt = now,+ updatedAt = now+ )+ )+ }+ }++ private suspend fun resolveSourceTimezoneId(sourceId: Long): String? {+ val providerTimezoneIds = providerEpgSourceDao.getProviderIdsForSourceSync(sourceId)+ .distinct()+ .mapNotNull { providerId ->+ providerDao.getById(providerId)+ ?.stalkerDeviceTimezone+ ?.trim()+ ?.takeIf(String::isNotEmpty)+ }+ .distinct()++ return when (providerTimezoneIds.size) {+ 0 -> null+ 1 -> providerTimezoneIds.single()+ else -> {+ Log.w(+ TAG,+ "Source $sourceId has multiple provider timezones $providerTimezoneIds; defaulting no-offset XMLTV timestamps to system timezone"+ )+ null+ }+ }+ }}diff --git a/data/src/main/java/com/streamvault/data/repository/FavoriteRepositoryImpl.kt b/data/src/main/java/com/streamvault/data/repository/FavoriteRepositoryImpl.ktindex 10387fcf..ca7c346e 100644--- a/data/src/main/java/com/streamvault/data/repository/FavoriteRepositoryImpl.kt+++ b/data/src/main/java/com/streamvault/data/repository/FavoriteRepositoryImpl.kt@@ -7,6 +7,7 @@ import com.streamvault.data.local.entity.CategoryCountimport com.streamvault.data.mapper.toDomainimport com.streamvault.data.mapper.toEntityimport com.streamvault.domain.model.*+import kotlinx.coroutines.flow.firstimport com.streamvault.domain.repository.FavoriteRepositoryimport kotlinx.coroutines.flow.Flowimport kotlinx.coroutines.flow.flowOf@@ -70,6 +71,12 @@ class FavoriteRepositoryImpl @Inject constructor(favoriteDao.getGroupFavoriteCounts(providerId, contentType.name).map { list -> list.associate { it.categoryId to it.item_count } }+ override fun getGroupFavoriteCounts(providerIds: List<Long>, contentType: ContentType): Flow<Map<Long, Int>> {+ if (providerIds.isEmpty()) return flowOf(emptyMap())+ return favoriteDao.getGroupFavoriteCountsForProviders(providerIds, contentType.name)+ .map { list -> list.associate { it.categoryId to it.item_count } }+ }+override suspend fun addFavorite(providerId: Long,contentId: Long,@@ -77,6 +84,10 @@ class FavoriteRepositoryImpl @Inject constructor(groupId: Long?): Result<Unit> = try {transactionRunner.inTransaction {+ validateGroupAssignment(providerId, contentType, groupId)+ if (favoriteDao.get(providerId, contentId, contentType.name, groupId) != null) {+ return@inTransaction+ }val maxPos = favoriteDao.getMaxPosition(providerId, groupId) ?: -1val favorite = Favorite(providerId = providerId,@@ -99,7 +110,74 @@ class FavoriteRepositoryImpl @Inject constructor(Result.error("Failed to remove favorite: ${e.message}", e)}+ override suspend fun moveFavoriteToGroup(+ providerId: Long,+ contentId: Long,+ contentType: ContentType,+ fromGroupId: Long?,+ targetGroupId: Long?+ ): Result<Unit> {+ return try {+ if (fromGroupId == targetGroupId) {+ return Result.success(Unit)+ }++ transactionRunner.inTransaction {+ validateGroupAssignment(providerId, contentType, targetGroupId)+ val sourceFavorite = favoriteDao.get(providerId, contentId, contentType.name, fromGroupId)+ ?: throw IllegalArgumentException("Favorite $contentId is not saved in the requested source group")+ val targetFavorite = favoriteDao.get(providerId, contentId, contentType.name, targetGroupId)+ if (targetFavorite != null) {+ favoriteDao.delete(providerId, contentId, contentType.name, fromGroupId)+ } else {+ favoriteDao.updateGroup(sourceFavorite.id, targetGroupId)+ }+ }+ Result.success(Unit)+ } catch (e: Exception) {+ Result.error("Failed to move favorite: ${e.message}", e)+ }+ }++ override suspend fun mergeGroupInto(sourceGroupId: Long, targetGroupId: Long): Result<Unit> = try {+ require(sourceGroupId != targetGroupId) { "Source and target groups must differ" }++ transactionRunner.inTransaction {+ val sourceGroup = virtualGroupDao.getById(sourceGroupId)+ ?: throw IllegalArgumentException("Favorite group $sourceGroupId does not exist")+ val targetGroup = virtualGroupDao.getById(targetGroupId)+ ?: throw IllegalArgumentException("Favorite group $targetGroupId does not exist")++ require(sourceGroup.providerId == targetGroup.providerId) {+ "Favorite groups must belong to the same provider"+ }+ require(sourceGroup.contentType == targetGroup.contentType) {+ "Favorite groups must have the same content type"+ }++ favoriteDao.getByGroup(sourceGroupId).first().forEach { favorite ->+ val targetFavorite = favoriteDao.get(+ providerId = favorite.providerId,+ contentId = favorite.contentId,+ contentType = favorite.contentType.name,+ groupId = targetGroupId+ )+ if (targetFavorite != null) {+ favoriteDao.delete(favorite.providerId, favorite.contentId, favorite.contentType.name, sourceGroupId)+ } else {+ favoriteDao.updateGroup(favorite.id, targetGroupId)+ }+ }++ virtualGroupDao.delete(sourceGroupId)+ }+ Result.success(Unit)+ } catch (e: Exception) {+ Result.error("Failed to merge groups: ${e.message}", e)+ }+override suspend fun reorderFavorites(favorites: List<Favorite>): Result<Unit> = try {+ validateReorderPartition(favorites)val updates = buildReorderUpdates(favorites)if (updates.isNotEmpty()) {favoriteDao.updateAll(updates.map(Favorite::toEntity))@@ -117,11 +195,13 @@ class FavoriteRepositoryImpl @Inject constructor(favoriteDao.getGroupMemberships(providerId, contentId, contentType.name)override suspend fun createGroup(providerId: Long, name: String, iconEmoji: String?, contentType: ContentType): Result<VirtualGroup> = try {+ val position = (virtualGroupDao.getMaxPosition(providerId, contentType.name) ?: -POSITION_STEP) + POSITION_STEPval id = virtualGroupDao.insert(com.streamvault.data.local.entity.VirtualGroupEntity(providerId = providerId,name = name,iconEmoji = iconEmoji,+ position = position,contentType = contentType))@@ -131,6 +211,7 @@ class FavoriteRepositoryImpl @Inject constructor(providerId = providerId,name = name,iconEmoji = iconEmoji,+ position = position,contentType = contentType))@@ -139,7 +220,22 @@ class FavoriteRepositoryImpl @Inject constructor(}override suspend fun deleteGroup(groupId: Long): Result<Unit> = try {- virtualGroupDao.delete(groupId)+ transactionRunner.inTransaction {+ favoriteDao.getByGroup(groupId).first().forEach { favorite ->+ val globalFavorite = favoriteDao.get(+ providerId = favorite.providerId,+ contentId = favorite.contentId,+ contentType = favorite.contentType.name,+ groupId = null+ )+ if (globalFavorite != null) {+ favoriteDao.delete(favorite.providerId, favorite.contentId, favorite.contentType.name, groupId)+ } else {+ favoriteDao.updateGroup(favorite.id, null)+ }+ }+ virtualGroupDao.delete(groupId)+ }Result.success(Unit)} catch (e: Exception) {Result.error("Failed to delete group: ${e.message}", e)@@ -178,6 +274,38 @@ class FavoriteRepositoryImpl @Inject constructor(}}+ private fun validateReorderPartition(favorites: List<Favorite>) {+ if (favorites.isEmpty()) return++ require(favorites.map(Favorite::id).distinct().size == favorites.size) {+ "Favorite reorder request contains duplicate items"+ }++ val partitions = favorites+ .map { favorite -> favorite.providerId to favorite.groupId }+ .distinct()+ require(partitions.size == 1) {+ "Favorite reorder request must stay within one provider and group partition"+ }+ }++ private suspend fun validateGroupAssignment(+ providerId: Long,+ contentType: ContentType,+ groupId: Long?+ ) {+ val targetGroupId = groupId ?: return+ val group = virtualGroupDao.getById(targetGroupId)+ ?: throw IllegalArgumentException("Favorite group $targetGroupId does not exist")++ require(group.providerId == providerId) {+ "Favorite group $targetGroupId belongs to provider ${group.providerId}, not $providerId"+ }+ require(group.contentType == contentType) {+ "Favorite group $targetGroupId accepts ${group.contentType}, not $contentType"+ }+ }+private fun assignSparsePositions(items: List<Favorite>,leftBound: Long?,diff --git a/data/src/main/java/com/streamvault/data/repository/MovieRepositoryImpl.kt b/data/src/main/java/com/streamvault/data/repository/MovieRepositoryImpl.ktindex 6c555c33..a553b229 100644--- a/data/src/main/java/com/streamvault/data/repository/MovieRepositoryImpl.kt+++ b/data/src/main/java/com/streamvault/data/repository/MovieRepositoryImpl.kt@@ -1,6 +1,7 @@package com.streamvault.data.repositoryimport android.database.sqlite.SQLiteException+import android.util.Logimport com.streamvault.data.local.DatabaseTransactionRunnerimport com.streamvault.data.local.dao.CategoryDaoimport com.streamvault.data.local.dao.FavoriteDao@@ -31,6 +32,7 @@ import com.streamvault.domain.model.LibraryBrowseQueryimport com.streamvault.domain.model.LibrarySortByimport com.streamvault.domain.model.Movieimport com.streamvault.domain.model.PagedResult+import com.streamvault.domain.model.PlaybackHistoryimport com.streamvault.domain.model.ProviderTypeimport com.streamvault.domain.model.Resultimport com.streamvault.domain.model.Result.Success@@ -38,6 +40,7 @@ import com.streamvault.domain.model.StreamInfoimport com.streamvault.domain.model.StreamTypeimport com.streamvault.domain.model.VodSyncModeimport com.streamvault.domain.repository.MovieRepository+import com.streamvault.domain.repository.PlaybackHistoryRepositoryimport com.streamvault.domain.repository.SyncMetadataRepositoryimport kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.Dispatchers@@ -74,13 +77,16 @@ class MovieRepositoryImpl @Inject constructor(private val preferencesRepository: PreferencesRepository,private val favoriteDao: FavoriteDao,private val playbackHistoryDao: PlaybackHistoryDao,+ private val playbackHistoryRepository: PlaybackHistoryRepository,private val xtreamStreamUrlResolver: XtreamStreamUrlResolver,private val movieCategoryHydrationDao: MovieCategoryHydrationDao,private val syncMetadataRepository: SyncMetadataRepository,private val transactionRunner: DatabaseTransactionRunner) : MovieRepository {private companion object {+ const val TAG = "MovieRepository"const val SEARCH_RESULT_LIMIT = 200+ const val SEARCH_OVERSAMPLE_LIMIT = 500const val MIN_SEARCH_QUERY_LENGTH = 2const val BROWSE_WINDOW_BUFFER = 80const val XTREAM_MOVIE_HYDRATION_TIMEOUT_MILLIS = 60_000L@@ -288,8 +294,8 @@ class MovieRepositoryImpl @Inject constructor(getTopRatedPreview(providerId, limit = maxOf(limit * 4, 32))) { categoryItems, topRated ->buildRelatedContent(- movies = (categoryItems + topRated).distinctBy { it.id },- movieId = movieId,+ target = targetMovie,+ candidates = (categoryItems + topRated).distinctBy { it.id }.filterNot { it.id == movieId },limit = limit)}@@ -340,7 +346,11 @@ class MovieRepositoryImpl @Inject constructor(if (ftsQuery.isNullOrBlank()) {flowOf(emptyList())} else combine(- safeMovieSearchFlow(movieDao.search(providerId, ftsQuery, SEARCH_RESULT_LIMIT)),+ safeMovieSearchFlow(+ source = movieDao.search(providerId, ftsQuery, SEARCH_OVERSAMPLE_LIMIT),+ fallback = movieDao.searchFallback(providerId, query.trim().toSqlLikePattern(), SEARCH_OVERSAMPLE_LIMIT),+ rawQuery = query.trim()+ ),preferencesRepository.parentalControlLevel) { entities, level: Int ->if (level >= 3) {@@ -434,13 +444,6 @@ class MovieRepositoryImpl @Inject constructor(override suspend fun refreshMovies(providerId: Long): Result<Unit> =Result.success(Unit) // Handled by ProviderRepository- override suspend fun updateWatchProgress(movieId: Long, progress: Long): Result<Unit> = try {- movieDao.updateWatchProgress(movieId, progress)- Result.success(Unit)- } catch (e: Exception) {- Result.error("Failed to update movie watch progress", e)- }-private fun buildRecommendations(movies: List<Movie>,favoriteIds: Set<Long>,@@ -481,15 +484,12 @@ class MovieRepositoryImpl @Inject constructor(}private fun buildRelatedContent(- movies: List<Movie>,- movieId: Long,+ target: Movie,+ candidates: List<Movie>,limit: Int): List<Movie> {- val target = movies.firstOrNull { it.id == movieId } ?: return emptyList()-- return movies+ return candidates.asSequence()- .filterNot { it.id == movieId }.map { movie -> movie to relatedScore(target, movie) }.filter { (_, score) -> score > 0f }.sortedWith(@@ -555,7 +555,16 @@ class MovieRepositoryImpl @Inject constructor(val ftsQuery = normalizedSearch.toFtsPrefixQuery() ?: return flowOf(emptyList())query.categoryId?.let { categoryId ->combine(- safeMovieSearchFlow(movieDao.searchByCategory(query.providerId, categoryId, ftsQuery, SEARCH_RESULT_LIMIT)),+ safeMovieSearchFlow(+ source = movieDao.searchByCategory(query.providerId, categoryId, ftsQuery, SEARCH_OVERSAMPLE_LIMIT),+ fallback = movieDao.searchByCategoryFallback(+ query.providerId,+ categoryId,+ normalizedSearch.toSqlLikePattern(),+ SEARCH_OVERSAMPLE_LIMIT+ ),+ rawQuery = normalizedSearch+ ),preferencesRepository.parentalControlLevel) { entities, level ->if (level >= 3) entities.filter { !it.isUserProtected } else entities@@ -770,6 +779,16 @@ class MovieRepositoryImpl @Inject constructor(movieDao.getCountByCategory(query.providerId, categoryId)} ?: movieDao.getCount(query.providerId)}+ normalizedSearch.isBlank() && query.filterBy.type == LibraryFilterType.TOP_RATED -> {+ query.categoryId?.let { categoryId ->+ movieDao.getTopRatedCountByCategory(query.providerId, categoryId)+ } ?: movieDao.getTopRatedCountByProvider(query.providerId)+ }+ normalizedSearch.isBlank() && query.filterBy.type == LibraryFilterType.RECENTLY_UPDATED -> {+ query.categoryId?.let { categoryId ->+ movieDao.getFreshCountByCategory(query.providerId, categoryId)+ } ?: movieDao.getFreshCountByProvider(query.providerId)+ }query.filterBy.type in setOf(LibraryFilterType.ALL, LibraryFilterType.TOP_RATED, LibraryFilterType.RECENTLY_UPDATED) &&query.sortBy in setOf(LibrarySortBy.LIBRARY, LibrarySortBy.TITLE, LibrarySortBy.RELEASE, LibrarySortBy.UPDATED, LibrarySortBy.RATING) -> {query.categoryId?.let { categoryId ->@@ -958,8 +977,6 @@ class MovieRepositoryImpl @Inject constructor(LibrarySortBy.UPDATED,LibrarySortBy.RATING) -> true- query.filterBy.type == LibraryFilterType.TOP_RATED -> true- query.filterBy.type == LibraryFilterType.RECENTLY_UPDATED -> trueelse -> false}}@@ -1010,15 +1027,32 @@ class MovieRepositoryImpl @Inject constructor(.any { value -> value.lowercase().contains(normalizedQuery) }}- private fun safeMovieSearchFlow(source: Flow<List<MovieBrowseEntity>>): Flow<List<MovieBrowseEntity>> =+ private fun safeMovieSearchFlow(+ source: Flow<List<MovieBrowseEntity>>,+ fallback: Flow<List<MovieBrowseEntity>>,+ rawQuery: String+ ): Flow<List<MovieBrowseEntity>> =source.catch { error ->if (error is SQLiteException) {- emit(emptyList<MovieBrowseEntity>())+ Log.w(TAG, "FTS movie search failed for query '$rawQuery'; falling back to LIKE search", error)+ emitAll(fallback)} else {throw error}}+ private fun String.toSqlLikePattern(): String {+ val escaped = buildString(length) {+ [email protected] { char ->+ when (char) {+ '%', '_', '\\' -> append('\\')+ }+ append(char)+ }+ }+ return "%$escaped%"+ }+private suspend fun ensureXtreamCategoryLoaded(providerId: Long,categoryId: Long,diff --git a/data/src/main/java/com/streamvault/data/repository/PlaybackHistoryRepositoryImpl.kt b/data/src/main/java/com/streamvault/data/repository/PlaybackHistoryRepositoryImpl.ktindex d14e9b2f..4c7c5871 100644--- a/data/src/main/java/com/streamvault/data/repository/PlaybackHistoryRepositoryImpl.kt+++ b/data/src/main/java/com/streamvault/data/repository/PlaybackHistoryRepositoryImpl.kt@@ -20,6 +20,8 @@ import kotlinx.coroutines.SupervisorJobimport kotlinx.coroutines.delayimport kotlinx.coroutines.launchimport kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.combineimport kotlinx.coroutines.flow.mapimport kotlinx.coroutines.flow.SharingStartedimport kotlinx.coroutines.flow.StateFlow@@ -39,6 +41,7 @@ class PlaybackHistoryRepositoryImpl @Inject constructor() : PlaybackHistoryRepository {private val repositoryScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)private val pendingResumeUpdates = ConcurrentHashMap<PlaybackKey, PlaybackHistory>()+ private val pendingResumeUpdatesState = MutableStateFlow<Map<PlaybackKey, PlaybackHistory>>(emptyMap())private val isIncognito: StateFlow<Boolean> =preferencesRepository.isIncognitoMode.stateIn(repositoryScope, SharingStarted.Eagerly, false)@@ -53,11 +56,27 @@ class PlaybackHistoryRepositoryImpl @Inject constructor(}override fun getRecentlyWatched(limit: Int): Flow<List<PlaybackHistory>> {- return dao.getRecentlyWatched(limit).map { list -> list.map { it.toDomain() } }+ return mergedRecentHistory(+ persisted = dao.getRecentlyWatched(limit).map { list -> list.map { it.toDomain() } },+ limit = limit+ ) { true }}override fun getRecentlyWatchedByProvider(providerId: Long, limit: Int): Flow<List<PlaybackHistory>> {- return dao.getRecentlyWatchedByProvider(providerId, limit).map { list -> list.map { it.toDomain() } }+ return mergedRecentHistory(+ persisted = dao.getRecentlyWatchedByProvider(providerId, limit).map { list -> list.map { it.toDomain() } },+ limit = limit+ ) { history -> history.providerId == providerId }+ }++ override fun getRecentlyWatchedByProviders(providerIds: Set<Long>, limit: Int): Flow<List<PlaybackHistory>> {+ if (providerIds.isEmpty()) {+ return kotlinx.coroutines.flow.flowOf(emptyList())+ }+ return mergedRecentHistory(+ persisted = dao.getRecentlyWatchedByProviders(providerIds, limit).map { list -> list.map { it.toDomain() } },+ limit = limit+ ) { history -> history.providerId in providerIds }}override fun getUnwatchedCount(providerId: Long, seriesId: Long): Flow<Int> {@@ -68,7 +87,17 @@ class PlaybackHistoryRepositoryImpl @Inject constructor()}- override suspend fun getPlaybackHistory(contentId: Long, contentType: ContentType, providerId: Long): PlaybackHistory? {+ override suspend fun getPlaybackHistory(+ contentId: Long,+ contentType: ContentType,+ providerId: Long,+ seriesId: Long?,+ seasonNumber: Int?,+ episodeNumber: Int?+ ): PlaybackHistory? {+ val key = PlaybackKey(contentId, contentType, providerId)+ pendingResumeUpdates[key]?.let { return it }+val directMatch = dao.get(contentId, contentType.name, providerId)?.toDomain()if (directMatch != null) {return directMatch@@ -77,7 +106,12 @@ class PlaybackHistoryRepositoryImpl @Inject constructor(return when (contentType) {ContentType.MOVIE -> dao.getLatestMovieHistoryBySharedTmdb(contentId, providerId)?.toDomain()ContentType.SERIES -> dao.getLatestSeriesHistoryBySharedTmdb(contentId, providerId)?.toDomain()- ContentType.SERIES_EPISODE,+ ContentType.SERIES_EPISODE -> {+ if (seriesId != null && seasonNumber != null && episodeNumber != null) {+ dao.getLatestEpisodeHistoryByCoordinates(providerId, seriesId, seasonNumber, episodeNumber)+ ?.toDomain()+ } else null+ }ContentType.LIVE -> null}}@@ -88,7 +122,8 @@ class PlaybackHistoryRepositoryImpl @Inject constructor(return Result.success(Unit)}- val existing = takePendingResumeUpdate(history.playbackKey())+ val key = history.playbackKey()+ val existing = pendingResumeUpdates[history.playbackKey()]?: dao.get(history.contentId, history.contentType.name, history.providerId)?.toDomain()val resolvedTotalDuration = history.totalDurationMs.takeIf { it > 0L } ?: existing?.totalDurationMs ?: 0Lval resolvedResumePosition = when {@@ -108,6 +143,7 @@ class PlaybackHistoryRepositoryImpl @Inject constructor(dao.insertOrUpdate(updatedHistory.toEntity())syncDenormalizedProgress(updatedHistory.contentId, updatedHistory.contentType, updatedHistory.providerId)}+ clearPendingResumeUpdate(key)Result.success(Unit)} catch (e: Exception) {Result.error("Failed to mark content as watched", e)@@ -120,7 +156,8 @@ class PlaybackHistoryRepositoryImpl @Inject constructor(return Result.success(Unit)}- val existing = takePendingResumeUpdate(history.playbackKey())+ val key = history.playbackKey()+ val existing = pendingResumeUpdates[key]?: dao.get(history.contentId, history.contentType.name, history.providerId)?.toDomain()val updatedHistory = history.copy(streamUrl = XtreamUrlFactory.sanitizePersistedStreamUrl(history.streamUrl, history.providerId),@@ -138,6 +175,7 @@ class PlaybackHistoryRepositoryImpl @Inject constructor(dao.insertOrUpdate(updatedHistory.toEntity())syncDenormalizedProgress(updatedHistory.contentId, updatedHistory.contentType, updatedHistory.providerId)}+ clearPendingResumeUpdate(key)Result.success(Unit)} catch (e: Exception) {Result.error("Failed to record playback history", e)@@ -150,7 +188,8 @@ class PlaybackHistoryRepositoryImpl @Inject constructor(return Result.success(Unit)}- val existing = pendingResumeUpdates[history.playbackKey()]+ val key = history.playbackKey()+ val existing = pendingResumeUpdates[key]?: dao.get(history.contentId, history.contentType.name, history.providerId)?.toDomain()val updatedHistory = history.copy(@@ -164,6 +203,11 @@ class PlaybackHistoryRepositoryImpl @Inject constructor(lastWatchedAt = System.currentTimeMillis())pendingResumeUpdates[history.playbackKey()] = updatedHistory+ publishPendingResumeUpdates()+ transactionRunner.inTransaction {+ dao.insertOrUpdate(updatedHistory.toEntity())+ syncDenormalizedProgress(updatedHistory.contentId, updatedHistory.contentType, updatedHistory.providerId)+ }Result.success(Unit)} catch (e: Exception) {Result.error("Failed to update playback resume position", e)@@ -221,18 +265,50 @@ class PlaybackHistoryRepositoryImpl @Inject constructor(private suspend fun flushPendingResumeUpdates() {val snapshot = pendingResumeUpdates.entries.toList()+ var changed = falsesnapshot.forEach { (key, history) ->if (pendingResumeUpdates.remove(key, history)) {+ changed = truetransactionRunner.inTransaction {dao.insertOrUpdate(history.toEntity())syncDenormalizedProgress(history.contentId, history.contentType, history.providerId)}}}+ if (changed) {+ publishPendingResumeUpdates()+ }+ }++ private fun clearPendingResumeUpdate(key: PlaybackKey) {+ if (pendingResumeUpdates.remove(key) != null) {+ publishPendingResumeUpdates()+ }+ }++ private fun publishPendingResumeUpdates() {+ pendingResumeUpdatesState.value = pendingResumeUpdates.toMap()}- private fun takePendingResumeUpdate(key: PlaybackKey): PlaybackHistory? =- pendingResumeUpdates.remove(key)+ private fun mergedRecentHistory(+ persisted: Flow<List<PlaybackHistory>>,+ limit: Int,+ includePending: (PlaybackHistory) -> Boolean+ ): Flow<List<PlaybackHistory>> = combine(persisted, pendingResumeUpdatesState) { persistedItems, pendingItems ->+ val mergedByKey = LinkedHashMap<PlaybackKey, PlaybackHistory>()+ persistedItems.forEach { history ->+ mergedByKey[history.playbackKey()] = history+ }+ pendingItems.values+ .asSequence()+ .filter(includePending)+ .forEach { history ->+ mergedByKey[history.playbackKey()] = history+ }+ mergedByKey.values+ .sortedByDescending(PlaybackHistory::lastWatchedAt)+ .take(limit)+ }private suspend fun syncDenormalizedProgress(contentId: Long, contentType: ContentType, providerId: Long) {when (contentType) {@@ -242,6 +318,7 @@ class PlaybackHistoryRepositoryImpl @Inject constructor(}}+private suspend fun syncDenormalizedProgressForProvider(providerId: Long) {movieDao.syncWatchProgressFromHistoryByProvider(providerId)episodeDao.syncWatchProgressFromHistoryByProvider(providerId)diff --git a/data/src/main/java/com/streamvault/data/repository/ProviderRepositoryImpl.kt b/data/src/main/java/com/streamvault/data/repository/ProviderRepositoryImpl.ktindex d6cc3025..5f81a2a7 100644--- a/data/src/main/java/com/streamvault/data/repository/ProviderRepositoryImpl.kt+++ b/data/src/main/java/com/streamvault/data/repository/ProviderRepositoryImpl.kt@@ -3,6 +3,8 @@ package com.streamvault.data.repositoryimport com.streamvault.data.local.DatabaseTransactionRunnerimport com.streamvault.data.local.dao.*import com.streamvault.data.local.entity.ProviderEntity+import com.streamvault.data.manager.recording.RecordingAlarmScheduler+import com.streamvault.data.manager.reminder.ProgramReminderAlarmSchedulerimport com.streamvault.data.mapper.*import com.streamvault.data.preferences.PreferencesRepositoryimport com.streamvault.data.remote.stalker.StalkerApiService@@ -30,6 +32,7 @@ import kotlinx.coroutines.flow.Flowimport kotlinx.coroutines.flow.firstimport kotlinx.coroutines.flow.mapimport kotlinx.coroutines.launch+import java.util.logging.Loggerimport javax.inject.Injectimport javax.inject.Singleton@@ -38,17 +41,22 @@ class ProviderRepositoryImpl @Inject constructor(private val providerDao: ProviderDao,private val channelDao: ChannelDao,private val programDao: ProgramDao,+ private val recordingRunDao: RecordingRunDao,+ private val programReminderDao: ProgramReminderDao,private val stalkerApiService: StalkerApiService,private val xtreamApiService: XtreamApiService,private val credentialCrypto: CredentialCrypto,private val preferencesRepository: PreferencesRepository,private val syncManager: SyncManager,private val syncMetadataRepository: SyncMetadataRepository,- private val transactionRunner: DatabaseTransactionRunner+ private val transactionRunner: DatabaseTransactionRunner,+ private val recordingAlarmScheduler: RecordingAlarmScheduler,+ private val programReminderAlarmScheduler: ProgramReminderAlarmScheduler) : ProviderRepository {private companion object {const val XTREAM_GUIDE_BATCH_CONCURRENCY = 4const val BACKGROUND_EPG_START_DELAY_MS = 15_000L+ val logger: Logger = Logger.getLogger(ProviderRepositoryImpl::class.java.name)}private val repositoryScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)@@ -77,15 +85,37 @@ class ProviderRepositoryImpl @Inject constructor(}override suspend fun deleteProvider(id: Long): Result<Unit> = try {- // ProgramEntity still has no provider FK, so it requires explicit cleanup.- programDao.deleteByProvider(id)- providerDao.delete(id)- syncManager.onProviderDeleted(id)+ val recordingRunIds = recordingRunDao.getIdsByProvider(id)+ val reminderIds = programReminderDao.getIdsByProvider(id)+ transactionRunner.inTransaction {+ // ProgramEntity still has no provider FK, so it requires explicit cleanup.+ programDao.deleteByProvider(id)+ providerDao.delete(id)+ }+ recordingRunIds.forEach { runId ->+ runPostDeleteCleanup("recording alarm $runId") {+ recordingAlarmScheduler.cancel(runId)+ }+ }+ reminderIds.forEach { reminderId ->+ runPostDeleteCleanup("reminder alarm $reminderId") {+ programReminderAlarmScheduler.cancel(reminderId)+ }+ }+ runPostDeleteCleanup("provider sync cleanup $id") {+ syncManager.onProviderDeleted(id)+ }Result.success(Unit)} catch (e: Exception) {Result.error("Failed to delete provider: ${e.message}", e)}+ private inline fun runPostDeleteCleanup(step: String, block: () -> Unit) {+ runCatching(block).onFailure { throwable ->+ logger.warning("Provider delete committed but post-delete cleanup failed for $step: ${throwable.message}")+ }+ }+override suspend fun setActiveProvider(id: Long): Result<Unit> = try {providerDao.setActive(id)Result.success(Unit)@@ -115,6 +145,12 @@ class ProviderRepositoryImpl @Inject constructor(}onProgress?.invoke("Authenticating...")val existingProvider = if (id != null) {+ // Edit path: check that the new normalized identity does not collide with a+ // different provider before we commit the update.+ val collision = providerDao.getByUrlAndUser(normalizedServerUrl, normalizedUsername)+ if (collision != null && collision.id != id) {+ return Result.error("A provider with this server URL and username already exists.")+ }providerDao.getById(id)} else {providerDao.getByUrlAndUser(normalizedServerUrl, normalizedUsername)@@ -156,26 +192,11 @@ class ProviderRepositoryImpl @Inject constructor(}providerDao.setActive(providerData.id)- when (val syncResult = syncManager.sync(providerData.id, force = false, onProgress = onProgress)) {- is Result.Success -> {- val finalStatus = if (syncManager.currentSyncState(providerData.id) is SyncState.Partial) {- ProviderStatus.PARTIAL- } else {- ProviderStatus.ACTIVE- }- updateProviderSyncStatus(providerData.id, finalStatus, System.currentTimeMillis())- maybeScheduleBackgroundEpgSync(providerData.id)- Result.success(providerData.copy(status = finalStatus))- }- is Result.Error -> {- updateProviderSyncStatus(providerData.id, ProviderStatus.ERROR)- Result.error(- "Provider login succeeded, but initial sync failed. The provider was saved and can be retried from Settings: ${syncResult.message}",- syncResult.exception- )- }- is Result.Loading -> Result.error("Unexpected loading state")- }+ handleInitialOnboardingSync(+ providerData = providerData,+ syncResult = syncManager.sync(providerData.id, force = false, onProgress = onProgress),+ syncFailurePrefix = "Provider login succeeded, but initial sync failed. The provider was saved and can be retried from Settings"+ )}is Result.Error -> Result.error(authResult.message, authResult.exception)is Result.Loading -> Result.error("Unexpected loading state")@@ -205,6 +226,12 @@ class ProviderRepositoryImpl @Inject constructor(}val existingProvider = if (id != null) {+ // Edit path: check that the new normalized URL does not collide with a different+ // provider before we commit the update.+ val collision = providerDao.getByUrlAndUser(normalizedUrl, "")+ if (collision != null && collision.id != id) {+ return Result.error("A playlist provider with this URL already exists.")+ }providerDao.getById(id)} else {providerDao.getByUrlAndUser(normalizedUrl, "")@@ -236,28 +263,12 @@ class ProviderRepositoryImpl @Inject constructor(provider.copy(id = newId).copy(password = "")}- providerDao.deactivateAll()- providerDao.activate(providerData.id)- when (val syncResult = syncManager.sync(providerData.id, force = false, onProgress = onProgress)) {- is Result.Success -> {- val finalStatus = if (syncManager.currentSyncState(providerData.id) is SyncState.Partial) {- ProviderStatus.PARTIAL- } else {- ProviderStatus.ACTIVE- }- updateProviderSyncStatus(providerData.id, finalStatus, System.currentTimeMillis())- maybeScheduleBackgroundEpgSync(providerData.id)- Result.success(providerData.copy(status = finalStatus))- }- is Result.Error -> {- updateProviderSyncStatus(providerData.id, ProviderStatus.ERROR)- Result.error(- "Playlist saved, but initial sync failed. The provider was saved and can be retried from Settings: ${syncResult.message}",- syncResult.exception- )- }- is Result.Loading -> Result.error("Unexpected loading state")- }+ providerDao.setActive(providerData.id)+ handleInitialOnboardingSync(+ providerData = providerData,+ syncResult = syncManager.sync(providerData.id, force = false, onProgress = onProgress),+ syncFailurePrefix = "Playlist saved, but initial sync failed. The provider was saved and can be retried from Settings"+ )} catch (e: Exception) {Result.error("Failed to add M3U provider: ${e.message}", e)}@@ -292,6 +303,12 @@ class ProviderRepositoryImpl @Inject constructor(onProgress?.invoke("Authenticating...")val existingProvider = if (id != null) {+ // Edit path: check that the new normalized identity does not collide with a+ // different provider before we commit the update.+ val collision = providerDao.getByUrlAndUser(normalizedPortalUrl, "", normalizedMacAddress)+ if (collision != null && collision.id != id) {+ return Result.error("A Stalker provider with this portal URL and MAC address already exists.")+ }providerDao.getById(id)} else {providerDao.getByUrlAndUser(normalizedPortalUrl, "", normalizedMacAddress)@@ -345,32 +362,47 @@ class ProviderRepositoryImpl @Inject constructor(}providerDao.setActive(providerData.id)- when (val syncResult = syncManager.sync(providerData.id, force = false, onProgress = onProgress)) {- is Result.Success -> {- val finalStatus = if (syncManager.currentSyncState(providerData.id) is SyncState.Partial) {- ProviderStatus.PARTIAL- } else {- ProviderStatus.ACTIVE- }- updateProviderSyncStatus(providerData.id, finalStatus, System.currentTimeMillis())- maybeScheduleBackgroundEpgSync(providerData.id)- Result.success(providerData.copy(status = finalStatus))- }- is Result.Error -> {- updateProviderSyncStatus(providerData.id, ProviderStatus.ERROR)- Result.error(- "Provider login succeeded, but initial sync failed. The provider was saved and can be retried from Settings: ${syncResult.message}",- syncResult.exception- )- }- is Result.Loading -> Result.error("Unexpected loading state")- }+ handleInitialOnboardingSync(+ providerData = providerData,+ syncResult = syncManager.sync(providerData.id, force = false, onProgress = onProgress),+ syncFailurePrefix = "Provider login succeeded, but initial sync failed. The provider was saved and can be retried from Settings"+ )}is Result.Error -> Result.error(authResult.message, authResult.exception)is Result.Loading -> Result.error("Unexpected loading state")}}+ private suspend fun handleInitialOnboardingSync(+ providerData: Provider,+ syncResult: Result<Unit>,+ syncFailurePrefix: String+ ): Result<Provider> = when (syncResult) {+ is Result.Success -> {+ val finalStatus = if (syncManager.currentSyncState(providerData.id) is SyncState.Partial) {+ ProviderStatus.PARTIAL+ } else {+ ProviderStatus.ACTIVE+ }+ updateProviderSyncStatus(providerData.id, finalStatus, System.currentTimeMillis())+ maybeScheduleBackgroundEpgSync(providerData.id)+ Result.success(providerData.copy(status = finalStatus))+ }+ is Result.Error -> {+ updateProviderSyncStatus(providerData.id, ProviderStatus.ERROR)+ val message = "$syncFailurePrefix: ${syncResult.message}"+ Result.error(+ message,+ ProviderSavedWithSyncErrorException(+ provider = providerData.copy(status = ProviderStatus.ERROR),+ message = message,+ cause = syncResult.exception+ )+ )+ }+ is Result.Loading -> Result.error("Unexpected loading state")+ }+/*** Delegates to [SyncManager] — the single source of truth for the full sync pipeline.*/diff --git a/data/src/main/java/com/streamvault/data/repository/SeriesRepositoryImpl.kt b/data/src/main/java/com/streamvault/data/repository/SeriesRepositoryImpl.ktindex a0bfe497..e187a460 100644--- a/data/src/main/java/com/streamvault/data/repository/SeriesRepositoryImpl.kt+++ b/data/src/main/java/com/streamvault/data/repository/SeriesRepositoryImpl.kt@@ -1,6 +1,7 @@package com.streamvault.data.repositoryimport android.database.sqlite.SQLiteException+import android.util.Logimport com.streamvault.data.local.dao.*import com.streamvault.data.local.entity.*import com.streamvault.data.mapper.*@@ -13,6 +14,7 @@ import com.streamvault.data.security.CredentialCryptoimport com.streamvault.data.sync.ContentCachePolicyimport com.streamvault.domain.model.*import com.streamvault.domain.model.Result.Success+import com.streamvault.domain.repository.PlaybackHistoryRepositoryimport com.streamvault.domain.repository.SeriesRepositoryimport kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.Dispatchers@@ -50,6 +52,7 @@ class SeriesRepositoryImpl @Inject constructor(private val categoryDao: CategoryDao,private val favoriteDao: FavoriteDao,private val playbackHistoryDao: PlaybackHistoryDao,+ private val playbackHistoryRepository: PlaybackHistoryRepository,private val providerDao: ProviderDao,private val stalkerApiService: StalkerApiService,private val xtreamApiService: XtreamApiService,@@ -59,7 +62,9 @@ class SeriesRepositoryImpl @Inject constructor(private val seriesCategoryHydrationDao: SeriesCategoryHydrationDao) : SeriesRepository {private companion object {+ const val TAG = "SeriesRepository"const val SEARCH_RESULT_LIMIT = 200+ const val SEARCH_OVERSAMPLE_LIMIT = 500const val MIN_SEARCH_QUERY_LENGTH = 2const val BROWSE_WINDOW_BUFFER = 80const val XTREAM_SERIES_CATEGORY_TIMEOUT_MILLIS = 60_000L@@ -282,7 +287,11 @@ class SeriesRepositoryImpl @Inject constructor(if (ftsQuery.isNullOrBlank()) {flowOf(emptyList())} else combine(- safeSeriesSearchFlow(seriesDao.search(providerId, ftsQuery, SEARCH_RESULT_LIMIT)),+ safeSeriesSearchFlow(+ source = seriesDao.search(providerId, ftsQuery, SEARCH_OVERSAMPLE_LIMIT),+ fallback = seriesDao.searchFallback(providerId, query.trim().toSqlLikePattern(), SEARCH_OVERSAMPLE_LIMIT),+ rawQuery = query.trim()+ ),preferencesRepository.parentalControlLevel) { entities, level: Int ->if (level >= 3) {@@ -302,6 +311,9 @@ class SeriesRepositoryImpl @Inject constructor(override suspend fun getSeriesById(seriesId: Long): Series? =seriesDao.getById(seriesId)?.toDomain()+ override suspend fun getEpisodeById(episodeId: Long): Episode? =+ episodeDao.getById(episodeId)?.toDomain()+override suspend fun getSeriesDetails(providerId: Long, seriesId: Long): Result<Series> {val seriesEntity = seriesDao.getById(seriesId)?: seriesDao.getBySeriesId(providerId, seriesId)@@ -383,14 +395,23 @@ class SeriesRepositoryImpl @Inject constructor(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- )- }+ val seenIds = mutableSetOf<String>()+ val mergedEpisodes = remoteSeason.episodes+ .mapNotNull { remoteEpisode ->+ val remoteEpisodeId = remoteEpisode.episodeId.takeIf { it > 0 } ?: remoteEpisode.id+ val dedupeKey = if (remoteEpisodeId > 0) remoteEpisodeId.toString()+ else "${remoteEpisode.seasonNumber}-${remoteEpisode.episodeNumber}"+ if (!seenIds.add(dedupeKey)) {+ Log.w(TAG, "Duplicate episode skipped: seriesId=${seriesEntity.id} key=$dedupeKey")+ return@mapNotNull null+ }+ persistedByRemoteEpisodeId[remoteEpisodeId] ?: remoteEpisode.copy(+ episodeId = remoteEpisodeId,+ seriesId = seriesEntity.id,+ providerId = providerId+ )+ }+ .sortedBy { it.episodeNumber }remoteSeason.copy(episodes = mergedEpisodes,episodeCount = mergedEpisodes.size@@ -450,13 +471,6 @@ class SeriesRepositoryImpl @Inject constructor(override suspend fun refreshSeries(providerId: Long): Result<Unit> =Result.success(Unit) // Handled by ProviderRepository- override suspend fun updateEpisodeWatchProgress(episodeId: Long, progress: Long): Result<Unit> = try {- episodeDao.updateWatchProgress(episodeId, progress)- Result.success(Unit)- } catch (e: Exception) {- Result.error("Failed to update episode watch progress", e)- }-private suspend fun buildSeriesWithPersistedEpisodes(seriesEntity: SeriesEntity): Series {val episodes = episodeDao.getBySeriesSync(seriesEntity.id).map { it.toDomain() }val seasons = episodes.groupBy { it.seasonNumber }@@ -481,7 +495,16 @@ class SeriesRepositoryImpl @Inject constructor(val ftsQuery = normalizedSearch.toFtsPrefixQuery() ?: return flowOf(emptyList())query.categoryId?.let { categoryId ->combine(- safeSeriesSearchFlow(seriesDao.searchByCategory(query.providerId, categoryId, ftsQuery, SEARCH_RESULT_LIMIT)),+ safeSeriesSearchFlow(+ source = seriesDao.searchByCategory(query.providerId, categoryId, ftsQuery, SEARCH_OVERSAMPLE_LIMIT),+ fallback = seriesDao.searchByCategoryFallback(+ query.providerId,+ categoryId,+ normalizedSearch.toSqlLikePattern(),+ SEARCH_OVERSAMPLE_LIMIT+ ),+ rawQuery = normalizedSearch+ ),preferencesRepository.parentalControlLevel) { entities, level ->if (level >= 3) entities.filter { !it.isUserProtected } else entities@@ -688,6 +711,16 @@ class SeriesRepositoryImpl @Inject constructor(seriesDao.getCountByCategory(query.providerId, categoryId)} ?: seriesDao.getCount(query.providerId)}+ normalizedSearch.isBlank() && query.filterBy.type == LibraryFilterType.TOP_RATED -> {+ query.categoryId?.let { categoryId ->+ seriesDao.getTopRatedCountByCategory(query.providerId, categoryId)+ } ?: seriesDao.getTopRatedCountByProvider(query.providerId)+ }+ normalizedSearch.isBlank() && query.filterBy.type == LibraryFilterType.RECENTLY_UPDATED -> {+ query.categoryId?.let { categoryId ->+ seriesDao.getFreshCountByCategory(query.providerId, categoryId)+ } ?: seriesDao.getFreshCountByProvider(query.providerId)+ }query.filterBy.type in setOf(LibraryFilterType.ALL, LibraryFilterType.TOP_RATED, LibraryFilterType.RECENTLY_UPDATED) &&query.sortBy in setOf(LibrarySortBy.LIBRARY, LibrarySortBy.TITLE, LibrarySortBy.RELEASE, LibrarySortBy.UPDATED, LibrarySortBy.RATING) -> {query.categoryId?.let { categoryId ->@@ -726,6 +759,12 @@ class SeriesRepositoryImpl @Inject constructor(}.mapNotNull { it.seriesId ?: it.contentId }.toSet()+ val completedSeriesIds = history+ .asSequence()+ .filter { it.contentType == ContentType.SERIES_EPISODE }+ .filter { it.totalDurationMs > 0L && it.resumePositionMs >= (it.totalDurationMs * 0.95f).toLong() }+ .mapNotNull { it.seriesId }+ .toSet()val watchCounts = history.asSequence().filter { it.contentType == ContentType.SERIES || it.contentType == ContentType.SERIES_EPISODE }@@ -737,6 +776,7 @@ class SeriesRepositoryImpl @Inject constructor(query = query,favoriteIds = favoriteIds,inProgressIds = inProgressIds,+ completedSeriesIds = completedSeriesIds,watchCounts = watchCounts).drop(query.offset).take(query.limit)}@@ -872,8 +912,6 @@ class SeriesRepositoryImpl @Inject constructor(LibrarySortBy.UPDATED,LibrarySortBy.RATING) -> true- query.filterBy.type == LibraryFilterType.TOP_RATED -> true- query.filterBy.type == LibraryFilterType.RECENTLY_UPDATED -> trueelse -> false}}@@ -883,11 +921,12 @@ class SeriesRepositoryImpl @Inject constructor(query: LibraryBrowseQuery,favoriteIds: Set<Long>,inProgressIds: Set<Long>,+ completedSeriesIds: Set<Long> = emptySet(),watchCounts: Map<Long, Int>): List<Series> {val withFavoriteState = series.map { item -> item.copy(isFavorite = item.id in favoriteIds) }val filtered = withFavoriteState.filter { item ->- seriesMatchesFilter(item, query.filterBy.type, inProgressIds) && seriesMatchesSearch(item, query.searchQuery)+ seriesMatchesFilter(item, query.filterBy.type, inProgressIds, completedSeriesIds) && seriesMatchesSearch(item, query.searchQuery)}val sorted = when (query.sortBy) {@@ -905,11 +944,16 @@ class SeriesRepositoryImpl @Inject constructor(}}- private fun seriesMatchesFilter(series: Series, filterType: LibraryFilterType, inProgressIds: Set<Long>): Boolean = when (filterType) {+ private fun seriesMatchesFilter(+ series: Series,+ filterType: LibraryFilterType,+ inProgressIds: Set<Long>,+ completedSeriesIds: Set<Long> = emptySet()+ ): Boolean = when (filterType) {LibraryFilterType.ALL -> trueLibraryFilterType.FAVORITES -> series.isFavoriteLibraryFilterType.IN_PROGRESS -> series.id in inProgressIds- LibraryFilterType.UNWATCHED -> series.id !in inProgressIds+ LibraryFilterType.UNWATCHED -> series.id !in completedSeriesIdsLibraryFilterType.TOP_RATED -> series.rating > 0fLibraryFilterType.RECENTLY_UPDATED -> seriesFreshnessScore(series) > 0L}@@ -922,15 +966,32 @@ class SeriesRepositoryImpl @Inject constructor(.any { value -> value.lowercase().contains(normalizedQuery) }}- private fun safeSeriesSearchFlow(source: Flow<List<SeriesBrowseEntity>>): Flow<List<SeriesBrowseEntity>> =+ private fun safeSeriesSearchFlow(+ source: Flow<List<SeriesBrowseEntity>>,+ fallback: Flow<List<SeriesBrowseEntity>>,+ rawQuery: String+ ): Flow<List<SeriesBrowseEntity>> =source.catch { error ->if (error is SQLiteException) {- emit(emptyList<SeriesBrowseEntity>())+ Log.w(TAG, "FTS series search failed for query '$rawQuery'; falling back to LIKE search", error)+ emitAll(fallback)} else {throw error}}+ private fun String.toSqlLikePattern(): String {+ val escaped = buildString(length) {+ [email protected] { char ->+ when (char) {+ '%', '_', '\\' -> append('\\')+ }+ append(char)+ }+ }+ return "%$escaped%"+ }+private suspend fun ensureXtreamCategoryLoaded(providerId: Long,categoryId: Long,diff --git a/data/src/main/java/com/streamvault/data/sync/BackgroundEpgSyncWorker.kt b/data/src/main/java/com/streamvault/data/sync/BackgroundEpgSyncWorker.ktindex fd7a046f..b7ba4064 100644--- a/data/src/main/java/com/streamvault/data/sync/BackgroundEpgSyncWorker.kt+++ b/data/src/main/java/com/streamvault/data/sync/BackgroundEpgSyncWorker.kt@@ -54,7 +54,20 @@ class BackgroundEpgSyncWorker(BackgroundEpgSyncWorkerEntryPoint::class.java)when (val result = entryPoint.syncManager().syncEpg(providerId, force = force)) {- is com.streamvault.domain.model.Result.Success -> Result.success()+ is com.streamvault.domain.model.Result.Success -> {+ // A successful EPG sync may still have transient partial failures+ // (e.g. network hiccup on one provider section). Check the published+ // sync state and retry if it signals a retryable EPG failure so+ // WorkManager backoff can heal it without manual intervention.+ val syncState = entryPoint.syncManager().currentSyncState(providerId)+ if (syncState is com.streamvault.domain.model.SyncState.Partial &&+ syncState.hasRetryableEpgFailure) {+ Log.i(TAG, "Scheduling retry for provider $providerId: EPG completed with retryable failure")+ Result.retry()+ } else {+ Result.success()+ }+ }is com.streamvault.domain.model.Result.Error -> {if (result.message.contains("not found", ignoreCase = true)) {Result.success()@@ -134,7 +147,9 @@ class BackgroundEpgSyncWorker(WorkManager.getInstance(context).enqueueUniqueWork(uniqueWorkName(providerId),- ExistingWorkPolicy.KEEP,+ // Force-refresh requests must displace any queued stale work so the new+ // parameters (force=true) actually run; KEEP would silently drop them.+ if (force) ExistingWorkPolicy.REPLACE else ExistingWorkPolicy.KEEP,request)}diff --git a/data/src/main/java/com/streamvault/data/sync/SyncCatalogStore.kt b/data/src/main/java/com/streamvault/data/sync/SyncCatalogStore.ktindex f5738233..30b7deba 100644--- a/data/src/main/java/com/streamvault/data/sync/SyncCatalogStore.kt+++ b/data/src/main/java/com/streamvault/data/sync/SyncCatalogStore.kt@@ -38,6 +38,13 @@ internal class SyncCatalogStore(private const val STAGE_BATCH_SIZE = 500}+ /**+ * Result returned from staged-import helpers that track both the accepted count and+ * whether the size limit was hit, so callers can choose between full-replace and+ * upsert-only commit semantics.+ */+ private data class StagingResult(val acceptedCount: Int, val overflowed: Boolean)+private val sessionIds = AtomicLong(Random.nextLong(1L, Long.MAX_VALUE))private val digest = ThreadLocal.withInitial { MessageDigest.getInstance("SHA-256") }@@ -59,15 +66,23 @@ internal class SyncCatalogStore(val sessionId = newSessionId()val stagedChannels = buildChannelStages(providerId, sessionId, channels)val limitedChannels = limitChannels(providerId, stagedChannels)+ // If the provider exceeded the size limit we applied a subset. Running full stale+ // deletion would then delete every row outside the retained subset, converting a+ // safety cap into destructive data loss. Switch to upsert-only for overflow syncs.+ val overflowed = limitedChannels.size < stagedChannels.sizetry {clearProviderStaging(providerId)categories?.let { stageCategories(providerId, sessionId, it) }insertStageRows(limitedChannels, catalogSyncDao::insertChannelStages)transactionRunner.inTransaction {categories?.let { applyCategories(providerId, sessionId, "LIVE") }- applyChannels(providerId, sessionId)+ if (overflowed) {+ upsertChannels(providerId, sessionId)+ } else {+ applyChannels(providerId, sessionId)+ }+ catalogSyncDao.rebuildChannelFts()}- catalogSyncDao.rebuildChannelFts()return limitedChannels.size} finally {clearSession(providerId, sessionId)@@ -79,14 +94,18 @@ internal class SyncCatalogStore(try {clearProviderStaging(providerId)categories?.let { stageCategories(providerId, sessionId, it) }- val acceptedCount = stageMovieSequence(providerId, sessionId, movies)+ val stagingResult = stageMovieSequence(providerId, sessionId, movies)transactionRunner.inTransaction {categories?.let { applyCategories(providerId, sessionId, "MOVIE") }- applyMovies(providerId, sessionId)+ if (stagingResult.overflowed) {+ upsertMovies(providerId, sessionId)+ } else {+ applyMovies(providerId, sessionId)+ }+ catalogSyncDao.rebuildMovieFts()}- catalogSyncDao.rebuildMovieFts()movieDao.restoreWatchProgress(providerId)- return acceptedCount+ return stagingResult.acceptedCount} finally {clearSession(providerId, sessionId)}@@ -97,13 +116,17 @@ internal class SyncCatalogStore(try {clearProviderStaging(providerId)categories?.let { stageCategories(providerId, sessionId, it) }- val acceptedCount = stageSeriesSequence(providerId, sessionId, series)+ val stagingResult = stageSeriesSequence(providerId, sessionId, series)transactionRunner.inTransaction {categories?.let { applyCategories(providerId, sessionId, "SERIES") }- applySeries(providerId, sessionId)+ if (stagingResult.overflowed) {+ upsertSeries(providerId, sessionId)+ } else {+ applySeries(providerId, sessionId)+ }+ catalogSyncDao.rebuildSeriesFts()}- catalogSyncDao.rebuildSeriesFts()- return acceptedCount+ return stagingResult.acceptedCount} finally {clearSession(providerId, sessionId)}@@ -115,8 +138,8 @@ internal class SyncCatalogStore(categories?.let { stageCategories(providerId, sessionId, it) }categories?.let { applyCategories(providerId, sessionId, "LIVE") }applyChannels(providerId, sessionId)+ catalogSyncDao.rebuildChannelFts()}- catalogSyncDao.rebuildChannelFts()} finally {clearSession(providerId, sessionId)}@@ -128,8 +151,8 @@ internal class SyncCatalogStore(categories?.let { stageCategories(providerId, sessionId, it) }categories?.let { applyCategories(providerId, sessionId, "MOVIE") }applyMovies(providerId, sessionId)+ catalogSyncDao.rebuildMovieFts()}- catalogSyncDao.rebuildMovieFts()movieDao.restoreWatchProgress(providerId)} finally {clearSession(providerId, sessionId)@@ -142,8 +165,128 @@ internal class SyncCatalogStore(categories?.let { stageCategories(providerId, sessionId, it) }categories?.let { applyCategories(providerId, sessionId, "SERIES") }applySeries(providerId, sessionId)+ catalogSyncDao.rebuildSeriesFts()+ }+ } finally {+ clearSession(providerId, sessionId)+ }+ }++ // ── Upsert-only staged apply methods (Issue 1: Partial commit scope) ──────────────++ /**+ * Staged live-catalog commit that updates and inserts without deleting stale rows.+ * Use when the staged session represents a partial (subset) of categories/channels —+ * absent rows must NOT be treated as deletions.+ */+ suspend fun applyStagedLiveCatalogUpsertOnly(providerId: Long, sessionId: Long, categories: List<CategoryEntity>?) {+ try {+ transactionRunner.inTransaction {+ categories?.let { stageCategories(providerId, sessionId, it) }+ categories?.let { applyCategories(providerId, sessionId, "LIVE") }+ upsertChannels(providerId, sessionId)+ catalogSyncDao.rebuildChannelFts()+ }+ } finally {+ clearSession(providerId, sessionId)+ }+ }++ /**+ * Staged movie-catalog commit that updates and inserts without deleting stale rows.+ * Use when the staged session represents a partial (subset) of categories/pages.+ */+ suspend fun applyStagedMovieCatalogUpsertOnly(providerId: Long, sessionId: Long, categories: List<CategoryEntity>?) {+ try {+ transactionRunner.inTransaction {+ categories?.let { stageCategories(providerId, sessionId, it) }+ categories?.let { applyCategories(providerId, sessionId, "MOVIE") }+ upsertMovies(providerId, sessionId)+ catalogSyncDao.rebuildMovieFts()+ }+ movieDao.restoreWatchProgress(providerId)+ } finally {+ clearSession(providerId, sessionId)+ }+ }++ /**+ * Staged series-catalog commit that updates and inserts without deleting stale rows.+ * Use when the staged session represents a partial (subset) of categories/pages.+ */+ suspend fun applyStagedSeriesCatalogUpsertOnly(providerId: Long, sessionId: Long, categories: List<CategoryEntity>?) {+ try {+ transactionRunner.inTransaction {+ categories?.let { stageCategories(providerId, sessionId, it) }+ categories?.let { applyCategories(providerId, sessionId, "SERIES") }+ upsertSeries(providerId, sessionId)+ catalogSyncDao.rebuildSeriesFts()+ }+ } finally {+ clearSession(providerId, sessionId)+ }+ }++ /**+ * Non-staged live-catalog upsert: stages the given channels, then updates and inserts+ * without deleting stale rows. Used for partial Xtream category results.+ */+ suspend fun upsertLiveCatalog(providerId: Long, categories: List<CategoryEntity>?, channels: List<ChannelEntity>): Int {+ val sessionId = newSessionId()+ val stagedChannels = buildChannelStages(providerId, sessionId, channels)+ try {+ clearProviderStaging(providerId)+ categories?.let { stageCategories(providerId, sessionId, it) }+ insertStageRows(stagedChannels, catalogSyncDao::insertChannelStages)+ transactionRunner.inTransaction {+ categories?.let { applyCategories(providerId, sessionId, "LIVE") }+ upsertChannels(providerId, sessionId)+ catalogSyncDao.rebuildChannelFts()+ }+ return stagedChannels.size+ } finally {+ clearSession(providerId, sessionId)+ }+ }++ /**+ * Non-staged movie-catalog upsert: stages the given movies, then updates and inserts+ * without deleting stale rows. Used for partial Xtream category/page results.+ */+ suspend fun upsertMovieCatalog(providerId: Long, categories: List<CategoryEntity>?, movies: Sequence<MovieEntity>): Int {+ val sessionId = newSessionId()+ try {+ clearProviderStaging(providerId)+ categories?.let { stageCategories(providerId, sessionId, it) }+ val stagingResult = stageMovieSequence(providerId, sessionId, movies)+ transactionRunner.inTransaction {+ categories?.let { applyCategories(providerId, sessionId, "MOVIE") }+ upsertMovies(providerId, sessionId)+ catalogSyncDao.rebuildMovieFts()+ }+ movieDao.restoreWatchProgress(providerId)+ return stagingResult.acceptedCount+ } finally {+ clearSession(providerId, sessionId)+ }+ }++ /**+ * Non-staged series-catalog upsert: stages the given series, then updates and inserts+ * without deleting stale rows. Used for partial Xtream category/page results.+ */+ suspend fun upsertSeriesCatalog(providerId: Long, categories: List<CategoryEntity>?, series: Sequence<SeriesEntity>): Int {+ val sessionId = newSessionId()+ try {+ clearProviderStaging(providerId)+ categories?.let { stageCategories(providerId, sessionId, it) }+ val stagingResult = stageSeriesSequence(providerId, sessionId, series)+ transactionRunner.inTransaction {+ categories?.let { applyCategories(providerId, sessionId, "SERIES") }+ upsertSeries(providerId, sessionId)+ catalogSyncDao.rebuildSeriesFts()}- catalogSyncDao.rebuildSeriesFts()+ return stagingResult.acceptedCount} finally {clearSession(providerId, sessionId)}@@ -205,16 +348,16 @@ internal class SyncCatalogStore(stageCategories(providerId, sessionId, liveCategories.orEmpty())applyCategories(providerId, sessionId, "LIVE")applyChannels(providerId, sessionId)+ catalogSyncDao.rebuildChannelFts()}if (includeMovies) {stageCategories(providerId, sessionId, movieCategories.orEmpty())applyCategories(providerId, sessionId, "MOVIE")applyMovies(providerId, sessionId)+ catalogSyncDao.rebuildMovieFts()}}- if (includeLive) { catalogSyncDao.rebuildChannelFts() }if (includeMovies) {- catalogSyncDao.rebuildMovieFts()movieDao.restoreWatchProgress(providerId)}}@@ -233,33 +376,25 @@ internal class SyncCatalogStore(private suspend fun applyCategories(providerId: Long, sessionId: Long, type: String) {val stagedByCategoryId = catalogSyncDao.getCategoryStages(providerId, sessionId, type).associateBy { it.categoryId }- val remappedProtectedCategoryIds = mutableListOf<Long>()val changed = categoryDao.getByProviderAndTypeSync(providerId, type).mapNotNull { current ->val stage = stagedByCategoryId[current.categoryId] ?: return@mapNotNull nullif (current.syncFingerprint == stage.syncFingerprint) return@mapNotNull null- val invalidateProtection = current.isUserProtected- if (invalidateProtection) {- remappedProtectedCategoryIds += current.categoryId- }+ // User-set protection is preserved across provider metadata changes (rename,+ // parent, adult-flag). Protection is removed only when the category identity+ // truly disappears (deleteStaleCategoriesForStage cascade) or via explicit+ // user action — never by a harmless provider-side metadata drift.current.copy(name = stage.name,parentId = stage.parentId,isAdult = stage.isAdult,- isUserProtected = if (invalidateProtection) false else current.isUserProtected,+ isUserProtected = current.isUserProtected,syncFingerprint = stage.syncFingerprint)}if (changed.isNotEmpty()) {categoryDao.updateAll(changed)}- if (remappedProtectedCategoryIds.isNotEmpty()) {- when (type) {- "LIVE" -> channelDao.clearProtectionForCategories(providerId, remappedProtectedCategoryIds)- "MOVIE" -> movieDao.clearProtectionForCategories(providerId, remappedProtectedCategoryIds)- "SERIES" -> seriesDao.clearProtectionForCategories(providerId, remappedProtectedCategoryIds)- }- }catalogSyncDao.insertMissingCategoriesFromStage(providerId, sessionId, type)catalogSyncDao.deleteStaleCategoriesForStage(providerId, sessionId, type)}@@ -270,6 +405,18 @@ internal class SyncCatalogStore(catalogSyncDao.deleteStaleChannelsForStage(providerId, sessionId)}+ /**+ * Upsert-only channel apply: updates and inserts staged rows without deleting any+ * existing rows. Used when a partial result or size-limit overflow makes it unsafe+ * to treat absent staged rows as deletions.+ */+ private suspend fun upsertChannels(providerId: Long, sessionId: Long) {+ catalogSyncDao.updateChangedChannelsFromStage(providerId, sessionId)+ catalogSyncDao.insertMissingChannelsFromStage(providerId, sessionId)+ // Intentionally no stale deletion — partial or overflow commits must not remove+ // channels that were not part of the successfully fetched subset.+ }+private suspend fun applyMovies(providerId: Long, sessionId: Long) {catalogSyncDao.updateChangedMoviesFromStage(providerId, sessionId)catalogSyncDao.insertMissingMoviesFromStage(providerId, sessionId)@@ -277,6 +424,17 @@ internal class SyncCatalogStore(refreshMovieTmdbIdentities(providerId)}+ /**+ * Upsert-only movie apply: updates and inserts staged rows without deleting any+ * existing rows. Used for partial category/page results and size-limit overflow.+ */+ private suspend fun upsertMovies(providerId: Long, sessionId: Long) {+ catalogSyncDao.updateChangedMoviesFromStage(providerId, sessionId)+ catalogSyncDao.insertMissingMoviesFromStage(providerId, sessionId)+ // Intentionally no stale deletion.+ refreshMovieTmdbIdentities(providerId)+ }+private suspend fun applySeries(providerId: Long, sessionId: Long) {catalogSyncDao.updateChangedSeriesFromStage(providerId, sessionId)catalogSyncDao.insertMissingSeriesFromStage(providerId, sessionId)@@ -284,6 +442,17 @@ internal class SyncCatalogStore(refreshSeriesTmdbIdentities(providerId)}+ /**+ * Upsert-only series apply: updates and inserts staged rows without deleting any+ * existing rows. Used for partial category/page results and size-limit overflow.+ */+ private suspend fun upsertSeries(providerId: Long, sessionId: Long) {+ catalogSyncDao.updateChangedSeriesFromStage(providerId, sessionId)+ catalogSyncDao.insertMissingSeriesFromStage(providerId, sessionId)+ // Intentionally no stale deletion.+ refreshSeriesTmdbIdentities(providerId)+ }+private suspend fun refreshMovieTmdbIdentities(providerId: Long) {val identities = movieDao.getTmdbIdsByProvider(providerId).distinctBy { it.tmdbId }@@ -387,7 +556,8 @@ internal class SyncCatalogStore(tmdbId = movie.tmdbId,youtubeTrailer = movie.youtubeTrailer,isAdult = movie.isAdult,- syncFingerprint = movieFingerprint(movie)+ syncFingerprint = movieFingerprint(movie),+ addedAt = movie.addedAt)}}@@ -398,12 +568,14 @@ internal class SyncCatalogStore(series: List<SeriesEntity>): List<SeriesImportStageEntity> {return series- .distinctBy { it.seriesId }+ .distinctBy(::seriesRemoteKey).map { item ->SeriesImportStageEntity(sessionId = sessionId,providerId = providerId,seriesId = item.seriesId,+ providerSeriesId = item.providerSeriesId,+ providerSeriesKey = seriesRemoteKey(item),name = item.name,posterUrl = item.posterUrl,backdropUrl = item.backdropUrl,@@ -429,7 +601,7 @@ internal class SyncCatalogStore(providerId: Long,sessionId: Long,movies: Sequence<MovieEntity>- ): Int {+ ): StagingResult {return stageDistinctRows(items = movies,keySelector = { movie -> movie.streamId },@@ -448,7 +620,7 @@ internal class SyncCatalogStore(providerId: Long,sessionId: Long,series: Sequence<SeriesEntity>- ): Int {+ ): StagingResult {return stageDistinctRows(items = series,keySelector = { item -> item.seriesId },@@ -472,7 +644,7 @@ internal class SyncCatalogStore(providerId: Long,stageBuilder: (T) -> S,insert: suspend (List<S>) -> Unit- ): Int {+ ): StagingResult {val seenKeys = HashSet<K>()val bestItems = java.util.PriorityQueue<T>(limit.coerceAtLeast(1), bestFirstComparator.reversed())val batch = ArrayList<S>(STAGE_BATCH_SIZE)@@ -491,7 +663,8 @@ internal class SyncCatalogStore(}}- if (distinctCount > limit) {+ val overflowed = distinctCount > limit+ if (overflowed) {Log.w(TAG,"Provider $providerId $logLabel staging exceeded limit $limit; kept ${bestItems.size} highest-priority distinct rows out of $distinctCount."@@ -513,7 +686,7 @@ internal class SyncCatalogStore(insert(batch)}- return bestItems.size+ return StagingResult(acceptedCount = bestItems.size, overflowed = overflowed)}private suspend fun <T> insertStageRows(@@ -569,6 +742,8 @@ internal class SyncCatalogStore(sessionId = sessionId,providerId = providerId,seriesId = item.seriesId,+ providerSeriesId = item.providerSeriesId,+ providerSeriesKey = seriesRemoteKey(item),name = item.name,posterUrl = item.posterUrl,backdropUrl = item.backdropUrl,@@ -626,12 +801,14 @@ internal class SyncCatalogStore(normalizeText(movie.year),movie.tmdbId?.toString().orEmpty(),normalizeUrl(movie.youtubeTrailer),- movie.isAdult.toString()+ movie.isAdult.toString(),+ movie.addedAt.toString())}private fun seriesFingerprint(series: SeriesEntity): String {return fingerprint(+ seriesRemoteKey(series),normalizeText(series.name),normalizeUrl(series.posterUrl),normalizeUrl(series.backdropUrl),@@ -651,6 +828,10 @@ internal class SyncCatalogStore()}+ private fun seriesRemoteKey(series: SeriesEntity): String {+ return series.providerSeriesId?.takeIf { it.isNotBlank() } ?: series.seriesId.toString()+ }+private fun categoryFingerprint(category: CategoryEntity): String {return fingerprint(category.categoryId.toString(),diff --git a/data/src/main/java/com/streamvault/data/sync/SyncManager.kt b/data/src/main/java/com/streamvault/data/sync/SyncManager.ktindex af27d3b8..160551e3 100644--- a/data/src/main/java/com/streamvault/data/sync/SyncManager.kt+++ b/data/src/main/java/com/streamvault/data/sync/SyncManager.kt@@ -323,7 +323,7 @@ class SyncManager @Inject constructor(publishSyncState(providerId, SyncState.Syncing("Downloading EPG..."))try {- val warnings = syncProviderEpg(+ val epgResult = syncProviderEpg(provider = provider,metadata = syncMetadataRepository.getMetadata(provider.id) ?: SyncMetadata(provider.id),now = System.currentTimeMillis(),@@ -332,14 +332,18 @@ class SyncManager @Inject constructor()updateSyncStatusMetadata(providerId = providerId,- status = if (warnings.isEmpty()) "SUCCESS" else "PARTIAL"+ status = if (epgResult.warnings.isEmpty()) "SUCCESS" else "PARTIAL")publishSyncState(providerId,- if (warnings.isEmpty()) {+ if (epgResult.warnings.isEmpty()) {SyncState.Success()} else {- SyncState.Partial("EPG sync completed with warnings", warnings)+ SyncState.Partial(+ message = "EPG sync completed with warnings",+ warnings = epgResult.warnings,+ hasRetryableEpgFailure = epgResult.hasRetryableFailure+ )})com.streamvault.domain.model.Result.success(Unit)@@ -433,16 +437,29 @@ class SyncManager @Inject constructor(}try {- withContext(Dispatchers.IO) {+ val outcome = withContext(Dispatchers.IO) {when (section) {SyncRepairSection.LIVE -> syncLiveOnly(provider, onProgress)- SyncRepairSection.EPG -> syncEpgOnly(provider, onProgress)+ SyncRepairSection.EPG -> {+ syncEpgOnly(provider, onProgress)+ SyncOutcome()+ }SyncRepairSection.MOVIES -> syncMoviesOnly(provider, onProgress)SyncRepairSection.SERIES -> syncSeriesOnly(provider, onProgress)}}- updateSyncStatusMetadata(providerId = providerId, status = "SUCCESS")- publishSyncState(providerId, SyncState.Success())+ updateSyncStatusMetadata(+ providerId = providerId,+ status = if (outcome.partial) "PARTIAL" else "SUCCESS"+ )+ publishSyncState(+ providerId,+ if (outcome.partial) {+ SyncState.Partial("Section retry completed with warnings", outcome.warnings)+ } else {+ SyncState.Success()+ }+ )com.streamvault.domain.model.Result.success(Unit)} catch (e: CancellationException) {resetState(providerId)@@ -531,13 +548,15 @@ class SyncManager @Inject constructor(warnings += liveSyncResult.warnings + liveResult.warnings}is CatalogStrategyResult.Partial -> {+ // Partial snapshot: upsert only so that channels absent from the subset+ // are not deleted from the existing live catalog.val liveCatalog = mergeVisibleLiveSyncWithHiddenStoredContent(providerId = provider.id,visibleCategories = liveSyncResult.categories,visibleChannels = liveResult.items.map { it.toEntity() },hiddenLiveCategoryIds = hiddenLiveCategoryIds)- val acceptedCount = syncCatalogStore.replaceLiveCatalog(+ val acceptedCount = syncCatalogStore.upsertLiveCatalog(providerId = provider.id,categories = liveCatalog.categories,channels = liveCatalog.channels@@ -636,10 +655,13 @@ class SyncManager @Inject constructor()}is CatalogStrategyResult.Partial -> {+ // Partial means the server returned a truncated or mid-interrupted+ // catalog subset. Running full stale deletion would remove titles that+ // simply weren't included in the partial snapshot, so we upsert only.val acceptedCount = movieSyncResult.stagedSessionId?.let { sessionId ->- syncCatalogStore.applyStagedMovieCatalog(provider.id, sessionId, movieSyncResult.categories)+ syncCatalogStore.applyStagedMovieCatalogUpsertOnly(provider.id, sessionId, movieSyncResult.categories)movieSyncResult.stagedAcceptedCount- } ?: syncCatalogStore.replaceMovieCatalog(+ } ?: syncCatalogStore.upsertMovieCatalog(providerId = provider.id,categories = movieSyncResult.categories,movies = catalogResult.items.asSequence().map { movie -> movie.toEntity() }@@ -754,10 +776,12 @@ class SyncManager @Inject constructor(warnings += seriesSyncResult.warnings + seriesResult.warnings}is CatalogStrategyResult.Partial -> {+ // Partial result: upsert only to avoid deleting titles that weren't+ // included in the truncated snapshot.val acceptedCount = seriesSyncResult.stagedSessionId?.let { sessionId ->- syncCatalogStore.applyStagedSeriesCatalog(provider.id, sessionId, seriesSyncResult.categories)+ syncCatalogStore.applyStagedSeriesCatalogUpsertOnly(provider.id, sessionId, seriesSyncResult.categories)seriesSyncResult.stagedAcceptedCount- } ?: syncCatalogStore.replaceSeriesCatalog(+ } ?: syncCatalogStore.upsertSeriesCatalog(providerId = provider.id,categories = seriesSyncResult.categories,series = seriesResult.items.asSequence().map { it.toEntity() }@@ -823,7 +847,7 @@ class SyncManager @Inject constructor(now = now,force = force,onProgress = onProgress- )+ ).warnings}return if (warnings.isEmpty()) SyncOutcome() else SyncOutcome(partial = true, warnings = warnings)@@ -872,7 +896,7 @@ class SyncManager @Inject constructor(now = now,force = force,onProgress = onProgress- )+ ).warnings}return if (warnings.isEmpty()) SyncOutcome() else SyncOutcome(partial = true, warnings = warnings)@@ -910,8 +934,13 @@ class SyncManager @Inject constructor(if (force || ContentCachePolicy.shouldRefresh(metadata.lastMovieSuccess, ContentCachePolicy.CATALOG_TTL_MILLIS, now)) {progress(provider.id, onProgress, "Downloading Movies...")val categories = requireResult(api.getVodCategories(), "Failed to load movie categories")- syncCatalogStore.replaceMovieCatalog(+ // Stalker uses lazy-by-category VoD loading — only categories are persisted up+ // front. Using replaceMovieCatalog with an empty sequence would run full stale+ // deletion and destroy any movies already hydrated via on-demand category loads.+ // replaceCategories updates/inserts category rows without touching movie rows.+ syncCatalogStore.replaceCategories(providerId = provider.id,+ type = "MOVIE",categories = categories.map { category ->CategoryEntity(providerId = provider.id,@@ -921,8 +950,7 @@ class SyncManager @Inject constructor(type = ContentType.MOVIE,isAdult = category.isAdult)- },- movies = emptySequence()+ })metadata = metadata.copy(lastMovieSync = now,@@ -939,8 +967,11 @@ class SyncManager @Inject constructor(if (force || ContentCachePolicy.shouldRefresh(metadata.lastSeriesSuccess, ContentCachePolicy.CATALOG_TTL_MILLIS, now)) {progress(provider.id, onProgress, "Downloading Series...")val categories = requireResult(api.getSeriesCategories(), "Failed to load series categories")- syncCatalogStore.replaceSeriesCatalog(+ // Same rationale as movies: use replaceCategories to avoid destroying any+ // already-hydrated series rows when running a category-only Stalker sync.+ syncCatalogStore.replaceCategories(providerId = provider.id,+ type = "SERIES",categories = categories.map { category ->CategoryEntity(providerId = provider.id,@@ -950,8 +981,7 @@ class SyncManager @Inject constructor(type = ContentType.SERIES,isAdult = category.isAdult)- },- series = emptySequence()+ })metadata = metadata.copy(lastSeriesSync = now,@@ -968,21 +998,51 @@ class SyncManager @Inject constructor(now = now,force = force,onProgress = onProgress- )+ ).warnings}return if (warnings.isEmpty()) SyncOutcome() else SyncOutcome(partial = true, warnings = warnings)}+ /**+ * Returned by [syncProviderEpg] so callers can distinguish between warning-only+ * degradations and transient network/IO failures that WorkManager should retry.+ */+ private data class EpgSyncResult(+ val warnings: List<String>,+ /** True when at least one EPG sub-operation failed due to a network or IO error+ * rather than a permanent configuration problem (bad URL, bad credentials, etc.).+ * WorkManager workers should return [Result.retry()] when this is true. */+ val hasRetryableFailure: Boolean+ )++ /**+ * Returns true for transient network/IO exceptions that are worth retrying via+ * WorkManager backoff — as opposed to permanent failures (bad URL, auth, parse error)+ * that will fail identically on every attempt.+ */+ private fun isRetryableEpgException(e: Exception): Boolean =+ e is java.io.IOException ||+ e is java.net.SocketTimeoutException ||+ e is java.net.ConnectException ||+ e is java.net.UnknownHostException ||+ e.cause?.let {+ it is java.io.IOException ||+ it is java.net.SocketTimeoutException ||+ it is java.net.ConnectException ||+ it is java.net.UnknownHostException+ } == true+private suspend fun syncProviderEpg(provider: Provider,metadata: SyncMetadata,now: Long,force: Boolean,onProgress: ((String) -> Unit)?- ): List<String> {+ ): EpgSyncResult {var updatedMetadata = metadataval warnings = mutableListOf<String>()+ var hasRetryableFailure = falseval hiddenLiveCategoryIds = preferencesRepository.getHiddenCategoryIds(provider.id, ContentType.LIVE).first()when (provider.type) {@@ -1012,6 +1072,7 @@ class SyncManager @Inject constructor(throw e} catch (e: Exception) {Log.e(TAG, "EPG sync failed (non-fatal): ${sanitizeThrowableMessage(e)}")+ if (isRetryableEpgException(e)) hasRetryableFailure = truewarnings.add("EPG XMLTV sync failed; live guide will fall back to on-demand Xtream data.")}}@@ -1037,6 +1098,7 @@ class SyncManager @Inject constructor(throw e} catch (e: Exception) {Log.e(TAG, "EPG sync failed (non-fatal): ${sanitizeThrowableMessage(e)}")+ if (isRetryableEpgException(e)) hasRetryableFailure = truewarnings.add("EPG sync failed")}}@@ -1045,11 +1107,15 @@ class SyncManager @Inject constructor(ProviderType.STALKER_PORTAL -> {if (force || ContentCachePolicy.shouldRefresh(updatedMetadata.lastEpgSuccess, ContentCachePolicy.EPG_TTL_MILLIS, now)) {- warnings += syncStalkerPreferredEpg(+ val stalkerEpgWarnings = syncStalkerPreferredEpg(provider = provider,now = now,onProgress = onProgress)+ // Any Stalker EPG warning indicates an HTTP request failure, which is+ // typically transient.+ if (stalkerEpgWarnings.isNotEmpty()) hasRetryableFailure = true+ warnings += stalkerEpgWarningsupdatedMetadata = syncMetadataRepository.getMetadata(provider.id) ?: updatedMetadata}}@@ -1064,10 +1130,11 @@ class SyncManager @Inject constructor(throw e} catch (e: Exception) {Log.e(TAG, "External EPG resolution failed (non-fatal): ${sanitizeThrowableMessage(e)}")+ if (isRetryableEpgException(e)) hasRetryableFailure = truewarnings.add("External EPG source refresh/resolution failed.")}- return warnings+ return EpgSyncResult(warnings = warnings, hasRetryableFailure = hasRetryableFailure)}private suspend fun syncEpgOnly(@@ -1394,8 +1461,9 @@ class SyncManager @Inject constructor(private suspend fun syncLiveOnly(provider: Provider,onProgress: ((String) -> Unit)?- ) {+ ): SyncOutcome {val now = System.currentTimeMillis()+ val sectionWarnings = mutableListOf<String>()when (provider.type) {ProviderType.XTREAM_CODES -> {progress(provider.id, onProgress, "Retrying Live TV...")@@ -1448,13 +1516,14 @@ class SyncManager @Inject constructor()}is CatalogStrategyResult.Partial -> {+ // Partial snapshot: upsert only so channels not in the subset are preserved.val liveCatalog = mergeVisibleLiveSyncWithHiddenStoredContent(providerId = provider.id,visibleCategories = liveSyncResult.categories,visibleChannels = liveResult.items.map { it.toEntity() },hiddenLiveCategoryIds = hiddenLiveCategoryIds)- val acceptedCount = syncCatalogStore.replaceLiveCatalog(+ val acceptedCount = syncCatalogStore.upsertLiveCatalog(providerId = provider.id,categories = liveCatalog.categories,channels = liveCatalog.channels@@ -1468,6 +1537,8 @@ class SyncManager @Inject constructor(liveHealthySyncStreak = 0))+ sectionWarnings += liveSyncResult.warnings + liveResult.warnings ++ listOf("Live TV retry completed partially.")}is CatalogStrategyResult.EmptyValid -> {val existingLiveCount = channelDao.getCount(provider.id).first()@@ -1529,15 +1600,18 @@ class SyncManager @Inject constructor(liveCount = liveCatalogResult.acceptedCount)syncMetadataRepository.updateMetadata(metadata)+ sectionWarnings += liveCatalogResult.warnings}}+ return if (sectionWarnings.isEmpty()) SyncOutcome() else SyncOutcome(partial = true, warnings = sectionWarnings)}private suspend fun syncMoviesOnly(provider: Provider,onProgress: ((String) -> Unit)?- ) {+ ): SyncOutcome {val now = System.currentTimeMillis()+ val sectionWarnings = mutableListOf<String>()when (provider.type) {ProviderType.XTREAM_CODES -> {progress(@@ -1607,10 +1681,11 @@ class SyncManager @Inject constructor()}is CatalogStrategyResult.Partial -> {+ // Partial snapshot: upsert only to avoid deleting titles absent from the subset.val acceptedCount = movieSyncResult.stagedSessionId?.let { sessionId ->- syncCatalogStore.applyStagedMovieCatalog(provider.id, sessionId, movieSyncResult.categories)+ syncCatalogStore.applyStagedMovieCatalogUpsertOnly(provider.id, sessionId, movieSyncResult.categories)movieSyncResult.stagedAcceptedCount- } ?: syncCatalogStore.replaceMovieCatalog(+ } ?: syncCatalogStore.upsertMovieCatalog(providerId = provider.id,categories = movieSyncResult.categories,movies = catalogResult.items.asSequence().map { movie -> movie.toEntity() }@@ -1626,6 +1701,7 @@ class SyncManager @Inject constructor(movieHealthySyncStreak = 0))+ sectionWarnings += movieWarnings + listOf("Movies retry completed partially.")}is CatalogStrategyResult.EmptyValid -> {val existingMovieCount = movieDao.getCount(provider.id).first()@@ -1721,12 +1797,14 @@ class SyncManager @Inject constructor(syncMetadataRepository.updateMetadata(metadata)}}+ return if (sectionWarnings.isEmpty()) SyncOutcome() else SyncOutcome(partial = true, warnings = sectionWarnings)}private suspend fun syncSeriesOnly(provider: Provider,onProgress: ((String) -> Unit)?- ) {+ ): SyncOutcome {+ val sectionWarnings = mutableListOf<String>()when (provider.type) {ProviderType.XTREAM_CODES -> {progress(provider.id, onProgress, "Retrying Series...")@@ -1775,10 +1853,11 @@ class SyncManager @Inject constructor()}is CatalogStrategyResult.Partial -> {+ // Partial snapshot: upsert only to preserve series absent from the subset.val acceptedCount = seriesSyncResult.stagedSessionId?.let { sessionId ->- syncCatalogStore.applyStagedSeriesCatalog(provider.id, sessionId, seriesSyncResult.categories)+ syncCatalogStore.applyStagedSeriesCatalogUpsertOnly(provider.id, sessionId, seriesSyncResult.categories)seriesSyncResult.stagedAcceptedCount- } ?: syncCatalogStore.replaceSeriesCatalog(+ } ?: syncCatalogStore.upsertSeriesCatalog(providerId = provider.id,categories = seriesSyncResult.categories,series = seriesResult.items.asSequence().map { it.toEntity() }@@ -1792,6 +1871,8 @@ class SyncManager @Inject constructor(seriesHealthySyncStreak = 0))+ sectionWarnings += seriesSyncResult.warnings + seriesResult.warnings ++ listOf("Series retry completed partially.")}is CatalogStrategyResult.EmptyValid -> {val existingSeriesCount = seriesDao.getCount(provider.id).first()@@ -1864,6 +1945,7 @@ class SyncManager @Inject constructor(throw IllegalStateException("Series retry is unavailable for this provider")}}+ return if (sectionWarnings.isEmpty()) SyncOutcome() else SyncOutcome(partial = true, warnings = sectionWarnings)}private suspend fun syncXtreamMoviesCatalog(diff --git a/data/src/main/java/com/streamvault/data/sync/SyncManagerM3uImporter.kt b/data/src/main/java/com/streamvault/data/sync/SyncManagerM3uImporter.ktindex aa2a2b07..3b19aee2 100644--- a/data/src/main/java/com/streamvault/data/sync/SyncManagerM3uImporter.kt+++ b/data/src/main/java/com/streamvault/data/sync/SyncManagerM3uImporter.kt@@ -160,13 +160,19 @@ internal class SyncManagerM3uImporter(flushChannelBatch(provider.id, sessionId, channelBatch)flushMovieBatch(provider.id, sessionId, movieBatch)+ // Only commit a section if it produced at least one entry. Committing an+ // empty stage with includeLive=true runs stale deletion and wipes the entire+ // live-TV catalog — even though the absence of entries may reflect a server+ // error or a filtered playlist rather than a legitimate empty provider.+ val effectiveLive = includeLive && liveCount > 0+ val effectiveMovies = includeMovies && movieCount > 0syncCatalogStore.finalizeStagedImport(providerId = provider.id,sessionId = sessionId,- liveCategories = if (includeLive) liveCategories.entities() else null,- movieCategories = if (includeMovies) movieCategories.entities() else null,- includeLive = includeLive,- includeMovies = includeMovies+ liveCategories = if (effectiveLive) liveCategories.entities() else null,+ movieCategories = if (effectiveMovies) movieCategories.entities() else null,+ includeLive = effectiveLive,+ includeMovies = effectiveMovies)} finally {syncCatalogStore.discardStagedImport(provider.id, sessionId)diff --git a/data/src/main/java/com/streamvault/data/util/ProviderInputSanitizer.kt b/data/src/main/java/com/streamvault/data/util/ProviderInputSanitizer.ktindex 6518380e..dc9427fe 100644--- a/data/src/main/java/com/streamvault/data/util/ProviderInputSanitizer.kt+++ b/data/src/main/java/com/streamvault/data/util/ProviderInputSanitizer.kt@@ -35,6 +35,8 @@ object ProviderInputSanitizer {fun normalizeUsername(input: String): String = sanitizeSingleLine(input, MAX_USERNAME_LENGTH).trim()+ fun normalizePassword(input: String): String = sanitizeRaw(input, MAX_PASSWORD_LENGTH)+fun normalizeMacAddress(input: String): String {val raw = sanitizeSingleLine(input, MAX_MAC_ADDRESS_LENGTH + 5).uppercase()@@ -73,6 +75,19 @@ object ProviderInputSanitizer {}}+ fun validatePassword(password: String, allowBlank: Boolean): String? {+ if (!allowBlank && password.isBlank()) {+ return "Please enter password"+ }+ if (password.length > MAX_PASSWORD_LENGTH) {+ return "Password is too long"+ }+ if (password.any(Char::isISOControl)) {+ return "Password cannot contain control characters."+ }+ return null+ }+private fun sanitizeSingleLine(input: String, maxLength: Int): String {return sanitizeRaw(input, maxLength).replace(WHITESPACE_REGEX, " ")}diff --git a/data/src/main/java/com/streamvault/data/util/UrlSecurityPolicy.kt b/data/src/main/java/com/streamvault/data/util/UrlSecurityPolicy.ktindex 60563957..0d004b77 100644--- a/data/src/main/java/com/streamvault/data/util/UrlSecurityPolicy.kt+++ b/data/src/main/java/com/streamvault/data/util/UrlSecurityPolicy.kt@@ -9,6 +9,9 @@ object UrlSecurityPolicy {private val playlistSourceSchemes = setOf("http", "https")private val xtreamServerSchemes = setOf("http", "https")private val localSchemes = setOf("file", "content")+ // Playlist storage only ever writes file:// paths via the internal copy flow;+ // content:// URIs are not openable by SyncManagerM3uImporter (OkHttp + java.io.File only).+ private val playlistLocalSchemes = setOf("file")// IPTV stream/asset URLs may legitimately use plain HTTP or RTSPprivate val streamEntrySchemes = setOf("http", "https", "rtsp", "rtsps", "rtmp", "file", "content")@@ -23,35 +26,58 @@ object UrlSecurityPolicy {StreamEntryUrlPolicy.isAllowed(url)fun validateXtreamServerUrl(url: String): String? {- return if (!containsNewlines(url) && hasAllowedScheme(url, xtreamServerSchemes)) {- null- } else {- "Xtream server URLs must use HTTP or HTTPS."- }+ return validateRemoteUrl(+ url = url,+ allowedSchemes = xtreamServerSchemes,+ invalidSchemeMessage = "Xtream server URLs must use HTTP or HTTPS.",+ missingHostMessage = "Xtream server URLs must include a host.",+ userInfoMessage = "Xtream server URLs must not include embedded credentials.",+ queryFragmentMessage = "Xtream server URLs must not include query parameters or fragments.",+ allowQuery = false+ )}fun validateStalkerPortalUrl(url: String): String? {- return if (!containsNewlines(url) && hasAllowedScheme(url, xtreamServerSchemes)) {- null- } else {- "Portal URLs must use HTTP or HTTPS."- }+ return validateRemoteUrl(+ url = url,+ allowedSchemes = xtreamServerSchemes,+ invalidSchemeMessage = "Portal URLs must use HTTP or HTTPS.",+ missingHostMessage = "Portal URLs must include a host.",+ userInfoMessage = "Portal URLs must not include embedded credentials.",+ queryFragmentMessage = "Portal URLs must not include query parameters or fragments.",+ allowQuery = false+ )}fun validateXtreamEpgUrl(url: String): String? {- return if (!containsNewlines(url) && hasAllowedScheme(url, xtreamServerSchemes)) {- null- } else {- "Xtream EPG URLs must use HTTP or HTTPS."- }+ return validateRemoteUrl(+ url = url,+ allowedSchemes = xtreamServerSchemes,+ invalidSchemeMessage = "Xtream EPG URLs must use HTTP or HTTPS.",+ missingHostMessage = "Xtream EPG URLs must include a host.",+ userInfoMessage = "Xtream EPG URLs must not include embedded credentials.",+ queryFragmentMessage = "Xtream EPG URLs must not include URL fragments.",+ allowQuery = true+ )}fun validatePlaylistSourceUrl(url: String): String? {- return if (!containsNewlines(url) && hasAllowedScheme(url, playlistSourceSchemes + localSchemes)) {- null- } else {- "Playlist sources must use HTTP, HTTPS, or point to a local file."+ if (containsNewlines(url)) {+ return "Playlist sources must use HTTP, HTTPS, or point to a local file."+ }+ val scheme = parseScheme(url) ?: return "Playlist sources must use HTTP, HTTPS, or point to a local file."+ if (scheme in playlistLocalSchemes) {+ return null}+ return validateRemoteUrl(+ url = url,+ allowedSchemes = playlistSourceSchemes,+ invalidSchemeMessage = "Playlist sources must use HTTP, HTTPS, or point to a local file.",+ missingHostMessage = "Playlist sources must include a host.",+ userInfoMessage = "Playlist sources must not include embedded credentials in the URL authority.",+ queryFragmentMessage = "Playlist sources must not include URL fragments.",+ allowQuery = true+ )}fun validateOptionalEpgUrl(url: String): String? {@@ -93,4 +119,25 @@ object UrlSecurityPolicy {.getOrNull()?.lowercase(Locale.ROOT)}++ private fun validateRemoteUrl(+ url: String,+ allowedSchemes: Set<String>,+ invalidSchemeMessage: String,+ missingHostMessage: String,+ userInfoMessage: String,+ queryFragmentMessage: String,+ allowQuery: Boolean+ ): String? {+ if (containsNewlines(url)) return invalidSchemeMessage++ val uri = runCatching { URI(url.trim()) }.getOrNull() ?: return invalidSchemeMessage+ val scheme = uri.scheme?.lowercase(Locale.ROOT) ?: return invalidSchemeMessage+ if (scheme !in allowedSchemes) return invalidSchemeMessage+ if (uri.host.isNullOrBlank()) return missingHostMessage+ if (!uri.userInfo.isNullOrBlank()) return userInfoMessage+ if (!allowQuery && !uri.rawQuery.isNullOrBlank()) return queryFragmentMessage+ if (!uri.rawFragment.isNullOrBlank()) return queryFragmentMessage+ return null+ }}diff --git a/data/src/main/java/com/streamvault/data/validation/ProviderSetupInputValidatorImpl.kt b/data/src/main/java/com/streamvault/data/validation/ProviderSetupInputValidatorImpl.ktindex bce2ae92..0f352c82 100644--- a/data/src/main/java/com/streamvault/data/validation/ProviderSetupInputValidatorImpl.kt+++ b/data/src/main/java/com/streamvault/data/validation/ProviderSetupInputValidatorImpl.kt@@ -7,6 +7,7 @@ import com.streamvault.domain.manager.ValidatedM3uProviderInputimport com.streamvault.domain.manager.ValidatedStalkerProviderInputimport com.streamvault.domain.manager.ValidatedXtreamProviderInputimport com.streamvault.domain.model.Result+import java.time.ZoneIdimport javax.inject.Injectimport javax.inject.Singleton@@ -16,10 +17,13 @@ class ProviderSetupInputValidatorImpl @Inject constructor() : ProviderSetupInputoverride fun validateXtream(serverUrl: String,username: String,+ password: String,+ allowBlankPassword: Boolean,name: String): Result<ValidatedXtreamProviderInput> {val normalizedServerUrl = ProviderInputSanitizer.normalizeUrl(serverUrl)val normalizedUsername = ProviderInputSanitizer.normalizeUsername(username)+ val normalizedPassword = ProviderInputSanitizer.normalizePassword(password)val normalizedName = ProviderInputSanitizer.normalizeProviderName(name)if (normalizedServerUrl.isBlank()) {@@ -34,11 +38,15 @@ class ProviderSetupInputValidatorImpl @Inject constructor() : ProviderSetupInputif (normalizedUsername.isBlank()) {return Result.error("Please enter username")}+ ProviderInputSanitizer.validatePassword(password, allowBlankPassword)?.let { message ->+ return Result.error(message)+ }return Result.success(ValidatedXtreamProviderInput(serverUrl = normalizedServerUrl,username = normalizedUsername,+ password = normalizedPassword,name = normalizedName))@@ -97,6 +105,33 @@ class ProviderSetupInputValidatorImpl @Inject constructor() : ProviderSetupInputreturn Result.error(message)}+ // deviceProfile becomes the X-User-Agent model and part of the device signature. Blank+ // is fine (defaults to MAG250 internally); a non-blank value must be a safe ASCII token.+ if (normalizedDeviceProfile.isNotBlank() && !DEVICE_PROFILE_SAFE_REGEX.matches(normalizedDeviceProfile)) {+ return Result.error("Device profile must contain only letters, digits, dots, hyphens, and underscores (e.g. MAG250).")+ }++ // timezone is embedded literally in the Cookie header:+ // Cookie: mac=...; stb_lang=...; timezone=<value>+ // A semicolon in the value would inject additional cookie pairs. An unknown zone ID+ // would silently cause MAG portals to reject authentication or use the wrong time.+ if (normalizedTimezone.isNotBlank()) {+ if (!COOKIE_VALUE_SAFE_REGEX.matches(normalizedTimezone)) {+ return Result.error("Timezone contains characters that are not allowed in this field.")+ }+ runCatching { ZoneId.of(normalizedTimezone) }.onFailure {+ return Result.error("Timezone is not a recognized identifier (e.g. America/New_York, Europe/London, UTC).")+ }+ }++ // locale is embedded in the Cookie header as stb_lang. Apply the same cookie-safety+ // check and require a conservative BCP-47 language-tag shape.+ if (normalizedLocale.isNotBlank()) {+ if (!LOCALE_SAFE_REGEX.matches(normalizedLocale)) {+ return Result.error("Locale must be a language tag like 'en' or 'en-US'.")+ }+ }+return Result.success(ValidatedStalkerProviderInput(portalUrl = normalizedPortalUrl,@@ -108,4 +143,20 @@ class ProviderSetupInputValidatorImpl @Inject constructor() : ProviderSetupInput))}++ private companion object {+ // Safe ASCII token for device profiles (MAG250, MAG254, etc.). Excludes cookie+ // delimiters (;, ,, =, ") and HTTP header-breaking characters.+ private val DEVICE_PROFILE_SAFE_REGEX = Regex("^[A-Za-z0-9._-]+$")++ // Validates that a value can be safely embedded in a cookie without breaking the+ // Cookie: header. Semicolons, commas, double-quotes, and backslashes are all cookie+ // delimiters or quoting characters defined in RFC 6265 §4.1.1. Control characters+ // are already stripped by ProviderInputSanitizer before this point.+ private val COOKIE_VALUE_SAFE_REGEX = Regex("^[^;,\"\\\\]+$")++ // BCP-47 language tag: primary subtag (2–8 letters) optionally followed by+ // hyphen-separated extension subtags (1–8 alphanumeric characters each).+ private val LOCALE_SAFE_REGEX = Regex("^[a-zA-Z]{1,8}(-[a-zA-Z0-9]{1,8})*$")+ }}diff --git a/data/src/test/java/com/streamvault/data/epg/EpgResolutionEngineTest.kt b/data/src/test/java/com/streamvault/data/epg/EpgResolutionEngineTest.ktindex ab3a22a6..1c58c95c 100644--- a/data/src/test/java/com/streamvault/data/epg/EpgResolutionEngineTest.kt+++ b/data/src/test/java/com/streamvault/data/epg/EpgResolutionEngineTest.kt@@ -44,6 +44,9 @@ class EpgResolutionEngineTest {@Beforefun setup() {+ runTest {+ whenever(programDao.getChannelIdsWithPrograms(any(), any())).thenReturn(emptyList())+ }engine = EpgResolutionEngine(channelDao = channelDao,channelEpgMappingDao = channelEpgMappingDao,@@ -67,7 +70,6 @@ class EpgResolutionEngineTest {listOf(EpgChannelEntity(id = 1, epgSourceId = SOURCE_1, xmltvChannelId = "bbc1.uk", displayName = "BBC One", normalizedName = "bbcone")))whenever(channelEpgMappingDao.getForProvider(PROVIDER_ID)).thenReturn(emptyList())- whenever(programDao.countByProvider(PROVIDER_ID)).thenReturn(0)val summary = engine.resolveForProvider(PROVIDER_ID)@@ -95,7 +97,6 @@ class EpgResolutionEngineTest {listOf(EpgChannelEntity(id = 1, epgSourceId = SOURCE_1, xmltvChannelId = "cnn.intl", displayName = "CNN International", normalizedName = EpgNameNormalizer.normalize("CNN International"))))whenever(channelEpgMappingDao.getForProvider(PROVIDER_ID)).thenReturn(emptyList())- whenever(programDao.countByProvider(PROVIDER_ID)).thenReturn(0)val summary = engine.resolveForProvider(PROVIDER_ID)@@ -116,7 +117,7 @@ class EpgResolutionEngineTest {whenever(channelDao.getByProviderSync(PROVIDER_ID)).thenReturn(listOf(channel))whenever(providerEpgSourceDao.getEnabledForProviderSync(PROVIDER_ID)).thenReturn(emptyList())whenever(channelEpgMappingDao.getForProvider(PROVIDER_ID)).thenReturn(emptyList())- whenever(programDao.countByProvider(PROVIDER_ID)).thenReturn(10)+ whenever(programDao.getChannelIdsWithPrograms(PROVIDER_ID, listOf("local.ch1"))).thenReturn(listOf("local.ch1"))val summary = engine.resolveForProvider(PROVIDER_ID)@@ -135,7 +136,6 @@ class EpgResolutionEngineTest {whenever(channelDao.getByProviderSync(PROVIDER_ID)).thenReturn(listOf(channel))whenever(providerEpgSourceDao.getEnabledForProviderSync(PROVIDER_ID)).thenReturn(emptyList())whenever(channelEpgMappingDao.getForProvider(PROVIDER_ID)).thenReturn(emptyList())- whenever(programDao.countByProvider(PROVIDER_ID)).thenReturn(0)val summary = engine.resolveForProvider(PROVIDER_ID)@@ -155,7 +155,7 @@ class EpgResolutionEngineTest {whenever(channelDao.getByProviderSync(PROVIDER_ID)).thenReturn(listOf(channel))whenever(providerEpgSourceDao.getEnabledForProviderSync(PROVIDER_ID)).thenReturn(emptyList())whenever(channelEpgMappingDao.getForProvider(PROVIDER_ID)).thenReturn(emptyList())- whenever(programDao.countByProvider(PROVIDER_ID)).thenReturn(10)+ whenever(programDao.getChannelIdsWithPrograms(PROVIDER_ID, listOf("local.ch1"))).thenReturn(listOf("local.ch1"))val summary = engine.resolveForProvider(PROVIDER_ID)@@ -179,7 +179,6 @@ class EpgResolutionEngineTest {EpgChannelEntity(id = 2, epgSourceId = SOURCE_2, xmltvChannelId = "bbc1", displayName = "BBC 1", normalizedName = "bbc1")))whenever(channelEpgMappingDao.getForProvider(PROVIDER_ID)).thenReturn(emptyList())- whenever(programDao.countByProvider(PROVIDER_ID)).thenReturn(0)val summary = engine.resolveForProvider(PROVIDER_ID)@@ -210,7 +209,6 @@ class EpgResolutionEngineTest {confidence = 1.0f, isManualOverride = true, updatedAt = 1000L)whenever(channelEpgMappingDao.getForProvider(PROVIDER_ID)).thenReturn(listOf(manualMapping))- whenever(programDao.countByProvider(PROVIDER_ID)).thenReturn(0)engine.resolveForProvider(PROVIDER_ID)@@ -248,7 +246,6 @@ class EpgResolutionEngineTest {EpgChannelEntity(id = 2, epgSourceId = SOURCE_1, xmltvChannelId = "bbc.one.sd", displayName = "BBC One HD", normalizedName = EpgNameNormalizer.normalize("BBC One HD"))))whenever(channelEpgMappingDao.getForProvider(PROVIDER_ID)).thenReturn(emptyList())- whenever(programDao.countByProvider(PROVIDER_ID)).thenReturn(0)val summary = engine.resolveForProvider(PROVIDER_ID)@@ -276,7 +273,6 @@ class EpgResolutionEngineTest {EpgChannelEntity(id = 2, epgSourceId = SOURCE_1, xmltvChannelId = "ch-b", displayName = "Channel B", normalizedName = "channelb")))whenever(channelEpgMappingDao.getForProvider(PROVIDER_ID)).thenReturn(emptyList())- whenever(programDao.countByProvider(PROVIDER_ID)).thenReturn(0)val summary = engine.resolveForProvider(PROVIDER_ID)@@ -291,6 +287,27 @@ class EpgResolutionEngineTest {assertThat(mappings.map { it.providerChannelId }.toSet()).containsExactly(1L, 2L)}+ @Test+ fun `resolveForProvider_providerNativeFallback_requiresCoverageForEachChannel`() = runTest {+ val coveredChannel = makeChannel(id = 1, name = "Local One", epgChannelId = "local.one")+ val uncoveredChannel = makeChannel(id = 2, name = "Local Two", epgChannelId = "local.two")+ whenever(channelDao.getByProviderSync(PROVIDER_ID)).thenReturn(listOf(coveredChannel, uncoveredChannel))+ whenever(providerEpgSourceDao.getEnabledForProviderSync(PROVIDER_ID)).thenReturn(emptyList())+ whenever(channelEpgMappingDao.getForProvider(PROVIDER_ID)).thenReturn(emptyList())+ whenever(programDao.getChannelIdsWithPrograms(PROVIDER_ID, listOf("local.one", "local.two"))).thenReturn(listOf("local.one"))++ val summary = engine.resolveForProvider(PROVIDER_ID)++ assertThat(summary.providerNativeMatches).isEqualTo(1)+ assertThat(summary.unresolvedChannels).isEqualTo(1)++ val captor = argumentCaptor<List<ChannelEpgMappingEntity>>()+ verify(channelEpgMappingDao).replaceForProvider(any(), captor.capture())+ val mappings = captor.firstValue.associateBy { it.providerChannelId }+ assertThat(mappings.getValue(1L).sourceType).isEqualTo(EpgSourceType.PROVIDER.name)+ assertThat(mappings.getValue(2L).sourceType).isEqualTo(EpgSourceType.NONE.name)+ }+// ── getResolvedProgrammes ──────────────────────────────────────@Testdiff --git a/data/src/test/java/com/streamvault/data/local/RoomEnumConvertersTest.kt b/data/src/test/java/com/streamvault/data/local/RoomEnumConvertersTest.ktnew file mode 100644index 00000000..796188ac--- /dev/null+++ b/data/src/test/java/com/streamvault/data/local/RoomEnumConvertersTest.kt@@ -0,0 +1,36 @@+package com.streamvault.data.local++import com.google.common.truth.Truth.assertThat+import com.streamvault.domain.model.ContentType+import com.streamvault.domain.model.ProviderEpgSyncMode+import com.streamvault.domain.model.ProviderStatus+import com.streamvault.domain.model.ProviderType+import org.junit.Test++class RoomEnumConvertersTest {+ private val converters = RoomEnumConverters()++ @Test+ fun `unknown enum tokens map to compatibility defaults instead of throwing`() {+ assertThat(converters.toProviderType("legacy_xtream")).isEqualTo(ProviderType.M3U)+ assertThat(converters.toProviderStatus("legacy_status")).isEqualTo(ProviderStatus.UNKNOWN)+ assertThat(converters.toProviderEpgSyncMode("legacy_mode")).isEqualTo(ProviderEpgSyncMode.SKIP)+ assertThat(converters.toContentType("legacy_content")).isEqualTo(ContentType.LIVE)+ }++ @Test+ fun `known legacy aliases map to the intended enum values`() {+ assertThat(converters.toProviderType("xtream")).isEqualTo(ProviderType.XTREAM_CODES)+ assertThat(converters.toProviderType("stb")).isEqualTo(ProviderType.STALKER_PORTAL)+ assertThat(converters.toProviderEpgSyncMode("disabled")).isEqualTo(ProviderEpgSyncMode.SKIP)+ assertThat(converters.toContentType("episode")).isEqualTo(ContentType.SERIES_EPISODE)+ }++ @Test+ fun `enum parsing remains null safe and case insensitive`() {+ assertThat(converters.toProviderType(null)).isNull()+ assertThat(converters.toProviderStatus("active")).isEqualTo(ProviderStatus.ACTIVE)+ assertThat(converters.toProviderEpgSyncMode("background")).isEqualTo(ProviderEpgSyncMode.BACKGROUND)+ assertThat(converters.toContentType("series_episode")).isEqualTo(ContentType.SERIES_EPISODE)+ }+}\ No newline at end of filediff --git a/data/src/test/java/com/streamvault/data/manager/BackupManagerImplTest.kt b/data/src/test/java/com/streamvault/data/manager/BackupManagerImplTest.ktnew file mode 100644index 00000000..0190a45c--- /dev/null+++ b/data/src/test/java/com/streamvault/data/manager/BackupManagerImplTest.kt@@ -0,0 +1,646 @@+package com.streamvault.data.manager++import android.content.ContentResolver+import android.content.Context+import android.net.Uri+import com.google.gson.Gson+import com.google.common.truth.Truth.assertThat+import com.streamvault.data.local.DatabaseTransactionRunner+import com.streamvault.data.local.dao.EpisodeDao+import com.streamvault.data.local.dao.FavoriteDao+import com.streamvault.data.local.dao.MovieDao+import com.streamvault.data.local.dao.PlaybackHistoryDao+import com.streamvault.data.local.dao.ProviderDao+import com.streamvault.data.local.dao.RecordingScheduleDao+import com.streamvault.data.local.dao.VirtualGroupDao+import com.streamvault.data.local.entity.ProviderEntity+import com.streamvault.data.local.entity.RecordingScheduleEntity+import com.streamvault.data.preferences.PreferencesRepository+import com.streamvault.data.security.CredentialCrypto+import com.streamvault.domain.manager.BackupData+import com.streamvault.domain.manager.BackupConflictStrategy+import com.streamvault.domain.manager.BackupImportPlan+import com.streamvault.domain.manager.RecordingManager+import com.streamvault.domain.manager.RecordingScheduleImportDisposition+import com.streamvault.domain.manager.ScheduledRecordingBackup+import com.streamvault.domain.model.ContentType+import com.streamvault.domain.model.Favorite+import com.streamvault.domain.model.PlaybackHistory+import com.streamvault.domain.model.Provider+import com.streamvault.domain.model.ProviderType+import com.streamvault.domain.model.RecordingItem+import com.streamvault.domain.model.RecordingRecurrence+import com.streamvault.domain.model.RecordingStatus+import com.streamvault.domain.model.Result+import com.streamvault.domain.repository.CategoryRepository+import java.io.ByteArrayInputStream+import kotlinx.coroutines.runBlocking+import org.junit.Test+import org.mockito.kotlin.any+import org.mockito.kotlin.argThat+import org.mockito.kotlin.doAnswer+import org.mockito.kotlin.mock+import org.mockito.kotlin.never+import org.mockito.kotlin.verify+import org.mockito.kotlin.whenever++class BackupManagerImplTest {++ @Test+ fun `importConfig replace history only deletes imported providers and resyncs them in transaction`() = runBlocking {+ val context: Context = mock()+ val contentResolver: ContentResolver = mock()+ whenever(context.contentResolver).thenReturn(contentResolver)++ val providerDao: ProviderDao = mock()+ val playbackHistoryDao: PlaybackHistoryDao = mock()+ val movieDao: MovieDao = mock()+ val episodeDao: EpisodeDao = mock()+ val transactionRunner = RecordingTransactionRunner()+ val gson = Gson()++ val backupProvider = Provider(+ id = 100L,+ name = "Provider",+ type = ProviderType.M3U,+ serverUrl = "https://example.com",+ username = "user",+ password = "",+ stalkerMacAddress = ""+ )+ val backupData = BackupData(+ providers = listOf(backupProvider),+ playbackHistory = listOf(+ PlaybackHistory(+ contentId = 55L,+ contentType = ContentType.MOVIE,+ providerId = 100L,+ title = "Movie",+ streamUrl = "https://stream.example.test/movie.mp4",+ resumePositionMs = 12_000L,+ totalDurationMs = 5_400_000L+ )+ )+ )+ whenever(contentResolver.openInputStream(Uri.parse("content://backup"))).thenReturn(+ ByteArrayInputStream(gson.toJson(backupData).toByteArray())+ )+ whenever(providerDao.getAllSync()).thenReturn(+ listOf(+ ProviderEntity(+ id = 7L,+ name = "Stored Provider",+ type = ProviderType.M3U,+ serverUrl = "https://example.com",+ username = "user"+ )+ )+ )++ val manager = BackupManagerImpl(+ context = context,+ preferencesRepository = mock<PreferencesRepository>(),+ credentialCrypto = mock<CredentialCrypto>(),+ providerDao = providerDao,+ favoriteDao = mock<FavoriteDao>(),+ virtualGroupDao = mock<VirtualGroupDao>(),+ playbackHistoryDao = playbackHistoryDao,+ movieDao = movieDao,+ episodeDao = episodeDao,+ categoryRepository = mock<CategoryRepository>(),+ recordingScheduleDao = mock<RecordingScheduleDao>(),+ recordingManager = mock<RecordingManager>(),+ transactionRunner = transactionRunner,+ gson = gson+ )++ val result = manager.importConfig(+ uriString = "content://backup",+ plan = BackupImportPlan(+ importPreferences = false,+ importProviders = false,+ importSavedLibrary = false,+ importPlaybackHistory = true,+ importMultiViewPresets = false,+ importRecordingSchedules = false,+ conflictStrategy = BackupConflictStrategy.REPLACE_EXISTING+ )+ )++ assertThat(result).isInstanceOf(Result.Success::class.java)+ assertThat(transactionRunner.calls).isEqualTo(1)+ verify(playbackHistoryDao).deleteByProvider(7L)+ verify(playbackHistoryDao, never()).deleteAll()+ verify(playbackHistoryDao).insertOrUpdate(argThat {+ providerId == 7L &&+ contentId == 55L &&+ contentType == ContentType.MOVIE+ })+ verify(movieDao).syncWatchProgressFromHistoryByProvider(7L)+ verify(episodeDao).syncWatchProgressFromHistoryByProvider(7L)+ verify(movieDao, never()).syncAllWatchProgressFromHistory()+ verify(episodeDao, never()).syncAllWatchProgressFromHistory()+ }++ @Test+ fun `importConfig keeps saved library and history writes inside one room transaction`() = runBlocking {+ val context: Context = mock()+ val contentResolver: ContentResolver = mock()+ whenever(context.contentResolver).thenReturn(contentResolver)++ val providerDao: ProviderDao = mock()+ val favoriteDao: FavoriteDao = mock()+ val playbackHistoryDao: PlaybackHistoryDao = mock()+ val movieDao: MovieDao = mock()+ val episodeDao: EpisodeDao = mock()+ val transactionRunner = RecordingTransactionRunner()+ val gson = Gson()+ val backupProvider = Provider(+ id = 100L,+ name = "Provider",+ type = ProviderType.M3U,+ serverUrl = "https://example.com",+ username = "user",+ password = "",+ stalkerMacAddress = ""+ )+ val backupData = BackupData(+ providers = listOf(backupProvider),+ favorites = listOf(+ Favorite(+ providerId = 100L,+ contentId = 88L,+ contentType = ContentType.MOVIE,+ position = 0+ )+ ),+ playbackHistory = listOf(+ PlaybackHistory(+ contentId = 55L,+ contentType = ContentType.MOVIE,+ providerId = 100L,+ title = "Movie",+ streamUrl = "https://stream.example.test/movie.mp4",+ watchCount = 1+ )+ )+ )+ whenever(contentResolver.openInputStream(Uri.parse("content://backup-transaction"))).thenReturn(+ ByteArrayInputStream(gson.toJson(backupData).toByteArray())+ )+ whenever(providerDao.getAllSync()).thenReturn(+ listOf(+ ProviderEntity(+ id = 7L,+ name = "Stored Provider",+ type = ProviderType.M3U,+ serverUrl = "https://example.com",+ username = "user"+ )+ )+ )+ whenever(favoriteDao.get(any(), any(), any(), any())).thenReturn(null)+ doAnswer {+ assertThat(transactionRunner.isInTransaction).isTrue()+ 1L+ }.whenever(favoriteDao).insert(any())+ doAnswer {+ assertThat(transactionRunner.isInTransaction).isTrue()+ Unit+ }.whenever(playbackHistoryDao).deleteByProvider(any())+ doAnswer {+ assertThat(transactionRunner.isInTransaction).isTrue()+ Unit+ }.whenever(playbackHistoryDao).insertOrUpdate(any())+ doAnswer {+ assertThat(transactionRunner.isInTransaction).isTrue()+ Unit+ }.whenever(movieDao).syncWatchProgressFromHistoryByProvider(any())+ doAnswer {+ assertThat(transactionRunner.isInTransaction).isTrue()+ Unit+ }.whenever(episodeDao).syncWatchProgressFromHistoryByProvider(any())++ val manager = BackupManagerImpl(+ context = context,+ preferencesRepository = mock<PreferencesRepository>(),+ credentialCrypto = mock<CredentialCrypto>(),+ providerDao = providerDao,+ favoriteDao = favoriteDao,+ virtualGroupDao = mock<VirtualGroupDao>(),+ playbackHistoryDao = playbackHistoryDao,+ movieDao = movieDao,+ episodeDao = episodeDao,+ categoryRepository = mock<CategoryRepository>(),+ recordingScheduleDao = mock<RecordingScheduleDao>(),+ recordingManager = mock<RecordingManager>(),+ transactionRunner = transactionRunner,+ gson = gson+ )++ val result = manager.importConfig(+ uriString = "content://backup-transaction",+ plan = BackupImportPlan(+ importPreferences = false,+ importProviders = false,+ importSavedLibrary = true,+ importPlaybackHistory = true,+ importMultiViewPresets = false,+ importRecordingSchedules = false,+ conflictStrategy = BackupConflictStrategy.REPLACE_EXISTING+ )+ )++ assertThat(result).isInstanceOf(Result.Success::class.java)+ assertThat(transactionRunner.calls).isEqualTo(1)+ verify(favoriteDao).insert(any())+ verify(playbackHistoryDao).insertOrUpdate(any())+ }++ @Test+ fun `importConfig does not restore preferences before room-backed import succeeds`() = runBlocking {+ val context: Context = mock()+ val contentResolver: ContentResolver = mock()+ whenever(context.contentResolver).thenReturn(contentResolver)++ val providerDao: ProviderDao = mock()+ val favoriteDao: FavoriteDao = mock()+ val preferencesRepository: PreferencesRepository = mock()+ val gson = Gson()+ val backupProvider = Provider(+ id = 100L,+ name = "Provider",+ type = ProviderType.M3U,+ serverUrl = "https://example.com",+ username = "user",+ password = "",+ stalkerMacAddress = ""+ )+ val backupData = BackupData(+ preferences = mapOf("parentalControlLevel" to "4"),+ providers = listOf(backupProvider),+ favorites = listOf(+ Favorite(+ providerId = 100L,+ contentId = 88L,+ contentType = ContentType.MOVIE,+ position = 0+ )+ )+ )+ whenever(contentResolver.openInputStream(Uri.parse("content://backup-preferences-order"))).thenReturn(+ ByteArrayInputStream(gson.toJson(backupData).toByteArray())+ )+ whenever(providerDao.getAllSync()).thenReturn(+ listOf(+ ProviderEntity(+ id = 7L,+ name = "Stored Provider",+ type = ProviderType.M3U,+ serverUrl = "https://example.com",+ username = "user"+ )+ )+ )+ whenever(favoriteDao.get(any(), any(), any(), any())).thenReturn(null)+ whenever(favoriteDao.insert(any())).thenThrow(IllegalStateException("favorite insert failed"))++ val manager = BackupManagerImpl(+ context = context,+ preferencesRepository = preferencesRepository,+ credentialCrypto = mock<CredentialCrypto>(),+ providerDao = providerDao,+ favoriteDao = favoriteDao,+ virtualGroupDao = mock<VirtualGroupDao>(),+ playbackHistoryDao = mock<PlaybackHistoryDao>(),+ movieDao = mock<MovieDao>(),+ episodeDao = mock<EpisodeDao>(),+ categoryRepository = mock<CategoryRepository>(),+ recordingScheduleDao = mock<RecordingScheduleDao>(),+ recordingManager = mock<RecordingManager>(),+ transactionRunner = object : DatabaseTransactionRunner {+ override suspend fun <T> inTransaction(block: suspend () -> T): T = block()+ },+ gson = gson+ )++ val result = manager.importConfig(+ uriString = "content://backup-preferences-order",+ plan = BackupImportPlan(+ importPreferences = true,+ importProviders = false,+ importSavedLibrary = true,+ importPlaybackHistory = false,+ importMultiViewPresets = false,+ importRecordingSchedules = false,+ conflictStrategy = BackupConflictStrategy.REPLACE_EXISTING+ )+ )++ assertThat(result).isInstanceOf(Result.Error::class.java)+ verify(preferencesRepository, never()).setParentalControlLevel(any())+ }++ @Test+ fun `toScheduledRecordingBackup stores requested window and padding separately`() {+ val provider = Provider(+ id = 7L,+ name = "Provider",+ type = ProviderType.M3U,+ serverUrl = "https://example.com",+ username = "user",+ stalkerMacAddress = ""+ )+ val item = RecordingItem(+ id = "scheduled-1",+ scheduleId = 21L,+ providerId = 7L,+ channelId = 100L,+ channelName = "BBC One",+ streamUrl = "https://example.com/live.ts",+ scheduledStartMs = 1_700_000_000_000L,+ scheduledEndMs = 1_700_000_540_000L,+ programTitle = "World News",+ recurrence = RecordingRecurrence.DAILY,+ status = RecordingStatus.SCHEDULED+ )+ val schedule = RecordingScheduleEntity(+ id = 21L,+ providerId = 7L,+ channelId = 100L,+ channelName = "BBC One",+ streamUrl = "https://example.com/live.ts",+ programTitle = "World News",+ requestedStartMs = 1_700_000_120_000L,+ requestedEndMs = 1_700_000_480_000L,+ recurrence = RecordingRecurrence.DAILY+ )++ val backup = item.toScheduledRecordingBackup(provider, schedule)++ assertThat(backup.scheduledStartMs).isEqualTo(item.scheduledStartMs)+ assertThat(backup.scheduledEndMs).isEqualTo(item.scheduledEndMs)+ assertThat(backup.requestedStartMs).isEqualTo(schedule.requestedStartMs)+ assertThat(backup.requestedEndMs).isEqualTo(schedule.requestedEndMs)+ assertThat(backup.paddingBeforeMs).isEqualTo(120_000L)+ assertThat(backup.paddingAfterMs).isEqualTo(60_000L)+ assertThat(backup.recurringRuleId).isEqualTo(schedule.recurringRuleId)+ }++ @Test+ fun `toRecordingRequest preserves legacy effective backup windows`() {+ val backup = ScheduledRecordingBackup(+ providerServerUrl = "https://example.com",+ providerUsername = "user",+ channelId = 100L,+ channelName = "BBC One",+ streamUrl = "https://example.com/live.ts",+ scheduledStartMs = 1_700_000_000_000L,+ scheduledEndMs = 1_700_000_540_000L,+ programTitle = "World News",+ recurrence = RecordingRecurrence.NONE+ )++ val request = backup.toRecordingRequest(providerId = 7L)++ assertThat(request.scheduledStartMs).isEqualTo(backup.scheduledStartMs)+ assertThat(request.scheduledEndMs).isEqualTo(backup.scheduledEndMs)+ assertThat(request.paddingBeforeMs).isEqualTo(0L)+ assertThat(request.paddingAfterMs).isEqualTo(0L)+ }++ @Test+ fun `toRecordingRequest restores requested window and explicit padding from new backups`() {+ val backup = ScheduledRecordingBackup(+ providerServerUrl = "https://example.com",+ providerUsername = "user",+ channelId = 100L,+ channelName = "BBC One",+ streamUrl = "https://example.com/live.ts",+ scheduledStartMs = 1_700_000_000_000L,+ scheduledEndMs = 1_700_000_540_000L,+ requestedStartMs = 1_700_000_120_000L,+ requestedEndMs = 1_700_000_480_000L,+ paddingBeforeMs = 120_000L,+ paddingAfterMs = 60_000L,+ programTitle = "World News",+ recurrence = RecordingRecurrence.WEEKLY,+ recurringRuleId = "rule-1"+ )++ val request = backup.toRecordingRequest(providerId = 7L)++ assertThat(request.scheduledStartMs).isEqualTo(backup.requestedStartMs)+ assertThat(request.scheduledEndMs).isEqualTo(backup.requestedEndMs)+ assertThat(request.paddingBeforeMs).isEqualTo(backup.paddingBeforeMs)+ assertThat(request.paddingAfterMs).isEqualTo(backup.paddingAfterMs)+ assertThat(request.recurrence).isEqualTo(RecordingRecurrence.WEEKLY)+ assertThat(request.recurringRuleId).isEqualTo("rule-1")+ }++ @Test+ fun `normalizedRecurringBackups collapses duplicate occurrences for the same recurring rule`() {+ val recurringFirst = ScheduledRecordingBackup(+ providerServerUrl = "https://example.com",+ providerUsername = "user",+ channelId = 100L,+ channelName = "BBC One",+ streamUrl = "https://example.com/live.ts",+ scheduledStartMs = 1_700_000_000_000L,+ scheduledEndMs = 1_700_000_540_000L,+ requestedStartMs = 1_700_000_120_000L,+ requestedEndMs = 1_700_000_480_000L,+ programTitle = "World News",+ recurrence = RecordingRecurrence.DAILY,+ recurringRuleId = "rule-1"+ )+ val recurringSecond = recurringFirst.copy(+ scheduledStartMs = 1_700_086_400_000L,+ scheduledEndMs = 1_700_086_940_000L,+ requestedStartMs = 1_700_086_520_000L,+ requestedEndMs = 1_700_086_880_000L+ )+ val oneShot = ScheduledRecordingBackup(+ providerServerUrl = "https://example.com",+ providerUsername = "user",+ channelId = 101L,+ channelName = "BBC Two",+ streamUrl = "https://example.com/other.ts",+ scheduledStartMs = 1_700_010_000_000L,+ scheduledEndMs = 1_700_010_540_000L,+ programTitle = "Documentary",+ recurrence = RecordingRecurrence.NONE+ )++ val normalized = listOf(recurringSecond, oneShot, recurringFirst).normalizedRecurringBackups()++ assertThat(normalized).hasSize(2)+ assertThat(normalized).contains(recurringFirst)+ assertThat(normalized).contains(oneShot)+ }++ @Test+ fun `normalizedRecurringBackups keeps recurring entries without stable identity`() {+ val first = ScheduledRecordingBackup(+ providerServerUrl = "https://example.com",+ providerUsername = "user",+ channelId = 100L,+ channelName = "BBC One",+ streamUrl = "https://example.com/live.ts",+ scheduledStartMs = 1_700_000_000_000L,+ scheduledEndMs = 1_700_000_540_000L,+ programTitle = "World News",+ recurrence = RecordingRecurrence.DAILY+ )+ val second = first.copy(+ scheduledStartMs = 1_700_086_400_000L,+ scheduledEndMs = 1_700_086_940_000L+ )++ val normalized = listOf(first, second).normalizedRecurringBackups()++ assertThat(normalized).containsExactly(first, second)+ }++ @Test+ fun `importScheduledRecordingBackups reports skipped and failed outcomes`() {+ val recordingManager: RecordingManager = mock()+ val provider = ProviderEntity(+ id = 7L,+ name = "Provider",+ type = ProviderType.M3U,+ serverUrl = "https://example.com",+ username = "user"+ )+ val existingSchedule = RecordingItem(+ id = "existing-1",+ providerId = 7L,+ channelId = 100L,+ channelName = "BBC One",+ streamUrl = "https://example.com/live.ts",+ scheduledStartMs = 1_700_000_000_000L,+ scheduledEndMs = 1_700_000_540_000L,+ status = RecordingStatus.SCHEDULED+ )+ val keepExisting = ScheduledRecordingBackup(+ providerServerUrl = provider.serverUrl,+ providerUsername = provider.username,+ channelId = 100L,+ channelName = "BBC One",+ streamUrl = "https://example.com/live.ts",+ scheduledStartMs = existingSchedule.scheduledStartMs,+ scheduledEndMs = existingSchedule.scheduledEndMs,+ programTitle = "World News"+ )+ val validationFailure = keepExisting.copy(+ channelId = 101L,+ channelName = "BBC Two",+ streamUrl = "https://example.com/other.ts",+ scheduledStartMs = 1_700_001_000_000L,+ scheduledEndMs = 1_700_001_540_000L+ )++ runBlocking {+ whenever(recordingManager.scheduleRecording(any()))+ .thenReturn(Result.error("Recording conflicts with an existing active recording for World News."))+ }++ val summary = kotlinx.coroutines.runBlocking {+ importScheduledRecordingBackups(+ recordings = listOf(keepExisting, validationFailure),+ storedProviders = listOf(provider),+ existingSchedules = mutableListOf(existingSchedule),+ conflictStrategy = BackupConflictStrategy.KEEP_EXISTING,+ recordingManager = recordingManager,+ nowMs = 1_699_999_000_000L+ )+ }++ assertThat(summary.importedCount).isEqualTo(0)+ assertThat(summary.skippedCount).isEqualTo(1)+ assertThat(summary.failedCount).isEqualTo(1)+ assertThat(summary.outcomes.map { it.disposition }).containsExactly(+ RecordingScheduleImportDisposition.SKIPPED_EXISTING,+ RecordingScheduleImportDisposition.FAILED+ )+ assertThat(summary.outcomes.last().reason).contains("conflicts")+ runBlocking {+ verify(recordingManager).scheduleRecording(any())+ }+ }++ @Test+ fun `importScheduledRecordingBackups reports replaced existing schedules`() {+ val recordingManager: RecordingManager = mock()+ val provider = ProviderEntity(+ id = 7L,+ name = "Provider",+ type = ProviderType.M3U,+ serverUrl = "https://example.com",+ username = "user"+ )+ val existingSchedule = RecordingItem(+ id = "existing-1",+ providerId = 7L,+ channelId = 100L,+ channelName = "BBC One",+ streamUrl = "https://example.com/live.ts",+ scheduledStartMs = 1_700_000_000_000L,+ scheduledEndMs = 1_700_000_540_000L,+ status = RecordingStatus.SCHEDULED+ )+ val imported = ScheduledRecordingBackup(+ providerServerUrl = provider.serverUrl,+ providerUsername = provider.username,+ channelId = 100L,+ channelName = "BBC One",+ streamUrl = "https://example.com/live.ts",+ scheduledStartMs = existingSchedule.scheduledStartMs,+ scheduledEndMs = existingSchedule.scheduledEndMs,+ programTitle = "World News"+ )+ val importedItem = existingSchedule.copy(id = "imported-1")++ runBlocking {+ whenever(recordingManager.cancelRecording(existingSchedule.id)).thenReturn(Result.success(Unit))+ whenever(recordingManager.scheduleRecording(any())).thenReturn(Result.success(importedItem))+ }++ val summary = kotlinx.coroutines.runBlocking {+ importScheduledRecordingBackups(+ recordings = listOf(imported),+ storedProviders = listOf(provider),+ existingSchedules = mutableListOf(existingSchedule),+ conflictStrategy = BackupConflictStrategy.REPLACE_EXISTING,+ recordingManager = recordingManager,+ nowMs = 1_699_999_000_000L+ )+ }++ assertThat(summary.importedCount).isEqualTo(1)+ assertThat(summary.failedCount).isEqualTo(0)+ assertThat(summary.outcomes.single().disposition).isEqualTo(RecordingScheduleImportDisposition.REPLACED_EXISTING)+ runBlocking {+ verify(recordingManager).cancelRecording(existingSchedule.id)+ verify(recordingManager).scheduleRecording(any())+ }+ }++ private class RecordingTransactionRunner : DatabaseTransactionRunner {+ var calls: Int = 0+ private var depth: Int = 0++ val isInTransaction: Boolean+ get() = depth > 0++ override suspend fun <T> inTransaction(block: suspend () -> T): T {+ calls += 1+ depth += 1+ return try {+ block()+ } finally {+ depth -= 1+ }+ }+ }+}\ No newline at end of filediff --git a/data/src/test/java/com/streamvault/data/manager/ProgramReminderManagerImplTest.kt b/data/src/test/java/com/streamvault/data/manager/ProgramReminderManagerImplTest.ktindex 3d88b22f..fdfeacc3 100644--- a/data/src/test/java/com/streamvault/data/manager/ProgramReminderManagerImplTest.kt+++ b/data/src/test/java/com/streamvault/data/manager/ProgramReminderManagerImplTest.kt@@ -6,11 +6,17 @@ import com.streamvault.data.local.entity.ProgramReminderEntityimport com.streamvault.data.manager.reminder.ProgramReminderAlarmSchedulerimport com.streamvault.data.manager.reminder.ProgramReminderNotifierimport com.streamvault.domain.model.Program+import com.streamvault.domain.model.ProgramReminder+import com.streamvault.domain.model.Result+import kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.firstimport kotlinx.coroutines.test.runTestimport org.junit.Testimport org.mockito.kotlin.argumentCaptorimport org.mockito.kotlin.eqimport org.mockito.kotlin.mock+import org.mockito.kotlin.neverimport org.mockito.kotlin.verifyimport org.mockito.kotlin.whenever@@ -26,6 +32,11 @@ class ProgramReminderManagerImplTest {notifier = notifier)+ init {+ whenever(alarmScheduler.canScheduleExactAlarms()).thenReturn(true)+ whenever(alarmScheduler.schedule(org.mockito.kotlin.any(), org.mockito.kotlin.any())).thenReturn(Result.success(Unit))+ }+@Testfun `scheduleReminder inserts reminder and schedules alarm`() = runTest {val now = System.currentTimeMillis()@@ -51,6 +62,30 @@ class ProgramReminderManagerImplTest {verify(alarmScheduler).schedule(eq(42L), org.mockito.kotlin.any())}+ @Test+ fun `scheduleReminder fails when exact alarms are unavailable`() = runTest {+ val now = System.currentTimeMillis()+ val program = Program(+ channelId = "bbc1",+ title = "World News",+ startTime = now + 30 * 60_000L,+ endTime = now + 60 * 60_000L,+ providerId = 7L+ )+ whenever(alarmScheduler.canScheduleExactAlarms()).thenReturn(false)++ val result = manager.scheduleReminder(+ providerId = 7L,+ channelId = "bbc1",+ channelName = "BBC One",+ program = program+ )++ assertThat(result).isInstanceOf(Result.Error::class.java)+ verify(dao, never()).insert(org.mockito.kotlin.any())+ verify(alarmScheduler, never()).schedule(org.mockito.kotlin.any(), org.mockito.kotlin.any())+ }+@Testfun `cancelReminder deletes reminder and cancels alarm`() = runTest {val reminder = ProgramReminderEntity(@@ -75,6 +110,57 @@ class ProgramReminderManagerImplTest {verify(alarmScheduler).cancel(42L)}+ @Test+ fun `restoreScheduledReminders coerces overdue reminder alarms into the future`() = runTest {+ val nowBeforeRestore = System.currentTimeMillis()+ val reminder = ProgramReminderEntity(+ id = 42L,+ providerId = 7L,+ channelId = "bbc1",+ channelName = "BBC One",+ programTitle = "World News",+ programStartTime = nowBeforeRestore + 5 * 60_000L,+ remindAt = nowBeforeRestore - 60_000L+ )+ whenever(dao.getPendingActive(org.mockito.kotlin.any())).thenReturn(listOf(reminder))++ manager.restoreScheduledReminders()++ val remindAtCaptor = argumentCaptor<Long>()+ verify(alarmScheduler).schedule(eq(42L), remindAtCaptor.capture())+ assertThat(remindAtCaptor.firstValue).isAtLeast(nowBeforeRestore + 1_000L)+ }++ @Test+ fun `restoreScheduledReminders continues after one reminder fails to reschedule`() = runTest {+ val now = System.currentTimeMillis()+ val first = ProgramReminderEntity(+ id = 41L,+ providerId = 7L,+ channelId = "bbc1",+ channelName = "BBC One",+ programTitle = "World News",+ programStartTime = now + 5 * 60_000L,+ remindAt = now + 60_000L+ )+ val second = ProgramReminderEntity(+ id = 42L,+ providerId = 7L,+ channelId = "bbc2",+ channelName = "BBC Two",+ programTitle = "Documentary",+ programStartTime = now + 10 * 60_000L,+ remindAt = now + 120_000L+ )+ whenever(dao.getPendingActive(org.mockito.kotlin.any())).thenReturn(listOf(first, second))+ whenever(alarmScheduler.schedule(41L, first.remindAt)).thenReturn(Result.error("denied"))++ manager.restoreScheduledReminders()++ verify(alarmScheduler).schedule(41L, first.remindAt)+ verify(alarmScheduler).schedule(42L, second.remindAt)+ }+@Testfun `deliverReminder notifies once and marks reminder notified`() = runTest {val reminder = ProgramReminderEntity(@@ -95,4 +181,91 @@ class ProgramReminderManagerImplTest {verify(dao).update(updatedCaptor.capture())assertThat(updatedCaptor.firstValue.notifiedAt).isNotNull()}++ @Test+ fun `deliverReminder skips stale reminders and dismisses them`() = runTest {+ val reminder = ProgramReminderEntity(+ id = 42L,+ providerId = 7L,+ channelId = "bbc1",+ channelName = "BBC One",+ programTitle = "World News",+ programStartTime = System.currentTimeMillis() - 3 * 60_000L,+ remindAt = System.currentTimeMillis() - 8 * 60_000L+ )+ whenever(dao.getById(42L)).thenReturn(reminder)++ manager.deliverReminder(42L)++ verify(notifier, never()).showReminder(org.mockito.kotlin.any())+ val updatedCaptor = argumentCaptor<ProgramReminderEntity>()+ verify(dao).update(updatedCaptor.capture())+ assertThat(updatedCaptor.firstValue.isDismissed).isTrue()+ assertThat(updatedCaptor.firstValue.notifiedAt).isNull()+ }++ @Test+ fun `observeUpcomingReminders drops expired reminders when only time advances`() = runTest {+ var now = 10_000L+ val reminders = MutableStateFlow(+ listOf(+ ProgramReminderEntity(+ id = 42L,+ providerId = 7L,+ channelId = "bbc1",+ channelName = "BBC One",+ programTitle = "World News",+ programStartTime = now + 1_000L,+ remindAt = now - 30_000L+ )+ )+ )+ val upcomingTimeFlow = MutableStateFlow(now)+ val flowDao = object : ProgramReminderDao {+ override fun observeUpcoming(): Flow<List<ProgramReminderEntity>> = reminders++ override suspend fun getIdsByProvider(providerId: Long): List<Long> = error("unused")++ override suspend fun getByProgram(+ providerId: Long,+ channelId: String,+ programTitle: String,+ programStartTime: Long+ ): ProgramReminderEntity? = error("unused")++ override suspend fun getById(id: Long): ProgramReminderEntity? = error("unused")++ override suspend fun getPendingActive(now: Long): List<ProgramReminderEntity> = error("unused")++ override suspend fun insert(reminder: ProgramReminderEntity): Long = error("unused")++ override suspend fun update(reminder: ProgramReminderEntity) = error("unused")++ override suspend fun deleteByProgram(+ providerId: Long,+ channelId: String,+ programTitle: String,+ programStartTime: Long+ ) = error("unused")++ override suspend fun deleteById(id: Long) = error("unused")++ override suspend fun deleteExpired(beforeTime: Long): Int = error("unused")+ }+ val timedManager = ProgramReminderManagerImpl.forTesting(+ programReminderDao = flowDao,+ alarmScheduler = alarmScheduler,+ notifier = notifier,+ nowProvider = { now },+ upcomingTimeFlow = upcomingTimeFlow+ )+ val initial = timedManager.observeUpcomingReminders().first()+ assertThat(initial.map(ProgramReminder::id)).containsExactly(42L)++ now += 2_000L+ upcomingTimeFlow.value = now++ val expired = timedManager.observeUpcomingReminders().first()+ assertThat(expired).isEmpty()+ }}diff --git a/data/src/test/java/com/streamvault/data/manager/RecordingManagerImplTest.kt b/data/src/test/java/com/streamvault/data/manager/RecordingManagerImplTest.ktnew file mode 100644index 00000000..750114aa--- /dev/null+++ b/data/src/test/java/com/streamvault/data/manager/RecordingManagerImplTest.kt@@ -0,0 +1,274 @@+package com.streamvault.data.manager++import android.app.NotificationManager+import android.content.ContentResolver+import android.content.Context+import com.google.common.truth.Truth.assertThat+import com.google.gson.Gson+import com.streamvault.data.local.DatabaseTransactionRunner+import com.streamvault.data.local.dao.ProviderDao+import com.streamvault.data.local.dao.RecordingRunDao+import com.streamvault.data.local.dao.RecordingScheduleDao+import com.streamvault.data.local.dao.RecordingStorageDao+import com.streamvault.data.local.entity.ProviderEntity+import com.streamvault.data.local.entity.RecordingRunEntity+import com.streamvault.data.local.entity.RecordingStorageEntity+import com.streamvault.data.manager.recording.HlsLiveCaptureEngine+import com.streamvault.data.manager.recording.RecordingAlarmScheduler+import com.streamvault.data.manager.recording.RecordingServiceLauncher+import com.streamvault.data.manager.recording.RecordingSourceResolver+import com.streamvault.data.manager.recording.ResolvedRecordingSource+import com.streamvault.data.manager.recording.TsPassThroughCaptureEngine+import com.streamvault.data.preferences.PreferencesRepository+import com.streamvault.domain.model.ProviderType+import com.streamvault.domain.model.RecordingFailureCategory+import com.streamvault.domain.model.RecordingRecurrence+import com.streamvault.domain.model.RecordingRequest+import com.streamvault.domain.model.RecordingSourceType+import com.streamvault.domain.model.RecordingStatus+import com.streamvault.domain.model.Result+import java.io.File+import java.util.UUID+import kotlinx.coroutines.flow.flowOf+import kotlinx.coroutines.runBlocking+import kotlinx.coroutines.withTimeout+import org.junit.Test+import org.mockito.kotlin.any+import org.mockito.kotlin.atLeastOnce+import org.mockito.kotlin.argThat+import org.mockito.kotlin.eq+import org.mockito.kotlin.mock+import org.mockito.kotlin.never+import org.mockito.kotlin.times+import org.mockito.kotlin.verify+import org.mockito.kotlin.whenever++class RecordingManagerImplTest {++ private val context: Context = mock()+ private val providerDao: ProviderDao = mock()+ private val recordingScheduleDao: RecordingScheduleDao = mock()+ private val recordingRunDao: RecordingRunDao = mock()+ private val recordingStorageDao: RecordingStorageDao = mock()+ private val recordingSourceResolver: RecordingSourceResolver = mock()+ private val tsEngine: TsPassThroughCaptureEngine = mock()+ private val hlsEngine: HlsLiveCaptureEngine = mock()+ private val alarmScheduler: RecordingAlarmScheduler = mock()+ private val preferencesRepository: PreferencesRepository = mock()+ private val recordingServiceLauncher: RecordingServiceLauncher = mock()+ private val transactionRunner = object : DatabaseTransactionRunner {+ override suspend fun <T> inTransaction(block: suspend () -> T): T = block()+ }++ private val tempRoot = File("build/tmp/recording-manager-tests/${UUID.randomUUID()}").apply { mkdirs() }++ init {+ whenever(context.filesDir).thenReturn(tempRoot)+ whenever(context.getExternalFilesDir(any())).thenReturn(null)+ whenever(context.contentResolver).thenReturn(mock<ContentResolver>())+ whenever(context.getSystemService(NotificationManager::class.java)).thenReturn(null)+ whenever(preferencesRepository.recordingWifiOnly).thenReturn(flowOf(false))+ whenever(preferencesRepository.recordingPaddingBeforeMinutes).thenReturn(flowOf(0))+ whenever(preferencesRepository.recordingPaddingAfterMinutes).thenReturn(flowOf(0))+ whenever(preferencesRepository.playerWifiMaxVideoHeight).thenReturn(flowOf(null))+ whenever(preferencesRepository.playerEthernetMaxVideoHeight).thenReturn(flowOf(null))+ whenever(alarmScheduler.canScheduleExactAlarms()).thenReturn(true)+ whenever(alarmScheduler.scheduleStart(any(), any())).thenReturn(Result.success(Unit))+ whenever(alarmScheduler.scheduleStop(any(), any())).thenReturn(Result.success(Unit))+ runBlocking {+ whenever(recordingStorageDao.get()).thenReturn(defaultStorage())+ whenever(recordingRunDao.getAlarmManagedScheduledRuns()).thenReturn(emptyList())+ whenever(recordingRunDao.getRecordingRuns()).thenReturn(emptyList())+ whenever(recordingRunDao.getOverlapping(any(), any())).thenReturn(emptyList())+ whenever(providerDao.getById(any())).thenReturn(providerEntity())+ }+ }++ @Test+ fun `scheduleRecording validates before inserting schedule`() = runBlocking {+ val existing = scheduledRun(id = "existing")+ runBlocking {+ whenever(recordingStorageDao.get()).thenReturn(defaultStorage(maxSimultaneousRecordings = 1))+ whenever(recordingRunDao.getOverlapping(any(), any())).thenReturn(listOf(existing))+ }++ val manager = createManager()+ val result = manager.scheduleRecording(recordingRequest())++ assertThat(result).isInstanceOf(com.streamvault.domain.model.Result.Error::class.java)+ verify(recordingScheduleDao, never()).insert(any())+ verify(recordingRunDao, never()).insert(any())+ }++ @Test+ fun `scheduleRecording fails when exact alarms are unavailable`() = runBlocking {+ whenever(alarmScheduler.canScheduleExactAlarms()).thenReturn(false)++ val manager = createManager()+ val result = manager.scheduleRecording(recordingRequest())++ assertThat(result).isInstanceOf(Result.Error::class.java)+ verify(recordingScheduleDao, never()).insert(any())+ verify(recordingRunDao, never()).insert(any())+ }++ @Test+ fun `startManualRecording routes capture through foreground service`() = runBlocking {+ val request = recordingRequest()+ whenever(recordingSourceResolver.resolveLiveSource(any(), any(), any())).thenReturn(resolvedSource())+ runBlocking {+ whenever(recordingScheduleDao.insert(any())).thenReturn(17L)+ }++ val manager = createManager()+ val result = manager.startManualRecording(request)++ assertThat(result).isInstanceOf(com.streamvault.domain.model.Result.Success::class.java)+ verify(recordingRunDao).insert(argThat { status == RecordingStatus.RECORDING })+ verify(alarmScheduler).scheduleStop(any(), eq(request.scheduledEndMs))+ verify(recordingServiceLauncher).startCapture(eq(context), any())+ }++ @Test+ fun `promoteScheduledRecording completes for one-shot schedule without deadlock`() {+ runBlocking {+ val run = scheduledRun(id = "scheduled-one-shot")+ whenever(recordingRunDao.getById(run.id)).thenReturn(run)+ whenever(recordingSourceResolver.resolveLiveSource(any(), any(), any())).thenReturn(resolvedSource())++ val manager = createManager()++ val result = withTimeout(1_000L) {+ manager.promoteScheduledRecording(run.id)+ }++ assertThat(result).isInstanceOf(com.streamvault.domain.model.Result.Success::class.java)+ verify(recordingRunDao).update(argThat { id == run.id && status == RecordingStatus.RECORDING })+ verify(alarmScheduler).scheduleStop(run.id, run.scheduledEndMs)+ }+ }++ @Test+ fun `promoteScheduledRecording spawns next recurring run without deadlock`() {+ runBlocking {+ val run = scheduledRun(+ id = "scheduled-recurring",+ recurrence = RecordingRecurrence.DAILY,+ recurringRuleId = "rule-1"+ )+ whenever(recordingRunDao.getById(run.id)).thenReturn(run)+ whenever(recordingRunDao.getByStatus(RecordingStatus.SCHEDULED)).thenReturn(emptyList())+ whenever(recordingRunDao.getRecordingRuns()).thenReturn(emptyList())+ whenever(recordingSourceResolver.resolveLiveSource(any(), any(), any())).thenReturn(resolvedSource())++ val manager = createManager()++ val result = withTimeout(1_000L) {+ manager.promoteScheduledRecording(run.id)+ }++ assertThat(result).isInstanceOf(com.streamvault.domain.model.Result.Success::class.java)+ verify(recordingRunDao).insert(any())+ verify(alarmScheduler, times(1)).scheduleStart(any(), any())+ }+ }++ @Test+ fun `reconcileRecordingState marks stale recording failed instead of restarting capture`() = runBlocking {+ val staleRun = scheduledRun(id = "stale-recording", status = RecordingStatus.RECORDING)+ runBlocking {+ whenever(recordingRunDao.getRecordingRuns()).thenReturn(listOf(staleRun))+ whenever(recordingRunDao.getById(staleRun.id)).thenReturn(staleRun)+ }++ val manager = createManager()+ val result = manager.reconcileRecordingState()++ assertThat(result).isInstanceOf(com.streamvault.domain.model.Result.Success::class.java)+ verify(recordingRunDao, atLeastOnce()).update(+ argThat {+ id == staleRun.id &&+ status == RecordingStatus.FAILED &&+ failureCategory == RecordingFailureCategory.UNKNOWN+ }+ )+ verify(recordingServiceLauncher, never()).startCapture(any(), any())+ }++ private fun createManager() = RecordingManagerImpl(+ context = context,+ gson = Gson(),+ transactionRunner = transactionRunner,+ providerDao = providerDao,+ recordingScheduleDao = recordingScheduleDao,+ recordingRunDao = recordingRunDao,+ recordingStorageDao = recordingStorageDao,+ recordingSourceResolver = recordingSourceResolver,+ tsPassThroughCaptureEngine = tsEngine,+ hlsLiveCaptureEngine = hlsEngine,+ alarmScheduler = alarmScheduler,+ preferencesRepository = preferencesRepository,+ recordingServiceLauncher = recordingServiceLauncher+ )++ private fun defaultStorage(maxSimultaneousRecordings: Int = 2) = RecordingStorageEntity(+ outputDirectory = tempRoot.absolutePath,+ availableBytes = 2_000_000_000L,+ isWritable = true,+ maxSimultaneousRecordings = maxSimultaneousRecordings+ )++ private fun recordingRequest() = RecordingRequest(+ providerId = 7L,+ channelId = 100L,+ channelName = "BBC One",+ streamUrl = "https://example.com/live.ts",+ scheduledStartMs = System.currentTimeMillis() + 60_000L,+ scheduledEndMs = System.currentTimeMillis() + 120_000L,+ programTitle = "World News"+ )++ private fun scheduledRun(+ id: String,+ status: RecordingStatus = RecordingStatus.SCHEDULED,+ recurrence: RecordingRecurrence = RecordingRecurrence.NONE,+ recurringRuleId: String? = null+ ) = RecordingRunEntity(+ id = id,+ scheduleId = 11L,+ providerId = 7L,+ channelId = 100L,+ channelName = "BBC One",+ streamUrl = "https://example.com/live.ts",+ programTitle = "World News",+ scheduledStartMs = System.currentTimeMillis() + 60_000L,+ scheduledEndMs = System.currentTimeMillis() + 120_000L,+ recurrence = recurrence,+ recurringRuleId = recurringRuleId,+ status = status,+ sourceType = RecordingSourceType.UNKNOWN,+ headersJson = "{}",+ failureCategory = RecordingFailureCategory.NONE,+ scheduleEnabled = true,+ alarmStartAtMs = System.currentTimeMillis() + 60_000L+ )++ private fun resolvedSource() = ResolvedRecordingSource(+ url = "https://example.com/live.ts",+ sourceType = RecordingSourceType.TS,+ headers = emptyMap(),+ userAgent = null,+ expirationTime = null,+ providerLabel = "Provider"+ )++ private fun providerEntity() = ProviderEntity(+ id = 7L,+ name = "Provider",+ type = ProviderType.M3U,+ serverUrl = "https://example.com",+ username = "user",+ password = "pass",+ maxConnections = 3+ )+}\ No newline at end of filediff --git a/data/src/test/java/com/streamvault/data/manager/recording/RecordingCaptureEngineTest.kt b/data/src/test/java/com/streamvault/data/manager/recording/RecordingCaptureEngineTest.ktnew file mode 100644index 00000000..5b55d29a--- /dev/null+++ b/data/src/test/java/com/streamvault/data/manager/recording/RecordingCaptureEngineTest.kt@@ -0,0 +1,92 @@+package com.streamvault.data.manager.recording++import android.content.ContentResolver+import com.google.common.truth.Truth.assertThat+import com.streamvault.domain.model.RecordingSourceType+import java.io.IOException+import java.util.concurrent.atomic.AtomicInteger+import kotlinx.coroutines.test.runTest+import okhttp3.Interceptor+import okhttp3.MediaType.Companion.toMediaType+import okhttp3.OkHttpClient+import okhttp3.Protocol+import okhttp3.Response+import okhttp3.ResponseBody.Companion.toResponseBody+import org.junit.Rule+import org.junit.Test+import org.junit.rules.TemporaryFolder+import org.mockito.kotlin.mock++class RecordingCaptureEngineTest {++ @get:Rule+ val tempFolder = TemporaryFolder()++ @Test+ fun hlsCaptureRetriesTransientSegmentFailureOnNextPlaylistRefresh() {+ runTest {+ val playlistBodies = listOf(+ """+ #EXTM3U+ #EXT-X-VERSION:3+ #EXT-X-TARGETDURATION:2+ #EXTINF:2.0,+ https://example.com/segment-1.ts+ """.trimIndent(),+ """+ #EXTM3U+ #EXT-X-VERSION:3+ #EXT-X-TARGETDURATION:2+ #EXTINF:2.0,+ https://example.com/segment-1.ts+ #EXT-X-ENDLIST+ """.trimIndent()+ )+ val playlistAttempts = AtomicInteger(0)+ val segmentAttempts = AtomicInteger(0)+ val client = OkHttpClient.Builder()+ .addInterceptor(Interceptor { chain ->+ when (chain.request().url.toString()) {+ "https://example.com/live.m3u8" -> {+ val attempt = (playlistAttempts.incrementAndGet() - 1)+ .coerceAtMost(playlistBodies.lastIndex)+ response(chain, 200, playlistBodies[attempt])+ }+ "https://example.com/segment-1.ts" -> {+ if (segmentAttempts.incrementAndGet() == 1) {+ throw IOException("socket timeout")+ }+ response(chain, 200, "segment-payload")+ }+ else -> error("Unexpected URL ${chain.request().url}")+ }+ })+ .build()+ val engine = HlsLiveCaptureEngine(client)+ val outputFile = tempFolder.newFile("capture.ts")++ engine.capture(+ source = ResolvedRecordingSource(+ url = "https://example.com/live.m3u8",+ sourceType = RecordingSourceType.HLS+ ),+ outputTarget = RecordingOutputTarget.FileTarget(outputFile),+ contentResolver = mock<ContentResolver>(),+ scheduledEndMs = System.currentTimeMillis() + 60_000,+ onProgress = {}+ )++ assertThat(segmentAttempts.get()).isEqualTo(2)+ assertThat(outputFile.readText()).isEqualTo("segment-payload")+ }+ }++ private fun response(chain: Interceptor.Chain, code: Int, body: String): Response =+ Response.Builder()+ .request(chain.request())+ .protocol(Protocol.HTTP_1_1)+ .code(code)+ .message("OK")+ .body(body.toResponseBody("application/vnd.apple.mpegurl".toMediaType()))+ .build()+}\ No newline at end of filediff --git a/data/src/test/java/com/streamvault/data/manager/recording/RecordingForegroundIdleGateTest.kt b/data/src/test/java/com/streamvault/data/manager/recording/RecordingForegroundIdleGateTest.ktnew file mode 100644index 00000000..578da590--- /dev/null+++ b/data/src/test/java/com/streamvault/data/manager/recording/RecordingForegroundIdleGateTest.kt@@ -0,0 +1,42 @@+package com.streamvault.data.manager.recording++import com.google.common.truth.Truth.assertThat+import org.junit.Test++class RecordingForegroundIdleGateTest {++ @Test+ fun `pending command keeps service alive when active count is zero`() {+ val gate = RecordingForegroundIdleGate()++ gate.onCommandStarted()+ gate.onActiveCountChanged(0)++ assertThat(gate.shouldKeepAlive()).isTrue()+ assertThat(gate.hasPendingCommands).isTrue()+ }++ @Test+ fun `service becomes idle only after pending command completes and no recordings remain`() {+ val gate = RecordingForegroundIdleGate()++ gate.onCommandStarted()+ gate.onActiveCountChanged(0)+ gate.onCommandFinished()++ assertThat(gate.shouldKeepAlive()).isFalse()+ assertThat(gate.pendingCommandCount).isEqualTo(0)+ }++ @Test+ fun `active recording keeps service alive after pending command finishes`() {+ val gate = RecordingForegroundIdleGate()++ gate.onCommandStarted()+ gate.onActiveCountChanged(1)+ gate.onCommandFinished()++ assertThat(gate.shouldKeepAlive()).isTrue()+ assertThat(gate.activeRecordingCount).isEqualTo(1)+ }+}\ No newline at end of filediff --git a/data/src/test/java/com/streamvault/data/parser/XmltvParserTest.kt b/data/src/test/java/com/streamvault/data/parser/XmltvParserTest.ktindex 6b36eead..fc1a068b 100644--- a/data/src/test/java/com/streamvault/data/parser/XmltvParserTest.kt+++ b/data/src/test/java/com/streamvault/data/parser/XmltvParserTest.kt@@ -8,6 +8,9 @@ import kotlinx.coroutines.awaitAllimport kotlinx.coroutines.test.runTestimport org.junit.Beforeimport org.junit.Test+import java.io.ByteArrayOutputStream+import java.util.TimeZone+import java.util.zip.GZIPOutputStream/*** Unit tests for [XmltvParser].@@ -149,6 +152,69 @@ class XmltvParserTest {assertThat(prog.startTime).isEqualTo(expected09UTC)}+ @Test+ fun `parse_noOffsetTimestamp_usesProvidedTimezone`() {+ val xml = """+ <?xml version="1.0"?>+ <tv>+ <programme start="20250101120000" stop="20250101130000" channel="ch1">+ <title>Timezone Test</title>+ </programme>+ </tv>+ """.trimIndent()++ val programs = parser.parse(xml.byteInputStream(), timezoneId = "America/New_York")++ assertThat(programs).hasSize(1)+ assertThat(programs.single().startTime).isEqualTo(1_735_750_800_000L)+ }++ @Test+ fun `parse_noOffsetTimestamp_defaultsToSystemTimezoneWhenTimezoneMissing`() {+ val originalTimeZone = TimeZone.getDefault()+ try {+ TimeZone.setDefault(TimeZone.getTimeZone("Europe/Berlin"))+ val xml = """+ <?xml version="1.0"?>+ <tv>+ <programme start="20250101120000" stop="20250101130000" channel="ch1">+ <title>Timezone Test</title>+ </programme>+ </tv>+ """.trimIndent()++ val programs = parser.parse(xml.byteInputStream())++ assertThat(programs).hasSize(1)+ assertThat(programs.single().startTime).isEqualTo(1_735_729_200_000L)+ } finally {+ TimeZone.setDefault(originalTimeZone)+ }+ }++ @Test+ fun `parse_noOffsetTimestamp_defaultsToSystemTimezoneWhenTimezoneInvalid`() {+ val originalTimeZone = TimeZone.getDefault()+ try {+ TimeZone.setDefault(TimeZone.getTimeZone("Europe/Berlin"))+ val xml = """+ <?xml version="1.0"?>+ <tv>+ <programme start="20250101120000" stop="20250101130000" channel="ch1">+ <title>Timezone Test</title>+ </programme>+ </tv>+ """.trimIndent()++ val programs = parser.parse(xml.byteInputStream(), timezoneId = "Mars/Olympus")++ assertThat(programs).hasSize(1)+ assertThat(programs.single().startTime).isEqualTo(1_735_729_200_000L)+ } finally {+ TimeZone.setDefault(originalTimeZone)+ }+ }+@Testfun `parse_emptyStream_returnsEmpty`() {val xml = """<?xml version="1.0"?><tv></tv>"""@@ -369,9 +435,68 @@ class XmltvParserTest {}@Test- fun `maybeDecompressGzip_nonGzUrl_returnsOriginal`() {+ fun `parseStreamingWithChannels_skipsMalformedProgrammes`() = runTest {+ val xml = """+ <?xml version="1.0" encoding="UTF-8"?>+ <tv>+ <channel id="ch1">+ <display-name>BBC One</display-name>+ </channel>+ <programme start="20250101120000 +0000" stop="20250101130000 +0000" channel="ch1">+ <title>Valid News</title>+ </programme>+ <programme start="20250101130000 +0000" channel="ch1">+ <title>Missing Stop</title>+ </programme>+ <programme start="invalid" stop="20250101150000 +0000" channel="ch1">+ <title>Invalid Start</title>+ </programme>+ <programme start="20250101160000 +0000" stop="20250101160000 +0000" channel="ch1">+ <title>Zero Length</title>+ </programme>+ </tv>+ """.trimIndent()++ val programmes = mutableListOf<XmltvProgramme>()+ parser.parseStreamingWithChannels(+ inputStream = xml.byteInputStream(),+ onChannel = { },+ onProgramme = { programmes.add(it) }+ )++ assertThat(programmes).hasSize(1)+ assertThat(programmes.single().title).isEqualTo("Valid News")+ }++ @Test+ fun `maybeDecompressGzip_nonGzUrl_returnsReadableStream`() {val original = "hello".byteInputStream()val result = parser.maybeDecompressGzip("http://example.com/epg.xml", original)- assertThat(result).isSameInstanceAs(original)+ assertThat(String(result.readBytes(), Charsets.UTF_8)).isEqualTo("hello")+ }++ @Test+ fun `maybeDecompressGzip_detectsGzipByMagicBytesWithoutGzSuffix`() {+ val xml = """+ <?xml version="1.0" encoding="UTF-8"?>+ <tv>+ <channel id="myepg.ch1">+ <display-name>MyEPG Channel</display-name>+ </channel>+ </tv>+ """.trimIndent()++ val result = parser.maybeDecompressGzip(+ "https://myepg.example/download?order=private&key=redacted",+ gzip(xml.toByteArray(Charsets.UTF_8)).inputStream()+ )++ assertThat(String(result.readBytes(), Charsets.UTF_8)).isEqualTo(xml)+ }++ private fun gzip(bytes: ByteArray): ByteArray {+ val output = ByteArrayOutputStream()+ GZIPOutputStream(output).use { it.write(bytes) }+ return output.toByteArray()}}diff --git a/data/src/test/java/com/streamvault/data/remote/xtream/XtreamProviderTest.kt b/data/src/test/java/com/streamvault/data/remote/xtream/XtreamProviderTest.ktindex cf9026ae..21efcc53 100644--- a/data/src/test/java/com/streamvault/data/remote/xtream/XtreamProviderTest.kt+++ b/data/src/test/java/com/streamvault/data/remote/xtream/XtreamProviderTest.kt@@ -408,6 +408,31 @@ class XtreamProviderTest {assertThat(channel.isAdult).isTrue()}+ @Test+ fun `getLiveStreams uses category_ids when live category_id is missing or zero`() = runBlocking {+ val provider = XtreamProvider(+ providerId = 42,+ api = FakeXtreamApiService(+ liveStreams = listOf(+ XtreamStream(+ name = "Channel",+ streamId = 77,+ categoryId = "0",+ categoryIds = listOf("28")+ )+ )+ ),+ serverUrl = "https://example.com",+ username = "user",+ password = "pass"+ )++ val channel = provider.getLiveStreams().getOrNull().orEmpty().single()++ assertThat(channel.categoryId).isEqualTo(28L)+ assertThat(channel.categoryName).isEqualTo("Category 28")+ }+@Testfun `getSeriesCategories honors explicit adult flag from xtream category payload`() = runBlocking {val provider = XtreamProvider(diff --git a/data/src/test/java/com/streamvault/data/remote/xtream/XtreamStreamUrlResolverTest.kt b/data/src/test/java/com/streamvault/data/remote/xtream/XtreamStreamUrlResolverTest.ktindex 8b6925cc..0e3e8b63 100644--- a/data/src/test/java/com/streamvault/data/remote/xtream/XtreamStreamUrlResolverTest.kt+++ b/data/src/test/java/com/streamvault/data/remote/xtream/XtreamStreamUrlResolverTest.kt@@ -361,6 +361,8 @@ class XtreamStreamUrlResolverTest {override suspend fun getById(id: Long): ProviderEntity? = provider?.takeIf { it.id == id }override suspend fun getByIds(ids: List<Long>): List<ProviderEntity> =listOfNotNull(provider).filter { it.id in ids }+ override suspend fun insertDirect(provider: ProviderEntity): Long = provider.id+ override suspend fun updateDirect(provider: ProviderEntity) = Unitoverride suspend fun insert(provider: ProviderEntity): Long = provider.idoverride suspend fun update(provider: ProviderEntity) = Unitoverride suspend fun delete(id: Long) = Unitdiff --git a/data/src/test/java/com/streamvault/data/repository/ChannelRepositoryImplTest.kt b/data/src/test/java/com/streamvault/data/repository/ChannelRepositoryImplTest.ktindex 7474f7fc..e4589736 100644--- a/data/src/test/java/com/streamvault/data/repository/ChannelRepositoryImplTest.kt+++ b/data/src/test/java/com/streamvault/data/repository/ChannelRepositoryImplTest.kt@@ -186,6 +186,20 @@ class ChannelRepositoryImplTest {whenever(channelDao.search(eq(7L), any(), any())).thenReturn(flow { throw SQLiteException("malformed MATCH expression") })+ whenever(channelDao.searchFallback(eq(7L), any(), any())).thenReturn(+ flowOf(+ listOf(+ ChannelBrowseEntity(+ id = 99L,+ streamId = 199L,+ name = "News One",+ streamUrl = "https://stream/news",+ number = 9,+ providerId = 7L+ )+ )+ )+ )whenever(preferencesRepository.liveChannelNumberingMode).thenReturn(flowOf(ChannelNumberingMode.PROVIDER))whenever(parentalControlManager.unlockedCategoriesForProvider(7L)).thenReturn(flowOf(emptySet()))whenever(favoriteDao.getAllByType(7L, ContentType.LIVE.name)).thenReturn(flowOf(emptyList()))@@ -194,7 +208,7 @@ class ChannelRepositoryImplTest {val result = repository.searchChannels(7L, "news").first()- assertThat(result).isEmpty()+ assertThat(result.map { it.name }).containsExactly("News One")}private fun createRepository() = ChannelRepositoryImpl(diff --git a/data/src/test/java/com/streamvault/data/repository/EpgRepositoryImplTest.kt b/data/src/test/java/com/streamvault/data/repository/EpgRepositoryImplTest.ktindex 5eba01a6..b881a3c1 100644--- a/data/src/test/java/com/streamvault/data/repository/EpgRepositoryImplTest.kt+++ b/data/src/test/java/com/streamvault/data/repository/EpgRepositoryImplTest.kt@@ -3,10 +3,13 @@ package com.streamvault.data.repositoryimport com.google.common.truth.Truth.assertThatimport com.streamvault.data.local.DatabaseTransactionRunnerimport com.streamvault.data.local.dao.ProgramDao+import com.streamvault.data.local.dao.ProviderDao+import com.streamvault.data.local.entity.ProviderEntityimport com.streamvault.data.local.entity.ProgramBrowseEntityimport com.streamvault.data.local.entity.ProgramEntityimport com.streamvault.data.parser.XmltvParserimport com.streamvault.domain.model.Program+import com.streamvault.domain.model.ProviderTypeimport kotlinx.coroutines.CompletableDeferredimport kotlinx.coroutines.ExperimentalCoroutinesApiimport kotlinx.coroutines.async@@ -46,6 +49,7 @@ import java.util.zip.GZIPOutputStreamclass EpgRepositoryImplTest {private val programDao: ProgramDao = mock()+ private val providerDao: ProviderDao = mock()private val xmltvParser: XmltvParser = mock()private val epgSourceRepository: EpgSourceRepository = mock()private val transactionRunner = object : DatabaseTransactionRunner {@@ -57,6 +61,9 @@ class EpgRepositoryImplTest {whenever(xmltvParser.maybeDecompressGzip(any(), any())).thenAnswer { invocation ->invocation.getArgument(1)}+ runBlocking {+ whenever(providerDao.getById(any())).thenReturn(null)+ }}@Test@@ -86,6 +93,7 @@ class EpgRepositoryImplTest {val repository = EpgRepositoryImpl(programDao = programDao,+ providerDao = providerDao,xmltvParser = xmltvParser,okHttpClient = okHttpClientReturningXml(),transactionRunner = transactionRunner,@@ -120,6 +128,7 @@ class EpgRepositoryImplTest {val repository = EpgRepositoryImpl(programDao = programDao,+ providerDao = providerDao,xmltvParser = xmltvParser,okHttpClient = okHttpClientReturningXml(),transactionRunner = transactionRunner,@@ -165,6 +174,7 @@ class EpgRepositoryImplTest {val repository = EpgRepositoryImpl(programDao = programDao,+ providerDao = providerDao,xmltvParser = xmltvParser,okHttpClient = okHttpClientReturningXml(),transactionRunner = transactionRunner,@@ -192,7 +202,7 @@ class EpgRepositoryImplTest {val activeParsers = AtomicInteger(0)val maxConcurrentParsers = AtomicInteger(0)- whenever(xmltvParser.parseStreaming(any(), any())).thenAnswer { invocation ->+ whenever(xmltvParser.parseStreaming(any(), anyOrNull(), any())).thenAnswer { invocation ->val activeCount = activeParsers.incrementAndGet()maxConcurrentParsers.updateAndGet { current -> maxOf(current, activeCount) }val callIndex = parserCallOrder.incrementAndGet()@@ -205,7 +215,7 @@ class EpgRepositoryImplTest {secondParserEntered.complete(Unit)}- val onProgram = invocation.getArgument<suspend (Program) -> Unit>(1)+ val onProgram = invocation.getArgument<suspend (Program) -> Unit>(2)runBlocking {onProgram(Program(@@ -226,6 +236,7 @@ class EpgRepositoryImplTest {val repository = EpgRepositoryImpl(programDao = programDao,+ providerDao = providerDao,xmltvParser = xmltvParser,okHttpClient = okHttpClientReturningXml(),transactionRunner = transactionRunner,@@ -256,6 +267,7 @@ class EpgRepositoryImplTest {fun `refreshEpg decompresses gzip xmltv responses`() = runTest {val repository = EpgRepositoryImpl(programDao = programDao,+ providerDao = providerDao,xmltvParser = XmltvParser(),okHttpClient = okHttpClientReturningBody(gzip(@@ -285,6 +297,7 @@ class EpgRepositoryImplTest {fun `refreshEpg does not double decompress when content encoding and gz suffix are both present`() = runTest {val repository = EpgRepositoryImpl(programDao = programDao,+ providerDao = providerDao,xmltvParser = XmltvParser(),okHttpClient = okHttpClientReturningBody(body = gzip(@@ -338,6 +351,7 @@ class EpgRepositoryImplTest {val repository = EpgRepositoryImpl(programDao = programDao,+ providerDao = providerDao,xmltvParser = xmltvParser,okHttpClient = okHttpClientReturningXml(),transactionRunner = transactionRunner,@@ -359,6 +373,76 @@ class EpgRepositoryImplTest {verify(programDao, times(2)).getNowPlaying(eq(7L), eq("bbc1.uk"), any())}+ @Test+ fun `getNowPlayingForChannels refreshes over time for long lived subscriptions`() = runTest {+ whenever(programDao.getNowPlayingForChannels(eq(7L), eq(listOf("bbc1.uk", "bbc2.uk")), any())).thenReturn(+ flowOf(+ listOf(+ ProgramBrowseEntity(+ id = 1L,+ providerId = 7L,+ channelId = "bbc1.uk",+ title = "Current One",+ startTime = 100L,+ endTime = 200L+ ),+ ProgramBrowseEntity(+ id = 2L,+ providerId = 7L,+ channelId = "bbc2.uk",+ title = "Current Two",+ startTime = 100L,+ endTime = 200L+ )+ )+ ),+ flowOf(+ listOf(+ ProgramBrowseEntity(+ id = 3L,+ providerId = 7L,+ channelId = "bbc1.uk",+ title = "Next One",+ startTime = 200L,+ endTime = 300L+ ),+ ProgramBrowseEntity(+ id = 4L,+ providerId = 7L,+ channelId = "bbc2.uk",+ title = "Next Two",+ startTime = 200L,+ endTime = 300L+ )+ )+ )+ )++ val repository = EpgRepositoryImpl(+ programDao = programDao,+ providerDao = providerDao,+ xmltvParser = xmltvParser,+ okHttpClient = okHttpClientReturningXml(),+ transactionRunner = transactionRunner,+ epgSourceRepository = epgSourceRepository,+ externalScope = backgroundScope+ )++ val emissions = mutableListOf<Map<String, Program?>>()+ val collection = async {+ repository.getNowPlayingForChannels(7L, listOf("bbc1.uk", "bbc2.uk"))+ .take(2)+ .toList(emissions)+ }++ advanceTimeBy(60_000L)+ collection.await()++ assertThat(emissions.map { it.getValue("bbc1.uk")?.title }).containsExactly("Current One", "Next One").inOrder()+ assertThat(emissions.map { it.getValue("bbc2.uk")?.title }).containsExactly("Current Two", "Next Two").inOrder()+ verify(programDao, times(2)).getNowPlayingForChannels(eq(7L), eq(listOf("bbc1.uk", "bbc2.uk")), any())+ }+@Testfun `getProgramsForChannelsSnapshot chunks large requests without reactive combine`() = runTest {val firstChunk = (1..500).map { index ->@@ -388,6 +472,7 @@ class EpgRepositoryImplTest {val repository = EpgRepositoryImpl(programDao = programDao,+ providerDao = providerDao,xmltvParser = xmltvParser,okHttpClient = okHttpClientReturningXml(),transactionRunner = transactionRunner,@@ -415,7 +500,7 @@ class EpgRepositoryImplTest {override fun read(): Int = throw IOException("EPG response too large (>200 MB)")})- whenever(xmltvParser.parseStreaming(any(), any())).thenAnswer { invocation ->+ whenever(xmltvParser.parseStreaming(any(), anyOrNull(), any())).thenAnswer { invocation ->val input = invocation.getArgument<java.io.InputStream>(0)input.read()Unit@@ -423,6 +508,7 @@ class EpgRepositoryImplTest {val repository = EpgRepositoryImpl(programDao = programDao,+ providerDao = providerDao,xmltvParser = xmltvParser,okHttpClient = okHttpClientReturningXml(),transactionRunner = transactionRunner,@@ -456,8 +542,8 @@ class EpgRepositoryImplTest {insertTransactionDepths += transactionDepthUnit}.whenever(programDao).insertAll(any())- whenever(xmltvParser.parseStreaming(any(), any())).thenAnswer { invocation ->- val onProgram = invocation.getArgument<suspend (Program) -> Unit>(1)+ whenever(xmltvParser.parseStreaming(any(), anyOrNull(), any())).thenAnswer { invocation ->+ val onProgram = invocation.getArgument<suspend (Program) -> Unit>(2)runBlocking {repeat(600) { index ->parserCallbackTransactionDepths += transactionDepth@@ -478,6 +564,7 @@ class EpgRepositoryImplTest {val repository = EpgRepositoryImpl(programDao = programDao,+ providerDao = providerDao,xmltvParser = xmltvParser,okHttpClient = okHttpClientReturningXml(),transactionRunner = trackingTransactionRunner,@@ -494,6 +581,49 @@ class EpgRepositoryImplTest {assertThat(insertTransactionDepths.all { it > 0 }).isTrue()}+ @Test+ fun `refreshEpg passes provider timezone to parser for no offset timestamps`() = runTest {+ whenever(providerDao.getById(7L)).thenReturn(+ ProviderEntity(+ id = 7L,+ name = "Provider",+ type = ProviderType.M3U,+ serverUrl = "https://provider.example.com",+ stalkerDeviceTimezone = "America/New_York"+ )+ )+ whenever(xmltvParser.parseStreaming(any(), anyOrNull(), any())).thenAnswer { invocation ->+ val onProgram = invocation.getArgument<suspend (Program) -> Unit>(2)+ runBlocking {+ onProgram(+ Program(+ providerId = 7L,+ channelId = "channel-1",+ title = "News",+ description = "",+ startTime = 1L,+ endTime = 2L,+ lang = "en"+ )+ )+ }+ }++ val repository = EpgRepositoryImpl(+ programDao = programDao,+ providerDao = providerDao,+ xmltvParser = xmltvParser,+ okHttpClient = okHttpClientReturningXml(),+ transactionRunner = transactionRunner,+ epgSourceRepository = epgSourceRepository+ )++ val result = repository.refreshEpg(7L, "https://example.com/epg.xml")++ assertThat(result.isSuccess).isTrue()+ verify(xmltvParser).parseStreaming(any(), eq("America/New_York"), any())+ }+private fun okHttpClientReturningXml(): OkHttpClient =okHttpClientReturningBody("<tv></tv>".toByteArray(Charsets.UTF_8))diff --git a/data/src/test/java/com/streamvault/data/repository/EpgSourceRepositoryImplTest.kt b/data/src/test/java/com/streamvault/data/repository/EpgSourceRepositoryImplTest.ktindex daeda3b4..c234fa7f 100644--- a/data/src/test/java/com/streamvault/data/repository/EpgSourceRepositoryImplTest.kt+++ b/data/src/test/java/com/streamvault/data/repository/EpgSourceRepositoryImplTest.kt@@ -10,29 +10,50 @@ import com.streamvault.data.local.dao.ChannelEpgMappingDaoimport com.streamvault.data.local.dao.EpgChannelDaoimport com.streamvault.data.local.dao.EpgProgrammeDaoimport com.streamvault.data.local.dao.EpgSourceDao+import com.streamvault.data.local.dao.ProviderDaoimport com.streamvault.data.local.dao.ProviderEpgSourceDaoimport com.streamvault.data.local.entity.ChannelEpgMappingEntityimport com.streamvault.data.local.entity.EpgChannelEntity+import com.streamvault.data.local.entity.EpgProgrammeEntityimport com.streamvault.data.local.entity.EpgSourceEntity+import com.streamvault.data.local.entity.ProviderEntityimport com.streamvault.data.local.entity.ProviderEpgSourceEntityimport com.streamvault.data.parser.XmltvParser+import com.streamvault.data.preferences.PreferencesRepository+import com.streamvault.domain.model.ContentTypeimport com.streamvault.domain.model.EpgMatchTypeimport com.streamvault.domain.model.EpgSourceTypeimport com.streamvault.domain.model.Result+import com.streamvault.domain.model.ProviderTypeimport java.io.ByteArrayInputStream+import java.io.ByteArrayOutputStreamimport java.io.IOException+import kotlinx.coroutines.runBlocking+import kotlinx.coroutines.flow.flowOfimport kotlinx.coroutines.test.runTest+import okhttp3.MediaType.Companion.toMediaType+import okhttp3.Callimport okhttp3.OkHttpClient+import okhttp3.Protocol+import okhttp3.Request+import okhttp3.Response+import okhttp3.ResponseBody.Companion.toResponseBodyimport org.junit.Beforeimport org.junit.Testimport org.mockito.kotlin.any+import org.mockito.kotlin.anyOrNull+import org.mockito.kotlin.argThatimport org.mockito.kotlin.doAnswerimport org.mockito.kotlin.argumentCaptorimport org.mockito.kotlin.eq+import org.mockito.kotlin.inOrder+import org.mockito.kotlin.isNullimport org.mockito.kotlin.mock+import org.mockito.kotlin.timesimport org.mockito.kotlin.verifyimport org.mockito.kotlin.verifyNoMoreInteractionsimport org.mockito.kotlin.whenever+import java.util.zip.GZIPOutputStreamclass EpgSourceRepositoryImplTest {@@ -40,12 +61,15 @@ class EpgSourceRepositoryImplTest {private val contentResolver: ContentResolver = mock()private val epgSourceDao: EpgSourceDao = mock()private val providerEpgSourceDao: ProviderEpgSourceDao = mock()+ private val providerDao: ProviderDao = mock()private val channelEpgMappingDao: ChannelEpgMappingDao = mock()private val epgChannelDao: EpgChannelDao = mock()private val epgProgrammeDao: EpgProgrammeDao = mock()private val xmltvParser: XmltvParser = mock()private val okHttpClient: OkHttpClient = mock()+ private val epgHttpClientBuilder: OkHttpClient.Builder = mock()private val resolutionEngine: EpgResolutionEngine = mock()+ private val preferencesRepository: PreferencesRepository = mock()private val transactionRunner = object : DatabaseTransactionRunner {override suspend fun <T> inTransaction(block: suspend () -> T): T = block()}@@ -55,16 +79,25 @@ class EpgSourceRepositoryImplTest {@Beforefun setup() {whenever(context.contentResolver).thenReturn(contentResolver)+ whenever(preferencesRepository.getHiddenCategoryIds(any(), eq(ContentType.LIVE))).thenReturn(flowOf(emptySet()))+ whenever(okHttpClient.newBuilder()).thenReturn(epgHttpClientBuilder)+ whenever(epgHttpClientBuilder.readTimeout(any<Long>(), any())).thenReturn(epgHttpClientBuilder)+ whenever(epgHttpClientBuilder.build()).thenReturn(okHttpClient)+ runBlocking {+ whenever(providerDao.getById(any())).thenReturn(null)+ }repository = EpgSourceRepositoryImpl(context = context,epgSourceDao = epgSourceDao,providerEpgSourceDao = providerEpgSourceDao,+ providerDao = providerDao,channelEpgMappingDao = channelEpgMappingDao,epgChannelDao = epgChannelDao,epgProgrammeDao = epgProgrammeDao,xmltvParser = xmltvParser,okHttpClient = okHttpClient,resolutionEngine = resolutionEngine,+ preferencesRepository = preferencesRepository,transactionRunner = transactionRunner)}@@ -79,32 +112,36 @@ class EpgSourceRepositoryImplTest {assertThat(result is Result.Success).isTrue()verify(providerEpgSourceDao).insert(any())- verify(resolutionEngine).resolveForProvider(7L)+ verify(resolutionEngine).resolveForProvider(7L, emptySet())}@Testfun `setSourceEnabled_resolvesEachAffectedProviderOnce`() = runTest {whenever(providerEpgSourceDao.getProviderIdsForSourceSync(10L)).thenReturn(listOf(7L, 8L, 7L))+ whenever(preferencesRepository.getHiddenCategoryIds(7L, ContentType.LIVE)).thenReturn(flowOf(setOf(101L)))+ whenever(preferencesRepository.getHiddenCategoryIds(8L, ContentType.LIVE)).thenReturn(flowOf(setOf(202L)))repository.setSourceEnabled(10L, enabled = false)verify(epgSourceDao).setEnabled(eq(10L), eq(false), any())- verify(resolutionEngine).resolveForProvider(7L)- verify(resolutionEngine).resolveForProvider(8L)+ verify(resolutionEngine).resolveForProvider(7L, setOf(101L))+ verify(resolutionEngine).resolveForProvider(8L, setOf(202L))verifyNoMoreInteractions(resolutionEngine)}@Testfun `deleteSource_rebuildsAffectedProviderMappings`() = runTest {whenever(providerEpgSourceDao.getProviderIdsForSourceSync(10L)).thenReturn(listOf(4L, 5L))+ whenever(preferencesRepository.getHiddenCategoryIds(4L, ContentType.LIVE)).thenReturn(flowOf(setOf(401L)))+ whenever(preferencesRepository.getHiddenCategoryIds(5L, ContentType.LIVE)).thenReturn(flowOf(setOf(501L)))repository.deleteSource(10L)verify(epgProgrammeDao).deleteBySource(10L)verify(epgChannelDao).deleteBySource(10L)verify(epgSourceDao).delete(10L)- verify(resolutionEngine).resolveForProvider(4L)- verify(resolutionEngine).resolveForProvider(5L)+ verify(resolutionEngine).resolveForProvider(4L, setOf(401L))+ verify(resolutionEngine).resolveForProvider(5L, setOf(501L))}@Test@@ -160,7 +197,7 @@ class EpgSourceRepositoryImplTest {val result = repository.clearManualOverride(providerId = 7L, channelId = 101L)assertThat(result is Result.Success).isTrue()- verify(resolutionEngine).resolveForProvider(7L)+ verify(resolutionEngine).resolveForProvider(7L, emptySet())}@Test@@ -214,9 +251,10 @@ class EpgSourceRepositoryImplTest {whenever(epgSourceDao.getById(10L)).thenReturn(source)whenever(contentResolver.openInputStream(Uri.parse(source.url))).thenReturn(ByteArrayInputStream("<tv/>".toByteArray()))whenever(xmltvParser.maybeDecompressGzip(eq(source.url), any())).thenAnswer { it.arguments[1] }+ whenever(providerEpgSourceDao.getProviderIdsForSourceSync(10L)).thenReturn(emptyList())doAnswer { throw IOException("EPG response too large (>200 MB)") }.whenever(xmltvParser)- .parseStreamingWithChannels(any(), any(), any())+ .parseStreamingWithChannels(any(), anyOrNull(), any(), any())val result = repository.refreshSource(10L)@@ -225,6 +263,216 @@ class EpgSourceRepositoryImplTest {verify(epgSourceDao).updateRefreshError(eq(10L), eq("EPG response exceeded 200 MB limit"), any())}+ @Test+ fun `refreshSource imports gzip xmltv when download url has no gz suffix`() = runTest {+ val source = EpgSourceEntity(+ id = 10L,+ name = "MyEPG",+ url = "https://myepg.example/download?order=private&key=redacted",+ lastRefreshAt = 0L+ )+ val response = Response.Builder()+ .request(Request.Builder().url(source.url).build())+ .protocol(Protocol.HTTP_1_1)+ .code(200)+ .message("OK")+ .body(+ gzip(+ """+ <tv>+ <channel id="myepg.ch1">+ <display-name>MyEPG Channel</display-name>+ </channel>+ <programme channel="myepg.ch1" start="20260101000000 +0000" stop="20260101010000 +0000">+ <title>MyEPG News</title>+ </programme>+ </tv>+ """.trimIndent().toByteArray(Charsets.UTF_8)+ ).toResponseBody("application/octet-stream".toMediaType())+ )+ .build()+ val call: Call = mock()+ val repositoryWithRealParser = EpgSourceRepositoryImpl(+ context = context,+ epgSourceDao = epgSourceDao,+ providerEpgSourceDao = providerEpgSourceDao,+ providerDao = providerDao,+ channelEpgMappingDao = channelEpgMappingDao,+ epgChannelDao = epgChannelDao,+ epgProgrammeDao = epgProgrammeDao,+ xmltvParser = XmltvParser(),+ okHttpClient = okHttpClient,+ resolutionEngine = resolutionEngine,+ preferencesRepository = preferencesRepository,+ transactionRunner = transactionRunner+ )++ whenever(epgSourceDao.getById(10L)).thenReturn(source)+ whenever(okHttpClient.newCall(any())).thenReturn(call)+ whenever(call.execute()).thenReturn(response)+ whenever(providerEpgSourceDao.getProviderIdsForSourceSync(10L)).thenReturn(emptyList())++ val result = repositoryWithRealParser.refreshSource(10L)++ assertThat(result is Result.Success).isTrue()+ val channelCaptor = argumentCaptor<List<EpgChannelEntity>>()+ val programmeCaptor = argumentCaptor<List<EpgProgrammeEntity>>()+ verify(epgChannelDao).insertAll(channelCaptor.capture())+ verify(epgProgrammeDao).insertAll(programmeCaptor.capture())+ assertThat(channelCaptor.firstValue.single().xmltvChannelId).isEqualTo("myepg.ch1")+ assertThat(channelCaptor.firstValue.single().displayName).isEqualTo("MyEPG Channel")+ assertThat(channelCaptor.firstValue.single().epgSourceId).isEqualTo(-10L)+ assertThat(programmeCaptor.firstValue.single().title).isEqualTo("MyEPG News")+ assertThat(programmeCaptor.firstValue.single().epgSourceId).isEqualTo(-10L)+ verify(epgSourceDao).insert(argThat {+ id == -10L &&+ url == "streamvault://epg-source-staging/10" &&+ !enabled+ })+ inOrder(epgProgrammeDao, epgChannelDao, epgSourceDao).apply {+ verify(epgProgrammeDao).deleteBySource(-10L)+ verify(epgChannelDao).deleteBySource(-10L)+ verify(epgSourceDao).delete(-10L)+ verify(epgSourceDao).insert(argThat {+ id == -10L &&+ url == "streamvault://epg-source-staging/10" &&+ !enabled+ })+ verify(epgChannelDao).insertAll(any())+ verify(epgProgrammeDao).insertAll(any())+ }+ verify(epgChannelDao).moveToSource(-10L, 10L)+ verify(epgProgrammeDao).moveToSource(-10L, 10L)+ verify(epgSourceDao, times(2)).delete(-10L)+ verify(epgSourceDao).updateRefreshSuccess(eq(10L), any())+ }++ @Test+ fun `refreshSource rebuilds affected providers when remote source returns 304`() = runTest {+ val source = EpgSourceEntity(+ id = 10L,+ name = "Primary",+ url = "https://example.com/epg.xml",+ lastRefreshAt = 0L,+ etag = "etag-1"+ )+ val request = Request.Builder().url(source.url).build()+ val response = Response.Builder()+ .request(request)+ .protocol(Protocol.HTTP_1_1)+ .code(304)+ .message("Not Modified")+ .body("".toResponseBody())+ .build()+ val call: Call = mock()++ whenever(epgSourceDao.getById(10L)).thenReturn(source)+ whenever(okHttpClient.newCall(any())).thenReturn(call)+ whenever(call.execute()).thenReturn(response)+ whenever(providerEpgSourceDao.getProviderIdsForSourceSync(10L)).thenReturn(listOf(7L, 8L))++ val result = repository.refreshSource(10L)++ assertThat(result is Result.Success).isTrue()+ verify(epgSourceDao).updateRefreshSuccess(eq(10L), any())+ verify(resolutionEngine).resolveForProvider(7L, emptySet())+ verify(resolutionEngine).resolveForProvider(8L, emptySet())+ }++ @Test+ fun `refreshSource passes shared provider timezone to parser when assignments agree`() = runTest {+ val source = EpgSourceEntity(+ id = 10L,+ name = "Primary",+ url = "https://example.com/epg.xml"+ )+ val request = Request.Builder().url(source.url).build()+ val response = Response.Builder()+ .request(request)+ .protocol(Protocol.HTTP_1_1)+ .code(200)+ .message("OK")+ .body("<tv></tv>".toResponseBody())+ .build()+ val call: Call = mock()++ whenever(epgSourceDao.getById(10L)).thenReturn(source)+ whenever(okHttpClient.newCall(any())).thenReturn(call)+ whenever(call.execute()).thenReturn(response)+ whenever(xmltvParser.maybeDecompressGzip(eq(source.url), any())).thenAnswer { it.arguments[1] }+ whenever(providerEpgSourceDao.getProviderIdsForSourceSync(10L)).thenReturn(listOf(7L, 8L))+ whenever(providerDao.getById(7L)).thenReturn(+ ProviderEntity(+ id = 7L,+ name = "Provider 7",+ type = ProviderType.M3U,+ serverUrl = "https://provider7.example.com",+ stalkerDeviceTimezone = "America/New_York"+ )+ )+ whenever(providerDao.getById(8L)).thenReturn(+ ProviderEntity(+ id = 8L,+ name = "Provider 8",+ type = ProviderType.M3U,+ serverUrl = "https://provider8.example.com",+ stalkerDeviceTimezone = "America/New_York"+ )+ )++ val result = repository.refreshSource(10L)++ assertThat(result is Result.Success).isTrue()+ verify(xmltvParser).parseStreamingWithChannels(any(), eq("America/New_York"), any(), any())+ }++ @Test+ fun `refreshSource falls back to system timezone when assigned providers disagree`() = runTest {+ val source = EpgSourceEntity(+ id = 10L,+ name = "Primary",+ url = "https://example.com/epg.xml"+ )+ val request = Request.Builder().url(source.url).build()+ val response = Response.Builder()+ .request(request)+ .protocol(Protocol.HTTP_1_1)+ .code(200)+ .message("OK")+ .body("<tv></tv>".toResponseBody())+ .build()+ val call: Call = mock()++ whenever(epgSourceDao.getById(10L)).thenReturn(source)+ whenever(okHttpClient.newCall(any())).thenReturn(call)+ whenever(call.execute()).thenReturn(response)+ whenever(xmltvParser.maybeDecompressGzip(eq(source.url), any())).thenAnswer { it.arguments[1] }+ whenever(providerEpgSourceDao.getProviderIdsForSourceSync(10L)).thenReturn(listOf(7L, 8L))+ whenever(providerDao.getById(7L)).thenReturn(+ ProviderEntity(+ id = 7L,+ name = "Provider 7",+ type = ProviderType.M3U,+ serverUrl = "https://provider7.example.com",+ stalkerDeviceTimezone = "America/New_York"+ )+ )+ whenever(providerDao.getById(8L)).thenReturn(+ ProviderEntity(+ id = 8L,+ name = "Provider 8",+ type = ProviderType.M3U,+ serverUrl = "https://provider8.example.com",+ stalkerDeviceTimezone = "Europe/London"+ )+ )++ val result = repository.refreshSource(10L)++ assertThat(result is Result.Success).isTrue()+ verify(xmltvParser).parseStreamingWithChannels(any(), isNull(), any(), any())+ }+private class CloseTrackingInputStream : ByteArrayInputStream(byteArrayOf()) {var closed: Boolean = falseprivate set@@ -234,4 +482,10 @@ class EpgSourceRepositoryImplTest {super.close()}}++ private fun gzip(bytes: ByteArray): ByteArray {+ val output = ByteArrayOutputStream()+ GZIPOutputStream(output).use { it.write(bytes) }+ return output.toByteArray()+ }}diff --git a/data/src/test/java/com/streamvault/data/repository/FavoriteRepositoryImplTest.kt b/data/src/test/java/com/streamvault/data/repository/FavoriteRepositoryImplTest.ktindex 6719c548..c8f61079 100644--- a/data/src/test/java/com/streamvault/data/repository/FavoriteRepositoryImplTest.kt+++ b/data/src/test/java/com/streamvault/data/repository/FavoriteRepositoryImplTest.kt@@ -4,11 +4,15 @@ import com.google.common.truth.Truth.assertThatimport com.streamvault.data.local.DatabaseTransactionRunnerimport com.streamvault.data.local.dao.FavoriteDaoimport com.streamvault.data.local.dao.VirtualGroupDao+import com.streamvault.data.local.entity.CategoryCountimport com.streamvault.data.local.entity.FavoriteEntity+import com.streamvault.data.local.entity.VirtualGroupEntityimport com.streamvault.domain.model.Favoriteimport com.streamvault.domain.model.ContentTypeimport kotlinx.coroutines.ExperimentalCoroutinesApiimport kotlinx.coroutines.flow.emptyFlow+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.flow.flowOfimport kotlinx.coroutines.test.runTestimport org.junit.Testimport org.mockito.kotlin.any@@ -39,6 +43,7 @@ class FavoriteRepositoryImplTest {@Testfun `addFavorite runs max-position lookup and insert in one transaction`() = runTest {var inTransaction = false+ var getInsideTransaction = falsevar getMaxInsideTransaction = falsevar insertInsideTransaction = false@@ -54,6 +59,10 @@ class FavoriteRepositoryImplTest {}}+ whenever(favoriteDao.get(7L, 42L, ContentType.LIVE.name, null)).thenAnswer {+ getInsideTransaction = inTransaction+ null+ }whenever(favoriteDao.getMaxPosition(7L, null)).thenAnswer {getMaxInsideTransaction = inTransaction4@@ -77,16 +86,192 @@ class FavoriteRepositoryImplTest {)assertThat(result.isSuccess).isTrue()+ assertThat(getInsideTransaction).isTrue()assertThat(getMaxInsideTransaction).isTrue()assertThat(insertInsideTransaction).isTrue()val favoriteCaptor = argumentCaptor<FavoriteEntity>()+ verify(favoriteDao).get(7L, 42L, ContentType.LIVE.name, null)verify(favoriteDao).insert(favoriteCaptor.capture())verify(favoriteDao).getMaxPosition(7L, null)assertThat(favoriteCaptor.firstValue.providerId).isEqualTo(7L)assertThat(favoriteCaptor.firstValue.position).isEqualTo(1028)}+ @Test+ fun `addFavorite is a no-op when global favorite already exists`() = runTest {+ whenever(favoriteDao.get(7L, 42L, ContentType.LIVE.name, null)).thenReturn(+ FavoriteEntity(+ id = 9L,+ providerId = 7L,+ contentId = 42L,+ contentType = ContentType.LIVE,+ position = 512,+ groupId = null,+ addedAt = 1_000L+ )+ )++ val result = repository.addFavorite(+ providerId = 7L,+ contentId = 42L,+ contentType = ContentType.LIVE,+ groupId = null+ )++ assertThat(result.isSuccess).isTrue()+ verify(favoriteDao).get(7L, 42L, ContentType.LIVE.name, null)+ verify(favoriteDao, never()).getMaxPosition(any(), any())+ verify(favoriteDao, never()).insert(any())+ }++ @Test+ fun `addFavorite is a no-op when group favorite already exists`() = runTest {+ whenever(virtualGroupDao.getById(11L)).thenReturn(+ VirtualGroupEntity(+ id = 11L,+ providerId = 7L,+ name = "Live Group",+ contentType = ContentType.LIVE+ )+ )+ whenever(favoriteDao.get(7L, 42L, ContentType.LIVE.name, 11L)).thenReturn(+ FavoriteEntity(+ id = 12L,+ providerId = 7L,+ contentId = 42L,+ contentType = ContentType.LIVE,+ position = 256,+ groupId = 11L,+ addedAt = 2_000L+ )+ )++ val result = repository.addFavorite(+ providerId = 7L,+ contentId = 42L,+ contentType = ContentType.LIVE,+ groupId = 11L+ )++ assertThat(result.isSuccess).isTrue()+ verify(favoriteDao).get(7L, 42L, ContentType.LIVE.name, 11L)+ verify(favoriteDao, never()).getMaxPosition(any(), any())+ verify(favoriteDao, never()).insert(any())+ }++ @Test+ fun `getGroupFavoriteCounts for providers aggregates grouped counts across provider set`() = runTest {+ whenever(favoriteDao.getGroupFavoriteCountsForProviders(listOf(7L, 8L), ContentType.LIVE.name)).thenReturn(+ flowOf(+ listOf(+ CategoryCount(categoryId = 11L, item_count = 2),+ CategoryCount(categoryId = 12L, item_count = 1)+ )+ )+ )++ val counts = repository.getGroupFavoriteCounts(listOf(7L, 8L), ContentType.LIVE).first()++ assertThat(counts).containsExactly(11L, 2, 12L, 1)+ }++ @Test+ fun `getGroupFavoriteCounts for providers skips dao when provider set is empty`() = runTest {+ val counts = repository.getGroupFavoriteCounts(emptyList(), ContentType.LIVE).first()++ assertThat(counts).isEmpty()+ verify(favoriteDao, never()).getGroupFavoriteCountsForProviders(any(), any())+ }++ @Test+ fun `createGroup assigns sparse position after existing groups`() = runTest {+ whenever(virtualGroupDao.getMaxPosition(7L, ContentType.LIVE.name)).thenReturn(2_048)+ whenever(virtualGroupDao.insert(any())).thenReturn(15L)++ val result = repository.createGroup(+ providerId = 7L,+ name = "Sports",+ iconEmoji = "",+ contentType = ContentType.LIVE+ )++ assertThat(result.isSuccess).isTrue()+ val groupCaptor = argumentCaptor<VirtualGroupEntity>()+ verify(virtualGroupDao).getMaxPosition(7L, ContentType.LIVE.name)+ verify(virtualGroupDao).insert(groupCaptor.capture())+ assertThat(groupCaptor.firstValue.position).isEqualTo(3_072)+ assertThat(result.getOrNull()?.position).isEqualTo(3_072)+ }++ @Test+ fun `createGroup starts first group at zero position`() = runTest {+ whenever(virtualGroupDao.getMaxPosition(7L, ContentType.MOVIE.name)).thenReturn(null)+ whenever(virtualGroupDao.insert(any())).thenReturn(16L)++ val result = repository.createGroup(+ providerId = 7L,+ name = "Movies",+ iconEmoji = null,+ contentType = ContentType.MOVIE+ )++ assertThat(result.isSuccess).isTrue()+ val groupCaptor = argumentCaptor<VirtualGroupEntity>()+ verify(virtualGroupDao).getMaxPosition(7L, ContentType.MOVIE.name)+ verify(virtualGroupDao).insert(groupCaptor.capture())+ assertThat(groupCaptor.firstValue.position).isEqualTo(0)+ assertThat(result.getOrNull()?.position).isEqualTo(0)+ }++ @Test+ fun `addFavorite rejects groups from another provider`() = runTest {+ whenever(virtualGroupDao.getById(11L)).thenReturn(+ VirtualGroupEntity(+ id = 11L,+ providerId = 99L,+ name = "Other Provider",+ contentType = ContentType.LIVE+ )+ )++ val result = repository.addFavorite(+ providerId = 7L,+ contentId = 42L,+ contentType = ContentType.LIVE,+ groupId = 11L+ )++ assertThat(result.isSuccess).isFalse()+ assertThat(result.errorMessageOrNull()).contains("belongs to provider")+ verify(favoriteDao, never()).getMaxPosition(any(), any())+ verify(favoriteDao, never()).insert(any())+ }++ @Test+ fun `addFavorite rejects groups with another content type`() = runTest {+ whenever(virtualGroupDao.getById(11L)).thenReturn(+ VirtualGroupEntity(+ id = 11L,+ providerId = 7L,+ name = "Movies",+ contentType = ContentType.MOVIE+ )+ )++ val result = repository.addFavorite(+ providerId = 7L,+ contentId = 42L,+ contentType = ContentType.LIVE,+ groupId = 11L+ )++ assertThat(result.isSuccess).isFalse()+ assertThat(result.errorMessageOrNull()).contains("accepts MOVIE")+ verify(favoriteDao, never()).getMaxPosition(any(), any())+ verify(favoriteDao, never()).insert(any())+ }+@Testfun `reorderFavorites updates only affected favorites when sparse gap is available`() = runTest {val favorites = listOf(@@ -143,11 +328,259 @@ class FavoriteRepositoryImplTest {verify(favoriteDao, never()).updateAll(any())}- private fun favorite(id: Long, contentId: Long, position: Int) = Favorite(+ @Test+ fun `reorderFavorites rejects mixed provider partitions`() = runTest {+ val result = repository.reorderFavorites(+ listOf(+ favorite(id = 1, contentId = 101, position = 0, providerId = 7L),+ favorite(id = 2, contentId = 102, position = 1_024, providerId = 8L)+ )+ )++ assertThat(result.isSuccess).isFalse()+ assertThat(result.errorMessageOrNull()).contains("one provider and group partition")+ verify(favoriteDao, never()).updateAll(any())+ }++ @Test+ fun `reorderFavorites rejects mixed group partitions`() = runTest {+ val result = repository.reorderFavorites(+ listOf(+ favorite(id = 1, contentId = 101, position = 0, groupId = null),+ favorite(id = 2, contentId = 102, position = 1_024, groupId = 11L)+ )+ )++ assertThat(result.isSuccess).isFalse()+ assertThat(result.errorMessageOrNull()).contains("one provider and group partition")+ verify(favoriteDao, never()).updateAll(any())+ }++ @Test+ fun `moveFavoriteToGroup updates group in one transaction when target is empty`() = runTest {+ whenever(virtualGroupDao.getById(11L)).thenReturn(+ VirtualGroupEntity(+ id = 11L,+ providerId = 7L,+ name = "Live Group",+ contentType = ContentType.LIVE+ )+ )+ whenever(favoriteDao.get(7L, 42L, ContentType.LIVE.name, null)).thenReturn(+ FavoriteEntity(+ id = 9L,+ providerId = 7L,+ contentId = 42L,+ contentType = ContentType.LIVE,+ position = 512,+ groupId = null,+ addedAt = 1_000L+ )+ )+ whenever(favoriteDao.get(7L, 42L, ContentType.LIVE.name, 11L)).thenReturn(null)++ val result = repository.moveFavoriteToGroup(+ providerId = 7L,+ contentId = 42L,+ contentType = ContentType.LIVE,+ fromGroupId = null,+ targetGroupId = 11L+ )++ assertThat(result.isSuccess).isTrue()+ verify(favoriteDao).updateGroup(9L, 11L)+ verify(favoriteDao, never()).insert(any())+ verify(favoriteDao, never()).delete(7L, 42L, ContentType.LIVE.name, null)+ }++ @Test+ fun `moveFavoriteToGroup removes source duplicate when target already contains item`() = runTest {+ whenever(virtualGroupDao.getById(11L)).thenReturn(+ VirtualGroupEntity(+ id = 11L,+ providerId = 7L,+ name = "Live Group",+ contentType = ContentType.LIVE+ )+ )+ whenever(favoriteDao.get(7L, 42L, ContentType.LIVE.name, null)).thenReturn(+ FavoriteEntity(+ id = 9L,+ providerId = 7L,+ contentId = 42L,+ contentType = ContentType.LIVE,+ position = 512,+ groupId = null,+ addedAt = 1_000L+ )+ )+ whenever(favoriteDao.get(7L, 42L, ContentType.LIVE.name, 11L)).thenReturn(+ FavoriteEntity(+ id = 10L,+ providerId = 7L,+ contentId = 42L,+ contentType = ContentType.LIVE,+ position = 768,+ groupId = 11L,+ addedAt = 2_000L+ )+ )++ val result = repository.moveFavoriteToGroup(+ providerId = 7L,+ contentId = 42L,+ contentType = ContentType.LIVE,+ fromGroupId = null,+ targetGroupId = 11L+ )++ assertThat(result.isSuccess).isTrue()+ verify(favoriteDao).delete(7L, 42L, ContentType.LIVE.name, null)+ verify(favoriteDao, never()).updateGroup(any(), any())+ }++ @Test+ fun `mergeGroupInto moves unique favorites removes duplicates and deletes source group`() = runTest {+ whenever(virtualGroupDao.getById(11L)).thenReturn(+ VirtualGroupEntity(+ id = 11L,+ providerId = 7L,+ name = "Source",+ contentType = ContentType.LIVE+ )+ )+ whenever(virtualGroupDao.getById(12L)).thenReturn(+ VirtualGroupEntity(+ id = 12L,+ providerId = 7L,+ name = "Target",+ contentType = ContentType.LIVE+ )+ )+ whenever(favoriteDao.getByGroup(11L)).thenReturn(+ flowOf(+ listOf(+ FavoriteEntity(+ id = 1L,+ providerId = 7L,+ contentId = 101L,+ contentType = ContentType.LIVE,+ position = 0,+ groupId = 11L,+ addedAt = 1_000L+ ),+ FavoriteEntity(+ id = 2L,+ providerId = 7L,+ contentId = 102L,+ contentType = ContentType.LIVE,+ position = 1_024,+ groupId = 11L,+ addedAt = 2_000L+ )+ )+ )+ )+ whenever(favoriteDao.get(7L, 101L, ContentType.LIVE.name, 12L)).thenReturn(null)+ whenever(favoriteDao.get(7L, 102L, ContentType.LIVE.name, 12L)).thenReturn(+ FavoriteEntity(+ id = 3L,+ providerId = 7L,+ contentId = 102L,+ contentType = ContentType.LIVE,+ position = 2_048,+ groupId = 12L,+ addedAt = 3_000L+ )+ )++ val result = repository.mergeGroupInto(11L, 12L)++ assertThat(result.isSuccess).isTrue()+ verify(favoriteDao).updateGroup(1L, 12L)+ verify(favoriteDao).delete(7L, 102L, ContentType.LIVE.name, 11L)+ verify(virtualGroupDao).delete(11L)+ }++ @Test+ fun `deleteGroup promotes members to global favorites when no duplicate exists`() = runTest {+ whenever(favoriteDao.getByGroup(11L)).thenReturn(+ flowOf(+ listOf(+ FavoriteEntity(+ id = 1L,+ providerId = 7L,+ contentId = 101L,+ contentType = ContentType.LIVE,+ position = 0,+ groupId = 11L,+ groupKey = 11L,+ addedAt = 1_000L+ )+ )+ )+ )+ whenever(favoriteDao.get(7L, 101L, ContentType.LIVE.name, null)).thenReturn(null)++ val result = repository.deleteGroup(11L)++ assertThat(result.isSuccess).isTrue()+ verify(favoriteDao).updateGroup(1L, null)+ verify(favoriteDao, never()).delete(7L, 101L, ContentType.LIVE.name, 11L)+ verify(virtualGroupDao).delete(11L)+ }++ @Test+ fun `deleteGroup removes source membership when a global favorite already exists`() = runTest {+ whenever(favoriteDao.getByGroup(11L)).thenReturn(+ flowOf(+ listOf(+ FavoriteEntity(+ id = 1L,+ providerId = 7L,+ contentId = 101L,+ contentType = ContentType.LIVE,+ position = 0,+ groupId = 11L,+ groupKey = 11L,+ addedAt = 1_000L+ )+ )+ )+ )+ whenever(favoriteDao.get(7L, 101L, ContentType.LIVE.name, null)).thenReturn(+ FavoriteEntity(+ id = 2L,+ providerId = 7L,+ contentId = 101L,+ contentType = ContentType.LIVE,+ position = 1_024,+ groupId = null,+ groupKey = 0L,+ addedAt = 2_000L+ )+ )++ val result = repository.deleteGroup(11L)++ assertThat(result.isSuccess).isTrue()+ verify(favoriteDao).delete(7L, 101L, ContentType.LIVE.name, 11L)+ verify(favoriteDao, never()).updateGroup(1L, null)+ verify(virtualGroupDao).delete(11L)+ }++ private fun favorite(+ id: Long,+ contentId: Long,+ position: Int,+ providerId: Long = 7L,+ groupId: Long? = null+ ) = Favorite(id = id,- providerId = 7L,+ providerId = providerId,contentId = contentId,contentType = ContentType.LIVE,- position = position+ position = position,+ groupId = groupId)}diff --git a/data/src/test/java/com/streamvault/data/repository/MovieRepositoryImplTest.kt b/data/src/test/java/com/streamvault/data/repository/MovieRepositoryImplTest.ktindex 4227e5dd..9157192f 100644--- a/data/src/test/java/com/streamvault/data/repository/MovieRepositoryImplTest.kt+++ b/data/src/test/java/com/streamvault/data/repository/MovieRepositoryImplTest.kt@@ -28,11 +28,17 @@ import com.streamvault.data.remote.xtream.XtreamApiServiceimport com.streamvault.data.remote.xtream.XtreamStreamUrlResolverimport com.streamvault.data.security.CredentialCryptoimport com.streamvault.domain.model.ContentType+import com.streamvault.domain.model.LibraryBrowseQuery+import com.streamvault.domain.model.LibraryFilterBy+import com.streamvault.domain.model.LibraryFilterType+import com.streamvault.domain.model.LibrarySortBy+import com.streamvault.domain.model.PlaybackHistoryimport com.streamvault.domain.model.ProviderStatusimport com.streamvault.domain.model.ProviderTypeimport com.streamvault.domain.model.Resultimport com.streamvault.domain.model.SyncMetadataimport com.streamvault.domain.model.VodSyncMode+import com.streamvault.domain.repository.PlaybackHistoryRepositoryimport com.streamvault.domain.repository.SyncMetadataRepositoryimport kotlinx.coroutines.flow.firstimport kotlinx.coroutines.flow.flow@@ -59,6 +65,7 @@ class MovieRepositoryImplTest {private val preferencesRepository: PreferencesRepository = mock()private val favoriteDao: FavoriteDao = mock()private val playbackHistoryDao: PlaybackHistoryDao = mock()+ private val playbackHistoryRepository: PlaybackHistoryRepository = mock()private val xtreamStreamUrlResolver: XtreamStreamUrlResolver = mock()private val movieCategoryHydrationDao: MovieCategoryHydrationDao = mock()private val syncMetadataRepository: SyncMetadataRepository = mock()@@ -389,13 +396,58 @@ class MovieRepositoryImplTest {whenever(movieDao.search(eq(7L), any(), any())).thenReturn(flow { throw SQLiteException("malformed MATCH expression") })+ whenever(movieDao.searchFallback(eq(7L), any(), any())).thenReturn(+ flowOf(+ listOf(+ movieEntity(+ id = 101L,+ name = "Matrix Reloaded",+ genre = "Action",+ categoryId = 42L,+ rating = 8.0f+ )+ )+ )+ )whenever(favoriteDao.getAllByType(7L, ContentType.MOVIE.name)).thenReturn(flowOf(emptyList()))val repository = createRepository()val result = repository.searchMovies(7L, "matrix").first()- assertThat(result).isEmpty()+ assertThat(result.map { it.name }).containsExactly("Matrix Reloaded")+ }++ @Test+ fun `browseMovies top rated excludes unrated entries and uses filtered total count`() = runTest {+ whenever(preferencesRepository.parentalControlLevel).thenReturn(flowOf(0))+ whenever(preferencesRepository.xtreamBase64TextCompatibility).thenReturn(flowOf(false))+ whenever(movieDao.getTopRatedCountByProvider(7L)).thenReturn(flowOf(1))+ whenever(movieDao.getTopRatedPreview(7L, 100)).thenReturn(+ flowOf(+ listOf(+ movieEntity(id = 1L, name = "Rated Movie", genre = "Drama", categoryId = 10L, rating = 8.5f),+ movieEntity(id = 2L, name = "Unrated Movie", genre = "Drama", categoryId = 10L, rating = 0f)+ )+ )+ )+ whenever(favoriteDao.getAllByType(7L, ContentType.MOVIE.name)).thenReturn(flowOf(emptyList()))+ whenever(playbackHistoryDao.getByProvider(7L)).thenReturn(flowOf(emptyList()))++ val repository = createRepository()++ val result = repository.browseMovies(+ LibraryBrowseQuery(+ providerId = 7L,+ sortBy = LibrarySortBy.RATING,+ filterBy = LibraryFilterBy(LibraryFilterType.TOP_RATED),+ offset = 0,+ limit = 20+ )+ ).first()++ assertThat(result.totalCount).isEqualTo(1)+ assertThat(result.items.map { it.name }).containsExactly("Rated Movie")}private fun createRepository() = MovieRepositoryImpl(@@ -408,6 +460,7 @@ class MovieRepositoryImplTest {preferencesRepository = preferencesRepository,favoriteDao = favoriteDao,playbackHistoryDao = playbackHistoryDao,+ playbackHistoryRepository = playbackHistoryRepository,xtreamStreamUrlResolver = xtreamStreamUrlResolver,movieCategoryHydrationDao = movieCategoryHydrationDao,syncMetadataRepository = syncMetadataRepository,diff --git a/data/src/test/java/com/streamvault/data/repository/PlaybackHistoryRepositoryImplTest.kt b/data/src/test/java/com/streamvault/data/repository/PlaybackHistoryRepositoryImplTest.ktindex 28ed6ea9..46f74f3e 100644--- a/data/src/test/java/com/streamvault/data/repository/PlaybackHistoryRepositoryImplTest.kt+++ b/data/src/test/java/com/streamvault/data/repository/PlaybackHistoryRepositoryImplTest.kt@@ -6,17 +6,23 @@ import com.streamvault.data.local.dao.EpisodeDaoimport com.streamvault.data.local.dao.MovieDaoimport com.streamvault.data.local.dao.PlaybackHistoryDaoimport com.streamvault.data.local.entity.PlaybackHistoryEntity+import com.streamvault.data.local.entity.PlaybackHistoryLiteEntityimport com.streamvault.data.preferences.PreferencesRepositoryimport com.streamvault.domain.model.ContentTypeimport com.streamvault.domain.model.PlaybackHistoryimport com.streamvault.domain.model.PlaybackWatchedStatus+import kotlinx.coroutines.flow.firstimport kotlinx.coroutines.flow.flowOfimport kotlinx.coroutines.test.runTestimport org.junit.Test+import org.mockito.kotlin.argumentCaptor+import org.mockito.kotlin.atLeastOnceimport org.mockito.kotlin.mockimport org.mockito.kotlin.never+import org.mockito.kotlin.eqimport org.mockito.kotlin.verifyimport org.mockito.kotlin.whenever+import org.mockito.kotlin.checkclass PlaybackHistoryRepositoryImplTest {@@ -64,19 +70,70 @@ class PlaybackHistoryRepositoryImplTest {}@Test- fun `updateResumePosition buffers writes until later flush point`() = runTest {+ fun `updateResumePosition persists playback history and syncs movie progress immediately`() = runTest {whenever(preferencesRepository.isIncognitoMode).thenReturn(flowOf(false))val repository = repository()val result = repository.updateResumePosition(movieHistory())assertThat(result.isSuccess).isTrue()- verify(historyDao, never()).insertOrUpdate(org.mockito.kotlin.any())- verify(movieDao, never()).syncWatchProgressFromHistory(org.mockito.kotlin.any(), org.mockito.kotlin.any())+ verify(historyDao).insertOrUpdate(org.mockito.kotlin.any())+ verify(movieDao).syncWatchProgressFromHistory(10L, 5L)+ }++ @Test+ fun `getPlaybackHistory prefers buffered resume update before flush`() = runTest {+ whenever(preferencesRepository.isIncognitoMode).thenReturn(flowOf(false))+ whenever(historyDao.get(10L, ContentType.MOVIE.name, 5L)).thenReturn(+ PlaybackHistoryEntity(+ contentId = 10L,+ contentType = ContentType.MOVIE,+ providerId = 5L,+ title = "Movie",+ resumePositionMs = 1_500L,+ totalDurationMs = 10_000L,+ lastWatchedAt = 111L+ )+ )+ val repository = repository()++ repository.updateResumePosition(movieHistory(resumePositionMs = 4_000L))+ val result = repository.getPlaybackHistory(10L, ContentType.MOVIE, 5L)++ assertThat(result?.resumePositionMs).isEqualTo(4_000L)+ assertThat(result?.lastWatchedAt).isGreaterThan(111L)+ }++ @Test+ fun `getRecentlyWatched overlays buffered resume updates before flush`() = runTest {+ whenever(preferencesRepository.isIncognitoMode).thenReturn(flowOf(false))+ whenever(historyDao.getRecentlyWatched(5)).thenReturn(+ flowOf(+ listOf(+ PlaybackHistoryLiteEntity(+ contentId = 10L,+ contentType = ContentType.MOVIE,+ providerId = 5L,+ title = "Movie",+ resumePositionMs = 1_500L,+ totalDurationMs = 10_000L,+ lastWatchedAt = 111L+ )+ )+ )+ )+ val repository = repository()++ repository.updateResumePosition(movieHistory(resumePositionMs = 4_000L))+ val result = repository.getRecentlyWatched(limit = 5).first()++ assertThat(result).hasSize(1)+ assertThat(result.first().resumePositionMs).isEqualTo(4_000L)+ assertThat(result.first().lastWatchedAt).isGreaterThan(111L)}@Test- fun `recordPlayback flushes buffered resume update as one explicit write`() = runTest {+ fun `recordPlayback persists final playback state after buffered resume update`() = runTest {whenever(preferencesRepository.isIncognitoMode).thenReturn(flowOf(false))val repository = repository()@@ -84,13 +141,82 @@ class PlaybackHistoryRepositoryImplTest {val result = repository.recordPlayback(movieHistory(resumePositionMs = 3_000L))assertThat(result.isSuccess).isTrue()- verify(historyDao).insertOrUpdate(org.mockito.kotlin.check {- assertThat(it.resumePositionMs).isEqualTo(3_000L)- assertThat(it.watchCount).isEqualTo(2)+ val historyCaptor = argumentCaptor<PlaybackHistoryEntity>()+ verify(historyDao, atLeastOnce()).insertOrUpdate(historyCaptor.capture())+ assertThat(historyCaptor.lastValue.resumePositionMs).isEqualTo(3_000L)+ assertThat(historyCaptor.lastValue.watchCount).isEqualTo(2)+ verify(movieDao, atLeastOnce()).syncWatchProgressFromHistory(10L, 5L)+ }++ @Test+ fun `markAsWatched syncs denormalized movie progress`() = runTest {+ whenever(preferencesRepository.isIncognitoMode).thenReturn(flowOf(false))+ val repository = repository()++ val result = repository.markAsWatched(movieHistory(resumePositionMs = 0L, totalDurationMs = 15_000L))++ assertThat(result.isSuccess).isTrue()+ verify(historyDao).insertOrUpdate(check {+ assertThat(it.resumePositionMs).isEqualTo(15_000L)+ assertThat(it.totalDurationMs).isEqualTo(15_000L)+ assertThat(it.watchedStatus).isEqualTo(PlaybackWatchedStatus.COMPLETED_MANUAL.name)})verify(movieDao).syncWatchProgressFromHistory(10L, 5L)}+ @Test+ fun `flushPendingProgress persists buffered episode progress and syncs denormalized state`() = runTest {+ whenever(preferencesRepository.isIncognitoMode).thenReturn(flowOf(false))+ val repository = repository()+ val history = PlaybackHistory(+ contentId = 11L,+ contentType = ContentType.SERIES_EPISODE,+ providerId = 6L,+ title = "Episode",+ streamUrl = "https://provider.example.com/episode",+ resumePositionMs = 7_500L,+ totalDurationMs = 12_000L,+ watchedStatus = PlaybackWatchedStatus.IN_PROGRESS+ )++ repository.updateResumePosition(history)+ val result = repository.flushPendingProgress()++ assertThat(result.isSuccess).isTrue()+ verify(historyDao, org.mockito.kotlin.atLeastOnce()).insertOrUpdate(check {+ assertThat(it.contentId).isEqualTo(11L)+ assertThat(it.contentType).isEqualTo(ContentType.SERIES_EPISODE)+ assertThat(it.providerId).isEqualTo(6L)+ assertThat(it.resumePositionMs).isEqualTo(7_500L)+ })+ verify(episodeDao, org.mockito.kotlin.atLeastOnce()).syncWatchProgressFromHistory(11L, 6L)+ }++ @Test+ fun `removeFromHistory deletes record and syncs denormalized movie progress`() = runTest {+ whenever(preferencesRepository.isIncognitoMode).thenReturn(flowOf(false))+ val repository = repository()++ val result = repository.removeFromHistory(10L, ContentType.MOVIE, 5L)++ assertThat(result.isSuccess).isTrue()+ verify(historyDao).delete(10L, ContentType.MOVIE.name, 5L)+ verify(movieDao).syncWatchProgressFromHistory(10L, 5L)+ }++ @Test+ fun `clearHistoryForProvider resyncs denormalized movie and episode progress`() = runTest {+ whenever(preferencesRepository.isIncognitoMode).thenReturn(flowOf(false))+ val repository = repository()++ val result = repository.clearHistoryForProvider(5L)++ assertThat(result.isSuccess).isTrue()+ verify(historyDao).deleteByProvider(5L)+ verify(movieDao).syncWatchProgressFromHistoryByProvider(5L)+ verify(episodeDao).syncWatchProgressFromHistoryByProvider(5L)+ }+@Testfun `getPlaybackHistory falls back to shared tmdb movie history across providers`() = runTest {whenever(preferencesRepository.isIncognitoMode).thenReturn(flowOf(false))@@ -113,4 +239,30 @@ class PlaybackHistoryRepositoryImplTest {assertThat(result?.providerId).isEqualTo(9L)assertThat(result?.resumePositionMs).isEqualTo(4_000L)}++ @Test+ fun `getRecentlyWatchedByProviders uses provider set query`() = runTest {+ whenever(preferencesRepository.isIncognitoMode).thenReturn(flowOf(false))+ whenever(historyDao.getRecentlyWatchedByProviders(setOf(5L, 6L), 8)).thenReturn(+ flowOf(+ listOf(+ PlaybackHistoryLiteEntity(+ contentId = 10L,+ contentType = ContentType.MOVIE,+ providerId = 5L,+ title = "Movie",+ resumePositionMs = 4_000L,+ totalDurationMs = 10_000L,+ lastWatchedAt = 123L+ )+ )+ )+ )++ val result = repository().getRecentlyWatchedByProviders(setOf(5L, 6L), 8)++ assertThat(result.first()).hasSize(1)+ assertThat(result.first().first().providerId).isEqualTo(5L)+ verify(historyDao).getRecentlyWatchedByProviders(eq(setOf(5L, 6L)), eq(8))+ }}diff --git a/data/src/test/java/com/streamvault/data/repository/ProviderRepositoryImplTest.kt b/data/src/test/java/com/streamvault/data/repository/ProviderRepositoryImplTest.ktnew file mode 100644index 00000000..a4657921--- /dev/null+++ b/data/src/test/java/com/streamvault/data/repository/ProviderRepositoryImplTest.kt@@ -0,0 +1,284 @@+package com.streamvault.data.repository++import com.google.common.truth.Truth.assertThat+import com.streamvault.data.local.DatabaseTransactionRunner+import com.streamvault.data.local.dao.ChannelDao+import com.streamvault.data.local.dao.ProgramDao+import com.streamvault.data.local.dao.ProgramReminderDao+import com.streamvault.data.local.dao.ProviderDao+import com.streamvault.data.local.dao.RecordingRunDao+import com.streamvault.data.local.entity.ProviderEntity+import com.streamvault.data.manager.recording.RecordingAlarmScheduler+import com.streamvault.data.manager.reminder.ProgramReminderAlarmScheduler+import com.streamvault.data.preferences.PreferencesRepository+import com.streamvault.data.remote.stalker.StalkerApiService+import com.streamvault.data.remote.xtream.XtreamApiService+import com.streamvault.data.security.CredentialCrypto+import com.streamvault.data.sync.SyncManager+import com.streamvault.domain.model.ProviderEpgSyncMode+import com.streamvault.domain.model.ProviderSavedWithSyncErrorException+import com.streamvault.domain.model.Result+import com.streamvault.domain.model.SyncState+import com.streamvault.domain.model.ProviderStatus+import com.streamvault.domain.model.ProviderType+import com.streamvault.domain.repository.SyncMetadataRepository+import kotlinx.coroutines.test.runTest+import org.junit.Test+import org.mockito.kotlin.any+import org.mockito.kotlin.anyOrNull+import org.mockito.kotlin.doAnswer+import org.mockito.kotlin.eq+import org.mockito.kotlin.inOrder+import org.mockito.kotlin.mock+import org.mockito.kotlin.never+import org.mockito.kotlin.verify+import org.mockito.kotlin.whenever++class ProviderRepositoryImplTest {++ private val providerDao: ProviderDao = mock()+ private val channelDao: ChannelDao = mock()+ private val programDao: ProgramDao = mock()+ private val recordingRunDao: RecordingRunDao = mock()+ private val programReminderDao: ProgramReminderDao = mock()+ private val stalkerApiService: StalkerApiService = mock()+ private val xtreamApiService: XtreamApiService = mock()+ private val credentialCrypto: CredentialCrypto = mock()+ private val preferencesRepository: PreferencesRepository = mock()+ private val syncManager: SyncManager = mock()+ private val syncMetadataRepository: SyncMetadataRepository = mock()+ private val recordingAlarmScheduler: RecordingAlarmScheduler = mock()+ private val programReminderAlarmScheduler: ProgramReminderAlarmScheduler = mock()+ private val transactionRunner = object : DatabaseTransactionRunner {+ override suspend fun <T> inTransaction(block: suspend () -> T): T = block()+ }++ private fun createRepository(+ transactionRunner: DatabaseTransactionRunner = this.transactionRunner+ ) = ProviderRepositoryImpl(+ providerDao = providerDao,+ channelDao = channelDao,+ programDao = programDao,+ recordingRunDao = recordingRunDao,+ programReminderDao = programReminderDao,+ stalkerApiService = stalkerApiService,+ xtreamApiService = xtreamApiService,+ credentialCrypto = credentialCrypto,+ preferencesRepository = preferencesRepository,+ syncManager = syncManager,+ syncMetadataRepository = syncMetadataRepository,+ transactionRunner = transactionRunner,+ recordingAlarmScheduler = recordingAlarmScheduler,+ programReminderAlarmScheduler = programReminderAlarmScheduler+ )++ private val repository = createRepository()++ @Test+ fun `deleteProvider cancels recording and reminder alarms before deleting provider rows`() = runTest {+ whenever(recordingRunDao.getIdsByProvider(7L)).thenReturn(listOf("run-1", "run-2"))+ whenever(programReminderDao.getIdsByProvider(7L)).thenReturn(listOf(11L, 12L))++ val result = repository.deleteProvider(7L)++ assertThat(result.isSuccess).isTrue()+ val inOrder = inOrder(recordingAlarmScheduler, programReminderAlarmScheduler, programDao, providerDao, syncManager)+ inOrder.verify(programDao).deleteByProvider(7L)+ inOrder.verify(providerDao).delete(7L)+ inOrder.verify(recordingAlarmScheduler).cancel("run-1")+ inOrder.verify(recordingAlarmScheduler).cancel("run-2")+ inOrder.verify(programReminderAlarmScheduler).cancel(11L)+ inOrder.verify(programReminderAlarmScheduler).cancel(12L)+ inOrder.verify(syncManager).onProviderDeleted(7L)+ verify(recordingRunDao).getIdsByProvider(7L)+ verify(programReminderDao).getIdsByProvider(7L)+ }++ @Test+ fun `deleteProvider commits database cleanup before sync side effects`() = runTest {+ val events = mutableListOf<String>()+ val trackedTransactionRunner = object : DatabaseTransactionRunner {+ override suspend fun <T> inTransaction(block: suspend () -> T): T {+ events += "transaction:start"+ return try {+ block()+ } finally {+ events += "transaction:end"+ }+ }+ }+ val trackedRepository = createRepository(transactionRunner = trackedTransactionRunner)++ whenever(recordingRunDao.getIdsByProvider(7L)).thenReturn(emptyList())+ whenever(programReminderDao.getIdsByProvider(7L)).thenReturn(emptyList())+ doAnswer {+ events += "programs:delete"+ Unit+ }.whenever(programDao).deleteByProvider(7L)+ doAnswer {+ events += "provider:delete"+ Unit+ }.whenever(providerDao).delete(7L)+ doAnswer {+ events += "sync:cleanup"+ Unit+ }.whenever(syncManager).onProviderDeleted(7L)++ val result = trackedRepository.deleteProvider(7L)++ assertThat(result.isSuccess).isTrue()+ assertThat(events).containsExactly(+ "transaction:start",+ "programs:delete",+ "provider:delete",+ "transaction:end",+ "sync:cleanup"+ ).inOrder()+ }++ @Test+ fun `deleteProvider keeps success after post commit cleanup failure`() = runTest {+ whenever(recordingRunDao.getIdsByProvider(7L)).thenReturn(listOf("run-1"))+ whenever(programReminderDao.getIdsByProvider(7L)).thenReturn(listOf(11L))+ doAnswer { throw IllegalStateException("sync cleanup failed") }+ .whenever(syncManager).onProviderDeleted(7L)++ val result = repository.deleteProvider(7L)++ assertThat(result.isSuccess).isTrue()+ verify(programDao).deleteByProvider(7L)+ verify(providerDao).delete(7L)+ verify(recordingAlarmScheduler).cancel("run-1")+ verify(programReminderAlarmScheduler).cancel(11L)+ verify(syncManager).onProviderDeleted(7L)+ }++ @Test+ fun `validateM3u uses transactional activation api`() = runTest {+ val existingProvider = ProviderEntity(+ id = 5L,+ name = "Playlist",+ type = ProviderType.M3U,+ serverUrl = "https://example.com/list.m3u",+ m3uUrl = "https://example.com/list.m3u",+ status = ProviderStatus.UNKNOWN+ )++ whenever(providerDao.getByUrlAndUser("https://example.com/list.m3u", "", "")).thenReturn(existingProvider)+ whenever(providerDao.getById(5L)).thenReturn(existingProvider)+ whenever(syncManager.sync(5L, false, null)).thenReturn(Result.success(Unit))+ whenever(syncManager.currentSyncState(5L)).thenReturn(SyncState.Success(123L))++ val result = repository.validateM3u(+ url = "https://example.com/list.m3u",+ name = "Playlist",+ epgSyncMode = ProviderEpgSyncMode.UPFRONT,+ m3uVodClassificationEnabled = false,+ onProgress = null,+ id = null+ )++ assertThat(result.isSuccess).isTrue()+ verify(providerDao).setActive(5L)+ verify(providerDao, never()).deactivateAll()+ verify(providerDao, never()).activate(5L)+ }++ @Test+ fun `validateM3u returns saved provider sync error exception when initial sync fails after save`() = runTest {+ whenever(providerDao.getByUrlAndUser("https://example.com/list.m3u", "", "")).thenReturn(null)+ whenever(credentialCrypto.encryptIfNeeded("")).thenReturn("")+ whenever(providerDao.insert(any())).thenReturn(9L)+ whenever(syncManager.sync(eq(9L), eq(false), anyOrNull(), anyOrNull(), any())).thenReturn(Result.error("timeout"))++ val result = repository.validateM3u(+ url = "https://example.com/list.m3u",+ name = "Playlist",+ epgSyncMode = ProviderEpgSyncMode.UPFRONT,+ m3uVodClassificationEnabled = false,+ onProgress = {},+ id = null+ )++ assertThat(result.isError).isTrue()+ val failure = (result as Result.Error).exception as ProviderSavedWithSyncErrorException+ assertThat(failure.provider.id).isEqualTo(9L)+ assertThat(failure.provider.status).isEqualTo(ProviderStatus.ERROR)+ assertThat(failure.message).contains("Playlist saved, but initial sync failed")+ verify(providerDao).setActive(9L)+ }++ @Test+ fun `validateM3u edit path rejects update when new URL already belongs to a different provider`() = runTest {+ val editTarget = ProviderEntity(+ id = 5L,+ name = "Playlist A",+ type = ProviderType.M3U,+ serverUrl = "https://example.com/a.m3u",+ m3uUrl = "https://example.com/a.m3u",+ status = ProviderStatus.ACTIVE+ )+ val collision = ProviderEntity(+ id = 9L,+ name = "Playlist B",+ type = ProviderType.M3U,+ serverUrl = "https://example.com/b.m3u",+ m3uUrl = "https://example.com/b.m3u",+ status = ProviderStatus.ACTIVE+ )+ // Provider 9 already owns the URL we want to move provider 5 to.+ whenever(providerDao.getByUrlAndUser("https://example.com/b.m3u", "", "")).thenReturn(collision)++ val result = repository.validateM3u(+ url = "https://example.com/b.m3u",+ name = "Playlist A",+ epgSyncMode = ProviderEpgSyncMode.BACKGROUND,+ m3uVodClassificationEnabled = false,+ onProgress = null,+ id = editTarget.id+ )++ assertThat(result.isError).isTrue()+ assertThat((result as Result.Error).message).contains("already exists")+ verify(providerDao, never()).insert(any())+ verify(providerDao, never()).update(any())+ }++ @Test+ fun `validateM3u edit path allows update when URL belongs to the same provider being edited`() = runTest {+ val editTarget = ProviderEntity(+ id = 5L,+ name = "Playlist A",+ type = ProviderType.M3U,+ serverUrl = "https://example.com/a.m3u",+ m3uUrl = "https://example.com/a.m3u",+ status = ProviderStatus.ACTIVE+ )+ // The collision query returns the same provider being edited — that is not a conflict.+ whenever(providerDao.getByUrlAndUser("https://example.com/a.m3u", "", "")).thenReturn(editTarget)+ whenever(providerDao.getById(5L)).thenReturn(editTarget)+ whenever(syncManager.sync(5L, false, null)).thenReturn(Result.success(Unit))+ whenever(syncManager.currentSyncState(5L)).thenReturn(SyncState.Success(123L))++ val result = repository.validateM3u(+ url = "https://example.com/a.m3u",+ name = "Playlist A renamed",+ epgSyncMode = ProviderEpgSyncMode.BACKGROUND,+ m3uVodClassificationEnabled = false,+ onProgress = null,+ id = editTarget.id+ )++ assertThat(result.isSuccess).isTrue()+ }++ @Test+ fun `setActiveProvider uses transactional activation api`() = runTest {+ val result = repository.setActiveProvider(9L)++ assertThat(result.isSuccess).isTrue()+ verify(providerDao).setActive(9L)+ verify(providerDao, never()).deactivateAll()+ verify(providerDao, never()).activate(9L)+ }+}\ No newline at end of filediff --git a/data/src/test/java/com/streamvault/data/repository/SeriesRepositoryImplTest.kt b/data/src/test/java/com/streamvault/data/repository/SeriesRepositoryImplTest.ktindex 0fdcc0d7..a4f0dd43 100644--- a/data/src/test/java/com/streamvault/data/repository/SeriesRepositoryImplTest.kt+++ b/data/src/test/java/com/streamvault/data/repository/SeriesRepositoryImplTest.kt@@ -9,7 +9,9 @@ import com.streamvault.data.local.dao.PlaybackHistoryDaoimport com.streamvault.data.local.dao.ProviderDaoimport com.streamvault.data.local.dao.SeriesDaoimport com.streamvault.data.local.dao.SeriesCategoryHydrationDao+import com.streamvault.data.local.entity.EpisodeEntityimport com.streamvault.data.local.entity.SeriesEntity+import com.streamvault.data.local.entity.SeriesBrowseEntityimport com.streamvault.data.local.entity.ProviderEntityimport com.streamvault.data.preferences.PreferencesRepositoryimport com.streamvault.data.remote.stalker.StalkerCategoryRecord@@ -28,9 +30,15 @@ import com.streamvault.data.remote.xtream.XtreamApiServiceimport com.streamvault.data.remote.xtream.XtreamStreamUrlResolverimport com.streamvault.data.security.CredentialCryptoimport com.streamvault.domain.model.ContentType+import com.streamvault.domain.model.LibraryBrowseQuery+import com.streamvault.domain.model.LibraryFilterBy+import com.streamvault.domain.model.LibraryFilterType+import com.streamvault.domain.model.LibrarySortBy+import com.streamvault.domain.model.PlaybackHistoryimport com.streamvault.domain.model.ProviderStatusimport com.streamvault.domain.model.ProviderTypeimport com.streamvault.domain.model.Result+import com.streamvault.domain.repository.PlaybackHistoryRepositoryimport kotlinx.coroutines.flow.firstimport kotlinx.coroutines.flow.flowimport kotlinx.coroutines.flow.flowOf@@ -53,6 +61,7 @@ class SeriesRepositoryImplTest {private val categoryDao: CategoryDao = mock()private val favoriteDao: FavoriteDao = mock()private val playbackHistoryDao: PlaybackHistoryDao = mock()+ private val playbackHistoryRepository: PlaybackHistoryRepository = mock()private val providerDao: ProviderDao = mock()private val stalkerApiService: StalkerApiService = mock()private val xtreamApiService: XtreamApiService = mock()@@ -215,6 +224,38 @@ class SeriesRepositoryImplTest {verify(stalkerApiService, never()).getSeriesPage(any(), any(), anyOrNull(), eq(2))}+ @Test+ fun `browseSeries recently updated excludes stale entries and uses filtered total count`() = runTest {+ whenever(preferencesRepository.parentalControlLevel).thenReturn(flowOf(0))+ whenever(preferencesRepository.xtreamBase64TextCompatibility).thenReturn(flowOf(false))+ whenever(seriesDao.getFreshCountByProvider(7L)).thenReturn(flowOf(1))+ whenever(seriesDao.getFreshPreview(7L, 100)).thenReturn(+ flowOf(+ listOf(+ SeriesBrowseEntity(id = 1L, seriesId = 101L, name = "Fresh Series", providerId = 7L, lastModified = 10_000L),+ SeriesBrowseEntity(id = 2L, seriesId = 102L, name = "Stale Series", providerId = 7L, lastModified = 0L)+ )+ )+ )+ whenever(favoriteDao.getAllByType(7L, ContentType.SERIES.name)).thenReturn(flowOf(emptyList()))+ whenever(playbackHistoryDao.getByProvider(7L)).thenReturn(flowOf(emptyList()))++ val repository = createRepository()++ val result = repository.browseSeries(+ LibraryBrowseQuery(+ providerId = 7L,+ sortBy = LibrarySortBy.UPDATED,+ filterBy = LibraryFilterBy(LibraryFilterType.RECENTLY_UPDATED),+ offset = 0,+ limit = 20+ )+ ).first()++ assertThat(result.totalCount).isEqualTo(1)+ assertThat(result.items.map { it.name }).containsExactly("Fresh Series")+ }+@Testfun `getSeriesByCategory marks empty xtream fast sync hydration for retry`() = runTest {whenever(preferencesRepository.parentalControlLevel).thenReturn(flowOf(0))@@ -391,13 +432,25 @@ class SeriesRepositoryImplTest {whenever(seriesDao.search(eq(7L), any(), any())).thenReturn(flow { throw SQLiteException("malformed MATCH expression") })+ whenever(seriesDao.searchFallback(eq(7L), any(), any())).thenReturn(+ flowOf(+ listOf(+ SeriesBrowseEntity(+ id = 15L,+ seriesId = 1500L,+ name = "Drama House",+ providerId = 7L+ )+ )+ )+ )whenever(favoriteDao.getAllByType(7L, ContentType.SERIES.name)).thenReturn(flowOf(emptyList()))val repository = createRepository()val result = repository.searchSeries(7L, "drama").first()- assertThat(result).isEmpty()+ assertThat(result.map { it.name }).containsExactly("Drama House")}private fun createRepository() = SeriesRepositoryImpl(@@ -406,6 +459,7 @@ class SeriesRepositoryImplTest {categoryDao = categoryDao,favoriteDao = favoriteDao,playbackHistoryDao = playbackHistoryDao,+ playbackHistoryRepository = playbackHistoryRepository,providerDao = providerDao,stalkerApiService = stalkerApiService,xtreamApiService = xtreamApiService,diff --git a/data/src/test/java/com/streamvault/data/sync/SyncCatalogStoreTest.kt b/data/src/test/java/com/streamvault/data/sync/SyncCatalogStoreTest.ktindex 5f1be638..9be4b349 100644--- a/data/src/test/java/com/streamvault/data/sync/SyncCatalogStoreTest.kt+++ b/data/src/test/java/com/streamvault/data/sync/SyncCatalogStoreTest.kt@@ -23,6 +23,7 @@ import org.junit.Beforeimport org.junit.Testimport org.mockito.kotlin.anyimport org.mockito.kotlin.argumentCaptor+import org.mockito.kotlin.doAnswerimport org.mockito.kotlin.eqimport org.mockito.kotlin.mockimport org.mockito.kotlin.never@@ -37,11 +38,12 @@ class SyncCatalogStoreTest {private val categoryDao: CategoryDao = mock()private val catalogSyncDao: CatalogSyncDao = mock()private val tmdbIdentityDao: TmdbIdentityDao = mock()- private val transactionRunner = object : DatabaseTransactionRunner {- override suspend fun <T> inTransaction(block: suspend () -> T): T = block()- }+ private val defaultTransactionRunner = TrackingTransactionRunner()- private fun store(sizeLimits: CatalogSizeLimits = CatalogSizeLimits()) = SyncCatalogStore(+ private fun store(+ sizeLimits: CatalogSizeLimits = CatalogSizeLimits(),+ transactionRunner: DatabaseTransactionRunner = defaultTransactionRunner+ ) = SyncCatalogStore(channelDao = channelDao,movieDao = movieDao,seriesDao = seriesDao,@@ -120,6 +122,7 @@ class SyncCatalogStoreTest {store().applyStagedMovieCatalog(providerId, sessionId, categories = null)verify(catalogSyncDao).updateChangedMoviesFromStage(providerId, sessionId)+ verify(catalogSyncDao).rebuildMovieFts()verify(movieDao).restoreWatchProgress(providerId)}@@ -130,6 +133,173 @@ class SyncCatalogStoreTest {store().applyStagedSeriesCatalog(providerId, sessionId, categories = null)verify(catalogSyncDao).updateChangedSeriesFromStage(providerId, sessionId)+ verify(catalogSyncDao).rebuildSeriesFts()+ }++ @Test+ fun `applyStagedLiveCatalog rebuilds channel fts inside transaction`() = runTest {+ val runner = TrackingTransactionRunner()+ doAnswer {+ assertThat(runner.isInTransaction).isTrue()+ Unit+ }.whenever(catalogSyncDao).rebuildChannelFts()++ store(transactionRunner = runner).applyStagedLiveCatalog(providerId = 7L, sessionId = 55L, categories = null)++ assertThat(runner.calls).isEqualTo(1)+ verify(catalogSyncDao).rebuildChannelFts()+ }++ @Test+ fun `replaceSeriesCatalog stages provider-native series ids`() = runTest {+ val providerId = 7L+ whenever(seriesDao.getByProviderSync(providerId)).thenReturn(emptyList())+ whenever(catalogSyncDao.getSeriesStages(eq(providerId), any())).thenReturn(emptyList())++ val acceptedCount = store().replaceSeriesCatalog(+ providerId = providerId,+ categories = null,+ series = sequenceOf(+ SeriesEntity(+ seriesId = 256103980L,+ providerSeriesId = "55000:55000",+ name = "Composite Series",+ providerId = providerId,+ syncFingerprint = ""+ )+ )+ )++ assertThat(acceptedCount).isEqualTo(1)+ val insertedStages = argumentCaptor<List<SeriesImportStageEntity>>()+ verify(catalogSyncDao).insertSeriesStages(insertedStages.capture())+ assertThat(insertedStages.firstValue.single().providerSeriesId).isEqualTo("55000:55000")+ assertThat(insertedStages.firstValue.single().providerSeriesKey).isEqualTo("55000:55000")+ }++ @Test+ fun `stageMovieBatch preserves movie metadata needed by staged apply`() = runTest {+ val providerId = 7L+ val sessionId = 88L+ val movie = MovieEntity(+ streamId = 1001L,+ name = "Late Night Feature",+ posterUrl = "https://img.example.test/movie-poster.jpg",+ backdropUrl = "https://img.example.test/movie-backdrop.jpg",+ categoryId = 42L,+ categoryName = "Thriller",+ streamUrl = "https://stream.example.test/movie.m3u8",+ containerExtension = "mp4",+ plot = "A staged sync guardrail.",+ cast = "Lead Actor",+ director = "Director Name",+ genre = "Thriller",+ releaseDate = "2026-05-02",+ duration = "01:45:00",+ durationSeconds = 6_300,+ rating = 8.4f,+ year = "2026",+ tmdbId = 555001L,+ youtubeTrailer = "trailer123",+ providerId = providerId,+ isAdult = true,+ addedAt = 123_456L+ )++ store().stageMovieBatch(providerId, sessionId, listOf(movie))++ val insertedStages = argumentCaptor<List<MovieImportStageEntity>>()+ verify(catalogSyncDao).insertMovieStages(insertedStages.capture())+ val stagedMovie = insertedStages.firstValue.single()+ assertThat(stagedMovie.copy(syncFingerprint = "")).isEqualTo(+ MovieImportStageEntity(+ sessionId = sessionId,+ providerId = providerId,+ streamId = movie.streamId,+ name = movie.name,+ posterUrl = movie.posterUrl,+ backdropUrl = movie.backdropUrl,+ categoryId = movie.categoryId,+ categoryName = movie.categoryName,+ streamUrl = movie.streamUrl,+ containerExtension = movie.containerExtension,+ plot = movie.plot,+ cast = movie.cast,+ director = movie.director,+ genre = movie.genre,+ releaseDate = movie.releaseDate,+ duration = movie.duration,+ durationSeconds = movie.durationSeconds,+ rating = movie.rating,+ year = movie.year,+ tmdbId = movie.tmdbId,+ youtubeTrailer = movie.youtubeTrailer,+ isAdult = movie.isAdult,+ syncFingerprint = "",+ addedAt = movie.addedAt+ )+ )+ assertThat(stagedMovie.syncFingerprint).isNotEmpty()+ }++ @Test+ fun `stageSeriesBatch preserves provider identity and metadata needed by staged apply`() = runTest {+ val providerId = 7L+ val sessionId = 89L+ val series = SeriesEntity(+ seriesId = 256103980L,+ providerSeriesId = "55000:55000",+ name = "Composite Series",+ posterUrl = "https://img.example.test/series-poster.jpg",+ backdropUrl = "https://img.example.test/series-backdrop.jpg",+ categoryId = 77L,+ categoryName = "Drama",+ plot = "Series staging guardrail.",+ cast = "Ensemble Cast",+ director = "Showrunner",+ genre = "Drama",+ releaseDate = "2026-05-02",+ rating = 9.1f,+ tmdbId = 777001L,+ youtubeTrailer = "seriesTrailer",+ episodeRunTime = "52",+ lastModified = 9_999L,+ providerId = providerId,+ isAdult = true+ )++ store().stageSeriesBatch(providerId, sessionId, listOf(series))++ val insertedStages = argumentCaptor<List<SeriesImportStageEntity>>()+ verify(catalogSyncDao).insertSeriesStages(insertedStages.capture())+ val stagedSeries = insertedStages.firstValue.single()+ assertThat(stagedSeries.copy(syncFingerprint = "")).isEqualTo(+ SeriesImportStageEntity(+ sessionId = sessionId,+ providerId = providerId,+ seriesId = series.seriesId,+ providerSeriesId = series.providerSeriesId,+ providerSeriesKey = series.providerSeriesId!!,+ name = series.name,+ posterUrl = series.posterUrl,+ backdropUrl = series.backdropUrl,+ categoryId = series.categoryId,+ categoryName = series.categoryName,+ plot = series.plot,+ cast = series.cast,+ director = series.director,+ genre = series.genre,+ releaseDate = series.releaseDate,+ rating = series.rating,+ tmdbId = series.tmdbId,+ youtubeTrailer = series.youtubeTrailer,+ episodeRunTime = series.episodeRunTime,+ lastModified = series.lastModified,+ isAdult = series.isAdult,+ syncFingerprint = ""+ )+ )+ assertThat(stagedSeries.syncFingerprint).isNotEmpty()}@Test@@ -198,6 +368,7 @@ class SyncCatalogStoreTest {val insertedChannels = argumentCaptor<List<ChannelImportStageEntity>>()verify(catalogSyncDao).insertChannelStages(insertedChannels.capture())assertThat(insertedChannels.firstValue.map { it.streamId }).containsExactly(1002L, 1003L).inOrder()+ verify(catalogSyncDao).rebuildChannelFts()}@Test@@ -219,5 +390,54 @@ class SyncCatalogStoreTest {val insertedMovies = argumentCaptor<List<MovieImportStageEntity>>()verify(catalogSyncDao).insertMovieStages(insertedMovies.capture())assertThat(insertedMovies.firstValue.map { it.streamId }).containsExactly(2002L, 2003L).inOrder()+ verify(catalogSyncDao).rebuildMovieFts()+ }++ @Test+ fun `finalizeStagedImport rebuilds live and movie fts inside transaction`() = runTest {+ val runner = TrackingTransactionRunner()+ whenever(categoryDao.getByProviderAndTypeSync(7L, ContentType.LIVE.name)).thenReturn(emptyList())+ whenever(categoryDao.getByProviderAndTypeSync(7L, ContentType.MOVIE.name)).thenReturn(emptyList())+ whenever(catalogSyncDao.getCategoryStages(eq(7L), any(), eq(ContentType.LIVE.name))).thenReturn(emptyList())+ whenever(catalogSyncDao.getCategoryStages(eq(7L), any(), eq(ContentType.MOVIE.name))).thenReturn(emptyList())+ doAnswer {+ assertThat(runner.isInTransaction).isTrue()+ Unit+ }.whenever(catalogSyncDao).rebuildChannelFts()+ doAnswer {+ assertThat(runner.isInTransaction).isTrue()+ Unit+ }.whenever(catalogSyncDao).rebuildMovieFts()++ store(transactionRunner = runner).finalizeStagedImport(+ providerId = 7L,+ sessionId = 66L,+ liveCategories = null,+ movieCategories = null,+ includeLive = true,+ includeMovies = true+ )++ verify(catalogSyncDao).rebuildChannelFts()+ verify(catalogSyncDao).rebuildMovieFts()+ verify(movieDao).restoreWatchProgress(7L)+ }++ private class TrackingTransactionRunner : DatabaseTransactionRunner {+ var calls: Int = 0+ private var depth: Int = 0++ val isInTransaction: Boolean+ get() = depth > 0++ override suspend fun <T> inTransaction(block: suspend () -> T): T {+ calls += 1+ depth += 1+ return try {+ block()+ } finally {+ depth -= 1+ }+ }}}diff --git a/data/src/test/java/com/streamvault/data/sync/SyncManagerTest.kt b/data/src/test/java/com/streamvault/data/sync/SyncManagerTest.ktindex 7fe98235..990f8a3f 100644--- a/data/src/test/java/com/streamvault/data/sync/SyncManagerTest.kt+++ b/data/src/test/java/com/streamvault/data/sync/SyncManagerTest.kt@@ -88,6 +88,8 @@ class SyncManagerTest {override fun getAll() = kotlinx.coroutines.flow.flowOf(listOfNotNull(provider))override suspend fun getAllSync(): List<ProviderEntity> = listOfNotNull(provider)override fun getActive() = kotlinx.coroutines.flow.flowOf(provider)+ override suspend fun insertDirect(provider: ProviderEntity) = this.provider?.id ?: 0L+ override suspend fun updateDirect(provider: ProviderEntity) = Unitoverride suspend fun insert(provider: ProviderEntity) = this.provider?.id ?: 0Loverride suspend fun update(provider: ProviderEntity) = Unitoverride suspend fun delete(id: Long) = Unitdiff --git a/data/src/test/java/com/streamvault/data/util/UrlSecurityPolicyTest.kt b/data/src/test/java/com/streamvault/data/util/UrlSecurityPolicyTest.ktindex 5b1307da..2ca4e7d6 100644--- a/data/src/test/java/com/streamvault/data/util/UrlSecurityPolicyTest.kt+++ b/data/src/test/java/com/streamvault/data/util/UrlSecurityPolicyTest.kt@@ -13,6 +13,14 @@ class UrlSecurityPolicyTest {.isEqualTo("Xtream server URLs must use HTTP or HTTPS.")}+ @Test+ fun `validateXtreamServerUrl rejects embedded credentials and missing host`() {+ assertThat(UrlSecurityPolicy.validateXtreamServerUrl("https://[email protected]"))+ .isEqualTo("Xtream server URLs must not include embedded credentials.")+ assertThat(UrlSecurityPolicy.validateXtreamServerUrl("https:///portal"))+ .isEqualTo("Xtream server URLs must include a host.")+ }+@Testfun `validateXtreamEpgUrl allows http and https endpoints`() {assertThat(UrlSecurityPolicy.validateXtreamEpgUrl("http://provider.example.com/xmltv.php")).isNull()@@ -24,13 +32,28 @@ class UrlSecurityPolicyTest {@Testfun `validatePlaylistSourceUrl allows local http and https`() {assertThat(UrlSecurityPolicy.validatePlaylistSourceUrl("file:///storage/emulated/0/playlist.m3u")).isNull()- assertThat(UrlSecurityPolicy.validatePlaylistSourceUrl("content://downloads/public_downloads/1")).isNull()assertThat(UrlSecurityPolicy.validatePlaylistSourceUrl("https://example.com/playlist.m3u")).isNull()assertThat(UrlSecurityPolicy.validatePlaylistSourceUrl("http://example.com/playlist.m3u")).isNull()assertThat(UrlSecurityPolicy.validatePlaylistSourceUrl("ftp://example.com/playlist.m3u")).isEqualTo("Playlist sources must use HTTP, HTTPS, or point to a local file.")}+ @Test+ fun `validatePlaylistSourceUrl rejects content uri because the importer cannot open it`() {+ // content:// URIs are accepted during the UI file-import flow but the imported data is+ // immediately copied to an internal file:// path. Storing a raw content:// URI as a+ // provider playlist source would cause every subsequent sync to fail because+ // SyncManagerM3uImporter only handles file: paths and HTTP/S via OkHttp.+ assertThat(UrlSecurityPolicy.validatePlaylistSourceUrl("content://downloads/public_downloads/1"))+ .isEqualTo("Playlist sources must use HTTP, HTTPS, or point to a local file.")+ }++ @Test+ fun `validatePlaylistSourceUrl rejects embedded credentials in remote urls`() {+ assertThat(UrlSecurityPolicy.validatePlaylistSourceUrl("https://[email protected]/get.php?username=a&password=b&type=m3u_plus"))+ .isEqualTo("Playlist sources must not include embedded credentials in the URL authority.")+ }+@Testfun `stream entry urls reject newline injection`() {assertThat(UrlSecurityPolicy.isAllowedStreamEntryUrl("https://example.com/live.ts%0AInjected: true")).isFalse()diff --git a/data/src/test/java/com/streamvault/data/validation/ProviderSetupInputValidatorImplTest.kt b/data/src/test/java/com/streamvault/data/validation/ProviderSetupInputValidatorImplTest.ktnew file mode 100644index 00000000..7e96d7e3--- /dev/null+++ b/data/src/test/java/com/streamvault/data/validation/ProviderSetupInputValidatorImplTest.kt@@ -0,0 +1,145 @@+package com.streamvault.data.validation++import com.google.common.truth.Truth.assertThat+import com.streamvault.domain.model.Result+import org.junit.Test++class ProviderSetupInputValidatorImplTest {++ private val validator = ProviderSetupInputValidatorImpl()++ @Test+ fun `validateXtream rejects blank password for new providers`() {+ val result = validator.validateXtream(+ serverUrl = "https://example.com",+ username = "alice",+ password = "",+ allowBlankPassword = false,+ name = "Premium"+ )++ assertThat(result).isInstanceOf(Result.Error::class.java)+ assertThat((result as Result.Error).message).isEqualTo("Please enter password")+ }++ @Test+ fun `validateXtream allows blank password when editing existing providers`() {+ val result = validator.validateXtream(+ serverUrl = "https://example.com",+ username = "alice",+ password = "",+ allowBlankPassword = true,+ name = "Premium"+ )++ assertThat(result).isInstanceOf(Result.Success::class.java)+ assertThat((result as Result.Success).data.password).isEmpty()+ }++ @Test+ fun `validateXtream rejects control characters in password`() {+ val result = validator.validateXtream(+ serverUrl = "https://example.com",+ username = "alice",+ password = "sec\u0000ret",+ allowBlankPassword = false,+ name = "Premium"+ )++ assertThat(result).isInstanceOf(Result.Error::class.java)+ assertThat((result as Result.Error).message).isEqualTo("Password cannot contain control characters.")+ }++ // ── Stalker semantic validation ──────────────────────────────────────────++ private fun stalkerResult(+ timezone: String = "UTC",+ locale: String = "en",+ deviceProfile: String = "MAG250"+ ) = validator.validateStalker(+ portalUrl = "https://portal.example.com",+ macAddress = "00:1A:79:12:34:56",+ name = "MAG",+ deviceProfile = deviceProfile,+ timezone = timezone,+ locale = locale+ )++ @Test+ fun `validateStalker accepts blank optional fields and uses defaults`() {+ val result = stalkerResult(timezone = "", locale = "", deviceProfile = "")+ assertThat(result).isInstanceOf(Result.Success::class.java)+ }++ @Test+ fun `validateStalker accepts valid timezone`() {+ assertThat(stalkerResult(timezone = "America/New_York")).isInstanceOf(Result.Success::class.java)+ assertThat(stalkerResult(timezone = "Europe/London")).isInstanceOf(Result.Success::class.java)+ assertThat(stalkerResult(timezone = "UTC")).isInstanceOf(Result.Success::class.java)+ }++ @Test+ fun `validateStalker rejects unknown timezone identifier`() {+ val result = stalkerResult(timezone = "Not/ATimezone")+ assertThat(result).isInstanceOf(Result.Error::class.java)+ assertThat((result as Result.Error).message).contains("recognized")+ }++ @Test+ fun `validateStalker rejects timezone with semicolon that would break cookie header`() {+ // Cookie header: "timezone=<value>" — a semicolon splits into a new cookie pair.+ val result = stalkerResult(timezone = "UTC;injected=value")+ assertThat(result).isInstanceOf(Result.Error::class.java)+ assertThat((result as Result.Error).message).contains("characters that are not allowed")+ }++ @Test+ fun `validateStalker rejects timezone with comma that would break cookie header`() {+ val result = stalkerResult(timezone = "UTC,extra")+ assertThat(result).isInstanceOf(Result.Error::class.java)+ assertThat((result as Result.Error).message).contains("characters that are not allowed")+ }++ @Test+ fun `validateStalker accepts valid BCP-47 locale`() {+ assertThat(stalkerResult(locale = "en")).isInstanceOf(Result.Success::class.java)+ assertThat(stalkerResult(locale = "en-US")).isInstanceOf(Result.Success::class.java)+ assertThat(stalkerResult(locale = "fr")).isInstanceOf(Result.Success::class.java)+ assertThat(stalkerResult(locale = "zh-Hans")).isInstanceOf(Result.Success::class.java)+ }++ @Test+ fun `validateStalker rejects locale with semicolon that would break cookie header`() {+ val result = stalkerResult(locale = "en;injected=value")+ assertThat(result).isInstanceOf(Result.Error::class.java)+ assertThat((result as Result.Error).message).contains("language tag")+ }++ @Test+ fun `validateStalker rejects locale that does not match BCP-47 pattern`() {+ val result = stalkerResult(locale = "not a locale")+ assertThat(result).isInstanceOf(Result.Error::class.java)+ assertThat((result as Result.Error).message).contains("language tag")+ }++ @Test+ fun `validateStalker accepts valid device profile tokens`() {+ assertThat(stalkerResult(deviceProfile = "MAG250")).isInstanceOf(Result.Success::class.java)+ assertThat(stalkerResult(deviceProfile = "MAG254")).isInstanceOf(Result.Success::class.java)+ assertThat(stalkerResult(deviceProfile = "Model.X-1")).isInstanceOf(Result.Success::class.java)+ }++ @Test+ fun `validateStalker rejects device profile with semicolon that would break cookie header`() {+ val result = stalkerResult(deviceProfile = "MAG250;injected=evil")+ assertThat(result).isInstanceOf(Result.Error::class.java)+ assertThat((result as Result.Error).message).contains("Device profile must contain only")+ }++ @Test+ fun `validateStalker rejects device profile with spaces`() {+ val result = stalkerResult(deviceProfile = "MAG 250")+ assertThat(result).isInstanceOf(Result.Error::class.java)+ assertThat((result as Result.Error).message).contains("Device profile must contain only")+ }+}diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.mdindex f03b4768..9986bf84 100644--- a/docs/CHANGELOG.md+++ b/docs/CHANGELOG.md@@ -2,6 +2,54 @@All notable product changes are recorded in this document.+## [1.0.10] - 2026-05-02++### Added++- Added Import Backup to startup provider setup, so new installs can restore saved providers from a backup instead of entering provider details manually.++### Fixed++- Fixed favorites, recent live, and continue-watching provider scoping in all-providers mode.+- Fixed favorites persistence: partition-safe reorder, atomic move/merge, duplicate-safe global favorites, correct group counts.+- Fixed favorites screen empty-state so recent activity still appears when no favorites are saved.+- Fixed playback-history resume persistence keeping continue-watching and movie/episode progress current during active playback.+- Fixed provider onboarding completing with a warning instead of failing when saved providers have a failed initial sync.+- Fixed Xtream and M3U onboarding validation: rejects embedded credentials, safe playlist-to-Xtream conversion, shared password validation.+- Fixed Xtream Live TV categories showing zero items when providers only send category membership in `category_ids`.+- Hardened playback session lifecycle for main, preview, and multiview engines; fixed stream renewal/catch-up/rewind losing headers, stale quality selections, and needless full re-prepares on metadata-only route updates.+- Fixed live playback decoder startup crashes and Auto-mode stutter by preferring hardware first with one software fallback.+- Fixed several DVR lifecycle edge cases around recording promotion, foreground-service startup, handoff, and recovery.+- Fixed recording schedule backup/restore for padding, recurring rules, and partial import failures.+- Fixed reminder and recording scheduling: exact-alarm enforcement, stale suppression, alarm identity/cleanup, OS alarm cancel on provider delete.+- Fixed Android 13+ reminder and recording alert delivery by adding notification permission handling.+- Fixed backup import applying preferences before Room restore completed.+- Fixed movie and series filtered browse views returning drifted totals or broken paging.+- Fixed persistence guardrails: single active provider, cross-provider favorite group assignments rejected.+- Fixed Android TV app-shell re-entry for launcher and external navigation; rejected unsupported route payloads.+- Fixed Watch Next, launcher recommendations, and Live Channels staying aligned during provider switches and deletes.+- Fixed TV continue-watching and guide resilience: episode resume context preserved, Live Channels holds last-known-good rows during EPG gaps.+- Fixed search oversampling to 500 candidates before reranking so alphabetical SQL order no longer drops better matches.+- Fixed partial search failures showing as full empty state; sections now fail independently with a distinct "Search unavailable" notice.+- Fixed dashboard combined-profile VOD/health sourcing from a non-member provider.+- Fixed continue-watching in combined-profile mode now spanning all member providers.+- Fixed continue-watching and recommendations degrading silently to empty on transient IO failures; explicit degraded state shown instead.+- Fixed TV launcher recommendation channels being deleted on transient failures; channels preserved until a successful refresh confirms empty.+- Fixed TV launcher recommendations in combined-profile mode sourcing from a validated member, not the globally active provider.+- Fixed switching to a combined live profile not triggering a launcher recommendation refresh.+- Fixed provider delete requiring no confirmation; now requires explicit confirmation, is blocked while in-flight, and reports success/failure.+- Fixed active-provider switch writing preferences before the repository call succeeded.+- Fixed combined M3U profiles allowing activation with no enabled members and removal/disabling of the last enabled member while active.+- Fixed settings forms (combined M3U, EPG source add) dismissing before async operations complete; forms stay open with input intact on failure.+- Fixed backup import dialog allowing double-confirm in-flight and confirmation with all sections disabled; guard is now an atomic state transition.+- Fixed EPG source refresh only updating providers visible in the current settings session.+- Fixed EPG assignment observer jobs accumulating for deleted providers; cleaned up immediately on provider removal.+- Fixed recording storage settings (folder, pattern, retention, concurrency) racing on concurrent updates; writes serialized behind a mutex.+- Fixed privacy toggle rows firing twice from outer surface and inner Switch; Switch is now a passive indicator.+- Fixed internet speed test card allowing concurrent test runs.++---+## [1.0.9] - 2026-04-27### Addeddiff --git a/domain/src/main/java/com/streamvault/domain/manager/BackupManager.kt b/domain/src/main/java/com/streamvault/domain/manager/BackupManager.ktindex ba9a3477..4632eff0 100644--- a/domain/src/main/java/com/streamvault/domain/manager/BackupManager.kt+++ b/domain/src/main/java/com/streamvault/domain/manager/BackupManager.kt@@ -8,7 +8,7 @@ import kotlinx.coroutines.flow.Flowimport com.streamvault.domain.model.Resultdata class BackupData(- val version: Int = 5,+ val version: Int = 7,val checksum: String? = null,val preferences: Map<String, String>? = null,val providers: List<Provider>? = null,@@ -38,8 +38,13 @@ data class ScheduledRecordingBackup(val streamUrl: String,val scheduledStartMs: Long,val scheduledEndMs: Long,+ val requestedStartMs: Long? = null,+ val requestedEndMs: Long? = null,+ val paddingBeforeMs: Long? = null,+ val paddingAfterMs: Long? = null,val programTitle: String? = null,- val recurrence: RecordingRecurrence = RecordingRecurrence.NONE+ val recurrence: RecordingRecurrence = RecordingRecurrence.NONE,+ val recurringRuleId: String? = null)enum class BackupConflictStrategy {@@ -75,9 +80,49 @@ data class BackupImportPlan(val conflictStrategy: BackupConflictStrategy = BackupConflictStrategy.KEEP_EXISTING)+enum class RecordingScheduleImportDisposition {+ IMPORTED,+ REPLACED_EXISTING,+ SKIPPED_EXISTING,+ SKIPPED_EXPIRED,+ SKIPPED_MISSING_PROVIDER,+ FAILED+}++data class RecordingScheduleImportOutcome(+ val channelName: String,+ val programTitle: String? = null,+ val scheduledStartMs: Long,+ val scheduledEndMs: Long,+ val recurrence: RecordingRecurrence = RecordingRecurrence.NONE,+ val disposition: RecordingScheduleImportDisposition,+ val reason: String? = null+)++data class RecordingScheduleImportSummary(+ val outcomes: List<RecordingScheduleImportOutcome> = emptyList()+) {+ val importedCount: Int+ get() = outcomes.count {+ it.disposition == RecordingScheduleImportDisposition.IMPORTED ||+ it.disposition == RecordingScheduleImportDisposition.REPLACED_EXISTING+ }++ val skippedCount: Int+ get() = outcomes.count {+ it.disposition == RecordingScheduleImportDisposition.SKIPPED_EXISTING ||+ it.disposition == RecordingScheduleImportDisposition.SKIPPED_EXPIRED ||+ it.disposition == RecordingScheduleImportDisposition.SKIPPED_MISSING_PROVIDER+ }++ val failedCount: Int+ get() = outcomes.count { it.disposition == RecordingScheduleImportDisposition.FAILED }+}+data class BackupImportResult(val importedSections: List<String> = emptyList(),- val skippedSections: List<String> = emptyList()+ val skippedSections: List<String> = emptyList(),+ val recordingScheduleImport: RecordingScheduleImportSummary? = null)interface BackupManager {diff --git a/domain/src/main/java/com/streamvault/domain/manager/ProviderSetupInputValidator.kt b/domain/src/main/java/com/streamvault/domain/manager/ProviderSetupInputValidator.ktindex 11923db3..ca22e30f 100644--- a/domain/src/main/java/com/streamvault/domain/manager/ProviderSetupInputValidator.kt+++ b/domain/src/main/java/com/streamvault/domain/manager/ProviderSetupInputValidator.kt@@ -5,6 +5,7 @@ import com.streamvault.domain.model.Resultdata class ValidatedXtreamProviderInput(val serverUrl: String,val username: String,+ val password: String,val name: String)@@ -26,6 +27,8 @@ interface ProviderSetupInputValidator {fun validateXtream(serverUrl: String,username: String,+ password: String,+ allowBlankPassword: Boolean = false,name: String): Result<ValidatedXtreamProviderInput>diff --git a/domain/src/main/java/com/streamvault/domain/model/Provider.kt b/domain/src/main/java/com/streamvault/domain/model/Provider.ktindex 4898970b..af4e4c95 100644--- a/domain/src/main/java/com/streamvault/domain/model/Provider.kt+++ b/domain/src/main/java/com/streamvault/domain/model/Provider.kt@@ -55,3 +55,9 @@ enum class ProviderStatus {ERROR,UNKNOWN}++class ProviderSavedWithSyncErrorException(+ val provider: Provider,+ message: String,+ cause: Throwable? = null+) : Exception(message, cause)diff --git a/domain/src/main/java/com/streamvault/domain/model/SyncState.kt b/domain/src/main/java/com/streamvault/domain/model/SyncState.ktindex 4eaf8e91..118b9ada 100644--- a/domain/src/main/java/com/streamvault/domain/model/SyncState.kt+++ b/domain/src/main/java/com/streamvault/domain/model/SyncState.kt@@ -20,12 +20,17 @@ sealed class 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.+ * @param message Human-readable partial-sync summary.+ * @param warnings Detailed list of failed/skipped sub-operations.+ * @param hasRetryableEpgFailure True when the EPG portion failed due to a transient+ * network/IO condition that WorkManager backoff should+ * retry. Callers that only care about warnings may ignore+ * this flag.*/data class Partial(val message: String,val warnings: List<String> = emptyList(),+ val hasRetryableEpgFailure: Boolean = false,val timestamp: Long = System.currentTimeMillis()) : SyncState()diff --git a/domain/src/main/java/com/streamvault/domain/repository/FavoriteRepository.kt b/domain/src/main/java/com/streamvault/domain/repository/FavoriteRepository.ktindex 6ccfc78c..7dc7042b 100644--- a/domain/src/main/java/com/streamvault/domain/repository/FavoriteRepository.kt+++ b/domain/src/main/java/com/streamvault/domain/repository/FavoriteRepository.kt@@ -20,9 +20,18 @@ interface FavoriteRepository {fun getGlobalFavoriteCount(providerId: Long, contentType: ContentType): Flow<Int>fun getGroupFavoriteCounts(providerId: Long, contentType: ContentType): Flow<Map<Long, Int>>+ fun getGroupFavoriteCounts(providerIds: List<Long>, contentType: ContentType): Flow<Map<Long, Int>>suspend fun addFavorite(providerId: Long, contentId: Long, contentType: ContentType, groupId: Long? = null): Result<Unit>suspend fun removeFavorite(providerId: Long, contentId: Long, contentType: ContentType, groupId: Long? = null): Result<Unit>+ suspend fun moveFavoriteToGroup(+ providerId: Long,+ contentId: Long,+ contentType: ContentType,+ fromGroupId: Long?,+ targetGroupId: Long?+ ): Result<Unit>+ suspend fun mergeGroupInto(sourceGroupId: Long, targetGroupId: Long): Result<Unit>suspend fun reorderFavorites(favorites: List<Favorite>): Result<Unit>suspend fun isFavorite(providerId: Long, contentId: Long, contentType: ContentType): Booleandiff --git a/domain/src/main/java/com/streamvault/domain/repository/MovieRepository.kt b/domain/src/main/java/com/streamvault/domain/repository/MovieRepository.ktindex bbaff3ca..1e07d1c9 100644--- a/domain/src/main/java/com/streamvault/domain/repository/MovieRepository.kt+++ b/domain/src/main/java/com/streamvault/domain/repository/MovieRepository.kt@@ -28,6 +28,5 @@ interface MovieRepository {suspend fun getMovieDetails(providerId: Long, movieId: Long): Result<Movie>suspend fun getStreamInfo(movie: Movie): Result<StreamInfo>suspend fun refreshMovies(providerId: Long): Result<Unit>- suspend fun updateWatchProgress(movieId: Long, progress: Long): Result<Unit>suspend fun getWatchProgress(movieId: Long): Long? = null}diff --git a/domain/src/main/java/com/streamvault/domain/repository/PlaybackHistoryRepository.kt b/domain/src/main/java/com/streamvault/domain/repository/PlaybackHistoryRepository.ktindex b5bc8e8c..57fc00a8 100644--- a/domain/src/main/java/com/streamvault/domain/repository/PlaybackHistoryRepository.kt+++ b/domain/src/main/java/com/streamvault/domain/repository/PlaybackHistoryRepository.kt@@ -8,8 +8,16 @@ import kotlinx.coroutines.flow.Flowinterface PlaybackHistoryRepository {fun getRecentlyWatched(limit: Int = 100): Flow<List<PlaybackHistory>>fun getRecentlyWatchedByProvider(providerId: Long, limit: Int = 100): Flow<List<PlaybackHistory>>+ fun getRecentlyWatchedByProviders(providerIds: Set<Long>, limit: Int = 100): Flow<List<PlaybackHistory>>fun getUnwatchedCount(providerId: Long, seriesId: Long): Flow<Int>- suspend fun getPlaybackHistory(contentId: Long, contentType: ContentType, providerId: Long): PlaybackHistory?+ suspend fun getPlaybackHistory(+ contentId: Long,+ contentType: ContentType,+ providerId: Long,+ seriesId: Long? = null,+ seasonNumber: Int? = null,+ episodeNumber: Int? = null+ ): PlaybackHistory?suspend fun markAsWatched(history: PlaybackHistory): Result<Unit>suspend fun recordPlayback(history: PlaybackHistory): Result<Unit>diff --git a/domain/src/main/java/com/streamvault/domain/repository/ProviderRepository.kt b/domain/src/main/java/com/streamvault/domain/repository/ProviderRepository.ktindex 84482198..c28140fb 100644--- a/domain/src/main/java/com/streamvault/domain/repository/ProviderRepository.kt+++ b/domain/src/main/java/com/streamvault/domain/repository/ProviderRepository.kt@@ -19,8 +19,8 @@ interface ProviderRepository {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, xtreamFastSyncEnabled: Boolean, epgSyncMode: ProviderEpgSyncMode = ProviderEpgSyncMode.UPFRONT, onProgress: ((String) -> Unit)? = null, id: Long? = null): Result<Provider>- suspend fun validateM3u(url: String, name: String, epgSyncMode: ProviderEpgSyncMode = ProviderEpgSyncMode.UPFRONT, m3uVodClassificationEnabled: Boolean = false, onProgress: ((String) -> Unit)? = null, id: Long? = null): Result<Provider>+ suspend fun loginXtream(serverUrl: String, username: String, password: String, name: String, xtreamFastSyncEnabled: Boolean, epgSyncMode: ProviderEpgSyncMode = ProviderEpgSyncMode.BACKGROUND, onProgress: ((String) -> Unit)? = null, id: Long? = null): Result<Provider>+ suspend fun validateM3u(url: String, name: String, epgSyncMode: ProviderEpgSyncMode = ProviderEpgSyncMode.BACKGROUND, m3uVodClassificationEnabled: Boolean = false, onProgress: ((String) -> Unit)? = null, id: Long? = null): Result<Provider>suspend fun loginStalker(portalUrl: String,macAddress: String,@@ -28,7 +28,7 @@ interface ProviderRepository {deviceProfile: String = "",timezone: String = "",locale: String = "",- epgSyncMode: ProviderEpgSyncMode = ProviderEpgSyncMode.UPFRONT,+ epgSyncMode: ProviderEpgSyncMode = ProviderEpgSyncMode.BACKGROUND,onProgress: ((String) -> Unit)? = null,id: Long? = null): Result<Provider>diff --git a/domain/src/main/java/com/streamvault/domain/repository/SeriesRepository.kt b/domain/src/main/java/com/streamvault/domain/repository/SeriesRepository.ktindex 50a8cca7..9ba6fd15 100644--- a/domain/src/main/java/com/streamvault/domain/repository/SeriesRepository.kt+++ b/domain/src/main/java/com/streamvault/domain/repository/SeriesRepository.kt@@ -24,8 +24,8 @@ interface SeriesRepository {fun browseSeries(query: LibraryBrowseQuery): Flow<PagedResult<Series>>fun searchSeries(providerId: Long, query: String): Flow<List<Series>>suspend fun getSeriesById(seriesId: Long): Series?+ suspend fun getEpisodeById(episodeId: Long): Episode?suspend fun getSeriesDetails(providerId: Long, seriesId: Long): Result<Series>suspend fun getEpisodeStreamInfo(episode: Episode): Result<StreamInfo>suspend fun refreshSeries(providerId: Long): Result<Unit>- suspend fun updateEpisodeWatchProgress(episodeId: Long, progress: Long): Result<Unit>}diff --git a/domain/src/main/java/com/streamvault/domain/usecase/GetContinueWatching.kt b/domain/src/main/java/com/streamvault/domain/usecase/GetContinueWatching.ktindex 9a752f9b..ade8a6da 100644--- a/domain/src/main/java/com/streamvault/domain/usecase/GetContinueWatching.kt+++ b/domain/src/main/java/com/streamvault/domain/usecase/GetContinueWatching.kt@@ -8,6 +8,7 @@ import com.streamvault.domain.util.shouldRethrowDomainFlowFailureimport javax.inject.Injectimport kotlinx.coroutines.flow.Flowimport kotlinx.coroutines.flow.catch+import kotlinx.coroutines.flow.flowOfimport kotlinx.coroutines.flow.mapimport java.util.logging.Levelimport java.util.logging.Logger@@ -18,6 +19,11 @@ enum class ContinueWatchingScope {SERIES}+sealed class ContinueWatchingResult {+ data class Items(val items: List<PlaybackHistory>) : ContinueWatchingResult()+ data object Degraded : ContinueWatchingResult()+}+class GetContinueWatching @Inject constructor(private val playbackHistoryRepository: PlaybackHistoryRepository) {@@ -28,27 +34,61 @@ class GetContinueWatching @Inject constructor(limit: Int = 24,scope: ContinueWatchingScope = ContinueWatchingScope.ALL_VOD,requireResumePosition: Boolean = false- ): Flow<List<PlaybackHistory>> {- val upstreamLimit = maxOf(limit * 4, limit)- return playbackHistoryRepository.getRecentlyWatchedByProvider(providerId, upstreamLimit)- .map { history ->- history.asSequence()- .filter { entry -> scope.matches(entry.contentType) }- .filterNot { entry -> entry.isCompleted() }- .filter { entry -> !requireResumePosition || entry.isResumeEligible() }- .distinctBy(::continueWatchingKey)- .take(limit)- .toList()+ ): Flow<ContinueWatchingResult> = invoke(+ providerIds = setOf(providerId),+ limit = limit,+ scope = scope,+ requireResumePosition = requireResumePosition+ )++ operator fun invoke(+ providerIds: Set<Long>,+ limit: Int = 24,+ scope: ContinueWatchingScope = ContinueWatchingScope.ALL_VOD,+ requireResumePosition: Boolean = false+ ): Flow<ContinueWatchingResult> {+ val normalizedProviderIds = providerIds.filterTo(linkedSetOf()) { it > 0L }+ if (normalizedProviderIds.isEmpty()) {+ return flowOf(ContinueWatchingResult.Items(emptyList()))+ }++ val historyFlow = if (normalizedProviderIds.size == 1) {+ playbackHistoryRepository.getRecentlyWatchedByProvider(normalizedProviderIds.first(), limit)+ } else {+ playbackHistoryRepository.getRecentlyWatchedByProviders(normalizedProviderIds, limit)+ }++ return historyFlow+ .map<List<PlaybackHistory>, ContinueWatchingResult> { history ->+ ContinueWatchingResult.Items(+ history.toContinueWatching(+ limit = limit,+ scope = scope,+ requireResumePosition = requireResumePosition+ )+ )}.catch { error ->if (error.shouldRethrowDomainFlowFailure()) {throw error}logger.log(Level.WARNING, "Failed to build continue watching list", error)- emit(emptyList())+ emit(ContinueWatchingResult.Degraded)}}+ private fun List<PlaybackHistory>.toContinueWatching(+ limit: Int,+ scope: ContinueWatchingScope,+ requireResumePosition: Boolean+ ): List<PlaybackHistory> = asSequence()+ .filter { entry -> scope.matches(entry.contentType) }+ .filterNot { entry -> entry.isCompleted() }+ .filter { entry -> !requireResumePosition || entry.isResumeEligible() }+ .distinctBy(::continueWatchingKey)+ .take(limit)+ .toList()+private fun ContinueWatchingScope.matches(contentType: ContentType): Boolean = when (this) {ContinueWatchingScope.ALL_VOD -> contentType != ContentType.LIVEContinueWatchingScope.MOVIES -> contentType == ContentType.MOVIEdiff --git a/domain/src/main/java/com/streamvault/domain/usecase/GetRecommendations.kt b/domain/src/main/java/com/streamvault/domain/usecase/GetRecommendations.ktindex 7a89e7c6..ba5e1c83 100644--- a/domain/src/main/java/com/streamvault/domain/usecase/GetRecommendations.kt+++ b/domain/src/main/java/com/streamvault/domain/usecase/GetRecommendations.kt@@ -13,20 +13,25 @@ import kotlinx.coroutines.flow.flatMapLatestimport kotlinx.coroutines.flow.flowOfimport kotlinx.coroutines.flow.map+sealed class RecommendationsResult {+ data class Success(val movies: List<Movie>) : RecommendationsResult()+ data object Degraded : RecommendationsResult()+}+class GetRecommendations @Inject constructor(private val movieRepository: MovieRepository) {private val logger = Logger.getLogger("GetRecommendations")@OptIn(ExperimentalCoroutinesApi::class)- operator fun invoke(providerId: Long, limit: Int = 12): Flow<List<Movie>> {+ operator fun invoke(providerId: Long, limit: Int = 12): Flow<RecommendationsResult> {return movieRepository.getRecommendations(providerId, limit).flatMapLatest { recommended ->if (recommended.isNotEmpty()) {- flowOf(recommended.take(limit))+ flowOf(RecommendationsResult.Success(recommended.take(limit)) as RecommendationsResult)} else {movieRepository.getTopRatedPreview(providerId, limit)- .map { fallback -> fallback.take(limit) }+ .map { fallback -> RecommendationsResult.Success(fallback.take(limit)) }}}.catch { error ->@@ -34,7 +39,7 @@ class GetRecommendations @Inject constructor(throw error}logger.log(Level.WARNING, "Failed to load recommendations", error)- emit(emptyList())+ emit(RecommendationsResult.Degraded)}}}\ No newline at end of filediff --git a/domain/src/main/java/com/streamvault/domain/usecase/ImportBackup.kt b/domain/src/main/java/com/streamvault/domain/usecase/ImportBackup.ktindex f467c2ef..e460b93e 100644--- a/domain/src/main/java/com/streamvault/domain/usecase/ImportBackup.kt+++ b/domain/src/main/java/com/streamvault/domain/usecase/ImportBackup.kt@@ -29,7 +29,17 @@ sealed class InspectBackupResult {sealed class ImportBackupResult {data class Success(val result: BackupImportResult) : ImportBackupResult() {val importedSummary: String- get() = result.importedSections.joinToString().ifBlank { "Nothing imported" }+ get() {+ val baseSummary = result.importedSections.joinToString().ifBlank { "Nothing imported" }+ val recordingSummary = result.recordingScheduleImport+ ?.takeIf { it.failedCount > 0 || it.skippedCount > 0 }+ ?.let { summary ->+ "Recording schedules: ${summary.importedCount} imported, ${summary.skippedCount} skipped, ${summary.failedCount} failed"+ }+ return listOf(baseSummary, recordingSummary)+ .filterNotNull()+ .joinToString(separator = ". ")+ }}data class Error(val message: String, val exception: Throwable? = null) : ImportBackupResult()diff --git a/domain/src/main/java/com/streamvault/domain/usecase/SearchContent.kt b/domain/src/main/java/com/streamvault/domain/usecase/SearchContent.ktindex b18d69bb..f9a8a30c 100644--- a/domain/src/main/java/com/streamvault/domain/usecase/SearchContent.kt+++ b/domain/src/main/java/com/streamvault/domain/usecase/SearchContent.kt@@ -14,6 +14,7 @@ import kotlinx.coroutines.flow.Flowimport kotlinx.coroutines.flow.catchimport kotlinx.coroutines.flow.combineimport kotlinx.coroutines.flow.flowOf+import kotlinx.coroutines.flow.mapenum class SearchContentScope {ALL,@@ -25,7 +26,8 @@ enum class SearchContentScope {data class SearchContentResult(val channels: List<Channel> = emptyList(),val movies: List<Movie> = emptyList(),- val series: List<Series> = emptyList()+ val series: List<Series> = emptyList(),+ val isPartialResult: Boolean = false)class SearchContent @Inject constructor(@@ -49,31 +51,44 @@ class SearchContent @Inject constructor(return combine(if (scope == SearchContentScope.ALL || scope == SearchContentScope.LIVE) {channelRepository.searchChannels(providerId, normalizedQuery)+ .map { it to false }+ .catch { error ->+ if (error.shouldRethrowDomainFlowFailure()) throw error+ logger.log(Level.WARNING, "Channel search section failed", error)+ emit(emptyList<Channel>() to true)+ }} else {- flowOf(emptyList())+ flowOf(emptyList<Channel>() to false)},if (scope == SearchContentScope.ALL || scope == SearchContentScope.MOVIES) {movieRepository.searchMovies(providerId, normalizedQuery)+ .map { it to false }+ .catch { error ->+ if (error.shouldRethrowDomainFlowFailure()) throw error+ logger.log(Level.WARNING, "Movie search section failed", error)+ emit(emptyList<Movie>() to true)+ }} else {- flowOf(emptyList())+ flowOf(emptyList<Movie>() to false)},if (scope == SearchContentScope.ALL || scope == SearchContentScope.SERIES) {seriesRepository.searchSeries(providerId, normalizedQuery)+ .map { it to false }+ .catch { error ->+ if (error.shouldRethrowDomainFlowFailure()) throw error+ logger.log(Level.WARNING, "Series search section failed", error)+ emit(emptyList<Series>() to true)+ }} else {- flowOf(emptyList())+ flowOf(emptyList<Series>() to false)}- ) { channels, movies, series ->+ ) { (channels, channelsDegraded), (movies, moviesDegraded), (series, seriesDegraded) ->SearchContentResult(channels = channels.take(maxResultsPerSection),movies = movies.take(maxResultsPerSection),- series = series.take(maxResultsPerSection)+ series = series.take(maxResultsPerSection),+ isPartialResult = channelsDegraded || moviesDegraded || seriesDegraded)- }.catch { error ->- if (error.shouldRethrowDomainFlowFailure()) {- throw error- }- logger.log(Level.WARNING, "Failed to build search results", error)- emit(SearchContentResult())}}}\ No newline at end of filediff --git a/domain/src/main/java/com/streamvault/domain/usecase/ValidateAndAddProvider.kt b/domain/src/main/java/com/streamvault/domain/usecase/ValidateAndAddProvider.ktindex bd250950..eae33f56 100644--- a/domain/src/main/java/com/streamvault/domain/usecase/ValidateAndAddProvider.kt+++ b/domain/src/main/java/com/streamvault/domain/usecase/ValidateAndAddProvider.kt@@ -3,6 +3,7 @@ package com.streamvault.domain.usecaseimport com.streamvault.domain.manager.ProviderSetupInputValidatorimport com.streamvault.domain.model.Providerimport com.streamvault.domain.model.ProviderEpgSyncMode+import com.streamvault.domain.model.ProviderSavedWithSyncErrorExceptionimport com.streamvault.domain.model.Resultimport com.streamvault.domain.repository.ProviderRepositoryimport java.net.URI@@ -41,6 +42,7 @@ data class StalkerProviderSetupCommand(sealed class ValidateAndAddProviderResult {data class Success(val provider: Provider) : ValidateAndAddProviderResult()+ data class SavedWithWarning(val provider: Provider, val warning: String) : ValidateAndAddProviderResult()data class ValidationError(val message: String) : ValidateAndAddProviderResult()data class Error(val message: String, val exception: Throwable? = null) : ValidateAndAddProviderResult()}@@ -54,6 +56,64 @@ class ValidateAndAddProvider @Inject constructor(private const val MAX_XTREAM_PLAYLIST_PASSWORD_LENGTH = 256}+ /**+ * Performs local input validation only — no network calls, no persistence, no side effects.+ * Returns the [ValidateAndAddProviderResult.ValidationError] if the input is invalid, or+ * `null` if the input passed all local checks and is ready for [loginXtream].+ */+ fun validateXtreamInput(command: XtreamProviderSetupCommand): ValidateAndAddProviderResult.ValidationError? {+ return when (+ val result = providerSetupInputValidator.validateXtream(+ serverUrl = command.serverUrl,+ username = command.username,+ password = command.password,+ allowBlankPassword = command.existingProviderId != null,+ name = command.name+ )+ ) {+ is Result.Error -> ValidateAndAddProviderResult.ValidationError(result.message)+ else -> null+ }+ }++ /**+ * Performs local input validation only — no network calls, no persistence, no side effects.+ * Returns the [ValidateAndAddProviderResult.ValidationError] if the input is invalid, or+ * `null` if the input passed all local checks and is ready for [addM3u].+ */+ fun validateM3uInput(command: M3uProviderSetupCommand): ValidateAndAddProviderResult.ValidationError? {+ return when (+ val result = providerSetupInputValidator.validateM3u(+ url = command.url,+ name = command.name+ )+ ) {+ is Result.Error -> ValidateAndAddProviderResult.ValidationError(result.message)+ else -> null+ }+ }++ /**+ * Performs local input validation only — no network calls, no persistence, no side effects.+ * Returns the [ValidateAndAddProviderResult.ValidationError] if the input is invalid, or+ * `null` if the input passed all local checks and is ready for [loginStalker].+ */+ fun validateStalkerInput(command: StalkerProviderSetupCommand): ValidateAndAddProviderResult.ValidationError? {+ return when (+ val result = providerSetupInputValidator.validateStalker(+ portalUrl = command.portalUrl,+ macAddress = command.macAddress,+ name = command.name,+ deviceProfile = command.deviceProfile,+ timezone = command.timezone,+ locale = command.locale+ )+ ) {+ is Result.Error -> ValidateAndAddProviderResult.ValidationError(result.message)+ else -> null+ }+ }+suspend fun loginXtream(command: XtreamProviderSetupCommand,onProgress: ((String) -> Unit)? = null@@ -62,13 +122,15 @@ class ValidateAndAddProvider @Inject constructor(val validated = providerSetupInputValidator.validateXtream(serverUrl = command.serverUrl,username = command.username,+ password = command.password,+ allowBlankPassword = command.existingProviderId != null,name = command.name)) {is Result.Success -> providerRepository.loginXtream(serverUrl = validated.data.serverUrl,username = validated.data.username,- password = command.password,+ password = validated.data.password,name = validated.data.name,xtreamFastSyncEnabled = command.xtreamFastSyncEnabled,epgSyncMode = command.epgSyncMode,@@ -161,7 +223,17 @@ class ValidateAndAddProvider @Inject constructor(private fun Result<Provider>.toUseCaseResult(): ValidateAndAddProviderResult = when (this) {is Result.Success -> ValidateAndAddProviderResult.Success(data)- is Result.Error -> ValidateAndAddProviderResult.Error(message, exception)+ is Result.Error -> {+ val savedWithWarning = exception as? ProviderSavedWithSyncErrorException+ if (savedWithWarning != null) {+ ValidateAndAddProviderResult.SavedWithWarning(+ provider = savedWithWarning.provider,+ warning = savedWithWarning.message ?: message+ )+ } else {+ ValidateAndAddProviderResult.Error(message, exception)+ }+ }is Result.Loading -> ValidateAndAddProviderResult.Error("Unexpected loading state")}@@ -199,8 +271,21 @@ class ValidateAndAddProvider @Inject constructor(return ParsedXtreamPlaylistUrlResult.ValidationError("Playlist password is too long.")}- val authority = uri.rawAuthority?.takeIf { it.isNotBlank() }- ?: return ParsedXtreamPlaylistUrlResult.NotXtreamPlaylist+ if (!uri.userInfo.isNullOrBlank()) {+ return ParsedXtreamPlaylistUrlResult.ValidationError(+ "Playlist sources must not include embedded credentials in the URL authority."+ )+ }++ val host = uri.host?.takeIf { it.isNotBlank() }+ ?: return ParsedXtreamPlaylistUrlResult.ValidationError("Playlist sources must include a host.")+ val authority = buildString {+ append(host.asXtreamServerHost())+ if (uri.port != -1) {+ append(":")+ append(uri.port)+ }+ }return ParsedXtreamPlaylistUrlResult.Success(serverUrl = "$scheme://$authority",username = username,@@ -223,4 +308,7 @@ class ValidateAndAddProvider @Inject constructor(private fun decodeQueryComponent(value: String): String =URLDecoder.decode(value, StandardCharsets.UTF_8.name())++ private fun String.asXtreamServerHost(): String =+ if (contains(':') && !startsWith("[")) "[$this]" else this}diff --git a/domain/src/test/java/com/streamvault/domain/usecase/GetContinueWatchingTest.kt b/domain/src/test/java/com/streamvault/domain/usecase/GetContinueWatchingTest.ktindex 41e3cae8..b92ba205 100644--- a/domain/src/test/java/com/streamvault/domain/usecase/GetContinueWatchingTest.kt+++ b/domain/src/test/java/com/streamvault/domain/usecase/GetContinueWatchingTest.kt@@ -4,6 +4,7 @@ import com.google.common.truth.Truth.assertThatimport com.streamvault.domain.model.ContentTypeimport com.streamvault.domain.model.PlaybackHistoryimport com.streamvault.domain.repository.PlaybackHistoryRepository+import java.io.IOExceptionimport kotlinx.coroutines.flow.Flowimport kotlinx.coroutines.flow.firstimport kotlinx.coroutines.flow.flow@@ -66,6 +67,61 @@ class GetContinueWatchingTest {assertThat(result.map { it.contentId }).containsExactly(2L, 4L).inOrder()}+ @Test+ fun aggregates_selected_provider_ids_only() = runTest {+ val useCase = GetContinueWatching(+ playbackHistoryRepository = FakePlaybackHistoryRepository(+ history = listOf(+ history(contentId = 20L, type = ContentType.SERIES_EPISODE, providerId = 2L, seriesId = 5L, lastWatchedAt = 300L, resumePositionMs = 15_000L),+ history(contentId = 10L, type = ContentType.MOVIE, providerId = 1L, lastWatchedAt = 200L, resumePositionMs = 12_000L),+ history(contentId = 30L, type = ContentType.MOVIE, providerId = 3L, lastWatchedAt = 100L, resumePositionMs = 9_000L)+ )+ )+ )++ val result = useCase(setOf(1L, 2L), limit = 5).collectOnce()++ assertThat(result.map { it.providerId to it.contentId }).containsExactly(+ 2L to 20L,+ 1L to 10L+ ).inOrder()+ }++ @Test+ fun multi_provider_requests_use_provider_set_repository_path() = runTest {+ val repository = FakePlaybackHistoryRepository(+ history = listOf(+ history(contentId = 99L, type = ContentType.MOVIE, providerId = 99L, lastWatchedAt = 500L, resumePositionMs = 12_000L)+ ),+ multiProviderHistory = listOf(+ history(contentId = 20L, type = ContentType.SERIES_EPISODE, providerId = 2L, seriesId = 5L, lastWatchedAt = 300L, resumePositionMs = 15_000L),+ history(contentId = 10L, type = ContentType.MOVIE, providerId = 1L, lastWatchedAt = 200L, resumePositionMs = 12_000L)+ )+ )+ val useCase = GetContinueWatching(playbackHistoryRepository = repository)++ val result = useCase(setOf(1L, 2L), limit = 5).collectOnce()++ assertThat(result.map { it.providerId to it.contentId }).containsExactly(+ 2L to 20L,+ 1L to 10L+ ).inOrder()+ assertThat(repository.lastRequestedProviderIds).containsExactly(1L, 2L)+ }++ @Test+ fun returns_degraded_on_recoverable_io_failure() = runTest {+ val useCase = GetContinueWatching(+ playbackHistoryRepository = FakePlaybackHistoryRepository(+ historyFlow = flow { throw IOException("network failure") }+ )+ )++ val result = useCase(providerId = 1L).first()++ assertThat(result).isEqualTo(ContinueWatchingResult.Degraded)+ }+@Testfun rethrows_non_io_upstream_failures() = runTest {val expected = IllegalStateException("database broken")@@ -86,18 +142,23 @@ class GetContinueWatchingTest {assertThat(thrown?.message).isEqualTo(expected.message)}- private suspend fun Flow<List<PlaybackHistory>>.collectOnce(): List<PlaybackHistory> = first()+ private suspend fun Flow<ContinueWatchingResult>.collectOnce(): List<PlaybackHistory> =+ first().let { result ->+ check(result is ContinueWatchingResult.Items) { "Expected Items but got $result" }+ result.items+ }private fun history(contentId: Long,type: ContentType,+ providerId: Long = 1L,seriesId: Long? = null,lastWatchedAt: Long,resumePositionMs: Long) = PlaybackHistory(contentId = contentId,contentType = type,- providerId = 1L,+ providerId = providerId,title = "$type-$contentId",streamUrl = "https://example.com/$contentId",resumePositionMs = resumePositionMs,@@ -108,10 +169,18 @@ class GetContinueWatchingTest {private class FakePlaybackHistoryRepository(private val history: List<PlaybackHistory> = emptyList(),+ private val multiProviderHistory: List<PlaybackHistory> = history,private val historyFlow: Flow<List<PlaybackHistory>>? = null) : PlaybackHistoryRepository {+ var lastRequestedProviderIds: Set<Long>? = null+override fun getRecentlyWatched(limit: Int): Flow<List<PlaybackHistory>> = historyFlow ?: flowOf(history.take(limit))- override fun getRecentlyWatchedByProvider(providerId: Long, limit: Int): Flow<List<PlaybackHistory>> = historyFlow ?: flowOf(history.take(limit))+ override fun getRecentlyWatchedByProvider(providerId: Long, limit: Int): Flow<List<PlaybackHistory>> =+ historyFlow ?: flowOf(history.filter { it.providerId == providerId }.take(limit))+ override fun getRecentlyWatchedByProviders(providerIds: Set<Long>, limit: Int): Flow<List<PlaybackHistory>> {+ lastRequestedProviderIds = providerIds+ return historyFlow ?: flowOf(multiProviderHistory.filter { it.providerId in providerIds }.take(limit))+ }override fun getUnwatchedCount(providerId: Long, seriesId: Long): Flow<Int> = flowOf(0)override suspend fun getPlaybackHistory(contentId: Long, contentType: ContentType, providerId: Long): PlaybackHistory? = nulloverride suspend fun markAsWatched(history: PlaybackHistory) = com.streamvault.domain.model.Result.success(Unit)diff --git a/domain/src/test/java/com/streamvault/domain/usecase/GetCustomCategoriesTest.kt b/domain/src/test/java/com/streamvault/domain/usecase/GetCustomCategoriesTest.ktindex 9db71aab..fc717310 100644--- a/domain/src/test/java/com/streamvault/domain/usecase/GetCustomCategoriesTest.kt+++ b/domain/src/test/java/com/streamvault/domain/usecase/GetCustomCategoriesTest.kt@@ -82,12 +82,26 @@ class GetCustomCategoriesTest {override fun getGroupFavoriteCounts(providerId: Long, contentType: ContentType): Flow<Map<Long, Int>> =error("Not used in test")+ override fun getGroupFavoriteCounts(providerIds: List<Long>, contentType: ContentType): Flow<Map<Long, Int>> =+ error("Not used in test")+override suspend fun addFavorite(providerId: Long, contentId: Long, contentType: ContentType, groupId: Long?) =error("Not used in test")override suspend fun removeFavorite(providerId: Long, contentId: Long, contentType: ContentType, groupId: Long?) =error("Not used in test")+ override suspend fun moveFavoriteToGroup(+ providerId: Long,+ contentId: Long,+ contentType: ContentType,+ fromGroupId: Long?,+ targetGroupId: Long?+ ) = error("Not used in test")++ override suspend fun mergeGroupInto(sourceGroupId: Long, targetGroupId: Long) =+ error("Not used in test")+override suspend fun reorderFavorites(favorites: List<Favorite>) = error("Not used in test")override suspend fun isFavorite(providerId: Long, contentId: Long, contentType: ContentType): Boolean =diff --git a/domain/src/test/java/com/streamvault/domain/usecase/GetRecommendationsTest.kt b/domain/src/test/java/com/streamvault/domain/usecase/GetRecommendationsTest.ktindex 6050ce9e..8332cc8d 100644--- a/domain/src/test/java/com/streamvault/domain/usecase/GetRecommendationsTest.kt+++ b/domain/src/test/java/com/streamvault/domain/usecase/GetRecommendationsTest.kt@@ -14,6 +14,7 @@ import kotlinx.coroutines.flow.flowimport kotlinx.coroutines.flow.flowOfimport kotlinx.coroutines.test.runTestimport org.junit.Test+import java.io.IOExceptionclass GetRecommendationsTest {@@ -31,7 +32,9 @@ class GetRecommendationsTest {val result = useCase(providerId = 7L, limit = 2).first()- assertThat(result.map(Movie::id)).containsExactly(1L, 2L).inOrder()+ assertThat(result).isInstanceOf(RecommendationsResult.Success::class.java)+ assertThat((result as RecommendationsResult.Success).movies.map(Movie::id))+ .containsExactly(1L, 2L).inOrder()}@Test@@ -48,7 +51,9 @@ class GetRecommendationsTest {val result = useCase(providerId = 7L, limit = 2).first()- assertThat(result.map(Movie::id)).containsExactly(10L, 11L).inOrder()+ assertThat(result).isInstanceOf(RecommendationsResult.Success::class.java)+ assertThat((result as RecommendationsResult.Success).movies.map(Movie::id))+ .containsExactly(10L, 11L).inOrder()}@Test@@ -73,6 +78,21 @@ class GetRecommendationsTest {assertThat(thrown?.message).isEqualTo(expected.message)}+ @Test+ fun returns_degraded_on_io_failure() = runTest {+ val useCase = GetRecommendations(+ movieRepository = FakeMovieRepository(+ recommendations = emptyList(),+ topRated = emptyList(),+ recommendationsFlow = flow { throw IOException("network failure") }+ )+ )++ val result = useCase(providerId = 7L, limit = 2).first()++ assertThat(result).isEqualTo(RecommendationsResult.Degraded)+ }+private class FakeMovieRepository(private val recommendations: List<Movie>,private val topRated: List<Movie>,@@ -99,7 +119,6 @@ class GetRecommendationsTest {override suspend fun getMovieDetails(providerId: Long, movieId: Long): Result<Movie> = error("Not used in test")override suspend fun getStreamInfo(movie: Movie): Result<StreamInfo> = error("Not used in test")override suspend fun refreshMovies(providerId: Long): Result<Unit> = error("Not used in test")- override suspend fun updateWatchProgress(movieId: Long, progress: Long): Result<Unit> = error("Not used in test")private fun <T> unsupported(): Flow<T> = error("Not used in test")}diff --git a/domain/src/test/java/com/streamvault/domain/usecase/ImportBackupTest.kt b/domain/src/test/java/com/streamvault/domain/usecase/ImportBackupTest.ktindex 666d17f0..ac749b00 100644--- a/domain/src/test/java/com/streamvault/domain/usecase/ImportBackupTest.kt+++ b/domain/src/test/java/com/streamvault/domain/usecase/ImportBackupTest.kt@@ -5,6 +5,9 @@ import com.streamvault.domain.manager.BackupConflictStrategyimport com.streamvault.domain.manager.BackupImportPlanimport com.streamvault.domain.manager.BackupImportResultimport com.streamvault.domain.manager.BackupPreview+import com.streamvault.domain.manager.RecordingScheduleImportDisposition+import com.streamvault.domain.manager.RecordingScheduleImportOutcome+import com.streamvault.domain.manager.RecordingScheduleImportSummaryimport com.streamvault.domain.model.Resultimport kotlinx.coroutines.test.runTestimport org.junit.Test@@ -77,6 +80,44 @@ class ImportBackupTest {assertThat(result).isInstanceOf(ImportBackupResult.Error::class.java)assertThat((result as ImportBackupResult.Error).message).isEqualTo("Backup source is unavailable.")}++ @Test+ fun import_summary_includes_recording_schedule_failures() = runTest {+ val manager = FakeImportBackupManager(+ importResult = Result.success(+ BackupImportResult(+ importedSections = listOf("Providers", "Recording Schedules"),+ recordingScheduleImport = RecordingScheduleImportSummary(+ outcomes = listOf(+ RecordingScheduleImportOutcome(+ channelName = "BBC One",+ programTitle = "World News",+ scheduledStartMs = 1_000L,+ scheduledEndMs = 2_000L,+ disposition = RecordingScheduleImportDisposition.REPLACED_EXISTING+ ),+ RecordingScheduleImportOutcome(+ channelName = "BBC Two",+ programTitle = "Documentary",+ scheduledStartMs = 3_000L,+ scheduledEndMs = 4_000L,+ disposition = RecordingScheduleImportDisposition.FAILED,+ reason = "Provider connection limit reached."+ )+ )+ )+ )+ )+ )+ val useCase = ImportBackup(manager)++ val result = useCase.confirm(ImportBackupCommand(uriString = "content://backup.json"))++ assertThat(result).isInstanceOf(ImportBackupResult.Success::class.java)+ val success = result as ImportBackupResult.Success+ assertThat(success.importedSummary)+ .isEqualTo("Providers, Recording Schedules. Recording schedules: 1 imported, 0 skipped, 1 failed")+ }}private class FakeImportBackupManager(diff --git a/domain/src/test/java/com/streamvault/domain/usecase/MarkAsWatchedTest.kt b/domain/src/test/java/com/streamvault/domain/usecase/MarkAsWatchedTest.ktindex 8e025267..2614f744 100644--- a/domain/src/test/java/com/streamvault/domain/usecase/MarkAsWatchedTest.kt+++ b/domain/src/test/java/com/streamvault/domain/usecase/MarkAsWatchedTest.kt@@ -50,6 +50,7 @@ class MarkAsWatchedTest {override fun getRecentlyWatched(limit: Int): Flow<List<PlaybackHistory>> = flowOf(emptyList())override fun getRecentlyWatchedByProvider(providerId: Long, limit: Int): Flow<List<PlaybackHistory>> = flowOf(emptyList())+ override fun getRecentlyWatchedByProviders(providerIds: Set<Long>, limit: Int): Flow<List<PlaybackHistory>> = flowOf(emptyList())override fun getUnwatchedCount(providerId: Long, seriesId: Long): Flow<Int> = flowOf(0)override suspend fun getPlaybackHistory(contentId: Long, contentType: ContentType, providerId: Long): PlaybackHistory? = nulloverride suspend fun markAsWatched(history: PlaybackHistory): com.streamvault.domain.model.Result<Unit> {diff --git a/domain/src/test/java/com/streamvault/domain/usecase/SearchContentTest.kt b/domain/src/test/java/com/streamvault/domain/usecase/SearchContentTest.ktindex e2210c24..0645eefb 100644--- a/domain/src/test/java/com/streamvault/domain/usecase/SearchContentTest.kt+++ b/domain/src/test/java/com/streamvault/domain/usecase/SearchContentTest.kt@@ -160,7 +160,6 @@ private class FakeMovieRepository(override suspend fun getMovieDetails(providerId: Long, movieId: Long): Result<Movie> = error("Not used in test")override suspend fun getStreamInfo(movie: Movie): Result<StreamInfo> = error("Not used in test")override suspend fun refreshMovies(providerId: Long): Result<Unit> = error("Not used in test")- override suspend fun updateWatchProgress(movieId: Long, progress: Long): Result<Unit> = error("Not used in test")}private class FakeSeriesRepository(@@ -184,7 +183,6 @@ private class FakeSeriesRepository(override suspend fun getSeriesDetails(providerId: Long, seriesId: Long): Result<Series> = error("Not used in test")override suspend fun getEpisodeStreamInfo(episode: com.streamvault.domain.model.Episode): Result<StreamInfo> = error("Not used in test")override suspend fun refreshSeries(providerId: Long): Result<Unit> = error("Not used in test")- override suspend fun updateEpisodeWatchProgress(episodeId: Long, progress: Long): Result<Unit> = error("Not used in test")}private fun <T> unsupported(): Flow<T> = error("Not used in test")diff --git a/domain/src/test/java/com/streamvault/domain/usecase/ValidateAndAddProviderTest.kt b/domain/src/test/java/com/streamvault/domain/usecase/ValidateAndAddProviderTest.ktindex 32e5d9f8..2eb96bef 100644--- a/domain/src/test/java/com/streamvault/domain/usecase/ValidateAndAddProviderTest.kt+++ b/domain/src/test/java/com/streamvault/domain/usecase/ValidateAndAddProviderTest.kt@@ -8,6 +8,7 @@ import com.streamvault.domain.manager.ValidatedStalkerProviderInputimport com.streamvault.domain.manager.ValidatedXtreamProviderInputimport com.streamvault.domain.model.ProviderEpgSyncModeimport com.streamvault.domain.model.Provider+import com.streamvault.domain.model.ProviderSavedWithSyncErrorExceptionimport com.streamvault.domain.model.ProviderStatusimport com.streamvault.domain.model.ProviderTypeimport com.streamvault.domain.model.Result@@ -19,6 +20,113 @@ import org.junit.Testclass ValidateAndAddProviderTest {+ @Test+ fun `validateXtreamInput returns null when input is valid without calling repository`() {+ val repository = FakeProviderRepository()+ val useCase = ValidateAndAddProvider(+ providerSetupInputValidator = FakeProviderSetupInputValidator(),+ providerRepository = repository+ )++ val error = useCase.validateXtreamInput(+ XtreamProviderSetupCommand(serverUrl = "https://example.com", username = "alice", password = "secret", name = "Provider")+ )++ assertThat(error).isNull()+ assertThat(repository.lastXtreamCall).isNull()+ }++ @Test+ fun `validateXtreamInput returns ValidationError without calling repository`() {+ val repository = FakeProviderRepository()+ val useCase = ValidateAndAddProvider(+ providerSetupInputValidator = FakeProviderSetupInputValidator(+ xtreamResult = Result.error("Please enter server URL")+ ),+ providerRepository = repository+ )++ val error = useCase.validateXtreamInput(+ XtreamProviderSetupCommand(serverUrl = "", username = "alice", password = "secret", name = "Provider")+ )++ assertThat(error).isInstanceOf(ValidateAndAddProviderResult.ValidationError::class.java)+ assertThat((error as ValidateAndAddProviderResult.ValidationError).message).isEqualTo("Please enter server URL")+ assertThat(repository.lastXtreamCall).isNull()+ }++ @Test+ fun `validateM3uInput returns null when input is valid without calling repository`() {+ val repository = FakeProviderRepository()+ val useCase = ValidateAndAddProvider(+ providerSetupInputValidator = FakeProviderSetupInputValidator(),+ providerRepository = repository+ )++ val error = useCase.validateM3uInput(+ M3uProviderSetupCommand(url = "https://example.com/list.m3u", name = "Playlist")+ )++ assertThat(error).isNull()+ assertThat(repository.lastM3uCall).isNull()+ }++ @Test+ fun `validateM3uInput returns ValidationError without calling repository`() {+ val repository = FakeProviderRepository()+ val useCase = ValidateAndAddProvider(+ providerSetupInputValidator = FakeProviderSetupInputValidator(+ m3uResult = Result.error("Please enter M3U URL")+ ),+ providerRepository = repository+ )++ val error = useCase.validateM3uInput(+ M3uProviderSetupCommand(url = "", name = "Playlist")+ )++ assertThat(error).isInstanceOf(ValidateAndAddProviderResult.ValidationError::class.java)+ assertThat(repository.lastM3uCall).isNull()+ }++ @Test+ fun `validateStalkerInput returns null when input is valid without calling repository`() {+ val repository = FakeProviderRepository()+ val useCase = ValidateAndAddProvider(+ providerSetupInputValidator = FakeProviderSetupInputValidator(),+ providerRepository = repository+ )++ val error = useCase.validateStalkerInput(+ StalkerProviderSetupCommand(+ portalUrl = "https://portal.example.com",+ macAddress = "00:1A:79:12:34:56",+ name = "MAG"+ )+ )++ assertThat(error).isNull()+ assertThat(repository.lastStalkerCall).isNull()+ }++ @Test+ fun `validateStalkerInput returns ValidationError without calling repository`() {+ val repository = FakeProviderRepository()+ val useCase = ValidateAndAddProvider(+ providerSetupInputValidator = FakeProviderSetupInputValidator(+ stalkerResult = Result.error("Please enter portal URL")+ ),+ providerRepository = repository+ )++ val error = useCase.validateStalkerInput(+ StalkerProviderSetupCommand(portalUrl = "", macAddress = "00:1A:79:12:34:56", name = "MAG")+ )++ assertThat(error).isInstanceOf(ValidateAndAddProviderResult.ValidationError::class.java)+ assertThat(repository.lastStalkerCall).isNull()+ }+@Testfun returns_validation_error_without_calling_repository_for_xtream() = runTest {val repository = FakeProviderRepository()@@ -52,6 +160,7 @@ class ValidateAndAddProviderTest {ValidatedXtreamProviderInput(serverUrl = "https://example.com",username = "alice",+ password = "normalized-secret",name = "Premium"))@@ -63,7 +172,7 @@ class ValidateAndAddProviderTest {XtreamProviderSetupCommand(serverUrl = " https://example.com ",username = " alice ",- password = "secret",+ password = "secret\u0000",name = " Premium ",xtreamFastSyncEnabled = true,epgSyncMode = ProviderEpgSyncMode.BACKGROUND,@@ -76,7 +185,7 @@ class ValidateAndAddProviderTest {XtreamCall(serverUrl = "https://example.com",username = "alice",- password = "secret",+ password = "normalized-secret",name = "Premium",xtreamFastSyncEnabled = true,epgSyncMode = ProviderEpgSyncMode.BACKGROUND,@@ -85,6 +194,69 @@ class ValidateAndAddProviderTest {)}+ @Test+ fun allows_blank_xtream_password_when_editing_existing_provider() = runTest {+ val repository = FakeProviderRepository()+ val useCase = ValidateAndAddProvider(+ providerSetupInputValidator = FakeProviderSetupInputValidator(+ xtreamResult = Result.success(+ ValidatedXtreamProviderInput(+ serverUrl = "https://example.com",+ username = "alice",+ password = "",+ name = "Premium"+ )+ )+ ),+ providerRepository = repository+ )++ val result = useCase.loginXtream(+ XtreamProviderSetupCommand(+ serverUrl = "https://example.com",+ username = "alice",+ password = "",+ name = "Premium",+ existingProviderId = 7L+ )+ )++ assertThat(result).isInstanceOf(ValidateAndAddProviderResult.Success::class.java)+ assertThat(repository.lastXtreamCall?.password).isEmpty()+ }++ @Test+ fun maps_saved_provider_sync_failure_to_saved_with_warning() = runTest {+ val repository = FakeProviderRepository().apply {+ xtreamResult = Result.error(+ "Provider login succeeded, but initial sync failed. The provider was saved and can be retried from Settings: timeout",+ ProviderSavedWithSyncErrorException(+ provider = provider(id = 7L, name = "Premium", type = ProviderType.XTREAM_CODES).copy(status = ProviderStatus.ERROR),+ message = "Provider login succeeded, but initial sync failed. The provider was saved and can be retried from Settings: timeout"+ )+ )+ }+ val useCase = ValidateAndAddProvider(+ providerSetupInputValidator = FakeProviderSetupInputValidator(),+ providerRepository = repository+ )++ val result = useCase.loginXtream(+ XtreamProviderSetupCommand(+ serverUrl = "https://example.com",+ username = "alice",+ password = "secret",+ name = "Premium"+ )+ )++ assertThat(result).isInstanceOf(ValidateAndAddProviderResult.SavedWithWarning::class.java)+ result as ValidateAndAddProviderResult.SavedWithWarning+ assertThat(result.provider.id).isEqualTo(7L)+ assertThat(result.provider.status).isEqualTo(ProviderStatus.ERROR)+ assertThat(result.warning).contains("initial sync failed")+ }+@Testfun delegates_validated_m3u_input_to_repository() = runTest {val repository = FakeProviderRepository()@@ -128,7 +300,7 @@ class ValidateAndAddProviderTest {providerSetupInputValidator = FakeProviderSetupInputValidator(m3uResult = Result.success(ValidatedM3uProviderInput(- url = "http://[email protected]:8080/get.php?username=Hakan1605&password=wg9daUwzfV&type=m3u_plus",+ url = "http://extapk2302.shop:8080/get.php?username=Hakan1605&password=wg9daUwzfV&type=m3u_plus",name = "Imported Playlist"))@@ -138,7 +310,7 @@ class ValidateAndAddProviderTest {val result = useCase.addM3u(M3uProviderSetupCommand(- url = "http://[email protected]:8080/get.php?username=Hakan1605&password=wg9daUwzfV&type=m3u_plus",+ url = "http://extapk2302.shop:8080/get.php?username=Hakan1605&password=wg9daUwzfV&type=m3u_plus",name = "Imported Playlist",epgSyncMode = ProviderEpgSyncMode.BACKGROUND,existingProviderId = 19L@@ -149,7 +321,7 @@ class ValidateAndAddProviderTest {assertThat(repository.lastM3uCall).isNull()assertThat(repository.lastXtreamCall).isEqualTo(XtreamCall(- serverUrl = "http://[email protected]:8080",+ serverUrl = "http://extapk2302.shop:8080",username = "Hakan1605",password = "wg9daUwzfV",name = "Imported Playlist",@@ -160,6 +332,34 @@ class ValidateAndAddProviderTest {)}+ @Test+ fun rejects_xtream_playlist_url_with_embedded_credentials_in_authority() = runTest {+ val repository = FakeProviderRepository()+ val useCase = ValidateAndAddProvider(+ providerSetupInputValidator = FakeProviderSetupInputValidator(+ m3uResult = Result.success(+ ValidatedM3uProviderInput(+ url = "http://[email protected]:8080/get.php?username=Hakan1605&password=wg9daUwzfV&type=m3u_plus",+ name = "Imported Playlist"+ )+ )+ ),+ providerRepository = repository+ )++ val result = useCase.addM3u(+ M3uProviderSetupCommand(+ url = "http://[email protected]:8080/get.php?username=Hakan1605&password=wg9daUwzfV&type=m3u_plus",+ name = "Imported Playlist"+ )+ )++ assertThat(result).isInstanceOf(ValidateAndAddProviderResult.ValidationError::class.java)+ assertThat((result as ValidateAndAddProviderResult.ValidationError).message)+ .isEqualTo("Playlist sources must not include embedded credentials in the URL authority.")+ assertThat(repository.lastXtreamCall).isNull()+ }+@Testfun rejects_xtream_playlist_with_oversized_decoded_password() = runTest {val repository = FakeProviderRepository()@@ -244,6 +444,7 @@ private class FakeProviderSetupInputValidator(ValidatedXtreamProviderInput(serverUrl = "https://example.com",username = "user",+ password = "secret",name = "Provider")),@@ -267,6 +468,8 @@ private class FakeProviderSetupInputValidator(override fun validateXtream(serverUrl: String,username: String,+ password: String,+ allowBlankPassword: Boolean,name: String): Result<ValidatedXtreamProviderInput> = xtreamResult@@ -318,6 +521,9 @@ private class FakeProviderRepository : ProviderRepository {var lastXtreamCall: XtreamCall? = nullvar lastM3uCall: M3uCall? = nullvar lastStalkerCall: StalkerCall? = null+ var xtreamResult: Result<Provider>? = null+ var m3uResult: Result<Provider>? = null+ var stalkerResult: Result<Provider>? = nulloverride fun getProviders(): Flow<List<Provider>> = flowOf(emptyList())@@ -344,7 +550,7 @@ private class FakeProviderRepository : ProviderRepository {id: Long?): Result<Provider> {lastXtreamCall = XtreamCall(serverUrl, username, password, name, xtreamFastSyncEnabled, epgSyncMode, id)- return Result.success(provider(id = id ?: 1L, name = name, type = ProviderType.XTREAM_CODES))+ return xtreamResult ?: Result.success(provider(id = id ?: 1L, name = name, type = ProviderType.XTREAM_CODES))}override suspend fun validateM3u(@@ -356,7 +562,7 @@ private class FakeProviderRepository : ProviderRepository {id: Long?): Result<Provider> {lastM3uCall = M3uCall(url, name, epgSyncMode, m3uVodClassificationEnabled, id)- return Result.success(provider(id = id ?: 2L, name = name, type = ProviderType.M3U, m3uUrl = url))+ return m3uResult ?: Result.success(provider(id = id ?: 2L, name = name, type = ProviderType.M3U, m3uUrl = url))}override suspend fun loginStalker(@@ -380,7 +586,7 @@ private class FakeProviderRepository : ProviderRepository {epgSyncMode = epgSyncMode,id = id)- return Result.success(+ return stalkerResult ?: Result.success(provider(id = id ?: 3L, name = name, type = ProviderType.STALKER_PORTAL).copy(serverUrl = portalUrl,stalkerMacAddress = macAddress,@@ -408,7 +614,7 @@ private class FakeProviderRepository : ProviderRepository {override suspend fun buildCatchUpUrl(providerId: Long, streamId: Long, start: Long, end: Long): String? = null- private fun provider(+ fun provider(id: Long,name: String,type: ProviderType,diff --git a/player/src/main/java/com/streamvault/player/Media3PlayerEngine.kt b/player/src/main/java/com/streamvault/player/Media3PlayerEngine.ktindex 16d3de49..ce49183d 100644--- a/player/src/main/java/com/streamvault/player/Media3PlayerEngine.kt+++ b/player/src/main/java/com/streamvault/player/Media3PlayerEngine.kt@@ -44,6 +44,7 @@ import com.streamvault.player.playback.PlaybackCompatibilityProfileimport com.streamvault.player.playback.PlaybackErrorCategoryimport com.streamvault.player.playback.PlaybackLogSanitizerimport com.streamvault.player.playback.PlaybackRetryContext+import com.streamvault.player.playback.buildPlaybackPreparationPlanimport com.streamvault.player.playback.PlayerDataSourceFactoryProviderimport com.streamvault.player.playback.PlayerErrorClassifierimport com.streamvault.player.playback.PlayerMediaSourceFactory@@ -124,10 +125,11 @@ class Media3PlayerEngine @Inject constructor(// (the engine scope dispatcher). No @Volatile or synchronisation is needed as long// as the scope is not replaced with a different dispatcher in tests.//- // scope is a var because release() cancels it to tear down dangling coroutines,- // then creates a fresh one so the singleton engine remains usable on re-entry.+ // scope is a var because resetForReuse() replaces it after cancelling the old+ // collectors. Terminal release() never recreates the scope.private var scope = CoroutineScope(Dispatchers.Main.immediate + SupervisorJob())private set+ private var isDisposed = falseprivate var exoPlayer: ExoPlayer? = nullprivate var mediaSession: MediaSession? = nullprivate var requestedDecoderMode: DecoderMode = DecoderMode.AUTO@@ -244,6 +246,7 @@ class Media3PlayerEngine @Inject constructor(}private fun startEngineCollectors() {+ if (isDisposed) returnscope.launch {liveTimeshiftManager.state.collectLatest {syncTimeshiftState()@@ -272,20 +275,33 @@ class Media3PlayerEngine @Inject constructor(}override fun prepare(streamInfo: StreamInfo) {+ if (ensureNotDisposed("prepare")) returnprepareInternal(streamInfo = streamInfo, preserveRetryState = false, seekPositionMs = null, autoPlay = true)}override fun renewStreamUrl(streamInfo: StreamInfo) {+ if (ensureNotDisposed("renewStreamUrl")) returnval player = exoPlayer ?: return- val retryPolicy = currentRetryPolicy ?: return+ val playbackPlan = buildPlaybackPreparationPlan(+ streamInfo = streamInfo,+ preload = false,+ playbackStarted = { playbackStarted }+ )lastStreamInfo = streamInfolastMediaId = mediaSourceFactory.mediaIdFor(streamInfo)+ currentResolvedStreamType = playbackPlan.resolvedStreamType+ currentTimeoutProfile = playbackPlan.timeoutProfile+ currentRetryContext = playbackPlan.retryContext+ currentRetryPolicy = playbackPlan.retryPolicy+ retryAttempt = 0+ _retryStatus.value = null+ playbackStarted = falseval mediaSource = mediaSourceFactory.create(streamInfo = streamInfo,resolvedStreamType = currentResolvedStreamType,- retryPolicy = retryPolicy,+ retryPolicy = playbackPlan.retryPolicy,preload = false).second@@ -413,6 +429,7 @@ class Media3PlayerEngine @Inject constructor(@MainThreadoverride fun startLiveTimeshift(streamInfo: StreamInfo, channelKey: String, config: TimeshiftConfig) {+ if (ensureNotDisposed("startLiveTimeshift")) returnactiveLiveTimeshiftStreamInfo = streamInfoactiveLiveTimeshiftChannelKey = channelKeyscope.launch {@@ -558,19 +575,18 @@ class Media3PlayerEngine @Inject constructor(if (streamInfo.url == lastStreamInfo?.url) returnval mediaId = mediaSourceFactory.mediaIdFor(streamInfo)- val resolvedStreamType = StreamTypeResolver.resolve(streamInfo)- val retryContext = PlaybackRetryContext(- resolvedStreamType = resolvedStreamType,- timeoutProfile = PlayerTimeoutProfile.resolve(streamInfo, resolvedStreamType, preload = true)+ val playbackPlan = buildPlaybackPreparationPlan(+ streamInfo = streamInfo,+ preload = true,+ playbackStarted = { false })- val retryPolicy = PlayerRetryPolicy(retryContext) { false }val (_, mediaSource) = mediaSourceFactory.create(streamInfo = streamInfo,- resolvedStreamType = resolvedStreamType,- retryPolicy = retryPolicy,+ resolvedStreamType = playbackPlan.resolvedStreamType,+ retryPolicy = playbackPlan.retryPolicy,preload = true)- preloadCoordinator.store(mediaId, streamInfo, resolvedStreamType, mediaSource)+ preloadCoordinator.store(mediaId, streamInfo, playbackPlan.resolvedStreamType, mediaSource)}override fun createRenderView(@@ -580,6 +596,7 @@ class Media3PlayerEngine @Inject constructor() = viewBinder.createRenderView(context, resizeMode, surfaceType)override fun bindRenderView(renderView: android.view.View, resizeMode: PlayerSurfaceResizeMode) {+ if (ensureNotDisposed("bindRenderView")) returnviewBinder.bind(renderView, getOrCreatePlayer(), resizeMode)}@@ -592,6 +609,20 @@ class Media3PlayerEngine @Inject constructor(}override fun release() {+ if (isDisposed) return+ isDisposed = true+ resetEngineState(restartCollectors = false)+ }++ override fun resetForReuse() {+ if (isDisposed) {+ Log.w(TAG, "resetForReuse ignored after terminal release")+ return+ }+ resetEngineState(restartCollectors = true)+ }++ private fun resetEngineState(restartCollectors: Boolean) {retryJob?.cancel()retryJob = nullpreloadCoordinator.release()@@ -625,13 +656,20 @@ class Media3PlayerEngine @Inject constructor(isPlayingTimeshiftSnapshot = false_timeshiftState.value = LiveTimeshiftState()scope.cancel()- // Replace with a fresh scope so the singleton engine remains functional on re-entry.- scope = CoroutineScope(Dispatchers.Main.immediate + SupervisorJob())- startEngineCollectors()+ if (restartCollectors) {+ scope = CoroutineScope(Dispatchers.Main.immediate + SupervisorJob())+ startEngineCollectors()+ }// File cleanup runs outside the engine scope — orphans are also cleaned on next app startCoroutineScope(Dispatchers.IO).launch { liveTimeshiftManager.stopSession() }}+ private fun ensureNotDisposed(action: String): Boolean {+ if (!isDisposed) return false+ Log.w(TAG, "$action ignored after terminal release")+ return true+ }+private fun prepareInternal(streamInfo: StreamInfo,preserveRetryState: Boolean,@@ -664,26 +702,35 @@ class Media3PlayerEngine @Inject constructor(}selectedVideoDecoderName = "Unknown"- currentResolvedStreamType = StreamTypeResolver.resolve(streamInfo)- currentTimeoutProfile = PlayerTimeoutProfile.resolve(streamInfo, currentResolvedStreamType, preload = false)- currentRetryContext = PlaybackRetryContext(currentResolvedStreamType, currentTimeoutProfile)- currentRetryPolicy = PlayerRetryPolicy(currentRetryContext!!) { playbackStarted }+ val playbackPlan = buildPlaybackPreparationPlan(+ streamInfo = streamInfo,+ preload = false,+ playbackStarted = { playbackStarted }+ )+ currentResolvedStreamType = playbackPlan.resolvedStreamType+ currentTimeoutProfile = playbackPlan.timeoutProfile+ currentRetryContext = playbackPlan.retryContext+ currentRetryPolicy = playbackPlan.retryPolicyif (!preserveRetryState) {recoveryDecoderPolicyOverride = null}- activeDecoderPolicy = recoveryDecoderPolicyOverride ?: resolveActiveDecoderPolicy(requestedDecoderMode)- updateRenderSurfaceForMode()- refreshKnownBadCompatibilityRecords()-val preferredDecoderMode = decoderPreferencePolicy.preferredMode(requestedDecoderMode, mediaId)+ val nextDecoderPolicy = recoveryDecoderPolicyOverride ?: resolveActiveDecoderPolicy(+ policyModeFor(requestedDecoderMode, preferredDecoderMode)+ )val isLiveBuffer = currentResolvedStreamType in setOf(ResolvedStreamType.HLS, ResolvedStreamType.MPEG_TS_LIVE, ResolvedStreamType.RTSP)+ val previousDecoderPolicy = activeDecoderPolicyval needsRecreate = activeDecoderMode != preferredDecoderMode ||+ previousDecoderPolicy != nextDecoderPolicy ||isLiveBuffer != currentBufferIsLive ||requestedDecoderMode == DecoderMode.COMPATIBILITYactiveDecoderMode = preferredDecoderMode+ activeDecoderPolicy = nextDecoderPolicycurrentBufferIsLive = isLiveBuffer+ updateRenderSurfaceForMode()+ refreshKnownBadCompatibilityRecords()if (needsRecreate) {recreatePlayer()}@@ -693,50 +740,54 @@ class Media3PlayerEngine @Inject constructor("prepare resolvedStreamType=$currentResolvedStreamType timeoutProfile=$currentTimeoutProfile decoderPreference=$activeDecoderMode activePolicy=$activeDecoderPolicy surface=${_renderSurfaceType.value} target=${PlaybackLogSanitizer.sanitizeUrl(streamInfo.url)}")- val player = getOrCreatePlayer()- trackController.applyInitialParameters(player, constrainResolutionForMultiView)- if (activeDecoderPolicy == ActiveDecoderPolicy.COMPATIBILITY) {- player.trackSelectionParameters = player.trackSelectionParameters- .buildUpon()- .setMaxVideoSize(Int.MAX_VALUE, 720)- .build()- }- player.playbackParameters = PlaybackParameters(_playbackSpeed.value)-- val mediaSource = preloadCoordinator.tryReuse(mediaId, streamInfo, currentResolvedStreamType)- ?: mediaSourceFactory.create(- streamInfo = streamInfo,- resolvedStreamType = currentResolvedStreamType,- retryPolicy = currentRetryPolicy!!,- preload = false- ).second- preloadCoordinator.onPlaybackStarted(mediaId)- player.setMediaSource(mediaSource)- player.prepare()- seekPositionMs?.takeIf { it > 0L }?.let(player::seekTo)-- val isLive = currentResolvedStreamType in setOf(- ResolvedStreamType.HLS, ResolvedStreamType.MPEG_TS_LIVE, ResolvedStreamType.RTSP- )- val osContentType = if (isLive) {- android.media.AudioAttributes.CONTENT_TYPE_MUSIC- } else {- android.media.AudioAttributes.CONTENT_TYPE_MOVIE- }- val media3ContentType = if (isLive) C.AUDIO_CONTENT_TYPE_MUSIC else C.AUDIO_CONTENT_TYPE_MOVIE- player.setAudioAttributes(- Media3AudioAttributes.Builder()- .setUsage(C.USAGE_MEDIA)- .setContentType(media3ContentType)- .build(),- false- )- val focusGranted = audioFocusController.requestAudioFocusIfNeeded(osContentType)- player.playWhenReady = autoPlay && focusGranted- if (autoPlay && !focusGranted) {- _audioFocusDenied.tryEmit(Unit)+ try {+ val player = getOrCreatePlayer()+ trackController.applyInitialParameters(player, constrainResolutionForMultiView)+ if (activeDecoderPolicy == ActiveDecoderPolicy.COMPATIBILITY) {+ player.trackSelectionParameters = player.trackSelectionParameters+ .buildUpon()+ .setMaxVideoSize(Int.MAX_VALUE, 720)+ .build()+ }+ player.playbackParameters = PlaybackParameters(_playbackSpeed.value)++ val mediaSource = preloadCoordinator.tryReuse(mediaId, streamInfo, currentResolvedStreamType)+ ?: mediaSourceFactory.create(+ streamInfo = streamInfo,+ resolvedStreamType = currentResolvedStreamType,+ retryPolicy = currentRetryPolicy!!,+ preload = false+ ).second+ preloadCoordinator.onPlaybackStarted(mediaId)+ player.setMediaSource(mediaSource)+ player.prepare()+ seekPositionMs?.takeIf { it > 0L }?.let(player::seekTo)++ val isLive = currentResolvedStreamType in setOf(+ ResolvedStreamType.HLS, ResolvedStreamType.MPEG_TS_LIVE, ResolvedStreamType.RTSP+ )+ val osContentType = if (isLive) {+ android.media.AudioAttributes.CONTENT_TYPE_MUSIC+ } else {+ android.media.AudioAttributes.CONTENT_TYPE_MOVIE+ }+ val media3ContentType = if (isLive) C.AUDIO_CONTENT_TYPE_MUSIC else C.AUDIO_CONTENT_TYPE_MOVIE+ player.setAudioAttributes(+ Media3AudioAttributes.Builder()+ .setUsage(C.USAGE_MEDIA)+ .setContentType(media3ContentType)+ .build(),+ false+ )+ val focusGranted = audioFocusController.requestAudioFocusIfNeeded(osContentType)+ player.playWhenReady = autoPlay && focusGranted+ if (autoPlay && !focusGranted) {+ _audioFocusDenied.tryEmit(Unit)+ }+ viewBinder.attachPlayer(player)+ } catch (error: Exception) {+ handlePlaybackSetupFailure(error, streamInfo, mediaId, seekPositionMs, autoPlay)}- viewBinder.attachPlayer(player)}private fun recreatePlayer() {@@ -750,6 +801,7 @@ class Media3PlayerEngine @Inject constructor(}private fun getOrCreatePlayer(): ExoPlayer {+ check(!isDisposed) { "Cannot create a player after terminal release" }return exoPlayer ?: createPlayer().also { player ->exoPlayer = playerstatsCollector.bind { exoPlayer }@@ -814,6 +866,8 @@ class Media3PlayerEngine @Inject constructor(}private fun buildRenderersFactory(): DefaultRenderersFactory {+ val decoderPolicy = activeDecoderPolicy+ val badDecoderNames = knownBadDecoderNamesreturn object : DefaultRenderersFactory(context) {override fun buildAudioSink(context: Context,@@ -881,12 +935,14 @@ class Media3PlayerEngine @Inject constructor(}}.apply {setEnableDecoderFallback(true)- setMediaCodecSelector(- PlaybackCodecSelector(- policyProvider = { activeDecoderPolicy },- knownBadProvider = { knownBadDecoderNames }+ if (decoderPolicy != ActiveDecoderPolicy.AUTO || badDecoderNames.isNotEmpty()) {+ setMediaCodecSelector(+ PlaybackCodecSelector(+ policyProvider = { decoderPolicy },+ knownBadProvider = { badDecoderNames }+ ))- )+ }setExtensionRendererMode(when (activeDecoderMode) {DecoderMode.AUTO, DecoderMode.HARDWARE -> DefaultRenderersFactory.EXTENSION_RENDERER_MODE_ON@@ -1150,12 +1206,18 @@ class Media3PlayerEngine @Inject constructor(}private fun resolveActiveDecoderPolicy(mode: DecoderMode): ActiveDecoderPolicy = when (mode) {- DecoderMode.AUTO -> ActiveDecoderPolicy.AUTO+ DecoderMode.AUTO -> ActiveDecoderPolicy.HARDWARE_PREFERREDDecoderMode.HARDWARE -> ActiveDecoderPolicy.HARDWARE_PREFERREDDecoderMode.SOFTWARE -> ActiveDecoderPolicy.SOFTWARE_PREFERREDDecoderMode.COMPATIBILITY -> ActiveDecoderPolicy.COMPATIBILITY}+ private fun policyModeFor(requestedMode: DecoderMode, preferredMode: DecoderMode): DecoderMode = when {+ requestedMode == DecoderMode.COMPATIBILITY -> DecoderMode.COMPATIBILITY+ preferredMode == DecoderMode.SOFTWARE -> DecoderMode.SOFTWARE+ else -> requestedMode+ }+private fun updateRenderSurfaceForMode() {_renderSurfaceType.value = when (requestedSurfaceMode) {PlayerSurfaceMode.SURFACE_VIEW -> PlayerRenderSurfaceType.SURFACE_VIEW@@ -1312,6 +1374,40 @@ class Media3PlayerEngine @Inject constructor()}+ private fun handlePlaybackSetupFailure(+ error: Exception,+ streamInfo: StreamInfo,+ mediaId: String,+ seekPositionMs: Long?,+ autoPlay: Boolean+ ) {+ val category = PlayerErrorClassifier.classify(error)+ Log.e(+ TAG,+ "prepare-failed category=$category decoderPreference=$activeDecoderMode activePolicy=$activeDecoderPolicy target=${PlaybackLogSanitizer.sanitizeUrl(streamInfo.url)} message=${PlaybackLogSanitizer.sanitizeMessage(error.message)}",+ error+ )++ if (category == PlaybackErrorCategory.DECODER || category == PlaybackErrorCategory.FORMAT_UNSUPPORTED) {+ recordCompatibilityFailure("DECODER_INIT")+ val fallbackMode = decoderPreferencePolicy.onDecoderInitFailure(requestedDecoderMode, mediaId)+ if (fallbackMode != null) {+ Log.w(+ TAG,+ "decoder-setup fallback=$fallbackMode mediaId=$mediaId target=${PlaybackLogSanitizer.sanitizeUrl(streamInfo.url)}"+ )+ recreatePlayer()+ prepareInternal(streamInfo, preserveRetryState = false, seekPositionMs = seekPositionMs, autoPlay = autoPlay)+ return+ }+ }++ recreatePlayer()+ _retryStatus.value = null+ _error.tryEmit(PlayerError.fromException(error))+ _playbackState.value = PlaybackState.ERROR+ }+private fun handlePlaybackError(error: PlaybackException) {retryJob?.cancel()retryJob = null@@ -1329,7 +1425,7 @@ class Media3PlayerEngine @Inject constructor(}if (category == PlaybackErrorCategory.DECODER || category == PlaybackErrorCategory.FORMAT_UNSUPPORTED) {- val fallbackMode = decoderPreferencePolicy.onDecoderInitFailure(activeDecoderMode, mediaId)+ val fallbackMode = decoderPreferencePolicy.onDecoderInitFailure(requestedDecoderMode, mediaId)if (fallbackMode != null) {Log.w(TAG,diff --git a/player/src/main/java/com/streamvault/player/PlayerEngine.kt b/player/src/main/java/com/streamvault/player/PlayerEngine.ktindex 106b3730..d5aa9f7a 100644--- a/player/src/main/java/com/streamvault/player/PlayerEngine.kt+++ b/player/src/main/java/com/streamvault/player/PlayerEngine.kt@@ -85,6 +85,7 @@ interface PlayerEngine {fun selectSubtitleTrack(trackId: String?) // null to disable subtitlesfun addExternalSubtitle(subtitleUri: android.net.Uri, language: String)fun release()+ fun resetForReuse() = release()/** Toggle mute without losing the remembered volume level. */fun toggleMute()diff --git a/player/src/main/java/com/streamvault/player/playback/CodecPreference.kt b/player/src/main/java/com/streamvault/player/playback/CodecPreference.ktindex 794552db..40cbe9f7 100644--- a/player/src/main/java/com/streamvault/player/playback/CodecPreference.kt+++ b/player/src/main/java/com/streamvault/player/playback/CodecPreference.kt@@ -48,8 +48,7 @@ class PlaybackCodecSelector(return normalized.startsWith("omx.google.") ||normalized.startsWith("c2.android.") ||normalized.contains("ffmpeg") ||- normalized.contains("avcodec") ||- normalized.contains("sw")+ normalized.contains("avcodec")}fun knownBadDecoderNames(records: List<PlaybackCompatibilityRecord>): Set<String> =diff --git a/player/src/main/java/com/streamvault/player/playback/DecoderPreferencePolicy.kt b/player/src/main/java/com/streamvault/player/playback/DecoderPreferencePolicy.ktindex 96107fcf..3a93976a 100644--- a/player/src/main/java/com/streamvault/player/playback/DecoderPreferencePolicy.kt+++ b/player/src/main/java/com/streamvault/player/playback/DecoderPreferencePolicy.kt@@ -14,12 +14,15 @@ class DefaultDecoderPreferencePolicy : DecoderPreferencePolicy {override fun preferredMode(requestedMode: DecoderMode, mediaId: String): DecoderMode {return when (requestedMode) {DecoderMode.SOFTWARE, DecoderMode.COMPATIBILITY -> DecoderMode.SOFTWARE- DecoderMode.HARDWARE, DecoderMode.AUTO -> DecoderMode.HARDWARE+ DecoderMode.AUTO -> {+ if (mediaId in softwareRetriedMediaIds) DecoderMode.SOFTWARE else DecoderMode.HARDWARE+ }+ DecoderMode.HARDWARE -> DecoderMode.HARDWARE}}override fun onDecoderInitFailure(requestedMode: DecoderMode, mediaId: String): DecoderMode? {- if (requestedMode == DecoderMode.SOFTWARE || requestedMode == DecoderMode.COMPATIBILITY) return null+ if (requestedMode != DecoderMode.AUTO) return nullif (!softwareRetriedMediaIds.add(mediaId)) return nullreturn DecoderMode.SOFTWARE}diff --git a/player/src/main/java/com/streamvault/player/playback/PlaybackPreparationPlan.kt b/player/src/main/java/com/streamvault/player/playback/PlaybackPreparationPlan.ktnew file mode 100644index 00000000..694d203e--- /dev/null+++ b/player/src/main/java/com/streamvault/player/playback/PlaybackPreparationPlan.kt@@ -0,0 +1,26 @@+package com.streamvault.player.playback++import com.streamvault.domain.model.StreamInfo++internal data class PlaybackPreparationPlan(+ val resolvedStreamType: ResolvedStreamType,+ val timeoutProfile: PlayerTimeoutProfile,+ val retryContext: PlaybackRetryContext,+ val retryPolicy: PlayerRetryPolicy+)++internal fun buildPlaybackPreparationPlan(+ streamInfo: StreamInfo,+ preload: Boolean,+ playbackStarted: () -> Boolean+): PlaybackPreparationPlan {+ val resolvedStreamType = StreamTypeResolver.resolve(streamInfo)+ val timeoutProfile = PlayerTimeoutProfile.resolve(streamInfo, resolvedStreamType, preload = preload)+ val retryContext = PlaybackRetryContext(resolvedStreamType, timeoutProfile)+ return PlaybackPreparationPlan(+ resolvedStreamType = resolvedStreamType,+ timeoutProfile = timeoutProfile,+ retryContext = retryContext,+ retryPolicy = PlayerRetryPolicy(retryContext) { playbackStarted() }+ )+}\ No newline at end of filediff --git a/player/src/main/java/com/streamvault/player/timeshift/LiveTimeshiftManager.kt b/player/src/main/java/com/streamvault/player/timeshift/LiveTimeshiftManager.ktindex 9553ce14..de6f5cb8 100644--- a/player/src/main/java/com/streamvault/player/timeshift/LiveTimeshiftManager.kt+++ b/player/src/main/java/com/streamvault/player/timeshift/LiveTimeshiftManager.kt@@ -41,6 +41,30 @@ internal interface LiveTimeshiftManager {suspend fun releaseRetiredSnapshots()}+internal data class DashSnapshotPlaylistSegment(+ val fileName: String,+ val durationMs: Long,+ val isInit: Boolean+)++internal fun buildDashSnapshotPlaylist(+ targetDurationSeconds: Int,+ segments: List<DashSnapshotPlaylistSegment>+): String = buildString {+ appendLine("#EXTM3U")+ appendLine("#EXT-X-VERSION:7")+ appendLine("#EXT-X-TARGETDURATION:$targetDurationSeconds")+ appendLine("#EXT-X-MEDIA-SEQUENCE:0")+ segments.firstOrNull { it.isInit }?.let { initSegment ->+ appendLine("#EXT-X-MAP:URI=\"${initSegment.fileName}\"")+ }+ segments.filterNot(DashSnapshotPlaylistSegment::isInit).forEach { segment ->+ appendLine("#EXTINF:${"%.3f".format(Locale.US, segment.durationMs / 1000.0)},")+ appendLine(segment.fileName)+ }+ appendLine("#EXT-X-ENDLIST")+}+@Singletoninternal class DefaultLiveTimeshiftManager @Inject constructor(@param:ApplicationContext private val context: Context,@@ -760,27 +784,25 @@ internal class DefaultLiveTimeshiftManager @Inject constructor(val playlist = File(snapshotDir, "index.m3u8")val targetDurationSeconds = snapshotSegments.maxOf { ((it.durationMs + 999L) / 1000L).toInt().coerceAtLeast(1) }val all = segmentMutex.withLock { segments.toList() } // includes init- val body = buildString {- appendLine("#EXTM3U")- appendLine("#EXT-X-VERSION:3")- appendLine("#EXT-X-TARGETDURATION:$targetDurationSeconds")- appendLine("#EXT-X-MEDIA-SEQUENCE:0")- var mediaIndex = 0- all.forEachIndexed { index, segment ->- val isInit = segment.durationMs == 0L- val fileName = if (isInit) "init-$index.mp4" else "segment-${mediaIndex++}.mp4"- val outputFile = File(snapshotDir, fileName)- when {- segment.file != null && segment.file.exists() -> segment.file.copyTo(outputFile, overwrite = true)- segment.payload != null -> outputFile.writeBytes(segment.payload)- }- if (!isInit) {- appendLine("#EXTINF:${"%.3f".format(Locale.US, segment.durationMs / 1000.0)},")- appendLine(fileName)- }+ var mediaIndex = 0+ val playlistSegments = all.mapIndexed { index, segment ->+ val isInit = segment.durationMs == 0L+ val fileName = if (isInit) "init-$index.mp4" else "segment-${mediaIndex++}.mp4"+ val outputFile = File(snapshotDir, fileName)+ when {+ segment.file != null && segment.file.exists() -> segment.file.copyTo(outputFile, overwrite = true)+ segment.payload != null -> outputFile.writeBytes(segment.payload)}- appendLine("#EXT-X-ENDLIST")+ DashSnapshotPlaylistSegment(+ fileName = fileName,+ durationMs = segment.durationMs,+ isInit = isInit+ )}+ val body = buildDashSnapshotPlaylist(+ targetDurationSeconds = targetDurationSeconds,+ segments = playlistSegments+ )playlist.writeText(body)return LiveTimeshiftSnapshot(url = playlist.toURI().toString(),diff --git a/player/src/main/java/com/streamvault/player/tracks/PlayerTrackController.kt b/player/src/main/java/com/streamvault/player/tracks/PlayerTrackController.ktindex a06fbb7a..9c4b574d 100644--- a/player/src/main/java/com/streamvault/player/tracks/PlayerTrackController.kt+++ b/player/src/main/java/com/streamvault/player/tracks/PlayerTrackController.kt@@ -108,6 +108,11 @@ class PlayerTrackController(}}+ selectedVideoTrackId = normalizeSelectedVideoTrackId(+ selectedTrackId = selectedVideoTrackId,+ availableTrackIds = videoTracks.map(PlayerTrack::id)+ )+_availableAudioTracks.value = audioTracks_availableSubtitleTracks.value = subtitleTracks_availableVideoTracks.value = when {@@ -135,13 +140,13 @@ class PlayerTrackController(}fun selectVideoTrack(player: ExoPlayer, trackId: String) {- selectedVideoTrackId = trackIdif (trackId == PLAYER_TRACK_AUTO_ID) {player.trackSelectionParameters = player.trackSelectionParameters.buildUpon().clearOverridesOfType(C.TRACK_TYPE_VIDEO).setTrackTypeDisabled(C.TRACK_TYPE_VIDEO, false).build()+ selectedVideoTrackId = PLAYER_TRACK_AUTO_ID} else {val override = findOverride(player.currentTracks, C.TRACK_TYPE_VIDEO, trackId) ?: returnplayer.trackSelectionParameters = player.trackSelectionParameters@@ -149,9 +154,12 @@ class PlayerTrackController(.setTrackTypeDisabled(C.TRACK_TYPE_VIDEO, false).setOverrideForType(override).build()+ selectedVideoTrackId = trackId}_availableVideoTracks.update { tracks ->- tracks.map { it.copy(isSelected = it.id == trackId) }+ tracks.map { track ->+ track.copy(isSelected = track.id == selectedVideoTrackId)+ }}}@@ -259,3 +267,14 @@ class PlayerTrackController(}}+internal fun normalizeSelectedVideoTrackId(+ selectedTrackId: String,+ availableTrackIds: List<String>+): String = when {+ availableTrackIds.isEmpty() -> PLAYER_TRACK_AUTO_ID+ selectedTrackId == PLAYER_TRACK_AUTO_ID -> PLAYER_TRACK_AUTO_ID+ selectedTrackId in availableTrackIds -> selectedTrackId+ availableTrackIds.size == 1 -> availableTrackIds.first()+ else -> PLAYER_TRACK_AUTO_ID+}+diff --git a/player/src/test/java/com/streamvault/player/playback/DecoderPreferencePolicyTest.kt b/player/src/test/java/com/streamvault/player/playback/DecoderPreferencePolicyTest.ktnew file mode 100644index 00000000..326b1925--- /dev/null+++ b/player/src/test/java/com/streamvault/player/playback/DecoderPreferencePolicyTest.kt@@ -0,0 +1,53 @@+package com.streamvault.player.playback++import com.google.common.truth.Truth.assertThat+import com.streamvault.domain.model.DecoderMode+import org.junit.Test++class DecoderPreferencePolicyTest {++ @Test+ fun `auto retries with software after decoder init failure`() {+ val policy = DefaultDecoderPreferencePolicy()+ val mediaId = "channel-1"++ assertThat(policy.preferredMode(DecoderMode.AUTO, mediaId)).isEqualTo(DecoderMode.HARDWARE)+ assertThat(policy.onDecoderInitFailure(DecoderMode.AUTO, mediaId)).isEqualTo(DecoderMode.SOFTWARE)+ assertThat(policy.preferredMode(DecoderMode.AUTO, mediaId)).isEqualTo(DecoderMode.SOFTWARE)+ }++ @Test+ fun `fallback is attempted once per media id`() {+ val policy = DefaultDecoderPreferencePolicy()+ val mediaId = "channel-1"++ assertThat(policy.onDecoderInitFailure(DecoderMode.AUTO, mediaId)).isEqualTo(DecoderMode.SOFTWARE)+ assertThat(policy.onDecoderInitFailure(DecoderMode.AUTO, mediaId)).isNull()+ }++ @Test+ fun `reset restores requested hardware preference`() {+ val policy = DefaultDecoderPreferencePolicy()+ val mediaId = "channel-1"++ policy.onDecoderInitFailure(DecoderMode.AUTO, mediaId)+ assertThat(policy.preferredMode(DecoderMode.AUTO, mediaId)).isEqualTo(DecoderMode.SOFTWARE)++ policy.resetForMedia(mediaId)++ assertThat(policy.preferredMode(DecoderMode.AUTO, mediaId)).isEqualTo(DecoderMode.HARDWARE)+ }++ @Test+ fun `explicit hardware software and compatibility do not fallback again`() {+ val policy = DefaultDecoderPreferencePolicy()+ val mediaId = "channel-1"++ assertThat(policy.preferredMode(DecoderMode.HARDWARE, mediaId)).isEqualTo(DecoderMode.HARDWARE)+ assertThat(policy.preferredMode(DecoderMode.SOFTWARE, mediaId)).isEqualTo(DecoderMode.SOFTWARE)+ assertThat(policy.preferredMode(DecoderMode.COMPATIBILITY, mediaId)).isEqualTo(DecoderMode.SOFTWARE)+ assertThat(policy.onDecoderInitFailure(DecoderMode.HARDWARE, mediaId)).isNull()+ assertThat(policy.onDecoderInitFailure(DecoderMode.SOFTWARE, mediaId)).isNull()+ assertThat(policy.onDecoderInitFailure(DecoderMode.COMPATIBILITY, mediaId)).isNull()+ }+}\ No newline at end of filediff --git a/player/src/test/java/com/streamvault/player/playback/PlaybackPreparationPlanTest.kt b/player/src/test/java/com/streamvault/player/playback/PlaybackPreparationPlanTest.ktnew file mode 100644index 00000000..86376b29--- /dev/null+++ b/player/src/test/java/com/streamvault/player/playback/PlaybackPreparationPlanTest.kt@@ -0,0 +1,46 @@+package com.streamvault.player.playback++import com.google.common.truth.Truth.assertThat+import com.streamvault.domain.model.StreamInfo+import org.junit.Test++class PlaybackPreparationPlanTest {++ @Test+ fun `refreshed stream info recomputes transport contract`() {+ val initial = buildPlaybackPreparationPlan(+ streamInfo = StreamInfo(url = "https://example.com/live/channel.m3u8"),+ preload = false,+ playbackStarted = { true }+ )++ val refreshed = buildPlaybackPreparationPlan(+ streamInfo = StreamInfo(url = "https://example.com/live/channel.ts", containerExtension = "ts"),+ preload = false,+ playbackStarted = { true }+ )++ assertThat(initial.resolvedStreamType).isEqualTo(ResolvedStreamType.HLS)+ assertThat(initial.timeoutProfile).isEqualTo(PlayerTimeoutProfile.LIVE)+ assertThat(refreshed.resolvedStreamType).isEqualTo(ResolvedStreamType.MPEG_TS_LIVE)+ assertThat(refreshed.timeoutProfile).isEqualTo(PlayerTimeoutProfile.LIVE)+ assertThat(refreshed.retryContext).isEqualTo(+ PlaybackRetryContext(+ resolvedStreamType = ResolvedStreamType.MPEG_TS_LIVE,+ timeoutProfile = PlayerTimeoutProfile.LIVE+ )+ )+ }++ @Test+ fun `preload plan uses preload timeout profile`() {+ val preloadPlan = buildPlaybackPreparationPlan(+ streamInfo = StreamInfo(url = "https://example.com/movie.mp4"),+ preload = true,+ playbackStarted = { false }+ )++ assertThat(preloadPlan.resolvedStreamType).isEqualTo(ResolvedStreamType.PROGRESSIVE)+ assertThat(preloadPlan.timeoutProfile).isEqualTo(PlayerTimeoutProfile.PRELOAD)+ }+}\ No newline at end of filediff --git a/player/src/test/java/com/streamvault/player/timeshift/DashSnapshotPlaylistTest.kt b/player/src/test/java/com/streamvault/player/timeshift/DashSnapshotPlaylistTest.ktnew file mode 100644index 00000000..88b6eab4--- /dev/null+++ b/player/src/test/java/com/streamvault/player/timeshift/DashSnapshotPlaylistTest.kt@@ -0,0 +1,39 @@+package com.streamvault.player.timeshift++import com.google.common.truth.Truth.assertThat+import org.junit.Test++class DashSnapshotPlaylistTest {++ @Test+ fun `buildDashSnapshotPlaylist emits init map for fmp4 snapshots`() {+ val playlist = buildDashSnapshotPlaylist(+ targetDurationSeconds = 6,+ segments = listOf(+ DashSnapshotPlaylistSegment(fileName = "init-0.mp4", durationMs = 0L, isInit = true),+ DashSnapshotPlaylistSegment(fileName = "segment-0.mp4", durationMs = 4_000L, isInit = false),+ DashSnapshotPlaylistSegment(fileName = "segment-1.mp4", durationMs = 5_500L, isInit = false)+ )+ )++ assertThat(playlist).contains("#EXT-X-VERSION:7")+ assertThat(playlist).contains("#EXT-X-MAP:URI=\"init-0.mp4\"")+ assertThat(playlist).contains("#EXTINF:4.000,")+ assertThat(playlist).contains("segment-0.mp4")+ assertThat(playlist).contains("#EXTINF:5.500,")+ assertThat(playlist).contains("segment-1.mp4")+ }++ @Test+ fun `buildDashSnapshotPlaylist omits extinf for init segment`() {+ val playlist = buildDashSnapshotPlaylist(+ targetDurationSeconds = 6,+ segments = listOf(+ DashSnapshotPlaylistSegment(fileName = "init-0.mp4", durationMs = 0L, isInit = true),+ DashSnapshotPlaylistSegment(fileName = "segment-0.mp4", durationMs = 4_000L, isInit = false)+ )+ )++ assertThat(playlist).doesNotContain("#EXTINF:0.000,")+ }+}diff --git a/player/src/test/java/com/streamvault/player/tracks/PlayerTrackControllerSelectionTest.kt b/player/src/test/java/com/streamvault/player/tracks/PlayerTrackControllerSelectionTest.ktnew file mode 100644index 00000000..8e0c8521--- /dev/null+++ b/player/src/test/java/com/streamvault/player/tracks/PlayerTrackControllerSelectionTest.kt@@ -0,0 +1,38 @@+package com.streamvault.player.tracks++import com.google.common.truth.Truth.assertThat+import com.streamvault.player.PLAYER_TRACK_AUTO_ID+import org.junit.Test++class PlayerTrackControllerSelectionTest {++ @Test+ fun `stale selected video track falls back to auto when multiple tracks remain`() {+ assertThat(+ normalizeSelectedVideoTrackId(+ selectedTrackId = "stale-id",+ availableTrackIds = listOf("720p", "1080p")+ )+ ).isEqualTo(PLAYER_TRACK_AUTO_ID)+ }++ @Test+ fun `stale selected video track falls back to only available track`() {+ assertThat(+ normalizeSelectedVideoTrackId(+ selectedTrackId = "stale-id",+ availableTrackIds = listOf("1080p")+ )+ ).isEqualTo("1080p")+ }++ @Test+ fun `current selected video track is preserved when still available`() {+ assertThat(+ normalizeSelectedVideoTrackId(+ selectedTrackId = "720p",+ availableTrackIds = listOf("720p", "1080p")+ )+ ).isEqualTo("720p")+ }+}\ No newline at end of file