Skip to content

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

Finalize player, sync, and EPG improvements

David Nashash2dcc8ce84942
diff --git a/_old_sync_manager_from_zip.kt b/_old_sync_manager_from_zip.kt
new file mode 100644
index 00000000..0175957f
--- /dev/null
+++ b/_old_sync_manager_from_zip.kt
@@ -0,0 +1,2390 @@
+package com.streamvault.data.sync
+
+import android.util.Log
+import com.streamvault.data.local.dao.CategoryDao
+import com.streamvault.data.local.dao.ChannelDao
+import com.streamvault.data.local.dao.MovieDao
+import com.streamvault.data.local.dao.ProgramDao
+import com.streamvault.data.local.dao.ProviderDao
+import com.streamvault.data.local.dao.SeriesDao
+import com.streamvault.data.local.entity.CategoryEntity
+import com.streamvault.data.local.entity.ChannelEntity
+import com.streamvault.data.local.entity.MovieEntity
+import com.streamvault.data.mapper.toDomain
+import com.streamvault.data.mapper.toEntity
+import com.streamvault.data.parser.M3uParser
+import com.streamvault.data.remote.dto.XtreamCategory
+import com.streamvault.data.remote.dto.XtreamSeriesItem
+import com.streamvault.data.remote.dto.XtreamStream
+import com.streamvault.data.remote.xtream.OkHttpXtreamApiService
+import com.streamvault.data.remote.xtream.XtreamAuthenticationException
+import com.streamvault.data.remote.xtream.XtreamNetworkException
+import com.streamvault.data.remote.xtream.XtreamParsingException
+import com.streamvault.data.remote.xtream.XtreamRequestException
+import com.streamvault.data.remote.xtream.XtreamApiService
+import com.streamvault.data.remote.xtream.XtreamProvider
+import com.streamvault.data.remote.xtream.XtreamUrlFactory
+import com.streamvault.data.security.CredentialCrypto
+import com.streamvault.data.util.AdultContentClassifier
+import com.streamvault.data.util.UrlSecurityPolicy
+import com.streamvault.domain.model.Channel
+import com.streamvault.domain.model.ContentType
+import com.streamvault.domain.model.Movie
+import com.streamvault.domain.model.Provider
+import com.streamvault.domain.model.ProviderType
+import com.streamvault.domain.model.Series
+import com.streamvault.domain.model.SyncMetadata
+import com.streamvault.domain.model.SyncState
+import com.streamvault.domain.model.VodSyncMode
+import com.streamvault.domain.repository.EpgRepository
+import com.streamvault.domain.repository.SyncMetadataRepository
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.async
+import kotlinx.coroutines.awaitAll
+import kotlinx.coroutines.coroutineScope
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.asStateFlow
+import kotlinx.coroutines.flow.first
+import kotlinx.coroutines.flow.map
+import kotlinx.coroutines.flow.update
+import kotlinx.coroutines.withContext
+import kotlinx.coroutines.sync.Mutex
+import kotlinx.coroutines.sync.Semaphore
+import kotlinx.coroutines.sync.withPermit
+import kotlinx.coroutines.sync.withLock
+import kotlinx.serialization.json.Json
+import okhttp3.OkHttpClient
+import okhttp3.Request
+import okhttp3.Response
+import java.io.BufferedInputStream
+import java.io.IOException
+import java.io.InputStream
+import java.security.MessageDigest
+import java.util.concurrent.ConcurrentHashMap
+import java.util.concurrent.TimeUnit.MINUTES
+import java.util.zip.GZIPInputStream
+import javax.inject.Inject
+import javax.inject.Singleton
+import kotlin.random.Random
+import kotlin.system.measureTimeMillis
+
+private const val TAG = "SyncManager"
+private const val XTREAM_LIVE_CATEGORY_SYNC_MAX_CONCURRENCY = 4
+private const val XTREAM_CATALOG_TIMEOUT_MINUTES = 5L
+private const val XTREAM_CATALOG_PAGE_SIZE = 1000
+private const val XTREAM_CATALOG_MAX_PAGES = 200
+private const val MOVIE_CATEGORY_SEQUENTIAL_MODE_WARNING =
+ "Movies category-bulk sync downgraded to sequential mode after provider stress signals."
+private const val LIVE_CATEGORY_SEQUENTIAL_MODE_WARNING =
+ "Live category sync downgraded to sequential mode after provider stress signals."
+private const val SERIES_CATEGORY_SEQUENTIAL_MODE_WARNING =
+ "Series category sync downgraded to sequential mode after provider stress signals."
+
+enum class SyncRepairSection {
+ EPG,
+ MOVIES,
+ SERIES
+}
+
+@Singleton
+class SyncManager @Inject constructor(
+ private val providerDao: ProviderDao,
+ private val channelDao: ChannelDao,
+ private val movieDao: MovieDao,
+ private val seriesDao: SeriesDao,
+ private val programDao: ProgramDao,
+ private val categoryDao: CategoryDao,
+ private val xtreamJson: Json,
+ private val m3uParser: M3uParser,
+ private val epgRepository: EpgRepository,
+ private val okHttpClient: OkHttpClient,
+ private val syncMetadataRepository: SyncMetadataRepository
+) {
+ private data class SyncOutcome(
+ val partial: Boolean = false,
+ val warnings: List<String> = emptyList()
+ )
+
+ private sealed interface CatalogStrategyResult<out T> {
+ val strategyName: String
+
+ data class Success<T>(
+ override val strategyName: String,
+ val items: List<T>,
+ val warnings: List<String> = emptyList()
+ ) : CatalogStrategyResult<T>
+
+ data class Partial<T>(
+ override val strategyName: String,
+ val items: List<T>,
+ val warnings: List<String>
+ ) : CatalogStrategyResult<T>
+
+ data class Failure(
+ override val strategyName: String,
+ val error: Throwable,
+ val warnings: List<String> = emptyList()
+ ) : CatalogStrategyResult<Nothing>
+
+ data class EmptyValid(
+ override val strategyName: String,
+ val warnings: List<String> = emptyList()
+ ) : CatalogStrategyResult<Nothing>
+ }
+
+ private data class MovieCatalogSyncResult(
+ val catalogResult: CatalogStrategyResult<Movie>,
+ val categories: List<CategoryEntity>?,
+ val syncMode: VodSyncMode,
+ val warnings: List<String> = emptyList()
+ )
+
+ private data class CatalogSyncPayload<T>(
+ val catalogResult: CatalogStrategyResult<T>,
+ val categories: List<CategoryEntity>?,
+ val warnings: List<String> = emptyList()
+ )
+
+ private data class MovieProviderAdaptation(
+ val rememberSequential: Boolean,
+ val healthyStreak: Int
+ )
+
+ private sealed interface CategoryFetchOutcome<out T> {
+ data class Success<T>(val categoryName: String, val items: List<T>) : CategoryFetchOutcome<T>
+ data class Empty(val categoryName: String) : CategoryFetchOutcome<Nothing>
+ data class Failure(val categoryName: String, val error: Throwable) : CategoryFetchOutcome<Nothing>
+ }
+
+ private data class M3uImportStats(
+ val header: M3uParser.M3uHeader,
+ val liveCount: Int,
+ val movieCount: Int,
+ val warnings: List<String> = emptyList()
+ )
+
+ private data class StreamedPlaylist(
+ val inputStream: InputStream,
+ val contentEncoding: String? = null,
+ val sourceName: String? = null
+ )
+
+ private class StableLongHasher {
+ private val digest = MessageDigest.getInstance("SHA-256")
+
+ fun hash(input: String): Long {
+ val bytes = digest.digest(input.toByteArray(Charsets.UTF_8))
+ var result = 0L
+ for (i in 0 until 8) {
+ result = (result shl 8) or (bytes[i].toLong() and 0xFF)
+ }
+ return result and Long.MAX_VALUE
+ }
+ }
+
+ private class CategoryAccumulator(
+ private val providerId: Long,
+ private val type: ContentType,
+ private val hasher: StableLongHasher
+ ) {
+ private val categoryIds = LinkedHashMap<String, Long>()
+ val count: Int
+ get() = categoryIds.size
+
+ fun idFor(name: String): Long {
+ return categoryIds.getOrPut(name) { stableId(providerId, type, name, hasher) }
+ }
+
+ fun entities(): List<CategoryEntity> {
+ return categoryIds.map { (name, id) ->
+ CategoryEntity(
+ categoryId = id,
+ name = name,
+ parentId = 0,
+ type = type,
+ providerId = providerId,
+ isAdult = AdultContentClassifier.isAdultCategoryName(name)
+ )
+ }
+ }
+
+ /** Generates a stable, collision-resistant ID from the provider+type+name triple. */
+ private fun stableId(
+ providerId: Long,
+ type: ContentType,
+ name: String,
+ hasher: StableLongHasher
+ ): Long {
+ return hasher.hash("$providerId/${type.name}/$name").coerceAtLeast(1L)
+ }
+ }
+
+ private val _syncState = MutableStateFlow<SyncState>(SyncState.Idle)
+ val syncState: StateFlow<SyncState> = _syncState.asStateFlow()
+ private val _syncStatesByProvider = MutableStateFlow<Map<Long, SyncState>>(emptyMap())
+ val syncStatesByProvider: StateFlow<Map<Long, SyncState>> = _syncStatesByProvider.asStateFlow()
+ private val providerSyncMutexes = ConcurrentHashMap<Long, Mutex>()
+ private val xtreamCatalogApiService: XtreamApiService by lazy {
+ OkHttpXtreamApiService(
+ client = okHttpClient.newBuilder()
+ .connectTimeout(XTREAM_CATALOG_TIMEOUT_MINUTES, MINUTES)
+ .readTimeout(XTREAM_CATALOG_TIMEOUT_MINUTES, MINUTES)
+ .writeTimeout(XTREAM_CATALOG_TIMEOUT_MINUTES, MINUTES)
+ .build(),
+ json = xtreamJson
+ )
+ }
+
+ fun syncStateForProvider(providerId: Long): Flow<SyncState> =
+ syncStatesByProvider.map { states -> states[providerId] ?: SyncState.Idle }
+
+ fun currentSyncState(providerId: Long): SyncState =
+ _syncStatesByProvider.value[providerId] ?: SyncState.Idle
+
+ private suspend fun <T> withProviderLock(providerId: Long, block: suspend () -> T): T {
+ val mutex = providerSyncMutexes.computeIfAbsent(providerId) { Mutex() }
+ return mutex.withLock { block() }
+ }
+
+ suspend fun sync(
+ providerId: Long,
+ force: Boolean = false,
+ onProgress: ((String) -> Unit)? = null
+ ): com.streamvault.domain.model.Result<Unit> = withProviderLock(providerId) lock@{
+ val providerEntity = providerDao.getById(providerId)
+ ?: return@lock com.streamvault.domain.model.Result.error("Provider $providerId not found")
+
+ val provider = providerEntity
+ .copy(password = CredentialCrypto.decryptIfNeeded(providerEntity.password))
+ .toDomain()
+ publishSyncState(providerId, SyncState.Syncing("Starting..."))
+
+ try {
+ val outcome = withContext(Dispatchers.IO) {
+ when (provider.type) {
+ ProviderType.XTREAM_CODES -> syncXtream(provider, force, onProgress)
+ ProviderType.M3U -> syncM3u(provider, force, onProgress)
+ }
+ }
+ providerDao.updateSyncTime(providerId, System.currentTimeMillis())
+ updateSyncStatusMetadata(
+ providerId = providerId,
+ status = if (outcome.partial) "PARTIAL" else "SUCCESS"
+ )
+ publishSyncState(providerId, if (outcome.partial) {
+ SyncState.Partial("Sync completed with warnings", outcome.warnings)
+ } else {
+ SyncState.Success()
+ })
+ com.streamvault.domain.model.Result.success(Unit)
+ } catch (e: Exception) {
+ Log.e(TAG, "Sync failed for provider $providerId: ${redactUrlForLogs(e.message)}")
+ updateSyncStatusMetadata(providerId = providerId, status = "ERROR")
+ publishSyncState(providerId, SyncState.Error(e.message ?: "Unknown error", e))
+ com.streamvault.domain.model.Result.error(e.message ?: "Sync failed", e)
+ }
+ }
+
+ fun resetState(providerId: Long? = null) {
+ if (providerId == null) {
+ _syncStatesByProvider.value = emptyMap()
+ } else {
+ _syncStatesByProvider.update { states -> states - providerId }
+ }
+ _syncState.value = SyncState.Idle
+ }
+
+ suspend fun retrySection(
+ providerId: Long,
+ section: SyncRepairSection,
+ onProgress: ((String) -> Unit)? = null
+ ): com.streamvault.domain.model.Result<Unit> = withProviderLock(providerId) lock@{
+ val providerEntity = providerDao.getById(providerId)
+ ?: return@lock com.streamvault.domain.model.Result.error("Provider $providerId not found")
+
+ val provider = providerEntity
+ .copy(password = CredentialCrypto.decryptIfNeeded(providerEntity.password))
+ .toDomain()
+
+ try {
+ withContext(Dispatchers.IO) {
+ when (section) {
+ SyncRepairSection.EPG -> syncEpgOnly(provider, onProgress)
+ SyncRepairSection.MOVIES -> syncMoviesOnly(provider, onProgress)
+ SyncRepairSection.SERIES -> syncSeriesOnly(provider, onProgress)
+ }
+ }
+ updateSyncStatusMetadata(providerId = providerId, status = "SUCCESS")
+ publishSyncState(providerId, SyncState.Success())
+ com.streamvault.domain.model.Result.success(Unit)
+ } catch (e: Exception) {
+ Log.e(TAG, "Section retry failed for provider $providerId [$section]: ${redactUrlForLogs(e.message)}")
+ updateSyncStatusMetadata(providerId = providerId, status = "ERROR")
+ publishSyncState(providerId, SyncState.Error(e.message ?: "Retry failed", e))
+ com.streamvault.domain.model.Result.error(e.message ?: "Retry failed", e)
+ }
+ }
+
+ private suspend fun syncXtream(
+ provider: Provider,
+ force: Boolean,
+ onProgress: ((String) -> Unit)?
+ ): SyncOutcome {
+ val warnings = mutableListOf<String>()
+ UrlSecurityPolicy.validateXtreamServerUrl(provider.serverUrl)?.let { message ->
+ throw IllegalStateException(message)
+ }
+ progress(provider.id, onProgress, "Connecting to server...")
+ val api = createXtreamSyncProvider(provider)
+
+ var metadata = syncMetadataRepository.getMetadata(provider.id) ?: SyncMetadata(provider.id)
+ val now = System.currentTimeMillis()
+
+ if (force || ContentCachePolicy.shouldRefresh(metadata.lastLiveSync, ContentCachePolicy.CATALOG_TTL_MILLIS, now)) {
+ progress(provider.id, onProgress, "Downloading Live TV...")
+ val liveSyncResult = syncXtreamLiveCatalog(
+ provider = provider,
+ api = api,
+ onProgress = onProgress
+ )
+
+ when (val liveResult = liveSyncResult.catalogResult) {
+ is CatalogStrategyResult.Success -> {
+ liveSyncResult.categories?.let { categoryDao.replaceAll(provider.id, "LIVE", it) }
+ channelDao.replaceAll(provider.id, liveResult.items.map { it.toEntity() })
+ metadata = metadata.copy(lastLiveSync = now, liveCount = liveResult.items.size)
+ warnings += liveSyncResult.warnings + liveResult.warnings
+ }
+ is CatalogStrategyResult.Partial -> {
+ liveSyncResult.categories?.let { categoryDao.replaceAll(provider.id, "LIVE", it) }
+ channelDao.replaceAll(provider.id, liveResult.items.map { it.toEntity() })
+ metadata = metadata.copy(lastLiveSync = now, liveCount = liveResult.items.size)
+ warnings += liveSyncResult.warnings + liveResult.warnings + listOf("Live TV sync completed partially.")
+ }
+ is CatalogStrategyResult.EmptyValid -> {
+ val existingChannelCount = channelDao.getCount(provider.id).first()
+ Log.w(TAG, "Live TV sync kept existing catalog for provider ${provider.id}: empty valid result, existingCount=$existingChannelCount")
+ warnings += liveSyncResult.warnings + liveResult.warnings +
+ if (existingChannelCount > 0) {
+ listOf("Live TV refresh returned an empty valid catalog; keeping previous channel library.")
+ } else {
+ listOf("Live TV refresh returned an empty valid catalog with no previous channel library.")
+ }
+ if (existingChannelCount == 0) {
+ throw IllegalStateException("Live TV catalog was empty.")
+ }
+ }
+ is CatalogStrategyResult.Failure -> {
+ val existingChannelCount = channelDao.getCount(provider.id).first()
+ Log.w(TAG, "Live TV sync preserved previous catalog for provider ${provider.id}: strategy=${liveResult.strategyName}, existingCount=$existingChannelCount, reason=${sanitizeThrowableMessage(liveResult.error)}")
+ warnings += liveSyncResult.warnings + liveResult.warnings +
+ if (existingChannelCount > 0) {
+ listOf("Live TV sync degraded; keeping previous channel library.")
+ } else {
+ listOf("Live TV sync failed before any usable channel catalog was available.")
+ }
+ if (existingChannelCount == 0) {
+ throw IllegalStateException("Failed to fetch live streams: ${liveResult.error.message}")
+ }
+ }
+ }
+ syncMetadataRepository.updateMetadata(metadata)
+ }
+
+ if (force || ContentCachePolicy.shouldRefresh(metadata.lastMovieSync, ContentCachePolicy.CATALOG_TTL_MILLIS, now)) {
+ progress(provider.id, onProgress, "Downloading Movies...")
+ val movieSyncResult = syncXtreamMoviesCatalog(
+ provider = provider,
+ api = api,
+ existingMetadata = metadata,
+ onProgress = onProgress
+ )
+ val sawSequentialStress = (movieSyncResult.warnings + strategyWarnings(movieSyncResult.catalogResult))
+ .any { warning -> warning.contains(MOVIE_CATEGORY_SEQUENTIAL_MODE_WARNING, ignoreCase = true) }
+ val healthyMovieProviderAdaptation = updateMovieProviderAdaptation(
+ previousRemembered = metadata.movieParallelFailuresRemembered,
+ previousHealthyStreak = metadata.movieHealthySyncStreak,
+ sawSequentialStress = sawSequentialStress
+ )
+
+ when (val catalogResult = movieSyncResult.catalogResult) {
+ is CatalogStrategyResult.Success -> {
+ movieSyncResult.categories?.let { categoryDao.replaceAll(provider.id, "MOVIE", it) }
+ movieDao.replaceAll(provider.id, catalogResult.items.map { movie -> movie.toEntity() })
+ metadata = metadata.copy(
+ lastMovieSync = now,
+ lastMovieAttempt = now,
+ lastMovieSuccess = now,
+ movieCount = catalogResult.items.size,
+ movieSyncMode = movieSyncResult.syncMode,
+ movieWarningsCount = (movieSyncResult.warnings + catalogResult.warnings).size,
+ movieCatalogStale = false,
+ movieParallelFailuresRemembered = healthyMovieProviderAdaptation.rememberSequential,
+ movieHealthySyncStreak = healthyMovieProviderAdaptation.healthyStreak
+ )
+ }
+ is CatalogStrategyResult.Partial -> {
+ movieSyncResult.categories?.let { categoryDao.replaceAll(provider.id, "MOVIE", it) }
+ movieDao.replaceAll(provider.id, catalogResult.items.map { movie -> movie.toEntity() })
+ metadata = metadata.copy(
+ lastMovieSync = now,
+ lastMovieAttempt = now,
+ lastMoviePartial = now,
+ movieCount = catalogResult.items.size,
+ movieSyncMode = movieSyncResult.syncMode,
+ movieWarningsCount = (movieSyncResult.warnings + catalogResult.warnings).size,
+ movieCatalogStale = true,
+ movieParallelFailuresRemembered = metadata.movieParallelFailuresRemembered || sawSequentialStress,
+ movieHealthySyncStreak = 0
+ )
+ warnings += movieSyncResult.warnings + catalogResult.warnings
+ }
+ is CatalogStrategyResult.EmptyValid -> {
+ val existingMovieCount = movieDao.getCount(provider.id).first()
+ Log.w(TAG, "Movies sync kept existing catalog for provider ${provider.id}: empty valid result, existingCount=$existingMovieCount")
+ metadata = metadata.copy(
+ lastMovieAttempt = now,
+ movieSyncMode = movieSyncResult.syncMode,
+ movieWarningsCount = (movieSyncResult.warnings + catalogResult.warnings).size,
+ movieCatalogStale = existingMovieCount > 0 || movieSyncResult.syncMode == VodSyncMode.LAZY_BY_CATEGORY,
+ movieParallelFailuresRemembered = metadata.movieParallelFailuresRemembered || sawSequentialStress,
+ movieHealthySyncStreak = 0
+ )
+ warnings += movieSyncResult.warnings + catalogResult.warnings +
+ if (existingMovieCount > 0) {
+ listOf("Movies refresh returned an empty valid catalog; keeping previous movie library.")
+ } else {
+ listOf("Movies refresh returned an empty valid catalog with no previous movie library.")
+ }
+ }
+ is CatalogStrategyResult.Failure -> {
+ val existingMovieCount = movieDao.getCount(provider.id).first()
+ val finalMode = if (movieSyncResult.syncMode == VodSyncMode.LAZY_BY_CATEGORY) {
+ VodSyncMode.LAZY_BY_CATEGORY
+ } else {
+ metadata.movieSyncMode
+ }
+ if (movieSyncResult.syncMode == VodSyncMode.LAZY_BY_CATEGORY) {
+ movieSyncResult.categories?.let { categoryDao.replaceAll(provider.id, "MOVIE", it) }
+ }
+ Log.w(TAG, "Movies sync preserved previous catalog for provider ${provider.id}: strategy=${catalogResult.strategyName}, existingCount=$existingMovieCount, mode=${movieSyncResult.syncMode}, reason=${sanitizeThrowableMessage(catalogResult.error)}")
+ metadata = metadata.copy(
+ lastMovieAttempt = now,
+ movieSyncMode = finalMode,
+ movieWarningsCount = (movieSyncResult.warnings + catalogResult.warnings).size,
+ movieCatalogStale = existingMovieCount > 0 || movieSyncResult.syncMode == VodSyncMode.LAZY_BY_CATEGORY,
+ movieParallelFailuresRemembered = metadata.movieParallelFailuresRemembered || sawSequentialStress || shouldRememberSequentialPreference(catalogResult.error),
+ movieHealthySyncStreak = 0
+ )
+ warnings += movieSyncResult.warnings + catalogResult.warnings +
+ if (existingMovieCount > 0) {
+ listOf("Movies sync degraded; keeping previous movie library.")
+ } else {
+ listOf("Movies sync failed before any usable movie catalog was available.")
+ }
+ if (existingMovieCount == 0 && movieSyncResult.syncMode != VodSyncMode.LAZY_BY_CATEGORY) {
+ throw IllegalStateException("Failed to fetch movie catalog: ${catalogResult.error.message}")
+ }
+ }
+ }
+ syncMetadataRepository.updateMetadata(metadata)
+ }
+
+ if (force || ContentCachePolicy.shouldRefresh(metadata.lastSeriesSync, ContentCachePolicy.CATALOG_TTL_MILLIS, now)) {
+ progress(provider.id, onProgress, "Downloading Series...")
+ val seriesSyncResult = syncXtreamSeriesCatalog(
+ provider = provider,
+ api = api,
+ onProgress = onProgress
+ )
+
+ when (val seriesResult = seriesSyncResult.catalogResult) {
+ is CatalogStrategyResult.Success -> {
+ seriesSyncResult.categories?.let { categoryDao.replaceAll(provider.id, "SERIES", it) }
+ seriesDao.replaceAll(provider.id, seriesResult.items.map { it.toEntity() })
+ metadata = metadata.copy(lastSeriesSync = now, seriesCount = seriesResult.items.size)
+ warnings += seriesSyncResult.warnings + seriesResult.warnings
+ }
+ is CatalogStrategyResult.Partial -> {
+ seriesSyncResult.categories?.let { categoryDao.replaceAll(provider.id, "SERIES", it) }
+ seriesDao.replaceAll(provider.id, seriesResult.items.map { it.toEntity() })
+ metadata = metadata.copy(lastSeriesSync = now, seriesCount = seriesResult.items.size)
+ warnings += seriesSyncResult.warnings + seriesResult.warnings + listOf("Series sync completed partially.")
+ }
+ is CatalogStrategyResult.EmptyValid -> {
+ val existingSeriesCount = seriesDao.getCount(provider.id).first()
+ Log.w(TAG, "Series sync kept existing catalog for provider ${provider.id}: empty valid result, existingCount=$existingSeriesCount")
+ warnings += seriesSyncResult.warnings + seriesResult.warnings +
+ if (existingSeriesCount > 0) {
+ listOf("Series refresh returned an empty valid catalog; keeping previous series library.")
+ } else {
+ listOf("Series refresh returned an empty valid catalog with no previous series library.")
+ }
+ if (existingSeriesCount == 0) {
+ throw IllegalStateException("Series catalog was empty.")
+ }
+ }
+ is CatalogStrategyResult.Failure -> {
+ val existingSeriesCount = seriesDao.getCount(provider.id).first()
+ Log.w(TAG, "Series sync preserved previous catalog for provider ${provider.id}: strategy=${seriesResult.strategyName}, existingCount=$existingSeriesCount, reason=${sanitizeThrowableMessage(seriesResult.error)}")
+ warnings += seriesSyncResult.warnings + seriesResult.warnings +
+ if (existingSeriesCount > 0) {
+ listOf("Series sync degraded; keeping previous series library.")
+ } else {
+ listOf("Series sync failed before any usable series catalog was available.")
+ }
+ if (existingSeriesCount == 0) {
+ throw IllegalStateException("Failed to fetch series catalog: ${seriesResult.error.message}")
+ }
+ }
+ }
+ syncMetadataRepository.updateMetadata(metadata)
+ }
+
+ if (force || ContentCachePolicy.shouldRefresh(metadata.lastEpgSync, ContentCachePolicy.EPG_TTL_MILLIS, now)) {
+ try {
+ progress(provider.id, onProgress, "Downloading EPG...")
+ val base = provider.serverUrl.trimEnd('/')
+ val xmltvUrl = provider.epgUrl.ifBlank {
+ XtreamUrlFactory.buildXmltvUrl(base, provider.username, provider.password)
+ }
+ UrlSecurityPolicy.validateXtreamEpgUrl(xmltvUrl)?.let { message ->
+ throw IllegalStateException(message)
+ }
+ retryTransient { epgRepository.refreshEpg(provider.id, xmltvUrl) }
+ val epgCount = programDao.countByProvider(provider.id)
+ metadata = metadata.copy(
+ lastEpgSync = now,
+ epgCount = epgCount
+ )
+ syncMetadataRepository.updateMetadata(metadata)
+ if (epgCount == 0) {
+ warnings.add("EPG imported zero programs; live guide will fall back to on-demand Xtream data.")
+ }
+ } catch (e: Exception) {
+ Log.e(TAG, "EPG sync failed (non-fatal): ${sanitizeThrowableMessage(e)}")
+ warnings.add("EPG XMLTV sync failed; live guide will fall back to on-demand Xtream data.")
+ }
+ }
+
+ return if (warnings.isEmpty()) SyncOutcome() else SyncOutcome(partial = true, warnings = warnings)
+ }
+
+ private suspend fun syncM3u(
+ provider: Provider,
+ force: Boolean,
+ onProgress: ((String) -> Unit)?
+ ): SyncOutcome {
+ val warnings = mutableListOf<String>()
+ var metadata = syncMetadataRepository.getMetadata(provider.id) ?: SyncMetadata(provider.id)
+ val now = System.currentTimeMillis()
+
+ if (force || ContentCachePolicy.shouldRefresh(metadata.lastLiveSync, ContentCachePolicy.CATALOG_TTL_MILLIS, now)) {
+ val stats = withContext(Dispatchers.IO) { importM3uPlaylist(provider, onProgress) }
+ if (stats.liveCount == 0 && stats.movieCount == 0) {
+ throw IllegalStateException("Playlist is empty or contains no supported entries")
+ }
+ warnings += stats.warnings
+ if (provider.epgUrl.isBlank() && !stats.header.tvgUrl.isNullOrBlank()) {
+ providerDao.updateEpgUrl(provider.id, stats.header.tvgUrl)
+ }
+ metadata = metadata.copy(
+ lastLiveSync = now,
+ lastMovieSync = now,
+ lastSeriesSync = now,
+ lastMovieAttempt = now,
+ lastMovieSuccess = now,
+ liveCount = stats.liveCount,
+ movieCount = stats.movieCount,
+ movieSyncMode = VodSyncMode.FULL,
+ movieWarningsCount = stats.warnings.size,
+ movieCatalogStale = false,
+ movieHealthySyncStreak = 0
+ )
+ syncMetadataRepository.updateMetadata(metadata)
+ }
+
+ val currentEpgUrl = providerDao.getById(provider.id)?.epgUrl ?: provider.epgUrl
+ if (!currentEpgUrl.isNullOrBlank() && (force || ContentCachePolicy.shouldRefresh(metadata.lastEpgSync, ContentCachePolicy.EPG_TTL_MILLIS, now))) {
+ val epgValidationError = UrlSecurityPolicy.validateOptionalEpgUrl(currentEpgUrl)
+ if (epgValidationError != null) {
+ warnings.add(epgValidationError)
+ } else {
+ try {
+ progress(provider.id, onProgress, "Downloading EPG...")
+ retryTransient { epgRepository.refreshEpg(provider.id, currentEpgUrl) }
+ metadata = metadata.copy(
+ lastEpgSync = now,
+ epgCount = programDao.countByProvider(provider.id)
+ )
+ syncMetadataRepository.updateMetadata(metadata)
+ } catch (e: Exception) {
+ Log.e(TAG, "EPG sync failed (non-fatal): ${sanitizeThrowableMessage(e)}")
+ warnings.add("EPG sync failed")
+ }
+ }
+ }
+
+ return if (warnings.isEmpty()) SyncOutcome() else SyncOutcome(partial = true, warnings = warnings)
+ }
+
+ private suspend fun syncEpgOnly(
+ provider: Provider,
+ onProgress: ((String) -> Unit)?
+ ) {
+ progress(provider.id, onProgress, "Retrying EPG...")
+ val epgUrl = when (provider.type) {
+ ProviderType.XTREAM_CODES -> {
+ val base = provider.serverUrl.trimEnd('/')
+ provider.epgUrl.ifBlank {
+ XtreamUrlFactory.buildXmltvUrl(base, provider.username, provider.password)
+ }
+ }
+ ProviderType.M3U -> providerDao.getById(provider.id)?.epgUrl ?: provider.epgUrl
+ }
+ if (epgUrl.isBlank()) {
+ throw IllegalStateException("No EPG URL configured for this provider")
+ }
+ val validationError = when (provider.type) {
+ ProviderType.XTREAM_CODES -> UrlSecurityPolicy.validateXtreamEpgUrl(epgUrl)
+ ProviderType.M3U -> UrlSecurityPolicy.validateOptionalEpgUrl(epgUrl)
+ }
+ validationError?.let { message ->
+ throw IllegalStateException(message)
+ }
+ retryTransient { epgRepository.refreshEpg(provider.id, epgUrl) }
+ val now = System.currentTimeMillis()
+ val metadata = (syncMetadataRepository.getMetadata(provider.id) ?: SyncMetadata(provider.id))
+ .copy(
+ lastEpgSync = now,
+ epgCount = programDao.countByProvider(provider.id)
+ )
+ syncMetadataRepository.updateMetadata(metadata)
+ }
+
+ private suspend fun syncMoviesOnly(
+ provider: Provider,
+ onProgress: ((String) -> Unit)?
+ ) {
+ val now = System.currentTimeMillis()
+ when (provider.type) {
+ ProviderType.XTREAM_CODES -> {
+ progress(provider.id, onProgress, "Retrying Movies...")
+ val api = createXtreamSyncProvider(provider)
+ val currentMetadata = syncMetadataRepository.getMetadata(provider.id) ?: SyncMetadata(provider.id)
+ val movieSyncResult = syncXtreamMoviesCatalog(
+ provider = provider,
+ api = api,
+ existingMetadata = currentMetadata,
+ onProgress = onProgress
+ )
+ val sawSequentialStress = (movieSyncResult.warnings + strategyWarnings(movieSyncResult.catalogResult))
+ .any { warning -> warning.contains(MOVIE_CATEGORY_SEQUENTIAL_MODE_WARNING, ignoreCase = true) }
+ val healthyMovieProviderAdaptation = updateMovieProviderAdaptation(
+ previousRemembered = currentMetadata.movieParallelFailuresRemembered,
+ previousHealthyStreak = currentMetadata.movieHealthySyncStreak,
+ sawSequentialStress = sawSequentialStress
+ )
+ val movieWarnings = movieSyncResult.warnings + strategyWarnings(movieSyncResult.catalogResult)
+
+ val metadata = currentMetadata.copy(
+ lastMovieAttempt = now,
+ movieSyncMode = movieSyncResult.syncMode,
+ movieWarningsCount = movieWarnings.size,
+ movieCatalogStale = movieSyncResult.syncMode == VodSyncMode.LAZY_BY_CATEGORY,
+ movieParallelFailuresRemembered = currentMetadata.movieParallelFailuresRemembered || sawSequentialStress
+ )
+
+ when (val catalogResult = movieSyncResult.catalogResult) {
+ is CatalogStrategyResult.Success -> {
+ movieSyncResult.categories?.let { categoryDao.replaceAll(provider.id, "MOVIE", it) }
+ movieDao.replaceAll(provider.id, catalogResult.items.map { movie -> movie.toEntity() })
+ syncMetadataRepository.updateMetadata(
+ metadata.copy(
+ lastMovieSync = now,
+ lastMovieSuccess = now,
+ movieCount = catalogResult.items.size,
+ movieCatalogStale = false,
+ movieParallelFailuresRemembered = healthyMovieProviderAdaptation.rememberSequential,
+ movieHealthySyncStreak = healthyMovieProviderAdaptation.healthyStreak
+ )
+ )
+ }
+ is CatalogStrategyResult.Partial -> {
+ movieSyncResult.categories?.let { categoryDao.replaceAll(provider.id, "MOVIE", it) }
+ movieDao.replaceAll(provider.id, catalogResult.items.map { movie -> movie.toEntity() })
+ syncMetadataRepository.updateMetadata(
+ metadata.copy(
+ lastMovieSync = now,
+ lastMoviePartial = now,
+ movieCount = catalogResult.items.size,
+ movieCatalogStale = true,
+ movieParallelFailuresRemembered = currentMetadata.movieParallelFailuresRemembered || sawSequentialStress,
+ movieHealthySyncStreak = 0
+ )
+ )
+ }
+ is CatalogStrategyResult.EmptyValid -> {
+ val existingMovieCount = movieDao.getCount(provider.id).first()
+ syncMetadataRepository.updateMetadata(
+ metadata.copy(
+ movieCatalogStale = existingMovieCount > 0 || movieSyncResult.syncMode == VodSyncMode.LAZY_BY_CATEGORY,
+ movieParallelFailuresRemembered = currentMetadata.movieParallelFailuresRemembered || sawSequentialStress,
+ movieHealthySyncStreak = 0
+ )
+ )
+ throw IllegalStateException(
+ if (existingMovieCount > 0) {
+ "Movies refresh returned an empty catalog; existing library was preserved."
+ } else {
+ "Movies refresh returned an empty catalog."
+ }
+ )
+ }
+ is CatalogStrategyResult.Failure -> {
+ val existingMovieCount = movieDao.getCount(provider.id).first()
+ if (movieSyncResult.syncMode == VodSyncMode.LAZY_BY_CATEGORY) {
+ movieSyncResult.categories?.let { categoryDao.replaceAll(provider.id, "MOVIE", it) }
+ }
+ syncMetadataRepository.updateMetadata(
+ metadata.copy(
+ movieCatalogStale = existingMovieCount > 0 || movieSyncResult.syncMode == VodSyncMode.LAZY_BY_CATEGORY,
+ movieParallelFailuresRemembered = currentMetadata.movieParallelFailuresRemembered || sawSequentialStress || shouldRememberSequentialPreference(catalogResult.error),
+ movieHealthySyncStreak = 0
+ )
+ )
+ throw IllegalStateException(catalogResult.error.message ?: "Failed to fetch VOD streams", catalogResult.error)
+ }
+ }
+ }
+ ProviderType.M3U -> {
+ progress(provider.id, onProgress, "Retrying Movies...")
+ val stats = withContext(Dispatchers.IO) {
+ importM3uPlaylist(provider, onProgress, includeLive = false, includeMovies = true)
+ }
+ if (stats.movieCount == 0) {
+ throw IllegalStateException("Playlist contains no movie entries")
+ }
+ val metadata = (syncMetadataRepository.getMetadata(provider.id) ?: SyncMetadata(provider.id))
+ .copy(
+ lastMovieSync = now,
+ lastMovieAttempt = now,
+ lastMovieSuccess = now,
+ movieCount = stats.movieCount,
+ movieSyncMode = VodSyncMode.FULL,
+ movieWarningsCount = stats.warnings.size,
+ movieCatalogStale = false
+ )
+ syncMetadataRepository.updateMetadata(metadata)
+ }
+ }
+ }
+
+ private suspend fun syncSeriesOnly(
+ provider: Provider,
+ onProgress: ((String) -> Unit)?
+ ) {
+ if (provider.type != ProviderType.XTREAM_CODES) {
+ throw IllegalStateException("Series retry is available only for Xtream providers")
+ }
+ progress(provider.id, onProgress, "Retrying Series...")
+ val api = createXtreamSyncProvider(provider)
+ val seriesSyncResult = syncXtreamSeriesCatalog(
+ provider = provider,
+ api = api,
+ onProgress = onProgress
+ )
+
+ val now = System.currentTimeMillis()
+ val currentMetadata = syncMetadataRepository.getMetadata(provider.id) ?: SyncMetadata(provider.id)
+ when (val seriesResult = seriesSyncResult.catalogResult) {
+ is CatalogStrategyResult.Success -> {
+ seriesSyncResult.categories?.let { categoryDao.replaceAll(provider.id, "SERIES", it) }
+ seriesDao.replaceAll(provider.id, seriesResult.items.map { it.toEntity() })
+ syncMetadataRepository.updateMetadata(
+ currentMetadata.copy(lastSeriesSync = now, seriesCount = seriesResult.items.size)
+ )
+ }
+ is CatalogStrategyResult.Partial -> {
+ seriesSyncResult.categories?.let { categoryDao.replaceAll(provider.id, "SERIES", it) }
+ seriesDao.replaceAll(provider.id, seriesResult.items.map { it.toEntity() })
+ syncMetadataRepository.updateMetadata(
+ currentMetadata.copy(lastSeriesSync = now, seriesCount = seriesResult.items.size)
+ )
+ }
+ is CatalogStrategyResult.EmptyValid -> {
+ val existingSeriesCount = seriesDao.getCount(provider.id).first()
+ throw IllegalStateException(
+ if (existingSeriesCount > 0) {
+ "Series refresh returned an empty catalog; existing library was preserved."
+ } else {
+ "Series catalog was empty."
+ }
+ )
+ }
+ is CatalogStrategyResult.Failure -> {
+ throw IllegalStateException(seriesResult.error.message ?: "Failed to fetch series list", seriesResult.error)
+ }
+ }
+ }
+
+ private suspend fun syncXtreamMoviesCatalog(
+ provider: Provider,
+ api: XtreamProvider,
+ existingMetadata: SyncMetadata,
+ onProgress: ((String) -> Unit)?
+ ): MovieCatalogSyncResult {
+ Log.i(
+ TAG,
+ "Xtream movies strategy start for provider ${provider.id}. previousMode=${existingMetadata.movieSyncMode} rememberSequential=${existingMetadata.movieParallelFailuresRemembered}"
+ )
+ val rawVodCategories = fetchXtreamVodCategories(provider)
+ val resolvedCategories = rawVodCategories
+ ?.let { categories -> api.mapCategories(ContentType.MOVIE, categories) }
+ ?.map { category -> category.toEntity(provider.id) }
+ ?.takeIf { it.isNotEmpty() }
+
+ val fullResult = loadXtreamMoviesFull(provider, api)
+ when (fullResult) {
+ is CatalogStrategyResult.Success -> return MovieCatalogSyncResult(
+ catalogResult = fullResult,
+ categories = resolvedCategories ?: buildFallbackMovieCategories(provider.id, fullResult.items),
+ syncMode = VodSyncMode.FULL
+ ).also {
+ Log.i(TAG, "Xtream movies strategy selected FULL for provider ${provider.id} with ${fullResult.items.size} items.")
+ }
+ is CatalogStrategyResult.Partial -> return MovieCatalogSyncResult(
+ catalogResult = fullResult,
+ categories = resolvedCategories ?: buildFallbackMovieCategories(provider.id, fullResult.items),
+ syncMode = VodSyncMode.FULL,
+ warnings = emptyList()
+ ).also {
+ Log.w(TAG, "Xtream movies strategy selected FULL(partial) for provider ${provider.id} with ${fullResult.items.size} items.")
+ }
+ else -> Unit
+ }
+
+ val categoryResult = loadXtreamMoviesByCategory(
+ provider = provider,
+ api = api,
+ rawCategories = rawVodCategories.orEmpty(),
+ onProgress = onProgress,
+ preferSequential = existingMetadata.movieParallelFailuresRemembered
+ )
+ when (categoryResult) {
+ is CatalogStrategyResult.Success -> return MovieCatalogSyncResult(
+ catalogResult = categoryResult,
+ categories = resolvedCategories ?: buildFallbackMovieCategories(provider.id, categoryResult.items),
+ syncMode = VodSyncMode.CATEGORY_BULK,
+ warnings = strategyWarnings(fullResult)
+ ).also {
+ Log.i(TAG, "Xtream movies strategy selected CATEGORY_BULK for provider ${provider.id} with ${categoryResult.items.size} items.")
+ }
+ is CatalogStrategyResult.Partial -> return MovieCatalogSyncResult(
+ catalogResult = categoryResult,
+ categories = resolvedCategories ?: buildFallbackMovieCategories(provider.id, categoryResult.items),
+ syncMode = VodSyncMode.CATEGORY_BULK,
+ warnings = strategyWarnings(fullResult)
+ ).also {
+ Log.w(TAG, "Xtream movies strategy selected CATEGORY_BULK(partial) for provider ${provider.id} with ${categoryResult.items.size} items.")
+ }
+ else -> Unit
+ }
+
+ val pagedResult = loadXtreamMoviesByPage(provider, api, onProgress)
+ when (pagedResult) {
+ is CatalogStrategyResult.Success -> return MovieCatalogSyncResult(
+ catalogResult = pagedResult,
+ categories = resolvedCategories ?: buildFallbackMovieCategories(provider.id, pagedResult.items),
+ syncMode = VodSyncMode.PAGED,
+ warnings = strategyWarnings(fullResult) + strategyWarnings(categoryResult)
+ ).also {
+ Log.i(TAG, "Xtream movies strategy selected PAGED for provider ${provider.id} with ${pagedResult.items.size} items.")
+ }
+ is CatalogStrategyResult.Partial -> return MovieCatalogSyncResult(
+ catalogResult = pagedResult,
+ categories = resolvedCategories ?: buildFallbackMovieCategories(provider.id, pagedResult.items),
+ syncMode = VodSyncMode.PAGED,
+ warnings = strategyWarnings(fullResult) + strategyWarnings(categoryResult)
+ ).also {
+ Log.w(TAG, "Xtream movies strategy selected PAGED(partial) for provider ${provider.id} with ${pagedResult.items.size} items.")
+ }
+ else -> Unit
+ }
+
+ val lazyWarnings = buildList {
+ addAll(strategyWarnings(fullResult))
+ addAll(strategyWarnings(categoryResult))
+ addAll(strategyWarnings(pagedResult))
+ add("Movies entered lazy category-only mode after full, category-bulk, and paged strategies failed.")
+ }
+ Log.w(
+ TAG,
+ "Xtream movies strategy exhausted for provider ${provider.id}. categoriesAvailable=${!resolvedCategories.isNullOrEmpty()} finalMode=${if (!resolvedCategories.isNullOrEmpty()) VodSyncMode.LAZY_BY_CATEGORY else VodSyncMode.UNKNOWN}"
+ )
+
+ return if (!resolvedCategories.isNullOrEmpty()) {
+ MovieCatalogSyncResult(
+ catalogResult = CatalogStrategyResult.Failure(
+ strategyName = "lazy_by_category",
+ error = IllegalStateException("Movie catalog strategies failed; exposing categories only"),
+ warnings = lazyWarnings
+ ),
+ categories = resolvedCategories,
+ syncMode = VodSyncMode.LAZY_BY_CATEGORY,
+ warnings = lazyWarnings
+ )
+ } else {
+ MovieCatalogSyncResult(
+ catalogResult = CatalogStrategyResult.Failure(
+ strategyName = "movies",
+ error = IllegalStateException("Movie catalog strategies failed and no categories were available"),
+ warnings = lazyWarnings
+ ),
+ categories = null,
+ syncMode = VodSyncMode.UNKNOWN,
+ warnings = lazyWarnings
+ )
+ }
+ }
+
+ private suspend fun loadXtreamMoviesFull(
+ provider: Provider,
+ api: XtreamProvider
+ ): CatalogStrategyResult<Movie> {
+ var fullMovies: List<Movie>? = null
+ var fullMoviesFailure: Throwable? = null
+ val fullMoviesElapsedMs = measureTimeMillis {
+ runCatching {
+ retryXtreamCatalogTransient { api.getVodStreams().getOrThrow("VOD streams") }
+ }.onSuccess { movies ->
+ fullMovies = movies
+ }.onFailure { error ->
+ fullMoviesFailure = error
+ }
+ }
+ if (!fullMovies.isNullOrEmpty()) {
+ Log.i(
+ TAG,
+ "Xtream movies full catalog succeeded for provider ${provider.id} in ${fullMoviesElapsedMs}ms with ${fullMovies!!.size} items."
+ )
+ return CatalogStrategyResult.Success(
+ strategyName = "full",
+ items = fullMovies!!
+ )
+ }
+ return if (fullMoviesFailure != null) {
+ logXtreamCatalogFallback(
+ provider = provider,
+ section = "movies",
+ stage = "full catalog",
+ elapsedMs = fullMoviesElapsedMs,
+ itemCount = fullMovies?.size,
+ error = fullMoviesFailure,
+ nextStep = "category-bulk"
+ )
+ CatalogStrategyResult.Failure(
+ strategyName = "full",
+ error = fullMoviesFailure!!,
+ warnings = listOf("Movies full catalog request failed: ${sanitizeThrowableMessage(fullMoviesFailure)}")
+ )
+ } else {
+ logXtreamCatalogFallback(
+ provider = provider,
+ section = "movies",
+ stage = "full catalog",
+ elapsedMs = fullMoviesElapsedMs,
+ itemCount = fullMovies?.size,
+ error = null,
+ nextStep = "category-bulk"
+ )
+ CatalogStrategyResult.EmptyValid(
+ strategyName = "full",
+ warnings = listOf("Movies full catalog returned an empty valid result.")
+ )
+ }
+ }
+
+ private suspend fun syncXtreamLiveCatalog(
+ provider: Provider,
+ api: XtreamProvider,
+ onProgress: ((String) -> Unit)?
+ ): CatalogSyncPayload<Channel> {
+ Log.i(TAG, "Xtream live strategy start for provider ${provider.id}.")
+ val rawLiveCategories = runCatching {
+ retryTransient {
+ xtreamCatalogApiService.getLiveCategories(
+ XtreamUrlFactory.buildPlayerApiUrl(
+ serverUrl = provider.serverUrl,
+ username = provider.username,
+ password = provider.password,
+ action = "get_live_categories"
+ )
+ )
+ }
+ }.onFailure { error ->
+ Log.w(TAG, "Xtream live categories request failed for provider ${provider.id}: ${sanitizeThrowableMessage(error)}")
+ }.getOrNull()
+ val resolvedCategories = rawLiveCategories
+ ?.let { categories -> api.mapCategories(ContentType.LIVE, categories) }
+ ?.map { category -> category.toEntity(provider.id) }
+ ?.takeIf { it.isNotEmpty() }
+
+ val fullResult = loadXtreamLiveFull(provider, api)
+ when (fullResult) {
+ is CatalogStrategyResult.Success -> return CatalogSyncPayload(
+ catalogResult = fullResult,
+ categories = resolvedCategories ?: buildFallbackLiveCategories(provider.id, fullResult.items)
+ )
+ is CatalogStrategyResult.Partial -> return CatalogSyncPayload(
+ catalogResult = fullResult,
+ categories = resolvedCategories ?: buildFallbackLiveCategories(provider.id, fullResult.items),
+ warnings = emptyList()
+ )
+ else -> Unit
+ }
+
+ val categoryResult = loadXtreamLiveByCategory(provider, api, rawLiveCategories.orEmpty(), onProgress, preferSequential = false)
+ return CatalogSyncPayload(
+ catalogResult = categoryResult,
+ categories = when (categoryResult) {
+ is CatalogStrategyResult.Success -> resolvedCategories ?: buildFallbackLiveCategories(provider.id, categoryResult.items)
+ is CatalogStrategyResult.Partial -> resolvedCategories ?: buildFallbackLiveCategories(provider.id, categoryResult.items)
+ else -> null
+ },
+ warnings = strategyWarnings(fullResult)
+ )
+ }
+
+ private suspend fun loadXtreamLiveFull(
+ provider: Provider,
+ api: XtreamProvider
+ ): CatalogStrategyResult<Channel> {
+ var fullChannels: List<Channel>? = null
+ var fullChannelsFailure: Throwable? = null
+ val fullChannelsElapsedMs = measureTimeMillis {
+ runCatching {
+ retryXtreamCatalogTransient { api.getLiveStreams().getOrThrow("Live streams") }
+ }.onSuccess { channels ->
+ fullChannels = channels
+ }.onFailure { error ->
+ fullChannelsFailure = error
+ }
+ }
+ if (!fullChannels.isNullOrEmpty()) {
+ Log.i(TAG, "Xtream live full catalog succeeded for provider ${provider.id} in ${fullChannelsElapsedMs}ms with ${fullChannels!!.size} items.")
+ return CatalogStrategyResult.Success("full", fullChannels!!)
+ }
+ return if (fullChannelsFailure != null) {
+ logXtreamCatalogFallback(
+ provider = provider,
+ section = "live",
+ stage = "full catalog",
+ elapsedMs = fullChannelsElapsedMs,
+ itemCount = fullChannels?.size,
+ error = fullChannelsFailure,
+ nextStep = "category-bulk"
+ )
+ CatalogStrategyResult.Failure(
+ strategyName = "full",
+ error = fullChannelsFailure!!,
+ warnings = listOf("Live full catalog request failed: ${sanitizeThrowableMessage(fullChannelsFailure)}")
+ )
+ } else {
+ logXtreamCatalogFallback(
+ provider = provider,
+ section = "live",
+ stage = "full catalog",
+ elapsedMs = fullChannelsElapsedMs,
+ itemCount = fullChannels?.size,
+ error = null,
+ nextStep = "category-bulk"
+ )
+ CatalogStrategyResult.EmptyValid(
+ strategyName = "full",
+ warnings = listOf("Live full catalog returned an empty valid result.")
+ )
+ }
+ }
+
+ private suspend fun loadXtreamLiveByCategory(
+ provider: Provider,
+ api: XtreamProvider,
+ rawCategories: List<XtreamCategory>,
+ onProgress: ((String) -> Unit)?,
+ preferSequential: Boolean
+ ): CatalogStrategyResult<Channel> {
+ val categories = rawCategories.filter { it.categoryId.isNotBlank() }
+ if (categories.isEmpty()) {
+ return CatalogStrategyResult.Failure(
+ strategyName = "category_bulk",
+ error = IllegalStateException("No live categories available"),
+ warnings = listOf("Live category-bulk strategy was unavailable because no categories were returned.")
+ )
+ }
+
+ val concurrency = if (preferSequential) 1 else XTREAM_LIVE_CATEGORY_SYNC_MAX_CONCURRENCY
+ val semaphore = Semaphore(concurrency)
+ val progressCounter = java.util.concurrent.atomic.AtomicInteger(0)
+ val failureCount = java.util.concurrent.atomic.AtomicInteger(0)
+ val fastFailureCount = java.util.concurrent.atomic.AtomicInteger(0)
+ val warnings = mutableListOf<String>()
+ val warningsMutex = Mutex()
+ progress(provider.id, onProgress, "Downloading Live TV 0/${categories.size}...")
+
+ val categoryOutcomes = coroutineScope {
+ categories.map { category ->
+ async {
+ semaphore.withPermit {
+ rateLimitXtreamCatalogRequest()
+ var rawStreams: List<XtreamStream> = emptyList()
+ var categoryFailure: Throwable? = null
+ val elapsedMs = measureTimeMillis {
+ runCatching {
+ retryXtreamCatalogTransient {
+ xtreamCatalogApiService.getLiveStreams(
+ XtreamUrlFactory.buildPlayerApiUrl(
+ serverUrl = provider.serverUrl,
+ username = provider.username,
+ password = provider.password,
+ action = "get_live_streams",
+ extraQueryParams = mapOf("category_id" to category.categoryId)
+ )
+ )
+ }
+ }.onSuccess { streams ->
+ rawStreams = streams
+ }.onFailure { error ->
+ categoryFailure = error
+ }
+ }
+
+ val completed = progressCounter.incrementAndGet()
+ progress(provider.id, onProgress, "Downloading Live TV $completed/${categories.size}...")
+
+ when {
+ categoryFailure != null -> {
+ failureCount.incrementAndGet()
+ if (elapsedMs <= 5_000L) fastFailureCount.incrementAndGet()
+ val failure = categoryFailure!!
+ warningsMutex.withLock {
+ warnings += "Live category '${category.categoryName}' failed: ${sanitizeThrowableMessage(failure)}"
+ }
+ Log.w(TAG, "Xtream live category '${category.categoryName}' failed after ${elapsedMs}ms: ${sanitizeThrowableMessage(failure)}")
+ CategoryFetchOutcome.Failure(category.categoryName, failure)
+ }
+ rawStreams.isEmpty() -> {
+ Log.i(TAG, "Xtream live category '${category.categoryName}' completed in ${elapsedMs}ms with a valid empty result.")
+ CategoryFetchOutcome.Empty(category.categoryName)
+ }
+ else -> {
+ Log.i(TAG, "Xtream live category '${category.categoryName}' completed in ${elapsedMs}ms with ${rawStreams.size} raw items.")
+ CategoryFetchOutcome.Success(category.categoryName, api.mapLiveStreamsResponse(rawStreams))
+ }
+ }
+ }
+ }
+ }.awaitAll()
+ }
+
+ if (concurrency > 1 && shouldDowngradeCategorySync(categories.size, failureCount.get(), fastFailureCount.get(), categoryOutcomes)) {
+ Log.w(TAG, "Xtream live category sync is downgrading to sequential mode for provider ${provider.id}.")
+ return when (val sequentialResult = loadXtreamLiveByCategory(provider, api, rawCategories, onProgress, preferSequential = true)) {
+ is CatalogStrategyResult.Success -> sequentialResult.copy(warnings = sequentialResult.warnings + LIVE_CATEGORY_SEQUENTIAL_MODE_WARNING)
+ is CatalogStrategyResult.Partial -> sequentialResult.copy(warnings = sequentialResult.warnings + LIVE_CATEGORY_SEQUENTIAL_MODE_WARNING)
+ is CatalogStrategyResult.Failure -> sequentialResult.copy(warnings = sequentialResult.warnings + LIVE_CATEGORY_SEQUENTIAL_MODE_WARNING)
+ is CatalogStrategyResult.EmptyValid -> sequentialResult.copy(warnings = sequentialResult.warnings + LIVE_CATEGORY_SEQUENTIAL_MODE_WARNING)
+ }
+ }
+
+ val channels = categoryOutcomes
+ .asSequence()
+ .filterIsInstance<CategoryFetchOutcome.Success<Channel>>()
+ .flatMap { it.items.asSequence() }
+ .filter { it.streamId > 0L }
+ .associateBy { it.streamId }
+ .values
+ .toList()
+ val failedCategories = categoryOutcomes.count { it is CategoryFetchOutcome.Failure }
+ val emptyCategories = categoryOutcomes.count { it is CategoryFetchOutcome.Empty }
+ val successfulCategories = categoryOutcomes.count { it is CategoryFetchOutcome.Success }
+ Log.i(TAG, "Xtream live category strategy summary for provider ${provider.id}: successful=$successfulCategories empty=$emptyCategories failed=$failedCategories dedupedChannels=${channels.size} concurrency=$concurrency")
+
+ return when {
+ channels.isNotEmpty() && failedCategories == 0 -> CatalogStrategyResult.Success("category_bulk", channels, warnings.toList())
+ channels.isNotEmpty() -> CatalogStrategyResult.Partial("category_bulk", channels, warnings.toList())
+ failedCategories > 0 -> CatalogStrategyResult.Failure(
+ strategyName = "category_bulk",
+ error = IllegalStateException("Live category-bulk sync failed for all usable categories"),
+ warnings = warnings.toList()
+ )
+ else -> CatalogStrategyResult.EmptyValid(
+ strategyName = "category_bulk",
+ warnings = listOf("All live categories returned valid empty results.")
+ )
+ }
+ }
+
+ private suspend fun loadXtreamMoviesByCategory(
+ provider: Provider,
+ api: XtreamProvider,
+ rawCategories: List<XtreamCategory>,
+ onProgress: ((String) -> Unit)?,
+ preferSequential: Boolean
+ ): CatalogStrategyResult<Movie> {
+ val categories = rawCategories.filter { it.categoryId.isNotBlank() }
+ if (categories.isEmpty()) {
+ return CatalogStrategyResult.Failure(
+ strategyName = "category_bulk",
+ error = IllegalStateException("No VOD categories available"),
+ warnings = listOf("Movies category-bulk strategy was unavailable because no categories were returned.")
+ )
+ }
+
+ val concurrency = if (preferSequential) 1 else xtreamCategorySyncConcurrency(categories.size)
+ val semaphore = Semaphore(concurrency)
+ val progressCounter = java.util.concurrent.atomic.AtomicInteger(0)
+ val failureCount = java.util.concurrent.atomic.AtomicInteger(0)
+ val fastFailureCount = java.util.concurrent.atomic.AtomicInteger(0)
+ val warnings = mutableListOf<String>()
+ val warningsMutex = Mutex()
+ progress(provider.id, onProgress, "Downloading Movies 0/${categories.size}...")
+
+ val categoryOutcomes = coroutineScope {
+ categories.map { category ->
+ async {
+ semaphore.withPermit {
+ rateLimitXtreamCatalogRequest()
+ var rawStreams: List<XtreamStream> = emptyList()
+ var categoryFailure: Throwable? = null
+ val elapsedMs = measureTimeMillis {
+ runCatching {
+ retryXtreamCatalogTransient {
+ xtreamCatalogApiService.getVodStreams(
+ XtreamUrlFactory.buildPlayerApiUrl(
+ serverUrl = provider.serverUrl,
+ username = provider.username,
+ password = provider.password,
+ action = "get_vod_streams",
+ extraQueryParams = mapOf("category_id" to category.categoryId)
+ )
+ )
+ }
+ }.onSuccess { streams ->
+ rawStreams = streams
+ }.onFailure { error ->
+ categoryFailure = error
+ }
+ }
+
+ val completed = progressCounter.incrementAndGet()
+ progress(provider.id, onProgress, "Downloading Movies $completed/${categories.size}...")
+
+ when {
+ categoryFailure != null -> {
+ failureCount.incrementAndGet()
+ if (elapsedMs <= 5_000L) fastFailureCount.incrementAndGet()
+ val failure = categoryFailure!!
+ warningsMutex.withLock {
+ warnings += "Category '${category.categoryName}' failed: ${failure.message}"
+ }
+ Log.w(
+ TAG,
+ "Xtream movie category '${category.categoryName}' failed after ${elapsedMs}ms: ${failure::class.java.simpleName}: ${failure.message}"
+ )
+ CategoryFetchOutcome.Failure(category.categoryName, failure)
+ }
+ rawStreams.isEmpty() -> {
+ Log.i(TAG, "Xtream movie category '${category.categoryName}' completed in ${elapsedMs}ms with a valid empty result.")
+ CategoryFetchOutcome.Empty(category.categoryName)
+ }
+ else -> {
+ Log.i(TAG, "Xtream movie category '${category.categoryName}' completed in ${elapsedMs}ms with ${rawStreams.size} raw items.")
+ CategoryFetchOutcome.Success(category.categoryName, api.mapVodStreamsResponse(rawStreams))
+ }
+ }
+ }
+ }
+ }.awaitAll()
+ }
+
+ if (concurrency > 1 && shouldDowngradeCategorySync(
+ totalCategories = categories.size,
+ failures = failureCount.get(),
+ fastFailures = fastFailureCount.get(),
+ outcomes = categoryOutcomes
+ )
+ ) {
+ val downgradeReasons = buildList {
+ add("failures=${failureCount.get()}/${categories.size}")
+ if (fastFailureCount.get() > 0) add("fastFailures=${fastFailureCount.get()}")
+ val providerStressSignals = categoryOutcomes.count { outcome ->
+ outcome is CategoryFetchOutcome.Failure && shouldRememberSequentialPreference(outcome.error)
+ }
+ if (providerStressSignals > 0) add("providerStressSignals=$providerStressSignals")
+ }.joinToString(", ")
+ Log.w(
+ TAG,
+ "Xtream movie category sync is downgrading to sequential mode for provider ${provider.id}: $downgradeReasons"
+ )
+ return when (val sequentialResult = loadXtreamMoviesByCategory(
+ provider = provider,
+ api = api,
+ rawCategories = rawCategories,
+ onProgress = onProgress,
+ preferSequential = true
+ )) {
+ is CatalogStrategyResult.Success -> sequentialResult.copy(
+ warnings = sequentialResult.warnings + MOVIE_CATEGORY_SEQUENTIAL_MODE_WARNING
+ )
+ is CatalogStrategyResult.Partial -> sequentialResult.copy(
+ warnings = sequentialResult.warnings + MOVIE_CATEGORY_SEQUENTIAL_MODE_WARNING
+ )
+ is CatalogStrategyResult.Failure -> sequentialResult.copy(
+ warnings = sequentialResult.warnings + MOVIE_CATEGORY_SEQUENTIAL_MODE_WARNING
+ )
+ is CatalogStrategyResult.EmptyValid -> sequentialResult.copy(
+ warnings = sequentialResult.warnings + MOVIE_CATEGORY_SEQUENTIAL_MODE_WARNING
+ )
+ }
+ }
+
+ val movies = categoryOutcomes
+ .asSequence()
+ .filterIsInstance<CategoryFetchOutcome.Success<Movie>>()
+ .flatMap { it.items.asSequence() }
+ .filter { it.streamId > 0L }
+ .associateBy { it.streamId }
+ .values
+ .toList()
+
+ val failedCategories = categoryOutcomes.count { it is CategoryFetchOutcome.Failure }
+ val successfulCategories = categoryOutcomes.count { it is CategoryFetchOutcome.Success }
+ val emptyCategories = categoryOutcomes.count { it is CategoryFetchOutcome.Empty }
+ Log.i(
+ TAG,
+ "Xtream movie category strategy summary for provider ${provider.id}: successful=$successfulCategories empty=$emptyCategories failed=$failedCategories dedupedMovies=${movies.size} concurrency=$concurrency"
+ )
+ return when {
+ movies.isNotEmpty() && failedCategories == 0 -> CatalogStrategyResult.Success(
+ strategyName = "category_bulk",
+ items = movies,
+ warnings = warnings.toList()
+ )
+ movies.isNotEmpty() -> CatalogStrategyResult.Partial(
+ strategyName = "category_bulk",
+ items = movies,
+ warnings = warnings.toList()
+ )
+ failedCategories > 0 -> CatalogStrategyResult.Failure(
+ strategyName = "category_bulk",
+ error = IllegalStateException("Movie category-bulk sync failed for all usable categories"),
+ warnings = warnings.toList()
+ )
+ else -> CatalogStrategyResult.EmptyValid(
+ strategyName = "category_bulk",
+ warnings = listOf("All movie categories returned valid empty results.")
+ )
+ }
+ }
+
+ private suspend fun loadXtreamMoviesByPage(
+ provider: Provider,
+ api: XtreamProvider,
+ onProgress: ((String) -> Unit)?
+ ): CatalogStrategyResult<Movie> {
+ val moviesByStreamId = LinkedHashMap<Long, Movie>()
+ val warnings = mutableListOf<String>()
+ var sawValidPage = false
+ for (page in 1..XTREAM_CATALOG_MAX_PAGES) {
+ progress(provider.id, onProgress, "Downloading Movies page $page...")
+ rateLimitXtreamCatalogRequest()
+ var rawStreams: List<XtreamStream> = emptyList()
+ var pageFailure: Throwable? = null
+ val pageElapsedMs = measureTimeMillis {
+ runCatching {
+ retryXtreamCatalogTransient {
+ xtreamCatalogApiService.getVodStreams(
+ XtreamUrlFactory.buildPlayerApiUrl(
+ serverUrl = provider.serverUrl,
+ username = provider.username,
+ password = provider.password,
+ action = "get_vod_streams",
+ extraQueryParams = paginationParamsForPage(page)
+ )
+ )
+ }
+ }.onSuccess { streams ->
+ rawStreams = streams
+ }.onFailure { error ->
+ pageFailure = error
+ }
+ }
+
+ if (pageFailure != null) {
+ val failure = pageFailure!!
+ Log.w(
+ TAG,
+ "Xtream paged movie request failed for provider ${provider.id} on page $page after ${pageElapsedMs}ms: ${failure::class.java.simpleName}: ${failure.message}"
+ )
+ return if (page == 1 || moviesByStreamId.isEmpty()) {
+ CatalogStrategyResult.Failure(
+ strategyName = "paged",
+ error = failure,
+ warnings = listOf("Movie paging failed on the first page: ${failure.message}")
+ )
+ } else {
+ warnings += "Movie paging failed on page $page: ${failure.message}"
+ CatalogStrategyResult.Partial(
+ strategyName = "paged",
+ items = moviesByStreamId.values.toList(),
+ warnings = warnings.toList()
+ )
+ }
+ }
+
+ Log.i(
+ TAG,
+ "Xtream paged movie request for provider ${provider.id} page $page completed in ${pageElapsedMs}ms with ${rawStreams.size} raw items."
+ )
+
+ if (rawStreams.isEmpty()) {
+ return when {
+ moviesByStreamId.isNotEmpty() -> CatalogStrategyResult.Success(
+ strategyName = "paged",
+ items = moviesByStreamId.values.toList(),
+ warnings = warnings.toList()
+ )
+ sawValidPage -> CatalogStrategyResult.EmptyValid(
+ strategyName = "paged",
+ warnings = listOf("Paged movie catalog returned no items.")
+ )
+ else -> CatalogStrategyResult.EmptyValid(
+ strategyName = "paged",
+ warnings = listOf("Paged movie catalog is unsupported or empty on this provider.")
+ )
+ }
+ }
+
+ sawValidPage = true
+ val mappedMovies = api.mapVodStreamsResponse(rawStreams)
+ val beforeCount = moviesByStreamId.size
+ mappedMovies.forEach { movie ->
+ if (movie.streamId > 0L) {
+ moviesByStreamId[movie.streamId] = movie
+ }
+ }
+ val newItems = moviesByStreamId.size - beforeCount
+ if (rawStreams.size < XTREAM_CATALOG_PAGE_SIZE || newItems == 0) {
+ break
+ }
+ }
+
+ return moviesByStreamId.values.toList()
+ .takeIf { it.isNotEmpty() }
+ ?.let { items ->
+ Log.i(TAG, "Xtream paged movie strategy completed for provider ${provider.id} with ${items.size} deduped items.")
+ CatalogStrategyResult.Success("paged", items, warnings.toList())
+ }
+ ?: CatalogStrategyResult.EmptyValid(
+ strategyName = "paged",
+ warnings = listOf("Paged movie catalog completed without items.")
+ )
+ }
+
+ private suspend fun syncXtreamSeriesCatalog(
+ provider: Provider,
+ api: XtreamProvider,
+ onProgress: ((String) -> Unit)?
+ ): CatalogSyncPayload<Series> {
+ Log.i(TAG, "Xtream series strategy start for provider ${provider.id}.")
+ val rawSeriesCategories = runCatching {
+ retryTransient {
+ xtreamCatalogApiService.getSeriesCategories(
+ XtreamUrlFactory.buildPlayerApiUrl(
+ serverUrl = provider.serverUrl,
+ username = provider.username,
+ password = provider.password,
+ action = "get_series_categories"
+ )
+ )
+ }
+ }.onFailure { error ->
+ Log.w(TAG, "Xtream series categories request failed for provider ${provider.id}: ${sanitizeThrowableMessage(error)}")
+ }.getOrNull()
+ val resolvedCategories = rawSeriesCategories
+ ?.let { categories -> api.mapCategories(ContentType.SERIES, categories) }
+ ?.map { category -> category.toEntity(provider.id) }
+ ?.takeIf { it.isNotEmpty() }
+
+ val fullResult = loadXtreamSeriesFull(provider, api)
+ when (fullResult) {
+ is CatalogStrategyResult.Success -> return CatalogSyncPayload(
+ catalogResult = fullResult,
+ categories = resolvedCategories ?: buildFallbackSeriesCategories(provider.id, fullResult.items)
+ )
+ is CatalogStrategyResult.Partial -> return CatalogSyncPayload(
+ catalogResult = fullResult,
+ categories = resolvedCategories ?: buildFallbackSeriesCategories(provider.id, fullResult.items),
+ warnings = emptyList()
+ )
+ else -> Unit
+ }
+
+ val categoryResult = loadXtreamSeriesByCategory(provider, api, rawSeriesCategories.orEmpty(), onProgress, preferSequential = false)
+ when (categoryResult) {
+ is CatalogStrategyResult.Success -> return CatalogSyncPayload(
+ catalogResult = categoryResult,
+ categories = resolvedCategories ?: buildFallbackSeriesCategories(provider.id, categoryResult.items),
+ warnings = strategyWarnings(fullResult)
+ )
+ is CatalogStrategyResult.Partial -> return CatalogSyncPayload(
+ catalogResult = categoryResult,
+ categories = resolvedCategories ?: buildFallbackSeriesCategories(provider.id, categoryResult.items),
+ warnings = strategyWarnings(fullResult)
+ )
+ else -> Unit
+ }
+
+ val pagedResult = loadXtreamSeriesByPage(provider, api, onProgress)
+ return CatalogSyncPayload(
+ catalogResult = pagedResult,
+ categories = when (pagedResult) {
+ is CatalogStrategyResult.Success -> resolvedCategories ?: buildFallbackSeriesCategories(provider.id, pagedResult.items)
+ is CatalogStrategyResult.Partial -> resolvedCategories ?: buildFallbackSeriesCategories(provider.id, pagedResult.items)
+ else -> null
+ },
+ warnings = strategyWarnings(fullResult) + strategyWarnings(categoryResult)
+ )
+ }
+
+ private suspend fun loadXtreamSeriesFull(
+ provider: Provider,
+ api: XtreamProvider
+ ): CatalogStrategyResult<Series> {
+ var fullSeries: List<Series>? = null
+ var fullSeriesFailure: Throwable? = null
+ val fullSeriesElapsedMs = measureTimeMillis {
+ runCatching {
+ retryXtreamCatalogTransient { api.getSeriesList().getOrThrow("Series list") }
+ }.onSuccess { series ->
+ fullSeries = series
+ }.onFailure { error ->
+ fullSeriesFailure = error
+ }
+ }
+ if (!fullSeries.isNullOrEmpty()) {
+ Log.i(TAG, "Xtream series full catalog succeeded for provider ${provider.id} in ${fullSeriesElapsedMs}ms with ${fullSeries!!.size} items.")
+ return CatalogStrategyResult.Success("full", fullSeries!!)
+ }
+ return if (fullSeriesFailure != null) {
+ logXtreamCatalogFallback(
+ provider = provider,
+ section = "series",
+ stage = "full catalog",
+ elapsedMs = fullSeriesElapsedMs,
+ itemCount = fullSeries?.size,
+ error = fullSeriesFailure,
+ nextStep = "category-bulk"
+ )
+ CatalogStrategyResult.Failure(
+ strategyName = "full",
+ error = fullSeriesFailure!!,
+ warnings = listOf("Series full catalog request failed: ${sanitizeThrowableMessage(fullSeriesFailure)}")
+ )
+ } else {
+ logXtreamCatalogFallback(
+ provider = provider,
+ section = "series",
+ stage = "full catalog",
+ elapsedMs = fullSeriesElapsedMs,
+ itemCount = fullSeries?.size,
+ error = null,
+ nextStep = "category-bulk"
+ )
+ CatalogStrategyResult.EmptyValid(
+ strategyName = "full",
+ warnings = listOf("Series full catalog returned an empty valid result.")
+ )
+ }
+ }
+
+ private suspend fun loadXtreamSeriesByCategory(
+ provider: Provider,
+ api: XtreamProvider,
+ rawCategories: List<XtreamCategory>,
+ onProgress: ((String) -> Unit)?,
+ preferSequential: Boolean
+ ): CatalogStrategyResult<Series> {
+ val categories = rawCategories.filter { it.categoryId.isNotBlank() }
+ if (categories.isEmpty()) {
+ return CatalogStrategyResult.Failure(
+ strategyName = "category_bulk",
+ error = IllegalStateException("No series categories available"),
+ warnings = listOf("Series category-bulk strategy was unavailable because no categories were returned.")
+ )
+ }
+
+ val concurrency = if (preferSequential) 1 else xtreamCategorySyncConcurrency(categories.size)
+ val semaphore = Semaphore(concurrency)
+ val progressCounter = java.util.concurrent.atomic.AtomicInteger(0)
+ val failureCount = java.util.concurrent.atomic.AtomicInteger(0)
+ val fastFailureCount = java.util.concurrent.atomic.AtomicInteger(0)
+ val warnings = mutableListOf<String>()
+ val warningsMutex = Mutex()
+ progress(provider.id, onProgress, "Downloading Series 0/${categories.size}...")
+
+ val categoryOutcomes = coroutineScope {
+ categories.map { category ->
+ async {
+ semaphore.withPermit {
+ rateLimitXtreamCatalogRequest()
+ var rawSeries: List<XtreamSeriesItem> = emptyList()
+ var categoryFailure: Throwable? = null
+ val elapsedMs = measureTimeMillis {
+ runCatching {
+ retryXtreamCatalogTransient {
+ xtreamCatalogApiService.getSeriesList(
+ XtreamUrlFactory.buildPlayerApiUrl(
+ serverUrl = provider.serverUrl,
+ username = provider.username,
+ password = provider.password,
+ action = "get_series",
+ extraQueryParams = mapOf("category_id" to category.categoryId)
+ )
+ )
+ }
+ }.onSuccess { series ->
+ rawSeries = series
+ }.onFailure { error ->
+ categoryFailure = error
+ }
+ }
+
+ val completed = progressCounter.incrementAndGet()
+ progress(provider.id, onProgress, "Downloading Series $completed/${categories.size}...")
+
+ when {
+ categoryFailure != null -> {
+ failureCount.incrementAndGet()
+ if (elapsedMs <= 5_000L) fastFailureCount.incrementAndGet()
+ val failure = categoryFailure!!
+ warningsMutex.withLock {
+ warnings += "Series category '${category.categoryName}' failed: ${sanitizeThrowableMessage(failure)}"
+ }
+ Log.w(TAG, "Xtream series category '${category.categoryName}' failed after ${elapsedMs}ms: ${sanitizeThrowableMessage(failure)}")
+ CategoryFetchOutcome.Failure(category.categoryName, failure)
+ }
+ rawSeries.isEmpty() -> {
+ Log.i(TAG, "Xtream series category '${category.categoryName}' completed in ${elapsedMs}ms with a valid empty result.")
+ CategoryFetchOutcome.Empty(category.categoryName)
+ }
+ else -> {
+ Log.i(TAG, "Xtream series category '${category.categoryName}' completed in ${elapsedMs}ms with ${rawSeries.size} raw items.")
+ CategoryFetchOutcome.Success(category.categoryName, api.mapSeriesListResponse(rawSeries))
+ }
+ }
+ }
+ }
+ }.awaitAll()
+ }
+
+ if (concurrency > 1 && shouldDowngradeCategorySync(categories.size, failureCount.get(), fastFailureCount.get(), categoryOutcomes)) {
+ Log.w(TAG, "Xtream series category sync is downgrading to sequential mode for provider ${provider.id}.")
+ return when (val sequentialResult = loadXtreamSeriesByCategory(provider, api, rawCategories, onProgress, preferSequential = true)) {
+ is CatalogStrategyResult.Success -> sequentialResult.copy(warnings = sequentialResult.warnings + SERIES_CATEGORY_SEQUENTIAL_MODE_WARNING)
+ is CatalogStrategyResult.Partial -> sequentialResult.copy(warnings = sequentialResult.warnings + SERIES_CATEGORY_SEQUENTIAL_MODE_WARNING)
+ is CatalogStrategyResult.Failure -> sequentialResult.copy(warnings = sequentialResult.warnings + SERIES_CATEGORY_SEQUENTIAL_MODE_WARNING)
+ is CatalogStrategyResult.EmptyValid -> sequentialResult.copy(warnings = sequentialResult.warnings + SERIES_CATEGORY_SEQUENTIAL_MODE_WARNING)
+ }
+ }
+
+ val series = categoryOutcomes
+ .asSequence()
+ .filterIsInstance<CategoryFetchOutcome.Success<Series>>()
+ .flatMap { it.items.asSequence() }
+ .filter { it.seriesId > 0L }
+ .associateBy { it.seriesId }
+ .values
+ .toList()
+ val failedCategories = categoryOutcomes.count { it is CategoryFetchOutcome.Failure }
+ val emptyCategories = categoryOutcomes.count { it is CategoryFetchOutcome.Empty }
+ val successfulCategories = categoryOutcomes.count { it is CategoryFetchOutcome.Success }
+ Log.i(TAG, "Xtream series category strategy summary for provider ${provider.id}: successful=$successfulCategories empty=$emptyCategories failed=$failedCategories dedupedSeries=${series.size} concurrency=$concurrency")
+
+ return when {
+ series.isNotEmpty() && failedCategories == 0 -> CatalogStrategyResult.Success("category_bulk", series, warnings.toList())
+ series.isNotEmpty() -> CatalogStrategyResult.Partial("category_bulk", series, warnings.toList())
+ failedCategories > 0 -> CatalogStrategyResult.Failure(
+ strategyName = "category_bulk",
+ error = IllegalStateException("Series category-bulk sync failed for all usable categories"),
+ warnings = warnings.toList()
+ )
+ else -> CatalogStrategyResult.EmptyValid(
+ strategyName = "category_bulk",
+ warnings = listOf("All series categories returned valid empty results.")
+ )
+ }
+ }
+
+ private suspend fun loadXtreamSeriesByPage(
+ provider: Provider,
+ api: XtreamProvider,
+ onProgress: ((String) -> Unit)?
+ ): CatalogStrategyResult<Series> {
+ val seriesById = LinkedHashMap<Long, Series>()
+ val warnings = mutableListOf<String>()
+ var sawValidPage = false
+ for (page in 1..XTREAM_CATALOG_MAX_PAGES) {
+ progress(provider.id, onProgress, "Downloading Series page $page...")
+ rateLimitXtreamCatalogRequest()
+ var rawSeries: List<XtreamSeriesItem> = emptyList()
+ var pageFailure: Throwable? = null
+ val pageElapsedMs = measureTimeMillis {
+ runCatching {
+ retryXtreamCatalogTransient {
+ xtreamCatalogApiService.getSeriesList(
+ XtreamUrlFactory.buildPlayerApiUrl(
+ serverUrl = provider.serverUrl,
+ username = provider.username,
+ password = provider.password,
+ action = "get_series",
+ extraQueryParams = paginationParamsForPage(page)
+ )
+ )
+ }
+ }.onSuccess { series ->
+ rawSeries = series
+ }.onFailure { error ->
+ pageFailure = error
+ }
+ }
+
+ if (pageFailure != null) {
+ val failure = pageFailure!!
+ Log.w(TAG, "Xtream paged series request failed for provider ${provider.id} on page $page after ${pageElapsedMs}ms: ${sanitizeThrowableMessage(failure)}")
+ return if (page == 1 || seriesById.isEmpty()) {
+ CatalogStrategyResult.Failure(
+ strategyName = "paged",
+ error = failure,
+ warnings = listOf("Series paging failed on the first page: ${sanitizeThrowableMessage(failure)}")
+ )
+ } else {
+ warnings += "Series paging failed on page $page: ${sanitizeThrowableMessage(failure)}"
+ CatalogStrategyResult.Partial(
+ strategyName = "paged",
+ items = seriesById.values.toList(),
+ warnings = warnings.toList()
+ )
+ }
+ }
+
+ Log.i(TAG, "Xtream paged series request for provider ${provider.id} page $page completed in ${pageElapsedMs}ms with ${rawSeries.size} raw items.")
+ if (rawSeries.isEmpty()) {
+ return when {
+ seriesById.isNotEmpty() -> CatalogStrategyResult.Success("paged", seriesById.values.toList(), warnings.toList())
+ sawValidPage -> CatalogStrategyResult.EmptyValid("paged", listOf("Paged series catalog returned no items."))
+ else -> CatalogStrategyResult.EmptyValid("paged", listOf("Paged series catalog is unsupported or empty on this provider."))
+ }
+ }
+
+ sawValidPage = true
+ val mappedSeries = api.mapSeriesListResponse(rawSeries)
+ val beforeCount = seriesById.size
+ mappedSeries.forEach { item ->
+ if (item.seriesId > 0L) {
+ seriesById[item.seriesId] = item
+ }
+ }
+ val newItems = seriesById.size - beforeCount
+ if (rawSeries.size < XTREAM_CATALOG_PAGE_SIZE || newItems == 0) {
+ break
+ }
+ }
+
+ return seriesById.values.toList()
+ .takeIf { it.isNotEmpty() }
+ ?.let { items -> CatalogStrategyResult.Success("paged", items, warnings.toList()) }
+ ?: CatalogStrategyResult.EmptyValid(
+ strategyName = "paged",
+ warnings = listOf("Paged series catalog completed without items.")
+ )
+ }
+
+ private suspend fun updateSyncStatusMetadata(providerId: Long, status: String) {
+ val metadata = (syncMetadataRepository.getMetadata(providerId) ?: SyncMetadata(providerId))
+ .copy(lastSyncStatus = status)
+ syncMetadataRepository.updateMetadata(metadata)
+ }
+
+ private suspend fun importM3uPlaylist(
+ provider: Provider,
+ onProgress: ((String) -> Unit)?,
+ includeLive: Boolean = true,
+ includeMovies: Boolean = true,
+ batchSize: Int = 1000
+ ): M3uImportStats {
+ UrlSecurityPolicy.validatePlaylistSourceUrl(provider.m3uUrl.ifBlank { provider.serverUrl })?.let { message ->
+ throw IllegalStateException(message)
+ }
+ progress(provider.id, onProgress, "Downloading Playlist...")
+ val existingChannelIds = if (includeLive) channelDao.getIdMappings(provider.id).associate { it.remoteId to it.id } else emptyMap()
+ val existingMovieIds = if (includeMovies) movieDao.getIdMappings(provider.id).associate { it.remoteId to it.id } else emptyMap()
+ val stableLongHasher = StableLongHasher()
+ val liveCategories = CategoryAccumulator(provider.id, ContentType.LIVE, stableLongHasher)
+ val movieCategories = CategoryAccumulator(provider.id, ContentType.MOVIE, stableLongHasher)
+ val channelBatch = ArrayList<ChannelEntity>(batchSize)
+ val movieBatch = ArrayList<MovieEntity>(batchSize)
+ val seenLiveStreamIds = if (includeLive) mutableSetOf<Long>() else null
+ val seenMovieStreamIds = if (includeMovies) mutableSetOf<Long>() else null
+ var header = M3uParser.M3uHeader()
+ var liveCount = 0
+ var movieCount = 0
+ var parsedCount = 0
+ var nextMilestone = PROGRESS_INTERVAL
+ val warnings = mutableListOf<String>()
+ var insecureStreamCount = 0
+
+ openPlaylistStream(provider) { streamed ->
+ progress(provider.id, onProgress, "Parsing Playlist...")
+ maybeDecompressPlaylist(streamed).use { input ->
+ m3uParser.parseStreaming(
+ inputStream = input,
+ onHeader = { parsedHeader ->
+ val secureEpgUrl = parsedHeader.tvgUrl?.takeIf { UrlSecurityPolicy.isSecureRemoteUrl(it) }
+ if (parsedHeader.tvgUrl != null && secureEpgUrl == null) {
+ warnings += "Ignored insecure EPG URL from playlist header."
+ }
+ header = parsedHeader.copy(tvgUrl = secureEpgUrl)
+ }
+ ) { entry ->
+ parsedCount++
+ if (parsedCount >= nextMilestone) {
+ progress(provider.id, onProgress, "Imported $parsedCount playlist entries...")
+ nextMilestone += PROGRESS_INTERVAL
+ }
+ if (!UrlSecurityPolicy.isAllowedStreamEntryUrl(entry.url)) {
+ insecureStreamCount++
+ return@parseStreaming
+ }
+
+ val safeLogoUrl = UrlSecurityPolicy.sanitizeImportedAssetUrl(entry.tvgLogo)
+ val safeCatchUpSource = UrlSecurityPolicy.sanitizeImportedAssetUrl(entry.catchUpSource)
+
+ if (isVodEntry(entry)) {
+ if (!includeMovies) {
+ return@parseStreaming
+ }
+ val groupTitle = entry.groupTitle.ifBlank { "Uncategorized" }
+ val stableStreamId = stableId(provider.id, entry.tvgId, entry.url, stableLongHasher)
+ val categoryId = movieCategories.idFor(groupTitle)
+ val isAdult = AdultContentClassifier.isAdultCategoryName(groupTitle)
+ seenMovieStreamIds?.add(stableStreamId)
+ movieBatch.add(
+ MovieEntity(
+ id = existingMovieIds[stableStreamId] ?: 0L,
+ streamId = stableStreamId,
+ name = entry.name,
+ posterUrl = safeLogoUrl,
+ categoryId = categoryId,
+ categoryName = groupTitle,
+ streamUrl = entry.url,
+ providerId = provider.id,
+ rating = entry.rating?.toFloatOrNull() ?: 0f,
+ year = entry.year,
+ genre = entry.genre,
+ isAdult = isAdult
+ )
+ )
+ movieCount++
+ if (movieBatch.size >= batchSize) {
+ flushMovieBatch(movieBatch)
+ }
+ } else {
+ if (!includeLive) {
+ return@parseStreaming
+ }
+ val groupTitle = entry.groupTitle.ifBlank { "Uncategorized" }
+ val stableStreamId = stableId(provider.id, entry.tvgId, entry.url, stableLongHasher)
+ val categoryId = liveCategories.idFor(groupTitle)
+ val isAdult = AdultContentClassifier.isAdultCategoryName(groupTitle)
+ seenLiveStreamIds?.add(stableStreamId)
+ channelBatch.add(
+ ChannelEntity(
+ id = existingChannelIds[stableStreamId] ?: 0L,
+ streamId = stableStreamId,
+ name = entry.name,
+ logoUrl = safeLogoUrl,
+ groupTitle = groupTitle,
+ categoryId = categoryId,
+ categoryName = groupTitle,
+ epgChannelId = entry.tvgId ?: entry.tvgName,
+ number = entry.tvgChno ?: 0,
+ streamUrl = entry.url,
+ catchUpSupported = entry.catchUp != null,
+ catchUpDays = entry.catchUpDays ?: 0,
+ catchUpSource = safeCatchUpSource,
+ providerId = provider.id,
+ isAdult = isAdult
+ )
+ )
+ liveCount++
+ if (channelBatch.size >= batchSize) {
+ flushChannelBatch(channelBatch)
+ }
+ }
+ }
+ }
+ }
+
+ flushChannelBatch(channelBatch)
+ flushMovieBatch(movieBatch)
+ if (includeLive) {
+ categoryDao.replaceAll(provider.id, "LIVE", liveCategories.entities())
+ pruneStaleChannels(existingChannelIds, seenLiveStreamIds.orEmpty())
+ }
+ if (includeMovies) {
+ categoryDao.replaceAll(provider.id, "MOVIE", movieCategories.entities())
+ pruneStaleMovies(existingMovieIds, seenMovieStreamIds.orEmpty())
+ movieDao.restoreWatchProgress(provider.id)
+ }
+
+ if (insecureStreamCount > 0) {
+ warnings += "Ignored $insecureStreamCount insecure playlist stream URL(s)."
+ }
+
+ return M3uImportStats(
+ header = header,
+ liveCount = liveCount,
+ movieCount = movieCount,
+ warnings = warnings
+ )
+ }
+
+ private suspend fun openPlaylistStream(
+ provider: Provider,
+ block: suspend (StreamedPlaylist) -> Unit
+ ) {
+ val urlStr = provider.m3uUrl.ifBlank { provider.serverUrl }
+ if (urlStr.startsWith("file:")) {
+ java.io.File(java.net.URI(urlStr)).inputStream().use { input ->
+ block(StreamedPlaylist(inputStream = input, sourceName = urlStr))
+ }
+ return
+ }
+
+ retryTransient {
+ okHttpClient.newCall(Request.Builder().url(urlStr).build()).execute().use { response ->
+ ensureSuccessfulPlaylistResponse(response)
+ val body = response.body ?: throw IllegalStateException("Empty M3U response")
+ body.byteStream().use { input ->
+ block(
+ StreamedPlaylist(
+ inputStream = input,
+ contentEncoding = response.header("Content-Encoding"),
+ sourceName = urlStr
+ )
+ )
+ }
+ }
+ }
+ }
+
+ private fun ensureSuccessfulPlaylistResponse(response: Response) {
+ if (response.isSuccessful) {
+ return
+ }
+ if (response.code in 500..599 || response.code == 429) {
+ throw IOException("Transient HTTP ${response.code}")
+ }
+ throw IllegalStateException("Failed to download M3U: HTTP ${response.code}")
+ }
+
+ private fun maybeDecompressPlaylist(streamed: StreamedPlaylist): InputStream {
+ val buffered = if (streamed.inputStream is BufferedInputStream) {
+ streamed.inputStream
+ } else {
+ BufferedInputStream(streamed.inputStream, 64 * 1024)
+ }
+ buffered.mark(2)
+ val first = buffered.read()
+ val second = buffered.read()
+ buffered.reset()
+ val gzipMagic = first == 0x1f && second == 0x8b
+ val encodedGzip = streamed.contentEncoding?.contains("gzip", ignoreCase = true) == true
+ val namedGzip = streamed.sourceName?.lowercase()?.endsWith(".gz") == true
+ return if (gzipMagic || encodedGzip || namedGzip) {
+ GZIPInputStream(buffered, 64 * 1024)
+ } else {
+ buffered
+ }
+ }
+
+ private suspend fun flushChannelBatch(batch: MutableList<ChannelEntity>) {
+ if (batch.isEmpty()) {
+ return
+ }
+ channelDao.insertAll(batch.distinctBy { it.streamId })
+ batch.clear()
+ }
+
+ private suspend fun flushMovieBatch(batch: MutableList<MovieEntity>) {
+ if (batch.isEmpty()) {
+ return
+ }
+ movieDao.insertAll(batch.distinctBy { it.streamId })
+ batch.clear()
+ }
+
+ private suspend fun pruneStaleChannels(
+ existingChannelIds: Map<Long, Long>,
+ seenStreamIds: Set<Long>
+ ) {
+ val staleIds = existingChannelIds
+ .filterKeys { it !in seenStreamIds }
+ .values
+
+ staleIds.chunked(900).forEach { chunk ->
+ if (chunk.isNotEmpty()) {
+ channelDao.deleteByIds(chunk)
+ }
+ }
+ }
+
+ private suspend fun pruneStaleMovies(
+ existingMovieIds: Map<Long, Long>,
+ seenStreamIds: Set<Long>
+ ) {
+ val staleIds = existingMovieIds
+ .filterKeys { it !in seenStreamIds }
+ .values
+
+ staleIds.chunked(900).forEach { chunk ->
+ if (chunk.isNotEmpty()) {
+ movieDao.deleteByIds(chunk)
+ }
+ }
+ }
+
+ private suspend fun fetchXtreamVodCategories(provider: Provider): List<XtreamCategory>? {
+ return runCatching {
+ retryTransient {
+ xtreamCatalogApiService.getVodCategories(
+ XtreamUrlFactory.buildPlayerApiUrl(
+ serverUrl = provider.serverUrl,
+ username = provider.username,
+ password = provider.password,
+ action = "get_vod_categories"
+ )
+ )
+ }
+ }.onFailure { error ->
+ Log.w(TAG, "Xtream VOD categories request failed for provider ${provider.id}: ${error::class.java.simpleName}: ${sanitizeThrowableMessage(error)}")
+ }.getOrNull()
+ }
+
+ private fun strategyWarnings(result: CatalogStrategyResult<*>): List<String> = when (result) {
+ is CatalogStrategyResult.Success -> result.warnings
+ is CatalogStrategyResult.Partial -> result.warnings
+ is CatalogStrategyResult.Failure -> result.warnings
+ is CatalogStrategyResult.EmptyValid -> result.warnings
+ }
+
+ private fun <T> shouldDowngradeCategorySync(
+ totalCategories: Int,
+ failures: Int,
+ fastFailures: Int,
+ outcomes: List<CategoryFetchOutcome<T>>
+ ): Boolean {
+ if (totalCategories <= 1) return false
+ val failureRatio = failures.toFloat() / totalCategories.toFloat()
+ val firstWindow = outcomes.take(minOf(4, outcomes.size))
+ val firstWindowFailures = firstWindow.count { outcome ->
+ outcome is CategoryFetchOutcome.Failure && shouldRememberSequentialPreference(outcome.error)
+ }
+ return failureRatio >= 0.75f ||
+ fastFailures >= minOf(3, totalCategories) ||
+ firstWindowFailures >= minOf(3, firstWindow.size)
+ }
+
+ private fun shouldRememberSequentialPreference(error: Throwable): Boolean {
+ return error is XtreamAuthenticationException ||
+ error is XtreamParsingException ||
+ (error is XtreamRequestException && error.statusCode in setOf(403, 429)) ||
+ (error is XtreamNetworkException && error.message.orEmpty().contains("reset", ignoreCase = true))
+ }
+
+ private fun paginationParamsForPage(page: Int): Map<String, String> {
+ return mapOf(
+ "page" to page.toString(),
+ "limit" to XTREAM_CATALOG_PAGE_SIZE.toString(),
+ "offset" to ((page - 1) * XTREAM_CATALOG_PAGE_SIZE).toString(),
+ "items_per_page" to XTREAM_CATALOG_PAGE_SIZE.toString()
+ )
+ }
+
+ private suspend fun rateLimitXtreamCatalogRequest() {
+ delay(250L)
+ }
+
+ private fun updateMovieProviderAdaptation(
+ previousRemembered: Boolean,
+ previousHealthyStreak: Int,
+ sawSequentialStress: Boolean
+ ): MovieProviderAdaptation {
+ if (sawSequentialStress) {
+ return MovieProviderAdaptation(rememberSequential = true, healthyStreak = 0)
+ }
+ if (!previousRemembered) {
+ return MovieProviderAdaptation(rememberSequential = false, healthyStreak = 0)
+ }
+ val nextHealthyStreak = (previousHealthyStreak + 1).coerceAtMost(2)
+ return if (nextHealthyStreak >= 2) {
+ MovieProviderAdaptation(rememberSequential = false, healthyStreak = 0)
+ } else {
+ MovieProviderAdaptation(rememberSequential = true, healthyStreak = nextHealthyStreak)
+ }
+ }
+
+ private fun stableId(
+ providerId: Long,
+ tvgId: String?,
+ url: String,
+ hasher: StableLongHasher
+ ): Long {
+ return if (!tvgId.isNullOrBlank()) {
+ hasher.hash("$providerId:tvg:$tvgId")
+ } else {
+ hasher.hash("$providerId:url:$url")
+ }
+ }
+
+ private fun buildFallbackMovieCategories(providerId: Long, movies: List<Movie>): List<CategoryEntity> {
+ return buildFallbackCategories(
+ providerId = providerId,
+ type = ContentType.MOVIE,
+ items = movies,
+ categoryId = { movie -> movie.categoryId },
+ categoryName = { movie -> movie.categoryName },
+ isAdult = { movie -> movie.isAdult }
+ )
+ }
+
+ private fun buildFallbackLiveCategories(providerId: Long, channels: List<Channel>): List<CategoryEntity> {
+ return buildFallbackCategories(
+ providerId = providerId,
+ type = ContentType.LIVE,
+ items = channels,
+ categoryId = { channel -> channel.categoryId },
+ categoryName = { channel -> channel.categoryName ?: channel.groupTitle },
+ isAdult = { channel -> channel.isAdult }
+ )
+ }
+
+ private fun buildFallbackSeriesCategories(providerId: Long, series: List<Series>): List<CategoryEntity> {
+ return buildFallbackCategories(
+ providerId = providerId,
+ type = ContentType.SERIES,
+ items = series,
+ categoryId = { item -> item.categoryId },
+ categoryName = { item -> item.categoryName },
+ isAdult = { item -> item.isAdult }
+ )
+ }
+
+ private fun <T> buildFallbackCategories(
+ providerId: Long,
+ type: ContentType,
+ items: List<T>,
+ categoryId: (T) -> Long?,
+ categoryName: (T) -> String?,
+ isAdult: (T) -> Boolean
+ ): List<CategoryEntity> {
+ return items
+ .asSequence()
+ .mapNotNull { item ->
+ val resolvedCategoryId = categoryId(item) ?: return@mapNotNull null
+ val resolvedCategoryName = categoryName(item)?.trim().takeUnless { it.isNullOrEmpty() }
+ ?: "Category $resolvedCategoryId"
+ CategoryEntity(
+ categoryId = resolvedCategoryId,
+ name = resolvedCategoryName,
+ parentId = 0,
+ type = type,
+ providerId = providerId,
+ isAdult = isAdult(item) || AdultContentClassifier.isAdultCategoryName(resolvedCategoryName)
+ )
+ }
+ .distinctBy { it.categoryId }
+ .toList()
+ }
+
+ /** Delegates to M3uParser to avoid duplicate logic. */
+ internal fun isVodEntry(entry: M3uParser.M3uEntry): Boolean = M3uParser.isVodEntry(entry)
+
+ private fun progress(providerId: Long, callback: ((String) -> Unit)?, message: String) {
+ publishSyncState(providerId, SyncState.Syncing(message))
+ callback?.invoke(message)
+ }
+
+ private fun publishSyncState(providerId: Long, state: SyncState) {
+ _syncState.value = state
+ _syncStatesByProvider.update { states -> states + (providerId to state) }
+ }
+
+ private fun redactUrlForLogs(url: String?): String {
+ if (url.isNullOrBlank()) return "<empty>"
+ return runCatching {
+ val parsed = java.net.URI(url)
+ val scheme = parsed.scheme ?: "http"
+ val host = parsed.host ?: return@runCatching "<redacted>"
+ val path = parsed.path.orEmpty()
+ "$scheme://$host$path"
+ }.getOrDefault("<redacted>")
+ }
+
+ private fun sanitizeThrowableMessage(error: Throwable?): String {
+ return sanitizeLogMessage(error?.message)
+ }
+
+ private fun sanitizeLogMessage(message: String?): String {
+ if (message.isNullOrBlank()) {
+ return "<empty>"
+ }
+ return message
+ .replace(Regex("""https?://\S+""", RegexOption.IGNORE_CASE), "<redacted-url>")
+ .replace(Regex("""([?&](username|password|token)=[^&\s]+)""", RegexOption.IGNORE_CASE), "<redacted-param>")
+ }
+
+ private suspend fun <T> retryTransient(
+ maxAttempts: Int = 3,
+ initialDelayMs: Long = 700L,
+ block: suspend () -> T
+ ): T {
+ var attempt = 0
+ var delayMs = initialDelayMs
+ var lastError: Throwable? = null
+
+ while (attempt < maxAttempts) {
+ try {
+ return block()
+ } catch (t: Throwable) {
+ lastError = t
+ attempt++
+ if (attempt >= maxAttempts || !isRetryable(t)) {
+ throw t
+ }
+ delay(delayMs)
+ delayMs *= 2
+ }
+ }
+
+ throw lastError ?: IllegalStateException("Unknown sync retry failure")
+ }
+
+ private suspend fun <T> retryXtreamCatalogTransient(block: suspend () -> T): T {
+ var attempt = 0
+ var delayMs = 1_000L
+ var lastError: Throwable? = null
+
+ while (attempt < 3) {
+ try {
+ return block()
+ } catch (t: Throwable) {
+ lastError = t
+ attempt++
+ if (attempt >= 3 || !isXtreamCatalogRetryable(t, attempt)) {
+ throw t
+ }
+ val jitterMs = Random.nextLong(0L, (delayMs / 3L).coerceAtLeast(1L) + 1L)
+ delay(delayMs + jitterMs)
+ delayMs = (delayMs * 2).coerceAtMost(8_000L)
+ }
+ }
+
+ throw lastError ?: IllegalStateException("Unknown Xtream catalog retry failure")
+ }
+
+ private fun isRetryable(error: Throwable): Boolean {
+ if (error is XtreamAuthenticationException) return false
+ if (error is XtreamParsingException) return false
+ if (error is XtreamRequestException) return false
+ if (error is XtreamNetworkException) return true
+ if (error is IOException) return true
+
+ val message = error.message.orEmpty().lowercase()
+ return message.contains("timeout") ||
+ message.contains("timed out") ||
+ message.contains("unable to resolve host") ||
+ message.contains("connection reset") ||
+ message.contains("connect") ||
+ message.contains("network")
+ }
+
+ private fun isXtreamCatalogRetryable(error: Throwable, attempt: Int): Boolean {
+ return when (error) {
+ is XtreamAuthenticationException -> false
+ is XtreamParsingException -> attempt == 1
+ is XtreamRequestException -> error.statusCode == 408 || error.statusCode == 409 || error.statusCode in 500..599
+ is XtreamNetworkException -> true
+ is IOException -> true
+ else -> isRetryable(error)
+ }
+ }
+
+ companion object {
+ private const val PROGRESS_INTERVAL = 5_000
+ private const val XTREAM_CATEGORY_SYNC_MAX_CONCURRENCY = 2
+ }
+
+ private fun xtreamCategorySyncConcurrency(categoryCount: Int): Int {
+ return categoryCount
+ .coerceAtLeast(1)
+ .coerceAtMost(XTREAM_CATEGORY_SYNC_MAX_CONCURRENCY)
+ }
+
+ private fun createXtreamSyncProvider(provider: Provider): XtreamProvider {
+ return XtreamProvider(
+ providerId = provider.id,
+ api = xtreamCatalogApiService,
+ serverUrl = provider.serverUrl,
+ username = provider.username,
+ password = provider.password,
+ allowedOutputFormats = provider.allowedOutputFormats
+ )
+ }
+
+ private fun logXtreamCatalogFallback(
+ provider: Provider,
+ section: String,
+ stage: String,
+ elapsedMs: Long,
+ itemCount: Int?,
+ error: Throwable?,
+ nextStep: String
+ ) {
+ val reason = when {
+ error != null -> "${error::class.java.simpleName}: ${sanitizeThrowableMessage(error)}"
+ itemCount == 0 -> "empty result"
+ else -> "no usable data"
+ }
+ Log.w(
+ TAG,
+ "Xtream $section $stage failed for provider ${provider.id} after ${elapsedMs}ms ($reason). Switching to $nextStep."
+ )
+ }
+
+ private fun <T> com.streamvault.domain.model.Result<T>.getOrThrow(resourceName: String): T {
+ return when (this) {
+ is com.streamvault.domain.model.Result.Success -> data
+ is com.streamvault.domain.model.Result.Error ->
+ throw exception ?: IllegalStateException("Failed to fetch $resourceName: $message")
+ is com.streamvault.domain.model.Result.Loading ->
+ throw Exception("Unexpected loading state for $resourceName")
+ }
+ }
+}
+
diff --git a/app/build.gradle.kts b/app/build.gradle.kts
index ef501154..9186a197 100644
--- a/app/build.gradle.kts
+++ b/app/build.gradle.kts
@@ -96,6 +96,7 @@ dependencies {
implementation(libs.compose.ui.tooling.preview)
debugImplementation(libs.compose.ui.tooling)
debugImplementation("androidx.compose.ui:ui-test-manifest")
+ debugImplementation(libs.leakcanary.android)
// Compose TV
implementation(libs.compose.tv.foundation)
diff --git a/app/src/main/java/com/streamvault/app/StreamVaultApp.kt b/app/src/main/java/com/streamvault/app/StreamVaultApp.kt
index ed452786..648cc48a 100644
--- a/app/src/main/java/com/streamvault/app/StreamVaultApp.kt
+++ b/app/src/main/java/com/streamvault/app/StreamVaultApp.kt
@@ -7,6 +7,7 @@ import coil3.SingletonImageLoader
import coil3.disk.DiskCache
import coil3.memory.MemoryCache
import coil3.request.crossfade
+import com.streamvault.app.diagnostics.RuntimeDiagnosticsManager
import com.streamvault.app.ui.accessibility.isReducedMotionEnabled
import dagger.hilt.android.HiltAndroidApp
import kotlinx.coroutines.Dispatchers
@@ -20,9 +21,11 @@ import androidx.work.WorkManager
@HiltAndroidApp
class StreamVaultApp : Application(), SingletonImageLoader.Factory {
+ private val runtimeDiagnosticsManager by lazy { RuntimeDiagnosticsManager(this) }
override fun onCreate() {
super.onCreate()
+ runtimeDiagnosticsManager.start()
// Schedule daily data maintenance: EPG pruning, stale-favorite cleanup, and DB compaction checks.
// BLD-H02: Require network + device idle so the worker doesn't drain battery.
@@ -43,6 +46,11 @@ class StreamVaultApp : Application(), SingletonImageLoader.Factory {
)
}
+ override fun onTerminate() {
+ runtimeDiagnosticsManager.stop()
+ super.onTerminate()
+ }
+
override fun newImageLoader(context: PlatformContext): ImageLoader {
return ImageLoader.Builder(context)
.memoryCache {
diff --git a/app/src/main/java/com/streamvault/app/di/DatabaseModule.kt b/app/src/main/java/com/streamvault/app/di/DatabaseModule.kt
index fe25593d..e56d7a0f 100644
--- a/app/src/main/java/com/streamvault/app/di/DatabaseModule.kt
+++ b/app/src/main/java/com/streamvault/app/di/DatabaseModule.kt
@@ -43,7 +43,11 @@ object DatabaseModule {
StreamVaultDatabase.MIGRATION_15_16,
StreamVaultDatabase.MIGRATION_16_17,
StreamVaultDatabase.MIGRATION_17_18,
- StreamVaultDatabase.MIGRATION_18_19
+ StreamVaultDatabase.MIGRATION_18_19,
+ StreamVaultDatabase.MIGRATION_19_20,
+ StreamVaultDatabase.MIGRATION_20_21,
+ StreamVaultDatabase.MIGRATION_21_22,
+ StreamVaultDatabase.MIGRATION_22_23
)
// NOTE: fallbackToDestructiveMigration() intentionally removed.
// All future schema changes MUST add a corresponding Migration in StreamVaultDatabase.
@@ -56,6 +60,7 @@ object DatabaseModule {
@Provides fun provideSeriesDao(db: StreamVaultDatabase): SeriesDao = db.seriesDao()
@Provides fun provideEpisodeDao(db: StreamVaultDatabase): EpisodeDao = db.episodeDao()
@Provides fun provideCategoryDao(db: StreamVaultDatabase): CategoryDao = db.categoryDao()
+ @Provides fun provideCatalogSyncDao(db: StreamVaultDatabase): CatalogSyncDao = db.catalogSyncDao()
@Provides fun provideProgramDao(db: StreamVaultDatabase): ProgramDao = db.programDao()
@Provides fun provideFavoriteDao(db: StreamVaultDatabase): FavoriteDao = db.favoriteDao()
@Provides fun provideVirtualGroupDao(db: StreamVaultDatabase): VirtualGroupDao = db.virtualGroupDao()
diff --git a/app/src/main/java/com/streamvault/app/diagnostics/RuntimeDiagnosticsManager.kt b/app/src/main/java/com/streamvault/app/diagnostics/RuntimeDiagnosticsManager.kt
new file mode 100644
index 00000000..34dc0903
--- /dev/null
+++ b/app/src/main/java/com/streamvault/app/diagnostics/RuntimeDiagnosticsManager.kt
@@ -0,0 +1,173 @@
+package com.streamvault.app.diagnostics
+
+import android.app.Activity
+import android.app.ActivityManager
+import android.app.Application
+import android.content.ComponentCallbacks2
+import android.content.res.Configuration
+import android.os.Build
+import android.os.Bundle
+import android.os.Debug
+import android.util.Log
+import com.streamvault.app.BuildConfig
+import java.io.File
+import java.time.OffsetDateTime
+import java.time.format.DateTimeFormatter
+import java.util.Locale
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.Job
+import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.cancel
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.isActive
+import kotlinx.coroutines.launch
+
+class RuntimeDiagnosticsManager(
+ private val application: Application
+) : ComponentCallbacks2 {
+ private val activityManager = application.getSystemService(ActivityManager::class.java)
+ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
+ private val formatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME
+ private val outputFile by lazy {
+ File(application.filesDir, "diagnostics/runtime-memory.log").also { file ->
+ file.parentFile?.mkdirs()
+ }
+ }
+ private var samplingJob: Job? = null
+ private var started = false
+ private var startedActivityCount = 0
+
+ private val activityCallbacks = object : Application.ActivityLifecycleCallbacks {
+ override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) = Unit
+ override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) = Unit
+ override fun onActivityDestroyed(activity: Activity) {
+ writeSnapshot("activity_destroyed:${activity.javaClass.simpleName}")
+ }
+
+ override fun onActivityStarted(activity: Activity) {
+ startedActivityCount++
+ writeSnapshot("activity_started:${activity.javaClass.simpleName}")
+ if (startedActivityCount == 1) {
+ onAppForegrounded()
+ }
+ }
+
+ override fun onActivityResumed(activity: Activity) {
+ writeSnapshot("activity_resumed:${activity.javaClass.simpleName}")
+ }
+
+ override fun onActivityPaused(activity: Activity) = Unit
+
+ override fun onActivityStopped(activity: Activity) {
+ startedActivityCount = (startedActivityCount - 1).coerceAtLeast(0)
+ if (startedActivityCount == 0) {
+ onAppBackgrounded()
+ }
+ }
+ }
+
+ fun start() {
+ if (!BuildConfig.DEBUG || started) return
+ started = true
+ application.registerComponentCallbacks(this)
+ application.registerActivityLifecycleCallbacks(activityCallbacks)
+ writeSnapshot("app_start")
+ }
+
+ fun stop() {
+ if (!started) return
+ samplingJob?.cancel()
+ samplingJob = null
+ application.unregisterActivityLifecycleCallbacks(activityCallbacks)
+ application.unregisterComponentCallbacks(this)
+ scope.cancel()
+ started = false
+ }
+
+ private fun onAppForegrounded() {
+ writeSnapshot("process_foreground")
+ if (samplingJob == null) {
+ samplingJob = scope.launch {
+ while (isActive) {
+ delay(SAMPLE_INTERVAL_MS)
+ writeSnapshot("periodic")
+ }
+ }
+ }
+ }
+
+ private fun onAppBackgrounded() {
+ writeSnapshot("process_background")
+ samplingJob?.cancel()
+ samplingJob = null
+ }
+
+ override fun onTrimMemory(level: Int) {
+ writeSnapshot("trim_memory:${trimLevelLabel(level)}")
+ }
+
+ override fun onLowMemory() {
+ writeSnapshot("low_memory")
+ }
+
+ override fun onConfigurationChanged(newConfig: Configuration) = Unit
+
+ private fun writeSnapshot(reason: String) {
+ if (!BuildConfig.DEBUG) return
+ scope.launch(Dispatchers.IO) {
+ val snapshot = captureSnapshot(reason)
+ runCatching {
+ outputFile.appendText(snapshot + System.lineSeparator())
+ }.onFailure { error ->
+ Log.w(TAG, "Failed to append runtime diagnostics snapshot: ${error.message}")
+ }
+ Log.i(TAG, snapshot)
+ }
+ }
+
+ private fun captureSnapshot(reason: String): String {
+ val runtime = Runtime.getRuntime()
+ val javaUsedBytes = runtime.totalMemory() - runtime.freeMemory()
+ val memoryInfo = ActivityManager.MemoryInfo().also { info ->
+ activityManager?.getMemoryInfo(info)
+ }
+ val debugInfo = Debug.MemoryInfo().also(Debug::getMemoryInfo)
+ return buildString {
+ append("ts=").append(OffsetDateTime.now().format(formatter))
+ append(" reason=").append(reason)
+ append(" javaUsedMb=").append(bytesToMb(javaUsedBytes))
+ append(" javaMaxMb=").append(bytesToMb(runtime.maxMemory()))
+ append(" nativeHeapMb=").append(bytesToMb(Debug.getNativeHeapAllocatedSize()))
+ append(" pssKb=").append(debugInfo.totalPss)
+ append(" privateDirtyKb=").append(debugInfo.totalPrivateDirty)
+ append(" availMemMb=").append(bytesToMb(memoryInfo.availMem))
+ append(" lowMemory=").append(memoryInfo.lowMemory)
+ append(" trimThresholdMb=").append(bytesToMb(memoryInfo.threshold))
+ append(" startedActivities=").append(startedActivityCount)
+ append(" memoryClassMb=").append(activityManager?.memoryClass ?: -1)
+ append(" largeMemoryClassMb=").append(activityManager?.largeMemoryClass ?: -1)
+ append(" sdk=").append(Build.VERSION.SDK_INT)
+ }
+ }
+
+ private fun bytesToMb(bytes: Long): String {
+ return String.format(Locale.US, "%.1f", bytes.toDouble() / (1024.0 * 1024.0))
+ }
+
+ private fun trimLevelLabel(level: Int): String = when (level) {
+ ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN -> "ui_hidden"
+ ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE -> "running_moderate"
+ ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW -> "running_low"
+ ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL -> "running_critical"
+ ComponentCallbacks2.TRIM_MEMORY_BACKGROUND -> "background"
+ ComponentCallbacks2.TRIM_MEMORY_MODERATE -> "moderate"
+ ComponentCallbacks2.TRIM_MEMORY_COMPLETE -> "complete"
+ else -> level.toString()
+ }
+
+ companion object {
+ private const val TAG = "RuntimeDiagnostics"
+ private const val SAMPLE_INTERVAL_MS = 30_000L
+ }
+}
diff --git a/app/src/main/java/com/streamvault/app/tv/WatchNextManager.kt b/app/src/main/java/com/streamvault/app/tv/WatchNextManager.kt
index 8e856daf..8d9eca54 100644
--- a/app/src/main/java/com/streamvault/app/tv/WatchNextManager.kt
+++ b/app/src/main/java/com/streamvault/app/tv/WatchNextManager.kt
@@ -98,6 +98,7 @@ class WatchNextManager @Inject constructor(
return ContentValues().apply {
put(COLUMN_INTERNAL_PROVIDER_ID, watchNextKey(history))
+ put(COLUMN_TYPE, watchNextProgramType(history.contentType))
put(COLUMN_TITLE, history.title)
put(COLUMN_DESCRIPTION, context.getString(R.string.saved_preset_watch_next))
put(COLUMN_POSTER_ART_URI, artworkUriFor(history).toString())
@@ -109,6 +110,13 @@ class WatchNextManager @Inject constructor(
}
}
+ private fun watchNextProgramType(contentType: ContentType): Int = when (contentType) {
+ ContentType.MOVIE -> TvContract.PreviewPrograms.TYPE_MOVIE
+ ContentType.SERIES,
+ ContentType.SERIES_EPISODE -> TvContract.PreviewPrograms.TYPE_TV_EPISODE
+ ContentType.LIVE -> TvContract.PreviewPrograms.TYPE_CLIP
+ }
+
private fun artworkUriFor(history: PlaybackHistory): Uri {
val remoteArtwork = history.posterUrl?.takeIf { it.isNotBlank() }
if (remoteArtwork != null) {
@@ -144,6 +152,7 @@ class WatchNextManager @Inject constructor(
const val MAX_WATCH_NEXT_ITEMS = 12
const val WATCH_NEXT_COMPLETION_THRESHOLD = 0.95f
const val COLUMN_INTERNAL_PROVIDER_ID = "internal_provider_id"
+ const val COLUMN_TYPE = "type"
const val COLUMN_TITLE = "title"
const val COLUMN_DESCRIPTION = "description"
const val COLUMN_POSTER_ART_URI = "poster_art_uri"
@@ -153,4 +162,4 @@ class WatchNextManager @Inject constructor(
const val COLUMN_LAST_ENGAGEMENT_TIME_UTC_MILLIS = "last_engagement_time_utc_millis"
const val COLUMN_WATCH_NEXT_TYPE = "watch_next_type"
}
-}
\ No newline at end of file
+}
diff --git a/app/src/main/java/com/streamvault/app/ui/components/Cards.kt b/app/src/main/java/com/streamvault/app/ui/components/Cards.kt
index d5b33a1f..6ff30b2d 100644
--- a/app/src/main/java/com/streamvault/app/ui/components/Cards.kt
+++ b/app/src/main/java/com/streamvault/app/ui/components/Cards.kt
@@ -57,6 +57,7 @@ import com.streamvault.app.ui.components.rememberCrossfadeImageModel
import com.streamvault.app.ui.components.shell.MoviePosterCard
import com.streamvault.app.ui.components.shell.SeriesPosterCard
import com.streamvault.app.ui.components.shell.StatusPill
+import com.streamvault.app.ui.model.formatVodRatingLabel
import com.streamvault.app.ui.theme.AccentAmber
import com.streamvault.app.ui.theme.AccentCyan
import com.streamvault.app.ui.theme.AccentRed
@@ -389,7 +390,7 @@ fun MovieCard(
.padding(horizontal = 6.dp, vertical = 2.dp)
) {
Text(
- text = stringResource(R.string.label_rating, String.format("%.1f", movie.rating)),
+ text = formatVodRatingLabel(movie.rating),
style = MaterialTheme.typography.labelSmall,
color = AccentAmber
)
@@ -486,7 +487,7 @@ fun SeriesCard(
.padding(horizontal = 6.dp, vertical = 2.dp)
) {
Text(
- text = stringResource(R.string.label_rating, String.format("%.1f", series.rating)),
+ text = formatVodRatingLabel(series.rating),
style = MaterialTheme.typography.labelSmall,
color = AccentAmber
)
diff --git a/app/src/main/java/com/streamvault/app/ui/components/SearchInput.kt b/app/src/main/java/com/streamvault/app/ui/components/SearchInput.kt
index 0e31f3c9..76bc32e5 100644
--- a/app/src/main/java/com/streamvault/app/ui/components/SearchInput.kt
+++ b/app/src/main/java/com/streamvault/app/ui/components/SearchInput.kt
@@ -14,6 +14,7 @@ import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
+import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Search
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
@@ -94,13 +95,6 @@ fun SearchInput(
contentAlignment = Alignment.CenterStart
) {
Row(verticalAlignment = Alignment.CenterVertically) {
- Icon(
- imageVector = Icons.Default.Search,
- contentDescription = null,
- tint = if (isFocused) Primary else OnSurfaceDim,
- modifier = Modifier.padding(end = 6.dp)
- )
-
Box(modifier = Modifier.weight(1f)) {
if (value.isEmpty() && !isFocused) {
Text(
@@ -124,6 +118,23 @@ fun SearchInput(
keyboardActions = KeyboardActions(onSearch = { onSearch() })
)
}
+
+ Icon(
+ imageVector = if (value.isBlank()) Icons.Default.Search else Icons.Default.Close,
+ contentDescription = null,
+ tint = if (value.isBlank()) {
+ if (isFocused) Primary else OnSurfaceDim
+ } else {
+ OnSurface
+ },
+ modifier = Modifier
+ .padding(start = 6.dp)
+ .clickable(enabled = enabled && value.isNotBlank()) {
+ onValueChange("")
+ focusRequester.requestFocus()
+ keyboardController?.show()
+ }
+ )
}
}
}
diff --git a/app/src/main/java/com/streamvault/app/ui/components/shell/AppMediaCards.kt b/app/src/main/java/com/streamvault/app/ui/components/shell/AppMediaCards.kt
index 4b2eefba..412ca54e 100644
--- a/app/src/main/java/com/streamvault/app/ui/components/shell/AppMediaCards.kt
+++ b/app/src/main/java/com/streamvault/app/ui/components/shell/AppMediaCards.kt
@@ -18,12 +18,18 @@ import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.runtime.Composable
+import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
-import androidx.compose.runtime.produceState
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.delay
+import kotlinx.coroutines.flow.SharingStarted
+import kotlinx.coroutines.flow.flow
+import kotlinx.coroutines.flow.stateIn
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
@@ -58,6 +64,21 @@ import com.streamvault.domain.model.Episode
import com.streamvault.domain.model.Movie
import com.streamvault.domain.model.Series
+private object LiveChannelRowTicker {
+ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
+
+ val nowMs = flow {
+ while (true) {
+ emit(System.currentTimeMillis())
+ delay(30_000L)
+ }
+ }.stateIn(
+ scope = scope,
+ started = SharingStarted.WhileSubscribed(stopTimeoutMillis = 30_000L),
+ initialValue = System.currentTimeMillis()
+ )
+}
+
@Composable
fun LiveChannelRowCard(
channel: Channel,
@@ -72,13 +93,7 @@ fun LiveChannelRowCard(
val logoPadding = if (isDense) 5.dp else if (isUltraCompact) 6.dp else 8.dp
val contentSpacing = if (isUltraCompact) 8.dp else 10.dp
val badgeSpacing = if (isUltraCompact) 3.dp else 4.dp
- // Ticks every 30s so EPG progress bars stay accurate without busy-looping
- val nowMs by produceState(initialValue = System.currentTimeMillis()) {
- while (true) {
- delay(30_000L)
- value = System.currentTimeMillis()
- }
- }
+ val nowMs by LiveChannelRowTicker.nowMs.collectAsState()
Box(
modifier = modifier
diff --git a/app/src/main/java/com/streamvault/app/ui/components/shell/AppShell.kt b/app/src/main/java/com/streamvault/app/ui/components/shell/AppShell.kt
index 56bb1305..1f82f7e9 100644
--- a/app/src/main/java/com/streamvault/app/ui/components/shell/AppShell.kt
+++ b/app/src/main/java/com/streamvault/app/ui/components/shell/AppShell.kt
@@ -251,7 +251,7 @@ private fun TopNavigationBar(
Surface(
modifier = modifier.focusProperties {
onEnter = {
- val activeItem = items.firstOrNull { it.route == currentRoute }
+ val activeItem = findActiveDestinationItem(items, currentRoute)
focusRequesters[activeItem?.route] ?: FocusRequester.Default
}
},
@@ -645,7 +645,7 @@ private fun DestinationRail(
)
.focusProperties {
onEnter = {
- val activeItem = items.firstOrNull { it.route == currentRoute }
+ val activeItem = findActiveDestinationItem(items, currentRoute)
focusRequesters[activeItem?.route] ?: FocusRequester.Default
}
}
@@ -751,6 +751,15 @@ private data class DestinationItem(
val icon: ImageVector
)
+private fun findActiveDestinationItem(
+ items: List<DestinationItem>,
+ currentRoute: String
+): DestinationItem? =
+ items
+ .filter { currentRoute.startsWith(it.route) }
+ .maxByOrNull { it.route.length }
+ ?: items.firstOrNull { it.route == currentRoute }
+
private fun buildDestinationItems(): List<DestinationItem> = listOf(
DestinationItem(Routes.HOME, R.string.nav_home, Icons.Default.Home),
DestinationItem(Routes.LIVE_TV, R.string.nav_live_tv, Icons.Default.PlayArrow),
diff --git a/app/src/main/java/com/streamvault/app/ui/model/VodRatingFormatter.kt b/app/src/main/java/com/streamvault/app/ui/model/VodRatingFormatter.kt
new file mode 100644
index 00000000..f2c93f6d
--- /dev/null
+++ b/app/src/main/java/com/streamvault/app/ui/model/VodRatingFormatter.kt
@@ -0,0 +1,15 @@
+package com.streamvault.app.ui.model
+
+import java.util.Locale
+
+fun formatVodRatingLabel(rating: Float): String {
+ val normalizedRating = rating.coerceAtLeast(0f)
+ val scale = if (normalizedRating <= 5f) 5 else 10
+ val valueText = formatVodRatingValue(normalizedRating)
+ return "\u2605 $valueText/$scale"
+}
+
+private fun formatVodRatingValue(rating: Float): String {
+ val formatted = String.format(Locale.US, "%.1f", rating)
+ return formatted.removeSuffix(".0")
+}
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.kt
index 238df4e8..d2d919fc 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,5 +1,6 @@
package com.streamvault.app.ui.screens.epg
+import android.view.inputmethod.InputMethodManager
import com.streamvault.app.ui.model.guideLookupKey
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.background
@@ -44,6 +45,7 @@ import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.produceState
import androidx.compose.runtime.remember
+import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
@@ -54,7 +56,9 @@ import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.SolidColor
+import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
+import androidx.compose.ui.platform.LocalView
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.style.TextOverflow
@@ -79,6 +83,7 @@ import com.streamvault.app.ui.components.ChannelLogoBadge
import com.streamvault.app.navigation.Routes
import com.streamvault.app.ui.components.SelectionChip
import com.streamvault.app.ui.components.SelectionChipRow
+import com.streamvault.app.ui.components.dialogs.PinDialog
import com.streamvault.app.ui.components.shell.AppNavigationChrome
import com.streamvault.app.ui.components.shell.AppScreenScaffold
import com.streamvault.app.ui.theme.FocusBorder
@@ -99,8 +104,16 @@ import java.util.Calendar
import java.util.Date
import java.util.Locale
import kotlinx.coroutines.delay
+import kotlinx.coroutines.launch
import kotlin.math.max
+private sealed interface LockedGuideAction {
+ data class SelectCategory(val category: Category) : LockedGuideAction
+ data class OpenProgram(val channel: Channel, val program: Program) : LockedGuideAction
+ data class PlayChannel(val channel: Channel, val returnRoute: String) : LockedGuideAction
+ data class PlayArchive(val channel: Channel, val program: Program, val returnRoute: String) : LockedGuideAction
+}
+
@Composable
fun FullEpgScreen(
currentRoute: String,
@@ -120,6 +133,11 @@ fun FullEpgScreen(
var showCategoryPicker by rememberSaveable { mutableStateOf(false) }
var showGuideOptions by rememberSaveable { mutableStateOf(false) }
var showSearchOverlay by rememberSaveable { mutableStateOf(false) }
+ var showPinDialog by rememberSaveable { mutableStateOf(false) }
+ var pinError by rememberSaveable { mutableStateOf<String?>(null) }
+ var pendingLockedAction by remember { mutableStateOf<LockedGuideAction?>(null) }
+ val scope = rememberCoroutineScope()
+ val context = LocalContext.current
val now = rememberGuideNow()
val returnRoute = remember(uiState.selectedCategoryId, uiState.guideAnchorTime, uiState.showFavoritesOnly) {
Routes.epg(
@@ -128,6 +146,24 @@ fun FullEpgScreen(
favoritesOnly = uiState.showFavoritesOnly
)
}
+ val categoriesById = remember(uiState.categories) {
+ uiState.categories.associateBy { it.id }
+ }
+
+ fun executeLockedGuideAction(action: LockedGuideAction) {
+ when (action) {
+ is LockedGuideAction.SelectCategory -> viewModel.selectCategory(action.category.id)
+ is LockedGuideAction.OpenProgram -> selectedProgram = action.channel to action.program
+ is LockedGuideAction.PlayChannel -> onPlayChannel(action.channel, action.returnRoute)
+ is LockedGuideAction.PlayArchive -> onPlayArchive(action.channel, action.program, action.returnRoute)
+ }
+ }
+
+ fun requestLockedGuideAction(action: LockedGuideAction) {
+ pendingLockedAction = action
+ pinError = null
+ showPinDialog = true
+ }
LaunchedEffect(initialCategoryId, initialAnchorTime, initialFavoritesOnly) {
viewModel.applyNavigationContext(
@@ -313,10 +349,20 @@ fun FullEpgScreen(
guideWindowEnd = uiState.guideWindowEnd,
density = uiState.selectedDensity,
now = now,
- onChannelClick = { channel -> onPlayChannel(channel, returnRoute) },
+ onChannelClick = { channel ->
+ if (isGuideChannelLocked(channel, categoriesById, uiState.parentalControlLevel)) {
+ requestLockedGuideAction(LockedGuideAction.PlayChannel(channel, returnRoute))
+ } else {
+ onPlayChannel(channel, returnRoute)
+ }
+ },
onProgramClick = { channel, program ->
topNavVisible = false
- selectedProgram = channel to program
+ if (isGuideChannelLocked(channel, categoriesById, uiState.parentalControlLevel)) {
+ requestLockedGuideAction(LockedGuideAction.OpenProgram(channel, program))
+ } else {
+ selectedProgram = channel to program
+ }
},
onChannelFocused = { channel, currentProgram ->
topNavVisible = false
@@ -338,10 +384,15 @@ fun FullEpgScreen(
GuideCategoryPickerDialog(
categories = uiState.categories,
selectedCategoryId = uiState.selectedCategoryId,
+ parentalControlLevel = uiState.parentalControlLevel,
onDismiss = { showCategoryPicker = false },
- onCategorySelected = { categoryId ->
+ onCategorySelected = { category ->
showCategoryPicker = false
- viewModel.selectCategory(categoryId)
+ if (isGuideCategoryLocked(category, uiState.parentalControlLevel)) {
+ requestLockedGuideAction(LockedGuideAction.SelectCategory(category))
+ } else {
+ viewModel.selectCategory(category.id)
+ }
}
)
}
@@ -351,7 +402,10 @@ fun FullEpgScreen(
query = uiState.programSearchQuery,
onQueryChange = viewModel::updateProgramSearchQuery,
onClear = viewModel::clearProgramSearch,
- onDismiss = { showSearchOverlay = false }
+ onDismiss = {
+ viewModel.clearProgramSearch()
+ showSearchOverlay = false
+ }
)
}
@@ -383,6 +437,38 @@ fun FullEpgScreen(
)
}
+ if (showPinDialog) {
+ PinDialog(
+ onDismissRequest = {
+ showPinDialog = false
+ pinError = null
+ pendingLockedAction = null
+ },
+ onPinEntered = { pin ->
+ scope.launch {
+ if (viewModel.verifyPin(pin)) {
+ val action = pendingLockedAction
+ val lockedCategoryId = when (action) {
+ is LockedGuideAction.SelectCategory -> action.category.id
+ is LockedGuideAction.OpenProgram -> action.channel.categoryId
+ is LockedGuideAction.PlayChannel -> action.channel.categoryId
+ is LockedGuideAction.PlayArchive -> action.channel.categoryId
+ null -> null
+ }
+ lockedCategoryId?.let(viewModel::unlockCategory)
+ showPinDialog = false
+ pinError = null
+ pendingLockedAction = null
+ action?.let(::executeLockedGuideAction)
+ } else {
+ pinError = context.getString(R.string.home_incorrect_pin)
+ }
+ }
+ },
+ error = pinError
+ )
+ }
+
val dialogState = selectedProgram
if (dialogState != null) {
val (channel, program) = dialogState
@@ -394,12 +480,20 @@ fun FullEpgScreen(
onDismiss = { selectedProgram = null },
onWatchLive = {
selectedProgram = null
- onPlayChannel(channel, returnRoute)
+ if (isGuideChannelLocked(channel, categoriesById, uiState.parentalControlLevel)) {
+ requestLockedGuideAction(LockedGuideAction.PlayChannel(channel, returnRoute))
+ } else {
+ onPlayChannel(channel, returnRoute)
+ }
},
onWatchArchive = if (program.hasArchive || channel.catchUpSupported) {
{
selectedProgram = null
- onPlayArchive(channel, program, returnRoute)
+ if (isGuideChannelLocked(channel, categoriesById, uiState.parentalControlLevel)) {
+ requestLockedGuideAction(LockedGuideAction.PlayArchive(channel, program, returnRoute))
+ } else {
+ onPlayArchive(channel, program, returnRoute)
+ }
}
} else {
null
@@ -575,6 +669,7 @@ private fun GuideProgramSearchRow(
query: String,
onQueryChange: (String) -> Unit,
onClear: () -> Unit,
+ onSearch: (() -> Unit)? = null,
focusRequester: FocusRequester? = null,
autoRequestFocus: Boolean = false,
contentPadding: PaddingValues = PaddingValues(horizontal = 24.dp, vertical = 12.dp),
@@ -582,6 +677,27 @@ private fun GuideProgramSearchRow(
onSearchFieldActivated: (() -> Unit)? = null
) {
val resolvedFocusRequester = focusRequester ?: remember { FocusRequester() }
+ var localQuery by rememberSaveable { mutableStateOf(query) }
+ var refocusToken by rememberSaveable { mutableStateOf(0) }
+
+ LaunchedEffect(query) {
+ if (query != localQuery) {
+ localQuery = query
+ }
+ }
+
+ LaunchedEffect(localQuery) {
+ if (localQuery == query) return@LaunchedEffect
+ if (localQuery.isBlank()) {
+ onQueryChange("")
+ return@LaunchedEffect
+ }
+ delay(250)
+ if (localQuery != query) {
+ onQueryChange(localQuery)
+ }
+ }
+
Column(
modifier = Modifier
.fillMaxWidth()
@@ -601,19 +717,25 @@ private fun GuideProgramSearchRow(
verticalAlignment = Alignment.CenterVertically
) {
GuideSearchField(
- value = query,
- onValueChange = onQueryChange,
+ value = localQuery,
+ onValueChange = { localQuery = it },
placeholder = stringResource(R.string.epg_search_placeholder),
modifier = Modifier.weight(1f),
focusRequester = resolvedFocusRequester,
autoRequestFocus = autoRequestFocus,
+ refocusToken = refocusToken,
+ onSearch = onSearch,
onActivated = onSearchFieldActivated
)
Box(modifier = Modifier.widthIn(min = 104.dp), contentAlignment = Alignment.CenterEnd) {
- if (query.isNotBlank()) {
+ if (localQuery.isNotBlank()) {
GuideShortcutChip(
label = stringResource(R.string.epg_clear_search),
- onClick = onClear
+ onClick = {
+ localQuery = ""
+ onClear()
+ refocusToken += 1
+ }
)
}
}
@@ -629,22 +751,62 @@ private fun GuideSearchField(
modifier: Modifier = Modifier,
focusRequester: FocusRequester = remember { FocusRequester() },
autoRequestFocus: Boolean = false,
+ refocusToken: Int = 0,
+ onSearch: (() -> Unit)? = null,
onActivated: (() -> Unit)? = null
) {
var isFocused by remember { mutableStateOf(false) }
val keyboardController = LocalSoftwareKeyboardController.current
+ val view = LocalView.current
+ val context = LocalContext.current
+ var pendingKeyboardRequest by remember { mutableStateOf(0) }
+ val inputMethodManager = remember(context) {
+ context.getSystemService(InputMethodManager::class.java)
+ }
+
+ fun requestKeyboard() {
+ pendingKeyboardRequest += 1
+ onActivated?.invoke()
+ }
LaunchedEffect(autoRequestFocus) {
if (autoRequestFocus) {
- focusRequester.requestFocus()
+ requestKeyboard()
+ }
+ }
+
+ LaunchedEffect(refocusToken) {
+ if (refocusToken > 0) {
+ requestKeyboard()
+ }
+ }
+
+ LaunchedEffect(pendingKeyboardRequest) {
+ if (pendingKeyboardRequest <= 0) return@LaunchedEffect
+ focusRequester.requestFocus()
+ kotlinx.coroutines.delay(80)
+ view.post {
+ val focusedView = view.findFocus() ?: view
+ focusedView.requestFocus()
+ keyboardController?.show()
+ inputMethodManager?.showSoftInput(focusedView, InputMethodManager.SHOW_IMPLICIT)
+ }
+ }
+
+ LaunchedEffect(isFocused) {
+ if (!isFocused) return@LaunchedEffect
+ kotlinx.coroutines.delay(50)
+ view.post {
+ val focusedView = view.findFocus() ?: view
+ focusedView.requestFocus()
+ keyboardController?.show()
+ inputMethodManager?.showSoftInput(focusedView, InputMethodManager.SHOW_IMPLICIT)
}
}
Surface(
onClick = {
- focusRequester.requestFocus()
- keyboardController?.show()
- onActivated?.invoke()
+ requestKeyboard()
},
modifier = modifier.height(40.dp),
colors = ClickableSurfaceDefaults.colors(
@@ -692,7 +854,6 @@ private fun GuideSearchField(
modifier = Modifier
.fillMaxWidth()
.focusRequester(focusRequester)
- .focusable()
.onFocusChanged {
isFocused = it.isFocused
if (it.isFocused) {
@@ -703,7 +864,10 @@ private fun GuideSearchField(
singleLine = true,
cursorBrush = SolidColor(Primary),
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search),
- keyboardActions = KeyboardActions(onSearch = { keyboardController?.hide() })
+ keyboardActions = KeyboardActions(onSearch = {
+ keyboardController?.hide()
+ onSearch?.invoke()
+ })
)
}
}
@@ -1330,7 +1494,7 @@ private fun ImmersiveGuideHero(
}
Column(
- modifier = Modifier.widthIn(min = 112.dp, max = 128.dp),
+ modifier = Modifier.widthIn(min = 176.dp, max = 220.dp),
verticalArrangement = Arrangement.spacedBy(3.dp)
) {
GuideHeroBadge(text = stringResource(R.string.epg_schedule_summary_short, channelsWithSchedule, channelCount))
@@ -1381,7 +1545,9 @@ private fun GuideHeroBadge(
text = text,
modifier = Modifier.padding(horizontal = 12.dp, vertical = 6.dp),
style = MaterialTheme.typography.labelMedium,
- color = if (highlight) accentColor else OnSurface
+ color = if (highlight) accentColor else OnSurface,
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis
)
}
}
@@ -1503,6 +1669,18 @@ private fun GuideSearchOverlay(
onDismiss: () -> Unit
) {
val searchFocusRequester = remember { FocusRequester() }
+ val applySearchAndClose = remember(query, onQueryChange, onDismiss) {
+ {
+ onQueryChange(query.trim())
+ onDismiss()
+ }
+ }
+ val clearAndClose = remember(onClear, onDismiss) {
+ {
+ onClear()
+ onDismiss()
+ }
+ }
LaunchedEffect(Unit) {
searchFocusRequester.requestFocus()
@@ -1534,15 +1712,22 @@ private fun GuideSearchOverlay(
style = MaterialTheme.typography.titleLarge,
color = OnSurface
)
- GuideShortcutChip(
- label = stringResource(R.string.settings_cancel),
- onClick = onDismiss
- )
+ Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ GuideShortcutChip(
+ label = stringResource(R.string.epg_search_apply),
+ onClick = applySearchAndClose
+ )
+ GuideShortcutChip(
+ label = stringResource(R.string.epg_clear_search_close),
+ onClick = clearAndClose
+ )
+ }
}
GuideProgramSearchRow(
query = query,
onQueryChange = onQueryChange,
onClear = onClear,
+ onSearch = applySearchAndClose,
focusRequester = searchFocusRequester,
autoRequestFocus = true,
contentPadding = PaddingValues(0.dp),
@@ -2617,8 +2802,9 @@ private fun GuideCategoryLauncherRow(
private fun GuideCategoryPickerDialog(
categories: List<Category>,
selectedCategoryId: Long,
+ parentalControlLevel: Int,
onDismiss: () -> Unit,
- onCategorySelected: (Long) -> Unit
+ onCategorySelected: (Category) -> Unit
) {
var query by rememberSaveable { mutableStateOf("") }
var shouldFocusFirstCategory by rememberSaveable { mutableStateOf(true) }
@@ -2696,8 +2882,9 @@ private fun GuideCategoryPickerDialog(
key = { index, category -> epgCategoryKey(category, index) }
) { _, category ->
val isSelected = category.id == selectedCategoryId
+ val isLocked = isGuideCategoryLocked(category, parentalControlLevel)
Surface(
- onClick = { onCategorySelected(category.id) },
+ onClick = { onCategorySelected(category) },
modifier = if (category.id == filteredCategories.firstOrNull()?.id) {
Modifier.focusRequester(firstCategoryFocusRequester)
} else {
@@ -2735,7 +2922,13 @@ private fun GuideCategoryPickerDialog(
style = MaterialTheme.typography.titleMedium,
color = if (isSelected) Primary else OnSurface
)
- if (category.count > 0) {
+ if (isLocked) {
+ Text(
+ text = stringResource(R.string.settings_parental_control),
+ style = MaterialTheme.typography.bodySmall,
+ color = OnSurfaceDim
+ )
+ } else if (category.count > 0) {
Text(
text = "${category.count} channels",
style = MaterialTheme.typography.bodySmall,
@@ -2775,6 +2968,23 @@ private fun epgChannelKey(channel: Channel, index: Int): String {
return "channel:${channel.id}:${channel.streamId}:${epgId}:${channel.name.trim()}:$index"
}
+private fun isGuideCategoryLocked(category: Category, parentalControlLevel: Int): Boolean =
+ parentalControlLevel == 1 && (category.isAdult || category.isUserProtected)
+
+private fun isGuideChannelLocked(
+ channel: Channel,
+ categoriesById: Map<Long, Category>,
+ parentalControlLevel: Int
+): Boolean {
+ if (parentalControlLevel != 1) {
+ return false
+ }
+ val categoryLocked = channel.categoryId?.let(categoriesById::get)?.let { category ->
+ category.isAdult || category.isUserProtected
+ } ?: false
+ return channel.isAdult || channel.isUserProtected || categoryLocked
+}
+
@Composable
private fun dayRelativeLabel(dayStart: Long): String {
val todayStart = remember { startOfDay(System.currentTimeMillis()) }
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/epg/EpgViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/epg/EpgViewModel.kt
index 7dfa3740..f16ebc9c 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
@@ -4,6 +4,7 @@ import com.streamvault.app.ui.model.guideLookupKey
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.streamvault.app.ui.model.applyProviderCategoryDisplayPreferences
+import com.streamvault.domain.manager.ParentalControlManager
import com.streamvault.domain.model.Category
import com.streamvault.domain.model.Channel
import com.streamvault.domain.model.ContentType
@@ -39,6 +40,7 @@ data class EpgUiState(
val showScheduledOnly: Boolean = false,
val selectedChannelMode: GuideChannelMode = GuideChannelMode.ALL,
val selectedDensity: GuideDensity = GuideDensity.COMPACT,
+ val parentalControlLevel: Int = 0,
val showFavoritesOnly: Boolean = false,
val favoriteChannelIds: Set<Long> = emptySet(),
val channels: List<Channel> = emptyList(),
@@ -82,6 +84,7 @@ private data class GuideBaseRequest(
val categories: List<Category>,
val hiddenCategoryIds: Set<Long>,
val resolvedCategoryId: Long,
+ val parentalControlLevel: Int,
val anchorTime: Long,
val favoritesOnly: Boolean,
val windowStart: Long,
@@ -95,6 +98,7 @@ private data class GuideBaseSnapshot(
val providerArchiveSummary: String,
val categories: List<Category>,
val selectedCategoryId: Long,
+ val parentalControlLevel: Int,
val showFavoritesOnly: Boolean,
val favoriteChannelIds: Set<Long>,
val allChannels: List<Channel>,
@@ -124,13 +128,22 @@ private data class GuideBaseComputation(
val hasUpcomingData: Boolean
)
+private data class GuideSelectionRequest(
+ val requestedCategoryId: Long,
+ val anchorTime: Long,
+ val favoritesOnly: Boolean,
+ val parentalControlLevel: Int,
+ val unlockedCategoryIds: Set<Long>
+)
+
@HiltViewModel
class EpgViewModel @Inject constructor(
private val providerRepository: ProviderRepository,
private val channelRepository: ChannelRepository,
private val epgRepository: EpgRepository,
private val favoriteRepository: FavoriteRepository,
- private val preferencesRepository: PreferencesRepository
+ private val preferencesRepository: PreferencesRepository,
+ private val parentalControlManager: ParentalControlManager
) : ViewModel() {
companion object {
@@ -179,6 +192,14 @@ class EpgViewModel @Inject constructor(
programSearchQuery.value = ""
}
+ suspend fun verifyPin(pin: String): Boolean =
+ preferencesRepository.verifyParentalPin(pin)
+
+ fun unlockCategory(categoryId: Long) {
+ val providerId = baseGuideSnapshot.value?.providerId ?: return
+ parentalControlManager.unlockCategory(providerId, categoryId)
+ }
+
fun refresh() {
refreshNonce.update { it + 1 }
}
@@ -325,21 +346,37 @@ class EpgViewModel @Inject constructor(
refreshNonce
) { requestedCategoryId, anchorTime, favoritesOnly, _ ->
Triple(requestedCategoryId, anchorTime, favoritesOnly)
+ }.combine(preferencesRepository.parentalControlLevel) { selection, parentalControlLevel ->
+ selection to parentalControlLevel
+ }.combine(parentalControlManager.unlockedCategoriesForProvider(provider.id)) { (selection, parentalControlLevel), unlockedCategoryIds ->
+ GuideSelectionRequest(
+ requestedCategoryId = selection.first,
+ anchorTime = selection.second,
+ favoritesOnly = selection.third,
+ parentalControlLevel = parentalControlLevel,
+ unlockedCategoryIds = unlockedCategoryIds
+ )
}
) { (providerCategories, hiddenCategoryIds, sortMode), selection ->
- val (requestedCategoryId, anchorTime, favoritesOnly) = selection
+ val requestedCategoryId = selection.requestedCategoryId
+ val anchorTime = selection.anchorTime
+ val favoritesOnly = selection.favoritesOnly
val visibleProviderCategories = applyProviderCategoryDisplayPreferences(
categories = providerCategories.filter { it.id != ChannelRepository.ALL_CHANNELS_ID },
hiddenCategoryIds = hiddenCategoryIds,
sortMode = sortMode
)
- val resolvedCategoryId = requestedCategoryId.takeIf { categoryId ->
- categoryId == ChannelRepository.ALL_CHANNELS_ID || visibleProviderCategories.any { it.id == categoryId }
- } ?: ChannelRepository.ALL_CHANNELS_ID
+ val resolvedCategoryId = resolveGuideCategorySelection(
+ requestedCategoryId = requestedCategoryId,
+ categories = visibleProviderCategories,
+ parentalControlLevel = selection.parentalControlLevel,
+ unlockedCategoryIds = selection.unlockedCategoryIds
+ )
GuideBaseRequest(
categories = visibleProviderCategories,
hiddenCategoryIds = hiddenCategoryIds,
resolvedCategoryId = resolvedCategoryId,
+ parentalControlLevel = selection.parentalControlLevel,
anchorTime = anchorTime,
favoritesOnly = favoritesOnly,
windowStart = anchorTime - LOOKBACK_MS,
@@ -362,6 +399,7 @@ class EpgViewModel @Inject constructor(
},
providerArchiveSummary = buildProviderArchiveSummary(provider),
categories = categories,
+ parentalControlLevel = request.parentalControlLevel,
showFavoritesOnly = request.favoritesOnly,
selectedCategoryId = request.resolvedCategoryId,
guideAnchorTime = request.anchorTime,
@@ -408,8 +446,8 @@ class EpgViewModel @Inject constructor(
?.let { lookupKey -> loadedGuideResult.programsByChannel[lookupKey].orEmpty().isNotEmpty() }
?: false
}
- val computedHasUpcomingData = loadedGuideResult.programsByChannel.values.flatten().any { program ->
- program.endTime > request.windowStart
+ val computedHasUpcomingData = loadedGuideResult.programsByChannel.values.any { programs ->
+ programs.any { program -> program.endTime > request.windowStart }
}
GuideBaseComputation(
guideResult = loadedGuideResult,
@@ -428,6 +466,7 @@ class EpgViewModel @Inject constructor(
providerArchiveSummary = buildProviderArchiveSummary(provider),
categories = categories,
selectedCategoryId = request.resolvedCategoryId,
+ parentalControlLevel = request.parentalControlLevel,
showFavoritesOnly = request.favoritesOnly,
favoriteChannelIds = channelSelection.favoriteChannelIds,
allChannels = allChannels,
@@ -492,6 +531,7 @@ class EpgViewModel @Inject constructor(
providerArchiveSummary = baseSnapshot.providerArchiveSummary,
categories = baseSnapshot.categories,
selectedCategoryId = baseSnapshot.selectedCategoryId,
+ parentalControlLevel = baseSnapshot.parentalControlLevel,
programSearchQuery = presentation.searchQuery,
showScheduledOnly = presentation.scheduledOnly,
selectedChannelMode = presentation.channelMode,
@@ -576,19 +616,8 @@ class EpgViewModel @Inject constructor(
val guideKeys = channels.mapNotNull(Channel::guideLookupKey).distinct()
val xmltvKeys = channels.mapNotNull { it.epgChannelId?.trim()?.takeIf { value -> value.isNotEmpty() } }.distinct()
val programsByChannel = runCatching {
- val allowedIds = guideKeys.toSet()
- when {
- categoryId != ChannelRepository.ALL_CHANNELS_ID && !favoritesOnly -> {
- epgRepository.getProgramsByCategory(
- providerId = providerId,
- categoryId = categoryId,
- startTime = windowStart,
- endTime = windowEnd
- ).first().filter { it.channelId in allowedIds }.groupBy { it.channelId }
- }
-
- else -> epgRepository.getProgramsForChannels(providerId, xmltvKeys, windowStart, windowEnd).first()
- }
+ if (xmltvKeys.isEmpty()) emptyMap()
+ else epgRepository.getProgramsForChannels(providerId, xmltvKeys, windowStart, windowEnd).first()
}.getOrElse { emptyMap() }
val fallbackProgramsByChannel = fetchXtreamGuideFallback(
@@ -687,8 +716,8 @@ class EpgViewModel @Inject constructor(
?.let { lookupKey -> candidateProgramsByChannel[lookupKey].orEmpty().isNotEmpty() }
?: false
}
- val hasUpcomingData = candidateProgramsByChannel.values.flatten().any { program ->
- program.endTime > baseSnapshot.guideWindowStart
+ val hasUpcomingData = candidateProgramsByChannel.values.any { programs ->
+ programs.any { program -> program.endTime > baseSnapshot.guideWindowStart }
}
return GuideDisplaySnapshot(
@@ -704,7 +733,7 @@ class EpgViewModel @Inject constructor(
baseSnapshot: GuideBaseSnapshot,
searchQuery: String
): Pair<List<Channel>, Map<String, List<Program>>> {
- val localMatches = baseSnapshot.baseProgramsByChannel
+ val matchedProgramsByChannel = baseSnapshot.baseProgramsByChannel
.mapValues { (_, programs) ->
programs.filter { program ->
program.title.contains(searchQuery, ignoreCase = true) ||
@@ -713,41 +742,48 @@ class EpgViewModel @Inject constructor(
}
.filterValues { it.isNotEmpty() }
- val searchedPrograms = runCatching {
- epgRepository.searchPrograms(
- providerId = baseSnapshot.providerId,
- query = searchQuery,
- startTime = baseSnapshot.guideWindowStart,
- endTime = baseSnapshot.guideWindowEnd,
- categoryId = baseSnapshot.selectedCategoryId.takeUnless { it == ChannelRepository.ALL_CHANNELS_ID },
- limit = maxOf(120, baseSnapshot.allChannels.size * 6)
- ).first()
- }.getOrElse { emptyList() }
-
- val dbMatches = searchedPrograms
- .groupBy { it.channelId }
- .mapValues { (_, programs) ->
- programs
- .distinctBy { Triple(it.startTime, it.endTime, it.title) }
- .sortedBy { it.startTime }
- }
-
- val mergedPrograms = (localMatches.keys + dbMatches.keys)
- .associateWith { key ->
- (localMatches[key].orEmpty() + dbMatches[key].orEmpty())
- .distinctBy { Triple(it.startTime, it.endTime, it.title) }
- .sortedBy { it.startTime }
- }
- .filterValues { it.isNotEmpty() }
-
- val matchedChannels = baseSnapshot.allChannels.filter { channel ->
- channel.guideLookupKey()?.let(mergedPrograms::containsKey) == true
+ 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 mergedPrograms.filterKeys { it in matchedChannelKeys }
+ return matchedChannels to matchedProgramsByChannel.filterKeys { it in matchedChannelKeys }
+ }
+
+ private fun resolveGuideCategorySelection(
+ requestedCategoryId: Long,
+ categories: List<Category>,
+ parentalControlLevel: Int,
+ unlockedCategoryIds: Set<Long>
+ ): Long {
+ val requestedExists = requestedCategoryId == ChannelRepository.ALL_CHANNELS_ID ||
+ categories.any { it.id == requestedCategoryId }
+ if (requestedCategoryId == ChannelRepository.ALL_CHANNELS_ID && requestedExists) {
+ return ChannelRepository.ALL_CHANNELS_ID
+ }
+
+ val requestedCategory = categories.firstOrNull { it.id == requestedCategoryId }
+ if (requestedCategory != null && isGuideCategoryAccessible(requestedCategory, parentalControlLevel, unlockedCategoryIds)) {
+ return requestedCategory.id
+ }
+
+ return categories.firstOrNull { category ->
+ isGuideCategoryAccessible(category, parentalControlLevel, unlockedCategoryIds)
+ }?.id ?: ChannelRepository.ALL_CHANNELS_ID
}
+ private fun isGuideCategoryAccessible(
+ category: Category,
+ parentalControlLevel: Int,
+ unlockedCategoryIds: Set<Long>
+ ): Boolean {
+ if (parentalControlLevel != 1) {
+ return true
+ }
+ return (!category.isAdult && !category.isUserProtected) || unlockedCategoryIds.contains(category.id)
+ }
}
private data class GuidePresentationState(
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/home/HomeScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/home/HomeScreen.kt
index 65ed8476..a3c4d5a7 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
@@ -81,6 +81,8 @@ private enum class FocusRestoreTarget {
CHANNEL
}
+private const val HOME_CATEGORY_SEARCH_RESULT_LIMIT = 250
+
@Composable
private fun HomeLoadingPane(
message: String,
@@ -267,7 +269,10 @@ fun HomeScreen(
if (uiState.selectedCategoryForOptions != null) {
val category = uiState.selectedCategoryForOptions!!
- val isCategoryLocked = (category.isAdult || category.isUserProtected) && uiState.parentalControlLevel == 1
+ val isCategoryLocked =
+ (category.isAdult || category.isUserProtected) &&
+ uiState.parentalControlLevel == 1 &&
+ kotlin.math.abs(category.id) !in uiState.unlockedCategoryIds
CategoryOptionsDialog(
category = category,
onDismissRequest = { viewModel.dismissCategoryOptions() },
@@ -348,24 +353,54 @@ fun HomeScreen(
val categoryFocusRequesters = remember { mutableMapOf<Long, FocusRequester>() }
val channelFocusRequesters = remember { mutableMapOf<Long, FocusRequester>() }
val visibleCategories = remember(uiState.categories, uiState.categorySearchQuery) {
- uiState.categories.filter {
- uiState.categorySearchQuery.isEmpty() ||
- it.name.contains(uiState.categorySearchQuery, ignoreCase = true)
- }
+ uiState.categories
+ .asSequence()
+ .filter {
+ uiState.categorySearchQuery.isEmpty() ||
+ it.name.contains(uiState.categorySearchQuery, ignoreCase = true)
+ }
+ .take(HOME_CATEGORY_SEARCH_RESULT_LIMIT)
+ .toList()
}
- val isCategoryLocked: (Category) -> Boolean = remember(uiState.parentalControlLevel) {
+ val isCategoryLocked: (Category) -> Boolean = remember(uiState.parentalControlLevel, uiState.unlockedCategoryIds) {
{ category ->
- (category.isAdult || category.isUserProtected) && uiState.parentalControlLevel == 1
+ (category.isAdult || category.isUserProtected) &&
+ uiState.parentalControlLevel == 1 &&
+ kotlin.math.abs(category.id) !in uiState.unlockedCategoryIds
+ }
+ }
+ val isChannelLocked: (Channel) -> Boolean = remember(
+ uiState.parentalControlLevel,
+ uiState.unlockedCategoryIds,
+ uiState.selectedCategory?.id,
+ uiState.selectedCategory?.isAdult,
+ uiState.selectedCategory?.isUserProtected
+ ) {
+ { channel ->
+ val selectedCategory = uiState.selectedCategory
+ val channelCategoryId = channel.categoryId
+ val unlockedByChannelCategory =
+ channelCategoryId != null && kotlin.math.abs(channelCategoryId) in uiState.unlockedCategoryIds
+ val unlockedBySelectedCategory =
+ selectedCategory != null && kotlin.math.abs(selectedCategory.id) in uiState.unlockedCategoryIds
+ val unlocked = unlockedByChannelCategory || unlockedBySelectedCategory
+ (channel.isAdult || channel.isUserProtected || (selectedCategory?.isAdult == true) || (selectedCategory?.isUserProtected == true)) &&
+ uiState.parentalControlLevel == 1 &&
+ !unlocked
}
}
- val unlockedVisibleCategories = remember(visibleCategories, uiState.parentalControlLevel) {
+ val unlockedVisibleCategories = remember(
+ visibleCategories,
+ uiState.parentalControlLevel,
+ uiState.unlockedCategoryIds
+ ) {
visibleCategories.filterNot(isCategoryLocked)
}
var lastFocusedCategoryId by rememberSaveable { mutableStateOf<Long?>(null) }
var lastFocusedChannelId by rememberSaveable { mutableStateOf<Long?>(null) }
var preferredRestoreTarget by rememberSaveable { mutableStateOf(FocusRestoreTarget.CHANNEL.name) }
- var shouldRestoreCategoryFocus by remember { mutableStateOf(false) }
- var shouldRestoreChannelFocus by remember { mutableStateOf(false) }
+ var pendingRestoreTarget by remember { mutableStateOf<FocusRestoreTarget?>(null) }
+ var focusRestoreNonce by rememberSaveable { mutableStateOf(0) }
val displayedCategory = uiState.selectedCategory?.takeIf { !isCategoryLocked(it) }
val hasBlockedCategorySearch =
@@ -425,46 +460,61 @@ fun HomeScreen(
FocusRestoreTarget.valueOf(preferredRestoreTarget)
}.getOrDefault(FocusRestoreTarget.CHANNEL)
- shouldRestoreCategoryFocus = restoreTarget == FocusRestoreTarget.CATEGORY && canRestoreCategory
- shouldRestoreChannelFocus = when {
- restoreTarget == FocusRestoreTarget.CATEGORY -> false
- canRestoreChannel -> true
- else -> false
+ pendingRestoreTarget = when {
+ restoreTarget == FocusRestoreTarget.CATEGORY && canRestoreCategory -> FocusRestoreTarget.CATEGORY
+ canRestoreChannel -> FocusRestoreTarget.CHANNEL
+ canRestoreCategory -> FocusRestoreTarget.CATEGORY
+ else -> null
}
-
- if (!shouldRestoreChannelFocus && !shouldRestoreCategoryFocus && canRestoreCategory) {
- shouldRestoreCategoryFocus = true
+ if (pendingRestoreTarget != null) {
+ focusRestoreNonce++
}
}
- LaunchedEffect(shouldRestoreChannelFocus, uiState.filteredChannels) {
- if (!shouldRestoreChannelFocus) return@LaunchedEffect
+ LaunchedEffect(focusRestoreNonce, uiState.categories, uiState.filteredChannels) {
+ val restoreTarget = pendingRestoreTarget ?: return@LaunchedEffect
kotlinx.coroutines.delay(80)
- val channelId = lastFocusedChannelId
- val restored = channelId != null && runCatching {
- channelFocusRequesters[channelId]?.requestFocus()
- }.isSuccess
- if (!restored) {
- val fallbackId = uiState.filteredChannels.firstOrNull()?.id
- fallbackId?.let { runCatching { channelFocusRequesters[it]?.requestFocus() } }
+ val restored = when (restoreTarget) {
+ FocusRestoreTarget.CHANNEL -> {
+ val channelId = lastFocusedChannelId
+ channelId != null && runCatching {
+ channelFocusRequesters[channelId]?.requestFocus()
+ }.isSuccess
+ }
+ FocusRestoreTarget.CATEGORY -> {
+ val categoryId = lastFocusedCategoryId
+ categoryId != null && runCatching {
+ categoryFocusRequesters[categoryId]?.requestFocus()
+ }.isSuccess
+ }
}
- shouldRestoreChannelFocus = false
- }
-
- LaunchedEffect(shouldRestoreCategoryFocus, uiState.categories) {
- if (!shouldRestoreCategoryFocus) return@LaunchedEffect
- kotlinx.coroutines.delay(80)
- val categoryId = lastFocusedCategoryId
- if (categoryId != null) {
- runCatching { categoryFocusRequesters[categoryId]?.requestFocus() }
+ if (!restored) {
+ when (restoreTarget) {
+ FocusRestoreTarget.CHANNEL -> {
+ val fallbackChannelId = uiState.filteredChannels.firstOrNull()?.id
+ if (fallbackChannelId != null) {
+ runCatching { channelFocusRequesters[fallbackChannelId]?.requestFocus() }
+ } else {
+ val fallbackCategoryId = uiState.categories.firstOrNull()?.id
+ fallbackCategoryId?.let {
+ runCatching { categoryFocusRequesters[it]?.requestFocus() }
+ }
+ }
+ }
+ FocusRestoreTarget.CATEGORY -> {
+ val fallbackCategoryId = uiState.categories.firstOrNull()?.id
+ fallbackCategoryId?.let {
+ runCatching { categoryFocusRequesters[it]?.requestFocus() }
+ }
+ }
+ }
}
- shouldRestoreCategoryFocus = false
+ pendingRestoreTarget = null
}
FocusRestoreHost(
enabled = !hasOverlay && !uiState.isLoading && uiState.categories.isNotEmpty(),
onRestore = {
- kotlinx.coroutines.delay(80)
val restoreTarget = runCatching {
FocusRestoreTarget.valueOf(preferredRestoreTarget)
}.getOrDefault(FocusRestoreTarget.CHANNEL)
@@ -474,27 +524,14 @@ fun HomeScreen(
val canRestoreCategory = lastFocusedCategoryId != null &&
uiState.categories.any { it.id == lastFocusedCategoryId }
- when {
- restoreTarget == FocusRestoreTarget.CATEGORY && canRestoreCategory -> {
- runCatching { categoryFocusRequesters[lastFocusedCategoryId]?.requestFocus() }
- }
- canRestoreChannel -> {
- val restored = runCatching {
- channelFocusRequesters[lastFocusedChannelId]?.requestFocus()
- }.isSuccess
- if (!restored) {
- val fallbackId = uiState.filteredChannels.firstOrNull()?.id
- fallbackId?.let { runCatching { channelFocusRequesters[it]?.requestFocus() } }
- }
- }
- canRestoreCategory -> {
- runCatching { categoryFocusRequesters[lastFocusedCategoryId]?.requestFocus() }
- }
- else -> {
- uiState.categories.firstOrNull()?.id?.let { firstCategoryId ->
- runCatching { categoryFocusRequesters[firstCategoryId]?.requestFocus() }
- }
- }
+ pendingRestoreTarget = when {
+ restoreTarget == FocusRestoreTarget.CATEGORY && canRestoreCategory -> FocusRestoreTarget.CATEGORY
+ canRestoreChannel -> FocusRestoreTarget.CHANNEL
+ canRestoreCategory -> FocusRestoreTarget.CATEGORY
+ else -> null
+ }
+ if (pendingRestoreTarget != null) {
+ focusRestoreNonce++
}
}
) {
@@ -628,14 +665,16 @@ fun HomeScreen(
?: uiState.filteredChannels.first().id
lastFocusedChannelId = preferredChannelId
preferredRestoreTarget = FocusRestoreTarget.CHANNEL.name
- shouldRestoreChannelFocus = true
+ pendingRestoreTarget = FocusRestoreTarget.CHANNEL
+ focusRestoreNonce++
scope.launch {
kotlinx.coroutines.delay(60)
val focused = runCatching {
channelFocusRequesters[preferredChannelId]?.requestFocus()
}.getOrNull() != null
if (!focused) {
- shouldRestoreChannelFocus = true
+ pendingRestoreTarget = FocusRestoreTarget.CHANNEL
+ focusRestoreNonce++
}
}
} else {
@@ -884,8 +923,7 @@ fun HomeScreen(
items = uiState.filteredChannels,
key = { it.id }
) { channel ->
- val isLocked = (channel.isAdult || channel.isUserProtected || (uiState.selectedCategory?.isUserProtected
- ?: false)) && uiState.parentalControlLevel == 1
+ val isLocked = isChannelLocked(channel)
val isDraggingThis = draggingChannel == channel
val channelFocusRequester = channelFocusRequesters.getOrPut(channel.id) { FocusRequester() }
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/home/HomeViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/home/HomeViewModel.kt
index ad470091..11397f78 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
@@ -67,6 +67,10 @@ class HomeViewModel @Inject constructor(
@AuxiliaryPlayerEngine
private val playerEngineProvider: InjectProvider<PlayerEngine>
) : ViewModel() {
+ private companion object {
+ const val MIN_CHANNEL_SEARCH_QUERY_LENGTH = 2
+ }
+
private val appContext = application
private val _uiState = MutableStateFlow(HomeUiState())
@@ -83,6 +87,7 @@ class HomeViewModel @Inject constructor(
private var previewPlaybackJob: Job? = null
private var previewErrorJob: Job? = null
private var previewPlayerEngine: PlayerEngine? = null
+ private var previewSessionVersion: Long = 0L
init {
loadAllProviders()
@@ -91,6 +96,7 @@ class HomeViewModel @Inject constructor(
.filterNotNull()
.distinctUntilChangedBy { it.id }
.collectLatest { provider ->
+ parentalControlManager.clearUnlockedCategories(provider.id)
_uiState.update {
it.copy(
provider = provider,
@@ -179,6 +185,17 @@ class HomeViewModel @Inject constructor(
}
}
+ viewModelScope.launch {
+ providerRepository.getActiveProvider()
+ .filterNotNull()
+ .flatMapLatest { provider ->
+ parentalControlManager.unlockedCategoriesForProvider(provider.id)
+ }
+ .collectLatest { unlockedIds ->
+ _uiState.update { it.copy(unlockedCategoryIds = unlockedIds) }
+ }
+ }
+
viewModelScope.launch {
preferencesRepository.liveTvChannelMode
.map(LiveTvChannelMode::fromStorage)
@@ -348,7 +365,6 @@ class HomeViewModel @Inject constructor(
fun selectCategory(category: Category) {
if (_uiState.value.selectedCategory?.id == category.id) return
- parentalControlManager.clearUnlockedCategories(_uiState.value.provider?.id)
clearPreview()
_uiState.update {
it.copy(
@@ -418,18 +434,24 @@ class HomeViewModel @Inject constructor(
}
combine(orderedFlow, queryFlow) { channels, query ->
- if (query.isBlank()) {
+ val trimmedQuery = query.trim()
+ if (trimmedQuery.isBlank()) {
channels
+ } else if (trimmedQuery.length < MIN_CHANNEL_SEARCH_QUERY_LENGTH) {
+ emptyList()
} else {
- channels.filter { it.name.contains(query, ignoreCase = true) }
+ channels.filter { it.name.contains(trimmedQuery, ignoreCase = true) }
}
}
} else {
queryFlow.flatMapLatest { query ->
- if (query.isBlank()) {
+ val trimmedQuery = query.trim()
+ if (trimmedQuery.isBlank()) {
channelRepository.getChannelsByCategory(providerId, category.id)
+ } else if (trimmedQuery.length < MIN_CHANNEL_SEARCH_QUERY_LENGTH) {
+ flowOf(emptyList())
} else {
- channelRepository.searchChannelsByCategory(providerId, category.id, query)
+ channelRepository.searchChannelsByCategory(providerId, category.id, trimmedQuery)
}
}
}
@@ -496,6 +518,7 @@ class HomeViewModel @Inject constructor(
if (_uiState.value.liveTvChannelMode != LiveTvChannelMode.PRO) return
if (_uiState.value.previewChannelId == channel.id && _uiState.value.previewPlayerEngine != null) return
+ val previewVersion = ++previewSessionVersion
val engine = previewPlayerEngine ?: playerEngineProvider.get().also { previewPlayerEngine = it }
previewPlaybackJob?.cancel()
previewErrorJob?.cancel()
@@ -511,6 +534,7 @@ class HomeViewModel @Inject constructor(
previewPlaybackJob = viewModelScope.launch {
engine.playbackState.collectLatest { playbackState ->
+ if (!isActivePreviewSession(previewVersion, channel.id)) return@collectLatest
_uiState.update { state ->
state.copy(
isPreviewLoading = playbackState == PlaybackState.IDLE || playbackState == PlaybackState.BUFFERING,
@@ -527,6 +551,7 @@ class HomeViewModel @Inject constructor(
previewErrorJob = viewModelScope.launch {
engine.error.collectLatest { error ->
+ if (!isActivePreviewSession(previewVersion, channel.id)) return@collectLatest
if (error != null) {
_uiState.update {
it.copy(
@@ -541,12 +566,14 @@ class HomeViewModel @Inject constructor(
viewModelScope.launch {
when (val result = channelRepository.getStreamInfo(channel)) {
is Result.Success -> {
+ if (!isActivePreviewSession(previewVersion, channel.id)) return@launch
engine.stop()
engine.prepare(result.data)
engine.setVolume(0f)
engine.play()
}
is Result.Error -> {
+ if (!isActivePreviewSession(previewVersion, channel.id)) return@launch
_uiState.update {
it.copy(
isPreviewLoading = false,
@@ -560,6 +587,7 @@ class HomeViewModel @Inject constructor(
}
fun clearPreview() {
+ previewSessionVersion++
previewPlaybackJob?.cancel()
previewErrorJob?.cancel()
previewPlaybackJob = null
@@ -577,6 +605,9 @@ class HomeViewModel @Inject constructor(
}
}
+ private fun isActivePreviewSession(version: Long, channelId: Long): Boolean =
+ version == previewSessionVersion && _uiState.value.previewChannelId == channelId
+
private fun fetchEpgForChannels(providerId: Long, channels: List<Channel>) {
epgJob?.cancel()
val lookupKeys = channels.mapNotNull(Channel::guideLookupKey).distinct()
@@ -1140,6 +1171,7 @@ data class HomeUiState(
val showDeleteGroupDialog: Boolean = false,
val groupToDelete: Category? = null,
val parentalControlLevel: Int = 0,
+ val unlockedCategoryIds: Set<Long> = emptySet(),
val selectedCategoryForOptions: Category? = null,
val isChannelReorderMode: Boolean = false,
val reorderCategory: Category? = null,
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.kt
index 70239e20..62f075b7 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
@@ -19,10 +19,13 @@ import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
+import androidx.compose.ui.focus.FocusRequester
+import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
@@ -32,6 +35,7 @@ import androidx.compose.ui.unit.dp
import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.compose.ui.platform.LocalContext
+import androidx.compose.runtime.remember
import androidx.tv.material3.Border
import androidx.tv.material3.Button
import androidx.tv.material3.ButtonDefaults
@@ -44,6 +48,8 @@ import com.streamvault.app.ui.components.rememberCrossfadeImageModel
import com.streamvault.app.ui.components.shell.ContentMetadataStrip
import com.streamvault.app.ui.components.shell.StatusPill
import com.streamvault.app.ui.design.AppColors
+import com.streamvault.app.ui.design.requestFocusSafely
+import com.streamvault.app.ui.model.formatVodRatingLabel
import com.streamvault.domain.model.Movie
@Composable
@@ -101,6 +107,15 @@ private fun MovieDetailContent(
) {
val context = LocalContext.current
val isTelevisionDevice = rememberIsTelevisionDevice()
+ val playButtonFocusRequester = remember { FocusRequester() }
+
+ LaunchedEffect(movie.id) {
+ playButtonFocusRequester.requestFocusSafely(
+ tag = "MovieDetailScreen",
+ target = "Play button"
+ )
+ }
+
BoxWithConstraints(
modifier = Modifier
.fillMaxSize()
@@ -168,6 +183,7 @@ private fun MovieDetailContent(
movie = movie,
hasResume = hasResume,
onPlay = onPlay,
+ playButtonFocusRequester = playButtonFocusRequester,
onPlayTrailer = {
resolveTrailerUrl(movie.youtubeTrailer)?.let { trailerUrl ->
context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(trailerUrl)))
@@ -185,6 +201,7 @@ private fun MovieDetailContent(
movie = movie,
hasResume = hasResume,
onPlay = onPlay,
+ playButtonFocusRequester = playButtonFocusRequester,
onPlayTrailer = {
resolveTrailerUrl(movie.youtubeTrailer)?.let { trailerUrl ->
context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(trailerUrl)))
@@ -225,6 +242,7 @@ private fun MovieDetailHeroText(
movie: Movie,
hasResume: Boolean,
onPlay: () -> Unit,
+ playButtonFocusRequester: FocusRequester,
onPlayTrailer: () -> Unit,
modifier: Modifier = Modifier
) {
@@ -237,7 +255,7 @@ private fun MovieDetailHeroText(
StatusPill(label = stringResource(R.string.nav_movies), containerColor = AppColors.BrandMuted)
movie.rating.takeIf { it > 0f }?.let {
StatusPill(
- label = stringResource(R.string.label_rating, String.format("%.1f", it)),
+ label = formatVodRatingLabel(it),
containerColor = AppColors.Warning,
contentColor = Color.Black
)
@@ -268,6 +286,7 @@ private fun MovieDetailHeroText(
Row(horizontalArrangement = Arrangement.spacedBy(12.dp), verticalAlignment = Alignment.CenterVertically) {
Button(
onClick = onPlay,
+ modifier = Modifier.focusRequester(playButtonFocusRequester),
colors = ButtonDefaults.colors(
containerColor = AppColors.Brand,
contentColor = Color.White
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/movies/MoviesScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/movies/MoviesScreen.kt
index 03b761ae..829d71f5 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
@@ -358,6 +358,14 @@ private fun MoviesVodContent(
kotlin.math.abs(category.id) !in uiState.unlockedCategoryIds
}
}
+ val isMovieLocked = remember(uiState.parentalControlLevel, uiState.unlockedCategoryIds) {
+ { movie: Movie ->
+ val categoryId = movie.categoryId
+ (movie.isAdult || movie.isUserProtected) &&
+ uiState.parentalControlLevel == 1 &&
+ (categoryId == null || kotlin.math.abs(categoryId) !in uiState.unlockedCategoryIds)
+ }
+ }
val openProtectedCategory: (Category) -> Unit = onProtectedCategoryClick
val visibleCategoryNames = remember(uiState.categoryNames, categoryByName, uiState.parentalControlLevel, uiState.unlockedCategoryIds) {
uiState.categoryNames.filter { name ->
@@ -430,7 +438,7 @@ private fun MoviesVodContent(
?: stringResource(R.string.movies_library_lens_subtitle),
actionLabel = stringResource(R.string.player_resume).substringBefore(" "),
onClick = {
- val isLocked = (heroMovie.isAdult || heroMovie.isUserProtected) && uiState.parentalControlLevel == 1
+ val isLocked = isMovieLocked(heroMovie)
if (isLocked) onProtectedMovieClick(heroMovie) else onMovieClick(heroMovie)
},
modifier = Modifier.padding(top = 8.dp, bottom = 6.dp)
@@ -529,7 +537,7 @@ private fun MoviesVodContent(
onSeeAll = { onSelectCategory(uiState.favoriteCategoryName) },
keySelector = { it.id }
) { movie ->
- val isLocked = (movie.isAdult || movie.isUserProtected) && uiState.parentalControlLevel == 1
+ val isLocked = isMovieLocked(movie)
MovieCard(
movie = movie,
isLocked = isLocked,
@@ -551,7 +559,7 @@ private fun MoviesVodContent(
onSeeAll = null,
keySelector = { it.id }
) { movie ->
- val isLocked = (movie.isAdult || movie.isUserProtected) && uiState.parentalControlLevel == 1
+ val isLocked = isMovieLocked(movie)
MovieCard(
movie = movie,
isLocked = isLocked,
@@ -570,7 +578,7 @@ private fun MoviesVodContent(
onSeeAll = null,
keySelector = { it.id }
) { movie ->
- val isLocked = (movie.isAdult || movie.isUserProtected) && uiState.parentalControlLevel == 1
+ val isLocked = isMovieLocked(movie)
MovieCard(
movie = movie,
isLocked = isLocked,
@@ -597,7 +605,7 @@ private fun MoviesVodContent(
},
keySelector = { it.id }
) { movie ->
- val isLocked = (movie.isAdult || movie.isUserProtected) && uiState.parentalControlLevel == 1
+ val isLocked = isMovieLocked(movie)
MovieCard(
movie = movie,
isLocked = isLocked,
@@ -744,7 +752,7 @@ private fun MoviesVodContent(
}
} else {
gridItems(filteredGridMovies, key = { it.id }) { movie ->
- val isLocked = (movie.isAdult || movie.isUserProtected) && uiState.parentalControlLevel == 1
+ val isLocked = isMovieLocked(movie)
val isDraggingThis = draggingMovie == movie
MovieCard(
movie = movie,
@@ -836,6 +844,14 @@ private fun MoviesVodClassicContent(
kotlin.math.abs(category.id) !in uiState.unlockedCategoryIds
}
}
+ val isMovieLocked = remember(uiState.parentalControlLevel, uiState.unlockedCategoryIds) {
+ { movie: Movie ->
+ val categoryId = movie.categoryId
+ (movie.isAdult || movie.isUserProtected) &&
+ uiState.parentalControlLevel == 1 &&
+ (categoryId == null || kotlin.math.abs(categoryId) !in uiState.unlockedCategoryIds)
+ }
+ }
val openProtectedCategory: (Category) -> Unit = onProtectedCategoryClick
val visibleCategoryNames = remember(uiState.categoryNames, categoryByName, uiState.parentalControlLevel, uiState.unlockedCategoryIds) {
uiState.categoryNames.filter { name ->
@@ -1050,7 +1066,7 @@ private fun MoviesVodClassicContent(
}
} else {
gridItems(filteredGridMovies, key = { it.id }) { movie ->
- val isLocked = (movie.isAdult || movie.isUserProtected) && uiState.parentalControlLevel == 1
+ val isLocked = isMovieLocked(movie)
val isDraggingThis = draggingMovie == movie
MovieCard(
movie = movie,
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/movies/MoviesViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/movies/MoviesViewModel.kt
index 23e9a2a1..2e156e48 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
@@ -80,6 +80,8 @@ class MoviesViewModel @Inject constructor(
) : ViewModel() {
private companion object {
const val UNCATEGORIZED = "Uncategorized"
+ const val MIN_SEARCH_QUERY_LENGTH = 2
+ const val FAVORITE_ID_FETCH_BUFFER = 80
}
private val _uiState = MutableStateFlow(MoviesUiState())
@@ -145,6 +147,14 @@ class MoviesViewModel @Inject constructor(
emit(
if (params.query.isBlank()) {
buildPreviewCatalog(params)
+ } else if (params.query.length < MIN_SEARCH_QUERY_LENGTH) {
+ buildSearchCatalog(
+ movies = emptyList(),
+ allFavorites = params.allFavorites,
+ customCategories = params.customCategories,
+ providerCategories = params.providerCategories,
+ hiddenCategoryIds = params.hiddenCategoryIds
+ ).copy(libraryCount = 0)
} else {
val searchResults = movieRepository.searchMovies(params.providerId, params.query).first()
buildSearchCatalog(
@@ -842,6 +852,9 @@ class MoviesViewModel @Inject constructor(
if (request.selectedCategory.isNullOrBlank()) {
return SelectedMovieCategorySnapshot()
}
+ if (request.query.isNotBlank() && request.query.length < MIN_SEARCH_QUERY_LENGTH) {
+ return SelectedMovieCategorySnapshot()
+ }
val globalFavoriteIds = request.allFavorites
.asSequence()
@@ -851,15 +864,19 @@ class MoviesViewModel @Inject constructor(
val (selectedItems, totalCount) = when (request.selectedCategory) {
VodBrowseDefaults.FULL_LIBRARY_CATEGORY -> {
- val filteredItems = applyLocalBrowseToMovies(
- movieRepository.getMovies(request.providerId)
- .first()
- .filterNot { movie -> movie.categoryId in request.hiddenCategoryIds },
- request.filterType,
- request.sortBy,
- request.query
- )
- filteredItems.take(request.loadLimit) to filteredItems.size
+ val result = movieRepository
+ .browseMovies(
+ LibraryBrowseQuery(
+ providerId = request.providerId,
+ sortBy = request.sortBy,
+ filterBy = LibraryFilterBy(type = request.filterType),
+ searchQuery = request.query,
+ limit = request.loadLimit,
+ offset = 0
+ )
+ )
+ .first()
+ result.items.filterNot { movie -> movie.categoryId in request.hiddenCategoryIds } to result.totalCount
}
VodBrowseDefaults.FAVORITES_CATEGORY -> {
val ids = request.allFavorites
@@ -868,12 +885,17 @@ class MoviesViewModel @Inject constructor(
.sortedBy { it.position }
.map { it.contentId }
.toList()
+ val fetchIds = if (request.query.isBlank() && request.filterType == LibraryFilterType.ALL && request.sortBy == LibrarySortBy.LIBRARY) {
+ ids.take(request.loadLimit + FAVORITE_ID_FETCH_BUFFER)
+ } else {
+ ids
+ }
val items = if (ids.isEmpty()) {
emptyList()
} else {
- movieRepository.getMoviesByIds(ids).first()
+ movieRepository.getMoviesByIds(fetchIds).first()
.filterNot { movie -> movie.categoryId in request.hiddenCategoryIds }
- .orderByIds(ids)
+ .orderByIds(fetchIds)
}
val filteredItems = applyLocalBrowseToMovies(
items,
@@ -881,7 +903,7 @@ class MoviesViewModel @Inject constructor(
request.sortBy,
request.query
)
- filteredItems.take(request.loadLimit) to filteredItems.size
+ filteredItems.take(request.loadLimit) to if (fetchIds === ids) filteredItems.size else ids.size
}
else -> {
val customCategory = request.customCategories.firstOrNull { it.name == request.selectedCategory }
@@ -892,12 +914,17 @@ class MoviesViewModel @Inject constructor(
.sortedBy { it.position }
.map { it.contentId }
.toList()
+ val fetchIds = if (request.query.isBlank() && request.filterType == LibraryFilterType.ALL && request.sortBy == LibrarySortBy.LIBRARY) {
+ ids.take(request.loadLimit + FAVORITE_ID_FETCH_BUFFER)
+ } else {
+ ids
+ }
val items = if (ids.isEmpty()) {
emptyList()
} else {
- movieRepository.getMoviesByIds(ids).first()
+ movieRepository.getMoviesByIds(fetchIds).first()
.filterNot { movie -> movie.categoryId in request.hiddenCategoryIds }
- .orderByIds(ids)
+ .orderByIds(fetchIds)
}
val filteredItems = applyLocalBrowseToMovies(
items,
@@ -905,7 +932,7 @@ class MoviesViewModel @Inject constructor(
request.sortBy,
request.query
)
- filteredItems.take(request.loadLimit) to filteredItems.size
+ filteredItems.take(request.loadLimit) to if (fetchIds === ids) filteredItems.size else ids.size
} else {
val providerCategory = request.providerCategories.firstOrNull { it.name == request.selectedCategory }
if (providerCategory != null) {
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerScreen.kt
index 9b996e52..678afbf5 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
@@ -163,8 +163,6 @@ fun PlayerScreen(
val aspectRatio by viewModel.aspectRatio.collectAsStateWithLifecycle()
val showDiagnostics by viewModel.showDiagnostics.collectAsStateWithLifecycle()
val playerDiagnostics by viewModel.playerDiagnostics.collectAsStateWithLifecycle()
- val currentPosition by viewModel.playerEngine.currentPosition.collectAsStateWithLifecycle()
- val duration by viewModel.playerEngine.duration.collectAsStateWithLifecycle()
val playerNotice by viewModel.playerNotice.collectAsStateWithLifecycle()
val currentChannelRecording by viewModel.currentChannelRecording.collectAsStateWithLifecycle()
val isMuted by viewModel.isMuted.collectAsStateWithLifecycle()
@@ -360,6 +358,41 @@ fun PlayerScreen(
}
}
+ val handleBackPress = remember(
+ playerNotice,
+ showProgramHistory,
+ showSplitDialog,
+ showSpeedSelection,
+ showTrackSelection,
+ showDiagnostics,
+ showChannelInfoOverlay,
+ showChannelListOverlay,
+ showCategoryListOverlay,
+ showEpgOverlay,
+ showControls,
+ numericChannelInput
+ ) {
+ {
+ when {
+ viewModel.hasPendingNumericChannelInput() -> viewModel.clearNumericChannelInput()
+ playerNotice != null -> viewModel.dismissPlayerNotice()
+ showProgramHistory -> showProgramHistory = false
+ showSplitDialog -> showSplitDialog = false
+ showSpeedSelection -> showSpeedSelection = false
+ showTrackSelection != null -> showTrackSelection = null
+ showDiagnostics -> viewModel.toggleDiagnostics()
+ showChannelInfoOverlay -> viewModel.closeChannelInfoOverlay()
+ showChannelListOverlay || showCategoryListOverlay || showEpgOverlay -> viewModel.closeOverlays()
+ showControls -> viewModel.toggleControls()
+ else -> onBack()
+ }
+ }
+ }
+
+ BackHandler(enabled = !resumePrompt.show) {
+ handleBackPress()
+ }
+
Box(
modifier = Modifier
.fillMaxSize()
@@ -487,40 +520,8 @@ fun PlayerScreen(
true
}
KeyEvent.KEYCODE_BACK -> {
- if (viewModel.hasPendingNumericChannelInput()) {
- viewModel.clearNumericChannelInput()
- true
- } else if (playerNotice != null) {
- viewModel.dismissPlayerNotice()
- true
- } else if (showProgramHistory) {
- showProgramHistory = false
- true
- } else if (showSplitDialog) {
- showSplitDialog = false
- true
- } else if (showSpeedSelection) {
- showSpeedSelection = false
- true
- } else if (showTrackSelection != null) {
- showTrackSelection = null
- true
- } else if (showDiagnostics) {
- viewModel.toggleDiagnostics()
- true
- } else if (showChannelInfoOverlay) {
- viewModel.closeChannelInfoOverlay()
- true
- } else if (showChannelListOverlay || showCategoryListOverlay || showEpgOverlay) {
- viewModel.closeOverlays()
- true
- } else if (showControls) {
- viewModel.toggleControls()
- true
- } else {
- onBack()
- true
- }
+ handleBackPress()
+ true
}
KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE -> {
if (isPlaying) viewModel.pause() else viewModel.play()
@@ -684,7 +685,8 @@ fun PlayerScreen(
)
}
- PlayerControlsOverlay(
+ PlayerControlsOverlayHost(
+ playerEngine = viewModel.playerEngine,
visible = showControls,
title = title,
contentType = contentType,
@@ -692,8 +694,6 @@ fun PlayerScreen(
currentProgram = currentProgram,
currentChannelName = currentChannel?.name,
displayChannelNumber = displayChannelNumber,
- currentPosition = currentPosition,
- duration = duration,
aspectRatioLabel = aspectRatio.modeName,
subtitleTrackCount = availableSubtitleTracks.size,
audioTrackCount = availableAudioTracks.size,
@@ -705,7 +705,7 @@ fun PlayerScreen(
playButtonFocusRequester = playButtonFocusRequester,
quickActionsFocusRequester = quickActionsFocusRequester,
modifier = Modifier.fillMaxSize(),
- onClose = onBack,
+ onClose = viewModel::toggleControls,
onTogglePlayPause = { if (isPlaying) viewModel.pause() else viewModel.play() },
onSeekBackward = viewModel::seekBackward,
onSeekForward = viewModel::seekForward,
@@ -953,6 +953,109 @@ private fun buildResolutionBadgeLabel(
}
}
+@Composable
+private fun PlayerControlsOverlayHost(
+ playerEngine: PlayerEngine,
+ visible: Boolean,
+ title: String,
+ contentType: String,
+ isPlaying: Boolean,
+ currentProgram: Program?,
+ currentChannelName: String?,
+ displayChannelNumber: Int,
+ aspectRatioLabel: String,
+ subtitleTrackCount: Int,
+ audioTrackCount: Int,
+ videoQualityCount: Int,
+ currentRecordingStatus: com.streamvault.domain.model.RecordingStatus?,
+ isMuted: Boolean,
+ playbackSpeed: Float,
+ mediaTitle: String?,
+ playButtonFocusRequester: FocusRequester,
+ quickActionsFocusRequester: FocusRequester,
+ modifier: Modifier = Modifier,
+ onClose: () -> Unit,
+ onTogglePlayPause: () -> Unit,
+ onSeekBackward: () -> Unit,
+ onSeekForward: () -> Unit,
+ onRestartProgram: () -> Unit,
+ onOpenArchive: () -> Unit,
+ onStartRecording: () -> Unit,
+ onStopRecording: () -> Unit,
+ onScheduleRecording: () -> Unit,
+ onScheduleDailyRecording: () -> Unit,
+ onScheduleWeeklyRecording: () -> Unit,
+ onToggleAspectRatio: () -> Unit,
+ onOpenSubtitleTracks: () -> Unit,
+ onOpenAudioTracks: () -> Unit,
+ onOpenVideoTracks: () -> Unit,
+ onOpenPlaybackSpeed: () -> Unit,
+ onOpenSplitScreen: () -> Unit,
+ onEnterPictureInPicture: () -> Unit,
+ onToggleMute: () -> Unit,
+ isCastConnected: Boolean,
+ onCast: () -> Unit,
+ onStopCasting: () -> Unit,
+ onSeekToPosition: (Long) -> Unit,
+ onSetScrubbingMode: (Boolean) -> Unit,
+ seekPreview: SeekPreviewState,
+ onSeekPreviewPositionChanged: (Long?) -> Unit,
+ onUserInteraction: () -> Unit
+) {
+ val currentPosition by playerEngine.currentPosition.collectAsStateWithLifecycle()
+ val duration by playerEngine.duration.collectAsStateWithLifecycle()
+
+ PlayerControlsOverlay(
+ visible = visible,
+ title = title,
+ contentType = contentType,
+ isPlaying = isPlaying,
+ currentProgram = currentProgram,
+ currentChannelName = currentChannelName,
+ displayChannelNumber = displayChannelNumber,
+ currentPosition = currentPosition,
+ duration = duration,
+ aspectRatioLabel = aspectRatioLabel,
+ subtitleTrackCount = subtitleTrackCount,
+ audioTrackCount = audioTrackCount,
+ videoQualityCount = videoQualityCount,
+ currentRecordingStatus = currentRecordingStatus,
+ isMuted = isMuted,
+ playbackSpeed = playbackSpeed,
+ mediaTitle = mediaTitle,
+ playButtonFocusRequester = playButtonFocusRequester,
+ quickActionsFocusRequester = quickActionsFocusRequester,
+ modifier = modifier,
+ onClose = onClose,
+ onTogglePlayPause = onTogglePlayPause,
+ onSeekBackward = onSeekBackward,
+ onSeekForward = onSeekForward,
+ onRestartProgram = onRestartProgram,
+ onOpenArchive = onOpenArchive,
+ onStartRecording = onStartRecording,
+ onStopRecording = onStopRecording,
+ onScheduleRecording = onScheduleRecording,
+ onScheduleDailyRecording = onScheduleDailyRecording,
+ onScheduleWeeklyRecording = onScheduleWeeklyRecording,
+ onToggleAspectRatio = onToggleAspectRatio,
+ onOpenSubtitleTracks = onOpenSubtitleTracks,
+ onOpenAudioTracks = onOpenAudioTracks,
+ onOpenVideoTracks = onOpenVideoTracks,
+ onOpenPlaybackSpeed = onOpenPlaybackSpeed,
+ onOpenSplitScreen = onOpenSplitScreen,
+ onEnterPictureInPicture = onEnterPictureInPicture,
+ onToggleMute = onToggleMute,
+ isCastConnected = isCastConnected,
+ onCast = onCast,
+ onStopCasting = onStopCasting,
+ onSeekToPosition = onSeekToPosition,
+ onSetScrubbingMode = onSetScrubbingMode,
+ seekPreview = seekPreview,
+ onSeekPreviewPositionChanged = onSeekPreviewPositionChanged,
+ onUserInteraction = onUserInteraction
+ )
+}
+
private tailrec fun android.content.Context.findMainActivity(): MainActivity? = when (this) {
is MainActivity -> this
is android.content.ContextWrapper -> baseContext.findMainActivity()
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModel.kt
index 1eb3f5bc..2deeca67 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
@@ -137,6 +137,8 @@ class PlayerViewModel @Inject constructor(
) : ViewModel() {
companion object {
private const val MUTE_TOGGLE_DEBOUNCE_MS = 250L
+ private const val MAX_PROGRAM_HISTORY_ITEMS = 18
+ private const val MAX_UPCOMING_PROGRAM_ITEMS = 24
}
private val _showControls = MutableStateFlow(false)
@@ -221,6 +223,7 @@ class PlayerViewModel @Inject constructor(
private var numericInputFeedbackJob: Job? = null
private var playerNoticeHideJob: Job? = null
private var mutePersistJob: Job? = null
+ private var recoveryJob: Job? = null
private var numericInputBuffer: String = ""
private val triedAlternativeStreams = mutableSetOf<String>()
private val failedStreamsThisSession = mutableMapOf<String, Int>()
@@ -232,6 +235,13 @@ class PlayerViewModel @Inject constructor(
private var currentResolvedPlaybackUrl: String = ""
private var pendingCatchUpUrls: List<String> = emptyList()
private var channelNumberingMode: ChannelNumberingMode = ChannelNumberingMode.GROUP
+ private var activeEpgRequestKey: EpgRequestKey? = null
+
+ private data class EpgRequestKey(
+ val providerId: Long,
+ val epgChannelId: String?,
+ val streamId: Long
+ )
val castConnectionState: StateFlow<CastConnectionState> = castManager.connectionState
@@ -296,7 +306,11 @@ class PlayerViewModel @Inject constructor(
}
private fun handlePlaybackError(error: PlayerError) {
+ val requestVersion = prepareRequestVersion
+ val playbackUrl = currentPlaybackIdentityUrl()
+ recoveryJob?.cancel()
if (error is PlayerError.DecoderError && !hasRetriedWithSoftwareDecoder) {
+ if (!isActivePlaybackSession(requestVersion, playbackUrl)) return
hasRetriedWithSoftwareDecoder = true
android.util.Log.w("PlayerVM", "Decoder error detected. Retrying with software decoder mode.")
playerEngine.setDecoderMode(DecoderMode.SOFTWARE)
@@ -315,6 +329,7 @@ class PlayerViewModel @Inject constructor(
val channel = _currentChannel.value
if (currentContentType != ContentType.LIVE || channel == null) {
+ if (!isActivePlaybackSession(requestVersion, playbackUrl)) return
showPlayerNotice(
message = resolvePlaybackErrorMessage(error),
recoveryType = recoveryType,
@@ -323,7 +338,8 @@ class PlayerViewModel @Inject constructor(
return
}
- viewModelScope.launch {
+ recoveryJob = viewModelScope.launch {
+ if (!isActivePlaybackSession(requestVersion, playbackUrl)) return@launch
if (isCatchUpPlayback()) {
markStreamFailure(currentStreamUrl)
setLastFailureReason(error.message)
@@ -335,6 +351,7 @@ class PlayerViewModel @Inject constructor(
else -> false
}
+ if (!isActivePlaybackSession(requestVersion, playbackUrl)) return@launch
if (switched) {
appendRecoveryAction("Trying alternate catch-up URL")
showPlayerNotice(
@@ -372,6 +389,7 @@ class PlayerViewModel @Inject constructor(
else -> false
}
+ if (!isActivePlaybackSession(requestVersion, playbackUrl)) return@launch
if (switched) {
appendRecoveryAction("Trying alternate stream")
showPlayerNotice(
@@ -613,8 +631,51 @@ class PlayerViewModel @Inject constructor(
}
}
- private suspend fun preparePlayer(streamInfo: com.streamvault.domain.model.StreamInfo) {
- currentResolvedPlaybackUrl = streamInfo.url
+ private fun beginPlaybackSession(): Long {
+ recoveryJob?.cancel()
+ return ++prepareRequestVersion
+ }
+
+ private fun currentPlaybackIdentityUrl(): String =
+ currentResolvedPlaybackUrl.ifBlank { currentStreamUrl }
+
+ private fun isActivePlaybackSession(
+ requestVersion: Long,
+ expectedLogicalUrl: String? = null
+ ): Boolean {
+ if (requestVersion != prepareRequestVersion) return false
+ val expectedUrl = expectedLogicalUrl?.takeIf { it.isNotBlank() } ?: return true
+ val activeUrl = currentPlaybackIdentityUrl()
+ return activeUrl.isBlank() || activeUrl == expectedUrl || currentStreamUrl == expectedUrl
+ }
+
+ private fun requestEpg(providerId: Long, epgChannelId: String?, streamId: Long = 0L) {
+ val normalizedChannelId = epgChannelId?.trim()?.takeIf { it.isNotEmpty() }
+ if (providerId <= 0L || (normalizedChannelId == null && streamId <= 0L)) {
+ activeEpgRequestKey = null
+ fetchEpg(providerId = -1L, epgChannelId = null)
+ return
+ }
+
+ val key = EpgRequestKey(
+ providerId = providerId,
+ epgChannelId = normalizedChannelId,
+ streamId = streamId.takeIf { it > 0L } ?: 0L
+ )
+ if (key == activeEpgRequestKey) return
+ activeEpgRequestKey = key
+ fetchEpg(
+ providerId = key.providerId,
+ epgChannelId = key.epgChannelId,
+ streamId = key.streamId
+ )
+ }
+
+ private suspend fun preparePlayer(
+ streamInfo: com.streamvault.domain.model.StreamInfo,
+ requestVersion: Long
+ ): Boolean {
+ if (!isActivePlaybackSession(requestVersion)) return false
playerEngine.setMuted(preferencesRepository.playerMuted.first())
playerEngine.setPlaybackSpeed(
if (currentContentType == ContentType.LIVE) {
@@ -633,7 +694,10 @@ class PlayerViewModel @Inject constructor(
wifiMaxHeight = preferencesRepository.playerWifiMaxVideoHeight.first(),
ethernetMaxHeight = preferencesRepository.playerEthernetMaxVideoHeight.first()
)
+ if (!isActivePlaybackSession(requestVersion)) return false
+ currentResolvedPlaybackUrl = streamInfo.url
playerEngine.prepare(streamInfo)
+ return true
}
fun prepare(
@@ -655,7 +719,7 @@ class PlayerViewModel @Inject constructor(
archiveStartMs > 0L &&
archiveEndMs > archiveStartMs &&
try { ContentType.valueOf(contentType) } catch (e: Exception) { ContentType.LIVE } == ContentType.LIVE
- val requestVersion = ++prepareRequestVersion
+ val requestVersion = beginPlaybackSession()
val previousProviderId = currentProviderId
val previousCategoryId = currentCategoryId
val shouldReloadPlaylist = categoryId != -1L &&
@@ -693,8 +757,9 @@ class PlayerViewModel @Inject constructor(
if (!hasArchiveRequest) {
viewModelScope.launch {
val resolvedUrl = resolvePlaybackUrl(streamUrl, internalChannelId, providerId, currentContentType)
- if (requestVersion != prepareRequestVersion) return@launch
+ if (!isActivePlaybackSession(requestVersion, streamUrl)) return@launch
if (resolvedUrl.isNullOrBlank()) {
+ if (!isActivePlaybackSession(requestVersion, streamUrl)) return@launch
showPlayerNotice(message = "No playable stream URL was available.", recoveryType = PlayerRecoveryType.SOURCE)
return@launch
}
@@ -703,7 +768,7 @@ class PlayerViewModel @Inject constructor(
title = currentTitle,
streamType = com.streamvault.domain.model.StreamType.UNKNOWN
)
- preparePlayer(streamInfo)
+ if (!preparePlayer(streamInfo, requestVersion)) return@launch
}
}
@@ -732,6 +797,7 @@ class PlayerViewModel @Inject constructor(
if (currentContentType != ContentType.LIVE && currentContentId != -1L && currentProviderId != -1L) {
viewModelScope.launch {
val history = playbackHistoryRepository.getPlaybackHistory(currentContentId, currentContentType, currentProviderId)
+ if (!isActivePlaybackSession(requestVersion, streamUrl)) return@launch
if (history != null && history.resumePositionMs > 5000L && !isPlaybackComplete(history.resumePositionMs, history.totalDurationMs)) {
playerEngine.pause()
_resumePrompt.value = ResumePromptState(
@@ -769,6 +835,7 @@ class PlayerViewModel @Inject constructor(
end = archiveEndMs / 1000L
)
} catch (e: CredentialDecryptionException) {
+ if (!isActivePlaybackSession(requestVersion, streamUrl)) return@launch
setLastFailureReason(e.message ?: CredentialDecryptionException.MESSAGE)
showPlayerNotice(
message = e.message ?: CredentialDecryptionException.MESSAGE,
@@ -776,11 +843,13 @@ class PlayerViewModel @Inject constructor(
)
return@launch
}
+ if (!isActivePlaybackSession(requestVersion, streamUrl)) return@launch
if (catchUpUrls.isNotEmpty()) {
startCatchUpPlayback(
urls = catchUpUrls,
title = archiveTitle?.takeIf { it.isNotBlank() } ?: currentTitle,
- recoveryAction = "Opened catch-up stream"
+ recoveryAction = "Opened catch-up stream",
+ requestVersionOverride = requestVersion
)
} else {
val reason = resolveCatchUpFailureMessage(_currentChannel.value, archiveRequested = true, programHasArchive = true)
@@ -795,7 +864,11 @@ class PlayerViewModel @Inject constructor(
}
// Fetch EPG if ID provided
- fetchEpg(currentProviderId, epgChannelId)
+ if (currentContentType == ContentType.LIVE) {
+ requestEpg(currentProviderId, epgChannelId)
+ } else {
+ requestEpg(providerId = -1L, epgChannelId = null)
+ }
observeRecentChannels()
observeLastVisitedCategory()
@@ -816,6 +889,7 @@ class PlayerViewModel @Inject constructor(
// Fetch Channel for tracking alternative streams (video qualities)
viewModelScope.launch {
val channel = channelRepository.getChannel(internalChannelId)
+ if (!isActivePlaybackSession(requestVersion, streamUrl)) return@launch
_currentChannel.value = channel
refreshCurrentChannelRecording()
if (channel != null) {
@@ -831,7 +905,7 @@ class PlayerViewModel @Inject constructor(
)
if (currentContentType == ContentType.LIVE) {
recordLivePlayback(channel)
- fetchEpg(currentProviderId, channel.epgChannelId, channel.streamId)
+ requestEpg(currentProviderId, channel.epgChannelId, channel.streamId)
}
updateChannelDiagnostics(channel)
}
@@ -978,6 +1052,7 @@ class PlayerViewModel @Inject constructor(
_programHistory.value = programs
.filter { it.hasArchive || catchUpSupported }
.sortedByDescending { it.startTime }
+ .take(MAX_PROGRAM_HISTORY_ITEMS)
}
}
launch {
@@ -985,7 +1060,9 @@ class PlayerViewModel @Inject constructor(
val now = System.currentTimeMillis()
val end = now + (6 * 60 * 60 * 1000L)
epgRepository.getProgramsForChannel(providerId, epgChannelId, now, end).collect { programs ->
- _upcomingPrograms.value = programs.sortedBy { it.startTime }
+ _upcomingPrograms.value = programs
+ .sortedBy { it.startTime }
+ .take(MAX_UPCOMING_PROGRAM_ITEMS)
}
}
}
@@ -1022,9 +1099,11 @@ class PlayerViewModel @Inject constructor(
_programHistory.value = programs
.filter { it.endTime <= now && (it.hasArchive || catchUpSupported) }
.sortedByDescending { it.startTime }
+ .take(MAX_PROGRAM_HISTORY_ITEMS)
_upcomingPrograms.value = programs
.filter { it.endTime > now || it == _currentProgram.value }
.sortedBy { it.startTime }
+ .take(MAX_UPCOMING_PROGRAM_ITEMS)
}
}
} else {
@@ -1311,6 +1390,7 @@ class PlayerViewModel @Inject constructor(
if (currentChannelIndex != -1 && currentChannelIndex != index) {
previousChannelIndex = currentChannelIndex
}
+ val requestVersion = beginPlaybackSession()
val channel = channelList[index]
currentChannelIndex = index
currentContentId = channel.id
@@ -1329,25 +1409,30 @@ class PlayerViewModel @Inject constructor(
viewModelScope.launch {
val resolvedUrl = resolvePlaybackUrl(channel.streamUrl, channel.id, channel.providerId, ContentType.LIVE)
?: return@launch
+ if (!isActivePlaybackSession(requestVersion, channel.streamUrl)) return@launch
val streamInfo = com.streamvault.domain.model.StreamInfo(
url = resolvedUrl,
title = currentTitle,
streamType = com.streamvault.domain.model.StreamType.UNKNOWN
)
- preparePlayer(streamInfo)
+ if (!preparePlayer(streamInfo, requestVersion)) return@launch
playerEngine.play()
// Once the first frame is on screen, turn off scrubbing for full quality
playerEngine.playbackState
.filter { it == com.streamvault.player.PlaybackState.READY }
.take(1)
- .collect { playerEngine.setScrubbingMode(false) }
+ .collect {
+ if (isActivePlaybackSession(requestVersion, channel.streamUrl)) {
+ playerEngine.setScrubbingMode(false)
+ }
+ }
}
// Pre-warm the next channel in sequence so the subsequent zap is near-instant
preloadAdjacentChannel(index)
- fetchEpg(currentProviderId, channel.epgChannelId, channel.streamId)
+ requestEpg(currentProviderId, channel.epgChannelId, channel.streamId)
// Show bottom live info overlay
_showZapOverlay.value = false
@@ -1540,18 +1625,20 @@ class PlayerViewModel @Inject constructor(
altUrl != currentStreamUrl && altUrl !in triedAlternativeStreams
} ?: return false
+ val requestVersion = beginPlaybackSession()
triedAlternativeStreams.add(nextStream)
currentStreamUrl = nextStream
updateStreamClass("Alternate")
viewModelScope.launch {
val resolvedUrl = resolvePlaybackUrl(nextStream, channel.id, channel.providerId, ContentType.LIVE)
?: return@launch
+ if (!isActivePlaybackSession(requestVersion, nextStream)) return@launch
val streamInfo = com.streamvault.domain.model.StreamInfo(
url = resolvedUrl,
title = currentTitle,
streamType = com.streamvault.domain.model.StreamType.UNKNOWN
)
- preparePlayer(streamInfo)
+ if (!preparePlayer(streamInfo, requestVersion)) return@launch
playerEngine.play()
}
return true
@@ -1571,18 +1658,20 @@ class PlayerViewModel @Inject constructor(
private fun tryNextCatchUpVariantInternal(): Boolean {
val nextStream = nextCatchUpVariant() ?: return false
+ val requestVersion = beginPlaybackSession()
triedAlternativeStreams.add(nextStream)
currentStreamUrl = nextStream
updateStreamClass("Catch-up")
viewModelScope.launch {
val resolvedUrl = resolvePlaybackUrl(nextStream, currentContentId, currentProviderId, ContentType.LIVE)
?: return@launch
+ if (!isActivePlaybackSession(requestVersion, nextStream)) return@launch
val streamInfo = com.streamvault.domain.model.StreamInfo(
url = resolvedUrl,
title = currentTitle,
streamType = com.streamvault.domain.model.StreamType.UNKNOWN
)
- preparePlayer(streamInfo)
+ if (!preparePlayer(streamInfo, requestVersion)) return@launch
playerEngine.play()
}
return true
@@ -1590,8 +1679,10 @@ class PlayerViewModel @Inject constructor(
private fun scheduleZapBufferWatchdog(targetIndex: Int) {
zapBufferWatchdogJob?.cancel()
+ val requestVersion = prepareRequestVersion
zapBufferWatchdogJob = viewModelScope.launch {
delay(9000)
+ if (!isActivePlaybackSession(requestVersion)) return@launch
val stillOnTarget = currentChannelIndex == targetIndex
val state = playerEngine.playbackState.value
val stalled = state == PlaybackState.BUFFERING || state == PlaybackState.ERROR
@@ -1705,8 +1796,10 @@ class PlayerViewModel @Inject constructor(
private suspend fun startCatchUpPlayback(
urls: List<String>,
title: String,
- recoveryAction: String
+ recoveryAction: String,
+ requestVersionOverride: Long? = null
) {
+ val requestVersion = requestVersionOverride ?: beginPlaybackSession()
val candidates = urls
.asSequence()
.map { it.trim() }
@@ -1728,13 +1821,14 @@ class PlayerViewModel @Inject constructor(
title = currentTitle,
streamType = com.streamvault.domain.model.StreamType.UNKNOWN
)
- preparePlayer(catchupStream)
+ if (!preparePlayer(catchupStream, requestVersion)) return
playerEngine.play()
_showControls.value = true
}
fun playCatchUp(program: Program) {
viewModelScope.launch {
+ val requestVersion = prepareRequestVersion
val start = program.startTime / 1000L
val end = program.endTime / 1000L
val streamId = _currentChannel.value?.id ?: 0L
@@ -1753,6 +1847,7 @@ class PlayerViewModel @Inject constructor(
val catchUpUrls = try {
providerRepository.buildCatchUpUrls(providerId, streamId, start, end)
} catch (e: CredentialDecryptionException) {
+ if (!isActivePlaybackSession(requestVersion)) return@launch
setLastFailureReason(e.message ?: CredentialDecryptionException.MESSAGE)
showPlayerNotice(
message = e.message ?: CredentialDecryptionException.MESSAGE,
@@ -1761,6 +1856,7 @@ class PlayerViewModel @Inject constructor(
)
return@launch
}
+ if (!isActivePlaybackSession(requestVersion)) return@launch
if (catchUpUrls.isNotEmpty()) {
startCatchUpPlayback(
urls = catchUpUrls,
@@ -2030,15 +2126,17 @@ class PlayerViewModel @Inject constructor(
fun retryStream(streamUrl: String, epgChannelId: String?) {
if (isCatchUpPlayback()) {
+ val requestVersion = beginPlaybackSession()
viewModelScope.launch {
val resolvedUrl = resolvePlaybackUrl(streamUrl, currentContentId, currentProviderId, currentContentType)
?: return@launch
+ if (!isActivePlaybackSession(requestVersion, streamUrl)) return@launch
val streamInfo = com.streamvault.domain.model.StreamInfo(
url = resolvedUrl,
title = currentTitle,
streamType = com.streamvault.domain.model.StreamType.UNKNOWN
)
- preparePlayer(streamInfo)
+ if (!preparePlayer(streamInfo, requestVersion)) return@launch
playerEngine.play()
}
return
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerControlsChrome.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerControlsChrome.kt
index fdae2e19..ec61fca2 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerControlsChrome.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerControlsChrome.kt
@@ -688,7 +688,7 @@ private fun PlayerLiveInfo(
if (audioTrackCount > 0) {
add(PlayerActionSpec(stringResource(R.string.player_audio), onOpenAudioTracks))
}
- if (videoQualityCount > 1) {
+ if (videoQualityCount > 0) {
add(PlayerActionSpec(stringResource(R.string.player_video_quality), onOpenVideoTracks))
}
add(PlayerActionSpec(stringResource(R.string.multiview_nav), onOpenSplitScreen))
@@ -848,31 +848,31 @@ private fun PlayerVodInfo(
val playbackLabel = stringResource(R.string.player_playback_label)
val actions = buildList {
- add(
- PlayerActionSpec(
- stringResource(R.string.player_playback_speed_value, formatPlaybackSpeedLabel(playbackSpeed)),
- onOpenPlaybackSpeed
- )
- )
- add(PlayerActionSpec(stringResource(R.string.player_aspect_ratio_label, aspectRatioLabel), onToggleAspectRatio))
add(PlayerActionSpec(
stringResource(if (isMuted) R.string.player_unmute else R.string.player_mute),
onToggleMute
))
- add(PlayerActionSpec(
- stringResource(if (isCastConnected) R.string.player_stop_casting else R.string.player_cast),
- if (isCastConnected) onStopCasting else onCast
- ))
- add(PlayerActionSpec(stringResource(R.string.player_picture_in_picture), onEnterPictureInPicture))
if (subtitleTrackCount > 0) {
add(PlayerActionSpec(stringResource(R.string.player_subs), onOpenSubtitleTracks))
}
if (audioTrackCount > 0) {
add(PlayerActionSpec(stringResource(R.string.player_audio), onOpenAudioTracks))
}
- if (videoQualityCount > 1) {
+ if (videoQualityCount > 0) {
add(PlayerActionSpec(stringResource(R.string.player_video_quality), onOpenVideoTracks))
}
+ add(
+ PlayerActionSpec(
+ stringResource(R.string.player_playback_speed_value, formatPlaybackSpeedLabel(playbackSpeed)),
+ onOpenPlaybackSpeed
+ )
+ )
+ add(PlayerActionSpec(
+ stringResource(if (isCastConnected) R.string.player_stop_casting else R.string.player_cast),
+ if (isCastConnected) onStopCasting else onCast
+ ))
+ add(PlayerActionSpec(stringResource(R.string.player_picture_in_picture), onEnterPictureInPicture))
+ add(PlayerActionSpec(stringResource(R.string.player_aspect_ratio_label, aspectRatioLabel), onToggleAspectRatio))
}
var sliderValue by remember(duration, currentPosition) {
mutableStateOf(if (duration > 0) currentPosition.toFloat() / duration.toFloat() else 0f)
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerOverlays.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerOverlays.kt
index bad27136..50238f31 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerOverlays.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerOverlays.kt
@@ -9,6 +9,7 @@ import androidx.compose.animation.scaleIn
import androidx.compose.animation.scaleOut
import androidx.compose.animation.togetherWith
import androidx.compose.foundation.background
+import androidx.compose.foundation.basicMarquee
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
@@ -48,10 +49,13 @@ import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.platform.LocalLayoutDirection
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.foundation.layout.offset
+import androidx.compose.ui.unit.LayoutDirection
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.foundation.rememberScrollState
@@ -372,74 +376,49 @@ fun ChannelInfoOverlay(
}
item {
QuickActionButton(
- icon = if (currentRecordingStatus == RecordingStatus.RECORDING) {
- stringResource(R.string.player_stop_recording)
- } else {
- stringResource(R.string.player_record)
- },
- label = if (currentRecordingStatus == RecordingStatus.RECORDING) {
- stringResource(R.string.player_stop_recording)
- } else {
- stringResource(R.string.player_record)
- },
+ icon = stringResource(R.string.player_action_mute),
+ label = if (isMuted) stringResource(R.string.player_unmute) else stringResource(R.string.player_mute),
onClick = {
onOverlayInteracted()
- if (currentRecordingStatus == RecordingStatus.RECORDING) {
- onStopRecording()
- } else {
- onStartRecording()
- }
+ onToggleMute()
},
onInteraction = onOverlayInteracted
)
}
- if (currentChannel?.catchUpSupported == true) {
+ if (subtitleTrackCount > 0) {
item {
QuickActionButton(
- icon = stringResource(R.string.player_catchup_badge),
- label = stringResource(R.string.player_archive),
+ icon = stringResource(R.string.player_subs),
+ label = stringResource(R.string.player_subs),
onClick = {
onOverlayInteracted()
- onDismiss()
- onOpenFullEpg()
+ onOpenSubtitleTracks()
},
onInteraction = onOverlayInteracted
)
}
}
- if (currentChannel?.catchUpSupported == true && currentProgram?.hasArchive == true) {
+ if (videoQualityCount > 0) {
item {
QuickActionButton(
- icon = stringResource(R.string.player_action_restart_short),
- label = stringResource(R.string.player_restart),
+ icon = stringResource(R.string.player_action_quality),
+ label = stringResource(R.string.player_quality_short),
onClick = {
onOverlayInteracted()
- onRestartProgram()
- onDismiss()
+ onOpenVideoTracks()
},
onInteraction = onOverlayInteracted
)
}
}
- item {
- QuickActionButton(
- icon = stringResource(R.string.player_action_view),
- label = currentAspectRatio,
- onClick = {
- onOverlayInteracted()
- onToggleAspectRatio()
- },
- onInteraction = onOverlayInteracted
- )
- }
- if (!lastVisitedCategoryName.isNullOrBlank()) {
+ if (audioTrackCount > 0) {
item {
QuickActionButton(
- icon = stringResource(R.string.player_action_group),
- label = lastVisitedCategoryName,
+ icon = stringResource(R.string.player_audio),
+ label = stringResource(R.string.player_audio),
onClick = {
onOverlayInteracted()
- onOpenLastGroup()
+ onOpenAudioTracks()
},
onInteraction = onOverlayInteracted
)
@@ -479,17 +458,70 @@ fun ChannelInfoOverlay(
onInteraction = onOverlayInteracted
)
}
+ if (!lastVisitedCategoryName.isNullOrBlank()) {
+ item {
+ QuickActionButton(
+ icon = stringResource(R.string.player_action_group),
+ label = lastVisitedCategoryName,
+ onClick = {
+ onOverlayInteracted()
+ onOpenLastGroup()
+ },
+ onInteraction = onOverlayInteracted
+ )
+ }
+ }
item {
QuickActionButton(
- icon = stringResource(R.string.player_action_mute),
- label = if (isMuted) stringResource(R.string.player_unmute) else stringResource(R.string.player_mute),
+ icon = if (currentRecordingStatus == RecordingStatus.RECORDING) {
+ stringResource(R.string.player_stop_recording)
+ } else {
+ stringResource(R.string.player_record)
+ },
+ label = if (currentRecordingStatus == RecordingStatus.RECORDING) {
+ stringResource(R.string.player_stop_recording)
+ } else {
+ stringResource(R.string.player_record)
+ },
onClick = {
onOverlayInteracted()
- onToggleMute()
+ if (currentRecordingStatus == RecordingStatus.RECORDING) {
+ onStopRecording()
+ } else {
+ onStartRecording()
+ }
},
onInteraction = onOverlayInteracted
)
}
+ if (currentChannel?.catchUpSupported == true) {
+ item {
+ QuickActionButton(
+ icon = stringResource(R.string.player_catchup_badge),
+ label = stringResource(R.string.player_archive),
+ onClick = {
+ onOverlayInteracted()
+ onDismiss()
+ onOpenFullEpg()
+ },
+ onInteraction = onOverlayInteracted
+ )
+ }
+ }
+ if (currentChannel?.catchUpSupported == true && currentProgram?.hasArchive == true) {
+ item {
+ QuickActionButton(
+ icon = stringResource(R.string.player_action_restart_short),
+ label = stringResource(R.string.player_restart),
+ onClick = {
+ onOverlayInteracted()
+ onRestartProgram()
+ onDismiss()
+ },
+ onInteraction = onOverlayInteracted
+ )
+ }
+ }
item {
QuickActionButton(
icon = stringResource(R.string.player_action_cast),
@@ -512,44 +544,27 @@ fun ChannelInfoOverlay(
onInteraction = onOverlayInteracted
)
}
- if (subtitleTrackCount > 0) {
- item {
- QuickActionButton(
- icon = stringResource(R.string.player_subs),
- label = stringResource(R.string.player_subs),
- onClick = {
- onOverlayInteracted()
- onOpenSubtitleTracks()
- },
- onInteraction = onOverlayInteracted
- )
- }
- }
- if (audioTrackCount > 0) {
- item {
- QuickActionButton(
- icon = stringResource(R.string.player_audio),
- label = stringResource(R.string.player_audio),
- onClick = {
- onOverlayInteracted()
- onOpenAudioTracks()
- },
- onInteraction = onOverlayInteracted
- )
- }
+ item {
+ QuickActionButton(
+ icon = stringResource(R.string.player_action_pip),
+ label = stringResource(R.string.player_pip_short),
+ onClick = {
+ onOverlayInteracted()
+ onEnterPictureInPicture()
+ },
+ onInteraction = onOverlayInteracted
+ )
}
- if (videoQualityCount > 0) {
- item {
- QuickActionButton(
- icon = stringResource(R.string.player_action_quality),
- label = stringResource(R.string.player_quality_short),
- onClick = {
- onOverlayInteracted()
- onOpenVideoTracks()
- },
- onInteraction = onOverlayInteracted
- )
- }
+ item {
+ QuickActionButton(
+ icon = stringResource(R.string.player_action_view),
+ label = currentAspectRatio,
+ onClick = {
+ onOverlayInteracted()
+ onToggleAspectRatio()
+ },
+ onInteraction = onOverlayInteracted
+ )
}
}
}
@@ -648,6 +663,7 @@ fun ChannelListOverlay(
val canScrollUp by remember { derivedStateOf { listState.canScrollBackward } }
val canScrollDown by remember { derivedStateOf { listState.canScrollForward } }
val scope = rememberCoroutineScope()
+ val isRtl = LocalLayoutDirection.current == LayoutDirection.Rtl
// Count header items before the channels list so we can map channel index → lazy index
val headerItemCount = remember(lastVisitedCategoryName, recentChannels) {
var count = 2 // title row + channel list hint (always present)
@@ -881,30 +897,48 @@ fun ChannelListOverlay(
Row(
modifier = Modifier
.fillMaxWidth()
- .padding(horizontal = 16.dp, vertical = 12.dp),
+ .padding(horizontal = 14.dp, vertical = 12.dp),
verticalAlignment = Alignment.CenterVertically,
- horizontalArrangement = Arrangement.spacedBy(12.dp)
+ horizontalArrangement = Arrangement.spacedBy(8.dp)
) {
- if (isSelected) {
- StatusPill(
- label = stringResource(R.string.player_channel_selected),
- containerColor = AppColors.BrandMuted
- )
- } else {
- Spacer(Modifier.width(42.dp))
+ Box(
+ modifier = Modifier.width(48.dp),
+ contentAlignment = Alignment.CenterStart
+ ) {
+ if (isSelected) {
+ StatusPill(
+ label = stringResource(R.string.player_channel_selected),
+ containerColor = AppColors.BrandMuted
+ )
+ }
}
Text(
text = channelNumber.toString().padStart(2, '0'),
- style = MaterialTheme.typography.labelMedium,
- color = Color.White.copy(alpha = 0.72f)
+ style = MaterialTheme.typography.labelSmall.copy(fontSize = 16.sp),
+ color = Color.White.copy(alpha = 0.72f),
+ textAlign = TextAlign.Start,
+ modifier = Modifier.width(28.dp)
)
Text(
text = channel.name,
- style = MaterialTheme.typography.bodyLarge,
+ style = MaterialTheme.typography.bodyMedium.copy(fontSize = 22.sp),
color = Color.White,
maxLines = 1,
- overflow = TextOverflow.Ellipsis,
- modifier = Modifier.weight(1f)
+ overflow = if (isFocused) TextOverflow.Clip else TextOverflow.Ellipsis,
+ modifier = Modifier
+ .weight(1f)
+ .then(
+ if (isFocused) {
+ Modifier.basicMarquee(
+ iterations = Int.MAX_VALUE,
+ initialDelayMillis = 600,
+ repeatDelayMillis = 900,
+ velocity = 26.dp
+ )
+ } else {
+ Modifier
+ }
+ )
)
if (channel.catchUpSupported) {
StatusPill(
@@ -982,10 +1016,13 @@ fun ChannelListOverlay(
onOpenCategories()
},
modifier = Modifier
- .align(Alignment.CenterStart)
- .offset(x = (-28).dp)
+ .align(if (isRtl) Alignment.CenterEnd else Alignment.CenterStart)
+ .offset(x = if (isRtl) 28.dp else (-28).dp)
.onFocusChanged { if (it.isFocused) onOverlayInteracted() },
- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(topStart = 10.dp, bottomStart = 10.dp)),
+ shape = ClickableSurfaceDefaults.shape(
+ if (isRtl) RoundedCornerShape(topEnd = 10.dp, bottomEnd = 10.dp)
+ else RoundedCornerShape(topStart = 10.dp, bottomStart = 10.dp)
+ ),
colors = ClickableSurfaceDefaults.colors(
containerColor = AppColors.SurfaceEmphasis.copy(alpha = 0.92f),
focusedContainerColor = Primary
@@ -999,7 +1036,7 @@ fun ChannelListOverlay(
verticalArrangement = Arrangement.Center
) {
Text(
- text = "\u25c4",
+ text = if (isRtl) "\u25ba" else "\u25c4",
style = MaterialTheme.typography.labelSmall,
color = Color.White.copy(alpha = 0.85f)
)
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerSystemOverlays.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerSystemOverlays.kt
index fcde7baa..c66e3998 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerSystemOverlays.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerSystemOverlays.kt
@@ -3,6 +3,7 @@ package com.streamvault.app.ui.screens.player.overlay
import android.view.KeyEvent
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
+import androidx.compose.foundation.focusGroup
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
@@ -23,6 +24,7 @@ import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.focus.FocusRequester
+import androidx.compose.ui.focus.focusProperties
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.key.onPreviewKeyEvent
@@ -434,6 +436,16 @@ fun PlayerResumePrompt(
onStartOver: () -> Unit,
onResume: () -> Unit
) {
+ val startOverFocusRequester = remember(title) { FocusRequester() }
+ val resumeFocusRequester = remember(title) { FocusRequester() }
+
+ LaunchedEffect(title) {
+ resumeFocusRequester.requestFocusSafely(
+ tag = "PlayerResumePrompt",
+ target = "Resume button"
+ )
+ }
+
Box(
modifier = Modifier
.fillMaxSize()
@@ -444,6 +456,15 @@ fun PlayerResumePrompt(
modifier = Modifier
.widthIn(max = 500.dp)
.background(SurfaceElevated, RoundedCornerShape(12.dp))
+ .focusGroup()
+ .onPreviewKeyEvent { event ->
+ if (event.nativeKeyEvent.action != KeyEvent.ACTION_DOWN) return@onPreviewKeyEvent false
+ when (event.nativeKeyEvent.keyCode) {
+ KeyEvent.KEYCODE_DPAD_UP,
+ KeyEvent.KEYCODE_DPAD_DOWN -> true
+ else -> false
+ }
+ }
.padding(32.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
@@ -468,7 +489,12 @@ fun PlayerResumePrompt(
containerColor = SurfaceElevated,
focusedContainerColor = SurfaceHighlight
),
- modifier = Modifier.weight(1f)
+ modifier = Modifier
+ .weight(1f)
+ .focusRequester(startOverFocusRequester)
+ .focusProperties {
+ right = resumeFocusRequester
+ }
) {
Text(
stringResource(R.string.player_resume_start_over),
@@ -487,7 +513,12 @@ fun PlayerResumePrompt(
containerColor = Primary,
focusedContainerColor = PrimaryLight
),
- modifier = Modifier.weight(1f)
+ modifier = Modifier
+ .weight(1f)
+ .focusRequester(resumeFocusRequester)
+ .focusProperties {
+ left = startOverFocusRequester
+ }
) {
Text(
stringResource(R.string.player_resume),
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupScreen.kt
index 6a53ef59..16112658 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
@@ -69,7 +69,14 @@ fun ProviderSetupScreen(
coroutineScope.launch(Dispatchers.IO) {
try {
val inputStream = context.contentResolver.openInputStream(uri)
- if (inputStream != null) {
+ if (inputStream == null) {
+ withContext(Dispatchers.Main) {
+ fileImportError = context.getString(R.string.setup_file_import_failed)
+ }
+ return@launch
+ }
+
+ inputStream.use {
var fileName = "Local_Playlist"
val cursor = context.contentResolver.query(uri, null, null, null, null)
cursor?.use {
@@ -105,10 +112,6 @@ fun ProviderSetupScreen(
}
fileImportError = null
}
- } else {
- withContext(Dispatchers.Main) {
- fileImportError = context.getString(R.string.setup_file_import_failed)
- }
}
} catch (e: Exception) {
withContext(Dispatchers.Main) {
@@ -127,7 +130,7 @@ fun ProviderSetupScreen(
}
LaunchedEffect(knownLocalM3uUrls) {
- cleanupOldImportedM3uFiles(
+ cleanupOldImportedM3uFilesAsync(
filesDir = context.filesDir,
protectedFileUris = knownLocalM3uUrls,
keepLatest = 20
@@ -159,7 +162,7 @@ fun ProviderSetupScreen(
selectedLocal?.let(::add)
}
- cleanupOldImportedM3uFiles(
+ cleanupOldImportedM3uFilesAsync(
filesDir = context.filesDir,
protectedFileUris = protectedUris,
keepLatest = 20
@@ -878,6 +881,20 @@ private fun cleanupOldImportedM3uFiles(
}
}
+private suspend fun cleanupOldImportedM3uFilesAsync(
+ filesDir: java.io.File,
+ protectedFileUris: Set<String>,
+ keepLatest: Int
+) {
+ withContext(Dispatchers.IO) {
+ cleanupOldImportedM3uFiles(
+ filesDir = filesDir,
+ protectedFileUris = protectedFileUris,
+ keepLatest = keepLatest
+ )
+ }
+}
+
private fun resolveFileImportError(
context: android.content.Context,
error: Throwable
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupViewModel.kt
index e4c96f7c..4c0bf581 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
@@ -9,9 +9,12 @@ import com.streamvault.domain.usecase.ValidateAndAddProvider
import com.streamvault.domain.usecase.ValidateAndAddProviderResult
import com.streamvault.domain.usecase.XtreamProviderSetupCommand
import dagger.hilt.android.lifecycle.HiltViewModel
-import kotlinx.coroutines.flow.*
-import kotlinx.coroutines.launch
import javax.inject.Inject
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.asStateFlow
+import kotlinx.coroutines.flow.update
+import kotlinx.coroutines.launch
@HiltViewModel
class ProviderSetupViewModel @Inject constructor(
@@ -54,7 +57,6 @@ class ProviderSetupViewModel @Inject constructor(
name = provider.name,
serverUrl = provider.serverUrl,
username = provider.username,
- // Do not prefill stored passwords back into UI.
password = "",
m3uUrl = provider.m3uUrl,
selectedTab = if (provider.type == ProviderType.M3U) 1 else 0,
@@ -88,7 +90,13 @@ class ProviderSetupViewModel @Inject constructor(
)) {
is ValidateAndAddProviderResult.Success -> {
_uiState.update {
- it.copy(isLoading = false, loginSuccess = true, error = null, validationError = null, syncProgress = null)
+ it.copy(
+ isLoading = false,
+ loginSuccess = true,
+ error = null,
+ validationError = null,
+ syncProgress = null
+ )
}
}
is ValidateAndAddProviderResult.ValidationError -> {
@@ -97,17 +105,24 @@ class ProviderSetupViewModel @Inject constructor(
}
}
is ValidateAndAddProviderResult.Error -> {
+ val normalizedMessage = result.message.lowercase()
val userMessage = when {
- result.message.contains("certificate", ignoreCase = true) ||
- result.message.contains("trust", ignoreCase = true) ->
- "Secure connection failed — the server's TLS certificate is not trusted on this device"
- result.message.contains("authentication failed", ignoreCase = true) ||
- result.message.contains("auth", ignoreCase = true) ->
- "Login failed — please check your credentials and server URL"
- result.message.contains("unable to connect", ignoreCase = true) ||
- result.message.contains("timeout", ignoreCase = true) ||
- result.message.contains("network", ignoreCase = true) ->
- "Cannot reach server — check your internet connection and server URL"
+ normalizedMessage.contains("certificate") ||
+ normalizedMessage.contains("trust") ->
+ "Secure connection failed - the server's TLS certificate is not trusted on this device"
+ normalizedMessage.contains("provider login succeeded") ||
+ normalizedMessage.contains("initial sync failed") ->
+ "Login succeeded, but the initial sync failed while loading the playlist"
+ normalizedMessage.contains("authentication failed") ||
+ normalizedMessage.contains("invalid credentials") ||
+ (normalizedMessage.contains("username") && normalizedMessage.contains("password")) ->
+ "Login failed - please check your credentials and server URL"
+ normalizedMessage.contains("temporarily busy") ->
+ "Server is temporarily busy - try syncing again in a moment"
+ normalizedMessage.contains("unable to connect") ||
+ normalizedMessage.contains("timeout") ||
+ normalizedMessage.contains("network") ->
+ "Cannot reach server - check your internet connection and server URL"
else -> result.message
}
_uiState.update {
@@ -122,7 +137,9 @@ class ProviderSetupViewModel @Inject constructor(
_uiState.update { it.copy(validationError = null, error = null) }
if (url.isBlank()) {
- _uiState.update { it.copy(validationError = if (_uiState.value.m3uTab == 0) "Please enter M3U URL" else "Please select a file") }
+ _uiState.update {
+ it.copy(validationError = if (_uiState.value.m3uTab == 0) "Please enter M3U URL" else "Please select a file")
+ }
return
}
@@ -140,7 +157,13 @@ class ProviderSetupViewModel @Inject constructor(
)) {
is ValidateAndAddProviderResult.Success -> {
_uiState.update {
- it.copy(isLoading = false, loginSuccess = true, error = null, validationError = null, syncProgress = null)
+ it.copy(
+ isLoading = false,
+ loginSuccess = true,
+ error = null,
+ validationError = null,
+ syncProgress = null
+ )
}
}
is ValidateAndAddProviderResult.ValidationError -> {
@@ -150,7 +173,12 @@ class ProviderSetupViewModel @Inject constructor(
}
is ValidateAndAddProviderResult.Error -> {
_uiState.update {
- it.copy(isLoading = false, error = "Could not validate playlist: ${result.message}", validationError = null, syncProgress = null)
+ it.copy(
+ isLoading = false,
+ error = "Could not validate playlist: ${result.message}",
+ validationError = null,
+ syncProgress = null
+ )
}
}
}
@@ -167,9 +195,8 @@ data class ProviderSetupState(
val syncProgress: String? = null,
val isEditing: Boolean = false,
val existingProviderId: Long? = null,
- // Pre-fill data
val selectedTab: Int = 0,
- val m3uTab: Int = 0, // 0 = URL, 1 = File
+ val m3uTab: Int = 0,
val name: String = "",
val serverUrl: String = "",
val username: String = "",
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/search/SearchScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/search/SearchScreen.kt
index 175159df..cf603e39 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
@@ -44,6 +44,7 @@ import com.streamvault.app.ui.components.TvEmptyState
import com.streamvault.app.ui.components.shell.AppNavigationChrome
import com.streamvault.app.ui.components.shell.AppScreenScaffold
import com.streamvault.app.ui.theme.*
+import com.streamvault.domain.manager.ParentalControlManager
import com.streamvault.domain.model.Channel
import com.streamvault.domain.model.Movie
import com.streamvault.domain.model.Series
@@ -62,7 +63,8 @@ import javax.inject.Inject
class SearchViewModel @Inject constructor(
private val providerRepository: ProviderRepository,
private val searchContent: SearchContent,
- private val preferencesRepository: com.streamvault.data.preferences.PreferencesRepository
+ private val preferencesRepository: com.streamvault.data.preferences.PreferencesRepository,
+ private val parentalControlManager: ParentalControlManager
) : ViewModel() {
private companion object {
const val MAX_RESULTS_PER_SECTION = 120
@@ -78,6 +80,12 @@ class SearchViewModel @Inject constructor(
val recentQueries: StateFlow<List<String>> = _recentQueries.asStateFlow()
private val _parentalControlLevel = MutableStateFlow(0)
+ private val _activeProviderId = MutableStateFlow<Long?>(null)
+ private val unlockedCategoryIds = providerRepository.getActiveProvider()
+ .onEach { provider -> _activeProviderId.value = provider?.id }
+ .flatMapLatest { provider ->
+ provider?.let { parentalControlManager.unlockedCategoriesForProvider(it.id) } ?: flowOf(emptySet())
+ }
init {
viewModelScope.launch {
@@ -97,21 +105,24 @@ class SearchViewModel @Inject constructor(
providerRepository.getActiveProvider(),
_query.debounce(300),
_selectedTab,
- _parentalControlLevel
- ) { provider, query, tab, level ->
- SearchFilterParams(provider, query, tab, level)
+ _parentalControlLevel,
+ unlockedCategoryIds
+ ) { provider, query, tab, level, unlockedIds ->
+ SearchFilterParams(provider, query, tab, level, unlockedIds)
}.flatMapLatest { params ->
val provider = params.provider
val query = params.query
val tab = params.tab
val level = params.level
+ val unlockedIds = params.unlockedCategoryIds
if (provider == null || query.length < 2) {
flowOf(
SearchUiState(
parentalControlLevel = level,
hasActiveProvider = provider != null,
- queryLength = query.length
+ queryLength = query.length,
+ unlockedCategoryIds = unlockedIds
)
)
} else {
@@ -129,7 +140,8 @@ class SearchViewModel @Inject constructor(
hasSearched = true,
parentalControlLevel = level,
hasActiveProvider = true,
- queryLength = query.length
+ queryLength = query.length,
+ unlockedCategoryIds = unlockedIds
)
}
}
@@ -180,13 +192,20 @@ class SearchViewModel @Inject constructor(
suspend fun verifyPin(pin: String): Boolean {
return preferencesRepository.verifyParentalPin(pin)
}
+
+ fun unlockCategory(categoryId: Long?) {
+ val providerId = _activeProviderId.value ?: return
+ val resolvedCategoryId = categoryId ?: return
+ parentalControlManager.unlockCategory(providerId, resolvedCategoryId)
+ }
}
private data class SearchFilterParams(
val provider: com.streamvault.domain.model.Provider?,
val query: String,
val tab: SearchTab,
- val level: Int
+ val level: Int,
+ val unlockedCategoryIds: Set<Long>
)
enum class SearchTab(@get:StringRes val titleRes: Int) {
@@ -211,7 +230,8 @@ data class SearchUiState(
val hasSearched: Boolean = false,
val parentalControlLevel: Int = 0,
val hasActiveProvider: Boolean = false,
- val queryLength: Int = 0
+ val queryLength: Int = 0,
+ val unlockedCategoryIds: Set<Long> = emptySet()
) {
val isEmpty: Boolean get() = hasSearched && channels.isEmpty() && movies.isEmpty() && series.isEmpty()
val totalResults: Int get() = channels.size + movies.size + series.size
@@ -243,6 +263,16 @@ fun SearchScreen(
val scope = rememberCoroutineScope()
val selectedStateLabel = stringResource(R.string.a11y_selected)
+ fun isLocked(categoryId: Long?, isAdult: Boolean, isUserProtected: Boolean): Boolean {
+ if (uiState.parentalControlLevel != 1) {
+ return false
+ }
+ if (!isAdult && !isUserProtected) {
+ return false
+ }
+ return categoryId == null || categoryId !in uiState.unlockedCategoryIds
+ }
+
LaunchedEffect(Unit) {
runCatching { searchFocusRequester.requestFocus() }
}
@@ -272,6 +302,9 @@ fun SearchScreen(
onPinEntered = { pin ->
scope.launch {
if (viewModel.verifyPin(pin)) {
+ pendingChannel?.categoryId?.let(viewModel::unlockCategory)
+ pendingMovie?.categoryId?.let(viewModel::unlockCategory)
+ pendingSeries?.categoryId?.let(viewModel::unlockCategory)
showPinDialog = false
pinError = null
pendingChannel?.let { onChannelClick(it) }
@@ -456,7 +489,11 @@ fun SearchScreen(
}
}
items(uiState.channels, key = { it.id }) { channel ->
- val isLocked = (channel.isAdult || channel.isUserProtected) && uiState.parentalControlLevel == 1
+ val isLocked = isLocked(
+ categoryId = channel.categoryId,
+ isAdult = channel.isAdult,
+ isUserProtected = channel.isUserProtected
+ )
ChannelCard(
channel = channel,
isLocked = isLocked,
@@ -480,7 +517,11 @@ fun SearchScreen(
}
}
items(uiState.movies, key = { it.id }) { movie ->
- val isLocked = (movie.isAdult || movie.isUserProtected) && uiState.parentalControlLevel == 1
+ val isLocked = isLocked(
+ categoryId = movie.categoryId,
+ isAdult = movie.isAdult,
+ isUserProtected = movie.isUserProtected
+ )
MovieCard(
movie = movie,
isLocked = isLocked,
@@ -504,7 +545,11 @@ fun SearchScreen(
}
}
items(uiState.series, key = { it.id }) { series ->
- val isLocked = (series.isAdult || series.isUserProtected) && uiState.parentalControlLevel == 1
+ val isLocked = isLocked(
+ categoryId = series.categoryId,
+ isAdult = series.isAdult,
+ isUserProtected = series.isUserProtected
+ )
SeriesCard(
series = series,
isLocked = isLocked,
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesDetailScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesDetailScreen.kt
index e783febb..a119d232 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesDetailScreen.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesDetailScreen.kt
@@ -52,6 +52,7 @@ import com.streamvault.app.ui.components.shell.ContentMetadataStrip
import com.streamvault.app.ui.components.shell.EpisodeRowCard
import com.streamvault.app.ui.components.shell.StatusPill
import com.streamvault.app.ui.design.AppColors
+import com.streamvault.app.ui.model.formatVodRatingLabel
import com.streamvault.domain.model.Episode
import com.streamvault.domain.model.Season
import com.streamvault.domain.model.Series
@@ -201,7 +202,7 @@ private fun SeriesDetailContent(
StatusPill(label = stringResource(R.string.nav_series), containerColor = AppColors.BrandMuted)
series.rating.takeIf { it > 0f }?.let {
StatusPill(
- label = stringResource(R.string.label_rating, String.format("%.1f", it)),
+ label = formatVodRatingLabel(it),
containerColor = AppColors.Warning,
contentColor = Color.Black
)
@@ -264,7 +265,7 @@ private fun SeriesDetailContent(
StatusPill(label = stringResource(R.string.nav_series), containerColor = AppColors.BrandMuted)
series.rating.takeIf { it > 0f }?.let {
StatusPill(
- label = stringResource(R.string.label_rating, String.format("%.1f", it)),
+ label = formatVodRatingLabel(it),
containerColor = AppColors.Warning,
contentColor = Color.Black
)
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesScreen.kt
index 4763b703..75f8faa4 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
@@ -356,6 +356,14 @@ private fun SeriesVodContent(
kotlin.math.abs(category.id) !in uiState.unlockedCategoryIds
}
}
+ val isSeriesLocked = remember(uiState.parentalControlLevel, uiState.unlockedCategoryIds) {
+ { series: Series ->
+ val categoryId = series.categoryId
+ (series.isAdult || series.isUserProtected) &&
+ uiState.parentalControlLevel == 1 &&
+ (categoryId == null || kotlin.math.abs(categoryId) !in uiState.unlockedCategoryIds)
+ }
+ }
val openProtectedCategory: (Category) -> Unit = onProtectedCategoryClick
val visibleCategoryNames = remember(uiState.categoryNames, categoryByName, uiState.parentalControlLevel, uiState.unlockedCategoryIds) {
uiState.categoryNames.filter { name ->
@@ -428,7 +436,7 @@ private fun SeriesVodContent(
?: stringResource(R.string.series_library_lens_subtitle),
actionLabel = stringResource(R.string.player_resume).substringBefore(" "),
onClick = {
- val isLocked = (heroSeries.isAdult || heroSeries.isUserProtected) && uiState.parentalControlLevel == 1
+ val isLocked = isSeriesLocked(heroSeries)
if (isLocked) onProtectedSeriesClick(heroSeries.id) else onSeriesClick(heroSeries.id)
},
modifier = Modifier.padding(top = 8.dp, bottom = 6.dp)
@@ -517,7 +525,7 @@ private fun SeriesVodContent(
onSeeAll = { onSelectCategory(uiState.favoriteCategoryName) },
keySelector = { it.id }
) { series ->
- val isLocked = (series.isAdult || series.isUserProtected) && uiState.parentalControlLevel == 1
+ val isLocked = isSeriesLocked(series)
SeriesCard(
series = series,
isLocked = isLocked,
@@ -537,7 +545,7 @@ private fun SeriesVodContent(
onSeeAll = null,
keySelector = { it.id }
) { series ->
- val isLocked = (series.isAdult || series.isUserProtected) && uiState.parentalControlLevel == 1
+ val isLocked = isSeriesLocked(series)
SeriesCard(
series = series,
isLocked = isLocked,
@@ -556,7 +564,7 @@ private fun SeriesVodContent(
onSeeAll = null,
keySelector = { it.id }
) { series ->
- val isLocked = (series.isAdult || series.isUserProtected) && uiState.parentalControlLevel == 1
+ val isLocked = isSeriesLocked(series)
SeriesCard(
series = series,
isLocked = isLocked,
@@ -583,7 +591,7 @@ private fun SeriesVodContent(
},
keySelector = { it.id }
) { series ->
- val isLocked = (series.isAdult || series.isUserProtected) && uiState.parentalControlLevel == 1
+ val isLocked = isSeriesLocked(series)
SeriesCard(
series = series,
isLocked = isLocked,
@@ -730,7 +738,7 @@ private fun SeriesVodContent(
}
} else {
gridItems(filteredGridSeries, key = { it.id }) { series ->
- val isLocked = (series.isAdult || series.isUserProtected) && uiState.parentalControlLevel == 1
+ val isLocked = isSeriesLocked(series)
val isDraggingThis = draggingSeries == series
SeriesCard(
series = series,
@@ -822,6 +830,14 @@ private fun SeriesVodClassicContent(
kotlin.math.abs(category.id) !in uiState.unlockedCategoryIds
}
}
+ val isSeriesLocked = remember(uiState.parentalControlLevel, uiState.unlockedCategoryIds) {
+ { series: Series ->
+ val categoryId = series.categoryId
+ (series.isAdult || series.isUserProtected) &&
+ uiState.parentalControlLevel == 1 &&
+ (categoryId == null || kotlin.math.abs(categoryId) !in uiState.unlockedCategoryIds)
+ }
+ }
val openProtectedCategory: (Category) -> Unit = onProtectedCategoryClick
val visibleCategoryNames = remember(uiState.categoryNames, categoryByName, uiState.parentalControlLevel, uiState.unlockedCategoryIds) {
uiState.categoryNames.filter { name ->
@@ -1036,7 +1052,7 @@ private fun SeriesVodClassicContent(
}
} else {
gridItems(filteredGridSeries, key = { it.id }) { series ->
- val isLocked = (series.isAdult || series.isUserProtected) && uiState.parentalControlLevel == 1
+ val isLocked = isSeriesLocked(series)
val isDraggingThis = draggingSeries == series
SeriesCard(
series = series,
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesViewModel.kt
index 475bece3..13710043 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
@@ -79,6 +79,8 @@ class SeriesViewModel @Inject constructor(
) : ViewModel() {
private companion object {
const val UNCATEGORIZED = "Uncategorized"
+ const val MIN_SEARCH_QUERY_LENGTH = 2
+ const val FAVORITE_ID_FETCH_BUFFER = 80
}
private val _uiState = MutableStateFlow(SeriesUiState())
@@ -143,6 +145,14 @@ class SeriesViewModel @Inject constructor(
emit(
if (params.query.isBlank()) {
buildPreviewCatalog(params)
+ } else if (params.query.length < MIN_SEARCH_QUERY_LENGTH) {
+ buildSearchCatalog(
+ series = emptyList(),
+ allFavorites = params.allFavorites,
+ customCategories = params.customCategories,
+ providerCategories = params.providerCategories,
+ hiddenCategoryIds = params.hiddenCategoryIds
+ ).copy(libraryCount = 0)
} else {
val searchResults = seriesRepository.searchSeries(params.providerId, params.query).first()
buildSearchCatalog(
@@ -846,6 +856,9 @@ class SeriesViewModel @Inject constructor(
if (request.selectedCategory.isNullOrBlank()) {
return SelectedSeriesCategorySnapshot()
}
+ if (request.query.isNotBlank() && request.query.length < MIN_SEARCH_QUERY_LENGTH) {
+ return SelectedSeriesCategorySnapshot()
+ }
val globalFavoriteIds = request.allFavorites
.asSequence()
@@ -855,16 +868,19 @@ class SeriesViewModel @Inject constructor(
val (selectedItems, totalCount) = when (request.selectedCategory) {
VodBrowseDefaults.FULL_LIBRARY_CATEGORY -> {
- val filteredItems = applyLocalBrowseToSeries(
- seriesRepository.getSeries(request.providerId)
- .first()
- .filterNot { item -> item.categoryId in request.hiddenCategoryIds },
- request.history,
- request.filterType,
- request.sortBy,
- request.query
- )
- filteredItems.take(request.loadLimit) to filteredItems.size
+ val result = seriesRepository
+ .browseSeries(
+ LibraryBrowseQuery(
+ providerId = request.providerId,
+ sortBy = request.sortBy,
+ filterBy = LibraryFilterBy(type = request.filterType),
+ searchQuery = request.query,
+ limit = request.loadLimit,
+ offset = 0
+ )
+ )
+ .first()
+ result.items.filterNot { item -> item.categoryId in request.hiddenCategoryIds } to result.totalCount
}
VodBrowseDefaults.FAVORITES_CATEGORY -> {
val ids = request.allFavorites
@@ -873,12 +889,17 @@ class SeriesViewModel @Inject constructor(
.sortedBy { it.position }
.map { it.contentId }
.toList()
+ val fetchIds = if (request.query.isBlank() && request.filterType == LibraryFilterType.ALL && request.sortBy == LibrarySortBy.LIBRARY) {
+ ids.take(request.loadLimit + FAVORITE_ID_FETCH_BUFFER)
+ } else {
+ ids
+ }
val items = if (ids.isEmpty()) {
emptyList()
} else {
- seriesRepository.getSeriesByIds(ids).first()
+ seriesRepository.getSeriesByIds(fetchIds).first()
.filterNot { item -> item.categoryId in request.hiddenCategoryIds }
- .orderByIds(ids)
+ .orderByIds(fetchIds)
}
val filteredItems = applyLocalBrowseToSeries(
items,
@@ -887,7 +908,7 @@ class SeriesViewModel @Inject constructor(
request.sortBy,
request.query
)
- filteredItems.take(request.loadLimit) to filteredItems.size
+ filteredItems.take(request.loadLimit) to if (fetchIds === ids) filteredItems.size else ids.size
}
else -> {
val customCategory = request.customCategories.firstOrNull { it.name == request.selectedCategory }
@@ -898,12 +919,17 @@ class SeriesViewModel @Inject constructor(
.sortedBy { it.position }
.map { it.contentId }
.toList()
+ val fetchIds = if (request.query.isBlank() && request.filterType == LibraryFilterType.ALL && request.sortBy == LibrarySortBy.LIBRARY) {
+ ids.take(request.loadLimit + FAVORITE_ID_FETCH_BUFFER)
+ } else {
+ ids
+ }
val items = if (ids.isEmpty()) {
emptyList()
} else {
- seriesRepository.getSeriesByIds(ids).first()
+ seriesRepository.getSeriesByIds(fetchIds).first()
.filterNot { item -> item.categoryId in request.hiddenCategoryIds }
- .orderByIds(ids)
+ .orderByIds(fetchIds)
}
val filteredItems = applyLocalBrowseToSeries(
items,
@@ -912,7 +938,7 @@ class SeriesViewModel @Inject constructor(
request.sortBy,
request.query
)
- filteredItems.take(request.loadLimit) to filteredItems.size
+ filteredItems.take(request.loadLimit) to if (fetchIds === ids) filteredItems.size else ids.size
} else {
val providerCategory = request.providerCategories.firstOrNull { it.name == request.selectedCategory }
if (providerCategory != null) {
diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml
index ec4e18b5..aed7b6eb 100644
--- a/app/src/main/res/values-ar/strings.xml
+++ b/app/src/main/res/values-ar/strings.xml
@@ -1,4 +1,4 @@
-<?xml version="1.0" encoding="utf-8"?>
+<?xml version='1.0' encoding='utf-8'?>
<resources>
<string name="app_name">StreamVault</string>
<string name="nav_home">الصفحة الرئيسية</string>
@@ -124,7 +124,7 @@
<string name="card_locked_channel">قناة مقفلة</string>
<string name="card_live_badge">مباشر</string>
<string name="card_locked">مغلق</string>
- <string name="category_see_all">شاهد الكل →</string>
+ <string name="category_see_all">شاهد الكل</string>
<string name="continue_watching_title">مواصلة المشاهدة</string>
<string name="continue_watching_season_episode">ق%1$d هـ%2$d</string>
<string name="playlist_no_provider">لا يوجد مزود</string>
@@ -383,7 +383,7 @@
<string name="settings_recording_status_completed">مكتمل</string>
<string name="settings_recording_status_failed">فشل</string>
<string name="settings_recording_status_cancelled">تم الإلغاء</string>
- <string name="settings_recording_time_window">%1$s → %2$s</string>
+ <string name="settings_recording_time_window">%1$s - %2$s</string>
<string name="settings_recording_recurrence_none">تسجيل لمرة واحدة</string>
<string name="settings_recording_recurrence_daily">يكرر يوميا</string>
<string name="settings_recording_recurrence_weekly">يتكرر اسبوعيا</string>
@@ -453,8 +453,8 @@
<string name="guide_shell_subtitle">قم بتوجيه المرشحات وكثافة الجدول الزمني وتفاصيل البرنامج المركزة في سطح واحد عن بعد أولاً.</string>
<string name="favorites_reordering">إعادة الترتيب</string>
<string name="favorites_reorder_mode">وضع إعادة الطلب</string>
- <string name="favorites_move_up">لأعلى أو لليسار: تحرك مبكرًا</string>
- <string name="favorites_move_down">لأسفل أو لليمين: تحرك لاحقًا</string>
+ <string name="favorites_move_up">تحرك إلى موضع أبكر</string>
+ <string name="favorites_move_down">تحرك إلى موضع لاحق</string>
<string name="favorites_confirm">المركز: حفظ الطلب</string>
<string name="favorites_cancel">العودة: إلغاء</string>
<string name="search_title">بحث</string>
@@ -868,4 +868,89 @@
<string name="settings_history_cleared">تم مسح سجل المشاهدة والأحداث الأخيرة</string>
<string name="settings_pin_changed">تم حفظ رقم التعريف الشخصي بنجاح</string>
<string name="home_reorder_channels">إعادة ترتيب القنوات</string>
+
+ <string name="category_options_hide">Hide Category</string>
+ <string name="settings_provider_category_controls_action">Category Controls</string>
+ <string name="settings_provider_category_controls_title">Category Controls</string>
+ <string name="settings_provider_category_controls_subtitle">Lock, unlock, hide, and restore categories for the current playlist from one place.</string>
+ <string name="settings_provider_category_controls_search">Search categories...</string>
+ <string name="settings_categories_title">Category Preferences</string>
+ <string name="settings_categories_subtitle">Hide provider categories and keep their sort order exactly how you want it.</string>
+ <string name="settings_category_sorting_title">Category Sorting</string>
+ <string name="settings_category_sorting_subtitle">Sort categories for the active playlist. Locking and hiding now live in Category Controls.</string>
+ <string name="settings_category_sort_live">Live TV Categories</string>
+ <string name="settings_category_sort_movies">Movie Categories</string>
+ <string name="settings_category_sort_series">Series Categories</string>
+ <string name="settings_hidden_categories_title">Hidden Categories</string>
+ <string name="settings_hidden_categories_subtitle">Restore any provider categories you previously hid from browsing surfaces.</string>
+ <string name="settings_hidden_categories_none">None hidden</string>
+ <string name="settings_hidden_categories_count">%1$d hidden</string>
+ <string name="settings_hidden_categories_empty">No hidden categories right now.</string>
+ <string name="settings_unhide_category">Unhide</string>
+ <string name="settings_hide_category">Hide</string>
+ <string name="settings_category_sort_default">Provider Order</string>
+ <string name="settings_category_sort_az">A-Z</string>
+ <string name="settings_category_sort_za">Z-A</string>
+ <string name="settings_category_sort_most_items">Most Items First</string>
+ <string name="settings_category_sort_least_items">Least Items First</string>
+ <string name="settings_category_type_live_description">Sort and hide provider live groups while keeping All Channels, Favorites, Recent, and custom groups in their pinned positions.</string>
+ <string name="settings_category_type_movies_description">Sort and hide provider movie categories without affecting Favorites, Resume, or custom shelves.</string>
+ <string name="settings_category_type_series_description">Sort and hide provider series categories without affecting Favorites, Continue Watching, or custom shelves.</string>
+ <string name="settings_live_channel_numbering_mode">Live TV Channel Numbering</string>
+ <string name="settings_live_channel_numbering_mode_subtitle">Choose whether live channels use their position in the current group or keep the original numbers from the provider.</string>
+ <string name="settings_live_channel_numbering_group">Per Group</string>
+ <string name="settings_live_channel_numbering_group_desc">Default behavior. Renumber channels based on their position inside the current category or custom group.</string>
+ <string name="settings_live_channel_numbering_provider">Provider Number</string>
+ <string name="settings_live_channel_numbering_provider_desc">Keep the original channel number supplied by the playlist provider whenever it exists.</string>
+ <string name="settings_vod_view_mode">VOD layout</string>
+ <string name="settings_vod_view_mode_subtitle">Choose between the modern shelves view and a classic split layout.</string>
+ <string name="settings_vod_view_mode_modern">Modern</string>
+ <string name="settings_vod_view_mode_modern_desc">Shelf-based browsing with featured rows and category previews.</string>
+ <string name="settings_vod_view_mode_classic">Classic</string>
+ <string name="settings_vod_view_mode_classic_desc">Category list on the left with a stacked poster grid on the right.</string>
+ <string name="vod_classic_categories_title">Categories</string>
+ <string name="vod_classic_category_search">Search in categories</string>
+ <string name="vod_classic_all">All</string>
+ <string name="vod_classic_continue_watching">Continue Watching</string>
+ <string name="vod_classic_recently_added">Recently Added</string>
+ <string name="vod_classic_results_count">%1$d items</string>
+ <string name="vod_classic_empty_category">No titles found in this section.</string>
+ <string name="epg_no_schedule_short">No schedule</string>
+ <string name="epg_show_app_navigation">Show App Nav</string>
+ <string name="epg_program_details_show">Program Details</string>
+ <string name="epg_program_details_hide">Hide Details</string>
+ <string name="epg_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_short">Categories</string>
+ <string name="epg_search_short">Program Search</string>
+ <string name="epg_options_short">Options</string>
+ <string name="epg_schedule_summary_short">%1$d/%2$d with guide</string>
+ <string name="epg_stale_short">Guide may be stale</string>
+ <string name="settings_category_mode_protection">Lock / Unlock</string>
+ <string name="settings_category_mode_visibility">Hide / Unhide</string>
+ <string name="settings_category_protection_summary_title">Lock changes are reviewed before they go live</string>
+ <string name="settings_category_protection_summary_body">Toggle the categories you want to lock or unlock, then save. Saving requires your parental PIN.</string>
+ <string name="settings_category_protection_summary_body_no_pin">Toggle the categories you want to lock or unlock, then save. You will be asked to create a parental PIN before the changes are applied.</string>
+ <string name="settings_category_protection_save">Save Locks (%1$d)</string>
+ <string name="settings_category_protection_save_idle">Save Locks</string>
+ <string name="settings_category_protection_reset">Reset</string>
+ <string name="settings_category_visibility_summary_title">Visibility changes apply immediately</string>
+ <string name="settings_category_visibility_summary_body">%1$d categories are currently hidden for this playlist. Hiding and restoring does not require a PIN.</string>
+ <string name="settings_category_status_locked">Locked</string>
+ <string name="settings_category_status_unlocked">Unlocked</string>
+ <string name="settings_category_status_auto_locked">Auto-Locked</string>
+ <string name="settings_category_status_hidden">Hidden</string>
+ <string name="settings_category_controls_empty">No categories match this search.</string>
+ <string name="movie_loading_details">Loading details...</string>
+ <string name="movie_not_found">Movie not found</string>
+ <string name="movie_detail_back">العودة إلى المكتبة</string>
+ <string name="movie_detail_play">Play</string>
+ <string name="movie_detail_trailer">Trailer</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>
+ <string name="movie_detail_duration">Duration:</string>
+ <string name="movie_detail_genre">Genre:</string>
+ <string name="movie_detail_cast">Cast:</string>
+ <string name="movie_detail_unknown">Unknown</string>
</resources>
diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml
index c01daebe..0188d2a7 100644
--- a/app/src/main/res/values-cs/strings.xml
+++ b/app/src/main/res/values-cs/strings.xml
@@ -868,4 +868,89 @@
<string name="settings_history_cleared">Historie sledování a nedávné události byly vymazány</string>
<string name="settings_pin_changed">PIN byl úspěšně uložen</string>
<string name="home_reorder_channels">Změnit pořadí kanálů</string>
+ <!-- Synced fallback strings from English -->
+ <string name="category_options_hide">Hide Category</string>
+ <string name="settings_provider_category_controls_action">Category Controls</string>
+ <string name="settings_provider_category_controls_title">Category Controls</string>
+ <string name="settings_provider_category_controls_subtitle">Lock, unlock, hide, and restore categories for the current playlist from one place.</string>
+ <string name="settings_provider_category_controls_search">Search categories...</string>
+ <string name="settings_categories_title">Category Preferences</string>
+ <string name="settings_categories_subtitle">Hide provider categories and keep their sort order exactly how you want it.</string>
+ <string name="settings_category_sorting_title">Category Sorting</string>
+ <string name="settings_category_sorting_subtitle">Sort categories for the active playlist. Locking and hiding now live in Category Controls.</string>
+ <string name="settings_category_sort_live">Live TV Categories</string>
+ <string name="settings_category_sort_movies">Movie Categories</string>
+ <string name="settings_category_sort_series">Series Categories</string>
+ <string name="settings_hidden_categories_title">Hidden Categories</string>
+ <string name="settings_hidden_categories_subtitle">Restore any provider categories you previously hid from browsing surfaces.</string>
+ <string name="settings_hidden_categories_none">None hidden</string>
+ <string name="settings_hidden_categories_count">%1$d hidden</string>
+ <string name="settings_hidden_categories_empty">No hidden categories right now.</string>
+ <string name="settings_unhide_category">Unhide</string>
+ <string name="settings_hide_category">Hide</string>
+ <string name="settings_category_sort_default">Provider Order</string>
+ <string name="settings_category_sort_az">A-Z</string>
+ <string name="settings_category_sort_za">Z-A</string>
+ <string name="settings_category_sort_most_items">Most Items First</string>
+ <string name="settings_category_sort_least_items">Least Items First</string>
+ <string name="settings_category_type_live_description">Sort and hide provider live groups while keeping All Channels, Favorites, Recent, and custom groups in their pinned positions.</string>
+ <string name="settings_category_type_movies_description">Sort and hide provider movie categories without affecting Favorites, Resume, or custom shelves.</string>
+ <string name="settings_category_type_series_description">Sort and hide provider series categories without affecting Favorites, Continue Watching, or custom shelves.</string>
+ <string name="settings_live_channel_numbering_mode">Live TV Channel Numbering</string>
+ <string name="settings_live_channel_numbering_mode_subtitle">Choose whether live channels use their position in the current group or keep the original numbers from the provider.</string>
+ <string name="settings_live_channel_numbering_group">Per Group</string>
+ <string name="settings_live_channel_numbering_group_desc">Default behavior. Renumber channels based on their position inside the current category or custom group.</string>
+ <string name="settings_live_channel_numbering_provider">Provider Number</string>
+ <string name="settings_live_channel_numbering_provider_desc">Keep the original channel number supplied by the playlist provider whenever it exists.</string>
+ <string name="settings_vod_view_mode">VOD layout</string>
+ <string name="settings_vod_view_mode_subtitle">Choose between the modern shelves view and a classic split layout.</string>
+ <string name="settings_vod_view_mode_modern">Modern</string>
+ <string name="settings_vod_view_mode_modern_desc">Shelf-based browsing with featured rows and category previews.</string>
+ <string name="settings_vod_view_mode_classic">Classic</string>
+ <string name="settings_vod_view_mode_classic_desc">Category list on the left with a stacked poster grid on the right.</string>
+ <string name="vod_classic_categories_title">Categories</string>
+ <string name="vod_classic_category_search">Search in categories</string>
+ <string name="vod_classic_all">All</string>
+ <string name="vod_classic_continue_watching">Continue Watching</string>
+ <string name="vod_classic_recently_added">Recently Added</string>
+ <string name="vod_classic_results_count">%1$d items</string>
+ <string name="vod_classic_empty_category">No titles found in this section.</string>
+ <string name="epg_no_schedule_short">No schedule</string>
+ <string name="epg_show_app_navigation">Show App Nav</string>
+ <string name="epg_program_details_show">Program Details</string>
+ <string name="epg_program_details_hide">Hide Details</string>
+ <string name="epg_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_short">Categories</string>
+ <string name="epg_search_short">Program Search</string>
+ <string name="epg_options_short">Options</string>
+ <string name="epg_schedule_summary_short">%1$d/%2$d with guide</string>
+ <string name="epg_stale_short">Guide may be stale</string>
+ <string name="settings_category_mode_protection">Lock / Unlock</string>
+ <string name="settings_category_mode_visibility">Hide / Unhide</string>
+ <string name="settings_category_protection_summary_title">Lock changes are reviewed before they go live</string>
+ <string name="settings_category_protection_summary_body">Toggle the categories you want to lock or unlock, then save. Saving requires your parental PIN.</string>
+ <string name="settings_category_protection_summary_body_no_pin">Toggle the categories you want to lock or unlock, then save. You will be asked to create a parental PIN before the changes are applied.</string>
+ <string name="settings_category_protection_save">Save Locks (%1$d)</string>
+ <string name="settings_category_protection_save_idle">Save Locks</string>
+ <string name="settings_category_protection_reset">Reset</string>
+ <string name="settings_category_visibility_summary_title">Visibility changes apply immediately</string>
+ <string name="settings_category_visibility_summary_body">%1$d categories are currently hidden for this playlist. Hiding and restoring does not require a PIN.</string>
+ <string name="settings_category_status_locked">Locked</string>
+ <string name="settings_category_status_unlocked">Unlocked</string>
+ <string name="settings_category_status_auto_locked">Auto-Locked</string>
+ <string name="settings_category_status_hidden">Hidden</string>
+ <string name="settings_category_controls_empty">No categories match this search.</string>
+ <string name="movie_loading_details">Loading details...</string>
+ <string name="movie_not_found">Movie not found</string>
+ <string name="movie_detail_back">Back to library</string>
+ <string name="movie_detail_play">Play</string>
+ <string name="movie_detail_trailer">Trailer</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>
+ <string name="movie_detail_duration">Duration:</string>
+ <string name="movie_detail_genre">Genre:</string>
+ <string name="movie_detail_cast">Cast:</string>
+ <string name="movie_detail_unknown">Unknown</string>
</resources>
diff --git a/app/src/main/res/values-da/strings.xml b/app/src/main/res/values-da/strings.xml
index b1683f8c..7a0c9c53 100644
--- a/app/src/main/res/values-da/strings.xml
+++ b/app/src/main/res/values-da/strings.xml
@@ -868,4 +868,89 @@
<string name="settings_history_cleared">Afspilningshistorik og seneste ryddet</string>
<string name="settings_pin_changed">PIN-koden blev gemt</string>
<string name="home_reorder_channels">Omarranger kanaler</string>
+ <!-- Synced fallback strings from English -->
+ <string name="category_options_hide">Hide Category</string>
+ <string name="settings_provider_category_controls_action">Category Controls</string>
+ <string name="settings_provider_category_controls_title">Category Controls</string>
+ <string name="settings_provider_category_controls_subtitle">Lock, unlock, hide, and restore categories for the current playlist from one place.</string>
+ <string name="settings_provider_category_controls_search">Search categories...</string>
+ <string name="settings_categories_title">Category Preferences</string>
+ <string name="settings_categories_subtitle">Hide provider categories and keep their sort order exactly how you want it.</string>
+ <string name="settings_category_sorting_title">Category Sorting</string>
+ <string name="settings_category_sorting_subtitle">Sort categories for the active playlist. Locking and hiding now live in Category Controls.</string>
+ <string name="settings_category_sort_live">Live TV Categories</string>
+ <string name="settings_category_sort_movies">Movie Categories</string>
+ <string name="settings_category_sort_series">Series Categories</string>
+ <string name="settings_hidden_categories_title">Hidden Categories</string>
+ <string name="settings_hidden_categories_subtitle">Restore any provider categories you previously hid from browsing surfaces.</string>
+ <string name="settings_hidden_categories_none">None hidden</string>
+ <string name="settings_hidden_categories_count">%1$d hidden</string>
+ <string name="settings_hidden_categories_empty">No hidden categories right now.</string>
+ <string name="settings_unhide_category">Unhide</string>
+ <string name="settings_hide_category">Hide</string>
+ <string name="settings_category_sort_default">Provider Order</string>
+ <string name="settings_category_sort_az">A-Z</string>
+ <string name="settings_category_sort_za">Z-A</string>
+ <string name="settings_category_sort_most_items">Most Items First</string>
+ <string name="settings_category_sort_least_items">Least Items First</string>
+ <string name="settings_category_type_live_description">Sort and hide provider live groups while keeping All Channels, Favorites, Recent, and custom groups in their pinned positions.</string>
+ <string name="settings_category_type_movies_description">Sort and hide provider movie categories without affecting Favorites, Resume, or custom shelves.</string>
+ <string name="settings_category_type_series_description">Sort and hide provider series categories without affecting Favorites, Continue Watching, or custom shelves.</string>
+ <string name="settings_live_channel_numbering_mode">Live TV Channel Numbering</string>
+ <string name="settings_live_channel_numbering_mode_subtitle">Choose whether live channels use their position in the current group or keep the original numbers from the provider.</string>
+ <string name="settings_live_channel_numbering_group">Per Group</string>
+ <string name="settings_live_channel_numbering_group_desc">Default behavior. Renumber channels based on their position inside the current category or custom group.</string>
+ <string name="settings_live_channel_numbering_provider">Provider Number</string>
+ <string name="settings_live_channel_numbering_provider_desc">Keep the original channel number supplied by the playlist provider whenever it exists.</string>
+ <string name="settings_vod_view_mode">VOD layout</string>
+ <string name="settings_vod_view_mode_subtitle">Choose between the modern shelves view and a classic split layout.</string>
+ <string name="settings_vod_view_mode_modern">Modern</string>
+ <string name="settings_vod_view_mode_modern_desc">Shelf-based browsing with featured rows and category previews.</string>
+ <string name="settings_vod_view_mode_classic">Classic</string>
+ <string name="settings_vod_view_mode_classic_desc">Category list on the left with a stacked poster grid on the right.</string>
+ <string name="vod_classic_categories_title">Categories</string>
+ <string name="vod_classic_category_search">Search in categories</string>
+ <string name="vod_classic_all">All</string>
+ <string name="vod_classic_continue_watching">Continue Watching</string>
+ <string name="vod_classic_recently_added">Recently Added</string>
+ <string name="vod_classic_results_count">%1$d items</string>
+ <string name="vod_classic_empty_category">No titles found in this section.</string>
+ <string name="epg_no_schedule_short">No schedule</string>
+ <string name="epg_show_app_navigation">Show App Nav</string>
+ <string name="epg_program_details_show">Program Details</string>
+ <string name="epg_program_details_hide">Hide Details</string>
+ <string name="epg_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_short">Categories</string>
+ <string name="epg_search_short">Program Search</string>
+ <string name="epg_options_short">Options</string>
+ <string name="epg_schedule_summary_short">%1$d/%2$d with guide</string>
+ <string name="epg_stale_short">Guide may be stale</string>
+ <string name="settings_category_mode_protection">Lock / Unlock</string>
+ <string name="settings_category_mode_visibility">Hide / Unhide</string>
+ <string name="settings_category_protection_summary_title">Lock changes are reviewed before they go live</string>
+ <string name="settings_category_protection_summary_body">Toggle the categories you want to lock or unlock, then save. Saving requires your parental PIN.</string>
+ <string name="settings_category_protection_summary_body_no_pin">Toggle the categories you want to lock or unlock, then save. You will be asked to create a parental PIN before the changes are applied.</string>
+ <string name="settings_category_protection_save">Save Locks (%1$d)</string>
+ <string name="settings_category_protection_save_idle">Save Locks</string>
+ <string name="settings_category_protection_reset">Reset</string>
+ <string name="settings_category_visibility_summary_title">Visibility changes apply immediately</string>
+ <string name="settings_category_visibility_summary_body">%1$d categories are currently hidden for this playlist. Hiding and restoring does not require a PIN.</string>
+ <string name="settings_category_status_locked">Locked</string>
+ <string name="settings_category_status_unlocked">Unlocked</string>
+ <string name="settings_category_status_auto_locked">Auto-Locked</string>
+ <string name="settings_category_status_hidden">Hidden</string>
+ <string name="settings_category_controls_empty">No categories match this search.</string>
+ <string name="movie_loading_details">Loading details...</string>
+ <string name="movie_not_found">Movie not found</string>
+ <string name="movie_detail_back">Back to library</string>
+ <string name="movie_detail_play">Play</string>
+ <string name="movie_detail_trailer">Trailer</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>
+ <string name="movie_detail_duration">Duration:</string>
+ <string name="movie_detail_genre">Genre:</string>
+ <string name="movie_detail_cast">Cast:</string>
+ <string name="movie_detail_unknown">Unknown</string>
</resources>
diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml
index b3db9f68..9bc4bad0 100644
--- a/app/src/main/res/values-de/strings.xml
+++ b/app/src/main/res/values-de/strings.xml
@@ -868,4 +868,89 @@
<string name="settings_history_cleared">Der Verlauf und die neuesten Wiedergaben wurden gelöscht</string>
<string name="settings_pin_changed">PIN erfolgreich gespeichert</string>
<string name="home_reorder_channels">Kanäle neu anordnen</string>
+ <!-- Synced fallback strings from English -->
+ <string name="category_options_hide">Hide Category</string>
+ <string name="settings_provider_category_controls_action">Category Controls</string>
+ <string name="settings_provider_category_controls_title">Category Controls</string>
+ <string name="settings_provider_category_controls_subtitle">Lock, unlock, hide, and restore categories for the current playlist from one place.</string>
+ <string name="settings_provider_category_controls_search">Search categories...</string>
+ <string name="settings_categories_title">Category Preferences</string>
+ <string name="settings_categories_subtitle">Hide provider categories and keep their sort order exactly how you want it.</string>
+ <string name="settings_category_sorting_title">Category Sorting</string>
+ <string name="settings_category_sorting_subtitle">Sort categories for the active playlist. Locking and hiding now live in Category Controls.</string>
+ <string name="settings_category_sort_live">Live TV Categories</string>
+ <string name="settings_category_sort_movies">Movie Categories</string>
+ <string name="settings_category_sort_series">Series Categories</string>
+ <string name="settings_hidden_categories_title">Hidden Categories</string>
+ <string name="settings_hidden_categories_subtitle">Restore any provider categories you previously hid from browsing surfaces.</string>
+ <string name="settings_hidden_categories_none">None hidden</string>
+ <string name="settings_hidden_categories_count">%1$d hidden</string>
+ <string name="settings_hidden_categories_empty">No hidden categories right now.</string>
+ <string name="settings_unhide_category">Unhide</string>
+ <string name="settings_hide_category">Hide</string>
+ <string name="settings_category_sort_default">Provider Order</string>
+ <string name="settings_category_sort_az">A-Z</string>
+ <string name="settings_category_sort_za">Z-A</string>
+ <string name="settings_category_sort_most_items">Most Items First</string>
+ <string name="settings_category_sort_least_items">Least Items First</string>
+ <string name="settings_category_type_live_description">Sort and hide provider live groups while keeping All Channels, Favorites, Recent, and custom groups in their pinned positions.</string>
+ <string name="settings_category_type_movies_description">Sort and hide provider movie categories without affecting Favorites, Resume, or custom shelves.</string>
+ <string name="settings_category_type_series_description">Sort and hide provider series categories without affecting Favorites, Continue Watching, or custom shelves.</string>
+ <string name="settings_live_channel_numbering_mode">Live TV Channel Numbering</string>
+ <string name="settings_live_channel_numbering_mode_subtitle">Choose whether live channels use their position in the current group or keep the original numbers from the provider.</string>
+ <string name="settings_live_channel_numbering_group">Per Group</string>
+ <string name="settings_live_channel_numbering_group_desc">Default behavior. Renumber channels based on their position inside the current category or custom group.</string>
+ <string name="settings_live_channel_numbering_provider">Provider Number</string>
+ <string name="settings_live_channel_numbering_provider_desc">Keep the original channel number supplied by the playlist provider whenever it exists.</string>
+ <string name="settings_vod_view_mode">VOD layout</string>
+ <string name="settings_vod_view_mode_subtitle">Choose between the modern shelves view and a classic split layout.</string>
+ <string name="settings_vod_view_mode_modern">Modern</string>
+ <string name="settings_vod_view_mode_modern_desc">Shelf-based browsing with featured rows and category previews.</string>
+ <string name="settings_vod_view_mode_classic">Classic</string>
+ <string name="settings_vod_view_mode_classic_desc">Category list on the left with a stacked poster grid on the right.</string>
+ <string name="vod_classic_categories_title">Categories</string>
+ <string name="vod_classic_category_search">Search in categories</string>
+ <string name="vod_classic_all">All</string>
+ <string name="vod_classic_continue_watching">Continue Watching</string>
+ <string name="vod_classic_recently_added">Recently Added</string>
+ <string name="vod_classic_results_count">%1$d items</string>
+ <string name="vod_classic_empty_category">No titles found in this section.</string>
+ <string name="epg_no_schedule_short">No schedule</string>
+ <string name="epg_show_app_navigation">Show App Nav</string>
+ <string name="epg_program_details_show">Program Details</string>
+ <string name="epg_program_details_hide">Hide Details</string>
+ <string name="epg_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_short">Categories</string>
+ <string name="epg_search_short">Program Search</string>
+ <string name="epg_options_short">Options</string>
+ <string name="epg_schedule_summary_short">%1$d/%2$d with guide</string>
+ <string name="epg_stale_short">Guide may be stale</string>
+ <string name="settings_category_mode_protection">Lock / Unlock</string>
+ <string name="settings_category_mode_visibility">Hide / Unhide</string>
+ <string name="settings_category_protection_summary_title">Lock changes are reviewed before they go live</string>
+ <string name="settings_category_protection_summary_body">Toggle the categories you want to lock or unlock, then save. Saving requires your parental PIN.</string>
+ <string name="settings_category_protection_summary_body_no_pin">Toggle the categories you want to lock or unlock, then save. You will be asked to create a parental PIN before the changes are applied.</string>
+ <string name="settings_category_protection_save">Save Locks (%1$d)</string>
+ <string name="settings_category_protection_save_idle">Save Locks</string>
+ <string name="settings_category_protection_reset">Reset</string>
+ <string name="settings_category_visibility_summary_title">Visibility changes apply immediately</string>
+ <string name="settings_category_visibility_summary_body">%1$d categories are currently hidden for this playlist. Hiding and restoring does not require a PIN.</string>
+ <string name="settings_category_status_locked">Locked</string>
+ <string name="settings_category_status_unlocked">Unlocked</string>
+ <string name="settings_category_status_auto_locked">Auto-Locked</string>
+ <string name="settings_category_status_hidden">Hidden</string>
+ <string name="settings_category_controls_empty">No categories match this search.</string>
+ <string name="movie_loading_details">Loading details...</string>
+ <string name="movie_not_found">Movie not found</string>
+ <string name="movie_detail_back">Back to library</string>
+ <string name="movie_detail_play">Play</string>
+ <string name="movie_detail_trailer">Trailer</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>
+ <string name="movie_detail_duration">Duration:</string>
+ <string name="movie_detail_genre">Genre:</string>
+ <string name="movie_detail_cast">Cast:</string>
+ <string name="movie_detail_unknown">Unknown</string>
</resources>
diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml
index 06be2e3b..9225969e 100644
--- a/app/src/main/res/values-el/strings.xml
+++ b/app/src/main/res/values-el/strings.xml
@@ -868,4 +868,89 @@
<string name="settings_history_cleared">Το ιστορικό παρακολούθησης και τα πρόσφατα διαγράφηκαν</string>
<string name="settings_pin_changed">Το PIN αποθηκεύτηκε με επιτυχία</string>
<string name="home_reorder_channels">Αναδιάταξη καναλιών</string>
+ <!-- Synced fallback strings from English -->
+ <string name="category_options_hide">Hide Category</string>
+ <string name="settings_provider_category_controls_action">Category Controls</string>
+ <string name="settings_provider_category_controls_title">Category Controls</string>
+ <string name="settings_provider_category_controls_subtitle">Lock, unlock, hide, and restore categories for the current playlist from one place.</string>
+ <string name="settings_provider_category_controls_search">Search categories...</string>
+ <string name="settings_categories_title">Category Preferences</string>
+ <string name="settings_categories_subtitle">Hide provider categories and keep their sort order exactly how you want it.</string>
+ <string name="settings_category_sorting_title">Category Sorting</string>
+ <string name="settings_category_sorting_subtitle">Sort categories for the active playlist. Locking and hiding now live in Category Controls.</string>
+ <string name="settings_category_sort_live">Live TV Categories</string>
+ <string name="settings_category_sort_movies">Movie Categories</string>
+ <string name="settings_category_sort_series">Series Categories</string>
+ <string name="settings_hidden_categories_title">Hidden Categories</string>
+ <string name="settings_hidden_categories_subtitle">Restore any provider categories you previously hid from browsing surfaces.</string>
+ <string name="settings_hidden_categories_none">None hidden</string>
+ <string name="settings_hidden_categories_count">%1$d hidden</string>
+ <string name="settings_hidden_categories_empty">No hidden categories right now.</string>
+ <string name="settings_unhide_category">Unhide</string>
+ <string name="settings_hide_category">Hide</string>
+ <string name="settings_category_sort_default">Provider Order</string>
+ <string name="settings_category_sort_az">A-Z</string>
+ <string name="settings_category_sort_za">Z-A</string>
+ <string name="settings_category_sort_most_items">Most Items First</string>
+ <string name="settings_category_sort_least_items">Least Items First</string>
+ <string name="settings_category_type_live_description">Sort and hide provider live groups while keeping All Channels, Favorites, Recent, and custom groups in their pinned positions.</string>
+ <string name="settings_category_type_movies_description">Sort and hide provider movie categories without affecting Favorites, Resume, or custom shelves.</string>
+ <string name="settings_category_type_series_description">Sort and hide provider series categories without affecting Favorites, Continue Watching, or custom shelves.</string>
+ <string name="settings_live_channel_numbering_mode">Live TV Channel Numbering</string>
+ <string name="settings_live_channel_numbering_mode_subtitle">Choose whether live channels use their position in the current group or keep the original numbers from the provider.</string>
+ <string name="settings_live_channel_numbering_group">Per Group</string>
+ <string name="settings_live_channel_numbering_group_desc">Default behavior. Renumber channels based on their position inside the current category or custom group.</string>
+ <string name="settings_live_channel_numbering_provider">Provider Number</string>
+ <string name="settings_live_channel_numbering_provider_desc">Keep the original channel number supplied by the playlist provider whenever it exists.</string>
+ <string name="settings_vod_view_mode">VOD layout</string>
+ <string name="settings_vod_view_mode_subtitle">Choose between the modern shelves view and a classic split layout.</string>
+ <string name="settings_vod_view_mode_modern">Modern</string>
+ <string name="settings_vod_view_mode_modern_desc">Shelf-based browsing with featured rows and category previews.</string>
+ <string name="settings_vod_view_mode_classic">Classic</string>
+ <string name="settings_vod_view_mode_classic_desc">Category list on the left with a stacked poster grid on the right.</string>
+ <string name="vod_classic_categories_title">Categories</string>
+ <string name="vod_classic_category_search">Search in categories</string>
+ <string name="vod_classic_all">All</string>
+ <string name="vod_classic_continue_watching">Continue Watching</string>
+ <string name="vod_classic_recently_added">Recently Added</string>
+ <string name="vod_classic_results_count">%1$d items</string>
+ <string name="vod_classic_empty_category">No titles found in this section.</string>
+ <string name="epg_no_schedule_short">No schedule</string>
+ <string name="epg_show_app_navigation">Show App Nav</string>
+ <string name="epg_program_details_show">Program Details</string>
+ <string name="epg_program_details_hide">Hide Details</string>
+ <string name="epg_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_short">Categories</string>
+ <string name="epg_search_short">Program Search</string>
+ <string name="epg_options_short">Options</string>
+ <string name="epg_schedule_summary_short">%1$d/%2$d with guide</string>
+ <string name="epg_stale_short">Guide may be stale</string>
+ <string name="settings_category_mode_protection">Lock / Unlock</string>
+ <string name="settings_category_mode_visibility">Hide / Unhide</string>
+ <string name="settings_category_protection_summary_title">Lock changes are reviewed before they go live</string>
+ <string name="settings_category_protection_summary_body">Toggle the categories you want to lock or unlock, then save. Saving requires your parental PIN.</string>
+ <string name="settings_category_protection_summary_body_no_pin">Toggle the categories you want to lock or unlock, then save. You will be asked to create a parental PIN before the changes are applied.</string>
+ <string name="settings_category_protection_save">Save Locks (%1$d)</string>
+ <string name="settings_category_protection_save_idle">Save Locks</string>
+ <string name="settings_category_protection_reset">Reset</string>
+ <string name="settings_category_visibility_summary_title">Visibility changes apply immediately</string>
+ <string name="settings_category_visibility_summary_body">%1$d categories are currently hidden for this playlist. Hiding and restoring does not require a PIN.</string>
+ <string name="settings_category_status_locked">Locked</string>
+ <string name="settings_category_status_unlocked">Unlocked</string>
+ <string name="settings_category_status_auto_locked">Auto-Locked</string>
+ <string name="settings_category_status_hidden">Hidden</string>
+ <string name="settings_category_controls_empty">No categories match this search.</string>
+ <string name="movie_loading_details">Loading details...</string>
+ <string name="movie_not_found">Movie not found</string>
+ <string name="movie_detail_back">Back to library</string>
+ <string name="movie_detail_play">Play</string>
+ <string name="movie_detail_trailer">Trailer</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>
+ <string name="movie_detail_duration">Duration:</string>
+ <string name="movie_detail_genre">Genre:</string>
+ <string name="movie_detail_cast">Cast:</string>
+ <string name="movie_detail_unknown">Unknown</string>
</resources>
diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml
index 102d7c87..9c360965 100644
--- a/app/src/main/res/values-es/strings.xml
+++ b/app/src/main/res/values-es/strings.xml
@@ -868,4 +868,89 @@
<string name="settings_history_cleared">Historial de visualización y recientes borrados</string>
<string name="settings_pin_changed">PIN guardado correctamente</string>
<string name="home_reorder_channels">Reordenar canales</string>
+ <!-- Synced fallback strings from English -->
+ <string name="category_options_hide">Hide Category</string>
+ <string name="settings_provider_category_controls_action">Category Controls</string>
+ <string name="settings_provider_category_controls_title">Category Controls</string>
+ <string name="settings_provider_category_controls_subtitle">Lock, unlock, hide, and restore categories for the current playlist from one place.</string>
+ <string name="settings_provider_category_controls_search">Search categories...</string>
+ <string name="settings_categories_title">Category Preferences</string>
+ <string name="settings_categories_subtitle">Hide provider categories and keep their sort order exactly how you want it.</string>
+ <string name="settings_category_sorting_title">Category Sorting</string>
+ <string name="settings_category_sorting_subtitle">Sort categories for the active playlist. Locking and hiding now live in Category Controls.</string>
+ <string name="settings_category_sort_live">Live TV Categories</string>
+ <string name="settings_category_sort_movies">Movie Categories</string>
+ <string name="settings_category_sort_series">Series Categories</string>
+ <string name="settings_hidden_categories_title">Hidden Categories</string>
+ <string name="settings_hidden_categories_subtitle">Restore any provider categories you previously hid from browsing surfaces.</string>
+ <string name="settings_hidden_categories_none">None hidden</string>
+ <string name="settings_hidden_categories_count">%1$d hidden</string>
+ <string name="settings_hidden_categories_empty">No hidden categories right now.</string>
+ <string name="settings_unhide_category">Unhide</string>
+ <string name="settings_hide_category">Hide</string>
+ <string name="settings_category_sort_default">Provider Order</string>
+ <string name="settings_category_sort_az">A-Z</string>
+ <string name="settings_category_sort_za">Z-A</string>
+ <string name="settings_category_sort_most_items">Most Items First</string>
+ <string name="settings_category_sort_least_items">Least Items First</string>
+ <string name="settings_category_type_live_description">Sort and hide provider live groups while keeping All Channels, Favorites, Recent, and custom groups in their pinned positions.</string>
+ <string name="settings_category_type_movies_description">Sort and hide provider movie categories without affecting Favorites, Resume, or custom shelves.</string>
+ <string name="settings_category_type_series_description">Sort and hide provider series categories without affecting Favorites, Continue Watching, or custom shelves.</string>
+ <string name="settings_live_channel_numbering_mode">Live TV Channel Numbering</string>
+ <string name="settings_live_channel_numbering_mode_subtitle">Choose whether live channels use their position in the current group or keep the original numbers from the provider.</string>
+ <string name="settings_live_channel_numbering_group">Per Group</string>
+ <string name="settings_live_channel_numbering_group_desc">Default behavior. Renumber channels based on their position inside the current category or custom group.</string>
+ <string name="settings_live_channel_numbering_provider">Provider Number</string>
+ <string name="settings_live_channel_numbering_provider_desc">Keep the original channel number supplied by the playlist provider whenever it exists.</string>
+ <string name="settings_vod_view_mode">VOD layout</string>
+ <string name="settings_vod_view_mode_subtitle">Choose between the modern shelves view and a classic split layout.</string>
+ <string name="settings_vod_view_mode_modern">Modern</string>
+ <string name="settings_vod_view_mode_modern_desc">Shelf-based browsing with featured rows and category previews.</string>
+ <string name="settings_vod_view_mode_classic">Classic</string>
+ <string name="settings_vod_view_mode_classic_desc">Category list on the left with a stacked poster grid on the right.</string>
+ <string name="vod_classic_categories_title">Categories</string>
+ <string name="vod_classic_category_search">Search in categories</string>
+ <string name="vod_classic_all">All</string>
+ <string name="vod_classic_continue_watching">Continue Watching</string>
+ <string name="vod_classic_recently_added">Recently Added</string>
+ <string name="vod_classic_results_count">%1$d items</string>
+ <string name="vod_classic_empty_category">No titles found in this section.</string>
+ <string name="epg_no_schedule_short">No schedule</string>
+ <string name="epg_show_app_navigation">Show App Nav</string>
+ <string name="epg_program_details_show">Program Details</string>
+ <string name="epg_program_details_hide">Hide Details</string>
+ <string name="epg_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_short">Categories</string>
+ <string name="epg_search_short">Program Search</string>
+ <string name="epg_options_short">Options</string>
+ <string name="epg_schedule_summary_short">%1$d/%2$d with guide</string>
+ <string name="epg_stale_short">Guide may be stale</string>
+ <string name="settings_category_mode_protection">Lock / Unlock</string>
+ <string name="settings_category_mode_visibility">Hide / Unhide</string>
+ <string name="settings_category_protection_summary_title">Lock changes are reviewed before they go live</string>
+ <string name="settings_category_protection_summary_body">Toggle the categories you want to lock or unlock, then save. Saving requires your parental PIN.</string>
+ <string name="settings_category_protection_summary_body_no_pin">Toggle the categories you want to lock or unlock, then save. You will be asked to create a parental PIN before the changes are applied.</string>
+ <string name="settings_category_protection_save">Save Locks (%1$d)</string>
+ <string name="settings_category_protection_save_idle">Save Locks</string>
+ <string name="settings_category_protection_reset">Reset</string>
+ <string name="settings_category_visibility_summary_title">Visibility changes apply immediately</string>
+ <string name="settings_category_visibility_summary_body">%1$d categories are currently hidden for this playlist. Hiding and restoring does not require a PIN.</string>
+ <string name="settings_category_status_locked">Locked</string>
+ <string name="settings_category_status_unlocked">Unlocked</string>
+ <string name="settings_category_status_auto_locked">Auto-Locked</string>
+ <string name="settings_category_status_hidden">Hidden</string>
+ <string name="settings_category_controls_empty">No categories match this search.</string>
+ <string name="movie_loading_details">Loading details...</string>
+ <string name="movie_not_found">Movie not found</string>
+ <string name="movie_detail_back">Back to library</string>
+ <string name="movie_detail_play">Play</string>
+ <string name="movie_detail_trailer">Trailer</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>
+ <string name="movie_detail_duration">Duration:</string>
+ <string name="movie_detail_genre">Genre:</string>
+ <string name="movie_detail_cast">Cast:</string>
+ <string name="movie_detail_unknown">Unknown</string>
</resources>
diff --git a/app/src/main/res/values-fi/strings.xml b/app/src/main/res/values-fi/strings.xml
index 4c538056..fc8c105c 100644
--- a/app/src/main/res/values-fi/strings.xml
+++ b/app/src/main/res/values-fi/strings.xml
@@ -868,4 +868,89 @@
<string name="settings_history_cleared">Katseluhistoria ja viimeaikaiset tapahtumat tyhjennetty</string>
<string name="settings_pin_changed">PIN-koodi tallennettu onnistuneesti</string>
<string name="home_reorder_channels">Järjestä kanavat uudelleen</string>
+ <!-- Synced fallback strings from English -->
+ <string name="category_options_hide">Hide Category</string>
+ <string name="settings_provider_category_controls_action">Category Controls</string>
+ <string name="settings_provider_category_controls_title">Category Controls</string>
+ <string name="settings_provider_category_controls_subtitle">Lock, unlock, hide, and restore categories for the current playlist from one place.</string>
+ <string name="settings_provider_category_controls_search">Search categories...</string>
+ <string name="settings_categories_title">Category Preferences</string>
+ <string name="settings_categories_subtitle">Hide provider categories and keep their sort order exactly how you want it.</string>
+ <string name="settings_category_sorting_title">Category Sorting</string>
+ <string name="settings_category_sorting_subtitle">Sort categories for the active playlist. Locking and hiding now live in Category Controls.</string>
+ <string name="settings_category_sort_live">Live TV Categories</string>
+ <string name="settings_category_sort_movies">Movie Categories</string>
+ <string name="settings_category_sort_series">Series Categories</string>
+ <string name="settings_hidden_categories_title">Hidden Categories</string>
+ <string name="settings_hidden_categories_subtitle">Restore any provider categories you previously hid from browsing surfaces.</string>
+ <string name="settings_hidden_categories_none">None hidden</string>
+ <string name="settings_hidden_categories_count">%1$d hidden</string>
+ <string name="settings_hidden_categories_empty">No hidden categories right now.</string>
+ <string name="settings_unhide_category">Unhide</string>
+ <string name="settings_hide_category">Hide</string>
+ <string name="settings_category_sort_default">Provider Order</string>
+ <string name="settings_category_sort_az">A-Z</string>
+ <string name="settings_category_sort_za">Z-A</string>
+ <string name="settings_category_sort_most_items">Most Items First</string>
+ <string name="settings_category_sort_least_items">Least Items First</string>
+ <string name="settings_category_type_live_description">Sort and hide provider live groups while keeping All Channels, Favorites, Recent, and custom groups in their pinned positions.</string>
+ <string name="settings_category_type_movies_description">Sort and hide provider movie categories without affecting Favorites, Resume, or custom shelves.</string>
+ <string name="settings_category_type_series_description">Sort and hide provider series categories without affecting Favorites, Continue Watching, or custom shelves.</string>
+ <string name="settings_live_channel_numbering_mode">Live TV Channel Numbering</string>
+ <string name="settings_live_channel_numbering_mode_subtitle">Choose whether live channels use their position in the current group or keep the original numbers from the provider.</string>
+ <string name="settings_live_channel_numbering_group">Per Group</string>
+ <string name="settings_live_channel_numbering_group_desc">Default behavior. Renumber channels based on their position inside the current category or custom group.</string>
+ <string name="settings_live_channel_numbering_provider">Provider Number</string>
+ <string name="settings_live_channel_numbering_provider_desc">Keep the original channel number supplied by the playlist provider whenever it exists.</string>
+ <string name="settings_vod_view_mode">VOD layout</string>
+ <string name="settings_vod_view_mode_subtitle">Choose between the modern shelves view and a classic split layout.</string>
+ <string name="settings_vod_view_mode_modern">Modern</string>
+ <string name="settings_vod_view_mode_modern_desc">Shelf-based browsing with featured rows and category previews.</string>
+ <string name="settings_vod_view_mode_classic">Classic</string>
+ <string name="settings_vod_view_mode_classic_desc">Category list on the left with a stacked poster grid on the right.</string>
+ <string name="vod_classic_categories_title">Categories</string>
+ <string name="vod_classic_category_search">Search in categories</string>
+ <string name="vod_classic_all">All</string>
+ <string name="vod_classic_continue_watching">Continue Watching</string>
+ <string name="vod_classic_recently_added">Recently Added</string>
+ <string name="vod_classic_results_count">%1$d items</string>
+ <string name="vod_classic_empty_category">No titles found in this section.</string>
+ <string name="epg_no_schedule_short">No schedule</string>
+ <string name="epg_show_app_navigation">Show App Nav</string>
+ <string name="epg_program_details_show">Program Details</string>
+ <string name="epg_program_details_hide">Hide Details</string>
+ <string name="epg_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_short">Categories</string>
+ <string name="epg_search_short">Program Search</string>
+ <string name="epg_options_short">Options</string>
+ <string name="epg_schedule_summary_short">%1$d/%2$d with guide</string>
+ <string name="epg_stale_short">Guide may be stale</string>
+ <string name="settings_category_mode_protection">Lock / Unlock</string>
+ <string name="settings_category_mode_visibility">Hide / Unhide</string>
+ <string name="settings_category_protection_summary_title">Lock changes are reviewed before they go live</string>
+ <string name="settings_category_protection_summary_body">Toggle the categories you want to lock or unlock, then save. Saving requires your parental PIN.</string>
+ <string name="settings_category_protection_summary_body_no_pin">Toggle the categories you want to lock or unlock, then save. You will be asked to create a parental PIN before the changes are applied.</string>
+ <string name="settings_category_protection_save">Save Locks (%1$d)</string>
+ <string name="settings_category_protection_save_idle">Save Locks</string>
+ <string name="settings_category_protection_reset">Reset</string>
+ <string name="settings_category_visibility_summary_title">Visibility changes apply immediately</string>
+ <string name="settings_category_visibility_summary_body">%1$d categories are currently hidden for this playlist. Hiding and restoring does not require a PIN.</string>
+ <string name="settings_category_status_locked">Locked</string>
+ <string name="settings_category_status_unlocked">Unlocked</string>
+ <string name="settings_category_status_auto_locked">Auto-Locked</string>
+ <string name="settings_category_status_hidden">Hidden</string>
+ <string name="settings_category_controls_empty">No categories match this search.</string>
+ <string name="movie_loading_details">Loading details...</string>
+ <string name="movie_not_found">Movie not found</string>
+ <string name="movie_detail_back">Back to library</string>
+ <string name="movie_detail_play">Play</string>
+ <string name="movie_detail_trailer">Trailer</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>
+ <string name="movie_detail_duration">Duration:</string>
+ <string name="movie_detail_genre">Genre:</string>
+ <string name="movie_detail_cast">Cast:</string>
+ <string name="movie_detail_unknown">Unknown</string>
</resources>
diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml
index c3cbd636..5e8e4051 100644
--- a/app/src/main/res/values-fr/strings.xml
+++ b/app/src/main/res/values-fr/strings.xml
@@ -868,4 +868,89 @@
<string name="settings_history_cleared">Regarder l\'historique et les événements récents effacés</string>
<string name="settings_pin_changed">Code PIN enregistré avec succès</string>
<string name="home_reorder_channels">Réorganiser les chaînes</string>
+ <!-- Synced fallback strings from English -->
+ <string name="category_options_hide">Hide Category</string>
+ <string name="settings_provider_category_controls_action">Category Controls</string>
+ <string name="settings_provider_category_controls_title">Category Controls</string>
+ <string name="settings_provider_category_controls_subtitle">Lock, unlock, hide, and restore categories for the current playlist from one place.</string>
+ <string name="settings_provider_category_controls_search">Search categories...</string>
+ <string name="settings_categories_title">Category Preferences</string>
+ <string name="settings_categories_subtitle">Hide provider categories and keep their sort order exactly how you want it.</string>
+ <string name="settings_category_sorting_title">Category Sorting</string>
+ <string name="settings_category_sorting_subtitle">Sort categories for the active playlist. Locking and hiding now live in Category Controls.</string>
+ <string name="settings_category_sort_live">Live TV Categories</string>
+ <string name="settings_category_sort_movies">Movie Categories</string>
+ <string name="settings_category_sort_series">Series Categories</string>
+ <string name="settings_hidden_categories_title">Hidden Categories</string>
+ <string name="settings_hidden_categories_subtitle">Restore any provider categories you previously hid from browsing surfaces.</string>
+ <string name="settings_hidden_categories_none">None hidden</string>
+ <string name="settings_hidden_categories_count">%1$d hidden</string>
+ <string name="settings_hidden_categories_empty">No hidden categories right now.</string>
+ <string name="settings_unhide_category">Unhide</string>
+ <string name="settings_hide_category">Hide</string>
+ <string name="settings_category_sort_default">Provider Order</string>
+ <string name="settings_category_sort_az">A-Z</string>
+ <string name="settings_category_sort_za">Z-A</string>
+ <string name="settings_category_sort_most_items">Most Items First</string>
+ <string name="settings_category_sort_least_items">Least Items First</string>
+ <string name="settings_category_type_live_description">Sort and hide provider live groups while keeping All Channels, Favorites, Recent, and custom groups in their pinned positions.</string>
+ <string name="settings_category_type_movies_description">Sort and hide provider movie categories without affecting Favorites, Resume, or custom shelves.</string>
+ <string name="settings_category_type_series_description">Sort and hide provider series categories without affecting Favorites, Continue Watching, or custom shelves.</string>
+ <string name="settings_live_channel_numbering_mode">Live TV Channel Numbering</string>
+ <string name="settings_live_channel_numbering_mode_subtitle">Choose whether live channels use their position in the current group or keep the original numbers from the provider.</string>
+ <string name="settings_live_channel_numbering_group">Per Group</string>
+ <string name="settings_live_channel_numbering_group_desc">Default behavior. Renumber channels based on their position inside the current category or custom group.</string>
+ <string name="settings_live_channel_numbering_provider">Provider Number</string>
+ <string name="settings_live_channel_numbering_provider_desc">Keep the original channel number supplied by the playlist provider whenever it exists.</string>
+ <string name="settings_vod_view_mode">VOD layout</string>
+ <string name="settings_vod_view_mode_subtitle">Choose between the modern shelves view and a classic split layout.</string>
+ <string name="settings_vod_view_mode_modern">Modern</string>
+ <string name="settings_vod_view_mode_modern_desc">Shelf-based browsing with featured rows and category previews.</string>
+ <string name="settings_vod_view_mode_classic">Classic</string>
+ <string name="settings_vod_view_mode_classic_desc">Category list on the left with a stacked poster grid on the right.</string>
+ <string name="vod_classic_categories_title">Categories</string>
+ <string name="vod_classic_category_search">Search in categories</string>
+ <string name="vod_classic_all">All</string>
+ <string name="vod_classic_continue_watching">Continue Watching</string>
+ <string name="vod_classic_recently_added">Recently Added</string>
+ <string name="vod_classic_results_count">%1$d items</string>
+ <string name="vod_classic_empty_category">No titles found in this section.</string>
+ <string name="epg_no_schedule_short">No schedule</string>
+ <string name="epg_show_app_navigation">Show App Nav</string>
+ <string name="epg_program_details_show">Program Details</string>
+ <string name="epg_program_details_hide">Hide Details</string>
+ <string name="epg_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_short">Categories</string>
+ <string name="epg_search_short">Program Search</string>
+ <string name="epg_options_short">Options</string>
+ <string name="epg_schedule_summary_short">%1$d/%2$d with guide</string>
+ <string name="epg_stale_short">Guide may be stale</string>
+ <string name="settings_category_mode_protection">Lock / Unlock</string>
+ <string name="settings_category_mode_visibility">Hide / Unhide</string>
+ <string name="settings_category_protection_summary_title">Lock changes are reviewed before they go live</string>
+ <string name="settings_category_protection_summary_body">Toggle the categories you want to lock or unlock, then save. Saving requires your parental PIN.</string>
+ <string name="settings_category_protection_summary_body_no_pin">Toggle the categories you want to lock or unlock, then save. You will be asked to create a parental PIN before the changes are applied.</string>
+ <string name="settings_category_protection_save">Save Locks (%1$d)</string>
+ <string name="settings_category_protection_save_idle">Save Locks</string>
+ <string name="settings_category_protection_reset">Reset</string>
+ <string name="settings_category_visibility_summary_title">Visibility changes apply immediately</string>
+ <string name="settings_category_visibility_summary_body">%1$d categories are currently hidden for this playlist. Hiding and restoring does not require a PIN.</string>
+ <string name="settings_category_status_locked">Locked</string>
+ <string name="settings_category_status_unlocked">Unlocked</string>
+ <string name="settings_category_status_auto_locked">Auto-Locked</string>
+ <string name="settings_category_status_hidden">Hidden</string>
+ <string name="settings_category_controls_empty">No categories match this search.</string>
+ <string name="movie_loading_details">Loading details...</string>
+ <string name="movie_not_found">Movie not found</string>
+ <string name="movie_detail_back">Back to library</string>
+ <string name="movie_detail_play">Play</string>
+ <string name="movie_detail_trailer">Trailer</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>
+ <string name="movie_detail_duration">Duration:</string>
+ <string name="movie_detail_genre">Genre:</string>
+ <string name="movie_detail_cast">Cast:</string>
+ <string name="movie_detail_unknown">Unknown</string>
</resources>
diff --git a/app/src/main/res/values-hu/strings.xml b/app/src/main/res/values-hu/strings.xml
index b18e40da..e0670fb6 100644
--- a/app/src/main/res/values-hu/strings.xml
+++ b/app/src/main/res/values-hu/strings.xml
@@ -868,4 +868,89 @@
<string name="settings_history_cleared">A megtekintési előzmények és a legutóbbi idők törölve</string>
<string name="settings_pin_changed">A PIN-kód sikeresen elmentve</string>
<string name="home_reorder_channels">Csatornák átrendezése</string>
+ <!-- Synced fallback strings from English -->
+ <string name="category_options_hide">Hide Category</string>
+ <string name="settings_provider_category_controls_action">Category Controls</string>
+ <string name="settings_provider_category_controls_title">Category Controls</string>
+ <string name="settings_provider_category_controls_subtitle">Lock, unlock, hide, and restore categories for the current playlist from one place.</string>
+ <string name="settings_provider_category_controls_search">Search categories...</string>
+ <string name="settings_categories_title">Category Preferences</string>
+ <string name="settings_categories_subtitle">Hide provider categories and keep their sort order exactly how you want it.</string>
+ <string name="settings_category_sorting_title">Category Sorting</string>
+ <string name="settings_category_sorting_subtitle">Sort categories for the active playlist. Locking and hiding now live in Category Controls.</string>
+ <string name="settings_category_sort_live">Live TV Categories</string>
+ <string name="settings_category_sort_movies">Movie Categories</string>
+ <string name="settings_category_sort_series">Series Categories</string>
+ <string name="settings_hidden_categories_title">Hidden Categories</string>
+ <string name="settings_hidden_categories_subtitle">Restore any provider categories you previously hid from browsing surfaces.</string>
+ <string name="settings_hidden_categories_none">None hidden</string>
+ <string name="settings_hidden_categories_count">%1$d hidden</string>
+ <string name="settings_hidden_categories_empty">No hidden categories right now.</string>
+ <string name="settings_unhide_category">Unhide</string>
+ <string name="settings_hide_category">Hide</string>
+ <string name="settings_category_sort_default">Provider Order</string>
+ <string name="settings_category_sort_az">A-Z</string>
+ <string name="settings_category_sort_za">Z-A</string>
+ <string name="settings_category_sort_most_items">Most Items First</string>
+ <string name="settings_category_sort_least_items">Least Items First</string>
+ <string name="settings_category_type_live_description">Sort and hide provider live groups while keeping All Channels, Favorites, Recent, and custom groups in their pinned positions.</string>
+ <string name="settings_category_type_movies_description">Sort and hide provider movie categories without affecting Favorites, Resume, or custom shelves.</string>
+ <string name="settings_category_type_series_description">Sort and hide provider series categories without affecting Favorites, Continue Watching, or custom shelves.</string>
+ <string name="settings_live_channel_numbering_mode">Live TV Channel Numbering</string>
+ <string name="settings_live_channel_numbering_mode_subtitle">Choose whether live channels use their position in the current group or keep the original numbers from the provider.</string>
+ <string name="settings_live_channel_numbering_group">Per Group</string>
+ <string name="settings_live_channel_numbering_group_desc">Default behavior. Renumber channels based on their position inside the current category or custom group.</string>
+ <string name="settings_live_channel_numbering_provider">Provider Number</string>
+ <string name="settings_live_channel_numbering_provider_desc">Keep the original channel number supplied by the playlist provider whenever it exists.</string>
+ <string name="settings_vod_view_mode">VOD layout</string>
+ <string name="settings_vod_view_mode_subtitle">Choose between the modern shelves view and a classic split layout.</string>
+ <string name="settings_vod_view_mode_modern">Modern</string>
+ <string name="settings_vod_view_mode_modern_desc">Shelf-based browsing with featured rows and category previews.</string>
+ <string name="settings_vod_view_mode_classic">Classic</string>
+ <string name="settings_vod_view_mode_classic_desc">Category list on the left with a stacked poster grid on the right.</string>
+ <string name="vod_classic_categories_title">Categories</string>
+ <string name="vod_classic_category_search">Search in categories</string>
+ <string name="vod_classic_all">All</string>
+ <string name="vod_classic_continue_watching">Continue Watching</string>
+ <string name="vod_classic_recently_added">Recently Added</string>
+ <string name="vod_classic_results_count">%1$d items</string>
+ <string name="vod_classic_empty_category">No titles found in this section.</string>
+ <string name="epg_no_schedule_short">No schedule</string>
+ <string name="epg_show_app_navigation">Show App Nav</string>
+ <string name="epg_program_details_show">Program Details</string>
+ <string name="epg_program_details_hide">Hide Details</string>
+ <string name="epg_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_short">Categories</string>
+ <string name="epg_search_short">Program Search</string>
+ <string name="epg_options_short">Options</string>
+ <string name="epg_schedule_summary_short">%1$d/%2$d with guide</string>
+ <string name="epg_stale_short">Guide may be stale</string>
+ <string name="settings_category_mode_protection">Lock / Unlock</string>
+ <string name="settings_category_mode_visibility">Hide / Unhide</string>
+ <string name="settings_category_protection_summary_title">Lock changes are reviewed before they go live</string>
+ <string name="settings_category_protection_summary_body">Toggle the categories you want to lock or unlock, then save. Saving requires your parental PIN.</string>
+ <string name="settings_category_protection_summary_body_no_pin">Toggle the categories you want to lock or unlock, then save. You will be asked to create a parental PIN before the changes are applied.</string>
+ <string name="settings_category_protection_save">Save Locks (%1$d)</string>
+ <string name="settings_category_protection_save_idle">Save Locks</string>
+ <string name="settings_category_protection_reset">Reset</string>
+ <string name="settings_category_visibility_summary_title">Visibility changes apply immediately</string>
+ <string name="settings_category_visibility_summary_body">%1$d categories are currently hidden for this playlist. Hiding and restoring does not require a PIN.</string>
+ <string name="settings_category_status_locked">Locked</string>
+ <string name="settings_category_status_unlocked">Unlocked</string>
+ <string name="settings_category_status_auto_locked">Auto-Locked</string>
+ <string name="settings_category_status_hidden">Hidden</string>
+ <string name="settings_category_controls_empty">No categories match this search.</string>
+ <string name="movie_loading_details">Loading details...</string>
+ <string name="movie_not_found">Movie not found</string>
+ <string name="movie_detail_back">Back to library</string>
+ <string name="movie_detail_play">Play</string>
+ <string name="movie_detail_trailer">Trailer</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>
+ <string name="movie_detail_duration">Duration:</string>
+ <string name="movie_detail_genre">Genre:</string>
+ <string name="movie_detail_cast">Cast:</string>
+ <string name="movie_detail_unknown">Unknown</string>
</resources>
diff --git a/app/src/main/res/values-in/strings.xml b/app/src/main/res/values-in/strings.xml
index d38f8db9..e0eaa0e2 100644
--- a/app/src/main/res/values-in/strings.xml
+++ b/app/src/main/res/values-in/strings.xml
@@ -868,4 +868,89 @@
<string name="settings_history_cleared">Riwayat tontonan dan terkini dihapus</string>
<string name="settings_pin_changed">PIN berhasil disimpan</string>
<string name="home_reorder_channels">Susun Ulang Saluran</string>
+ <!-- Synced fallback strings from English -->
+ <string name="category_options_hide">Hide Category</string>
+ <string name="settings_provider_category_controls_action">Category Controls</string>
+ <string name="settings_provider_category_controls_title">Category Controls</string>
+ <string name="settings_provider_category_controls_subtitle">Lock, unlock, hide, and restore categories for the current playlist from one place.</string>
+ <string name="settings_provider_category_controls_search">Search categories...</string>
+ <string name="settings_categories_title">Category Preferences</string>
+ <string name="settings_categories_subtitle">Hide provider categories and keep their sort order exactly how you want it.</string>
+ <string name="settings_category_sorting_title">Category Sorting</string>
+ <string name="settings_category_sorting_subtitle">Sort categories for the active playlist. Locking and hiding now live in Category Controls.</string>
+ <string name="settings_category_sort_live">Live TV Categories</string>
+ <string name="settings_category_sort_movies">Movie Categories</string>
+ <string name="settings_category_sort_series">Series Categories</string>
+ <string name="settings_hidden_categories_title">Hidden Categories</string>
+ <string name="settings_hidden_categories_subtitle">Restore any provider categories you previously hid from browsing surfaces.</string>
+ <string name="settings_hidden_categories_none">None hidden</string>
+ <string name="settings_hidden_categories_count">%1$d hidden</string>
+ <string name="settings_hidden_categories_empty">No hidden categories right now.</string>
+ <string name="settings_unhide_category">Unhide</string>
+ <string name="settings_hide_category">Hide</string>
+ <string name="settings_category_sort_default">Provider Order</string>
+ <string name="settings_category_sort_az">A-Z</string>
+ <string name="settings_category_sort_za">Z-A</string>
+ <string name="settings_category_sort_most_items">Most Items First</string>
+ <string name="settings_category_sort_least_items">Least Items First</string>
+ <string name="settings_category_type_live_description">Sort and hide provider live groups while keeping All Channels, Favorites, Recent, and custom groups in their pinned positions.</string>
+ <string name="settings_category_type_movies_description">Sort and hide provider movie categories without affecting Favorites, Resume, or custom shelves.</string>
+ <string name="settings_category_type_series_description">Sort and hide provider series categories without affecting Favorites, Continue Watching, or custom shelves.</string>
+ <string name="settings_live_channel_numbering_mode">Live TV Channel Numbering</string>
+ <string name="settings_live_channel_numbering_mode_subtitle">Choose whether live channels use their position in the current group or keep the original numbers from the provider.</string>
+ <string name="settings_live_channel_numbering_group">Per Group</string>
+ <string name="settings_live_channel_numbering_group_desc">Default behavior. Renumber channels based on their position inside the current category or custom group.</string>
+ <string name="settings_live_channel_numbering_provider">Provider Number</string>
+ <string name="settings_live_channel_numbering_provider_desc">Keep the original channel number supplied by the playlist provider whenever it exists.</string>
+ <string name="settings_vod_view_mode">VOD layout</string>
+ <string name="settings_vod_view_mode_subtitle">Choose between the modern shelves view and a classic split layout.</string>
+ <string name="settings_vod_view_mode_modern">Modern</string>
+ <string name="settings_vod_view_mode_modern_desc">Shelf-based browsing with featured rows and category previews.</string>
+ <string name="settings_vod_view_mode_classic">Classic</string>
+ <string name="settings_vod_view_mode_classic_desc">Category list on the left with a stacked poster grid on the right.</string>
+ <string name="vod_classic_categories_title">Categories</string>
+ <string name="vod_classic_category_search">Search in categories</string>
+ <string name="vod_classic_all">All</string>
+ <string name="vod_classic_continue_watching">Continue Watching</string>
+ <string name="vod_classic_recently_added">Recently Added</string>
+ <string name="vod_classic_results_count">%1$d items</string>
+ <string name="vod_classic_empty_category">No titles found in this section.</string>
+ <string name="epg_no_schedule_short">No schedule</string>
+ <string name="epg_show_app_navigation">Show App Nav</string>
+ <string name="epg_program_details_show">Program Details</string>
+ <string name="epg_program_details_hide">Hide Details</string>
+ <string name="epg_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_short">Categories</string>
+ <string name="epg_search_short">Program Search</string>
+ <string name="epg_options_short">Options</string>
+ <string name="epg_schedule_summary_short">%1$d/%2$d with guide</string>
+ <string name="epg_stale_short">Guide may be stale</string>
+ <string name="settings_category_mode_protection">Lock / Unlock</string>
+ <string name="settings_category_mode_visibility">Hide / Unhide</string>
+ <string name="settings_category_protection_summary_title">Lock changes are reviewed before they go live</string>
+ <string name="settings_category_protection_summary_body">Toggle the categories you want to lock or unlock, then save. Saving requires your parental PIN.</string>
+ <string name="settings_category_protection_summary_body_no_pin">Toggle the categories you want to lock or unlock, then save. You will be asked to create a parental PIN before the changes are applied.</string>
+ <string name="settings_category_protection_save">Save Locks (%1$d)</string>
+ <string name="settings_category_protection_save_idle">Save Locks</string>
+ <string name="settings_category_protection_reset">Reset</string>
+ <string name="settings_category_visibility_summary_title">Visibility changes apply immediately</string>
+ <string name="settings_category_visibility_summary_body">%1$d categories are currently hidden for this playlist. Hiding and restoring does not require a PIN.</string>
+ <string name="settings_category_status_locked">Locked</string>
+ <string name="settings_category_status_unlocked">Unlocked</string>
+ <string name="settings_category_status_auto_locked">Auto-Locked</string>
+ <string name="settings_category_status_hidden">Hidden</string>
+ <string name="settings_category_controls_empty">No categories match this search.</string>
+ <string name="movie_loading_details">Loading details...</string>
+ <string name="movie_not_found">Movie not found</string>
+ <string name="movie_detail_back">Back to library</string>
+ <string name="movie_detail_play">Play</string>
+ <string name="movie_detail_trailer">Trailer</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>
+ <string name="movie_detail_duration">Duration:</string>
+ <string name="movie_detail_genre">Genre:</string>
+ <string name="movie_detail_cast">Cast:</string>
+ <string name="movie_detail_unknown">Unknown</string>
</resources>
diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml
index 4029f583..d5997c0c 100644
--- a/app/src/main/res/values-it/strings.xml
+++ b/app/src/main/res/values-it/strings.xml
@@ -868,4 +868,89 @@
<string name="settings_history_cleared">Guarda la cronologia e i recenti cancellati</string>
<string name="settings_pin_changed">PIN salvato con successo</string>
<string name="home_reorder_channels">Riordina i canali</string>
+ <!-- Synced fallback strings from English -->
+ <string name="category_options_hide">Hide Category</string>
+ <string name="settings_provider_category_controls_action">Category Controls</string>
+ <string name="settings_provider_category_controls_title">Category Controls</string>
+ <string name="settings_provider_category_controls_subtitle">Lock, unlock, hide, and restore categories for the current playlist from one place.</string>
+ <string name="settings_provider_category_controls_search">Search categories...</string>
+ <string name="settings_categories_title">Category Preferences</string>
+ <string name="settings_categories_subtitle">Hide provider categories and keep their sort order exactly how you want it.</string>
+ <string name="settings_category_sorting_title">Category Sorting</string>
+ <string name="settings_category_sorting_subtitle">Sort categories for the active playlist. Locking and hiding now live in Category Controls.</string>
+ <string name="settings_category_sort_live">Live TV Categories</string>
+ <string name="settings_category_sort_movies">Movie Categories</string>
+ <string name="settings_category_sort_series">Series Categories</string>
+ <string name="settings_hidden_categories_title">Hidden Categories</string>
+ <string name="settings_hidden_categories_subtitle">Restore any provider categories you previously hid from browsing surfaces.</string>
+ <string name="settings_hidden_categories_none">None hidden</string>
+ <string name="settings_hidden_categories_count">%1$d hidden</string>
+ <string name="settings_hidden_categories_empty">No hidden categories right now.</string>
+ <string name="settings_unhide_category">Unhide</string>
+ <string name="settings_hide_category">Hide</string>
+ <string name="settings_category_sort_default">Provider Order</string>
+ <string name="settings_category_sort_az">A-Z</string>
+ <string name="settings_category_sort_za">Z-A</string>
+ <string name="settings_category_sort_most_items">Most Items First</string>
+ <string name="settings_category_sort_least_items">Least Items First</string>
+ <string name="settings_category_type_live_description">Sort and hide provider live groups while keeping All Channels, Favorites, Recent, and custom groups in their pinned positions.</string>
+ <string name="settings_category_type_movies_description">Sort and hide provider movie categories without affecting Favorites, Resume, or custom shelves.</string>
+ <string name="settings_category_type_series_description">Sort and hide provider series categories without affecting Favorites, Continue Watching, or custom shelves.</string>
+ <string name="settings_live_channel_numbering_mode">Live TV Channel Numbering</string>
+ <string name="settings_live_channel_numbering_mode_subtitle">Choose whether live channels use their position in the current group or keep the original numbers from the provider.</string>
+ <string name="settings_live_channel_numbering_group">Per Group</string>
+ <string name="settings_live_channel_numbering_group_desc">Default behavior. Renumber channels based on their position inside the current category or custom group.</string>
+ <string name="settings_live_channel_numbering_provider">Provider Number</string>
+ <string name="settings_live_channel_numbering_provider_desc">Keep the original channel number supplied by the playlist provider whenever it exists.</string>
+ <string name="settings_vod_view_mode">VOD layout</string>
+ <string name="settings_vod_view_mode_subtitle">Choose between the modern shelves view and a classic split layout.</string>
+ <string name="settings_vod_view_mode_modern">Modern</string>
+ <string name="settings_vod_view_mode_modern_desc">Shelf-based browsing with featured rows and category previews.</string>
+ <string name="settings_vod_view_mode_classic">Classic</string>
+ <string name="settings_vod_view_mode_classic_desc">Category list on the left with a stacked poster grid on the right.</string>
+ <string name="vod_classic_categories_title">Categories</string>
+ <string name="vod_classic_category_search">Search in categories</string>
+ <string name="vod_classic_all">All</string>
+ <string name="vod_classic_continue_watching">Continue Watching</string>
+ <string name="vod_classic_recently_added">Recently Added</string>
+ <string name="vod_classic_results_count">%1$d items</string>
+ <string name="vod_classic_empty_category">No titles found in this section.</string>
+ <string name="epg_no_schedule_short">No schedule</string>
+ <string name="epg_show_app_navigation">Show App Nav</string>
+ <string name="epg_program_details_show">Program Details</string>
+ <string name="epg_program_details_hide">Hide Details</string>
+ <string name="epg_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_short">Categories</string>
+ <string name="epg_search_short">Program Search</string>
+ <string name="epg_options_short">Options</string>
+ <string name="epg_schedule_summary_short">%1$d/%2$d with guide</string>
+ <string name="epg_stale_short">Guide may be stale</string>
+ <string name="settings_category_mode_protection">Lock / Unlock</string>
+ <string name="settings_category_mode_visibility">Hide / Unhide</string>
+ <string name="settings_category_protection_summary_title">Lock changes are reviewed before they go live</string>
+ <string name="settings_category_protection_summary_body">Toggle the categories you want to lock or unlock, then save. Saving requires your parental PIN.</string>
+ <string name="settings_category_protection_summary_body_no_pin">Toggle the categories you want to lock or unlock, then save. You will be asked to create a parental PIN before the changes are applied.</string>
+ <string name="settings_category_protection_save">Save Locks (%1$d)</string>
+ <string name="settings_category_protection_save_idle">Save Locks</string>
+ <string name="settings_category_protection_reset">Reset</string>
+ <string name="settings_category_visibility_summary_title">Visibility changes apply immediately</string>
+ <string name="settings_category_visibility_summary_body">%1$d categories are currently hidden for this playlist. Hiding and restoring does not require a PIN.</string>
+ <string name="settings_category_status_locked">Locked</string>
+ <string name="settings_category_status_unlocked">Unlocked</string>
+ <string name="settings_category_status_auto_locked">Auto-Locked</string>
+ <string name="settings_category_status_hidden">Hidden</string>
+ <string name="settings_category_controls_empty">No categories match this search.</string>
+ <string name="movie_loading_details">Loading details...</string>
+ <string name="movie_not_found">Movie not found</string>
+ <string name="movie_detail_back">Back to library</string>
+ <string name="movie_detail_play">Play</string>
+ <string name="movie_detail_trailer">Trailer</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>
+ <string name="movie_detail_duration">Duration:</string>
+ <string name="movie_detail_genre">Genre:</string>
+ <string name="movie_detail_cast">Cast:</string>
+ <string name="movie_detail_unknown">Unknown</string>
</resources>
diff --git a/app/src/main/res/values-iw/strings.xml b/app/src/main/res/values-iw/strings.xml
index 7e50b4e2..2a5841c6 100644
--- a/app/src/main/res/values-iw/strings.xml
+++ b/app/src/main/res/values-iw/strings.xml
@@ -1,4 +1,4 @@
-<?xml version="1.0" encoding="utf-8"?>
+<?xml version='1.0' encoding='utf-8'?>
<resources>
<string name="app_name">StreamVault</string>
<string name="nav_home">בית</string>
@@ -124,7 +124,7 @@
<string name="card_locked_channel">ערוץ נעול</string>
<string name="card_live_badge">בשידור חי</string>
<string name="card_locked">נעול</string>
- <string name="category_see_all">ראה הכל →</string>
+ <string name="category_see_all">ראה הכל</string>
<string name="continue_watching_title">המשך לצפות</string>
<string name="continue_watching_season_episode">עונה %1$d פרק %2$d</string>
<string name="playlist_no_provider">אין ספק</string>
@@ -383,7 +383,7 @@
<string name="settings_recording_status_completed">הושלם</string>
<string name="settings_recording_status_failed">נכשל</string>
<string name="settings_recording_status_cancelled">בוטלה</string>
- <string name="settings_recording_time_window">%1$s → %2$s</string>
+ <string name="settings_recording_time_window">%1$s - %2$s</string>
<string name="settings_recording_recurrence_none">הקלטה חד פעמית</string>
<string name="settings_recording_recurrence_daily">חוזר מדי יום</string>
<string name="settings_recording_recurrence_weekly">חוזר מדי שבוע</string>
@@ -453,8 +453,8 @@
<string name="guide_shell_subtitle">מסנני מדריך, צפיפות לוח זמנים ופרטי תוכנית ממוקדים במשטח אחד מרוחק-ראשון.</string>
<string name="favorites_reordering">מסדר מחדש</string>
<string name="favorites_reorder_mode">מצב סדר מחדש</string>
- <string name="favorites_move_up">למעלה או שמאלה: לזוז מוקדם יותר</string>
- <string name="favorites_move_down">למטה או ימינה: זז מאוחר יותר</string>
+ <string name="favorites_move_up">העבר למיקום מוקדם יותר</string>
+ <string name="favorites_move_down">העבר למיקום מאוחר יותר</string>
<string name="favorites_confirm">מרכז: שמור הזמנה</string>
<string name="favorites_cancel">גב: בטל</string>
<string name="search_title">חפש</string>
@@ -868,4 +868,89 @@
<string name="settings_history_cleared">היסטוריית הצפייה והאחרונים נוקו</string>
<string name="settings_pin_changed">PIN נשמר בהצלחה</string>
<string name="home_reorder_channels">סדר מחדש את הערוצים</string>
+
+ <string name="category_options_hide">Hide Category</string>
+ <string name="settings_provider_category_controls_action">Category Controls</string>
+ <string name="settings_provider_category_controls_title">Category Controls</string>
+ <string name="settings_provider_category_controls_subtitle">Lock, unlock, hide, and restore categories for the current playlist from one place.</string>
+ <string name="settings_provider_category_controls_search">Search categories...</string>
+ <string name="settings_categories_title">Category Preferences</string>
+ <string name="settings_categories_subtitle">Hide provider categories and keep their sort order exactly how you want it.</string>
+ <string name="settings_category_sorting_title">Category Sorting</string>
+ <string name="settings_category_sorting_subtitle">Sort categories for the active playlist. Locking and hiding now live in Category Controls.</string>
+ <string name="settings_category_sort_live">Live TV Categories</string>
+ <string name="settings_category_sort_movies">Movie Categories</string>
+ <string name="settings_category_sort_series">Series Categories</string>
+ <string name="settings_hidden_categories_title">Hidden Categories</string>
+ <string name="settings_hidden_categories_subtitle">Restore any provider categories you previously hid from browsing surfaces.</string>
+ <string name="settings_hidden_categories_none">None hidden</string>
+ <string name="settings_hidden_categories_count">%1$d hidden</string>
+ <string name="settings_hidden_categories_empty">No hidden categories right now.</string>
+ <string name="settings_unhide_category">Unhide</string>
+ <string name="settings_hide_category">Hide</string>
+ <string name="settings_category_sort_default">Provider Order</string>
+ <string name="settings_category_sort_az">A-Z</string>
+ <string name="settings_category_sort_za">Z-A</string>
+ <string name="settings_category_sort_most_items">Most Items First</string>
+ <string name="settings_category_sort_least_items">Least Items First</string>
+ <string name="settings_category_type_live_description">Sort and hide provider live groups while keeping All Channels, Favorites, Recent, and custom groups in their pinned positions.</string>
+ <string name="settings_category_type_movies_description">Sort and hide provider movie categories without affecting Favorites, Resume, or custom shelves.</string>
+ <string name="settings_category_type_series_description">Sort and hide provider series categories without affecting Favorites, Continue Watching, or custom shelves.</string>
+ <string name="settings_live_channel_numbering_mode">Live TV Channel Numbering</string>
+ <string name="settings_live_channel_numbering_mode_subtitle">Choose whether live channels use their position in the current group or keep the original numbers from the provider.</string>
+ <string name="settings_live_channel_numbering_group">Per Group</string>
+ <string name="settings_live_channel_numbering_group_desc">Default behavior. Renumber channels based on their position inside the current category or custom group.</string>
+ <string name="settings_live_channel_numbering_provider">Provider Number</string>
+ <string name="settings_live_channel_numbering_provider_desc">Keep the original channel number supplied by the playlist provider whenever it exists.</string>
+ <string name="settings_vod_view_mode">VOD layout</string>
+ <string name="settings_vod_view_mode_subtitle">Choose between the modern shelves view and a classic split layout.</string>
+ <string name="settings_vod_view_mode_modern">Modern</string>
+ <string name="settings_vod_view_mode_modern_desc">Shelf-based browsing with featured rows and category previews.</string>
+ <string name="settings_vod_view_mode_classic">Classic</string>
+ <string name="settings_vod_view_mode_classic_desc">Category list on the left with a stacked poster grid on the right.</string>
+ <string name="vod_classic_categories_title">Categories</string>
+ <string name="vod_classic_category_search">Search in categories</string>
+ <string name="vod_classic_all">All</string>
+ <string name="vod_classic_continue_watching">Continue Watching</string>
+ <string name="vod_classic_recently_added">Recently Added</string>
+ <string name="vod_classic_results_count">%1$d items</string>
+ <string name="vod_classic_empty_category">No titles found in this section.</string>
+ <string name="epg_no_schedule_short">No schedule</string>
+ <string name="epg_show_app_navigation">Show App Nav</string>
+ <string name="epg_program_details_show">Program Details</string>
+ <string name="epg_program_details_hide">Hide Details</string>
+ <string name="epg_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_short">Categories</string>
+ <string name="epg_search_short">Program Search</string>
+ <string name="epg_options_short">Options</string>
+ <string name="epg_schedule_summary_short">%1$d/%2$d with guide</string>
+ <string name="epg_stale_short">Guide may be stale</string>
+ <string name="settings_category_mode_protection">Lock / Unlock</string>
+ <string name="settings_category_mode_visibility">Hide / Unhide</string>
+ <string name="settings_category_protection_summary_title">Lock changes are reviewed before they go live</string>
+ <string name="settings_category_protection_summary_body">Toggle the categories you want to lock or unlock, then save. Saving requires your parental PIN.</string>
+ <string name="settings_category_protection_summary_body_no_pin">Toggle the categories you want to lock or unlock, then save. You will be asked to create a parental PIN before the changes are applied.</string>
+ <string name="settings_category_protection_save">Save Locks (%1$d)</string>
+ <string name="settings_category_protection_save_idle">Save Locks</string>
+ <string name="settings_category_protection_reset">Reset</string>
+ <string name="settings_category_visibility_summary_title">Visibility changes apply immediately</string>
+ <string name="settings_category_visibility_summary_body">%1$d categories are currently hidden for this playlist. Hiding and restoring does not require a PIN.</string>
+ <string name="settings_category_status_locked">Locked</string>
+ <string name="settings_category_status_unlocked">Unlocked</string>
+ <string name="settings_category_status_auto_locked">Auto-Locked</string>
+ <string name="settings_category_status_hidden">Hidden</string>
+ <string name="settings_category_controls_empty">No categories match this search.</string>
+ <string name="movie_loading_details">Loading details...</string>
+ <string name="movie_not_found">Movie not found</string>
+ <string name="movie_detail_back">חזרה לספרייה</string>
+ <string name="movie_detail_play">Play</string>
+ <string name="movie_detail_trailer">Trailer</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>
+ <string name="movie_detail_duration">Duration:</string>
+ <string name="movie_detail_genre">Genre:</string>
+ <string name="movie_detail_cast">Cast:</string>
+ <string name="movie_detail_unknown">Unknown</string>
</resources>
diff --git a/app/src/main/res/values-ja/strings.xml b/app/src/main/res/values-ja/strings.xml
index 4b065d2c..abf8bcff 100644
--- a/app/src/main/res/values-ja/strings.xml
+++ b/app/src/main/res/values-ja/strings.xml
@@ -868,4 +868,89 @@
<string name="settings_history_cleared">視聴履歴と最近の内容が消去されました</string>
<string name="settings_pin_changed">PIN が正常に保存されました</string>
<string name="home_reorder_channels">チャンネルを並べ替える</string>
+ <!-- Synced fallback strings from English -->
+ <string name="category_options_hide">Hide Category</string>
+ <string name="settings_provider_category_controls_action">Category Controls</string>
+ <string name="settings_provider_category_controls_title">Category Controls</string>
+ <string name="settings_provider_category_controls_subtitle">Lock, unlock, hide, and restore categories for the current playlist from one place.</string>
+ <string name="settings_provider_category_controls_search">Search categories...</string>
+ <string name="settings_categories_title">Category Preferences</string>
+ <string name="settings_categories_subtitle">Hide provider categories and keep their sort order exactly how you want it.</string>
+ <string name="settings_category_sorting_title">Category Sorting</string>
+ <string name="settings_category_sorting_subtitle">Sort categories for the active playlist. Locking and hiding now live in Category Controls.</string>
+ <string name="settings_category_sort_live">Live TV Categories</string>
+ <string name="settings_category_sort_movies">Movie Categories</string>
+ <string name="settings_category_sort_series">Series Categories</string>
+ <string name="settings_hidden_categories_title">Hidden Categories</string>
+ <string name="settings_hidden_categories_subtitle">Restore any provider categories you previously hid from browsing surfaces.</string>
+ <string name="settings_hidden_categories_none">None hidden</string>
+ <string name="settings_hidden_categories_count">%1$d hidden</string>
+ <string name="settings_hidden_categories_empty">No hidden categories right now.</string>
+ <string name="settings_unhide_category">Unhide</string>
+ <string name="settings_hide_category">Hide</string>
+ <string name="settings_category_sort_default">Provider Order</string>
+ <string name="settings_category_sort_az">A-Z</string>
+ <string name="settings_category_sort_za">Z-A</string>
+ <string name="settings_category_sort_most_items">Most Items First</string>
+ <string name="settings_category_sort_least_items">Least Items First</string>
+ <string name="settings_category_type_live_description">Sort and hide provider live groups while keeping All Channels, Favorites, Recent, and custom groups in their pinned positions.</string>
+ <string name="settings_category_type_movies_description">Sort and hide provider movie categories without affecting Favorites, Resume, or custom shelves.</string>
+ <string name="settings_category_type_series_description">Sort and hide provider series categories without affecting Favorites, Continue Watching, or custom shelves.</string>
+ <string name="settings_live_channel_numbering_mode">Live TV Channel Numbering</string>
+ <string name="settings_live_channel_numbering_mode_subtitle">Choose whether live channels use their position in the current group or keep the original numbers from the provider.</string>
+ <string name="settings_live_channel_numbering_group">Per Group</string>
+ <string name="settings_live_channel_numbering_group_desc">Default behavior. Renumber channels based on their position inside the current category or custom group.</string>
+ <string name="settings_live_channel_numbering_provider">Provider Number</string>
+ <string name="settings_live_channel_numbering_provider_desc">Keep the original channel number supplied by the playlist provider whenever it exists.</string>
+ <string name="settings_vod_view_mode">VOD layout</string>
+ <string name="settings_vod_view_mode_subtitle">Choose between the modern shelves view and a classic split layout.</string>
+ <string name="settings_vod_view_mode_modern">Modern</string>
+ <string name="settings_vod_view_mode_modern_desc">Shelf-based browsing with featured rows and category previews.</string>
+ <string name="settings_vod_view_mode_classic">Classic</string>
+ <string name="settings_vod_view_mode_classic_desc">Category list on the left with a stacked poster grid on the right.</string>
+ <string name="vod_classic_categories_title">Categories</string>
+ <string name="vod_classic_category_search">Search in categories</string>
+ <string name="vod_classic_all">All</string>
+ <string name="vod_classic_continue_watching">Continue Watching</string>
+ <string name="vod_classic_recently_added">Recently Added</string>
+ <string name="vod_classic_results_count">%1$d items</string>
+ <string name="vod_classic_empty_category">No titles found in this section.</string>
+ <string name="epg_no_schedule_short">No schedule</string>
+ <string name="epg_show_app_navigation">Show App Nav</string>
+ <string name="epg_program_details_show">Program Details</string>
+ <string name="epg_program_details_hide">Hide Details</string>
+ <string name="epg_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_short">Categories</string>
+ <string name="epg_search_short">Program Search</string>
+ <string name="epg_options_short">Options</string>
+ <string name="epg_schedule_summary_short">%1$d/%2$d with guide</string>
+ <string name="epg_stale_short">Guide may be stale</string>
+ <string name="settings_category_mode_protection">Lock / Unlock</string>
+ <string name="settings_category_mode_visibility">Hide / Unhide</string>
+ <string name="settings_category_protection_summary_title">Lock changes are reviewed before they go live</string>
+ <string name="settings_category_protection_summary_body">Toggle the categories you want to lock or unlock, then save. Saving requires your parental PIN.</string>
+ <string name="settings_category_protection_summary_body_no_pin">Toggle the categories you want to lock or unlock, then save. You will be asked to create a parental PIN before the changes are applied.</string>
+ <string name="settings_category_protection_save">Save Locks (%1$d)</string>
+ <string name="settings_category_protection_save_idle">Save Locks</string>
+ <string name="settings_category_protection_reset">Reset</string>
+ <string name="settings_category_visibility_summary_title">Visibility changes apply immediately</string>
+ <string name="settings_category_visibility_summary_body">%1$d categories are currently hidden for this playlist. Hiding and restoring does not require a PIN.</string>
+ <string name="settings_category_status_locked">Locked</string>
+ <string name="settings_category_status_unlocked">Unlocked</string>
+ <string name="settings_category_status_auto_locked">Auto-Locked</string>
+ <string name="settings_category_status_hidden">Hidden</string>
+ <string name="settings_category_controls_empty">No categories match this search.</string>
+ <string name="movie_loading_details">Loading details...</string>
+ <string name="movie_not_found">Movie not found</string>
+ <string name="movie_detail_back">Back to library</string>
+ <string name="movie_detail_play">Play</string>
+ <string name="movie_detail_trailer">Trailer</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>
+ <string name="movie_detail_duration">Duration:</string>
+ <string name="movie_detail_genre">Genre:</string>
+ <string name="movie_detail_cast">Cast:</string>
+ <string name="movie_detail_unknown">Unknown</string>
</resources>
diff --git a/app/src/main/res/values-ko/strings.xml b/app/src/main/res/values-ko/strings.xml
index 61c4ce5b..f62e3fef 100644
--- a/app/src/main/res/values-ko/strings.xml
+++ b/app/src/main/res/values-ko/strings.xml
@@ -868,4 +868,89 @@
<string name="settings_history_cleared">시청 기록 및 최근 항목이 삭제되었습니다.</string>
<string name="settings_pin_changed">PIN이 저장되었습니다.</string>
<string name="home_reorder_channels">채널 재정렬</string>
+ <!-- Synced fallback strings from English -->
+ <string name="category_options_hide">Hide Category</string>
+ <string name="settings_provider_category_controls_action">Category Controls</string>
+ <string name="settings_provider_category_controls_title">Category Controls</string>
+ <string name="settings_provider_category_controls_subtitle">Lock, unlock, hide, and restore categories for the current playlist from one place.</string>
+ <string name="settings_provider_category_controls_search">Search categories...</string>
+ <string name="settings_categories_title">Category Preferences</string>
+ <string name="settings_categories_subtitle">Hide provider categories and keep their sort order exactly how you want it.</string>
+ <string name="settings_category_sorting_title">Category Sorting</string>
+ <string name="settings_category_sorting_subtitle">Sort categories for the active playlist. Locking and hiding now live in Category Controls.</string>
+ <string name="settings_category_sort_live">Live TV Categories</string>
+ <string name="settings_category_sort_movies">Movie Categories</string>
+ <string name="settings_category_sort_series">Series Categories</string>
+ <string name="settings_hidden_categories_title">Hidden Categories</string>
+ <string name="settings_hidden_categories_subtitle">Restore any provider categories you previously hid from browsing surfaces.</string>
+ <string name="settings_hidden_categories_none">None hidden</string>
+ <string name="settings_hidden_categories_count">%1$d hidden</string>
+ <string name="settings_hidden_categories_empty">No hidden categories right now.</string>
+ <string name="settings_unhide_category">Unhide</string>
+ <string name="settings_hide_category">Hide</string>
+ <string name="settings_category_sort_default">Provider Order</string>
+ <string name="settings_category_sort_az">A-Z</string>
+ <string name="settings_category_sort_za">Z-A</string>
+ <string name="settings_category_sort_most_items">Most Items First</string>
+ <string name="settings_category_sort_least_items">Least Items First</string>
+ <string name="settings_category_type_live_description">Sort and hide provider live groups while keeping All Channels, Favorites, Recent, and custom groups in their pinned positions.</string>
+ <string name="settings_category_type_movies_description">Sort and hide provider movie categories without affecting Favorites, Resume, or custom shelves.</string>
+ <string name="settings_category_type_series_description">Sort and hide provider series categories without affecting Favorites, Continue Watching, or custom shelves.</string>
+ <string name="settings_live_channel_numbering_mode">Live TV Channel Numbering</string>
+ <string name="settings_live_channel_numbering_mode_subtitle">Choose whether live channels use their position in the current group or keep the original numbers from the provider.</string>
+ <string name="settings_live_channel_numbering_group">Per Group</string>
+ <string name="settings_live_channel_numbering_group_desc">Default behavior. Renumber channels based on their position inside the current category or custom group.</string>
+ <string name="settings_live_channel_numbering_provider">Provider Number</string>
+ <string name="settings_live_channel_numbering_provider_desc">Keep the original channel number supplied by the playlist provider whenever it exists.</string>
+ <string name="settings_vod_view_mode">VOD layout</string>
+ <string name="settings_vod_view_mode_subtitle">Choose between the modern shelves view and a classic split layout.</string>
+ <string name="settings_vod_view_mode_modern">Modern</string>
+ <string name="settings_vod_view_mode_modern_desc">Shelf-based browsing with featured rows and category previews.</string>
+ <string name="settings_vod_view_mode_classic">Classic</string>
+ <string name="settings_vod_view_mode_classic_desc">Category list on the left with a stacked poster grid on the right.</string>
+ <string name="vod_classic_categories_title">Categories</string>
+ <string name="vod_classic_category_search">Search in categories</string>
+ <string name="vod_classic_all">All</string>
+ <string name="vod_classic_continue_watching">Continue Watching</string>
+ <string name="vod_classic_recently_added">Recently Added</string>
+ <string name="vod_classic_results_count">%1$d items</string>
+ <string name="vod_classic_empty_category">No titles found in this section.</string>
+ <string name="epg_no_schedule_short">No schedule</string>
+ <string name="epg_show_app_navigation">Show App Nav</string>
+ <string name="epg_program_details_show">Program Details</string>
+ <string name="epg_program_details_hide">Hide Details</string>
+ <string name="epg_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_short">Categories</string>
+ <string name="epg_search_short">Program Search</string>
+ <string name="epg_options_short">Options</string>
+ <string name="epg_schedule_summary_short">%1$d/%2$d with guide</string>
+ <string name="epg_stale_short">Guide may be stale</string>
+ <string name="settings_category_mode_protection">Lock / Unlock</string>
+ <string name="settings_category_mode_visibility">Hide / Unhide</string>
+ <string name="settings_category_protection_summary_title">Lock changes are reviewed before they go live</string>
+ <string name="settings_category_protection_summary_body">Toggle the categories you want to lock or unlock, then save. Saving requires your parental PIN.</string>
+ <string name="settings_category_protection_summary_body_no_pin">Toggle the categories you want to lock or unlock, then save. You will be asked to create a parental PIN before the changes are applied.</string>
+ <string name="settings_category_protection_save">Save Locks (%1$d)</string>
+ <string name="settings_category_protection_save_idle">Save Locks</string>
+ <string name="settings_category_protection_reset">Reset</string>
+ <string name="settings_category_visibility_summary_title">Visibility changes apply immediately</string>
+ <string name="settings_category_visibility_summary_body">%1$d categories are currently hidden for this playlist. Hiding and restoring does not require a PIN.</string>
+ <string name="settings_category_status_locked">Locked</string>
+ <string name="settings_category_status_unlocked">Unlocked</string>
+ <string name="settings_category_status_auto_locked">Auto-Locked</string>
+ <string name="settings_category_status_hidden">Hidden</string>
+ <string name="settings_category_controls_empty">No categories match this search.</string>
+ <string name="movie_loading_details">Loading details...</string>
+ <string name="movie_not_found">Movie not found</string>
+ <string name="movie_detail_back">Back to library</string>
+ <string name="movie_detail_play">Play</string>
+ <string name="movie_detail_trailer">Trailer</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>
+ <string name="movie_detail_duration">Duration:</string>
+ <string name="movie_detail_genre">Genre:</string>
+ <string name="movie_detail_cast">Cast:</string>
+ <string name="movie_detail_unknown">Unknown</string>
</resources>
diff --git a/app/src/main/res/values-nb/strings.xml b/app/src/main/res/values-nb/strings.xml
index 5212c280..dbfbcfa2 100644
--- a/app/src/main/res/values-nb/strings.xml
+++ b/app/src/main/res/values-nb/strings.xml
@@ -868,4 +868,89 @@
<string name="settings_history_cleared">Se historikk og nylig tømt</string>
<string name="settings_pin_changed">PIN-koden er lagret</string>
<string name="home_reorder_channels">Omorganiser kanaler</string>
+ <!-- Synced fallback strings from English -->
+ <string name="category_options_hide">Hide Category</string>
+ <string name="settings_provider_category_controls_action">Category Controls</string>
+ <string name="settings_provider_category_controls_title">Category Controls</string>
+ <string name="settings_provider_category_controls_subtitle">Lock, unlock, hide, and restore categories for the current playlist from one place.</string>
+ <string name="settings_provider_category_controls_search">Search categories...</string>
+ <string name="settings_categories_title">Category Preferences</string>
+ <string name="settings_categories_subtitle">Hide provider categories and keep their sort order exactly how you want it.</string>
+ <string name="settings_category_sorting_title">Category Sorting</string>
+ <string name="settings_category_sorting_subtitle">Sort categories for the active playlist. Locking and hiding now live in Category Controls.</string>
+ <string name="settings_category_sort_live">Live TV Categories</string>
+ <string name="settings_category_sort_movies">Movie Categories</string>
+ <string name="settings_category_sort_series">Series Categories</string>
+ <string name="settings_hidden_categories_title">Hidden Categories</string>
+ <string name="settings_hidden_categories_subtitle">Restore any provider categories you previously hid from browsing surfaces.</string>
+ <string name="settings_hidden_categories_none">None hidden</string>
+ <string name="settings_hidden_categories_count">%1$d hidden</string>
+ <string name="settings_hidden_categories_empty">No hidden categories right now.</string>
+ <string name="settings_unhide_category">Unhide</string>
+ <string name="settings_hide_category">Hide</string>
+ <string name="settings_category_sort_default">Provider Order</string>
+ <string name="settings_category_sort_az">A-Z</string>
+ <string name="settings_category_sort_za">Z-A</string>
+ <string name="settings_category_sort_most_items">Most Items First</string>
+ <string name="settings_category_sort_least_items">Least Items First</string>
+ <string name="settings_category_type_live_description">Sort and hide provider live groups while keeping All Channels, Favorites, Recent, and custom groups in their pinned positions.</string>
+ <string name="settings_category_type_movies_description">Sort and hide provider movie categories without affecting Favorites, Resume, or custom shelves.</string>
+ <string name="settings_category_type_series_description">Sort and hide provider series categories without affecting Favorites, Continue Watching, or custom shelves.</string>
+ <string name="settings_live_channel_numbering_mode">Live TV Channel Numbering</string>
+ <string name="settings_live_channel_numbering_mode_subtitle">Choose whether live channels use their position in the current group or keep the original numbers from the provider.</string>
+ <string name="settings_live_channel_numbering_group">Per Group</string>
+ <string name="settings_live_channel_numbering_group_desc">Default behavior. Renumber channels based on their position inside the current category or custom group.</string>
+ <string name="settings_live_channel_numbering_provider">Provider Number</string>
+ <string name="settings_live_channel_numbering_provider_desc">Keep the original channel number supplied by the playlist provider whenever it exists.</string>
+ <string name="settings_vod_view_mode">VOD layout</string>
+ <string name="settings_vod_view_mode_subtitle">Choose between the modern shelves view and a classic split layout.</string>
+ <string name="settings_vod_view_mode_modern">Modern</string>
+ <string name="settings_vod_view_mode_modern_desc">Shelf-based browsing with featured rows and category previews.</string>
+ <string name="settings_vod_view_mode_classic">Classic</string>
+ <string name="settings_vod_view_mode_classic_desc">Category list on the left with a stacked poster grid on the right.</string>
+ <string name="vod_classic_categories_title">Categories</string>
+ <string name="vod_classic_category_search">Search in categories</string>
+ <string name="vod_classic_all">All</string>
+ <string name="vod_classic_continue_watching">Continue Watching</string>
+ <string name="vod_classic_recently_added">Recently Added</string>
+ <string name="vod_classic_results_count">%1$d items</string>
+ <string name="vod_classic_empty_category">No titles found in this section.</string>
+ <string name="epg_no_schedule_short">No schedule</string>
+ <string name="epg_show_app_navigation">Show App Nav</string>
+ <string name="epg_program_details_show">Program Details</string>
+ <string name="epg_program_details_hide">Hide Details</string>
+ <string name="epg_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_short">Categories</string>
+ <string name="epg_search_short">Program Search</string>
+ <string name="epg_options_short">Options</string>
+ <string name="epg_schedule_summary_short">%1$d/%2$d with guide</string>
+ <string name="epg_stale_short">Guide may be stale</string>
+ <string name="settings_category_mode_protection">Lock / Unlock</string>
+ <string name="settings_category_mode_visibility">Hide / Unhide</string>
+ <string name="settings_category_protection_summary_title">Lock changes are reviewed before they go live</string>
+ <string name="settings_category_protection_summary_body">Toggle the categories you want to lock or unlock, then save. Saving requires your parental PIN.</string>
+ <string name="settings_category_protection_summary_body_no_pin">Toggle the categories you want to lock or unlock, then save. You will be asked to create a parental PIN before the changes are applied.</string>
+ <string name="settings_category_protection_save">Save Locks (%1$d)</string>
+ <string name="settings_category_protection_save_idle">Save Locks</string>
+ <string name="settings_category_protection_reset">Reset</string>
+ <string name="settings_category_visibility_summary_title">Visibility changes apply immediately</string>
+ <string name="settings_category_visibility_summary_body">%1$d categories are currently hidden for this playlist. Hiding and restoring does not require a PIN.</string>
+ <string name="settings_category_status_locked">Locked</string>
+ <string name="settings_category_status_unlocked">Unlocked</string>
+ <string name="settings_category_status_auto_locked">Auto-Locked</string>
+ <string name="settings_category_status_hidden">Hidden</string>
+ <string name="settings_category_controls_empty">No categories match this search.</string>
+ <string name="movie_loading_details">Loading details...</string>
+ <string name="movie_not_found">Movie not found</string>
+ <string name="movie_detail_back">Back to library</string>
+ <string name="movie_detail_play">Play</string>
+ <string name="movie_detail_trailer">Trailer</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>
+ <string name="movie_detail_duration">Duration:</string>
+ <string name="movie_detail_genre">Genre:</string>
+ <string name="movie_detail_cast">Cast:</string>
+ <string name="movie_detail_unknown">Unknown</string>
</resources>
diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml
index 61dde298..e74e4152 100644
--- a/app/src/main/res/values-nl/strings.xml
+++ b/app/src/main/res/values-nl/strings.xml
@@ -868,4 +868,89 @@
<string name="settings_history_cleared">Kijkgeschiedenis en recente beelden gewist</string>
<string name="settings_pin_changed">Pincode succesvol opgeslagen</string>
<string name="home_reorder_channels">Kanalen opnieuw rangschikken</string>
+ <!-- Synced fallback strings from English -->
+ <string name="category_options_hide">Hide Category</string>
+ <string name="settings_provider_category_controls_action">Category Controls</string>
+ <string name="settings_provider_category_controls_title">Category Controls</string>
+ <string name="settings_provider_category_controls_subtitle">Lock, unlock, hide, and restore categories for the current playlist from one place.</string>
+ <string name="settings_provider_category_controls_search">Search categories...</string>
+ <string name="settings_categories_title">Category Preferences</string>
+ <string name="settings_categories_subtitle">Hide provider categories and keep their sort order exactly how you want it.</string>
+ <string name="settings_category_sorting_title">Category Sorting</string>
+ <string name="settings_category_sorting_subtitle">Sort categories for the active playlist. Locking and hiding now live in Category Controls.</string>
+ <string name="settings_category_sort_live">Live TV Categories</string>
+ <string name="settings_category_sort_movies">Movie Categories</string>
+ <string name="settings_category_sort_series">Series Categories</string>
+ <string name="settings_hidden_categories_title">Hidden Categories</string>
+ <string name="settings_hidden_categories_subtitle">Restore any provider categories you previously hid from browsing surfaces.</string>
+ <string name="settings_hidden_categories_none">None hidden</string>
+ <string name="settings_hidden_categories_count">%1$d hidden</string>
+ <string name="settings_hidden_categories_empty">No hidden categories right now.</string>
+ <string name="settings_unhide_category">Unhide</string>
+ <string name="settings_hide_category">Hide</string>
+ <string name="settings_category_sort_default">Provider Order</string>
+ <string name="settings_category_sort_az">A-Z</string>
+ <string name="settings_category_sort_za">Z-A</string>
+ <string name="settings_category_sort_most_items">Most Items First</string>
+ <string name="settings_category_sort_least_items">Least Items First</string>
+ <string name="settings_category_type_live_description">Sort and hide provider live groups while keeping All Channels, Favorites, Recent, and custom groups in their pinned positions.</string>
+ <string name="settings_category_type_movies_description">Sort and hide provider movie categories without affecting Favorites, Resume, or custom shelves.</string>
+ <string name="settings_category_type_series_description">Sort and hide provider series categories without affecting Favorites, Continue Watching, or custom shelves.</string>
+ <string name="settings_live_channel_numbering_mode">Live TV Channel Numbering</string>
+ <string name="settings_live_channel_numbering_mode_subtitle">Choose whether live channels use their position in the current group or keep the original numbers from the provider.</string>
+ <string name="settings_live_channel_numbering_group">Per Group</string>
+ <string name="settings_live_channel_numbering_group_desc">Default behavior. Renumber channels based on their position inside the current category or custom group.</string>
+ <string name="settings_live_channel_numbering_provider">Provider Number</string>
+ <string name="settings_live_channel_numbering_provider_desc">Keep the original channel number supplied by the playlist provider whenever it exists.</string>
+ <string name="settings_vod_view_mode">VOD layout</string>
+ <string name="settings_vod_view_mode_subtitle">Choose between the modern shelves view and a classic split layout.</string>
+ <string name="settings_vod_view_mode_modern">Modern</string>
+ <string name="settings_vod_view_mode_modern_desc">Shelf-based browsing with featured rows and category previews.</string>
+ <string name="settings_vod_view_mode_classic">Classic</string>
+ <string name="settings_vod_view_mode_classic_desc">Category list on the left with a stacked poster grid on the right.</string>
+ <string name="vod_classic_categories_title">Categories</string>
+ <string name="vod_classic_category_search">Search in categories</string>
+ <string name="vod_classic_all">All</string>
+ <string name="vod_classic_continue_watching">Continue Watching</string>
+ <string name="vod_classic_recently_added">Recently Added</string>
+ <string name="vod_classic_results_count">%1$d items</string>
+ <string name="vod_classic_empty_category">No titles found in this section.</string>
+ <string name="epg_no_schedule_short">No schedule</string>
+ <string name="epg_show_app_navigation">Show App Nav</string>
+ <string name="epg_program_details_show">Program Details</string>
+ <string name="epg_program_details_hide">Hide Details</string>
+ <string name="epg_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_short">Categories</string>
+ <string name="epg_search_short">Program Search</string>
+ <string name="epg_options_short">Options</string>
+ <string name="epg_schedule_summary_short">%1$d/%2$d with guide</string>
+ <string name="epg_stale_short">Guide may be stale</string>
+ <string name="settings_category_mode_protection">Lock / Unlock</string>
+ <string name="settings_category_mode_visibility">Hide / Unhide</string>
+ <string name="settings_category_protection_summary_title">Lock changes are reviewed before they go live</string>
+ <string name="settings_category_protection_summary_body">Toggle the categories you want to lock or unlock, then save. Saving requires your parental PIN.</string>
+ <string name="settings_category_protection_summary_body_no_pin">Toggle the categories you want to lock or unlock, then save. You will be asked to create a parental PIN before the changes are applied.</string>
+ <string name="settings_category_protection_save">Save Locks (%1$d)</string>
+ <string name="settings_category_protection_save_idle">Save Locks</string>
+ <string name="settings_category_protection_reset">Reset</string>
+ <string name="settings_category_visibility_summary_title">Visibility changes apply immediately</string>
+ <string name="settings_category_visibility_summary_body">%1$d categories are currently hidden for this playlist. Hiding and restoring does not require a PIN.</string>
+ <string name="settings_category_status_locked">Locked</string>
+ <string name="settings_category_status_unlocked">Unlocked</string>
+ <string name="settings_category_status_auto_locked">Auto-Locked</string>
+ <string name="settings_category_status_hidden">Hidden</string>
+ <string name="settings_category_controls_empty">No categories match this search.</string>
+ <string name="movie_loading_details">Loading details...</string>
+ <string name="movie_not_found">Movie not found</string>
+ <string name="movie_detail_back">Back to library</string>
+ <string name="movie_detail_play">Play</string>
+ <string name="movie_detail_trailer">Trailer</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>
+ <string name="movie_detail_duration">Duration:</string>
+ <string name="movie_detail_genre">Genre:</string>
+ <string name="movie_detail_cast">Cast:</string>
+ <string name="movie_detail_unknown">Unknown</string>
</resources>
diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml
index 72c749a5..d35b001c 100644
--- a/app/src/main/res/values-pl/strings.xml
+++ b/app/src/main/res/values-pl/strings.xml
@@ -868,4 +868,89 @@
<string name="settings_history_cleared">Historia oglądania i najnowsze filmy zostały usunięte</string>
<string name="settings_pin_changed">Kod PIN został pomyślnie zapisany</string>
<string name="home_reorder_channels">Zmień kolejność kanałów</string>
+ <!-- Synced fallback strings from English -->
+ <string name="category_options_hide">Hide Category</string>
+ <string name="settings_provider_category_controls_action">Category Controls</string>
+ <string name="settings_provider_category_controls_title">Category Controls</string>
+ <string name="settings_provider_category_controls_subtitle">Lock, unlock, hide, and restore categories for the current playlist from one place.</string>
+ <string name="settings_provider_category_controls_search">Search categories...</string>
+ <string name="settings_categories_title">Category Preferences</string>
+ <string name="settings_categories_subtitle">Hide provider categories and keep their sort order exactly how you want it.</string>
+ <string name="settings_category_sorting_title">Category Sorting</string>
+ <string name="settings_category_sorting_subtitle">Sort categories for the active playlist. Locking and hiding now live in Category Controls.</string>
+ <string name="settings_category_sort_live">Live TV Categories</string>
+ <string name="settings_category_sort_movies">Movie Categories</string>
+ <string name="settings_category_sort_series">Series Categories</string>
+ <string name="settings_hidden_categories_title">Hidden Categories</string>
+ <string name="settings_hidden_categories_subtitle">Restore any provider categories you previously hid from browsing surfaces.</string>
+ <string name="settings_hidden_categories_none">None hidden</string>
+ <string name="settings_hidden_categories_count">%1$d hidden</string>
+ <string name="settings_hidden_categories_empty">No hidden categories right now.</string>
+ <string name="settings_unhide_category">Unhide</string>
+ <string name="settings_hide_category">Hide</string>
+ <string name="settings_category_sort_default">Provider Order</string>
+ <string name="settings_category_sort_az">A-Z</string>
+ <string name="settings_category_sort_za">Z-A</string>
+ <string name="settings_category_sort_most_items">Most Items First</string>
+ <string name="settings_category_sort_least_items">Least Items First</string>
+ <string name="settings_category_type_live_description">Sort and hide provider live groups while keeping All Channels, Favorites, Recent, and custom groups in their pinned positions.</string>
+ <string name="settings_category_type_movies_description">Sort and hide provider movie categories without affecting Favorites, Resume, or custom shelves.</string>
+ <string name="settings_category_type_series_description">Sort and hide provider series categories without affecting Favorites, Continue Watching, or custom shelves.</string>
+ <string name="settings_live_channel_numbering_mode">Live TV Channel Numbering</string>
+ <string name="settings_live_channel_numbering_mode_subtitle">Choose whether live channels use their position in the current group or keep the original numbers from the provider.</string>
+ <string name="settings_live_channel_numbering_group">Per Group</string>
+ <string name="settings_live_channel_numbering_group_desc">Default behavior. Renumber channels based on their position inside the current category or custom group.</string>
+ <string name="settings_live_channel_numbering_provider">Provider Number</string>
+ <string name="settings_live_channel_numbering_provider_desc">Keep the original channel number supplied by the playlist provider whenever it exists.</string>
+ <string name="settings_vod_view_mode">VOD layout</string>
+ <string name="settings_vod_view_mode_subtitle">Choose between the modern shelves view and a classic split layout.</string>
+ <string name="settings_vod_view_mode_modern">Modern</string>
+ <string name="settings_vod_view_mode_modern_desc">Shelf-based browsing with featured rows and category previews.</string>
+ <string name="settings_vod_view_mode_classic">Classic</string>
+ <string name="settings_vod_view_mode_classic_desc">Category list on the left with a stacked poster grid on the right.</string>
+ <string name="vod_classic_categories_title">Categories</string>
+ <string name="vod_classic_category_search">Search in categories</string>
+ <string name="vod_classic_all">All</string>
+ <string name="vod_classic_continue_watching">Continue Watching</string>
+ <string name="vod_classic_recently_added">Recently Added</string>
+ <string name="vod_classic_results_count">%1$d items</string>
+ <string name="vod_classic_empty_category">No titles found in this section.</string>
+ <string name="epg_no_schedule_short">No schedule</string>
+ <string name="epg_show_app_navigation">Show App Nav</string>
+ <string name="epg_program_details_show">Program Details</string>
+ <string name="epg_program_details_hide">Hide Details</string>
+ <string name="epg_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_short">Categories</string>
+ <string name="epg_search_short">Program Search</string>
+ <string name="epg_options_short">Options</string>
+ <string name="epg_schedule_summary_short">%1$d/%2$d with guide</string>
+ <string name="epg_stale_short">Guide may be stale</string>
+ <string name="settings_category_mode_protection">Lock / Unlock</string>
+ <string name="settings_category_mode_visibility">Hide / Unhide</string>
+ <string name="settings_category_protection_summary_title">Lock changes are reviewed before they go live</string>
+ <string name="settings_category_protection_summary_body">Toggle the categories you want to lock or unlock, then save. Saving requires your parental PIN.</string>
+ <string name="settings_category_protection_summary_body_no_pin">Toggle the categories you want to lock or unlock, then save. You will be asked to create a parental PIN before the changes are applied.</string>
+ <string name="settings_category_protection_save">Save Locks (%1$d)</string>
+ <string name="settings_category_protection_save_idle">Save Locks</string>
+ <string name="settings_category_protection_reset">Reset</string>
+ <string name="settings_category_visibility_summary_title">Visibility changes apply immediately</string>
+ <string name="settings_category_visibility_summary_body">%1$d categories are currently hidden for this playlist. Hiding and restoring does not require a PIN.</string>
+ <string name="settings_category_status_locked">Locked</string>
+ <string name="settings_category_status_unlocked">Unlocked</string>
+ <string name="settings_category_status_auto_locked">Auto-Locked</string>
+ <string name="settings_category_status_hidden">Hidden</string>
+ <string name="settings_category_controls_empty">No categories match this search.</string>
+ <string name="movie_loading_details">Loading details...</string>
+ <string name="movie_not_found">Movie not found</string>
+ <string name="movie_detail_back">Back to library</string>
+ <string name="movie_detail_play">Play</string>
+ <string name="movie_detail_trailer">Trailer</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>
+ <string name="movie_detail_duration">Duration:</string>
+ <string name="movie_detail_genre">Genre:</string>
+ <string name="movie_detail_cast">Cast:</string>
+ <string name="movie_detail_unknown">Unknown</string>
</resources>
diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml
index 99eefae4..a503e230 100644
--- a/app/src/main/res/values-pt/strings.xml
+++ b/app/src/main/res/values-pt/strings.xml
@@ -868,4 +868,89 @@
<string name="settings_history_cleared">Assistir histórico e recentes apagados</string>
<string name="settings_pin_changed">PIN salvo com sucesso</string>
<string name="home_reorder_channels">Reordenar canais</string>
+ <!-- Synced fallback strings from English -->
+ <string name="category_options_hide">Hide Category</string>
+ <string name="settings_provider_category_controls_action">Category Controls</string>
+ <string name="settings_provider_category_controls_title">Category Controls</string>
+ <string name="settings_provider_category_controls_subtitle">Lock, unlock, hide, and restore categories for the current playlist from one place.</string>
+ <string name="settings_provider_category_controls_search">Search categories...</string>
+ <string name="settings_categories_title">Category Preferences</string>
+ <string name="settings_categories_subtitle">Hide provider categories and keep their sort order exactly how you want it.</string>
+ <string name="settings_category_sorting_title">Category Sorting</string>
+ <string name="settings_category_sorting_subtitle">Sort categories for the active playlist. Locking and hiding now live in Category Controls.</string>
+ <string name="settings_category_sort_live">Live TV Categories</string>
+ <string name="settings_category_sort_movies">Movie Categories</string>
+ <string name="settings_category_sort_series">Series Categories</string>
+ <string name="settings_hidden_categories_title">Hidden Categories</string>
+ <string name="settings_hidden_categories_subtitle">Restore any provider categories you previously hid from browsing surfaces.</string>
+ <string name="settings_hidden_categories_none">None hidden</string>
+ <string name="settings_hidden_categories_count">%1$d hidden</string>
+ <string name="settings_hidden_categories_empty">No hidden categories right now.</string>
+ <string name="settings_unhide_category">Unhide</string>
+ <string name="settings_hide_category">Hide</string>
+ <string name="settings_category_sort_default">Provider Order</string>
+ <string name="settings_category_sort_az">A-Z</string>
+ <string name="settings_category_sort_za">Z-A</string>
+ <string name="settings_category_sort_most_items">Most Items First</string>
+ <string name="settings_category_sort_least_items">Least Items First</string>
+ <string name="settings_category_type_live_description">Sort and hide provider live groups while keeping All Channels, Favorites, Recent, and custom groups in their pinned positions.</string>
+ <string name="settings_category_type_movies_description">Sort and hide provider movie categories without affecting Favorites, Resume, or custom shelves.</string>
+ <string name="settings_category_type_series_description">Sort and hide provider series categories without affecting Favorites, Continue Watching, or custom shelves.</string>
+ <string name="settings_live_channel_numbering_mode">Live TV Channel Numbering</string>
+ <string name="settings_live_channel_numbering_mode_subtitle">Choose whether live channels use their position in the current group or keep the original numbers from the provider.</string>
+ <string name="settings_live_channel_numbering_group">Per Group</string>
+ <string name="settings_live_channel_numbering_group_desc">Default behavior. Renumber channels based on their position inside the current category or custom group.</string>
+ <string name="settings_live_channel_numbering_provider">Provider Number</string>
+ <string name="settings_live_channel_numbering_provider_desc">Keep the original channel number supplied by the playlist provider whenever it exists.</string>
+ <string name="settings_vod_view_mode">VOD layout</string>
+ <string name="settings_vod_view_mode_subtitle">Choose between the modern shelves view and a classic split layout.</string>
+ <string name="settings_vod_view_mode_modern">Modern</string>
+ <string name="settings_vod_view_mode_modern_desc">Shelf-based browsing with featured rows and category previews.</string>
+ <string name="settings_vod_view_mode_classic">Classic</string>
+ <string name="settings_vod_view_mode_classic_desc">Category list on the left with a stacked poster grid on the right.</string>
+ <string name="vod_classic_categories_title">Categories</string>
+ <string name="vod_classic_category_search">Search in categories</string>
+ <string name="vod_classic_all">All</string>
+ <string name="vod_classic_continue_watching">Continue Watching</string>
+ <string name="vod_classic_recently_added">Recently Added</string>
+ <string name="vod_classic_results_count">%1$d items</string>
+ <string name="vod_classic_empty_category">No titles found in this section.</string>
+ <string name="epg_no_schedule_short">No schedule</string>
+ <string name="epg_show_app_navigation">Show App Nav</string>
+ <string name="epg_program_details_show">Program Details</string>
+ <string name="epg_program_details_hide">Hide Details</string>
+ <string name="epg_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_short">Categories</string>
+ <string name="epg_search_short">Program Search</string>
+ <string name="epg_options_short">Options</string>
+ <string name="epg_schedule_summary_short">%1$d/%2$d with guide</string>
+ <string name="epg_stale_short">Guide may be stale</string>
+ <string name="settings_category_mode_protection">Lock / Unlock</string>
+ <string name="settings_category_mode_visibility">Hide / Unhide</string>
+ <string name="settings_category_protection_summary_title">Lock changes are reviewed before they go live</string>
+ <string name="settings_category_protection_summary_body">Toggle the categories you want to lock or unlock, then save. Saving requires your parental PIN.</string>
+ <string name="settings_category_protection_summary_body_no_pin">Toggle the categories you want to lock or unlock, then save. You will be asked to create a parental PIN before the changes are applied.</string>
+ <string name="settings_category_protection_save">Save Locks (%1$d)</string>
+ <string name="settings_category_protection_save_idle">Save Locks</string>
+ <string name="settings_category_protection_reset">Reset</string>
+ <string name="settings_category_visibility_summary_title">Visibility changes apply immediately</string>
+ <string name="settings_category_visibility_summary_body">%1$d categories are currently hidden for this playlist. Hiding and restoring does not require a PIN.</string>
+ <string name="settings_category_status_locked">Locked</string>
+ <string name="settings_category_status_unlocked">Unlocked</string>
+ <string name="settings_category_status_auto_locked">Auto-Locked</string>
+ <string name="settings_category_status_hidden">Hidden</string>
+ <string name="settings_category_controls_empty">No categories match this search.</string>
+ <string name="movie_loading_details">Loading details...</string>
+ <string name="movie_not_found">Movie not found</string>
+ <string name="movie_detail_back">Back to library</string>
+ <string name="movie_detail_play">Play</string>
+ <string name="movie_detail_trailer">Trailer</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>
+ <string name="movie_detail_duration">Duration:</string>
+ <string name="movie_detail_genre">Genre:</string>
+ <string name="movie_detail_cast">Cast:</string>
+ <string name="movie_detail_unknown">Unknown</string>
</resources>
diff --git a/app/src/main/res/values-ro/strings.xml b/app/src/main/res/values-ro/strings.xml
index 4357cba0..f60785a1 100644
--- a/app/src/main/res/values-ro/strings.xml
+++ b/app/src/main/res/values-ro/strings.xml
@@ -868,4 +868,89 @@
<string name="settings_history_cleared">Istoricul vizionărilor și recentele au fost șters</string>
<string name="settings_pin_changed">PIN-ul a fost salvat cu succes</string>
<string name="home_reorder_channels">Reordonați canalele</string>
+ <!-- Synced fallback strings from English -->
+ <string name="category_options_hide">Hide Category</string>
+ <string name="settings_provider_category_controls_action">Category Controls</string>
+ <string name="settings_provider_category_controls_title">Category Controls</string>
+ <string name="settings_provider_category_controls_subtitle">Lock, unlock, hide, and restore categories for the current playlist from one place.</string>
+ <string name="settings_provider_category_controls_search">Search categories...</string>
+ <string name="settings_categories_title">Category Preferences</string>
+ <string name="settings_categories_subtitle">Hide provider categories and keep their sort order exactly how you want it.</string>
+ <string name="settings_category_sorting_title">Category Sorting</string>
+ <string name="settings_category_sorting_subtitle">Sort categories for the active playlist. Locking and hiding now live in Category Controls.</string>
+ <string name="settings_category_sort_live">Live TV Categories</string>
+ <string name="settings_category_sort_movies">Movie Categories</string>
+ <string name="settings_category_sort_series">Series Categories</string>
+ <string name="settings_hidden_categories_title">Hidden Categories</string>
+ <string name="settings_hidden_categories_subtitle">Restore any provider categories you previously hid from browsing surfaces.</string>
+ <string name="settings_hidden_categories_none">None hidden</string>
+ <string name="settings_hidden_categories_count">%1$d hidden</string>
+ <string name="settings_hidden_categories_empty">No hidden categories right now.</string>
+ <string name="settings_unhide_category">Unhide</string>
+ <string name="settings_hide_category">Hide</string>
+ <string name="settings_category_sort_default">Provider Order</string>
+ <string name="settings_category_sort_az">A-Z</string>
+ <string name="settings_category_sort_za">Z-A</string>
+ <string name="settings_category_sort_most_items">Most Items First</string>
+ <string name="settings_category_sort_least_items">Least Items First</string>
+ <string name="settings_category_type_live_description">Sort and hide provider live groups while keeping All Channels, Favorites, Recent, and custom groups in their pinned positions.</string>
+ <string name="settings_category_type_movies_description">Sort and hide provider movie categories without affecting Favorites, Resume, or custom shelves.</string>
+ <string name="settings_category_type_series_description">Sort and hide provider series categories without affecting Favorites, Continue Watching, or custom shelves.</string>
+ <string name="settings_live_channel_numbering_mode">Live TV Channel Numbering</string>
+ <string name="settings_live_channel_numbering_mode_subtitle">Choose whether live channels use their position in the current group or keep the original numbers from the provider.</string>
+ <string name="settings_live_channel_numbering_group">Per Group</string>
+ <string name="settings_live_channel_numbering_group_desc">Default behavior. Renumber channels based on their position inside the current category or custom group.</string>
+ <string name="settings_live_channel_numbering_provider">Provider Number</string>
+ <string name="settings_live_channel_numbering_provider_desc">Keep the original channel number supplied by the playlist provider whenever it exists.</string>
+ <string name="settings_vod_view_mode">VOD layout</string>
+ <string name="settings_vod_view_mode_subtitle">Choose between the modern shelves view and a classic split layout.</string>
+ <string name="settings_vod_view_mode_modern">Modern</string>
+ <string name="settings_vod_view_mode_modern_desc">Shelf-based browsing with featured rows and category previews.</string>
+ <string name="settings_vod_view_mode_classic">Classic</string>
+ <string name="settings_vod_view_mode_classic_desc">Category list on the left with a stacked poster grid on the right.</string>
+ <string name="vod_classic_categories_title">Categories</string>
+ <string name="vod_classic_category_search">Search in categories</string>
+ <string name="vod_classic_all">All</string>
+ <string name="vod_classic_continue_watching">Continue Watching</string>
+ <string name="vod_classic_recently_added">Recently Added</string>
+ <string name="vod_classic_results_count">%1$d items</string>
+ <string name="vod_classic_empty_category">No titles found in this section.</string>
+ <string name="epg_no_schedule_short">No schedule</string>
+ <string name="epg_show_app_navigation">Show App Nav</string>
+ <string name="epg_program_details_show">Program Details</string>
+ <string name="epg_program_details_hide">Hide Details</string>
+ <string name="epg_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_short">Categories</string>
+ <string name="epg_search_short">Program Search</string>
+ <string name="epg_options_short">Options</string>
+ <string name="epg_schedule_summary_short">%1$d/%2$d with guide</string>
+ <string name="epg_stale_short">Guide may be stale</string>
+ <string name="settings_category_mode_protection">Lock / Unlock</string>
+ <string name="settings_category_mode_visibility">Hide / Unhide</string>
+ <string name="settings_category_protection_summary_title">Lock changes are reviewed before they go live</string>
+ <string name="settings_category_protection_summary_body">Toggle the categories you want to lock or unlock, then save. Saving requires your parental PIN.</string>
+ <string name="settings_category_protection_summary_body_no_pin">Toggle the categories you want to lock or unlock, then save. You will be asked to create a parental PIN before the changes are applied.</string>
+ <string name="settings_category_protection_save">Save Locks (%1$d)</string>
+ <string name="settings_category_protection_save_idle">Save Locks</string>
+ <string name="settings_category_protection_reset">Reset</string>
+ <string name="settings_category_visibility_summary_title">Visibility changes apply immediately</string>
+ <string name="settings_category_visibility_summary_body">%1$d categories are currently hidden for this playlist. Hiding and restoring does not require a PIN.</string>
+ <string name="settings_category_status_locked">Locked</string>
+ <string name="settings_category_status_unlocked">Unlocked</string>
+ <string name="settings_category_status_auto_locked">Auto-Locked</string>
+ <string name="settings_category_status_hidden">Hidden</string>
+ <string name="settings_category_controls_empty">No categories match this search.</string>
+ <string name="movie_loading_details">Loading details...</string>
+ <string name="movie_not_found">Movie not found</string>
+ <string name="movie_detail_back">Back to library</string>
+ <string name="movie_detail_play">Play</string>
+ <string name="movie_detail_trailer">Trailer</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>
+ <string name="movie_detail_duration">Duration:</string>
+ <string name="movie_detail_genre">Genre:</string>
+ <string name="movie_detail_cast">Cast:</string>
+ <string name="movie_detail_unknown">Unknown</string>
</resources>
diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml
index 25ebd9e1..54d6cff1 100644
--- a/app/src/main/res/values-ru/strings.xml
+++ b/app/src/main/res/values-ru/strings.xml
@@ -868,4 +868,89 @@
<string name="settings_history_cleared">История просмотров и последние события очищены.</string>
<string name="settings_pin_changed">PIN-код успешно сохранен</string>
<string name="home_reorder_channels">Изменение порядка каналов</string>
+ <!-- Synced fallback strings from English -->
+ <string name="category_options_hide">Hide Category</string>
+ <string name="settings_provider_category_controls_action">Category Controls</string>
+ <string name="settings_provider_category_controls_title">Category Controls</string>
+ <string name="settings_provider_category_controls_subtitle">Lock, unlock, hide, and restore categories for the current playlist from one place.</string>
+ <string name="settings_provider_category_controls_search">Search categories...</string>
+ <string name="settings_categories_title">Category Preferences</string>
+ <string name="settings_categories_subtitle">Hide provider categories and keep their sort order exactly how you want it.</string>
+ <string name="settings_category_sorting_title">Category Sorting</string>
+ <string name="settings_category_sorting_subtitle">Sort categories for the active playlist. Locking and hiding now live in Category Controls.</string>
+ <string name="settings_category_sort_live">Live TV Categories</string>
+ <string name="settings_category_sort_movies">Movie Categories</string>
+ <string name="settings_category_sort_series">Series Categories</string>
+ <string name="settings_hidden_categories_title">Hidden Categories</string>
+ <string name="settings_hidden_categories_subtitle">Restore any provider categories you previously hid from browsing surfaces.</string>
+ <string name="settings_hidden_categories_none">None hidden</string>
+ <string name="settings_hidden_categories_count">%1$d hidden</string>
+ <string name="settings_hidden_categories_empty">No hidden categories right now.</string>
+ <string name="settings_unhide_category">Unhide</string>
+ <string name="settings_hide_category">Hide</string>
+ <string name="settings_category_sort_default">Provider Order</string>
+ <string name="settings_category_sort_az">A-Z</string>
+ <string name="settings_category_sort_za">Z-A</string>
+ <string name="settings_category_sort_most_items">Most Items First</string>
+ <string name="settings_category_sort_least_items">Least Items First</string>
+ <string name="settings_category_type_live_description">Sort and hide provider live groups while keeping All Channels, Favorites, Recent, and custom groups in their pinned positions.</string>
+ <string name="settings_category_type_movies_description">Sort and hide provider movie categories without affecting Favorites, Resume, or custom shelves.</string>
+ <string name="settings_category_type_series_description">Sort and hide provider series categories without affecting Favorites, Continue Watching, or custom shelves.</string>
+ <string name="settings_live_channel_numbering_mode">Live TV Channel Numbering</string>
+ <string name="settings_live_channel_numbering_mode_subtitle">Choose whether live channels use their position in the current group or keep the original numbers from the provider.</string>
+ <string name="settings_live_channel_numbering_group">Per Group</string>
+ <string name="settings_live_channel_numbering_group_desc">Default behavior. Renumber channels based on their position inside the current category or custom group.</string>
+ <string name="settings_live_channel_numbering_provider">Provider Number</string>
+ <string name="settings_live_channel_numbering_provider_desc">Keep the original channel number supplied by the playlist provider whenever it exists.</string>
+ <string name="settings_vod_view_mode">VOD layout</string>
+ <string name="settings_vod_view_mode_subtitle">Choose between the modern shelves view and a classic split layout.</string>
+ <string name="settings_vod_view_mode_modern">Modern</string>
+ <string name="settings_vod_view_mode_modern_desc">Shelf-based browsing with featured rows and category previews.</string>
+ <string name="settings_vod_view_mode_classic">Classic</string>
+ <string name="settings_vod_view_mode_classic_desc">Category list on the left with a stacked poster grid on the right.</string>
+ <string name="vod_classic_categories_title">Categories</string>
+ <string name="vod_classic_category_search">Search in categories</string>
+ <string name="vod_classic_all">All</string>
+ <string name="vod_classic_continue_watching">Continue Watching</string>
+ <string name="vod_classic_recently_added">Recently Added</string>
+ <string name="vod_classic_results_count">%1$d items</string>
+ <string name="vod_classic_empty_category">No titles found in this section.</string>
+ <string name="epg_no_schedule_short">No schedule</string>
+ <string name="epg_show_app_navigation">Show App Nav</string>
+ <string name="epg_program_details_show">Program Details</string>
+ <string name="epg_program_details_hide">Hide Details</string>
+ <string name="epg_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_short">Categories</string>
+ <string name="epg_search_short">Program Search</string>
+ <string name="epg_options_short">Options</string>
+ <string name="epg_schedule_summary_short">%1$d/%2$d with guide</string>
+ <string name="epg_stale_short">Guide may be stale</string>
+ <string name="settings_category_mode_protection">Lock / Unlock</string>
+ <string name="settings_category_mode_visibility">Hide / Unhide</string>
+ <string name="settings_category_protection_summary_title">Lock changes are reviewed before they go live</string>
+ <string name="settings_category_protection_summary_body">Toggle the categories you want to lock or unlock, then save. Saving requires your parental PIN.</string>
+ <string name="settings_category_protection_summary_body_no_pin">Toggle the categories you want to lock or unlock, then save. You will be asked to create a parental PIN before the changes are applied.</string>
+ <string name="settings_category_protection_save">Save Locks (%1$d)</string>
+ <string name="settings_category_protection_save_idle">Save Locks</string>
+ <string name="settings_category_protection_reset">Reset</string>
+ <string name="settings_category_visibility_summary_title">Visibility changes apply immediately</string>
+ <string name="settings_category_visibility_summary_body">%1$d categories are currently hidden for this playlist. Hiding and restoring does not require a PIN.</string>
+ <string name="settings_category_status_locked">Locked</string>
+ <string name="settings_category_status_unlocked">Unlocked</string>
+ <string name="settings_category_status_auto_locked">Auto-Locked</string>
+ <string name="settings_category_status_hidden">Hidden</string>
+ <string name="settings_category_controls_empty">No categories match this search.</string>
+ <string name="movie_loading_details">Loading details...</string>
+ <string name="movie_not_found">Movie not found</string>
+ <string name="movie_detail_back">Back to library</string>
+ <string name="movie_detail_play">Play</string>
+ <string name="movie_detail_trailer">Trailer</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>
+ <string name="movie_detail_duration">Duration:</string>
+ <string name="movie_detail_genre">Genre:</string>
+ <string name="movie_detail_cast">Cast:</string>
+ <string name="movie_detail_unknown">Unknown</string>
</resources>
diff --git a/app/src/main/res/values-sv/strings.xml b/app/src/main/res/values-sv/strings.xml
index a4463c11..62044783 100644
--- a/app/src/main/res/values-sv/strings.xml
+++ b/app/src/main/res/values-sv/strings.xml
@@ -868,4 +868,89 @@
<string name="settings_history_cleared">Visningshistorik och senaste rensade</string>
<string name="settings_pin_changed">PIN-koden har sparats</string>
<string name="home_reorder_channels">Ordna om kanaler</string>
+ <!-- Synced fallback strings from English -->
+ <string name="category_options_hide">Hide Category</string>
+ <string name="settings_provider_category_controls_action">Category Controls</string>
+ <string name="settings_provider_category_controls_title">Category Controls</string>
+ <string name="settings_provider_category_controls_subtitle">Lock, unlock, hide, and restore categories for the current playlist from one place.</string>
+ <string name="settings_provider_category_controls_search">Search categories...</string>
+ <string name="settings_categories_title">Category Preferences</string>
+ <string name="settings_categories_subtitle">Hide provider categories and keep their sort order exactly how you want it.</string>
+ <string name="settings_category_sorting_title">Category Sorting</string>
+ <string name="settings_category_sorting_subtitle">Sort categories for the active playlist. Locking and hiding now live in Category Controls.</string>
+ <string name="settings_category_sort_live">Live TV Categories</string>
+ <string name="settings_category_sort_movies">Movie Categories</string>
+ <string name="settings_category_sort_series">Series Categories</string>
+ <string name="settings_hidden_categories_title">Hidden Categories</string>
+ <string name="settings_hidden_categories_subtitle">Restore any provider categories you previously hid from browsing surfaces.</string>
+ <string name="settings_hidden_categories_none">None hidden</string>
+ <string name="settings_hidden_categories_count">%1$d hidden</string>
+ <string name="settings_hidden_categories_empty">No hidden categories right now.</string>
+ <string name="settings_unhide_category">Unhide</string>
+ <string name="settings_hide_category">Hide</string>
+ <string name="settings_category_sort_default">Provider Order</string>
+ <string name="settings_category_sort_az">A-Z</string>
+ <string name="settings_category_sort_za">Z-A</string>
+ <string name="settings_category_sort_most_items">Most Items First</string>
+ <string name="settings_category_sort_least_items">Least Items First</string>
+ <string name="settings_category_type_live_description">Sort and hide provider live groups while keeping All Channels, Favorites, Recent, and custom groups in their pinned positions.</string>
+ <string name="settings_category_type_movies_description">Sort and hide provider movie categories without affecting Favorites, Resume, or custom shelves.</string>
+ <string name="settings_category_type_series_description">Sort and hide provider series categories without affecting Favorites, Continue Watching, or custom shelves.</string>
+ <string name="settings_live_channel_numbering_mode">Live TV Channel Numbering</string>
+ <string name="settings_live_channel_numbering_mode_subtitle">Choose whether live channels use their position in the current group or keep the original numbers from the provider.</string>
+ <string name="settings_live_channel_numbering_group">Per Group</string>
+ <string name="settings_live_channel_numbering_group_desc">Default behavior. Renumber channels based on their position inside the current category or custom group.</string>
+ <string name="settings_live_channel_numbering_provider">Provider Number</string>
+ <string name="settings_live_channel_numbering_provider_desc">Keep the original channel number supplied by the playlist provider whenever it exists.</string>
+ <string name="settings_vod_view_mode">VOD layout</string>
+ <string name="settings_vod_view_mode_subtitle">Choose between the modern shelves view and a classic split layout.</string>
+ <string name="settings_vod_view_mode_modern">Modern</string>
+ <string name="settings_vod_view_mode_modern_desc">Shelf-based browsing with featured rows and category previews.</string>
+ <string name="settings_vod_view_mode_classic">Classic</string>
+ <string name="settings_vod_view_mode_classic_desc">Category list on the left with a stacked poster grid on the right.</string>
+ <string name="vod_classic_categories_title">Categories</string>
+ <string name="vod_classic_category_search">Search in categories</string>
+ <string name="vod_classic_all">All</string>
+ <string name="vod_classic_continue_watching">Continue Watching</string>
+ <string name="vod_classic_recently_added">Recently Added</string>
+ <string name="vod_classic_results_count">%1$d items</string>
+ <string name="vod_classic_empty_category">No titles found in this section.</string>
+ <string name="epg_no_schedule_short">No schedule</string>
+ <string name="epg_show_app_navigation">Show App Nav</string>
+ <string name="epg_program_details_show">Program Details</string>
+ <string name="epg_program_details_hide">Hide Details</string>
+ <string name="epg_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_short">Categories</string>
+ <string name="epg_search_short">Program Search</string>
+ <string name="epg_options_short">Options</string>
+ <string name="epg_schedule_summary_short">%1$d/%2$d with guide</string>
+ <string name="epg_stale_short">Guide may be stale</string>
+ <string name="settings_category_mode_protection">Lock / Unlock</string>
+ <string name="settings_category_mode_visibility">Hide / Unhide</string>
+ <string name="settings_category_protection_summary_title">Lock changes are reviewed before they go live</string>
+ <string name="settings_category_protection_summary_body">Toggle the categories you want to lock or unlock, then save. Saving requires your parental PIN.</string>
+ <string name="settings_category_protection_summary_body_no_pin">Toggle the categories you want to lock or unlock, then save. You will be asked to create a parental PIN before the changes are applied.</string>
+ <string name="settings_category_protection_save">Save Locks (%1$d)</string>
+ <string name="settings_category_protection_save_idle">Save Locks</string>
+ <string name="settings_category_protection_reset">Reset</string>
+ <string name="settings_category_visibility_summary_title">Visibility changes apply immediately</string>
+ <string name="settings_category_visibility_summary_body">%1$d categories are currently hidden for this playlist. Hiding and restoring does not require a PIN.</string>
+ <string name="settings_category_status_locked">Locked</string>
+ <string name="settings_category_status_unlocked">Unlocked</string>
+ <string name="settings_category_status_auto_locked">Auto-Locked</string>
+ <string name="settings_category_status_hidden">Hidden</string>
+ <string name="settings_category_controls_empty">No categories match this search.</string>
+ <string name="movie_loading_details">Loading details...</string>
+ <string name="movie_not_found">Movie not found</string>
+ <string name="movie_detail_back">Back to library</string>
+ <string name="movie_detail_play">Play</string>
+ <string name="movie_detail_trailer">Trailer</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>
+ <string name="movie_detail_duration">Duration:</string>
+ <string name="movie_detail_genre">Genre:</string>
+ <string name="movie_detail_cast">Cast:</string>
+ <string name="movie_detail_unknown">Unknown</string>
</resources>
diff --git a/app/src/main/res/values-tr/strings.xml b/app/src/main/res/values-tr/strings.xml
index f4133f8d..261cb1e0 100644
--- a/app/src/main/res/values-tr/strings.xml
+++ b/app/src/main/res/values-tr/strings.xml
@@ -868,4 +868,89 @@
<string name="settings_history_cleared">İzleme geçmişi ve son izlemeler temizlendi</string>
<string name="settings_pin_changed">PIN başarıyla kaydedildi</string>
<string name="home_reorder_channels">Kanalları Yeniden Sırala</string>
+ <!-- Synced fallback strings from English -->
+ <string name="category_options_hide">Hide Category</string>
+ <string name="settings_provider_category_controls_action">Category Controls</string>
+ <string name="settings_provider_category_controls_title">Category Controls</string>
+ <string name="settings_provider_category_controls_subtitle">Lock, unlock, hide, and restore categories for the current playlist from one place.</string>
+ <string name="settings_provider_category_controls_search">Search categories...</string>
+ <string name="settings_categories_title">Category Preferences</string>
+ <string name="settings_categories_subtitle">Hide provider categories and keep their sort order exactly how you want it.</string>
+ <string name="settings_category_sorting_title">Category Sorting</string>
+ <string name="settings_category_sorting_subtitle">Sort categories for the active playlist. Locking and hiding now live in Category Controls.</string>
+ <string name="settings_category_sort_live">Live TV Categories</string>
+ <string name="settings_category_sort_movies">Movie Categories</string>
+ <string name="settings_category_sort_series">Series Categories</string>
+ <string name="settings_hidden_categories_title">Hidden Categories</string>
+ <string name="settings_hidden_categories_subtitle">Restore any provider categories you previously hid from browsing surfaces.</string>
+ <string name="settings_hidden_categories_none">None hidden</string>
+ <string name="settings_hidden_categories_count">%1$d hidden</string>
+ <string name="settings_hidden_categories_empty">No hidden categories right now.</string>
+ <string name="settings_unhide_category">Unhide</string>
+ <string name="settings_hide_category">Hide</string>
+ <string name="settings_category_sort_default">Provider Order</string>
+ <string name="settings_category_sort_az">A-Z</string>
+ <string name="settings_category_sort_za">Z-A</string>
+ <string name="settings_category_sort_most_items">Most Items First</string>
+ <string name="settings_category_sort_least_items">Least Items First</string>
+ <string name="settings_category_type_live_description">Sort and hide provider live groups while keeping All Channels, Favorites, Recent, and custom groups in their pinned positions.</string>
+ <string name="settings_category_type_movies_description">Sort and hide provider movie categories without affecting Favorites, Resume, or custom shelves.</string>
+ <string name="settings_category_type_series_description">Sort and hide provider series categories without affecting Favorites, Continue Watching, or custom shelves.</string>
+ <string name="settings_live_channel_numbering_mode">Live TV Channel Numbering</string>
+ <string name="settings_live_channel_numbering_mode_subtitle">Choose whether live channels use their position in the current group or keep the original numbers from the provider.</string>
+ <string name="settings_live_channel_numbering_group">Per Group</string>
+ <string name="settings_live_channel_numbering_group_desc">Default behavior. Renumber channels based on their position inside the current category or custom group.</string>
+ <string name="settings_live_channel_numbering_provider">Provider Number</string>
+ <string name="settings_live_channel_numbering_provider_desc">Keep the original channel number supplied by the playlist provider whenever it exists.</string>
+ <string name="settings_vod_view_mode">VOD layout</string>
+ <string name="settings_vod_view_mode_subtitle">Choose between the modern shelves view and a classic split layout.</string>
+ <string name="settings_vod_view_mode_modern">Modern</string>
+ <string name="settings_vod_view_mode_modern_desc">Shelf-based browsing with featured rows and category previews.</string>
+ <string name="settings_vod_view_mode_classic">Classic</string>
+ <string name="settings_vod_view_mode_classic_desc">Category list on the left with a stacked poster grid on the right.</string>
+ <string name="vod_classic_categories_title">Categories</string>
+ <string name="vod_classic_category_search">Search in categories</string>
+ <string name="vod_classic_all">All</string>
+ <string name="vod_classic_continue_watching">Continue Watching</string>
+ <string name="vod_classic_recently_added">Recently Added</string>
+ <string name="vod_classic_results_count">%1$d items</string>
+ <string name="vod_classic_empty_category">No titles found in this section.</string>
+ <string name="epg_no_schedule_short">No schedule</string>
+ <string name="epg_show_app_navigation">Show App Nav</string>
+ <string name="epg_program_details_show">Program Details</string>
+ <string name="epg_program_details_hide">Hide Details</string>
+ <string name="epg_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_short">Categories</string>
+ <string name="epg_search_short">Program Search</string>
+ <string name="epg_options_short">Options</string>
+ <string name="epg_schedule_summary_short">%1$d/%2$d with guide</string>
+ <string name="epg_stale_short">Guide may be stale</string>
+ <string name="settings_category_mode_protection">Lock / Unlock</string>
+ <string name="settings_category_mode_visibility">Hide / Unhide</string>
+ <string name="settings_category_protection_summary_title">Lock changes are reviewed before they go live</string>
+ <string name="settings_category_protection_summary_body">Toggle the categories you want to lock or unlock, then save. Saving requires your parental PIN.</string>
+ <string name="settings_category_protection_summary_body_no_pin">Toggle the categories you want to lock or unlock, then save. You will be asked to create a parental PIN before the changes are applied.</string>
+ <string name="settings_category_protection_save">Save Locks (%1$d)</string>
+ <string name="settings_category_protection_save_idle">Save Locks</string>
+ <string name="settings_category_protection_reset">Reset</string>
+ <string name="settings_category_visibility_summary_title">Visibility changes apply immediately</string>
+ <string name="settings_category_visibility_summary_body">%1$d categories are currently hidden for this playlist. Hiding and restoring does not require a PIN.</string>
+ <string name="settings_category_status_locked">Locked</string>
+ <string name="settings_category_status_unlocked">Unlocked</string>
+ <string name="settings_category_status_auto_locked">Auto-Locked</string>
+ <string name="settings_category_status_hidden">Hidden</string>
+ <string name="settings_category_controls_empty">No categories match this search.</string>
+ <string name="movie_loading_details">Loading details...</string>
+ <string name="movie_not_found">Movie not found</string>
+ <string name="movie_detail_back">Back to library</string>
+ <string name="movie_detail_play">Play</string>
+ <string name="movie_detail_trailer">Trailer</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>
+ <string name="movie_detail_duration">Duration:</string>
+ <string name="movie_detail_genre">Genre:</string>
+ <string name="movie_detail_cast">Cast:</string>
+ <string name="movie_detail_unknown">Unknown</string>
</resources>
diff --git a/app/src/main/res/values-uk/strings.xml b/app/src/main/res/values-uk/strings.xml
index 92427dea..3617b2c3 100644
--- a/app/src/main/res/values-uk/strings.xml
+++ b/app/src/main/res/values-uk/strings.xml
@@ -868,4 +868,89 @@
<string name="settings_history_cleared">Історію та останні перегляди очищено</string>
<string name="settings_pin_changed">PIN-код успішно збережено</string>
<string name="home_reorder_channels">Змінити порядок каналів</string>
+ <!-- Synced fallback strings from English -->
+ <string name="category_options_hide">Hide Category</string>
+ <string name="settings_provider_category_controls_action">Category Controls</string>
+ <string name="settings_provider_category_controls_title">Category Controls</string>
+ <string name="settings_provider_category_controls_subtitle">Lock, unlock, hide, and restore categories for the current playlist from one place.</string>
+ <string name="settings_provider_category_controls_search">Search categories...</string>
+ <string name="settings_categories_title">Category Preferences</string>
+ <string name="settings_categories_subtitle">Hide provider categories and keep their sort order exactly how you want it.</string>
+ <string name="settings_category_sorting_title">Category Sorting</string>
+ <string name="settings_category_sorting_subtitle">Sort categories for the active playlist. Locking and hiding now live in Category Controls.</string>
+ <string name="settings_category_sort_live">Live TV Categories</string>
+ <string name="settings_category_sort_movies">Movie Categories</string>
+ <string name="settings_category_sort_series">Series Categories</string>
+ <string name="settings_hidden_categories_title">Hidden Categories</string>
+ <string name="settings_hidden_categories_subtitle">Restore any provider categories you previously hid from browsing surfaces.</string>
+ <string name="settings_hidden_categories_none">None hidden</string>
+ <string name="settings_hidden_categories_count">%1$d hidden</string>
+ <string name="settings_hidden_categories_empty">No hidden categories right now.</string>
+ <string name="settings_unhide_category">Unhide</string>
+ <string name="settings_hide_category">Hide</string>
+ <string name="settings_category_sort_default">Provider Order</string>
+ <string name="settings_category_sort_az">A-Z</string>
+ <string name="settings_category_sort_za">Z-A</string>
+ <string name="settings_category_sort_most_items">Most Items First</string>
+ <string name="settings_category_sort_least_items">Least Items First</string>
+ <string name="settings_category_type_live_description">Sort and hide provider live groups while keeping All Channels, Favorites, Recent, and custom groups in their pinned positions.</string>
+ <string name="settings_category_type_movies_description">Sort and hide provider movie categories without affecting Favorites, Resume, or custom shelves.</string>
+ <string name="settings_category_type_series_description">Sort and hide provider series categories without affecting Favorites, Continue Watching, or custom shelves.</string>
+ <string name="settings_live_channel_numbering_mode">Live TV Channel Numbering</string>
+ <string name="settings_live_channel_numbering_mode_subtitle">Choose whether live channels use their position in the current group or keep the original numbers from the provider.</string>
+ <string name="settings_live_channel_numbering_group">Per Group</string>
+ <string name="settings_live_channel_numbering_group_desc">Default behavior. Renumber channels based on their position inside the current category or custom group.</string>
+ <string name="settings_live_channel_numbering_provider">Provider Number</string>
+ <string name="settings_live_channel_numbering_provider_desc">Keep the original channel number supplied by the playlist provider whenever it exists.</string>
+ <string name="settings_vod_view_mode">VOD layout</string>
+ <string name="settings_vod_view_mode_subtitle">Choose between the modern shelves view and a classic split layout.</string>
+ <string name="settings_vod_view_mode_modern">Modern</string>
+ <string name="settings_vod_view_mode_modern_desc">Shelf-based browsing with featured rows and category previews.</string>
+ <string name="settings_vod_view_mode_classic">Classic</string>
+ <string name="settings_vod_view_mode_classic_desc">Category list on the left with a stacked poster grid on the right.</string>
+ <string name="vod_classic_categories_title">Categories</string>
+ <string name="vod_classic_category_search">Search in categories</string>
+ <string name="vod_classic_all">All</string>
+ <string name="vod_classic_continue_watching">Continue Watching</string>
+ <string name="vod_classic_recently_added">Recently Added</string>
+ <string name="vod_classic_results_count">%1$d items</string>
+ <string name="vod_classic_empty_category">No titles found in this section.</string>
+ <string name="epg_no_schedule_short">No schedule</string>
+ <string name="epg_show_app_navigation">Show App Nav</string>
+ <string name="epg_program_details_show">Program Details</string>
+ <string name="epg_program_details_hide">Hide Details</string>
+ <string name="epg_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_short">Categories</string>
+ <string name="epg_search_short">Program Search</string>
+ <string name="epg_options_short">Options</string>
+ <string name="epg_schedule_summary_short">%1$d/%2$d with guide</string>
+ <string name="epg_stale_short">Guide may be stale</string>
+ <string name="settings_category_mode_protection">Lock / Unlock</string>
+ <string name="settings_category_mode_visibility">Hide / Unhide</string>
+ <string name="settings_category_protection_summary_title">Lock changes are reviewed before they go live</string>
+ <string name="settings_category_protection_summary_body">Toggle the categories you want to lock or unlock, then save. Saving requires your parental PIN.</string>
+ <string name="settings_category_protection_summary_body_no_pin">Toggle the categories you want to lock or unlock, then save. You will be asked to create a parental PIN before the changes are applied.</string>
+ <string name="settings_category_protection_save">Save Locks (%1$d)</string>
+ <string name="settings_category_protection_save_idle">Save Locks</string>
+ <string name="settings_category_protection_reset">Reset</string>
+ <string name="settings_category_visibility_summary_title">Visibility changes apply immediately</string>
+ <string name="settings_category_visibility_summary_body">%1$d categories are currently hidden for this playlist. Hiding and restoring does not require a PIN.</string>
+ <string name="settings_category_status_locked">Locked</string>
+ <string name="settings_category_status_unlocked">Unlocked</string>
+ <string name="settings_category_status_auto_locked">Auto-Locked</string>
+ <string name="settings_category_status_hidden">Hidden</string>
+ <string name="settings_category_controls_empty">No categories match this search.</string>
+ <string name="movie_loading_details">Loading details...</string>
+ <string name="movie_not_found">Movie not found</string>
+ <string name="movie_detail_back">Back to library</string>
+ <string name="movie_detail_play">Play</string>
+ <string name="movie_detail_trailer">Trailer</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>
+ <string name="movie_detail_duration">Duration:</string>
+ <string name="movie_detail_genre">Genre:</string>
+ <string name="movie_detail_cast">Cast:</string>
+ <string name="movie_detail_unknown">Unknown</string>
</resources>
diff --git a/app/src/main/res/values-vi/strings.xml b/app/src/main/res/values-vi/strings.xml
index 9d51198b..93d79ccb 100644
--- a/app/src/main/res/values-vi/strings.xml
+++ b/app/src/main/res/values-vi/strings.xml
@@ -868,4 +868,89 @@
<string name="settings_history_cleared">Đã xóa lịch sử xem và gần đây</string>
<string name="settings_pin_changed">Đã lưu mã PIN thành công</string>
<string name="home_reorder_channels">Sắp xếp lại kênh</string>
+ <!-- Synced fallback strings from English -->
+ <string name="category_options_hide">Hide Category</string>
+ <string name="settings_provider_category_controls_action">Category Controls</string>
+ <string name="settings_provider_category_controls_title">Category Controls</string>
+ <string name="settings_provider_category_controls_subtitle">Lock, unlock, hide, and restore categories for the current playlist from one place.</string>
+ <string name="settings_provider_category_controls_search">Search categories...</string>
+ <string name="settings_categories_title">Category Preferences</string>
+ <string name="settings_categories_subtitle">Hide provider categories and keep their sort order exactly how you want it.</string>
+ <string name="settings_category_sorting_title">Category Sorting</string>
+ <string name="settings_category_sorting_subtitle">Sort categories for the active playlist. Locking and hiding now live in Category Controls.</string>
+ <string name="settings_category_sort_live">Live TV Categories</string>
+ <string name="settings_category_sort_movies">Movie Categories</string>
+ <string name="settings_category_sort_series">Series Categories</string>
+ <string name="settings_hidden_categories_title">Hidden Categories</string>
+ <string name="settings_hidden_categories_subtitle">Restore any provider categories you previously hid from browsing surfaces.</string>
+ <string name="settings_hidden_categories_none">None hidden</string>
+ <string name="settings_hidden_categories_count">%1$d hidden</string>
+ <string name="settings_hidden_categories_empty">No hidden categories right now.</string>
+ <string name="settings_unhide_category">Unhide</string>
+ <string name="settings_hide_category">Hide</string>
+ <string name="settings_category_sort_default">Provider Order</string>
+ <string name="settings_category_sort_az">A-Z</string>
+ <string name="settings_category_sort_za">Z-A</string>
+ <string name="settings_category_sort_most_items">Most Items First</string>
+ <string name="settings_category_sort_least_items">Least Items First</string>
+ <string name="settings_category_type_live_description">Sort and hide provider live groups while keeping All Channels, Favorites, Recent, and custom groups in their pinned positions.</string>
+ <string name="settings_category_type_movies_description">Sort and hide provider movie categories without affecting Favorites, Resume, or custom shelves.</string>
+ <string name="settings_category_type_series_description">Sort and hide provider series categories without affecting Favorites, Continue Watching, or custom shelves.</string>
+ <string name="settings_live_channel_numbering_mode">Live TV Channel Numbering</string>
+ <string name="settings_live_channel_numbering_mode_subtitle">Choose whether live channels use their position in the current group or keep the original numbers from the provider.</string>
+ <string name="settings_live_channel_numbering_group">Per Group</string>
+ <string name="settings_live_channel_numbering_group_desc">Default behavior. Renumber channels based on their position inside the current category or custom group.</string>
+ <string name="settings_live_channel_numbering_provider">Provider Number</string>
+ <string name="settings_live_channel_numbering_provider_desc">Keep the original channel number supplied by the playlist provider whenever it exists.</string>
+ <string name="settings_vod_view_mode">VOD layout</string>
+ <string name="settings_vod_view_mode_subtitle">Choose between the modern shelves view and a classic split layout.</string>
+ <string name="settings_vod_view_mode_modern">Modern</string>
+ <string name="settings_vod_view_mode_modern_desc">Shelf-based browsing with featured rows and category previews.</string>
+ <string name="settings_vod_view_mode_classic">Classic</string>
+ <string name="settings_vod_view_mode_classic_desc">Category list on the left with a stacked poster grid on the right.</string>
+ <string name="vod_classic_categories_title">Categories</string>
+ <string name="vod_classic_category_search">Search in categories</string>
+ <string name="vod_classic_all">All</string>
+ <string name="vod_classic_continue_watching">Continue Watching</string>
+ <string name="vod_classic_recently_added">Recently Added</string>
+ <string name="vod_classic_results_count">%1$d items</string>
+ <string name="vod_classic_empty_category">No titles found in this section.</string>
+ <string name="epg_no_schedule_short">No schedule</string>
+ <string name="epg_show_app_navigation">Show App Nav</string>
+ <string name="epg_program_details_show">Program Details</string>
+ <string name="epg_program_details_hide">Hide Details</string>
+ <string name="epg_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_short">Categories</string>
+ <string name="epg_search_short">Program Search</string>
+ <string name="epg_options_short">Options</string>
+ <string name="epg_schedule_summary_short">%1$d/%2$d with guide</string>
+ <string name="epg_stale_short">Guide may be stale</string>
+ <string name="settings_category_mode_protection">Lock / Unlock</string>
+ <string name="settings_category_mode_visibility">Hide / Unhide</string>
+ <string name="settings_category_protection_summary_title">Lock changes are reviewed before they go live</string>
+ <string name="settings_category_protection_summary_body">Toggle the categories you want to lock or unlock, then save. Saving requires your parental PIN.</string>
+ <string name="settings_category_protection_summary_body_no_pin">Toggle the categories you want to lock or unlock, then save. You will be asked to create a parental PIN before the changes are applied.</string>
+ <string name="settings_category_protection_save">Save Locks (%1$d)</string>
+ <string name="settings_category_protection_save_idle">Save Locks</string>
+ <string name="settings_category_protection_reset">Reset</string>
+ <string name="settings_category_visibility_summary_title">Visibility changes apply immediately</string>
+ <string name="settings_category_visibility_summary_body">%1$d categories are currently hidden for this playlist. Hiding and restoring does not require a PIN.</string>
+ <string name="settings_category_status_locked">Locked</string>
+ <string name="settings_category_status_unlocked">Unlocked</string>
+ <string name="settings_category_status_auto_locked">Auto-Locked</string>
+ <string name="settings_category_status_hidden">Hidden</string>
+ <string name="settings_category_controls_empty">No categories match this search.</string>
+ <string name="movie_loading_details">Loading details...</string>
+ <string name="movie_not_found">Movie not found</string>
+ <string name="movie_detail_back">Back to library</string>
+ <string name="movie_detail_play">Play</string>
+ <string name="movie_detail_trailer">Trailer</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>
+ <string name="movie_detail_duration">Duration:</string>
+ <string name="movie_detail_genre">Genre:</string>
+ <string name="movie_detail_cast">Cast:</string>
+ <string name="movie_detail_unknown">Unknown</string>
</resources>
diff --git a/app/src/main/res/values-zh/strings.xml b/app/src/main/res/values-zh/strings.xml
index 8b1a4c1e..caf7ae83 100644
--- a/app/src/main/res/values-zh/strings.xml
+++ b/app/src/main/res/values-zh/strings.xml
@@ -868,4 +868,89 @@
<string name="settings_history_cleared">观看历史记录和最近观看记录已清除</string>
<string name="settings_pin_changed">PIN 码保存成功</string>
<string name="home_reorder_channels">重新排序频道</string>
+ <!-- Synced fallback strings from English -->
+ <string name="category_options_hide">Hide Category</string>
+ <string name="settings_provider_category_controls_action">Category Controls</string>
+ <string name="settings_provider_category_controls_title">Category Controls</string>
+ <string name="settings_provider_category_controls_subtitle">Lock, unlock, hide, and restore categories for the current playlist from one place.</string>
+ <string name="settings_provider_category_controls_search">Search categories...</string>
+ <string name="settings_categories_title">Category Preferences</string>
+ <string name="settings_categories_subtitle">Hide provider categories and keep their sort order exactly how you want it.</string>
+ <string name="settings_category_sorting_title">Category Sorting</string>
+ <string name="settings_category_sorting_subtitle">Sort categories for the active playlist. Locking and hiding now live in Category Controls.</string>
+ <string name="settings_category_sort_live">Live TV Categories</string>
+ <string name="settings_category_sort_movies">Movie Categories</string>
+ <string name="settings_category_sort_series">Series Categories</string>
+ <string name="settings_hidden_categories_title">Hidden Categories</string>
+ <string name="settings_hidden_categories_subtitle">Restore any provider categories you previously hid from browsing surfaces.</string>
+ <string name="settings_hidden_categories_none">None hidden</string>
+ <string name="settings_hidden_categories_count">%1$d hidden</string>
+ <string name="settings_hidden_categories_empty">No hidden categories right now.</string>
+ <string name="settings_unhide_category">Unhide</string>
+ <string name="settings_hide_category">Hide</string>
+ <string name="settings_category_sort_default">Provider Order</string>
+ <string name="settings_category_sort_az">A-Z</string>
+ <string name="settings_category_sort_za">Z-A</string>
+ <string name="settings_category_sort_most_items">Most Items First</string>
+ <string name="settings_category_sort_least_items">Least Items First</string>
+ <string name="settings_category_type_live_description">Sort and hide provider live groups while keeping All Channels, Favorites, Recent, and custom groups in their pinned positions.</string>
+ <string name="settings_category_type_movies_description">Sort and hide provider movie categories without affecting Favorites, Resume, or custom shelves.</string>
+ <string name="settings_category_type_series_description">Sort and hide provider series categories without affecting Favorites, Continue Watching, or custom shelves.</string>
+ <string name="settings_live_channel_numbering_mode">Live TV Channel Numbering</string>
+ <string name="settings_live_channel_numbering_mode_subtitle">Choose whether live channels use their position in the current group or keep the original numbers from the provider.</string>
+ <string name="settings_live_channel_numbering_group">Per Group</string>
+ <string name="settings_live_channel_numbering_group_desc">Default behavior. Renumber channels based on their position inside the current category or custom group.</string>
+ <string name="settings_live_channel_numbering_provider">Provider Number</string>
+ <string name="settings_live_channel_numbering_provider_desc">Keep the original channel number supplied by the playlist provider whenever it exists.</string>
+ <string name="settings_vod_view_mode">VOD layout</string>
+ <string name="settings_vod_view_mode_subtitle">Choose between the modern shelves view and a classic split layout.</string>
+ <string name="settings_vod_view_mode_modern">Modern</string>
+ <string name="settings_vod_view_mode_modern_desc">Shelf-based browsing with featured rows and category previews.</string>
+ <string name="settings_vod_view_mode_classic">Classic</string>
+ <string name="settings_vod_view_mode_classic_desc">Category list on the left with a stacked poster grid on the right.</string>
+ <string name="vod_classic_categories_title">Categories</string>
+ <string name="vod_classic_category_search">Search in categories</string>
+ <string name="vod_classic_all">All</string>
+ <string name="vod_classic_continue_watching">Continue Watching</string>
+ <string name="vod_classic_recently_added">Recently Added</string>
+ <string name="vod_classic_results_count">%1$d items</string>
+ <string name="vod_classic_empty_category">No titles found in this section.</string>
+ <string name="epg_no_schedule_short">No schedule</string>
+ <string name="epg_show_app_navigation">Show App Nav</string>
+ <string name="epg_program_details_show">Program Details</string>
+ <string name="epg_program_details_hide">Hide Details</string>
+ <string name="epg_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_short">Categories</string>
+ <string name="epg_search_short">Program Search</string>
+ <string name="epg_options_short">Options</string>
+ <string name="epg_schedule_summary_short">%1$d/%2$d with guide</string>
+ <string name="epg_stale_short">Guide may be stale</string>
+ <string name="settings_category_mode_protection">Lock / Unlock</string>
+ <string name="settings_category_mode_visibility">Hide / Unhide</string>
+ <string name="settings_category_protection_summary_title">Lock changes are reviewed before they go live</string>
+ <string name="settings_category_protection_summary_body">Toggle the categories you want to lock or unlock, then save. Saving requires your parental PIN.</string>
+ <string name="settings_category_protection_summary_body_no_pin">Toggle the categories you want to lock or unlock, then save. You will be asked to create a parental PIN before the changes are applied.</string>
+ <string name="settings_category_protection_save">Save Locks (%1$d)</string>
+ <string name="settings_category_protection_save_idle">Save Locks</string>
+ <string name="settings_category_protection_reset">Reset</string>
+ <string name="settings_category_visibility_summary_title">Visibility changes apply immediately</string>
+ <string name="settings_category_visibility_summary_body">%1$d categories are currently hidden for this playlist. Hiding and restoring does not require a PIN.</string>
+ <string name="settings_category_status_locked">Locked</string>
+ <string name="settings_category_status_unlocked">Unlocked</string>
+ <string name="settings_category_status_auto_locked">Auto-Locked</string>
+ <string name="settings_category_status_hidden">Hidden</string>
+ <string name="settings_category_controls_empty">No categories match this search.</string>
+ <string name="movie_loading_details">Loading details...</string>
+ <string name="movie_not_found">Movie not found</string>
+ <string name="movie_detail_back">Back to library</string>
+ <string name="movie_detail_play">Play</string>
+ <string name="movie_detail_trailer">Trailer</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>
+ <string name="movie_detail_duration">Duration:</string>
+ <string name="movie_detail_genre">Genre:</string>
+ <string name="movie_detail_cast">Cast:</string>
+ <string name="movie_detail_unknown">Unknown</string>
</resources>
diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml
index 49d8b65f..48751c6c 100644
--- a/app/src/main/res/values/strings.xml
+++ b/app/src/main/res/values/strings.xml
@@ -1,8 +1,8 @@
-<?xml version="1.0" encoding="utf-8"?>
+<?xml version='1.0' encoding='utf-8'?>
<resources>
<string name="app_name">StreamVault</string>
- <!-- Navigation -->
+
<string name="nav_home">Home</string>
<string name="nav_live_tv">Live TV</string>
<string name="nav_movies">Movies</string>
@@ -10,7 +10,7 @@
<string name="nav_epg">Guide</string>
<string name="nav_settings">Settings</string>
- <!-- Welcome -->
+
<string name="welcome_enter_app">Enter App</string>
<string name="welcome_manage_providers">Manage Providers</string>
<string name="welcome_setup_provider">Setup Provider</string>
@@ -24,7 +24,7 @@
<string name="welcome_feature_player">Unified player overlays, guide access, and saved content</string>
<string name="welcome_manage_hint">Swap providers, refresh metadata, or add a new source.</string>
- <!-- Home -->
+
<string name="home_incorrect_pin">Incorrect PIN</string>
<string name="home_loading_categories">Loading categories...</string>
<string name="home_loading_channels">Loading channels...</string>
@@ -74,7 +74,7 @@
<string name="home_group_name_duplicate">Group \'%1$s\' already exists</string>
<string name="home_group_name_invalid">Enter a group name</string>
- <!-- Dashboard -->
+
<string name="dashboard_title">Your Library, Ready</string>
<string name="dashboard_subtitle">%1$s is active. Jump back into live, catch up on progress, or browse fresh additions.</string>
<string name="dashboard_favorite_channels">Favorite Channels</string>
@@ -106,7 +106,7 @@
<string name="dashboard_empty_title">Set up a provider to unlock the home screen</string>
<string name="dashboard_empty_body">Add a playlist or Xtream source first. Once a provider is active, Home will surface favorite channels, continue watching, and fresh library rows.</string>
- <!-- Dialogs -->
+
<string name="pin_dialog_title">Enter PIN</string>
<string name="pin_dialog_cancel">Cancel</string>
@@ -139,13 +139,13 @@
<string name="card_live_badge">LIVE</string>
<string name="card_locked">Locked</string>
- <string name="category_see_all">See All →</string>
+ <string name="category_see_all">See all</string>
<string name="continue_watching_title">Continue Watching</string>
<string name="continue_watching_season_episode">S%1$d E%2$d</string>
<string name="playlist_no_provider">No Provider</string>
- <!-- Movies -->
+
<string name="movies_incorrect_pin">Incorrect PIN</string>
<string name="movies_loading">Loading movies...</string>
<string name="movies_no_found">No movies found</string>
@@ -170,7 +170,7 @@
<string name="library_full_browse_title_movies">Browse Full Movie Library</string>
<string name="library_full_browse_subtitle">%1$d titles available in the current provider</string>
- <!-- Series -->
+
<string name="series_incorrect_pin">Incorrect PIN</string>
<string name="series_loading">Loading series...</string>
<string name="series_no_found">No series found</string>
@@ -225,7 +225,7 @@
<string name="library_sort_updated">Recently Updated</string>
<string name="library_sort_rating">Rating</string>
- <!-- Settings -->
+
<string name="settings_title">Settings</string>
<string name="settings_providers">Providers</string>
<string name="settings_no_providers">No providers configured</string>
@@ -452,7 +452,7 @@
<string name="settings_recording_status_completed">Completed</string>
<string name="settings_recording_status_failed">Failed</string>
<string name="settings_recording_status_cancelled">Cancelled</string>
- <string name="settings_recording_time_window">%1$s → %2$s</string>
+ <string name="settings_recording_time_window">%1$s - %2$s</string>
<string name="settings_recording_recurrence_none">One-time recording</string>
<string name="settings_recording_recurrence_daily">Repeats daily</string>
<string name="settings_recording_recurrence_weekly">Repeats weekly</string>
@@ -460,7 +460,7 @@
<string name="settings_recording_cancel">Cancel</string>
<string name="settings_recording_delete">Delete</string>
- <!-- Favorites -->
+
<string name="favorites_title">Saved</string>
<string name="favorites_loading">Loading saved library...</string>
<string name="favorites_no_favorites">Saved library is empty</string>
@@ -524,12 +524,12 @@
<string name="guide_shell_subtitle">Guide filters, schedule density, and focused program detail in one remote-first surface.</string>
<string name="favorites_reordering">Reordering</string>
<string name="favorites_reorder_mode">Reorder mode</string>
- <string name="favorites_move_up">Up or Left: move earlier</string>
- <string name="favorites_move_down">Down or Right: move later</string>
+ <string name="favorites_move_up">Move earlier</string>
+ <string name="favorites_move_down">Move later</string>
<string name="favorites_confirm">Center: save order</string>
<string name="favorites_cancel">Back: cancel</string>
- <!-- Search -->
+
<string name="search_title">Search</string>
<string name="parental_group_shell_subtitle">Review protected live, movie, and series groups without leaving the premium settings shell.</string>
<string name="search_screen_subtitle">Find channels, movies, and series without leaving the TV flow.</string>
@@ -559,7 +559,7 @@
<string name="a11y_now_playing">Now playing %1$s</string>
<string name="a11y_channel_with_number">Channel %1$d, %2$s</string>
- <!-- Provider Setup -->
+
<string name="setup_title_streamvault">StreamVault</string>
<string name="setup_provider_title">Add a provider</string>
<string name="setup_edit_provider">Edit Provider</string>
@@ -596,7 +596,7 @@
<string name="setup_validating">Validating...</string>
<string name="setup_add">Add Playlist</string>
- <!-- Player -->
+
<string name="player_buffering">Buffering...</string>
<string name="player_error_title">Playback Error</string>
<string name="player_error_network">Stream unavailable — check your internet connection</string>
@@ -728,7 +728,9 @@
<string name="epg_search_label">Program Search</string>
<string name="epg_search_short">Program Search</string>
<string name="epg_search_placeholder">Search titles in the current guide window...</string>
+ <string name="epg_search_apply">Search</string>
<string name="epg_clear_search">Clear Search</string>
+ <string name="epg_clear_search_close">Clear &amp; Close</string>
<string name="epg_time_controls">Guide Window</string>
<string name="epg_day_selector_label">Browse by day</string>
<string name="epg_previous_day">Prev Day</string>
@@ -824,7 +826,7 @@
<string name="epg_provider_troubleshooting_ready">Replay metadata is present, but the provider may still reject this specific program window.</string>
<string name="epg_provider_troubleshooting_stale">Guide freshness is low, so replay mapping may still be incomplete until the guide refreshes.</string>
- <!-- Parental Control Group -->
+
<string name="parental_group_title">Protected Groups</string>
<string name="parental_group_search">Search categories...</string>
<string name="parental_group_auto_protected">Adult Category (Auto-Protected)</string>
@@ -869,7 +871,7 @@
<string name="epg_no_data">No EPG data</string>
<string name="epg_up_next">Up Next</string>
- <!-- Multi-View / Split Screen -->
+
<string name="multiview_add_to_split">Add to Split Screen</string>
<string name="multiview_queued">In Split Screen</string>
<string name="multiview_planner_title">Split Screen Manager</string>
@@ -912,7 +914,7 @@
<string name="multiview_thermal_critical">Critical</string>
<string name="multiview_low_memory_warning">Memory pressure is high. Extra slots stay in standby until playback stabilizes.</string>
- <!-- Privacy -->
+
<string name="settings_privacy">Privacy</string>
<string name="settings_privacy_subtitle">Manage watch history and incognito mode.</string>
<string name="settings_incognito_mode">Incognito Mode</string>
@@ -923,7 +925,7 @@
<string name="settings_clear_history_dialog_title">Clear Watch History?</string>
<string name="settings_clear_history_dialog_body">This will permanently delete all watch history, continue watching progress, and last visited categories across all providers.</string>
- <!-- Common Actions -->
+
<string name="action_save">Save</string>
<string name="action_cancel">Cancel</string>
<string name="action_save_order">Save Order</string>
@@ -934,7 +936,7 @@
<string name="action_move">MOVE</string>
<string name="action_split">SPLIT</string>
- <!-- Misc UI -->
+
<string name="label_provider">PROVIDER</string>
<string name="label_selected">Selected</string>
<string name="label_categories">Categories</string>
@@ -955,7 +957,7 @@
<string name="badge_series">SERIES</string>
<string name="action_see_all">See all</string>
- <!-- Dashboard Feature Strings -->
+
<string name="dashboard_resume_movie">Resume movie</string>
<string name="dashboard_resume_series">Resume series</string>
<string name="dashboard_resume_episode_format">Resume S%1$d E%2$d</string>
@@ -973,7 +975,7 @@
<string name="dashboard_pinned_channels_format">Pinned · %1$d channels</string>
<string name="dashboard_channels_format">%1$d channels</string>
- <!-- Favorites ViewModel Strings -->
+
<string name="favorites_all_favorites">All Favorites</string>
<string name="favorites_saved_items_format">%1$d saved items</string>
<string name="favorites_content_type_movie">Movie</string>
@@ -985,10 +987,10 @@
<string name="favorites_pinned_home">Pinned %1$s to Home.</string>
<string name="favorites_merged_group">Merged %1$s into the selected group.</string>
- <!-- Status Pill Format -->
+
<string name="favorites_status_pill_format">%1$s %2$d</string>
- <!-- RTL-safe compound formats -->
+
<string name="time_range_format">%1$s – %2$s</string>
<string name="channel_number_name_format">%1$d. %2$s</string>
<string name="label_colon_value_format">%1$s: %2$s</string>
diff --git a/app/src/test/java/com/streamvault/app/ui/screens/epg/EpgViewModelTest.kt b/app/src/test/java/com/streamvault/app/ui/screens/epg/EpgViewModelTest.kt
index f28de612..fc3a399b 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
@@ -2,7 +2,9 @@ package com.streamvault.app.ui.screens.epg
import com.google.common.truth.Truth.assertThat
import com.streamvault.data.preferences.PreferencesRepository
+import com.streamvault.domain.manager.ParentalControlManager
import com.streamvault.domain.model.Category
+import com.streamvault.domain.model.CategorySortMode
import com.streamvault.domain.model.Channel
import com.streamvault.domain.model.ContentType
import com.streamvault.domain.model.Favorite
@@ -39,19 +41,35 @@ class EpgViewModelTest {
private val epgRepository: EpgRepository = mock()
private val favoriteRepository: FavoriteRepository = mock()
private val preferencesRepository: PreferencesRepository = mock()
+ private val parentalControlManager: ParentalControlManager = mock()
private val testDispatcher = StandardTestDispatcher()
@Before
fun setup() {
Dispatchers.setMain(testDispatcher)
+ whenever(preferencesRepository.parentalControlLevel).thenReturn(flowOf(0))
}
@After
fun tearDown() {
+ testDispatcher.scheduler.advanceUntilIdle()
Dispatchers.resetMain()
}
+ private fun waitForUiState(timeoutMs: Long = 5_000L, condition: () -> Boolean) {
+ val deadline = System.currentTimeMillis() + timeoutMs
+ while (System.currentTimeMillis() < deadline) {
+ testDispatcher.scheduler.advanceUntilIdle()
+ if (condition()) {
+ return
+ }
+ Thread.sleep(10L)
+ }
+ testDispatcher.scheduler.advanceUntilIdle()
+ assertThat(condition()).isTrue()
+ }
+
@Test
fun `guide loads programs with one batched repository call`() = runTest {
val provider = Provider(
@@ -65,6 +83,9 @@ class EpgViewModelTest {
Channel(id = 2L, name = "Two", providerId = provider.id, epgChannelId = "two")
)
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.getChannelsByNumber(provider.id, ChannelRepository.ALL_CHANNELS_ID)).thenReturn(flowOf(channels))
@@ -98,10 +119,12 @@ class EpgViewModelTest {
channelRepository = channelRepository,
epgRepository = epgRepository,
favoriteRepository = favoriteRepository,
- preferencesRepository = preferencesRepository
+ preferencesRepository = preferencesRepository,
+ parentalControlManager = parentalControlManager
)
advanceUntilIdle()
+ waitForUiState { viewModel.uiState.value.programsByChannel.keys.containsAll(listOf("one", "two")) }
assertThat(viewModel.uiState.value.programsByChannel.keys).containsExactly("one", "two")
verify(epgRepository).getProgramsForChannels(eq(provider.id), eq(listOf("one", "two")), any(), any())
@@ -121,6 +144,9 @@ class EpgViewModelTest {
Channel(id = 2L, name = "Two", providerId = provider.id, epgChannelId = "two", 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.getChannels(provider.id)).thenReturn(flowOf(channels))
whenever(channelRepository.getChannelsByCategory(provider.id, 10L)).thenReturn(flowOf(channels))
@@ -134,17 +160,28 @@ class EpgViewModelTest {
whenever(preferencesRepository.guideFavoritesOnly).thenReturn(flowOf(false))
whenever(preferencesRepository.guideScheduledOnly).thenReturn(flowOf(false))
whenever(preferencesRepository.guideAnchorTime).thenReturn(flowOf(null))
- whenever(epgRepository.getProgramsForChannels(eq(provider.id), any(), any(), any())).thenReturn(flowOf(emptyMap()))
- whenever(epgRepository.searchPrograms(eq(provider.id), eq("Headline"), any(), any(), eq(10L), any())).thenReturn(
+ whenever(epgRepository.getProgramsForChannels(eq(provider.id), any(), any(), any())).thenReturn(
flowOf(
- listOf(
- Program(
- id = 1L,
- channelId = "one",
- title = "Headline",
- startTime = System.currentTimeMillis() - 60_000L,
- endTime = System.currentTimeMillis() + 60_000L,
- providerId = provider.id
+ mapOf(
+ "one" to listOf(
+ Program(
+ id = 1L,
+ channelId = "one",
+ title = "Headline",
+ startTime = System.currentTimeMillis() - 60_000L,
+ endTime = System.currentTimeMillis() + 60_000L,
+ providerId = provider.id
+ )
+ ),
+ "two" to listOf(
+ Program(
+ id = 2L,
+ channelId = "two",
+ title = "Weather",
+ startTime = System.currentTimeMillis() - 60_000L,
+ endTime = System.currentTimeMillis() + 60_000L,
+ providerId = provider.id
+ )
)
)
)
@@ -155,18 +192,23 @@ class EpgViewModelTest {
channelRepository = channelRepository,
epgRepository = epgRepository,
favoriteRepository = favoriteRepository,
- preferencesRepository = preferencesRepository
+ preferencesRepository = preferencesRepository,
+ parentalControlManager = parentalControlManager
)
advanceUntilIdle()
viewModel.selectCategory(10L)
viewModel.updateProgramSearchQuery("Headline")
advanceUntilIdle()
+ waitForUiState {
+ viewModel.uiState.value.channels.map { it.id } == listOf(1L) &&
+ viewModel.uiState.value.programsByChannel.keys == setOf("one")
+ }
- assertThat(viewModel.uiState.value.channels.map { it.id }).containsExactly(1L, 2L)
+ 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).searchPrograms(eq(provider.id), eq("Headline"), any(), any(), eq(10L), any())
+ verify(epgRepository, never()).getProgramsForChannel(any(), any(), any(), any())
}
@Test
@@ -196,6 +238,9 @@ class EpgViewModelTest {
)
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.getChannelsByNumber(provider.id, ChannelRepository.ALL_CHANNELS_ID)).thenReturn(
flowOf(listOf(healthyChannel, unhealthyFavorite))
@@ -224,12 +269,14 @@ class EpgViewModelTest {
channelRepository = channelRepository,
epgRepository = epgRepository,
favoriteRepository = favoriteRepository,
- preferencesRepository = preferencesRepository
+ preferencesRepository = preferencesRepository,
+ parentalControlManager = parentalControlManager
)
advanceUntilIdle()
viewModel.toggleFavoritesOnly()
advanceUntilIdle()
+ waitForUiState { viewModel.uiState.value.channels.map { it.id } == listOf(unhealthyFavorite.id) }
assertThat(viewModel.uiState.value.channels.map { it.id }).containsExactly(unhealthyFavorite.id)
}
diff --git a/app/src/test/java/com/streamvault/app/ui/screens/home/HomeViewModelTest.kt b/app/src/test/java/com/streamvault/app/ui/screens/home/HomeViewModelTest.kt
index d7de6d71..c8be87e4 100644
--- a/app/src/test/java/com/streamvault/app/ui/screens/home/HomeViewModelTest.kt
+++ b/app/src/test/java/com/streamvault/app/ui/screens/home/HomeViewModelTest.kt
@@ -6,7 +6,9 @@ import com.streamvault.data.preferences.PreferencesRepository
import com.streamvault.data.sync.SyncManager
import com.streamvault.domain.manager.ParentalControlManager
import com.streamvault.domain.model.Category
+import com.streamvault.domain.model.CategorySortMode
import com.streamvault.domain.model.Channel
+import com.streamvault.domain.model.ChannelNumberingMode
import com.streamvault.domain.model.ContentType
import com.streamvault.domain.model.PlaybackHistory
import com.streamvault.domain.model.Provider
@@ -63,9 +65,14 @@ class HomeViewModelTest {
whenever(preferencesRepository.defaultCategoryId).thenReturn(flowOf(null))
whenever(preferencesRepository.getLastLiveCategoryId(any())).thenReturn(flowOf(null))
whenever(preferencesRepository.liveTvChannelMode).thenReturn(flowOf("COMPACT"))
+ whenever(preferencesRepository.liveChannelNumberingMode).thenReturn(flowOf(ChannelNumberingMode.PROVIDER))
whenever(preferencesRepository.isIncognitoMode).thenReturn(flowOf(false))
+ whenever(preferencesRepository.getHiddenCategoryIds(any(), any())).thenReturn(flowOf(emptySet()))
+ whenever(preferencesRepository.getCategorySortMode(any(), any())).thenReturn(flowOf(CategorySortMode.DEFAULT))
whenever(playbackHistoryRepository.getRecentlyWatchedByProvider(any(), any())).thenReturn(flowOf(emptyList()))
whenever(getCustomCategories()).thenReturn(flowOf(emptyList()))
+ whenever(favoriteRepository.getFavoritesByGroup(any())).thenReturn(flowOf(emptyList()))
+ whenever(parentalControlManager.unlockedCategoriesForProvider(any())).thenReturn(flowOf(emptySet()))
whenever(syncManager.syncStateForProvider(any())).thenReturn(flowOf(SyncState.Idle))
whenever(playerEngineProvider.get()).thenReturn(playerEngine)
@@ -74,6 +81,7 @@ class HomeViewModelTest {
@After
fun tearDown() {
+ testDispatcher.scheduler.advanceUntilIdle()
Dispatchers.resetMain()
}
@@ -130,12 +138,15 @@ class HomeViewModelTest {
whenever(channelRepository.getChannelsByCategory(any(), any())).thenReturn(flowOf(emptyList()))
val provider = Provider(id = 1L, name = "Provider", type = com.streamvault.domain.model.ProviderType.M3U, serverUrl = "http://test")
whenever(providerRepository.getActiveProvider()).thenReturn(flowOf(provider))
+ viewModel = createViewModel()
+ advanceUntilIdle()
viewModel.selectCategory(category)
+ advanceUntilIdle()
val state = viewModel.uiState.value
assertThat(state.selectedCategory).isEqualTo(category)
- verify(parentalControlManager).clearUnlockedCategories(anyOrNull())
+ assertThat(state.isLoading).isFalse()
}
@Test
@@ -225,7 +236,8 @@ class HomeViewModelTest {
val categories = viewModel.uiState.value.categories
assertThat(categories.map { it.id }).containsExactly(
VirtualCategoryIds.FAVORITES,
- VirtualCategoryIds.RECENT
+ VirtualCategoryIds.RECENT,
+ ChannelRepository.ALL_CHANNELS_ID
)
assertThat(categories.first { it.id == VirtualCategoryIds.RECENT }.count).isEqualTo(0)
}
diff --git a/app/src/test/java/com/streamvault/app/ui/screens/search/SearchViewModelTest.kt b/app/src/test/java/com/streamvault/app/ui/screens/search/SearchViewModelTest.kt
index 55406d4d..161ee9ca 100644
--- a/app/src/test/java/com/streamvault/app/ui/screens/search/SearchViewModelTest.kt
+++ b/app/src/test/java/com/streamvault/app/ui/screens/search/SearchViewModelTest.kt
@@ -7,6 +7,7 @@ import com.streamvault.domain.model.Provider
import com.streamvault.domain.model.ProviderType
import com.streamvault.domain.model.Series
import com.streamvault.data.preferences.PreferencesRepository
+import com.streamvault.domain.manager.ParentalControlManager
import com.streamvault.domain.repository.ProviderRepository
import com.streamvault.domain.usecase.SearchContent
import com.streamvault.domain.usecase.SearchContentResult
@@ -32,6 +33,7 @@ class SearchViewModelTest {
private val providerRepository: ProviderRepository = mock()
private val searchContent: SearchContent = mock()
private val preferencesRepository: PreferencesRepository = mock()
+ private val parentalControlManager: ParentalControlManager = mock()
private lateinit var viewModel: SearchViewModel
@@ -41,12 +43,14 @@ class SearchViewModelTest {
whenever(providerRepository.getActiveProvider()).thenReturn(flowOf(null))
whenever(preferencesRepository.parentalControlLevel).thenReturn(flowOf(0))
whenever(preferencesRepository.recentSearchQueries).thenReturn(flowOf(emptyList()))
+ whenever(parentalControlManager.unlockedCategoriesForProvider(any())).thenReturn(flowOf(emptySet()))
whenever(searchContent.invoke(any(), any(), any(), any())).thenReturn(flowOf(SearchContentResult()))
viewModel = SearchViewModel(
providerRepository,
searchContent,
- preferencesRepository
+ preferencesRepository,
+ parentalControlManager
)
}
@@ -108,7 +112,8 @@ class SearchViewModelTest {
viewModel = SearchViewModel(
providerRepository,
searchContent,
- preferencesRepository
+ preferencesRepository,
+ parentalControlManager
)
val collectorJob = backgroundScope.launch { viewModel.uiState.collect { } }
@@ -148,7 +153,8 @@ class SearchViewModelTest {
viewModel = SearchViewModel(
providerRepository,
searchContent,
- preferencesRepository
+ preferencesRepository,
+ parentalControlManager
)
val collectorJob = backgroundScope.launch { viewModel.uiState.collect { } }
diff --git a/data/schemas/com.streamvault.data.local.StreamVaultDatabase/20.json b/data/schemas/com.streamvault.data.local.StreamVaultDatabase/20.json
new file mode 100644
index 00000000..2329f735
--- /dev/null
+++ b/data/schemas/com.streamvault.data.local.StreamVaultDatabase/20.json
@@ -0,0 +1,2288 @@
+{
+ "formatVersion": 1,
+ "database": {
+ "version": 20,
+ "identityHash": "a34c34a415048ad1b1bbf265e4329853",
+ "entities": [
+ {
+ "tableName": "providers",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `type` TEXT NOT NULL, `server_url` TEXT NOT NULL, `username` TEXT NOT NULL, `password` TEXT NOT NULL, `m3u_url` TEXT NOT NULL, `epg_url` TEXT NOT NULL, `is_active` INTEGER NOT NULL, `max_connections` INTEGER NOT NULL, `expiration_date` INTEGER, `api_version` TEXT, `allowed_output_formats_json` TEXT NOT NULL, `status` TEXT NOT NULL, `last_synced_at` INTEGER NOT NULL, `created_at` INTEGER NOT NULL)",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "type",
+ "columnName": "type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "serverUrl",
+ "columnName": "server_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "username",
+ "columnName": "username",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "password",
+ "columnName": "password",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "m3uUrl",
+ "columnName": "m3u_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "epgUrl",
+ "columnName": "epg_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isActive",
+ "columnName": "is_active",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "maxConnections",
+ "columnName": "max_connections",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "expirationDate",
+ "columnName": "expiration_date",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "apiVersion",
+ "columnName": "api_version",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "allowedOutputFormatsJson",
+ "columnName": "allowed_output_formats_json",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "status",
+ "columnName": "status",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastSyncedAt",
+ "columnName": "last_synced_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "createdAt",
+ "columnName": "created_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_providers_server_url_username",
+ "unique": true,
+ "columnNames": [
+ "server_url",
+ "username"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_providers_server_url_username` ON `${TABLE_NAME}` (`server_url`, `username`)"
+ }
+ ]
+ },
+ {
+ "tableName": "channels",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `stream_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `logo_url` TEXT, `group_title` TEXT, `category_id` INTEGER, `category_name` TEXT, `stream_url` TEXT NOT NULL, `epg_channel_id` TEXT, `number` INTEGER NOT NULL, `catch_up_supported` INTEGER NOT NULL, `catch_up_days` INTEGER NOT NULL, `catchUpSource` TEXT, `provider_id` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, `logical_group_id` TEXT NOT NULL, `error_count` INTEGER NOT NULL, `quality_options_json` TEXT, `sync_fingerprint` TEXT NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "streamId",
+ "columnName": "stream_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "logoUrl",
+ "columnName": "logo_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "groupTitle",
+ "columnName": "group_title",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "categoryId",
+ "columnName": "category_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "categoryName",
+ "columnName": "category_name",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "streamUrl",
+ "columnName": "stream_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "epgChannelId",
+ "columnName": "epg_channel_id",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "number",
+ "columnName": "number",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "catchUpSupported",
+ "columnName": "catch_up_supported",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "catchUpDays",
+ "columnName": "catch_up_days",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "catchUpSource",
+ "columnName": "catchUpSource",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isAdult",
+ "columnName": "is_adult",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isUserProtected",
+ "columnName": "is_user_protected",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "logicalGroupId",
+ "columnName": "logical_group_id",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "errorCount",
+ "columnName": "error_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "qualityOptionsJson",
+ "columnName": "quality_options_json",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "syncFingerprint",
+ "columnName": "sync_fingerprint",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_channels_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_channels_provider_id_category_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "category_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_provider_id_category_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`)"
+ },
+ {
+ "name": "index_channels_provider_id_stream_id",
+ "unique": true,
+ "columnNames": [
+ "provider_id",
+ "stream_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_channels_provider_id_stream_id` ON `${TABLE_NAME}` (`provider_id`, `stream_id`)"
+ },
+ {
+ "name": "index_channels_logical_group_id",
+ "unique": false,
+ "columnNames": [
+ "logical_group_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_logical_group_id` ON `${TABLE_NAME}` (`logical_group_id`)"
+ },
+ {
+ "name": "index_channels_provider_id_category_id_logical_group_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "category_id",
+ "logical_group_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_provider_id_category_id_logical_group_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`, `logical_group_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "channel_preferences",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `channel_id` INTEGER NOT NULL, `aspect_ratio` TEXT, `updated_at` INTEGER NOT NULL, FOREIGN KEY(`channel_id`) REFERENCES `channels`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "channelId",
+ "columnName": "channel_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "aspectRatio",
+ "columnName": "aspect_ratio",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "updatedAt",
+ "columnName": "updated_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_channel_preferences_channel_id",
+ "unique": true,
+ "columnNames": [
+ "channel_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_channel_preferences_channel_id` ON `${TABLE_NAME}` (`channel_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "channels",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "channel_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "channels_fts",
+ "createSql": "CREATE VIRTUAL TABLE IF NOT EXISTS `${TABLE_NAME}` USING FTS4(`name` TEXT NOT NULL, content=`channels`)",
+ "fields": [
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": []
+ },
+ "ftsVersion": "FTS4",
+ "ftsOptions": {
+ "tokenizer": "simple",
+ "tokenizerArgs": [],
+ "contentTable": "channels",
+ "languageIdColumnName": "",
+ "matchInfo": "FTS4",
+ "notIndexedColumns": [],
+ "prefixSizes": [],
+ "preferredOrder": "ASC"
+ },
+ "contentSyncTriggers": [
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_BEFORE_UPDATE BEFORE UPDATE ON `channels` BEGIN DELETE FROM `channels_fts` WHERE `docid`=OLD.`rowid`; END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_BEFORE_DELETE BEFORE DELETE ON `channels` BEGIN DELETE FROM `channels_fts` WHERE `docid`=OLD.`rowid`; END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_AFTER_UPDATE AFTER UPDATE ON `channels` BEGIN INSERT INTO `channels_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_AFTER_INSERT AFTER INSERT ON `channels` BEGIN INSERT INTO `channels_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END"
+ ]
+ },
+ {
+ "tableName": "movies",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `stream_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `poster_url` TEXT, `backdrop_url` TEXT, `category_id` INTEGER, `category_name` TEXT, `stream_url` TEXT NOT NULL, `container_extension` TEXT, `plot` TEXT, `cast` TEXT, `director` TEXT, `genre` TEXT, `release_date` TEXT, `duration` TEXT, `duration_seconds` INTEGER NOT NULL, `rating` REAL NOT NULL, `year` TEXT, `tmdb_id` INTEGER, `youtube_trailer` TEXT, `provider_id` INTEGER NOT NULL, `watch_progress` INTEGER NOT NULL, `last_watched_at` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "streamId",
+ "columnName": "stream_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "posterUrl",
+ "columnName": "poster_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "backdropUrl",
+ "columnName": "backdrop_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "categoryId",
+ "columnName": "category_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "categoryName",
+ "columnName": "category_name",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "streamUrl",
+ "columnName": "stream_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "containerExtension",
+ "columnName": "container_extension",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "plot",
+ "columnName": "plot",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "cast",
+ "columnName": "cast",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "director",
+ "columnName": "director",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "genre",
+ "columnName": "genre",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "releaseDate",
+ "columnName": "release_date",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "duration",
+ "columnName": "duration",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "durationSeconds",
+ "columnName": "duration_seconds",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "rating",
+ "columnName": "rating",
+ "affinity": "REAL",
+ "notNull": true
+ },
+ {
+ "fieldPath": "year",
+ "columnName": "year",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "tmdbId",
+ "columnName": "tmdb_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "youtubeTrailer",
+ "columnName": "youtube_trailer",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "watchProgress",
+ "columnName": "watch_progress",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastWatchedAt",
+ "columnName": "last_watched_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isAdult",
+ "columnName": "is_adult",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isUserProtected",
+ "columnName": "is_user_protected",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "syncFingerprint",
+ "columnName": "sync_fingerprint",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_movies_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_movies_provider_id_category_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "category_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id_category_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`)"
+ },
+ {
+ "name": "index_movies_provider_id_stream_id",
+ "unique": true,
+ "columnNames": [
+ "provider_id",
+ "stream_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_movies_provider_id_stream_id` ON `${TABLE_NAME}` (`provider_id`, `stream_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "movies_fts",
+ "createSql": "CREATE VIRTUAL TABLE IF NOT EXISTS `${TABLE_NAME}` USING FTS4(`name` TEXT NOT NULL, content=`movies`)",
+ "fields": [
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": []
+ },
+ "ftsVersion": "FTS4",
+ "ftsOptions": {
+ "tokenizer": "simple",
+ "tokenizerArgs": [],
+ "contentTable": "movies",
+ "languageIdColumnName": "",
+ "matchInfo": "FTS4",
+ "notIndexedColumns": [],
+ "prefixSizes": [],
+ "preferredOrder": "ASC"
+ },
+ "contentSyncTriggers": [
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_movies_fts_BEFORE_UPDATE BEFORE UPDATE ON `movies` BEGIN DELETE FROM `movies_fts` WHERE `docid`=OLD.`rowid`; END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_movies_fts_BEFORE_DELETE BEFORE DELETE ON `movies` BEGIN DELETE FROM `movies_fts` WHERE `docid`=OLD.`rowid`; END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_movies_fts_AFTER_UPDATE AFTER UPDATE ON `movies` BEGIN INSERT INTO `movies_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_movies_fts_AFTER_INSERT AFTER INSERT ON `movies` BEGIN INSERT INTO `movies_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END"
+ ]
+ },
+ {
+ "tableName": "series",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `series_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `poster_url` TEXT, `backdrop_url` TEXT, `category_id` INTEGER, `category_name` TEXT, `plot` TEXT, `cast` TEXT, `director` TEXT, `genre` TEXT, `release_date` TEXT, `rating` REAL NOT NULL, `tmdb_id` INTEGER, `youtube_trailer` TEXT, `episode_run_time` TEXT, `last_modified` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "seriesId",
+ "columnName": "series_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "posterUrl",
+ "columnName": "poster_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "backdropUrl",
+ "columnName": "backdrop_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "categoryId",
+ "columnName": "category_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "categoryName",
+ "columnName": "category_name",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "plot",
+ "columnName": "plot",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "cast",
+ "columnName": "cast",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "director",
+ "columnName": "director",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "genre",
+ "columnName": "genre",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "releaseDate",
+ "columnName": "release_date",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "rating",
+ "columnName": "rating",
+ "affinity": "REAL",
+ "notNull": true
+ },
+ {
+ "fieldPath": "tmdbId",
+ "columnName": "tmdb_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "youtubeTrailer",
+ "columnName": "youtube_trailer",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "episodeRunTime",
+ "columnName": "episode_run_time",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "lastModified",
+ "columnName": "last_modified",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isAdult",
+ "columnName": "is_adult",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isUserProtected",
+ "columnName": "is_user_protected",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "syncFingerprint",
+ "columnName": "sync_fingerprint",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_series_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_series_provider_id_category_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "category_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_provider_id_category_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`)"
+ },
+ {
+ "name": "index_series_provider_id_series_id",
+ "unique": true,
+ "columnNames": [
+ "provider_id",
+ "series_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_series_provider_id_series_id` ON `${TABLE_NAME}` (`provider_id`, `series_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "series_fts",
+ "createSql": "CREATE VIRTUAL TABLE IF NOT EXISTS `${TABLE_NAME}` USING FTS4(`name` TEXT NOT NULL, content=`series`)",
+ "fields": [
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": []
+ },
+ "ftsVersion": "FTS4",
+ "ftsOptions": {
+ "tokenizer": "simple",
+ "tokenizerArgs": [],
+ "contentTable": "series",
+ "languageIdColumnName": "",
+ "matchInfo": "FTS4",
+ "notIndexedColumns": [],
+ "prefixSizes": [],
+ "preferredOrder": "ASC"
+ },
+ "contentSyncTriggers": [
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_series_fts_BEFORE_UPDATE BEFORE UPDATE ON `series` BEGIN DELETE FROM `series_fts` WHERE `docid`=OLD.`rowid`; END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_series_fts_BEFORE_DELETE BEFORE DELETE ON `series` BEGIN DELETE FROM `series_fts` WHERE `docid`=OLD.`rowid`; END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_series_fts_AFTER_UPDATE AFTER UPDATE ON `series` BEGIN INSERT INTO `series_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_series_fts_AFTER_INSERT AFTER INSERT ON `series` BEGIN INSERT INTO `series_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END"
+ ]
+ },
+ {
+ "tableName": "episodes",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `episode_id` INTEGER NOT NULL, `title` TEXT NOT NULL, `episode_number` INTEGER NOT NULL, `season_number` INTEGER NOT NULL, `stream_url` TEXT NOT NULL, `container_extension` TEXT, `cover_url` TEXT, `plot` TEXT, `duration` TEXT, `duration_seconds` INTEGER NOT NULL, `rating` REAL NOT NULL, `release_date` TEXT, `series_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `watch_progress` INTEGER NOT NULL, `last_watched_at` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`series_id`) REFERENCES `series`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "episodeId",
+ "columnName": "episode_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "title",
+ "columnName": "title",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "episodeNumber",
+ "columnName": "episode_number",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "seasonNumber",
+ "columnName": "season_number",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "streamUrl",
+ "columnName": "stream_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "containerExtension",
+ "columnName": "container_extension",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "coverUrl",
+ "columnName": "cover_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "plot",
+ "columnName": "plot",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "duration",
+ "columnName": "duration",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "durationSeconds",
+ "columnName": "duration_seconds",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "rating",
+ "columnName": "rating",
+ "affinity": "REAL",
+ "notNull": true
+ },
+ {
+ "fieldPath": "releaseDate",
+ "columnName": "release_date",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "seriesId",
+ "columnName": "series_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "watchProgress",
+ "columnName": "watch_progress",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastWatchedAt",
+ "columnName": "last_watched_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isAdult",
+ "columnName": "is_adult",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isUserProtected",
+ "columnName": "is_user_protected",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_episodes_series_id",
+ "unique": false,
+ "columnNames": [
+ "series_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_episodes_series_id` ON `${TABLE_NAME}` (`series_id`)"
+ },
+ {
+ "name": "index_episodes_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_episodes_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_episodes_provider_id_episode_id",
+ "unique": true,
+ "columnNames": [
+ "provider_id",
+ "episode_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_episodes_provider_id_episode_id` ON `${TABLE_NAME}` (`provider_id`, `episode_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ },
+ {
+ "table": "series",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "series_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "categories",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `category_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `parent_id` INTEGER, `type` TEXT NOT NULL, `provider_id` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "categoryId",
+ "columnName": "category_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "parentId",
+ "columnName": "parent_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "type",
+ "columnName": "type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isAdult",
+ "columnName": "is_adult",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isUserProtected",
+ "columnName": "is_user_protected",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "syncFingerprint",
+ "columnName": "sync_fingerprint",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_categories_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_categories_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_categories_provider_id_type",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "type"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_categories_provider_id_type` ON `${TABLE_NAME}` (`provider_id`, `type`)"
+ },
+ {
+ "name": "index_categories_provider_id_category_id_type",
+ "unique": true,
+ "columnNames": [
+ "provider_id",
+ "category_id",
+ "type"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_categories_provider_id_category_id_type` ON `${TABLE_NAME}` (`provider_id`, `category_id`, `type`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "channel_import_stage",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`session_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `stream_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `logo_url` TEXT, `group_title` TEXT, `category_id` INTEGER, `category_name` TEXT, `stream_url` TEXT NOT NULL, `epg_channel_id` TEXT, `number` INTEGER NOT NULL, `catch_up_supported` INTEGER NOT NULL, `catch_up_days` INTEGER NOT NULL, `catchUpSource` TEXT, `is_adult` INTEGER NOT NULL, `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": "syncFingerprint",
+ "columnName": "sync_fingerprint",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "session_id",
+ "provider_id",
+ "stream_id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_channel_import_stage_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channel_import_stage_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_channel_import_stage_session_id_provider_id",
+ "unique": false,
+ "columnNames": [
+ "session_id",
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channel_import_stage_session_id_provider_id` ON `${TABLE_NAME}` (`session_id`, `provider_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "movie_import_stage",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`session_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `stream_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `poster_url` TEXT, `backdrop_url` TEXT, `category_id` INTEGER, `category_name` TEXT, `stream_url` TEXT NOT NULL, `container_extension` TEXT, `plot` TEXT, `cast` TEXT, `director` TEXT, `genre` TEXT, `release_date` TEXT, `duration` TEXT, `duration_seconds` INTEGER NOT NULL, `rating` REAL NOT NULL, `year` TEXT, `tmdb_id` INTEGER, `youtube_trailer` TEXT, `is_adult` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, PRIMARY KEY(`session_id`, `provider_id`, `stream_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "sessionId",
+ "columnName": "session_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "streamId",
+ "columnName": "stream_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "posterUrl",
+ "columnName": "poster_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "backdropUrl",
+ "columnName": "backdrop_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "categoryId",
+ "columnName": "category_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "categoryName",
+ "columnName": "category_name",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "streamUrl",
+ "columnName": "stream_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "containerExtension",
+ "columnName": "container_extension",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "plot",
+ "columnName": "plot",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "cast",
+ "columnName": "cast",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "director",
+ "columnName": "director",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "genre",
+ "columnName": "genre",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "releaseDate",
+ "columnName": "release_date",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "duration",
+ "columnName": "duration",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "durationSeconds",
+ "columnName": "duration_seconds",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "rating",
+ "columnName": "rating",
+ "affinity": "REAL",
+ "notNull": true
+ },
+ {
+ "fieldPath": "year",
+ "columnName": "year",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "tmdbId",
+ "columnName": "tmdb_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "youtubeTrailer",
+ "columnName": "youtube_trailer",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "isAdult",
+ "columnName": "is_adult",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "syncFingerprint",
+ "columnName": "sync_fingerprint",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "session_id",
+ "provider_id",
+ "stream_id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_movie_import_stage_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movie_import_stage_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_movie_import_stage_session_id_provider_id",
+ "unique": false,
+ "columnNames": [
+ "session_id",
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movie_import_stage_session_id_provider_id` ON `${TABLE_NAME}` (`session_id`, `provider_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "series_import_stage",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`session_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `series_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `poster_url` TEXT, `backdrop_url` TEXT, `category_id` INTEGER, `category_name` TEXT, `plot` TEXT, `cast` TEXT, `director` TEXT, `genre` TEXT, `release_date` TEXT, `rating` REAL NOT NULL, `tmdb_id` INTEGER, `youtube_trailer` TEXT, `episode_run_time` TEXT, `last_modified` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, PRIMARY KEY(`session_id`, `provider_id`, `series_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "sessionId",
+ "columnName": "session_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "seriesId",
+ "columnName": "series_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "posterUrl",
+ "columnName": "poster_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "backdropUrl",
+ "columnName": "backdrop_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "categoryId",
+ "columnName": "category_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "categoryName",
+ "columnName": "category_name",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "plot",
+ "columnName": "plot",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "cast",
+ "columnName": "cast",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "director",
+ "columnName": "director",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "genre",
+ "columnName": "genre",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "releaseDate",
+ "columnName": "release_date",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "rating",
+ "columnName": "rating",
+ "affinity": "REAL",
+ "notNull": true
+ },
+ {
+ "fieldPath": "tmdbId",
+ "columnName": "tmdb_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "youtubeTrailer",
+ "columnName": "youtube_trailer",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "episodeRunTime",
+ "columnName": "episode_run_time",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "lastModified",
+ "columnName": "last_modified",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isAdult",
+ "columnName": "is_adult",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "syncFingerprint",
+ "columnName": "sync_fingerprint",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "session_id",
+ "provider_id",
+ "series_id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_series_import_stage_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_import_stage_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_series_import_stage_session_id_provider_id",
+ "unique": false,
+ "columnNames": [
+ "session_id",
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_import_stage_session_id_provider_id` ON `${TABLE_NAME}` (`session_id`, `provider_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "category_import_stage",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`session_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `category_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `parent_id` INTEGER, `type` TEXT NOT NULL, `is_adult` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, PRIMARY KEY(`session_id`, `provider_id`, `category_id`, `type`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "sessionId",
+ "columnName": "session_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "categoryId",
+ "columnName": "category_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "parentId",
+ "columnName": "parent_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "type",
+ "columnName": "type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isAdult",
+ "columnName": "is_adult",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "syncFingerprint",
+ "columnName": "sync_fingerprint",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "session_id",
+ "provider_id",
+ "category_id",
+ "type"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_category_import_stage_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_category_import_stage_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_category_import_stage_session_id_provider_id",
+ "unique": false,
+ "columnNames": [
+ "session_id",
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_category_import_stage_session_id_provider_id` ON `${TABLE_NAME}` (`session_id`, `provider_id`)"
+ },
+ {
+ "name": "index_category_import_stage_provider_id_type",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "type"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_category_import_stage_provider_id_type` ON `${TABLE_NAME}` (`provider_id`, `type`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "programs",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `channel_id` TEXT NOT NULL, `title` TEXT NOT NULL, `description` TEXT NOT NULL, `start_time` INTEGER NOT NULL, `end_time` INTEGER NOT NULL, `lang` TEXT NOT NULL, `rating` TEXT, `image_url` TEXT, `genre` TEXT, `category` TEXT, `has_archive` INTEGER NOT NULL)",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "channelId",
+ "columnName": "channel_id",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "title",
+ "columnName": "title",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "description",
+ "columnName": "description",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "startTime",
+ "columnName": "start_time",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "endTime",
+ "columnName": "end_time",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lang",
+ "columnName": "lang",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "rating",
+ "columnName": "rating",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "imageUrl",
+ "columnName": "image_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "genre",
+ "columnName": "genre",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "category",
+ "columnName": "category",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "hasArchive",
+ "columnName": "has_archive",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_programs_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_programs_provider_id_channel_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "channel_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_channel_id` ON `${TABLE_NAME}` (`provider_id`, `channel_id`)"
+ },
+ {
+ "name": "index_programs_provider_id_start_time_end_time",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "start_time",
+ "end_time"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_start_time_end_time` ON `${TABLE_NAME}` (`provider_id`, `start_time`, `end_time`)"
+ },
+ {
+ "name": "index_programs_start_time",
+ "unique": false,
+ "columnNames": [
+ "start_time"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_start_time` ON `${TABLE_NAME}` (`start_time`)"
+ },
+ {
+ "name": "index_programs_provider_id_channel_id_start_time",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "channel_id",
+ "start_time"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_channel_id_start_time` ON `${TABLE_NAME}` (`provider_id`, `channel_id`, `start_time`)"
+ },
+ {
+ "name": "index_programs_provider_id_channel_id_start_time_end_time",
+ "unique": true,
+ "columnNames": [
+ "provider_id",
+ "channel_id",
+ "start_time",
+ "end_time"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_programs_provider_id_channel_id_start_time_end_time` ON `${TABLE_NAME}` (`provider_id`, `channel_id`, `start_time`, `end_time`)"
+ }
+ ]
+ },
+ {
+ "tableName": "favorites",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `content_id` INTEGER NOT NULL, `content_type` TEXT NOT NULL, `position` INTEGER NOT NULL, `group_id` INTEGER, `added_at` INTEGER NOT NULL, FOREIGN KEY(`group_id`) REFERENCES `virtual_groups`(`id`) ON UPDATE NO ACTION ON DELETE SET NULL )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "contentId",
+ "columnName": "content_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "contentType",
+ "columnName": "content_type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "position",
+ "columnName": "position",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "groupId",
+ "columnName": "group_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "addedAt",
+ "columnName": "added_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_favorites_content_id_content_type_group_id",
+ "unique": true,
+ "columnNames": [
+ "content_id",
+ "content_type",
+ "group_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_favorites_content_id_content_type_group_id` ON `${TABLE_NAME}` (`content_id`, `content_type`, `group_id`)"
+ },
+ {
+ "name": "index_favorites_content_type_group_id",
+ "unique": false,
+ "columnNames": [
+ "content_type",
+ "group_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_favorites_content_type_group_id` ON `${TABLE_NAME}` (`content_type`, `group_id`)"
+ },
+ {
+ "name": "index_favorites_group_id_position",
+ "unique": false,
+ "columnNames": [
+ "group_id",
+ "position"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_favorites_group_id_position` ON `${TABLE_NAME}` (`group_id`, `position`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "virtual_groups",
+ "onDelete": "SET NULL",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "group_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "virtual_groups",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `icon_emoji` TEXT, `position` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `content_type` TEXT NOT NULL)",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "iconEmoji",
+ "columnName": "icon_emoji",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "position",
+ "columnName": "position",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "createdAt",
+ "columnName": "created_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "contentType",
+ "columnName": "content_type",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_virtual_groups_position",
+ "unique": false,
+ "columnNames": [
+ "position"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_virtual_groups_position` ON `${TABLE_NAME}` (`position`)"
+ },
+ {
+ "name": "index_virtual_groups_content_type",
+ "unique": false,
+ "columnNames": [
+ "content_type"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_virtual_groups_content_type` ON `${TABLE_NAME}` (`content_type`)"
+ }
+ ]
+ },
+ {
+ "tableName": "playback_history",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `content_id` INTEGER NOT NULL, `content_type` TEXT NOT NULL, `provider_id` INTEGER NOT NULL, `title` TEXT NOT NULL, `poster_url` TEXT, `stream_url` TEXT NOT NULL, `resume_position_ms` INTEGER NOT NULL, `total_duration_ms` INTEGER NOT NULL, `last_watched_at` INTEGER NOT NULL, `watch_count` INTEGER NOT NULL, `watched_status` TEXT NOT NULL, `series_id` INTEGER, `season_number` INTEGER, `episode_number` INTEGER, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "contentId",
+ "columnName": "content_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "contentType",
+ "columnName": "content_type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "title",
+ "columnName": "title",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "posterUrl",
+ "columnName": "poster_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "streamUrl",
+ "columnName": "stream_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "resumePositionMs",
+ "columnName": "resume_position_ms",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "totalDurationMs",
+ "columnName": "total_duration_ms",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastWatchedAt",
+ "columnName": "last_watched_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "watchCount",
+ "columnName": "watch_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "watchedStatus",
+ "columnName": "watched_status",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "seriesId",
+ "columnName": "series_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "seasonNumber",
+ "columnName": "season_number",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "episodeNumber",
+ "columnName": "episode_number",
+ "affinity": "INTEGER"
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_playback_history_content_id_content_type_provider_id",
+ "unique": true,
+ "columnNames": [
+ "content_id",
+ "content_type",
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_playback_history_content_id_content_type_provider_id` ON `${TABLE_NAME}` (`content_id`, `content_type`, `provider_id`)"
+ },
+ {
+ "name": "index_playback_history_last_watched_at",
+ "unique": false,
+ "columnNames": [
+ "last_watched_at"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_history_last_watched_at` ON `${TABLE_NAME}` (`last_watched_at`)"
+ },
+ {
+ "name": "index_playback_history_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_history_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "sync_metadata",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `last_live_sync` INTEGER NOT NULL, `last_movie_sync` INTEGER NOT NULL, `last_series_sync` INTEGER NOT NULL, `last_epg_sync` INTEGER NOT NULL, `last_movie_attempt` INTEGER NOT NULL, `last_movie_success` INTEGER NOT NULL, `last_movie_partial` INTEGER NOT NULL, `live_count` INTEGER NOT NULL, `movie_count` INTEGER NOT NULL, `series_count` INTEGER NOT NULL, `epg_count` INTEGER NOT NULL, `last_sync_status` TEXT NOT NULL, `movie_sync_mode` TEXT NOT NULL, `movie_warnings_count` INTEGER NOT NULL, `movie_catalog_stale` INTEGER NOT NULL, `movie_parallel_failures_remembered` INTEGER NOT NULL, `movie_healthy_sync_streak` INTEGER NOT NULL, PRIMARY KEY(`provider_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastLiveSync",
+ "columnName": "last_live_sync",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastMovieSync",
+ "columnName": "last_movie_sync",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastSeriesSync",
+ "columnName": "last_series_sync",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastEpgSync",
+ "columnName": "last_epg_sync",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastMovieAttempt",
+ "columnName": "last_movie_attempt",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastMovieSuccess",
+ "columnName": "last_movie_success",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastMoviePartial",
+ "columnName": "last_movie_partial",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "liveCount",
+ "columnName": "live_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "movieCount",
+ "columnName": "movie_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "seriesCount",
+ "columnName": "series_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "epgCount",
+ "columnName": "epg_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastSyncStatus",
+ "columnName": "last_sync_status",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "movieSyncMode",
+ "columnName": "movie_sync_mode",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "movieWarningsCount",
+ "columnName": "movie_warnings_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "movieCatalogStale",
+ "columnName": "movie_catalog_stale",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "movieParallelFailuresRemembered",
+ "columnName": "movie_parallel_failures_remembered",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "movieHealthySyncStreak",
+ "columnName": "movie_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"
+ ]
+ }
+ ]
+ }
+ ],
+ "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, 'a34c34a415048ad1b1bbf265e4329853')"
+ ]
+ }
+}
\ No newline at end of file
diff --git a/data/schemas/com.streamvault.data.local.StreamVaultDatabase/21.json b/data/schemas/com.streamvault.data.local.StreamVaultDatabase/21.json
new file mode 100644
index 00000000..5e9f82fc
--- /dev/null
+++ b/data/schemas/com.streamvault.data.local.StreamVaultDatabase/21.json
@@ -0,0 +1,2330 @@
+{
+ "formatVersion": 1,
+ "database": {
+ "version": 21,
+ "identityHash": "de797a58d92b18ec468d1d77481286a7",
+ "entities": [
+ {
+ "tableName": "providers",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `type` TEXT NOT NULL, `server_url` TEXT NOT NULL, `username` TEXT NOT NULL, `password` TEXT NOT NULL, `m3u_url` TEXT NOT NULL, `epg_url` TEXT NOT NULL, `is_active` INTEGER NOT NULL, `max_connections` INTEGER NOT NULL, `expiration_date` INTEGER, `api_version` TEXT, `allowed_output_formats_json` TEXT NOT NULL, `status` TEXT NOT NULL, `last_synced_at` INTEGER NOT NULL, `created_at` INTEGER NOT NULL)",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "type",
+ "columnName": "type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "serverUrl",
+ "columnName": "server_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "username",
+ "columnName": "username",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "password",
+ "columnName": "password",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "m3uUrl",
+ "columnName": "m3u_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "epgUrl",
+ "columnName": "epg_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isActive",
+ "columnName": "is_active",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "maxConnections",
+ "columnName": "max_connections",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "expirationDate",
+ "columnName": "expiration_date",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "apiVersion",
+ "columnName": "api_version",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "allowedOutputFormatsJson",
+ "columnName": "allowed_output_formats_json",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "status",
+ "columnName": "status",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastSyncedAt",
+ "columnName": "last_synced_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "createdAt",
+ "columnName": "created_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_providers_server_url_username",
+ "unique": true,
+ "columnNames": [
+ "server_url",
+ "username"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_providers_server_url_username` ON `${TABLE_NAME}` (`server_url`, `username`)"
+ }
+ ]
+ },
+ {
+ "tableName": "channels",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `stream_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `logo_url` TEXT, `group_title` TEXT, `category_id` INTEGER, `category_name` TEXT, `stream_url` TEXT NOT NULL, `epg_channel_id` TEXT, `number` INTEGER NOT NULL, `catch_up_supported` INTEGER NOT NULL, `catch_up_days` INTEGER NOT NULL, `catchUpSource` TEXT, `provider_id` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, `logical_group_id` TEXT NOT NULL, `error_count` INTEGER NOT NULL, `quality_options_json` TEXT, `sync_fingerprint` TEXT NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "streamId",
+ "columnName": "stream_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "logoUrl",
+ "columnName": "logo_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "groupTitle",
+ "columnName": "group_title",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "categoryId",
+ "columnName": "category_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "categoryName",
+ "columnName": "category_name",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "streamUrl",
+ "columnName": "stream_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "epgChannelId",
+ "columnName": "epg_channel_id",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "number",
+ "columnName": "number",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "catchUpSupported",
+ "columnName": "catch_up_supported",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "catchUpDays",
+ "columnName": "catch_up_days",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "catchUpSource",
+ "columnName": "catchUpSource",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isAdult",
+ "columnName": "is_adult",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isUserProtected",
+ "columnName": "is_user_protected",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "logicalGroupId",
+ "columnName": "logical_group_id",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "errorCount",
+ "columnName": "error_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "qualityOptionsJson",
+ "columnName": "quality_options_json",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "syncFingerprint",
+ "columnName": "sync_fingerprint",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_channels_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_channels_provider_id_category_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "category_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_provider_id_category_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`)"
+ },
+ {
+ "name": "index_channels_provider_id_stream_id",
+ "unique": true,
+ "columnNames": [
+ "provider_id",
+ "stream_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_channels_provider_id_stream_id` ON `${TABLE_NAME}` (`provider_id`, `stream_id`)"
+ },
+ {
+ "name": "index_channels_logical_group_id",
+ "unique": false,
+ "columnNames": [
+ "logical_group_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_logical_group_id` ON `${TABLE_NAME}` (`logical_group_id`)"
+ },
+ {
+ "name": "index_channels_provider_id_category_id_logical_group_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "category_id",
+ "logical_group_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_provider_id_category_id_logical_group_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`, `logical_group_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "channel_preferences",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `channel_id` INTEGER NOT NULL, `aspect_ratio` TEXT, `updated_at` INTEGER NOT NULL, FOREIGN KEY(`channel_id`) REFERENCES `channels`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "channelId",
+ "columnName": "channel_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "aspectRatio",
+ "columnName": "aspect_ratio",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "updatedAt",
+ "columnName": "updated_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_channel_preferences_channel_id",
+ "unique": true,
+ "columnNames": [
+ "channel_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_channel_preferences_channel_id` ON `${TABLE_NAME}` (`channel_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "channels",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "channel_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "channels_fts",
+ "createSql": "CREATE VIRTUAL TABLE IF NOT EXISTS `${TABLE_NAME}` USING FTS4(`name` TEXT NOT NULL, content=`channels`)",
+ "fields": [
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": []
+ },
+ "ftsVersion": "FTS4",
+ "ftsOptions": {
+ "tokenizer": "simple",
+ "tokenizerArgs": [],
+ "contentTable": "channels",
+ "languageIdColumnName": "",
+ "matchInfo": "FTS4",
+ "notIndexedColumns": [],
+ "prefixSizes": [],
+ "preferredOrder": "ASC"
+ },
+ "contentSyncTriggers": [
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_BEFORE_UPDATE BEFORE UPDATE ON `channels` BEGIN DELETE FROM `channels_fts` WHERE `docid`=OLD.`rowid`; END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_BEFORE_DELETE BEFORE DELETE ON `channels` BEGIN DELETE FROM `channels_fts` WHERE `docid`=OLD.`rowid`; END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_AFTER_UPDATE AFTER UPDATE ON `channels` BEGIN INSERT INTO `channels_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_AFTER_INSERT AFTER INSERT ON `channels` BEGIN INSERT INTO `channels_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END"
+ ]
+ },
+ {
+ "tableName": "movies",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `stream_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `poster_url` TEXT, `backdrop_url` TEXT, `category_id` INTEGER, `category_name` TEXT, `stream_url` TEXT NOT NULL, `container_extension` TEXT, `plot` TEXT, `cast` TEXT, `director` TEXT, `genre` TEXT, `release_date` TEXT, `duration` TEXT, `duration_seconds` INTEGER NOT NULL, `rating` REAL NOT NULL, `year` TEXT, `tmdb_id` INTEGER, `youtube_trailer` TEXT, `provider_id` INTEGER NOT NULL, `watch_progress` INTEGER NOT NULL, `last_watched_at` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "streamId",
+ "columnName": "stream_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "posterUrl",
+ "columnName": "poster_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "backdropUrl",
+ "columnName": "backdrop_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "categoryId",
+ "columnName": "category_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "categoryName",
+ "columnName": "category_name",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "streamUrl",
+ "columnName": "stream_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "containerExtension",
+ "columnName": "container_extension",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "plot",
+ "columnName": "plot",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "cast",
+ "columnName": "cast",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "director",
+ "columnName": "director",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "genre",
+ "columnName": "genre",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "releaseDate",
+ "columnName": "release_date",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "duration",
+ "columnName": "duration",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "durationSeconds",
+ "columnName": "duration_seconds",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "rating",
+ "columnName": "rating",
+ "affinity": "REAL",
+ "notNull": true
+ },
+ {
+ "fieldPath": "year",
+ "columnName": "year",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "tmdbId",
+ "columnName": "tmdb_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "youtubeTrailer",
+ "columnName": "youtube_trailer",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "watchProgress",
+ "columnName": "watch_progress",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastWatchedAt",
+ "columnName": "last_watched_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isAdult",
+ "columnName": "is_adult",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isUserProtected",
+ "columnName": "is_user_protected",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "syncFingerprint",
+ "columnName": "sync_fingerprint",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_movies_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_movies_provider_id_category_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "category_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id_category_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`)"
+ },
+ {
+ "name": "index_movies_provider_id_stream_id",
+ "unique": true,
+ "columnNames": [
+ "provider_id",
+ "stream_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_movies_provider_id_stream_id` ON `${TABLE_NAME}` (`provider_id`, `stream_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "movies_fts",
+ "createSql": "CREATE VIRTUAL TABLE IF NOT EXISTS `${TABLE_NAME}` USING FTS4(`name` TEXT NOT NULL, content=`movies`)",
+ "fields": [
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": []
+ },
+ "ftsVersion": "FTS4",
+ "ftsOptions": {
+ "tokenizer": "simple",
+ "tokenizerArgs": [],
+ "contentTable": "movies",
+ "languageIdColumnName": "",
+ "matchInfo": "FTS4",
+ "notIndexedColumns": [],
+ "prefixSizes": [],
+ "preferredOrder": "ASC"
+ },
+ "contentSyncTriggers": [
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_movies_fts_BEFORE_UPDATE BEFORE UPDATE ON `movies` BEGIN DELETE FROM `movies_fts` WHERE `docid`=OLD.`rowid`; END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_movies_fts_BEFORE_DELETE BEFORE DELETE ON `movies` BEGIN DELETE FROM `movies_fts` WHERE `docid`=OLD.`rowid`; END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_movies_fts_AFTER_UPDATE AFTER UPDATE ON `movies` BEGIN INSERT INTO `movies_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_movies_fts_AFTER_INSERT AFTER INSERT ON `movies` BEGIN INSERT INTO `movies_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END"
+ ]
+ },
+ {
+ "tableName": "series",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `series_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `poster_url` TEXT, `backdrop_url` TEXT, `category_id` INTEGER, `category_name` TEXT, `plot` TEXT, `cast` TEXT, `director` TEXT, `genre` TEXT, `release_date` TEXT, `rating` REAL NOT NULL, `tmdb_id` INTEGER, `youtube_trailer` TEXT, `episode_run_time` TEXT, `last_modified` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "seriesId",
+ "columnName": "series_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "posterUrl",
+ "columnName": "poster_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "backdropUrl",
+ "columnName": "backdrop_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "categoryId",
+ "columnName": "category_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "categoryName",
+ "columnName": "category_name",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "plot",
+ "columnName": "plot",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "cast",
+ "columnName": "cast",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "director",
+ "columnName": "director",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "genre",
+ "columnName": "genre",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "releaseDate",
+ "columnName": "release_date",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "rating",
+ "columnName": "rating",
+ "affinity": "REAL",
+ "notNull": true
+ },
+ {
+ "fieldPath": "tmdbId",
+ "columnName": "tmdb_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "youtubeTrailer",
+ "columnName": "youtube_trailer",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "episodeRunTime",
+ "columnName": "episode_run_time",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "lastModified",
+ "columnName": "last_modified",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isAdult",
+ "columnName": "is_adult",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isUserProtected",
+ "columnName": "is_user_protected",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "syncFingerprint",
+ "columnName": "sync_fingerprint",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_series_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_series_provider_id_category_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "category_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_provider_id_category_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`)"
+ },
+ {
+ "name": "index_series_provider_id_series_id",
+ "unique": true,
+ "columnNames": [
+ "provider_id",
+ "series_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_series_provider_id_series_id` ON `${TABLE_NAME}` (`provider_id`, `series_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "series_fts",
+ "createSql": "CREATE VIRTUAL TABLE IF NOT EXISTS `${TABLE_NAME}` USING FTS4(`name` TEXT NOT NULL, content=`series`)",
+ "fields": [
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": []
+ },
+ "ftsVersion": "FTS4",
+ "ftsOptions": {
+ "tokenizer": "simple",
+ "tokenizerArgs": [],
+ "contentTable": "series",
+ "languageIdColumnName": "",
+ "matchInfo": "FTS4",
+ "notIndexedColumns": [],
+ "prefixSizes": [],
+ "preferredOrder": "ASC"
+ },
+ "contentSyncTriggers": [
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_series_fts_BEFORE_UPDATE BEFORE UPDATE ON `series` BEGIN DELETE FROM `series_fts` WHERE `docid`=OLD.`rowid`; END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_series_fts_BEFORE_DELETE BEFORE DELETE ON `series` BEGIN DELETE FROM `series_fts` WHERE `docid`=OLD.`rowid`; END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_series_fts_AFTER_UPDATE AFTER UPDATE ON `series` BEGIN INSERT INTO `series_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_series_fts_AFTER_INSERT AFTER INSERT ON `series` BEGIN INSERT INTO `series_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END"
+ ]
+ },
+ {
+ "tableName": "episodes",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `episode_id` INTEGER NOT NULL, `title` TEXT NOT NULL, `episode_number` INTEGER NOT NULL, `season_number` INTEGER NOT NULL, `stream_url` TEXT NOT NULL, `container_extension` TEXT, `cover_url` TEXT, `plot` TEXT, `duration` TEXT, `duration_seconds` INTEGER NOT NULL, `rating` REAL NOT NULL, `release_date` TEXT, `series_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `watch_progress` INTEGER NOT NULL, `last_watched_at` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`series_id`) REFERENCES `series`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "episodeId",
+ "columnName": "episode_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "title",
+ "columnName": "title",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "episodeNumber",
+ "columnName": "episode_number",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "seasonNumber",
+ "columnName": "season_number",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "streamUrl",
+ "columnName": "stream_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "containerExtension",
+ "columnName": "container_extension",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "coverUrl",
+ "columnName": "cover_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "plot",
+ "columnName": "plot",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "duration",
+ "columnName": "duration",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "durationSeconds",
+ "columnName": "duration_seconds",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "rating",
+ "columnName": "rating",
+ "affinity": "REAL",
+ "notNull": true
+ },
+ {
+ "fieldPath": "releaseDate",
+ "columnName": "release_date",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "seriesId",
+ "columnName": "series_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "watchProgress",
+ "columnName": "watch_progress",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastWatchedAt",
+ "columnName": "last_watched_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isAdult",
+ "columnName": "is_adult",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isUserProtected",
+ "columnName": "is_user_protected",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_episodes_series_id",
+ "unique": false,
+ "columnNames": [
+ "series_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_episodes_series_id` ON `${TABLE_NAME}` (`series_id`)"
+ },
+ {
+ "name": "index_episodes_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_episodes_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_episodes_provider_id_episode_id",
+ "unique": true,
+ "columnNames": [
+ "provider_id",
+ "episode_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_episodes_provider_id_episode_id` ON `${TABLE_NAME}` (`provider_id`, `episode_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ },
+ {
+ "table": "series",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "series_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "categories",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `category_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `parent_id` INTEGER, `type` TEXT NOT NULL, `provider_id` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "categoryId",
+ "columnName": "category_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "parentId",
+ "columnName": "parent_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "type",
+ "columnName": "type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isAdult",
+ "columnName": "is_adult",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isUserProtected",
+ "columnName": "is_user_protected",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "syncFingerprint",
+ "columnName": "sync_fingerprint",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_categories_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_categories_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_categories_provider_id_type",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "type"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_categories_provider_id_type` ON `${TABLE_NAME}` (`provider_id`, `type`)"
+ },
+ {
+ "name": "index_categories_provider_id_category_id_type",
+ "unique": true,
+ "columnNames": [
+ "provider_id",
+ "category_id",
+ "type"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_categories_provider_id_category_id_type` ON `${TABLE_NAME}` (`provider_id`, `category_id`, `type`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "channel_import_stage",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`session_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `stream_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `logo_url` TEXT, `group_title` TEXT, `category_id` INTEGER, `category_name` TEXT, `stream_url` TEXT NOT NULL, `epg_channel_id` TEXT, `number` INTEGER NOT NULL, `catch_up_supported` INTEGER NOT NULL, `catch_up_days` INTEGER NOT NULL, `catchUpSource` TEXT, `is_adult` INTEGER NOT NULL, `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": "syncFingerprint",
+ "columnName": "sync_fingerprint",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "session_id",
+ "provider_id",
+ "stream_id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_channel_import_stage_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channel_import_stage_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_channel_import_stage_session_id_provider_id",
+ "unique": false,
+ "columnNames": [
+ "session_id",
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channel_import_stage_session_id_provider_id` ON `${TABLE_NAME}` (`session_id`, `provider_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "movie_import_stage",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`session_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `stream_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `poster_url` TEXT, `backdrop_url` TEXT, `category_id` INTEGER, `category_name` TEXT, `stream_url` TEXT NOT NULL, `container_extension` TEXT, `plot` TEXT, `cast` TEXT, `director` TEXT, `genre` TEXT, `release_date` TEXT, `duration` TEXT, `duration_seconds` INTEGER NOT NULL, `rating` REAL NOT NULL, `year` TEXT, `tmdb_id` INTEGER, `youtube_trailer` TEXT, `is_adult` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, PRIMARY KEY(`session_id`, `provider_id`, `stream_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "sessionId",
+ "columnName": "session_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "streamId",
+ "columnName": "stream_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "posterUrl",
+ "columnName": "poster_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "backdropUrl",
+ "columnName": "backdrop_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "categoryId",
+ "columnName": "category_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "categoryName",
+ "columnName": "category_name",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "streamUrl",
+ "columnName": "stream_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "containerExtension",
+ "columnName": "container_extension",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "plot",
+ "columnName": "plot",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "cast",
+ "columnName": "cast",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "director",
+ "columnName": "director",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "genre",
+ "columnName": "genre",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "releaseDate",
+ "columnName": "release_date",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "duration",
+ "columnName": "duration",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "durationSeconds",
+ "columnName": "duration_seconds",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "rating",
+ "columnName": "rating",
+ "affinity": "REAL",
+ "notNull": true
+ },
+ {
+ "fieldPath": "year",
+ "columnName": "year",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "tmdbId",
+ "columnName": "tmdb_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "youtubeTrailer",
+ "columnName": "youtube_trailer",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "isAdult",
+ "columnName": "is_adult",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "syncFingerprint",
+ "columnName": "sync_fingerprint",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "session_id",
+ "provider_id",
+ "stream_id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_movie_import_stage_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movie_import_stage_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_movie_import_stage_session_id_provider_id",
+ "unique": false,
+ "columnNames": [
+ "session_id",
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movie_import_stage_session_id_provider_id` ON `${TABLE_NAME}` (`session_id`, `provider_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "series_import_stage",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`session_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `series_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `poster_url` TEXT, `backdrop_url` TEXT, `category_id` INTEGER, `category_name` TEXT, `plot` TEXT, `cast` TEXT, `director` TEXT, `genre` TEXT, `release_date` TEXT, `rating` REAL NOT NULL, `tmdb_id` INTEGER, `youtube_trailer` TEXT, `episode_run_time` TEXT, `last_modified` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, PRIMARY KEY(`session_id`, `provider_id`, `series_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "sessionId",
+ "columnName": "session_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "seriesId",
+ "columnName": "series_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "posterUrl",
+ "columnName": "poster_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "backdropUrl",
+ "columnName": "backdrop_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "categoryId",
+ "columnName": "category_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "categoryName",
+ "columnName": "category_name",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "plot",
+ "columnName": "plot",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "cast",
+ "columnName": "cast",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "director",
+ "columnName": "director",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "genre",
+ "columnName": "genre",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "releaseDate",
+ "columnName": "release_date",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "rating",
+ "columnName": "rating",
+ "affinity": "REAL",
+ "notNull": true
+ },
+ {
+ "fieldPath": "tmdbId",
+ "columnName": "tmdb_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "youtubeTrailer",
+ "columnName": "youtube_trailer",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "episodeRunTime",
+ "columnName": "episode_run_time",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "lastModified",
+ "columnName": "last_modified",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isAdult",
+ "columnName": "is_adult",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "syncFingerprint",
+ "columnName": "sync_fingerprint",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "session_id",
+ "provider_id",
+ "series_id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_series_import_stage_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_import_stage_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_series_import_stage_session_id_provider_id",
+ "unique": false,
+ "columnNames": [
+ "session_id",
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_import_stage_session_id_provider_id` ON `${TABLE_NAME}` (`session_id`, `provider_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "category_import_stage",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`session_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `category_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `parent_id` INTEGER, `type` TEXT NOT NULL, `is_adult` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, PRIMARY KEY(`session_id`, `provider_id`, `category_id`, `type`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "sessionId",
+ "columnName": "session_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "categoryId",
+ "columnName": "category_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "parentId",
+ "columnName": "parent_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "type",
+ "columnName": "type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isAdult",
+ "columnName": "is_adult",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "syncFingerprint",
+ "columnName": "sync_fingerprint",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "session_id",
+ "provider_id",
+ "category_id",
+ "type"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_category_import_stage_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_category_import_stage_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_category_import_stage_session_id_provider_id",
+ "unique": false,
+ "columnNames": [
+ "session_id",
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_category_import_stage_session_id_provider_id` ON `${TABLE_NAME}` (`session_id`, `provider_id`)"
+ },
+ {
+ "name": "index_category_import_stage_provider_id_type",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "type"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_category_import_stage_provider_id_type` ON `${TABLE_NAME}` (`provider_id`, `type`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "programs",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `channel_id` TEXT NOT NULL, `title` TEXT NOT NULL, `description` TEXT NOT NULL, `start_time` INTEGER NOT NULL, `end_time` INTEGER NOT NULL, `lang` TEXT NOT NULL, `rating` TEXT, `image_url` TEXT, `genre` TEXT, `category` TEXT, `has_archive` INTEGER NOT NULL)",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "channelId",
+ "columnName": "channel_id",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "title",
+ "columnName": "title",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "description",
+ "columnName": "description",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "startTime",
+ "columnName": "start_time",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "endTime",
+ "columnName": "end_time",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lang",
+ "columnName": "lang",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "rating",
+ "columnName": "rating",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "imageUrl",
+ "columnName": "image_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "genre",
+ "columnName": "genre",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "category",
+ "columnName": "category",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "hasArchive",
+ "columnName": "has_archive",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_programs_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_programs_provider_id_channel_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "channel_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_channel_id` ON `${TABLE_NAME}` (`provider_id`, `channel_id`)"
+ },
+ {
+ "name": "index_programs_provider_id_start_time_end_time",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "start_time",
+ "end_time"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_start_time_end_time` ON `${TABLE_NAME}` (`provider_id`, `start_time`, `end_time`)"
+ },
+ {
+ "name": "index_programs_start_time",
+ "unique": false,
+ "columnNames": [
+ "start_time"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_start_time` ON `${TABLE_NAME}` (`start_time`)"
+ },
+ {
+ "name": "index_programs_provider_id_channel_id_start_time",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "channel_id",
+ "start_time"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_channel_id_start_time` ON `${TABLE_NAME}` (`provider_id`, `channel_id`, `start_time`)"
+ },
+ {
+ "name": "index_programs_provider_id_channel_id_start_time_end_time",
+ "unique": true,
+ "columnNames": [
+ "provider_id",
+ "channel_id",
+ "start_time",
+ "end_time"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_programs_provider_id_channel_id_start_time_end_time` ON `${TABLE_NAME}` (`provider_id`, `channel_id`, `start_time`, `end_time`)"
+ }
+ ]
+ },
+ {
+ "tableName": "favorites",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `content_id` INTEGER NOT NULL, `content_type` TEXT NOT NULL, `position` INTEGER NOT NULL, `group_id` INTEGER, `added_at` INTEGER NOT NULL, FOREIGN KEY(`group_id`) REFERENCES `virtual_groups`(`id`) ON UPDATE NO ACTION ON DELETE SET NULL )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "contentId",
+ "columnName": "content_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "contentType",
+ "columnName": "content_type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "position",
+ "columnName": "position",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "groupId",
+ "columnName": "group_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "addedAt",
+ "columnName": "added_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_favorites_content_id_content_type_group_id",
+ "unique": true,
+ "columnNames": [
+ "content_id",
+ "content_type",
+ "group_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_favorites_content_id_content_type_group_id` ON `${TABLE_NAME}` (`content_id`, `content_type`, `group_id`)"
+ },
+ {
+ "name": "index_favorites_content_type_group_id",
+ "unique": false,
+ "columnNames": [
+ "content_type",
+ "group_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_favorites_content_type_group_id` ON `${TABLE_NAME}` (`content_type`, `group_id`)"
+ },
+ {
+ "name": "index_favorites_group_id_position",
+ "unique": false,
+ "columnNames": [
+ "group_id",
+ "position"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_favorites_group_id_position` ON `${TABLE_NAME}` (`group_id`, `position`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "virtual_groups",
+ "onDelete": "SET NULL",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "group_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "virtual_groups",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `icon_emoji` TEXT, `position` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `content_type` TEXT NOT NULL)",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "iconEmoji",
+ "columnName": "icon_emoji",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "position",
+ "columnName": "position",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "createdAt",
+ "columnName": "created_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "contentType",
+ "columnName": "content_type",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_virtual_groups_position",
+ "unique": false,
+ "columnNames": [
+ "position"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_virtual_groups_position` ON `${TABLE_NAME}` (`position`)"
+ },
+ {
+ "name": "index_virtual_groups_content_type",
+ "unique": false,
+ "columnNames": [
+ "content_type"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_virtual_groups_content_type` ON `${TABLE_NAME}` (`content_type`)"
+ }
+ ]
+ },
+ {
+ "tableName": "playback_history",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `content_id` INTEGER NOT NULL, `content_type` TEXT NOT NULL, `provider_id` INTEGER NOT NULL, `title` TEXT NOT NULL, `poster_url` TEXT, `stream_url` TEXT NOT NULL, `resume_position_ms` INTEGER NOT NULL, `total_duration_ms` INTEGER NOT NULL, `last_watched_at` INTEGER NOT NULL, `watch_count` INTEGER NOT NULL, `watched_status` TEXT NOT NULL, `series_id` INTEGER, `season_number` INTEGER, `episode_number` INTEGER, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "contentId",
+ "columnName": "content_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "contentType",
+ "columnName": "content_type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "title",
+ "columnName": "title",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "posterUrl",
+ "columnName": "poster_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "streamUrl",
+ "columnName": "stream_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "resumePositionMs",
+ "columnName": "resume_position_ms",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "totalDurationMs",
+ "columnName": "total_duration_ms",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastWatchedAt",
+ "columnName": "last_watched_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "watchCount",
+ "columnName": "watch_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "watchedStatus",
+ "columnName": "watched_status",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "seriesId",
+ "columnName": "series_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "seasonNumber",
+ "columnName": "season_number",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "episodeNumber",
+ "columnName": "episode_number",
+ "affinity": "INTEGER"
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_playback_history_content_id_content_type_provider_id",
+ "unique": true,
+ "columnNames": [
+ "content_id",
+ "content_type",
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_playback_history_content_id_content_type_provider_id` ON `${TABLE_NAME}` (`content_id`, `content_type`, `provider_id`)"
+ },
+ {
+ "name": "index_playback_history_last_watched_at",
+ "unique": false,
+ "columnNames": [
+ "last_watched_at"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_history_last_watched_at` ON `${TABLE_NAME}` (`last_watched_at`)"
+ },
+ {
+ "name": "index_playback_history_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_history_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "sync_metadata",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `last_live_sync` INTEGER NOT NULL, `last_movie_sync` INTEGER NOT NULL, `last_series_sync` INTEGER NOT NULL, `last_epg_sync` INTEGER NOT NULL, `last_movie_attempt` INTEGER NOT NULL, `last_movie_success` INTEGER NOT NULL, `last_movie_partial` INTEGER NOT NULL, `live_count` INTEGER NOT NULL, `movie_count` INTEGER NOT NULL, `series_count` INTEGER NOT NULL, `epg_count` INTEGER NOT NULL, `last_sync_status` TEXT NOT NULL, `movie_sync_mode` TEXT NOT NULL, `movie_warnings_count` INTEGER NOT NULL, `movie_catalog_stale` INTEGER NOT NULL, `live_avoid_full_until` INTEGER NOT NULL, `movie_avoid_full_until` INTEGER NOT NULL, `series_avoid_full_until` INTEGER NOT NULL, `live_sequential_failures_remembered` INTEGER NOT NULL, `live_healthy_sync_streak` INTEGER NOT NULL, `movie_parallel_failures_remembered` INTEGER NOT NULL, `movie_healthy_sync_streak` INTEGER NOT NULL, `series_sequential_failures_remembered` INTEGER NOT NULL, `series_healthy_sync_streak` INTEGER NOT NULL, PRIMARY KEY(`provider_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastLiveSync",
+ "columnName": "last_live_sync",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastMovieSync",
+ "columnName": "last_movie_sync",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastSeriesSync",
+ "columnName": "last_series_sync",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastEpgSync",
+ "columnName": "last_epg_sync",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastMovieAttempt",
+ "columnName": "last_movie_attempt",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastMovieSuccess",
+ "columnName": "last_movie_success",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastMoviePartial",
+ "columnName": "last_movie_partial",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "liveCount",
+ "columnName": "live_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "movieCount",
+ "columnName": "movie_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "seriesCount",
+ "columnName": "series_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "epgCount",
+ "columnName": "epg_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastSyncStatus",
+ "columnName": "last_sync_status",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "movieSyncMode",
+ "columnName": "movie_sync_mode",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "movieWarningsCount",
+ "columnName": "movie_warnings_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "movieCatalogStale",
+ "columnName": "movie_catalog_stale",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "liveAvoidFullUntil",
+ "columnName": "live_avoid_full_until",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "movieAvoidFullUntil",
+ "columnName": "movie_avoid_full_until",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "seriesAvoidFullUntil",
+ "columnName": "series_avoid_full_until",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "liveSequentialFailuresRemembered",
+ "columnName": "live_sequential_failures_remembered",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "liveHealthySyncStreak",
+ "columnName": "live_healthy_sync_streak",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "movieParallelFailuresRemembered",
+ "columnName": "movie_parallel_failures_remembered",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "movieHealthySyncStreak",
+ "columnName": "movie_healthy_sync_streak",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "seriesSequentialFailuresRemembered",
+ "columnName": "series_sequential_failures_remembered",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "seriesHealthySyncStreak",
+ "columnName": "series_healthy_sync_streak",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "provider_id"
+ ]
+ },
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ }
+ ],
+ "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, 'de797a58d92b18ec468d1d77481286a7')"
+ ]
+ }
+}
\ No newline at end of file
diff --git a/data/schemas/com.streamvault.data.local.StreamVaultDatabase/22.json b/data/schemas/com.streamvault.data.local.StreamVaultDatabase/22.json
new file mode 100644
index 00000000..6d88286e
--- /dev/null
+++ b/data/schemas/com.streamvault.data.local.StreamVaultDatabase/22.json
@@ -0,0 +1,2336 @@
+{
+ "formatVersion": 1,
+ "database": {
+ "version": 22,
+ "identityHash": "3ad126acc18a09e82756c34ff9a80fbb",
+ "entities": [
+ {
+ "tableName": "providers",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `type` TEXT NOT NULL, `server_url` TEXT NOT NULL, `username` TEXT NOT NULL, `password` TEXT NOT NULL, `m3u_url` TEXT NOT NULL, `epg_url` TEXT NOT NULL, `is_active` INTEGER NOT NULL, `max_connections` INTEGER NOT NULL, `expiration_date` INTEGER, `api_version` TEXT, `allowed_output_formats_json` TEXT NOT NULL, `status` TEXT NOT NULL, `last_synced_at` INTEGER NOT NULL, `created_at` INTEGER NOT NULL)",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "type",
+ "columnName": "type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "serverUrl",
+ "columnName": "server_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "username",
+ "columnName": "username",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "password",
+ "columnName": "password",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "m3uUrl",
+ "columnName": "m3u_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "epgUrl",
+ "columnName": "epg_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isActive",
+ "columnName": "is_active",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "maxConnections",
+ "columnName": "max_connections",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "expirationDate",
+ "columnName": "expiration_date",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "apiVersion",
+ "columnName": "api_version",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "allowedOutputFormatsJson",
+ "columnName": "allowed_output_formats_json",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "status",
+ "columnName": "status",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastSyncedAt",
+ "columnName": "last_synced_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "createdAt",
+ "columnName": "created_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_providers_server_url_username",
+ "unique": true,
+ "columnNames": [
+ "server_url",
+ "username"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_providers_server_url_username` ON `${TABLE_NAME}` (`server_url`, `username`)"
+ }
+ ]
+ },
+ {
+ "tableName": "channels",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `stream_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `logo_url` TEXT, `group_title` TEXT, `category_id` INTEGER, `category_name` TEXT, `stream_url` TEXT NOT NULL, `epg_channel_id` TEXT, `number` INTEGER NOT NULL, `catch_up_supported` INTEGER NOT NULL, `catch_up_days` INTEGER NOT NULL, `catchUpSource` TEXT, `provider_id` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, `logical_group_id` TEXT NOT NULL, `error_count` INTEGER NOT NULL, `quality_options_json` TEXT, `sync_fingerprint` TEXT NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "streamId",
+ "columnName": "stream_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "logoUrl",
+ "columnName": "logo_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "groupTitle",
+ "columnName": "group_title",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "categoryId",
+ "columnName": "category_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "categoryName",
+ "columnName": "category_name",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "streamUrl",
+ "columnName": "stream_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "epgChannelId",
+ "columnName": "epg_channel_id",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "number",
+ "columnName": "number",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "catchUpSupported",
+ "columnName": "catch_up_supported",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "catchUpDays",
+ "columnName": "catch_up_days",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "catchUpSource",
+ "columnName": "catchUpSource",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isAdult",
+ "columnName": "is_adult",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isUserProtected",
+ "columnName": "is_user_protected",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "logicalGroupId",
+ "columnName": "logical_group_id",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "errorCount",
+ "columnName": "error_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "qualityOptionsJson",
+ "columnName": "quality_options_json",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "syncFingerprint",
+ "columnName": "sync_fingerprint",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_channels_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_channels_provider_id_category_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "category_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_provider_id_category_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`)"
+ },
+ {
+ "name": "index_channels_provider_id_stream_id",
+ "unique": true,
+ "columnNames": [
+ "provider_id",
+ "stream_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_channels_provider_id_stream_id` ON `${TABLE_NAME}` (`provider_id`, `stream_id`)"
+ },
+ {
+ "name": "index_channels_logical_group_id",
+ "unique": false,
+ "columnNames": [
+ "logical_group_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_logical_group_id` ON `${TABLE_NAME}` (`logical_group_id`)"
+ },
+ {
+ "name": "index_channels_provider_id_category_id_logical_group_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "category_id",
+ "logical_group_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_provider_id_category_id_logical_group_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`, `logical_group_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "channel_preferences",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `channel_id` INTEGER NOT NULL, `aspect_ratio` TEXT, `updated_at` INTEGER NOT NULL, FOREIGN KEY(`channel_id`) REFERENCES `channels`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "channelId",
+ "columnName": "channel_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "aspectRatio",
+ "columnName": "aspect_ratio",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "updatedAt",
+ "columnName": "updated_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_channel_preferences_channel_id",
+ "unique": true,
+ "columnNames": [
+ "channel_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_channel_preferences_channel_id` ON `${TABLE_NAME}` (`channel_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "channels",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "channel_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "channels_fts",
+ "createSql": "CREATE VIRTUAL TABLE IF NOT EXISTS `${TABLE_NAME}` USING FTS4(`name` TEXT NOT NULL, content=`channels`)",
+ "fields": [
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": []
+ },
+ "ftsVersion": "FTS4",
+ "ftsOptions": {
+ "tokenizer": "simple",
+ "tokenizerArgs": [],
+ "contentTable": "channels",
+ "languageIdColumnName": "",
+ "matchInfo": "FTS4",
+ "notIndexedColumns": [],
+ "prefixSizes": [],
+ "preferredOrder": "ASC"
+ },
+ "contentSyncTriggers": [
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_BEFORE_UPDATE BEFORE UPDATE ON `channels` BEGIN DELETE FROM `channels_fts` WHERE `docid`=OLD.`rowid`; END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_BEFORE_DELETE BEFORE DELETE ON `channels` BEGIN DELETE FROM `channels_fts` WHERE `docid`=OLD.`rowid`; END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_AFTER_UPDATE AFTER UPDATE ON `channels` BEGIN INSERT INTO `channels_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_AFTER_INSERT AFTER INSERT ON `channels` BEGIN INSERT INTO `channels_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END"
+ ]
+ },
+ {
+ "tableName": "movies",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `stream_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `poster_url` TEXT, `backdrop_url` TEXT, `category_id` INTEGER, `category_name` TEXT, `stream_url` TEXT NOT NULL, `container_extension` TEXT, `plot` TEXT, `cast` TEXT, `director` TEXT, `genre` TEXT, `release_date` TEXT, `duration` TEXT, `duration_seconds` INTEGER NOT NULL, `rating` REAL NOT NULL, `year` TEXT, `tmdb_id` INTEGER, `youtube_trailer` TEXT, `provider_id` INTEGER NOT NULL, `watch_progress` INTEGER NOT NULL, `last_watched_at` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "streamId",
+ "columnName": "stream_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "posterUrl",
+ "columnName": "poster_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "backdropUrl",
+ "columnName": "backdrop_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "categoryId",
+ "columnName": "category_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "categoryName",
+ "columnName": "category_name",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "streamUrl",
+ "columnName": "stream_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "containerExtension",
+ "columnName": "container_extension",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "plot",
+ "columnName": "plot",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "cast",
+ "columnName": "cast",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "director",
+ "columnName": "director",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "genre",
+ "columnName": "genre",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "releaseDate",
+ "columnName": "release_date",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "duration",
+ "columnName": "duration",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "durationSeconds",
+ "columnName": "duration_seconds",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "rating",
+ "columnName": "rating",
+ "affinity": "REAL",
+ "notNull": true
+ },
+ {
+ "fieldPath": "year",
+ "columnName": "year",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "tmdbId",
+ "columnName": "tmdb_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "youtubeTrailer",
+ "columnName": "youtube_trailer",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "watchProgress",
+ "columnName": "watch_progress",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastWatchedAt",
+ "columnName": "last_watched_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isAdult",
+ "columnName": "is_adult",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isUserProtected",
+ "columnName": "is_user_protected",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "syncFingerprint",
+ "columnName": "sync_fingerprint",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_movies_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_movies_provider_id_category_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "category_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id_category_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`)"
+ },
+ {
+ "name": "index_movies_provider_id_stream_id",
+ "unique": true,
+ "columnNames": [
+ "provider_id",
+ "stream_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_movies_provider_id_stream_id` ON `${TABLE_NAME}` (`provider_id`, `stream_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "movies_fts",
+ "createSql": "CREATE VIRTUAL TABLE IF NOT EXISTS `${TABLE_NAME}` USING FTS4(`name` TEXT NOT NULL, content=`movies`)",
+ "fields": [
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": []
+ },
+ "ftsVersion": "FTS4",
+ "ftsOptions": {
+ "tokenizer": "simple",
+ "tokenizerArgs": [],
+ "contentTable": "movies",
+ "languageIdColumnName": "",
+ "matchInfo": "FTS4",
+ "notIndexedColumns": [],
+ "prefixSizes": [],
+ "preferredOrder": "ASC"
+ },
+ "contentSyncTriggers": [
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_movies_fts_BEFORE_UPDATE BEFORE UPDATE ON `movies` BEGIN DELETE FROM `movies_fts` WHERE `docid`=OLD.`rowid`; END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_movies_fts_BEFORE_DELETE BEFORE DELETE ON `movies` BEGIN DELETE FROM `movies_fts` WHERE `docid`=OLD.`rowid`; END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_movies_fts_AFTER_UPDATE AFTER UPDATE ON `movies` BEGIN INSERT INTO `movies_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_movies_fts_AFTER_INSERT AFTER INSERT ON `movies` BEGIN INSERT INTO `movies_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END"
+ ]
+ },
+ {
+ "tableName": "series",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `series_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `poster_url` TEXT, `backdrop_url` TEXT, `category_id` INTEGER, `category_name` TEXT, `plot` TEXT, `cast` TEXT, `director` TEXT, `genre` TEXT, `release_date` TEXT, `rating` REAL NOT NULL, `tmdb_id` INTEGER, `youtube_trailer` TEXT, `episode_run_time` TEXT, `last_modified` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "seriesId",
+ "columnName": "series_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "posterUrl",
+ "columnName": "poster_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "backdropUrl",
+ "columnName": "backdrop_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "categoryId",
+ "columnName": "category_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "categoryName",
+ "columnName": "category_name",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "plot",
+ "columnName": "plot",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "cast",
+ "columnName": "cast",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "director",
+ "columnName": "director",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "genre",
+ "columnName": "genre",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "releaseDate",
+ "columnName": "release_date",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "rating",
+ "columnName": "rating",
+ "affinity": "REAL",
+ "notNull": true
+ },
+ {
+ "fieldPath": "tmdbId",
+ "columnName": "tmdb_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "youtubeTrailer",
+ "columnName": "youtube_trailer",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "episodeRunTime",
+ "columnName": "episode_run_time",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "lastModified",
+ "columnName": "last_modified",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isAdult",
+ "columnName": "is_adult",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isUserProtected",
+ "columnName": "is_user_protected",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "syncFingerprint",
+ "columnName": "sync_fingerprint",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_series_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_series_provider_id_category_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "category_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_provider_id_category_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`)"
+ },
+ {
+ "name": "index_series_provider_id_series_id",
+ "unique": true,
+ "columnNames": [
+ "provider_id",
+ "series_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_series_provider_id_series_id` ON `${TABLE_NAME}` (`provider_id`, `series_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "series_fts",
+ "createSql": "CREATE VIRTUAL TABLE IF NOT EXISTS `${TABLE_NAME}` USING FTS4(`name` TEXT NOT NULL, content=`series`)",
+ "fields": [
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": []
+ },
+ "ftsVersion": "FTS4",
+ "ftsOptions": {
+ "tokenizer": "simple",
+ "tokenizerArgs": [],
+ "contentTable": "series",
+ "languageIdColumnName": "",
+ "matchInfo": "FTS4",
+ "notIndexedColumns": [],
+ "prefixSizes": [],
+ "preferredOrder": "ASC"
+ },
+ "contentSyncTriggers": [
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_series_fts_BEFORE_UPDATE BEFORE UPDATE ON `series` BEGIN DELETE FROM `series_fts` WHERE `docid`=OLD.`rowid`; END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_series_fts_BEFORE_DELETE BEFORE DELETE ON `series` BEGIN DELETE FROM `series_fts` WHERE `docid`=OLD.`rowid`; END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_series_fts_AFTER_UPDATE AFTER UPDATE ON `series` BEGIN INSERT INTO `series_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_series_fts_AFTER_INSERT AFTER INSERT ON `series` BEGIN INSERT INTO `series_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END"
+ ]
+ },
+ {
+ "tableName": "episodes",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `episode_id` INTEGER NOT NULL, `title` TEXT NOT NULL, `episode_number` INTEGER NOT NULL, `season_number` INTEGER NOT NULL, `stream_url` TEXT NOT NULL, `container_extension` TEXT, `cover_url` TEXT, `plot` TEXT, `duration` TEXT, `duration_seconds` INTEGER NOT NULL, `rating` REAL NOT NULL, `release_date` TEXT, `series_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `watch_progress` INTEGER NOT NULL, `last_watched_at` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`series_id`) REFERENCES `series`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "episodeId",
+ "columnName": "episode_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "title",
+ "columnName": "title",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "episodeNumber",
+ "columnName": "episode_number",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "seasonNumber",
+ "columnName": "season_number",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "streamUrl",
+ "columnName": "stream_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "containerExtension",
+ "columnName": "container_extension",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "coverUrl",
+ "columnName": "cover_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "plot",
+ "columnName": "plot",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "duration",
+ "columnName": "duration",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "durationSeconds",
+ "columnName": "duration_seconds",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "rating",
+ "columnName": "rating",
+ "affinity": "REAL",
+ "notNull": true
+ },
+ {
+ "fieldPath": "releaseDate",
+ "columnName": "release_date",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "seriesId",
+ "columnName": "series_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "watchProgress",
+ "columnName": "watch_progress",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastWatchedAt",
+ "columnName": "last_watched_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isAdult",
+ "columnName": "is_adult",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isUserProtected",
+ "columnName": "is_user_protected",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_episodes_series_id",
+ "unique": false,
+ "columnNames": [
+ "series_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_episodes_series_id` ON `${TABLE_NAME}` (`series_id`)"
+ },
+ {
+ "name": "index_episodes_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_episodes_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_episodes_provider_id_episode_id",
+ "unique": true,
+ "columnNames": [
+ "provider_id",
+ "episode_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_episodes_provider_id_episode_id` ON `${TABLE_NAME}` (`provider_id`, `episode_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ },
+ {
+ "table": "series",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "series_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "categories",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `category_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `parent_id` INTEGER, `type` TEXT NOT NULL, `provider_id` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "categoryId",
+ "columnName": "category_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "parentId",
+ "columnName": "parent_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "type",
+ "columnName": "type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isAdult",
+ "columnName": "is_adult",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isUserProtected",
+ "columnName": "is_user_protected",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "syncFingerprint",
+ "columnName": "sync_fingerprint",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_categories_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_categories_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_categories_provider_id_type",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "type"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_categories_provider_id_type` ON `${TABLE_NAME}` (`provider_id`, `type`)"
+ },
+ {
+ "name": "index_categories_provider_id_category_id_type",
+ "unique": true,
+ "columnNames": [
+ "provider_id",
+ "category_id",
+ "type"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_categories_provider_id_category_id_type` ON `${TABLE_NAME}` (`provider_id`, `category_id`, `type`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "channel_import_stage",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`session_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `stream_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `logo_url` TEXT, `group_title` TEXT, `category_id` INTEGER, `category_name` TEXT, `stream_url` TEXT NOT NULL, `epg_channel_id` TEXT, `number` INTEGER NOT NULL, `catch_up_supported` INTEGER NOT NULL, `catch_up_days` INTEGER NOT NULL, `catchUpSource` TEXT, `is_adult` INTEGER NOT NULL, `logical_group_id` TEXT NOT NULL, `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": "syncFingerprint",
+ "columnName": "sync_fingerprint",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "session_id",
+ "provider_id",
+ "stream_id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_channel_import_stage_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channel_import_stage_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_channel_import_stage_session_id_provider_id",
+ "unique": false,
+ "columnNames": [
+ "session_id",
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channel_import_stage_session_id_provider_id` ON `${TABLE_NAME}` (`session_id`, `provider_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "movie_import_stage",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`session_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `stream_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `poster_url` TEXT, `backdrop_url` TEXT, `category_id` INTEGER, `category_name` TEXT, `stream_url` TEXT NOT NULL, `container_extension` TEXT, `plot` TEXT, `cast` TEXT, `director` TEXT, `genre` TEXT, `release_date` TEXT, `duration` TEXT, `duration_seconds` INTEGER NOT NULL, `rating` REAL NOT NULL, `year` TEXT, `tmdb_id` INTEGER, `youtube_trailer` TEXT, `is_adult` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, PRIMARY KEY(`session_id`, `provider_id`, `stream_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "sessionId",
+ "columnName": "session_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "streamId",
+ "columnName": "stream_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "posterUrl",
+ "columnName": "poster_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "backdropUrl",
+ "columnName": "backdrop_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "categoryId",
+ "columnName": "category_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "categoryName",
+ "columnName": "category_name",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "streamUrl",
+ "columnName": "stream_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "containerExtension",
+ "columnName": "container_extension",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "plot",
+ "columnName": "plot",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "cast",
+ "columnName": "cast",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "director",
+ "columnName": "director",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "genre",
+ "columnName": "genre",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "releaseDate",
+ "columnName": "release_date",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "duration",
+ "columnName": "duration",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "durationSeconds",
+ "columnName": "duration_seconds",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "rating",
+ "columnName": "rating",
+ "affinity": "REAL",
+ "notNull": true
+ },
+ {
+ "fieldPath": "year",
+ "columnName": "year",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "tmdbId",
+ "columnName": "tmdb_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "youtubeTrailer",
+ "columnName": "youtube_trailer",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "isAdult",
+ "columnName": "is_adult",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "syncFingerprint",
+ "columnName": "sync_fingerprint",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "session_id",
+ "provider_id",
+ "stream_id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_movie_import_stage_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movie_import_stage_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_movie_import_stage_session_id_provider_id",
+ "unique": false,
+ "columnNames": [
+ "session_id",
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movie_import_stage_session_id_provider_id` ON `${TABLE_NAME}` (`session_id`, `provider_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "series_import_stage",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`session_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `series_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `poster_url` TEXT, `backdrop_url` TEXT, `category_id` INTEGER, `category_name` TEXT, `plot` TEXT, `cast` TEXT, `director` TEXT, `genre` TEXT, `release_date` TEXT, `rating` REAL NOT NULL, `tmdb_id` INTEGER, `youtube_trailer` TEXT, `episode_run_time` TEXT, `last_modified` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, PRIMARY KEY(`session_id`, `provider_id`, `series_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "sessionId",
+ "columnName": "session_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "seriesId",
+ "columnName": "series_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "posterUrl",
+ "columnName": "poster_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "backdropUrl",
+ "columnName": "backdrop_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "categoryId",
+ "columnName": "category_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "categoryName",
+ "columnName": "category_name",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "plot",
+ "columnName": "plot",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "cast",
+ "columnName": "cast",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "director",
+ "columnName": "director",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "genre",
+ "columnName": "genre",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "releaseDate",
+ "columnName": "release_date",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "rating",
+ "columnName": "rating",
+ "affinity": "REAL",
+ "notNull": true
+ },
+ {
+ "fieldPath": "tmdbId",
+ "columnName": "tmdb_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "youtubeTrailer",
+ "columnName": "youtube_trailer",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "episodeRunTime",
+ "columnName": "episode_run_time",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "lastModified",
+ "columnName": "last_modified",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isAdult",
+ "columnName": "is_adult",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "syncFingerprint",
+ "columnName": "sync_fingerprint",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "session_id",
+ "provider_id",
+ "series_id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_series_import_stage_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_import_stage_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_series_import_stage_session_id_provider_id",
+ "unique": false,
+ "columnNames": [
+ "session_id",
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_import_stage_session_id_provider_id` ON `${TABLE_NAME}` (`session_id`, `provider_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "category_import_stage",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`session_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `category_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `parent_id` INTEGER, `type` TEXT NOT NULL, `is_adult` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, PRIMARY KEY(`session_id`, `provider_id`, `category_id`, `type`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "sessionId",
+ "columnName": "session_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "categoryId",
+ "columnName": "category_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "parentId",
+ "columnName": "parent_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "type",
+ "columnName": "type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isAdult",
+ "columnName": "is_adult",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "syncFingerprint",
+ "columnName": "sync_fingerprint",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "session_id",
+ "provider_id",
+ "category_id",
+ "type"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_category_import_stage_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_category_import_stage_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_category_import_stage_session_id_provider_id",
+ "unique": false,
+ "columnNames": [
+ "session_id",
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_category_import_stage_session_id_provider_id` ON `${TABLE_NAME}` (`session_id`, `provider_id`)"
+ },
+ {
+ "name": "index_category_import_stage_provider_id_type",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "type"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_category_import_stage_provider_id_type` ON `${TABLE_NAME}` (`provider_id`, `type`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "programs",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `channel_id` TEXT NOT NULL, `title` TEXT NOT NULL, `description` TEXT NOT NULL, `start_time` INTEGER NOT NULL, `end_time` INTEGER NOT NULL, `lang` TEXT NOT NULL, `rating` TEXT, `image_url` TEXT, `genre` TEXT, `category` TEXT, `has_archive` INTEGER NOT NULL)",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "channelId",
+ "columnName": "channel_id",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "title",
+ "columnName": "title",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "description",
+ "columnName": "description",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "startTime",
+ "columnName": "start_time",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "endTime",
+ "columnName": "end_time",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lang",
+ "columnName": "lang",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "rating",
+ "columnName": "rating",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "imageUrl",
+ "columnName": "image_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "genre",
+ "columnName": "genre",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "category",
+ "columnName": "category",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "hasArchive",
+ "columnName": "has_archive",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_programs_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_programs_provider_id_channel_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "channel_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_channel_id` ON `${TABLE_NAME}` (`provider_id`, `channel_id`)"
+ },
+ {
+ "name": "index_programs_provider_id_start_time_end_time",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "start_time",
+ "end_time"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_start_time_end_time` ON `${TABLE_NAME}` (`provider_id`, `start_time`, `end_time`)"
+ },
+ {
+ "name": "index_programs_start_time",
+ "unique": false,
+ "columnNames": [
+ "start_time"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_start_time` ON `${TABLE_NAME}` (`start_time`)"
+ },
+ {
+ "name": "index_programs_provider_id_channel_id_start_time",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "channel_id",
+ "start_time"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_channel_id_start_time` ON `${TABLE_NAME}` (`provider_id`, `channel_id`, `start_time`)"
+ },
+ {
+ "name": "index_programs_provider_id_channel_id_start_time_end_time",
+ "unique": true,
+ "columnNames": [
+ "provider_id",
+ "channel_id",
+ "start_time",
+ "end_time"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_programs_provider_id_channel_id_start_time_end_time` ON `${TABLE_NAME}` (`provider_id`, `channel_id`, `start_time`, `end_time`)"
+ }
+ ]
+ },
+ {
+ "tableName": "favorites",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `content_id` INTEGER NOT NULL, `content_type` TEXT NOT NULL, `position` INTEGER NOT NULL, `group_id` INTEGER, `added_at` INTEGER NOT NULL, FOREIGN KEY(`group_id`) REFERENCES `virtual_groups`(`id`) ON UPDATE NO ACTION ON DELETE SET NULL )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "contentId",
+ "columnName": "content_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "contentType",
+ "columnName": "content_type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "position",
+ "columnName": "position",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "groupId",
+ "columnName": "group_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "addedAt",
+ "columnName": "added_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_favorites_content_id_content_type_group_id",
+ "unique": true,
+ "columnNames": [
+ "content_id",
+ "content_type",
+ "group_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_favorites_content_id_content_type_group_id` ON `${TABLE_NAME}` (`content_id`, `content_type`, `group_id`)"
+ },
+ {
+ "name": "index_favorites_content_type_group_id",
+ "unique": false,
+ "columnNames": [
+ "content_type",
+ "group_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_favorites_content_type_group_id` ON `${TABLE_NAME}` (`content_type`, `group_id`)"
+ },
+ {
+ "name": "index_favorites_group_id_position",
+ "unique": false,
+ "columnNames": [
+ "group_id",
+ "position"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_favorites_group_id_position` ON `${TABLE_NAME}` (`group_id`, `position`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "virtual_groups",
+ "onDelete": "SET NULL",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "group_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "virtual_groups",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `icon_emoji` TEXT, `position` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `content_type` TEXT NOT NULL)",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "iconEmoji",
+ "columnName": "icon_emoji",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "position",
+ "columnName": "position",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "createdAt",
+ "columnName": "created_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "contentType",
+ "columnName": "content_type",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_virtual_groups_position",
+ "unique": false,
+ "columnNames": [
+ "position"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_virtual_groups_position` ON `${TABLE_NAME}` (`position`)"
+ },
+ {
+ "name": "index_virtual_groups_content_type",
+ "unique": false,
+ "columnNames": [
+ "content_type"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_virtual_groups_content_type` ON `${TABLE_NAME}` (`content_type`)"
+ }
+ ]
+ },
+ {
+ "tableName": "playback_history",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `content_id` INTEGER NOT NULL, `content_type` TEXT NOT NULL, `provider_id` INTEGER NOT NULL, `title` TEXT NOT NULL, `poster_url` TEXT, `stream_url` TEXT NOT NULL, `resume_position_ms` INTEGER NOT NULL, `total_duration_ms` INTEGER NOT NULL, `last_watched_at` INTEGER NOT NULL, `watch_count` INTEGER NOT NULL, `watched_status` TEXT NOT NULL, `series_id` INTEGER, `season_number` INTEGER, `episode_number` INTEGER, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "contentId",
+ "columnName": "content_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "contentType",
+ "columnName": "content_type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "title",
+ "columnName": "title",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "posterUrl",
+ "columnName": "poster_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "streamUrl",
+ "columnName": "stream_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "resumePositionMs",
+ "columnName": "resume_position_ms",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "totalDurationMs",
+ "columnName": "total_duration_ms",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastWatchedAt",
+ "columnName": "last_watched_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "watchCount",
+ "columnName": "watch_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "watchedStatus",
+ "columnName": "watched_status",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "seriesId",
+ "columnName": "series_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "seasonNumber",
+ "columnName": "season_number",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "episodeNumber",
+ "columnName": "episode_number",
+ "affinity": "INTEGER"
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_playback_history_content_id_content_type_provider_id",
+ "unique": true,
+ "columnNames": [
+ "content_id",
+ "content_type",
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_playback_history_content_id_content_type_provider_id` ON `${TABLE_NAME}` (`content_id`, `content_type`, `provider_id`)"
+ },
+ {
+ "name": "index_playback_history_last_watched_at",
+ "unique": false,
+ "columnNames": [
+ "last_watched_at"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_history_last_watched_at` ON `${TABLE_NAME}` (`last_watched_at`)"
+ },
+ {
+ "name": "index_playback_history_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_history_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "sync_metadata",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `last_live_sync` INTEGER NOT NULL, `last_movie_sync` INTEGER NOT NULL, `last_series_sync` INTEGER NOT NULL, `last_epg_sync` INTEGER NOT NULL, `last_movie_attempt` INTEGER NOT NULL, `last_movie_success` INTEGER NOT NULL, `last_movie_partial` INTEGER NOT NULL, `live_count` INTEGER NOT NULL, `movie_count` INTEGER NOT NULL, `series_count` INTEGER NOT NULL, `epg_count` INTEGER NOT NULL, `last_sync_status` TEXT NOT NULL, `movie_sync_mode` TEXT NOT NULL, `movie_warnings_count` INTEGER NOT NULL, `movie_catalog_stale` INTEGER NOT NULL, `live_avoid_full_until` INTEGER NOT NULL, `movie_avoid_full_until` INTEGER NOT NULL, `series_avoid_full_until` INTEGER NOT NULL, `live_sequential_failures_remembered` INTEGER NOT NULL, `live_healthy_sync_streak` INTEGER NOT NULL, `movie_parallel_failures_remembered` INTEGER NOT NULL, `movie_healthy_sync_streak` INTEGER NOT NULL, `series_sequential_failures_remembered` INTEGER NOT NULL, `series_healthy_sync_streak` INTEGER NOT NULL, PRIMARY KEY(`provider_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastLiveSync",
+ "columnName": "last_live_sync",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastMovieSync",
+ "columnName": "last_movie_sync",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastSeriesSync",
+ "columnName": "last_series_sync",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastEpgSync",
+ "columnName": "last_epg_sync",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastMovieAttempt",
+ "columnName": "last_movie_attempt",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastMovieSuccess",
+ "columnName": "last_movie_success",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastMoviePartial",
+ "columnName": "last_movie_partial",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "liveCount",
+ "columnName": "live_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "movieCount",
+ "columnName": "movie_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "seriesCount",
+ "columnName": "series_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "epgCount",
+ "columnName": "epg_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastSyncStatus",
+ "columnName": "last_sync_status",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "movieSyncMode",
+ "columnName": "movie_sync_mode",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "movieWarningsCount",
+ "columnName": "movie_warnings_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "movieCatalogStale",
+ "columnName": "movie_catalog_stale",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "liveAvoidFullUntil",
+ "columnName": "live_avoid_full_until",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "movieAvoidFullUntil",
+ "columnName": "movie_avoid_full_until",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "seriesAvoidFullUntil",
+ "columnName": "series_avoid_full_until",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "liveSequentialFailuresRemembered",
+ "columnName": "live_sequential_failures_remembered",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "liveHealthySyncStreak",
+ "columnName": "live_healthy_sync_streak",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "movieParallelFailuresRemembered",
+ "columnName": "movie_parallel_failures_remembered",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "movieHealthySyncStreak",
+ "columnName": "movie_healthy_sync_streak",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "seriesSequentialFailuresRemembered",
+ "columnName": "series_sequential_failures_remembered",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "seriesHealthySyncStreak",
+ "columnName": "series_healthy_sync_streak",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "provider_id"
+ ]
+ },
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ }
+ ],
+ "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, '3ad126acc18a09e82756c34ff9a80fbb')"
+ ]
+ }
+}
\ No newline at end of file
diff --git a/data/schemas/com.streamvault.data.local.StreamVaultDatabase/23.json b/data/schemas/com.streamvault.data.local.StreamVaultDatabase/23.json
new file mode 100644
index 00000000..f84b787e
--- /dev/null
+++ b/data/schemas/com.streamvault.data.local.StreamVaultDatabase/23.json
@@ -0,0 +1,2342 @@
+{
+ "formatVersion": 1,
+ "database": {
+ "version": 23,
+ "identityHash": "87d297c018c8c8eb14620c14e9003bb1",
+ "entities": [
+ {
+ "tableName": "providers",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `type` TEXT NOT NULL, `server_url` TEXT NOT NULL, `username` TEXT NOT NULL, `password` TEXT NOT NULL, `m3u_url` TEXT NOT NULL, `epg_url` TEXT NOT NULL, `is_active` INTEGER NOT NULL, `max_connections` INTEGER NOT NULL, `expiration_date` INTEGER, `api_version` TEXT, `allowed_output_formats_json` TEXT NOT NULL, `status` TEXT NOT NULL, `last_synced_at` INTEGER NOT NULL, `created_at` INTEGER NOT NULL)",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "type",
+ "columnName": "type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "serverUrl",
+ "columnName": "server_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "username",
+ "columnName": "username",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "password",
+ "columnName": "password",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "m3uUrl",
+ "columnName": "m3u_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "epgUrl",
+ "columnName": "epg_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isActive",
+ "columnName": "is_active",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "maxConnections",
+ "columnName": "max_connections",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "expirationDate",
+ "columnName": "expiration_date",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "apiVersion",
+ "columnName": "api_version",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "allowedOutputFormatsJson",
+ "columnName": "allowed_output_formats_json",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "status",
+ "columnName": "status",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastSyncedAt",
+ "columnName": "last_synced_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "createdAt",
+ "columnName": "created_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_providers_server_url_username",
+ "unique": true,
+ "columnNames": [
+ "server_url",
+ "username"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_providers_server_url_username` ON `${TABLE_NAME}` (`server_url`, `username`)"
+ }
+ ]
+ },
+ {
+ "tableName": "channels",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `stream_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `logo_url` TEXT, `group_title` TEXT, `category_id` INTEGER, `category_name` TEXT, `stream_url` TEXT NOT NULL, `epg_channel_id` TEXT, `number` INTEGER NOT NULL, `catch_up_supported` INTEGER NOT NULL, `catch_up_days` INTEGER NOT NULL, `catchUpSource` TEXT, `provider_id` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, `logical_group_id` TEXT NOT NULL, `error_count` INTEGER NOT NULL, `quality_options_json` TEXT, `sync_fingerprint` TEXT NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "streamId",
+ "columnName": "stream_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "logoUrl",
+ "columnName": "logo_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "groupTitle",
+ "columnName": "group_title",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "categoryId",
+ "columnName": "category_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "categoryName",
+ "columnName": "category_name",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "streamUrl",
+ "columnName": "stream_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "epgChannelId",
+ "columnName": "epg_channel_id",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "number",
+ "columnName": "number",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "catchUpSupported",
+ "columnName": "catch_up_supported",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "catchUpDays",
+ "columnName": "catch_up_days",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "catchUpSource",
+ "columnName": "catchUpSource",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isAdult",
+ "columnName": "is_adult",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isUserProtected",
+ "columnName": "is_user_protected",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "logicalGroupId",
+ "columnName": "logical_group_id",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "errorCount",
+ "columnName": "error_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "qualityOptionsJson",
+ "columnName": "quality_options_json",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "syncFingerprint",
+ "columnName": "sync_fingerprint",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_channels_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_channels_provider_id_category_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "category_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_provider_id_category_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`)"
+ },
+ {
+ "name": "index_channels_provider_id_stream_id",
+ "unique": true,
+ "columnNames": [
+ "provider_id",
+ "stream_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_channels_provider_id_stream_id` ON `${TABLE_NAME}` (`provider_id`, `stream_id`)"
+ },
+ {
+ "name": "index_channels_logical_group_id",
+ "unique": false,
+ "columnNames": [
+ "logical_group_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_logical_group_id` ON `${TABLE_NAME}` (`logical_group_id`)"
+ },
+ {
+ "name": "index_channels_provider_id_category_id_logical_group_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "category_id",
+ "logical_group_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_provider_id_category_id_logical_group_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`, `logical_group_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "channel_preferences",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `channel_id` INTEGER NOT NULL, `aspect_ratio` TEXT, `updated_at` INTEGER NOT NULL, FOREIGN KEY(`channel_id`) REFERENCES `channels`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "channelId",
+ "columnName": "channel_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "aspectRatio",
+ "columnName": "aspect_ratio",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "updatedAt",
+ "columnName": "updated_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_channel_preferences_channel_id",
+ "unique": true,
+ "columnNames": [
+ "channel_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_channel_preferences_channel_id` ON `${TABLE_NAME}` (`channel_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "channels",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "channel_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "channels_fts",
+ "createSql": "CREATE VIRTUAL TABLE IF NOT EXISTS `${TABLE_NAME}` USING FTS4(`name` TEXT NOT NULL, content=`channels`)",
+ "fields": [
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": []
+ },
+ "ftsVersion": "FTS4",
+ "ftsOptions": {
+ "tokenizer": "simple",
+ "tokenizerArgs": [],
+ "contentTable": "channels",
+ "languageIdColumnName": "",
+ "matchInfo": "FTS4",
+ "notIndexedColumns": [],
+ "prefixSizes": [],
+ "preferredOrder": "ASC"
+ },
+ "contentSyncTriggers": [
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_BEFORE_UPDATE BEFORE UPDATE ON `channels` BEGIN DELETE FROM `channels_fts` WHERE `docid`=OLD.`rowid`; END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_BEFORE_DELETE BEFORE DELETE ON `channels` BEGIN DELETE FROM `channels_fts` WHERE `docid`=OLD.`rowid`; END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_AFTER_UPDATE AFTER UPDATE ON `channels` BEGIN INSERT INTO `channels_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_AFTER_INSERT AFTER INSERT ON `channels` BEGIN INSERT INTO `channels_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END"
+ ]
+ },
+ {
+ "tableName": "movies",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `stream_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `poster_url` TEXT, `backdrop_url` TEXT, `category_id` INTEGER, `category_name` TEXT, `stream_url` TEXT NOT NULL, `container_extension` TEXT, `plot` TEXT, `cast` TEXT, `director` TEXT, `genre` TEXT, `release_date` TEXT, `duration` TEXT, `duration_seconds` INTEGER NOT NULL, `rating` REAL NOT NULL, `year` TEXT, `tmdb_id` INTEGER, `youtube_trailer` TEXT, `provider_id` INTEGER NOT NULL, `watch_progress` INTEGER NOT NULL, `last_watched_at` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "streamId",
+ "columnName": "stream_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "posterUrl",
+ "columnName": "poster_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "backdropUrl",
+ "columnName": "backdrop_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "categoryId",
+ "columnName": "category_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "categoryName",
+ "columnName": "category_name",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "streamUrl",
+ "columnName": "stream_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "containerExtension",
+ "columnName": "container_extension",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "plot",
+ "columnName": "plot",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "cast",
+ "columnName": "cast",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "director",
+ "columnName": "director",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "genre",
+ "columnName": "genre",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "releaseDate",
+ "columnName": "release_date",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "duration",
+ "columnName": "duration",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "durationSeconds",
+ "columnName": "duration_seconds",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "rating",
+ "columnName": "rating",
+ "affinity": "REAL",
+ "notNull": true
+ },
+ {
+ "fieldPath": "year",
+ "columnName": "year",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "tmdbId",
+ "columnName": "tmdb_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "youtubeTrailer",
+ "columnName": "youtube_trailer",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "watchProgress",
+ "columnName": "watch_progress",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastWatchedAt",
+ "columnName": "last_watched_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isAdult",
+ "columnName": "is_adult",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isUserProtected",
+ "columnName": "is_user_protected",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "syncFingerprint",
+ "columnName": "sync_fingerprint",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_movies_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_movies_provider_id_category_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "category_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id_category_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`)"
+ },
+ {
+ "name": "index_movies_provider_id_stream_id",
+ "unique": true,
+ "columnNames": [
+ "provider_id",
+ "stream_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_movies_provider_id_stream_id` ON `${TABLE_NAME}` (`provider_id`, `stream_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "movies_fts",
+ "createSql": "CREATE VIRTUAL TABLE IF NOT EXISTS `${TABLE_NAME}` USING FTS4(`name` TEXT NOT NULL, content=`movies`)",
+ "fields": [
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": []
+ },
+ "ftsVersion": "FTS4",
+ "ftsOptions": {
+ "tokenizer": "simple",
+ "tokenizerArgs": [],
+ "contentTable": "movies",
+ "languageIdColumnName": "",
+ "matchInfo": "FTS4",
+ "notIndexedColumns": [],
+ "prefixSizes": [],
+ "preferredOrder": "ASC"
+ },
+ "contentSyncTriggers": [
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_movies_fts_BEFORE_UPDATE BEFORE UPDATE ON `movies` BEGIN DELETE FROM `movies_fts` WHERE `docid`=OLD.`rowid`; END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_movies_fts_BEFORE_DELETE BEFORE DELETE ON `movies` BEGIN DELETE FROM `movies_fts` WHERE `docid`=OLD.`rowid`; END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_movies_fts_AFTER_UPDATE AFTER UPDATE ON `movies` BEGIN INSERT INTO `movies_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_movies_fts_AFTER_INSERT AFTER INSERT ON `movies` BEGIN INSERT INTO `movies_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END"
+ ]
+ },
+ {
+ "tableName": "series",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `series_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `poster_url` TEXT, `backdrop_url` TEXT, `category_id` INTEGER, `category_name` TEXT, `plot` TEXT, `cast` TEXT, `director` TEXT, `genre` TEXT, `release_date` TEXT, `rating` REAL NOT NULL, `tmdb_id` INTEGER, `youtube_trailer` TEXT, `episode_run_time` TEXT, `last_modified` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "seriesId",
+ "columnName": "series_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "posterUrl",
+ "columnName": "poster_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "backdropUrl",
+ "columnName": "backdrop_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "categoryId",
+ "columnName": "category_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "categoryName",
+ "columnName": "category_name",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "plot",
+ "columnName": "plot",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "cast",
+ "columnName": "cast",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "director",
+ "columnName": "director",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "genre",
+ "columnName": "genre",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "releaseDate",
+ "columnName": "release_date",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "rating",
+ "columnName": "rating",
+ "affinity": "REAL",
+ "notNull": true
+ },
+ {
+ "fieldPath": "tmdbId",
+ "columnName": "tmdb_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "youtubeTrailer",
+ "columnName": "youtube_trailer",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "episodeRunTime",
+ "columnName": "episode_run_time",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "lastModified",
+ "columnName": "last_modified",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isAdult",
+ "columnName": "is_adult",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isUserProtected",
+ "columnName": "is_user_protected",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "syncFingerprint",
+ "columnName": "sync_fingerprint",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_series_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_series_provider_id_category_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "category_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_provider_id_category_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`)"
+ },
+ {
+ "name": "index_series_provider_id_series_id",
+ "unique": true,
+ "columnNames": [
+ "provider_id",
+ "series_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_series_provider_id_series_id` ON `${TABLE_NAME}` (`provider_id`, `series_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "series_fts",
+ "createSql": "CREATE VIRTUAL TABLE IF NOT EXISTS `${TABLE_NAME}` USING FTS4(`name` TEXT NOT NULL, content=`series`)",
+ "fields": [
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": []
+ },
+ "ftsVersion": "FTS4",
+ "ftsOptions": {
+ "tokenizer": "simple",
+ "tokenizerArgs": [],
+ "contentTable": "series",
+ "languageIdColumnName": "",
+ "matchInfo": "FTS4",
+ "notIndexedColumns": [],
+ "prefixSizes": [],
+ "preferredOrder": "ASC"
+ },
+ "contentSyncTriggers": [
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_series_fts_BEFORE_UPDATE BEFORE UPDATE ON `series` BEGIN DELETE FROM `series_fts` WHERE `docid`=OLD.`rowid`; END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_series_fts_BEFORE_DELETE BEFORE DELETE ON `series` BEGIN DELETE FROM `series_fts` WHERE `docid`=OLD.`rowid`; END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_series_fts_AFTER_UPDATE AFTER UPDATE ON `series` BEGIN INSERT INTO `series_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_series_fts_AFTER_INSERT AFTER INSERT ON `series` BEGIN INSERT INTO `series_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END"
+ ]
+ },
+ {
+ "tableName": "episodes",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `episode_id` INTEGER NOT NULL, `title` TEXT NOT NULL, `episode_number` INTEGER NOT NULL, `season_number` INTEGER NOT NULL, `stream_url` TEXT NOT NULL, `container_extension` TEXT, `cover_url` TEXT, `plot` TEXT, `duration` TEXT, `duration_seconds` INTEGER NOT NULL, `rating` REAL NOT NULL, `release_date` TEXT, `series_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `watch_progress` INTEGER NOT NULL, `last_watched_at` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`series_id`) REFERENCES `series`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "episodeId",
+ "columnName": "episode_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "title",
+ "columnName": "title",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "episodeNumber",
+ "columnName": "episode_number",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "seasonNumber",
+ "columnName": "season_number",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "streamUrl",
+ "columnName": "stream_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "containerExtension",
+ "columnName": "container_extension",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "coverUrl",
+ "columnName": "cover_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "plot",
+ "columnName": "plot",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "duration",
+ "columnName": "duration",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "durationSeconds",
+ "columnName": "duration_seconds",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "rating",
+ "columnName": "rating",
+ "affinity": "REAL",
+ "notNull": true
+ },
+ {
+ "fieldPath": "releaseDate",
+ "columnName": "release_date",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "seriesId",
+ "columnName": "series_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "watchProgress",
+ "columnName": "watch_progress",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastWatchedAt",
+ "columnName": "last_watched_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isAdult",
+ "columnName": "is_adult",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isUserProtected",
+ "columnName": "is_user_protected",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_episodes_series_id",
+ "unique": false,
+ "columnNames": [
+ "series_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_episodes_series_id` ON `${TABLE_NAME}` (`series_id`)"
+ },
+ {
+ "name": "index_episodes_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_episodes_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_episodes_provider_id_episode_id",
+ "unique": true,
+ "columnNames": [
+ "provider_id",
+ "episode_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_episodes_provider_id_episode_id` ON `${TABLE_NAME}` (`provider_id`, `episode_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ },
+ {
+ "table": "series",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "series_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "categories",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `category_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `parent_id` INTEGER, `type` TEXT NOT NULL, `provider_id` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "categoryId",
+ "columnName": "category_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "parentId",
+ "columnName": "parent_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "type",
+ "columnName": "type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isAdult",
+ "columnName": "is_adult",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isUserProtected",
+ "columnName": "is_user_protected",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "syncFingerprint",
+ "columnName": "sync_fingerprint",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_categories_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_categories_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_categories_provider_id_type",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "type"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_categories_provider_id_type` ON `${TABLE_NAME}` (`provider_id`, `type`)"
+ },
+ {
+ "name": "index_categories_provider_id_category_id_type",
+ "unique": true,
+ "columnNames": [
+ "provider_id",
+ "category_id",
+ "type"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_categories_provider_id_category_id_type` ON `${TABLE_NAME}` (`provider_id`, `category_id`, `type`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "channel_import_stage",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`session_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `stream_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `logo_url` TEXT, `group_title` TEXT, `category_id` INTEGER, `category_name` TEXT, `stream_url` TEXT NOT NULL, `epg_channel_id` TEXT, `number` INTEGER NOT NULL, `catch_up_supported` INTEGER NOT NULL, `catch_up_days` INTEGER NOT NULL, `catchUpSource` TEXT, `is_adult` INTEGER NOT NULL, `logical_group_id` TEXT NOT NULL, `error_count` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, PRIMARY KEY(`session_id`, `provider_id`, `stream_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "sessionId",
+ "columnName": "session_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "streamId",
+ "columnName": "stream_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "logoUrl",
+ "columnName": "logo_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "groupTitle",
+ "columnName": "group_title",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "categoryId",
+ "columnName": "category_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "categoryName",
+ "columnName": "category_name",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "streamUrl",
+ "columnName": "stream_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "epgChannelId",
+ "columnName": "epg_channel_id",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "number",
+ "columnName": "number",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "catchUpSupported",
+ "columnName": "catch_up_supported",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "catchUpDays",
+ "columnName": "catch_up_days",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "catchUpSource",
+ "columnName": "catchUpSource",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "isAdult",
+ "columnName": "is_adult",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "logicalGroupId",
+ "columnName": "logical_group_id",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "errorCount",
+ "columnName": "error_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "syncFingerprint",
+ "columnName": "sync_fingerprint",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "session_id",
+ "provider_id",
+ "stream_id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_channel_import_stage_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channel_import_stage_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_channel_import_stage_session_id_provider_id",
+ "unique": false,
+ "columnNames": [
+ "session_id",
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channel_import_stage_session_id_provider_id` ON `${TABLE_NAME}` (`session_id`, `provider_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "movie_import_stage",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`session_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `stream_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `poster_url` TEXT, `backdrop_url` TEXT, `category_id` INTEGER, `category_name` TEXT, `stream_url` TEXT NOT NULL, `container_extension` TEXT, `plot` TEXT, `cast` TEXT, `director` TEXT, `genre` TEXT, `release_date` TEXT, `duration` TEXT, `duration_seconds` INTEGER NOT NULL, `rating` REAL NOT NULL, `year` TEXT, `tmdb_id` INTEGER, `youtube_trailer` TEXT, `is_adult` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, PRIMARY KEY(`session_id`, `provider_id`, `stream_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "sessionId",
+ "columnName": "session_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "streamId",
+ "columnName": "stream_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "posterUrl",
+ "columnName": "poster_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "backdropUrl",
+ "columnName": "backdrop_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "categoryId",
+ "columnName": "category_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "categoryName",
+ "columnName": "category_name",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "streamUrl",
+ "columnName": "stream_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "containerExtension",
+ "columnName": "container_extension",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "plot",
+ "columnName": "plot",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "cast",
+ "columnName": "cast",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "director",
+ "columnName": "director",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "genre",
+ "columnName": "genre",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "releaseDate",
+ "columnName": "release_date",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "duration",
+ "columnName": "duration",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "durationSeconds",
+ "columnName": "duration_seconds",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "rating",
+ "columnName": "rating",
+ "affinity": "REAL",
+ "notNull": true
+ },
+ {
+ "fieldPath": "year",
+ "columnName": "year",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "tmdbId",
+ "columnName": "tmdb_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "youtubeTrailer",
+ "columnName": "youtube_trailer",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "isAdult",
+ "columnName": "is_adult",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "syncFingerprint",
+ "columnName": "sync_fingerprint",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "session_id",
+ "provider_id",
+ "stream_id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_movie_import_stage_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movie_import_stage_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_movie_import_stage_session_id_provider_id",
+ "unique": false,
+ "columnNames": [
+ "session_id",
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movie_import_stage_session_id_provider_id` ON `${TABLE_NAME}` (`session_id`, `provider_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "series_import_stage",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`session_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `series_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `poster_url` TEXT, `backdrop_url` TEXT, `category_id` INTEGER, `category_name` TEXT, `plot` TEXT, `cast` TEXT, `director` TEXT, `genre` TEXT, `release_date` TEXT, `rating` REAL NOT NULL, `tmdb_id` INTEGER, `youtube_trailer` TEXT, `episode_run_time` TEXT, `last_modified` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, PRIMARY KEY(`session_id`, `provider_id`, `series_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "sessionId",
+ "columnName": "session_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "seriesId",
+ "columnName": "series_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "posterUrl",
+ "columnName": "poster_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "backdropUrl",
+ "columnName": "backdrop_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "categoryId",
+ "columnName": "category_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "categoryName",
+ "columnName": "category_name",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "plot",
+ "columnName": "plot",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "cast",
+ "columnName": "cast",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "director",
+ "columnName": "director",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "genre",
+ "columnName": "genre",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "releaseDate",
+ "columnName": "release_date",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "rating",
+ "columnName": "rating",
+ "affinity": "REAL",
+ "notNull": true
+ },
+ {
+ "fieldPath": "tmdbId",
+ "columnName": "tmdb_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "youtubeTrailer",
+ "columnName": "youtube_trailer",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "episodeRunTime",
+ "columnName": "episode_run_time",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "lastModified",
+ "columnName": "last_modified",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isAdult",
+ "columnName": "is_adult",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "syncFingerprint",
+ "columnName": "sync_fingerprint",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "session_id",
+ "provider_id",
+ "series_id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_series_import_stage_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_import_stage_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_series_import_stage_session_id_provider_id",
+ "unique": false,
+ "columnNames": [
+ "session_id",
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_import_stage_session_id_provider_id` ON `${TABLE_NAME}` (`session_id`, `provider_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "category_import_stage",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`session_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `category_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `parent_id` INTEGER, `type` TEXT NOT NULL, `is_adult` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, PRIMARY KEY(`session_id`, `provider_id`, `category_id`, `type`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "sessionId",
+ "columnName": "session_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "categoryId",
+ "columnName": "category_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "parentId",
+ "columnName": "parent_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "type",
+ "columnName": "type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isAdult",
+ "columnName": "is_adult",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "syncFingerprint",
+ "columnName": "sync_fingerprint",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "session_id",
+ "provider_id",
+ "category_id",
+ "type"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_category_import_stage_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_category_import_stage_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_category_import_stage_session_id_provider_id",
+ "unique": false,
+ "columnNames": [
+ "session_id",
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_category_import_stage_session_id_provider_id` ON `${TABLE_NAME}` (`session_id`, `provider_id`)"
+ },
+ {
+ "name": "index_category_import_stage_provider_id_type",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "type"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_category_import_stage_provider_id_type` ON `${TABLE_NAME}` (`provider_id`, `type`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "programs",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `channel_id` TEXT NOT NULL, `title` TEXT NOT NULL, `description` TEXT NOT NULL, `start_time` INTEGER NOT NULL, `end_time` INTEGER NOT NULL, `lang` TEXT NOT NULL, `rating` TEXT, `image_url` TEXT, `genre` TEXT, `category` TEXT, `has_archive` INTEGER NOT NULL)",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "channelId",
+ "columnName": "channel_id",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "title",
+ "columnName": "title",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "description",
+ "columnName": "description",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "startTime",
+ "columnName": "start_time",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "endTime",
+ "columnName": "end_time",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lang",
+ "columnName": "lang",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "rating",
+ "columnName": "rating",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "imageUrl",
+ "columnName": "image_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "genre",
+ "columnName": "genre",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "category",
+ "columnName": "category",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "hasArchive",
+ "columnName": "has_archive",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_programs_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_programs_provider_id_channel_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "channel_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_channel_id` ON `${TABLE_NAME}` (`provider_id`, `channel_id`)"
+ },
+ {
+ "name": "index_programs_provider_id_start_time_end_time",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "start_time",
+ "end_time"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_start_time_end_time` ON `${TABLE_NAME}` (`provider_id`, `start_time`, `end_time`)"
+ },
+ {
+ "name": "index_programs_start_time",
+ "unique": false,
+ "columnNames": [
+ "start_time"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_start_time` ON `${TABLE_NAME}` (`start_time`)"
+ },
+ {
+ "name": "index_programs_provider_id_channel_id_start_time",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "channel_id",
+ "start_time"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_channel_id_start_time` ON `${TABLE_NAME}` (`provider_id`, `channel_id`, `start_time`)"
+ },
+ {
+ "name": "index_programs_provider_id_channel_id_start_time_end_time",
+ "unique": true,
+ "columnNames": [
+ "provider_id",
+ "channel_id",
+ "start_time",
+ "end_time"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_programs_provider_id_channel_id_start_time_end_time` ON `${TABLE_NAME}` (`provider_id`, `channel_id`, `start_time`, `end_time`)"
+ }
+ ]
+ },
+ {
+ "tableName": "favorites",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `content_id` INTEGER NOT NULL, `content_type` TEXT NOT NULL, `position` INTEGER NOT NULL, `group_id` INTEGER, `added_at` INTEGER NOT NULL, FOREIGN KEY(`group_id`) REFERENCES `virtual_groups`(`id`) ON UPDATE NO ACTION ON DELETE SET NULL )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "contentId",
+ "columnName": "content_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "contentType",
+ "columnName": "content_type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "position",
+ "columnName": "position",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "groupId",
+ "columnName": "group_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "addedAt",
+ "columnName": "added_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_favorites_content_id_content_type_group_id",
+ "unique": true,
+ "columnNames": [
+ "content_id",
+ "content_type",
+ "group_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_favorites_content_id_content_type_group_id` ON `${TABLE_NAME}` (`content_id`, `content_type`, `group_id`)"
+ },
+ {
+ "name": "index_favorites_content_type_group_id",
+ "unique": false,
+ "columnNames": [
+ "content_type",
+ "group_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_favorites_content_type_group_id` ON `${TABLE_NAME}` (`content_type`, `group_id`)"
+ },
+ {
+ "name": "index_favorites_group_id_position",
+ "unique": false,
+ "columnNames": [
+ "group_id",
+ "position"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_favorites_group_id_position` ON `${TABLE_NAME}` (`group_id`, `position`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "virtual_groups",
+ "onDelete": "SET NULL",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "group_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "virtual_groups",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `icon_emoji` TEXT, `position` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `content_type` TEXT NOT NULL)",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "iconEmoji",
+ "columnName": "icon_emoji",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "position",
+ "columnName": "position",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "createdAt",
+ "columnName": "created_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "contentType",
+ "columnName": "content_type",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_virtual_groups_position",
+ "unique": false,
+ "columnNames": [
+ "position"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_virtual_groups_position` ON `${TABLE_NAME}` (`position`)"
+ },
+ {
+ "name": "index_virtual_groups_content_type",
+ "unique": false,
+ "columnNames": [
+ "content_type"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_virtual_groups_content_type` ON `${TABLE_NAME}` (`content_type`)"
+ }
+ ]
+ },
+ {
+ "tableName": "playback_history",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `content_id` INTEGER NOT NULL, `content_type` TEXT NOT NULL, `provider_id` INTEGER NOT NULL, `title` TEXT NOT NULL, `poster_url` TEXT, `stream_url` TEXT NOT NULL, `resume_position_ms` INTEGER NOT NULL, `total_duration_ms` INTEGER NOT NULL, `last_watched_at` INTEGER NOT NULL, `watch_count` INTEGER NOT NULL, `watched_status` TEXT NOT NULL, `series_id` INTEGER, `season_number` INTEGER, `episode_number` INTEGER, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "contentId",
+ "columnName": "content_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "contentType",
+ "columnName": "content_type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "title",
+ "columnName": "title",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "posterUrl",
+ "columnName": "poster_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "streamUrl",
+ "columnName": "stream_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "resumePositionMs",
+ "columnName": "resume_position_ms",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "totalDurationMs",
+ "columnName": "total_duration_ms",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastWatchedAt",
+ "columnName": "last_watched_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "watchCount",
+ "columnName": "watch_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "watchedStatus",
+ "columnName": "watched_status",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "seriesId",
+ "columnName": "series_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "seasonNumber",
+ "columnName": "season_number",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "episodeNumber",
+ "columnName": "episode_number",
+ "affinity": "INTEGER"
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_playback_history_content_id_content_type_provider_id",
+ "unique": true,
+ "columnNames": [
+ "content_id",
+ "content_type",
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_playback_history_content_id_content_type_provider_id` ON `${TABLE_NAME}` (`content_id`, `content_type`, `provider_id`)"
+ },
+ {
+ "name": "index_playback_history_last_watched_at",
+ "unique": false,
+ "columnNames": [
+ "last_watched_at"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_history_last_watched_at` ON `${TABLE_NAME}` (`last_watched_at`)"
+ },
+ {
+ "name": "index_playback_history_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_history_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "sync_metadata",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `last_live_sync` INTEGER NOT NULL, `last_movie_sync` INTEGER NOT NULL, `last_series_sync` INTEGER NOT NULL, `last_epg_sync` INTEGER NOT NULL, `last_movie_attempt` INTEGER NOT NULL, `last_movie_success` INTEGER NOT NULL, `last_movie_partial` INTEGER NOT NULL, `live_count` INTEGER NOT NULL, `movie_count` INTEGER NOT NULL, `series_count` INTEGER NOT NULL, `epg_count` INTEGER NOT NULL, `last_sync_status` TEXT NOT NULL, `movie_sync_mode` TEXT NOT NULL, `movie_warnings_count` INTEGER NOT NULL, `movie_catalog_stale` INTEGER NOT NULL, `live_avoid_full_until` INTEGER NOT NULL, `movie_avoid_full_until` INTEGER NOT NULL, `series_avoid_full_until` INTEGER NOT NULL, `live_sequential_failures_remembered` INTEGER NOT NULL, `live_healthy_sync_streak` INTEGER NOT NULL, `movie_parallel_failures_remembered` INTEGER NOT NULL, `movie_healthy_sync_streak` INTEGER NOT NULL, `series_sequential_failures_remembered` INTEGER NOT NULL, `series_healthy_sync_streak` INTEGER NOT NULL, PRIMARY KEY(`provider_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastLiveSync",
+ "columnName": "last_live_sync",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastMovieSync",
+ "columnName": "last_movie_sync",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastSeriesSync",
+ "columnName": "last_series_sync",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastEpgSync",
+ "columnName": "last_epg_sync",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastMovieAttempt",
+ "columnName": "last_movie_attempt",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastMovieSuccess",
+ "columnName": "last_movie_success",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastMoviePartial",
+ "columnName": "last_movie_partial",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "liveCount",
+ "columnName": "live_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "movieCount",
+ "columnName": "movie_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "seriesCount",
+ "columnName": "series_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "epgCount",
+ "columnName": "epg_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastSyncStatus",
+ "columnName": "last_sync_status",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "movieSyncMode",
+ "columnName": "movie_sync_mode",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "movieWarningsCount",
+ "columnName": "movie_warnings_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "movieCatalogStale",
+ "columnName": "movie_catalog_stale",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "liveAvoidFullUntil",
+ "columnName": "live_avoid_full_until",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "movieAvoidFullUntil",
+ "columnName": "movie_avoid_full_until",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "seriesAvoidFullUntil",
+ "columnName": "series_avoid_full_until",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "liveSequentialFailuresRemembered",
+ "columnName": "live_sequential_failures_remembered",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "liveHealthySyncStreak",
+ "columnName": "live_healthy_sync_streak",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "movieParallelFailuresRemembered",
+ "columnName": "movie_parallel_failures_remembered",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "movieHealthySyncStreak",
+ "columnName": "movie_healthy_sync_streak",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "seriesSequentialFailuresRemembered",
+ "columnName": "series_sequential_failures_remembered",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "seriesHealthySyncStreak",
+ "columnName": "series_healthy_sync_streak",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "provider_id"
+ ]
+ },
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ }
+ ],
+ "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, '87d297c018c8c8eb14620c14e9003bb1')"
+ ]
+ }
+}
\ No newline at end of file
diff --git a/data/src/main/java/com/streamvault/data/local/StreamVaultDatabase.kt b/data/src/main/java/com/streamvault/data/local/StreamVaultDatabase.kt
index 1e29c49b..a676db1d 100644
--- a/data/src/main/java/com/streamvault/data/local/StreamVaultDatabase.kt
+++ b/data/src/main/java/com/streamvault/data/local/StreamVaultDatabase.kt
@@ -20,13 +20,17 @@ import com.streamvault.data.local.entity.*
SeriesFtsEntity::class,
EpisodeEntity::class,
CategoryEntity::class,
+ ChannelImportStageEntity::class,
+ MovieImportStageEntity::class,
+ SeriesImportStageEntity::class,
+ CategoryImportStageEntity::class,
ProgramEntity::class,
FavoriteEntity::class,
VirtualGroupEntity::class,
PlaybackHistoryEntity::class,
SyncMetadataEntity::class
],
- version = 19,
+ version = 23,
exportSchema = true // ← was false; schema JSON now tracked in version control
)
@TypeConverters(RoomEnumConverters::class)
@@ -38,6 +42,7 @@ abstract class StreamVaultDatabase : RoomDatabase() {
abstract fun seriesDao(): SeriesDao
abstract fun episodeDao(): EpisodeDao
abstract fun categoryDao(): CategoryDao
+ abstract fun catalogSyncDao(): CatalogSyncDao
abstract fun programDao(): ProgramDao
abstract fun favoriteDao(): FavoriteDao
abstract fun virtualGroupDao(): VirtualGroupDao
@@ -994,5 +999,150 @@ abstract class StreamVaultDatabase : RoomDatabase() {
database.execSQL("ALTER TABLE sync_metadata ADD COLUMN movie_healthy_sync_streak INTEGER NOT NULL DEFAULT 0")
}
}
+
+ val MIGRATION_19_20 = object : Migration(19, 20) {
+ override fun migrate(database: SupportSQLiteDatabase) {
+ database.execSQL("ALTER TABLE channels ADD COLUMN sync_fingerprint TEXT NOT NULL DEFAULT ''")
+ database.execSQL("ALTER TABLE movies ADD COLUMN sync_fingerprint TEXT NOT NULL DEFAULT ''")
+ database.execSQL("ALTER TABLE series ADD COLUMN sync_fingerprint TEXT NOT NULL DEFAULT ''")
+ database.execSQL("ALTER TABLE categories ADD COLUMN sync_fingerprint TEXT NOT NULL DEFAULT ''")
+
+ database.execSQL(
+ """
+ CREATE TABLE IF NOT EXISTS channel_import_stage (
+ 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,
+ sync_fingerprint TEXT NOT NULL,
+ PRIMARY KEY(session_id, provider_id, stream_id),
+ FOREIGN KEY(provider_id) REFERENCES providers(id) ON DELETE CASCADE
+ )
+ """.trimIndent()
+ )
+ database.execSQL("CREATE INDEX IF NOT EXISTS index_channel_import_stage_provider_id ON channel_import_stage(provider_id)")
+ database.execSQL("CREATE INDEX IF NOT EXISTS index_channel_import_stage_session_id_provider_id ON channel_import_stage(session_id, provider_id)")
+
+ database.execSQL(
+ """
+ CREATE TABLE IF NOT EXISTS movie_import_stage (
+ session_id INTEGER NOT NULL,
+ provider_id INTEGER NOT NULL,
+ stream_id INTEGER NOT NULL,
+ name TEXT NOT NULL,
+ poster_url TEXT,
+ backdrop_url TEXT,
+ category_id INTEGER,
+ category_name TEXT,
+ stream_url TEXT NOT NULL,
+ container_extension TEXT,
+ plot TEXT,
+ cast TEXT,
+ director TEXT,
+ genre TEXT,
+ release_date TEXT,
+ duration TEXT,
+ duration_seconds INTEGER NOT NULL,
+ rating REAL NOT NULL,
+ year TEXT,
+ tmdb_id INTEGER,
+ youtube_trailer TEXT,
+ is_adult INTEGER NOT NULL,
+ sync_fingerprint TEXT NOT NULL,
+ PRIMARY KEY(session_id, provider_id, stream_id),
+ FOREIGN KEY(provider_id) REFERENCES providers(id) ON DELETE CASCADE
+ )
+ """.trimIndent()
+ )
+ database.execSQL("CREATE INDEX IF NOT EXISTS index_movie_import_stage_provider_id ON movie_import_stage(provider_id)")
+ database.execSQL("CREATE INDEX IF NOT EXISTS index_movie_import_stage_session_id_provider_id ON movie_import_stage(session_id, provider_id)")
+
+ database.execSQL(
+ """
+ CREATE TABLE IF NOT EXISTS series_import_stage (
+ 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 DELETE CASCADE
+ )
+ """.trimIndent()
+ )
+ 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)")
+
+ database.execSQL(
+ """
+ CREATE TABLE IF NOT EXISTS category_import_stage (
+ 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 DELETE CASCADE
+ )
+ """.trimIndent()
+ )
+ database.execSQL("CREATE INDEX IF NOT EXISTS index_category_import_stage_provider_id ON category_import_stage(provider_id)")
+ database.execSQL("CREATE INDEX IF NOT EXISTS index_category_import_stage_session_id_provider_id ON category_import_stage(session_id, provider_id)")
+ database.execSQL("CREATE INDEX IF NOT EXISTS index_category_import_stage_provider_id_type ON category_import_stage(provider_id, type)")
+ }
+ }
+
+ val MIGRATION_20_21 = object : Migration(20, 21) {
+ override fun migrate(database: SupportSQLiteDatabase) {
+ database.execSQL("ALTER TABLE sync_metadata ADD COLUMN live_avoid_full_until INTEGER NOT NULL DEFAULT 0")
+ database.execSQL("ALTER TABLE sync_metadata ADD COLUMN movie_avoid_full_until INTEGER NOT NULL DEFAULT 0")
+ database.execSQL("ALTER TABLE sync_metadata ADD COLUMN series_avoid_full_until INTEGER NOT NULL DEFAULT 0")
+ database.execSQL("ALTER TABLE sync_metadata ADD COLUMN live_sequential_failures_remembered INTEGER NOT NULL DEFAULT 0")
+ database.execSQL("ALTER TABLE sync_metadata ADD COLUMN live_healthy_sync_streak INTEGER NOT NULL DEFAULT 0")
+ database.execSQL("ALTER TABLE sync_metadata ADD COLUMN series_sequential_failures_remembered INTEGER NOT NULL DEFAULT 0")
+ database.execSQL("ALTER TABLE sync_metadata ADD COLUMN series_healthy_sync_streak INTEGER NOT NULL DEFAULT 0")
+ }
+ }
+
+ val MIGRATION_21_22 = object : Migration(21, 22) {
+ override fun migrate(database: SupportSQLiteDatabase) {
+ database.execSQL("ALTER TABLE channel_import_stage ADD COLUMN logical_group_id TEXT NOT NULL DEFAULT ''")
+ }
+ }
+
+ val MIGRATION_22_23 = object : Migration(22, 23) {
+ override fun migrate(database: SupportSQLiteDatabase) {
+ database.execSQL("ALTER TABLE channel_import_stage ADD COLUMN error_count INTEGER NOT NULL DEFAULT 0")
+ }
+ }
}
}
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.kt
new file mode 100644
index 00000000..5fcb70da
--- /dev/null
+++ b/data/src/main/java/com/streamvault/data/local/dao/CatalogSyncDao.kt
@@ -0,0 +1,789 @@
+package com.streamvault.data.local.dao
+
+import androidx.room.Dao
+import androidx.room.Insert
+import androidx.room.OnConflictStrategy
+import androidx.room.Query
+import com.streamvault.data.local.entity.CategoryImportStageEntity
+import com.streamvault.data.local.entity.ChannelImportStageEntity
+import com.streamvault.data.local.entity.MovieImportStageEntity
+import com.streamvault.data.local.entity.SeriesImportStageEntity
+
+@Dao
+interface CatalogSyncDao {
+ @Insert(onConflict = OnConflictStrategy.REPLACE)
+ suspend fun insertChannelStages(rows: List<ChannelImportStageEntity>)
+
+ @Insert(onConflict = OnConflictStrategy.REPLACE)
+ suspend fun insertMovieStages(rows: List<MovieImportStageEntity>)
+
+ @Insert(onConflict = OnConflictStrategy.REPLACE)
+ suspend fun insertSeriesStages(rows: List<SeriesImportStageEntity>)
+
+ @Insert(onConflict = OnConflictStrategy.REPLACE)
+ suspend fun insertCategoryStages(rows: List<CategoryImportStageEntity>)
+
+ @Query("DELETE FROM channel_import_stage WHERE provider_id = :providerId AND session_id = :sessionId")
+ suspend fun clearChannelStages(providerId: Long, sessionId: Long)
+
+ @Query("DELETE FROM movie_import_stage WHERE provider_id = :providerId AND session_id = :sessionId")
+ suspend fun clearMovieStages(providerId: Long, sessionId: Long)
+
+ @Query("DELETE FROM series_import_stage WHERE provider_id = :providerId AND session_id = :sessionId")
+ suspend fun clearSeriesStages(providerId: Long, sessionId: Long)
+
+ @Query("DELETE FROM category_import_stage WHERE provider_id = :providerId AND session_id = :sessionId")
+ suspend fun clearCategoryStages(providerId: Long, sessionId: Long)
+
+ @Query("DELETE FROM channel_import_stage WHERE provider_id = :providerId")
+ suspend fun clearProviderChannelStages(providerId: Long)
+
+ @Query("DELETE FROM movie_import_stage WHERE provider_id = :providerId")
+ suspend fun clearProviderMovieStages(providerId: Long)
+
+ @Query("DELETE FROM series_import_stage WHERE provider_id = :providerId")
+ suspend fun clearProviderSeriesStages(providerId: Long)
+
+ @Query("DELETE FROM category_import_stage WHERE provider_id = :providerId")
+ suspend fun clearProviderCategoryStages(providerId: Long)
+
+ @Query(
+ """
+ UPDATE categories
+ SET name = (
+ SELECT stage.name
+ FROM category_import_stage AS stage
+ WHERE stage.session_id = :sessionId
+ AND stage.provider_id = :providerId
+ AND stage.type = :type
+ AND stage.category_id = categories.category_id
+ ),
+ parent_id = (
+ SELECT stage.parent_id
+ FROM category_import_stage AS stage
+ WHERE stage.session_id = :sessionId
+ AND stage.provider_id = :providerId
+ AND stage.type = :type
+ AND stage.category_id = categories.category_id
+ ),
+ is_adult = (
+ SELECT stage.is_adult
+ FROM category_import_stage AS stage
+ WHERE stage.session_id = :sessionId
+ AND stage.provider_id = :providerId
+ AND stage.type = :type
+ AND stage.category_id = categories.category_id
+ ),
+ sync_fingerprint = (
+ SELECT stage.sync_fingerprint
+ FROM category_import_stage AS stage
+ WHERE stage.session_id = :sessionId
+ AND stage.provider_id = :providerId
+ AND stage.type = :type
+ AND stage.category_id = categories.category_id
+ )
+ WHERE provider_id = :providerId
+ AND type = :type
+ AND EXISTS (
+ SELECT 1
+ FROM category_import_stage AS stage
+ WHERE stage.session_id = :sessionId
+ AND stage.provider_id = :providerId
+ AND stage.type = :type
+ AND stage.category_id = categories.category_id
+ AND categories.sync_fingerprint != stage.sync_fingerprint
+ )
+ """
+ )
+ suspend fun updateChangedCategoriesFromStage(providerId: Long, sessionId: Long, type: String)
+
+ @Query(
+ """
+ INSERT INTO categories (
+ category_id,
+ name,
+ parent_id,
+ type,
+ provider_id,
+ is_adult,
+ is_user_protected,
+ sync_fingerprint
+ )
+ SELECT
+ stage.category_id,
+ stage.name,
+ stage.parent_id,
+ stage.type,
+ stage.provider_id,
+ stage.is_adult,
+ 0,
+ stage.sync_fingerprint
+ FROM category_import_stage AS stage
+ WHERE stage.session_id = :sessionId
+ AND stage.provider_id = :providerId
+ AND stage.type = :type
+ AND NOT EXISTS (
+ SELECT 1
+ FROM categories AS existing
+ WHERE existing.provider_id = stage.provider_id
+ AND existing.type = stage.type
+ AND existing.category_id = stage.category_id
+ )
+ """
+ )
+ suspend fun insertMissingCategoriesFromStage(providerId: Long, sessionId: Long, type: String)
+
+ @Query(
+ """
+ DELETE FROM categories
+ WHERE provider_id = :providerId
+ AND type = :type
+ AND NOT EXISTS (
+ SELECT 1
+ FROM category_import_stage AS stage
+ WHERE stage.session_id = :sessionId
+ AND stage.provider_id = :providerId
+ AND stage.type = :type
+ AND stage.category_id = categories.category_id
+ )
+ """
+ )
+ suspend fun deleteStaleCategoriesForStage(providerId: Long, sessionId: Long, type: String)
+
+ @Query(
+ """
+ UPDATE channels
+ SET name = (
+ SELECT stage.name
+ FROM channel_import_stage AS stage
+ WHERE stage.session_id = :sessionId
+ AND stage.provider_id = :providerId
+ AND stage.stream_id = channels.stream_id
+ ),
+ logo_url = (
+ SELECT stage.logo_url
+ FROM channel_import_stage AS stage
+ WHERE stage.session_id = :sessionId
+ AND stage.provider_id = :providerId
+ AND stage.stream_id = channels.stream_id
+ ),
+ group_title = (
+ SELECT stage.group_title
+ FROM channel_import_stage AS stage
+ WHERE stage.session_id = :sessionId
+ AND stage.provider_id = :providerId
+ AND stage.stream_id = channels.stream_id
+ ),
+ category_id = (
+ SELECT stage.category_id
+ FROM channel_import_stage AS stage
+ WHERE stage.session_id = :sessionId
+ AND stage.provider_id = :providerId
+ AND stage.stream_id = channels.stream_id
+ ),
+ category_name = (
+ SELECT stage.category_name
+ FROM channel_import_stage AS stage
+ WHERE stage.session_id = :sessionId
+ AND stage.provider_id = :providerId
+ AND stage.stream_id = channels.stream_id
+ ),
+ stream_url = (
+ SELECT stage.stream_url
+ FROM channel_import_stage AS stage
+ WHERE stage.session_id = :sessionId
+ AND stage.provider_id = :providerId
+ AND stage.stream_id = channels.stream_id
+ ),
+ epg_channel_id = (
+ SELECT stage.epg_channel_id
+ FROM channel_import_stage AS stage
+ WHERE stage.session_id = :sessionId
+ AND stage.provider_id = :providerId
+ AND stage.stream_id = channels.stream_id
+ ),
+ number = (
+ SELECT stage.number
+ FROM channel_import_stage AS stage
+ WHERE stage.session_id = :sessionId
+ AND stage.provider_id = :providerId
+ AND stage.stream_id = channels.stream_id
+ ),
+ catch_up_supported = (
+ SELECT stage.catch_up_supported
+ FROM channel_import_stage AS stage
+ WHERE stage.session_id = :sessionId
+ AND stage.provider_id = :providerId
+ AND stage.stream_id = channels.stream_id
+ ),
+ catch_up_days = (
+ SELECT stage.catch_up_days
+ FROM channel_import_stage AS stage
+ WHERE stage.session_id = :sessionId
+ AND stage.provider_id = :providerId
+ AND stage.stream_id = channels.stream_id
+ ),
+ catchUpSource = (
+ SELECT stage.catchUpSource
+ FROM channel_import_stage AS stage
+ WHERE stage.session_id = :sessionId
+ AND stage.provider_id = :providerId
+ AND stage.stream_id = channels.stream_id
+ ),
+ logical_group_id = (
+ SELECT stage.logical_group_id
+ FROM channel_import_stage AS stage
+ WHERE stage.session_id = :sessionId
+ AND stage.provider_id = :providerId
+ AND stage.stream_id = channels.stream_id
+ ),
+ error_count = (
+ SELECT stage.error_count
+ FROM channel_import_stage AS stage
+ WHERE stage.session_id = :sessionId
+ AND stage.provider_id = :providerId
+ AND stage.stream_id = channels.stream_id
+ ),
+ is_adult = (
+ SELECT stage.is_adult
+ FROM channel_import_stage AS stage
+ WHERE stage.session_id = :sessionId
+ AND stage.provider_id = :providerId
+ AND stage.stream_id = channels.stream_id
+ ),
+ sync_fingerprint = (
+ SELECT stage.sync_fingerprint
+ FROM channel_import_stage AS stage
+ WHERE stage.session_id = :sessionId
+ AND stage.provider_id = :providerId
+ AND stage.stream_id = channels.stream_id
+ )
+ WHERE provider_id = :providerId
+ AND EXISTS (
+ SELECT 1
+ FROM channel_import_stage AS stage
+ WHERE stage.session_id = :sessionId
+ AND stage.provider_id = :providerId
+ AND stage.stream_id = channels.stream_id
+ AND channels.sync_fingerprint != stage.sync_fingerprint
+ )
+ """
+ )
+ suspend fun updateChangedChannelsFromStage(providerId: Long, sessionId: Long)
+
+ @Query(
+ """
+ INSERT INTO channels (
+ stream_id,
+ name,
+ logo_url,
+ group_title,
+ category_id,
+ category_name,
+ stream_url,
+ epg_channel_id,
+ number,
+ catch_up_supported,
+ catch_up_days,
+ catchUpSource,
+ logical_group_id,
+ error_count,
+ provider_id,
+ is_adult,
+ is_user_protected,
+ sync_fingerprint
+ )
+ SELECT
+ stage.stream_id,
+ stage.name,
+ stage.logo_url,
+ stage.group_title,
+ stage.category_id,
+ stage.category_name,
+ stage.stream_url,
+ stage.epg_channel_id,
+ stage.number,
+ stage.catch_up_supported,
+ stage.catch_up_days,
+ stage.catchUpSource,
+ stage.logical_group_id,
+ stage.error_count,
+ stage.provider_id,
+ stage.is_adult,
+ 0,
+ stage.sync_fingerprint
+ FROM channel_import_stage AS stage
+ WHERE stage.session_id = :sessionId
+ AND stage.provider_id = :providerId
+ AND NOT EXISTS (
+ SELECT 1
+ FROM channels AS existing
+ WHERE existing.provider_id = stage.provider_id
+ AND existing.stream_id = stage.stream_id
+ )
+ """
+ )
+ suspend fun insertMissingChannelsFromStage(providerId: Long, sessionId: Long)
+
+ @Query(
+ """
+ DELETE FROM channels
+ WHERE provider_id = :providerId
+ AND NOT EXISTS (
+ SELECT 1
+ FROM channel_import_stage AS stage
+ WHERE stage.session_id = :sessionId
+ AND stage.provider_id = :providerId
+ AND stage.stream_id = channels.stream_id
+ )
+ """
+ )
+ suspend fun deleteStaleChannelsForStage(providerId: Long, sessionId: Long)
+
+ @Query(
+ """
+ UPDATE movies
+ SET name = (
+ SELECT stage.name
+ FROM movie_import_stage AS stage
+ WHERE stage.session_id = :sessionId
+ AND stage.provider_id = :providerId
+ AND stage.stream_id = movies.stream_id
+ ),
+ poster_url = (
+ SELECT stage.poster_url
+ FROM movie_import_stage AS stage
+ WHERE stage.session_id = :sessionId
+ AND stage.provider_id = :providerId
+ AND stage.stream_id = movies.stream_id
+ ),
+ backdrop_url = (
+ SELECT stage.backdrop_url
+ FROM movie_import_stage AS stage
+ WHERE stage.session_id = :sessionId
+ AND stage.provider_id = :providerId
+ AND stage.stream_id = movies.stream_id
+ ),
+ category_id = (
+ SELECT stage.category_id
+ FROM movie_import_stage AS stage
+ WHERE stage.session_id = :sessionId
+ AND stage.provider_id = :providerId
+ AND stage.stream_id = movies.stream_id
+ ),
+ category_name = (
+ SELECT stage.category_name
+ FROM movie_import_stage AS stage
+ WHERE stage.session_id = :sessionId
+ AND stage.provider_id = :providerId
+ AND stage.stream_id = movies.stream_id
+ ),
+ stream_url = (
+ SELECT stage.stream_url
+ FROM movie_import_stage AS stage
+ WHERE stage.session_id = :sessionId
+ AND stage.provider_id = :providerId
+ AND stage.stream_id = movies.stream_id
+ ),
+ container_extension = (
+ SELECT stage.container_extension
+ FROM movie_import_stage AS stage
+ WHERE stage.session_id = :sessionId
+ AND stage.provider_id = :providerId
+ AND stage.stream_id = movies.stream_id
+ ),
+ plot = (
+ SELECT stage.plot
+ FROM movie_import_stage AS stage
+ WHERE stage.session_id = :sessionId
+ AND stage.provider_id = :providerId
+ AND stage.stream_id = movies.stream_id
+ ),
+ cast = (
+ SELECT stage.cast
+ FROM movie_import_stage AS stage
+ WHERE stage.session_id = :sessionId
+ AND stage.provider_id = :providerId
+ AND stage.stream_id = movies.stream_id
+ ),
+ director = (
+ SELECT stage.director
+ FROM movie_import_stage AS stage
+ WHERE stage.session_id = :sessionId
+ AND stage.provider_id = :providerId
+ AND stage.stream_id = movies.stream_id
+ ),
+ genre = (
+ SELECT stage.genre
+ FROM movie_import_stage AS stage
+ WHERE stage.session_id = :sessionId
+ AND stage.provider_id = :providerId
+ AND stage.stream_id = movies.stream_id
+ ),
+ release_date = (
+ SELECT stage.release_date
+ FROM movie_import_stage AS stage
+ WHERE stage.session_id = :sessionId
+ AND stage.provider_id = :providerId
+ AND stage.stream_id = movies.stream_id
+ ),
+ duration = (
+ SELECT stage.duration
+ FROM movie_import_stage AS stage
+ WHERE stage.session_id = :sessionId
+ AND stage.provider_id = :providerId
+ AND stage.stream_id = movies.stream_id
+ ),
+ duration_seconds = (
+ SELECT stage.duration_seconds
+ FROM movie_import_stage AS stage
+ WHERE stage.session_id = :sessionId
+ AND stage.provider_id = :providerId
+ AND stage.stream_id = movies.stream_id
+ ),
+ rating = (
+ SELECT stage.rating
+ FROM movie_import_stage AS stage
+ WHERE stage.session_id = :sessionId
+ AND stage.provider_id = :providerId
+ AND stage.stream_id = movies.stream_id
+ ),
+ year = (
+ SELECT stage.year
+ FROM movie_import_stage AS stage
+ WHERE stage.session_id = :sessionId
+ AND stage.provider_id = :providerId
+ AND stage.stream_id = movies.stream_id
+ ),
+ tmdb_id = (
+ SELECT stage.tmdb_id
+ FROM movie_import_stage AS stage
+ WHERE stage.session_id = :sessionId
+ AND stage.provider_id = :providerId
+ AND stage.stream_id = movies.stream_id
+ ),
+ youtube_trailer = (
+ SELECT stage.youtube_trailer
+ FROM movie_import_stage AS stage
+ WHERE stage.session_id = :sessionId
+ AND stage.provider_id = :providerId
+ AND stage.stream_id = movies.stream_id
+ ),
+ is_adult = (
+ SELECT stage.is_adult
+ FROM movie_import_stage AS stage
+ WHERE stage.session_id = :sessionId
+ AND stage.provider_id = :providerId
+ AND stage.stream_id = movies.stream_id
+ ),
+ sync_fingerprint = (
+ SELECT stage.sync_fingerprint
+ FROM movie_import_stage AS stage
+ WHERE stage.session_id = :sessionId
+ AND stage.provider_id = :providerId
+ AND stage.stream_id = movies.stream_id
+ )
+ WHERE provider_id = :providerId
+ AND EXISTS (
+ SELECT 1
+ FROM movie_import_stage AS stage
+ WHERE stage.session_id = :sessionId
+ AND stage.provider_id = :providerId
+ AND stage.stream_id = movies.stream_id
+ AND movies.sync_fingerprint != stage.sync_fingerprint
+ )
+ """
+ )
+ suspend fun updateChangedMoviesFromStage(providerId: Long, sessionId: Long)
+
+ @Query(
+ """
+ INSERT INTO movies (
+ stream_id,
+ name,
+ poster_url,
+ backdrop_url,
+ category_id,
+ category_name,
+ stream_url,
+ container_extension,
+ plot,
+ cast,
+ director,
+ genre,
+ release_date,
+ duration,
+ duration_seconds,
+ rating,
+ year,
+ tmdb_id,
+ youtube_trailer,
+ provider_id,
+ watch_progress,
+ last_watched_at,
+ is_adult,
+ is_user_protected,
+ sync_fingerprint
+ )
+ SELECT
+ stage.stream_id,
+ stage.name,
+ stage.poster_url,
+ stage.backdrop_url,
+ stage.category_id,
+ stage.category_name,
+ stage.stream_url,
+ stage.container_extension,
+ stage.plot,
+ stage.cast,
+ stage.director,
+ stage.genre,
+ stage.release_date,
+ stage.duration,
+ stage.duration_seconds,
+ stage.rating,
+ stage.year,
+ stage.tmdb_id,
+ stage.youtube_trailer,
+ stage.provider_id,
+ 0,
+ 0,
+ stage.is_adult,
+ 0,
+ stage.sync_fingerprint
+ FROM movie_import_stage AS stage
+ WHERE stage.session_id = :sessionId
+ AND stage.provider_id = :providerId
+ AND NOT EXISTS (
+ SELECT 1
+ FROM movies AS existing
+ WHERE existing.provider_id = stage.provider_id
+ AND existing.stream_id = stage.stream_id
+ )
+ """
+ )
+ suspend fun insertMissingMoviesFromStage(providerId: Long, sessionId: Long)
+
+ @Query(
+ """
+ DELETE FROM movies
+ WHERE provider_id = :providerId
+ AND NOT EXISTS (
+ SELECT 1
+ FROM movie_import_stage AS stage
+ WHERE stage.session_id = :sessionId
+ AND stage.provider_id = :providerId
+ AND stage.stream_id = movies.stream_id
+ )
+ """
+ )
+ suspend fun deleteStaleMoviesForStage(providerId: Long, sessionId: Long)
+
+ @Query(
+ """
+ UPDATE series
+ SET name = (
+ SELECT stage.name
+ FROM series_import_stage AS stage
+ WHERE stage.session_id = :sessionId
+ AND stage.provider_id = :providerId
+ AND stage.series_id = series.series_id
+ ),
+ poster_url = (
+ SELECT stage.poster_url
+ FROM series_import_stage AS stage
+ WHERE stage.session_id = :sessionId
+ AND stage.provider_id = :providerId
+ AND stage.series_id = series.series_id
+ ),
+ backdrop_url = (
+ SELECT stage.backdrop_url
+ FROM series_import_stage AS stage
+ WHERE stage.session_id = :sessionId
+ AND stage.provider_id = :providerId
+ AND stage.series_id = series.series_id
+ ),
+ category_id = (
+ SELECT stage.category_id
+ FROM series_import_stage AS stage
+ WHERE stage.session_id = :sessionId
+ AND stage.provider_id = :providerId
+ AND stage.series_id = series.series_id
+ ),
+ category_name = (
+ SELECT stage.category_name
+ FROM series_import_stage AS stage
+ WHERE stage.session_id = :sessionId
+ AND stage.provider_id = :providerId
+ AND stage.series_id = series.series_id
+ ),
+ plot = (
+ SELECT stage.plot
+ FROM series_import_stage AS stage
+ WHERE stage.session_id = :sessionId
+ AND stage.provider_id = :providerId
+ AND stage.series_id = series.series_id
+ ),
+ cast = (
+ SELECT stage.cast
+ FROM series_import_stage AS stage
+ WHERE stage.session_id = :sessionId
+ AND stage.provider_id = :providerId
+ AND stage.series_id = series.series_id
+ ),
+ director = (
+ SELECT stage.director
+ FROM series_import_stage AS stage
+ WHERE stage.session_id = :sessionId
+ AND stage.provider_id = :providerId
+ AND stage.series_id = series.series_id
+ ),
+ genre = (
+ SELECT stage.genre
+ FROM series_import_stage AS stage
+ WHERE stage.session_id = :sessionId
+ AND stage.provider_id = :providerId
+ AND stage.series_id = series.series_id
+ ),
+ release_date = (
+ SELECT stage.release_date
+ FROM series_import_stage AS stage
+ WHERE stage.session_id = :sessionId
+ AND stage.provider_id = :providerId
+ AND stage.series_id = series.series_id
+ ),
+ rating = (
+ SELECT stage.rating
+ FROM series_import_stage AS stage
+ WHERE stage.session_id = :sessionId
+ AND stage.provider_id = :providerId
+ AND stage.series_id = series.series_id
+ ),
+ tmdb_id = (
+ SELECT stage.tmdb_id
+ FROM series_import_stage AS stage
+ WHERE stage.session_id = :sessionId
+ AND stage.provider_id = :providerId
+ AND stage.series_id = series.series_id
+ ),
+ youtube_trailer = (
+ SELECT stage.youtube_trailer
+ FROM series_import_stage AS stage
+ WHERE stage.session_id = :sessionId
+ AND stage.provider_id = :providerId
+ AND stage.series_id = series.series_id
+ ),
+ episode_run_time = (
+ SELECT stage.episode_run_time
+ FROM series_import_stage AS stage
+ WHERE stage.session_id = :sessionId
+ AND stage.provider_id = :providerId
+ AND stage.series_id = series.series_id
+ ),
+ last_modified = (
+ SELECT stage.last_modified
+ FROM series_import_stage AS stage
+ WHERE stage.session_id = :sessionId
+ AND stage.provider_id = :providerId
+ AND stage.series_id = series.series_id
+ ),
+ is_adult = (
+ SELECT stage.is_adult
+ FROM series_import_stage AS stage
+ WHERE stage.session_id = :sessionId
+ AND stage.provider_id = :providerId
+ AND stage.series_id = series.series_id
+ ),
+ sync_fingerprint = (
+ SELECT stage.sync_fingerprint
+ FROM series_import_stage AS stage
+ WHERE stage.session_id = :sessionId
+ AND stage.provider_id = :providerId
+ AND stage.series_id = series.series_id
+ )
+ WHERE provider_id = :providerId
+ AND EXISTS (
+ SELECT 1
+ FROM series_import_stage AS stage
+ WHERE stage.session_id = :sessionId
+ AND stage.provider_id = :providerId
+ AND stage.series_id = series.series_id
+ AND series.sync_fingerprint != stage.sync_fingerprint
+ )
+ """
+ )
+ suspend fun updateChangedSeriesFromStage(providerId: Long, sessionId: Long)
+
+ @Query(
+ """
+ INSERT INTO series (
+ series_id,
+ name,
+ poster_url,
+ backdrop_url,
+ category_id,
+ category_name,
+ plot,
+ cast,
+ director,
+ genre,
+ release_date,
+ rating,
+ tmdb_id,
+ youtube_trailer,
+ episode_run_time,
+ last_modified,
+ provider_id,
+ is_adult,
+ is_user_protected,
+ sync_fingerprint
+ )
+ SELECT
+ stage.series_id,
+ stage.name,
+ stage.poster_url,
+ stage.backdrop_url,
+ stage.category_id,
+ stage.category_name,
+ stage.plot,
+ stage.cast,
+ stage.director,
+ stage.genre,
+ stage.release_date,
+ stage.rating,
+ stage.tmdb_id,
+ stage.youtube_trailer,
+ stage.episode_run_time,
+ stage.last_modified,
+ stage.provider_id,
+ stage.is_adult,
+ 0,
+ stage.sync_fingerprint
+ FROM series_import_stage AS stage
+ WHERE stage.session_id = :sessionId
+ AND stage.provider_id = :providerId
+ AND NOT EXISTS (
+ SELECT 1
+ FROM series AS existing
+ WHERE existing.provider_id = stage.provider_id
+ AND existing.series_id = stage.series_id
+ )
+ """
+ )
+ suspend fun insertMissingSeriesFromStage(providerId: Long, sessionId: Long)
+
+ @Query(
+ """
+ DELETE FROM series
+ WHERE provider_id = :providerId
+ AND NOT EXISTS (
+ SELECT 1
+ FROM series_import_stage AS stage
+ WHERE stage.session_id = :sessionId
+ AND stage.provider_id = :providerId
+ AND stage.series_id = series.series_id
+ )
+ """
+ )
+ suspend fun deleteStaleSeriesForStage(providerId: Long, sessionId: Long)
+}
diff --git a/data/src/main/java/com/streamvault/data/local/dao/Daos.kt b/data/src/main/java/com/streamvault/data/local/dao/Daos.kt
index 798827f9..9857a0c0 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
@@ -54,27 +54,66 @@ abstract class ProviderDao {
@Dao
interface ChannelDao {
- @Query("SELECT * FROM channels WHERE provider_id = :providerId ORDER BY number ASC")
- fun getByProvider(providerId: Long): Flow<List<ChannelEntity>>
+ @Query(
+ """
+ SELECT id, stream_id, name, logo_url, group_title, category_id, category_name, stream_url,
+ epg_channel_id, number, catch_up_supported, catch_up_days, catchUpSource,
+ provider_id, is_adult, is_user_protected, logical_group_id, error_count
+ FROM channels
+ WHERE provider_id = :providerId
+ ORDER BY number ASC
+ """
+ )
+ fun getByProvider(providerId: Long): Flow<List<ChannelBrowseEntity>>
- @Query("SELECT * FROM channels WHERE provider_id = :providerId AND error_count = 0 ORDER BY number ASC")
- fun getByProviderWithoutErrors(providerId: Long): Flow<List<ChannelEntity>>
+ @Query(
+ """
+ SELECT id, stream_id, name, logo_url, group_title, category_id, category_name, stream_url,
+ epg_channel_id, number, catch_up_supported, catch_up_days, catchUpSource,
+ provider_id, is_adult, is_user_protected, logical_group_id, error_count
+ FROM channels
+ WHERE provider_id = :providerId AND error_count = 0
+ ORDER BY number ASC
+ """
+ )
+ fun getByProviderWithoutErrors(providerId: Long): Flow<List<ChannelBrowseEntity>>
@Query("SELECT * FROM channels WHERE provider_id = :providerId ORDER BY number ASC LIMIT :limit OFFSET :offset")
fun getByProviderPage(providerId: Long, limit: Int, offset: Int): Flow<List<ChannelEntity>>
- @Query("SELECT * FROM channels WHERE provider_id = :providerId AND category_id = :categoryId ORDER BY number ASC")
- fun getByCategory(providerId: Long, categoryId: Long): Flow<List<ChannelEntity>>
+ @Query(
+ """
+ SELECT id, stream_id, name, logo_url, group_title, category_id, category_name, stream_url,
+ epg_channel_id, number, catch_up_supported, catch_up_days, catchUpSource,
+ provider_id, is_adult, is_user_protected, logical_group_id, error_count
+ FROM channels
+ WHERE provider_id = :providerId AND category_id = :categoryId
+ ORDER BY number ASC
+ """
+ )
+ fun getByCategory(providerId: Long, categoryId: Long): Flow<List<ChannelBrowseEntity>>
- @Query("SELECT * FROM channels WHERE provider_id = :providerId AND category_id = :categoryId AND error_count = 0 ORDER BY number ASC")
- fun getByCategoryWithoutErrors(providerId: Long, categoryId: Long): Flow<List<ChannelEntity>>
+ @Query(
+ """
+ SELECT id, stream_id, name, logo_url, group_title, category_id, category_name, stream_url,
+ epg_channel_id, number, catch_up_supported, catch_up_days, catchUpSource,
+ provider_id, is_adult, is_user_protected, logical_group_id, error_count
+ FROM channels
+ WHERE provider_id = :providerId AND category_id = :categoryId AND error_count = 0
+ ORDER BY number ASC
+ """
+ )
+ fun getByCategoryWithoutErrors(providerId: Long, categoryId: Long): Flow<List<ChannelBrowseEntity>>
@Query("SELECT * FROM channels WHERE provider_id = :providerId AND category_id = :categoryId ORDER BY number ASC LIMIT :limit OFFSET :offset")
fun getByCategoryPage(providerId: Long, categoryId: Long, limit: Int, offset: Int): Flow<List<ChannelEntity>>
@Query(
"""
- SELECT c.* FROM channels c
+ 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
JOIN channels_fts ON c.id = channels_fts.rowid
WHERE c.provider_id = :providerId
AND channels_fts MATCH :query
@@ -82,11 +121,14 @@ interface ChannelDao {
LIMIT :limit
"""
)
- fun search(providerId: Long, query: String, limit: Int): Flow<List<ChannelEntity>>
+ fun search(providerId: Long, query: String, limit: Int): Flow<List<ChannelBrowseEntity>>
@Query(
"""
- SELECT c.* FROM channels c
+ 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
JOIN channels_fts ON c.id = channels_fts.rowid
WHERE c.provider_id = :providerId
AND c.category_id = :categoryId
@@ -95,11 +137,14 @@ interface ChannelDao {
LIMIT :limit
"""
)
- fun searchByCategory(providerId: Long, categoryId: Long, query: String, limit: Int): Flow<List<ChannelEntity>>
+ fun searchByCategory(providerId: Long, categoryId: Long, query: String, limit: Int): Flow<List<ChannelBrowseEntity>>
@Query("SELECT * FROM channels WHERE id = :id")
suspend fun getById(id: Long): ChannelEntity?
+ @Query("SELECT * FROM channels WHERE provider_id = :providerId")
+ suspend fun getByProviderSync(providerId: Long): List<ChannelEntity>
+
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertAll(channels: List<ChannelEntity>)
@@ -122,8 +167,16 @@ interface ChannelDao {
insertAll(remapped)
}
- @Query("SELECT * FROM channels WHERE id IN (:ids)")
- fun getByIds(ids: List<Long>): Flow<List<ChannelEntity>>
+ @Query(
+ """
+ SELECT id, stream_id, name, logo_url, group_title, category_id, category_name, stream_url,
+ epg_channel_id, number, catch_up_supported, catch_up_days, catchUpSource,
+ provider_id, is_adult, is_user_protected, logical_group_id, error_count
+ FROM channels
+ WHERE id IN (:ids)
+ """
+ )
+ fun getByIds(ids: List<Long>): Flow<List<ChannelBrowseEntity>>
@Query("SELECT category_id, COUNT(*) as item_count FROM channels WHERE provider_id = :providerId AND category_id IS NOT NULL GROUP BY category_id")
fun getCategoryCounts(providerId: Long): Flow<List<CategoryCount>>
@@ -172,53 +225,290 @@ interface ChannelPreferenceDao {
}
@Dao
+@RewriteQueriesToDropUnusedColumns
interface MovieDao {
@Query("SELECT * FROM movies WHERE provider_id = :providerId ORDER BY name ASC")
- fun getByProvider(providerId: Long): Flow<List<MovieEntity>>
+ fun getByProvider(providerId: Long): Flow<List<MovieBrowseEntity>>
/** SQL-level parental filter — avoids loading protected items into memory. */
@Query("SELECT * FROM movies WHERE provider_id = :providerId AND is_user_protected = 0 ORDER BY name ASC")
- fun getByProviderUnprotected(providerId: Long): Flow<List<MovieEntity>>
+ fun getByProviderUnprotected(providerId: Long): Flow<List<MovieBrowseEntity>>
@Query("SELECT * FROM movies WHERE provider_id = :providerId ORDER BY name ASC LIMIT :limit OFFSET :offset")
- fun getByProviderPage(providerId: Long, limit: Int, offset: Int): Flow<List<MovieEntity>>
+ fun getByProviderPage(providerId: Long, limit: Int, offset: Int): Flow<List<MovieBrowseEntity>>
+
+ @Query(
+ """
+ SELECT movies.* FROM movies
+ WHERE movies.provider_id = :providerId
+ AND EXISTS (
+ SELECT 1 FROM favorites
+ WHERE favorites.content_type = 'MOVIE'
+ AND favorites.group_id IS NULL
+ AND favorites.content_id = movies.id
+ )
+ ORDER BY movies.name ASC
+ LIMIT :limit OFFSET :offset
+ """
+ )
+ fun getFavoritesByProviderPage(providerId: Long, limit: Int, offset: Int): Flow<List<MovieBrowseEntity>>
+
+ @Query(
+ """
+ SELECT COUNT(*)
+ FROM movies
+ WHERE provider_id = :providerId
+ AND EXISTS (
+ SELECT 1 FROM favorites
+ WHERE favorites.content_type = 'MOVIE'
+ AND favorites.group_id IS NULL
+ AND favorites.content_id = movies.id
+ )
+ """
+ )
+ fun getFavoriteCountByProvider(providerId: Long): Flow<Int>
+
+ @Query(
+ """
+ SELECT movies.* FROM movies
+ WHERE movies.provider_id = :providerId
+ 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 :limit OFFSET :offset
+ """
+ )
+ fun getInProgressByProviderPage(providerId: Long, limit: Int, offset: Int): Flow<List<MovieBrowseEntity>>
+
+ @Query(
+ """
+ SELECT COUNT(*)
+ FROM movies
+ WHERE provider_id = :providerId
+ 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)
+ )
+ )
+ """
+ )
+ fun getInProgressCountByProvider(providerId: Long): Flow<Int>
+
+ @Query(
+ """
+ SELECT movies.* FROM movies
+ WHERE movies.provider_id = :providerId
+ AND COALESCE(movies.watch_progress, 0) <= 0
+ ORDER BY movies.name ASC
+ LIMIT :limit OFFSET :offset
+ """
+ )
+ fun getUnwatchedByProviderPage(providerId: Long, limit: Int, offset: Int): Flow<List<MovieBrowseEntity>>
+
+ @Query("SELECT COUNT(*) FROM movies WHERE provider_id = :providerId AND COALESCE(watch_progress, 0) <= 0")
+ fun getUnwatchedCountByProvider(providerId: Long): Flow<Int>
+
+ @Query(
+ """
+ SELECT movies.* FROM movies
+ WHERE movies.provider_id = :providerId
+ ORDER BY COALESCE((
+ SELECT playback_history.watch_count
+ FROM playback_history
+ WHERE playback_history.provider_id = movies.provider_id
+ AND playback_history.content_type = 'MOVIE'
+ AND playback_history.content_id = movies.id
+ LIMIT 1
+ ), 0) DESC, movies.name ASC
+ LIMIT :limit OFFSET :offset
+ """
+ )
+ fun getByWatchCountProviderPage(providerId: Long, limit: Int, offset: Int): Flow<List<MovieBrowseEntity>>
@Query("SELECT * FROM movies WHERE provider_id = :providerId AND category_id = :categoryId ORDER BY name ASC")
- fun getByCategory(providerId: Long, categoryId: Long): Flow<List<MovieEntity>>
+ fun getByCategory(providerId: Long, categoryId: Long): Flow<List<MovieBrowseEntity>>
+
+ @Query(
+ """
+ SELECT movies.* FROM movies
+ WHERE movies.provider_id = :providerId
+ AND movies.category_id = :categoryId
+ AND EXISTS (
+ SELECT 1 FROM favorites
+ WHERE favorites.content_type = 'MOVIE'
+ AND favorites.group_id IS NULL
+ AND favorites.content_id = movies.id
+ )
+ ORDER BY movies.name ASC
+ LIMIT :limit OFFSET :offset
+ """
+ )
+ fun getFavoritesByCategoryPage(providerId: Long, categoryId: Long, limit: Int, offset: Int): Flow<List<MovieBrowseEntity>>
+
+ @Query(
+ """
+ SELECT COUNT(*)
+ FROM movies
+ WHERE provider_id = :providerId
+ AND category_id = :categoryId
+ AND EXISTS (
+ SELECT 1 FROM favorites
+ WHERE favorites.content_type = 'MOVIE'
+ AND favorites.group_id IS NULL
+ AND favorites.content_id = movies.id
+ )
+ """
+ )
+ fun getFavoriteCountByCategory(providerId: Long, categoryId: Long): Flow<Int>
+
+ @Query(
+ """
+ SELECT movies.* FROM movies
+ WHERE movies.provider_id = :providerId
+ AND movies.category_id = :categoryId
+ 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 :limit OFFSET :offset
+ """
+ )
+ fun getInProgressByCategoryPage(providerId: Long, categoryId: Long, limit: Int, offset: Int): Flow<List<MovieBrowseEntity>>
+
+ @Query(
+ """
+ SELECT COUNT(*)
+ FROM movies
+ WHERE provider_id = :providerId
+ AND category_id = :categoryId
+ AND 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)
+ )
+ )
+ """
+ )
+ fun getInProgressCountByCategory(providerId: Long, categoryId: Long): Flow<Int>
+
+ @Query(
+ """
+ SELECT movies.* FROM movies
+ WHERE movies.provider_id = :providerId
+ AND movies.category_id = :categoryId
+ AND COALESCE(movies.watch_progress, 0) <= 0
+ ORDER BY movies.name ASC
+ LIMIT :limit OFFSET :offset
+ """
+ )
+ fun getUnwatchedByCategoryPage(providerId: Long, categoryId: Long, limit: Int, offset: Int): Flow<List<MovieBrowseEntity>>
+
+ @Query(
+ "SELECT COUNT(*) FROM movies WHERE provider_id = :providerId AND category_id = :categoryId AND COALESCE(watch_progress, 0) <= 0"
+ )
+ fun getUnwatchedCountByCategory(providerId: Long, categoryId: Long): Flow<Int>
+
+ @Query(
+ """
+ SELECT movies.* FROM movies
+ WHERE movies.provider_id = :providerId
+ AND movies.category_id = :categoryId
+ ORDER BY COALESCE((
+ SELECT playback_history.watch_count
+ FROM playback_history
+ WHERE playback_history.provider_id = movies.provider_id
+ AND playback_history.content_type = 'MOVIE'
+ AND playback_history.content_id = movies.id
+ LIMIT 1
+ ), 0) DESC, movies.name ASC
+ LIMIT :limit OFFSET :offset
+ """
+ )
+ fun getByWatchCountCategoryPage(providerId: Long, categoryId: Long, limit: Int, offset: Int): Flow<List<MovieBrowseEntity>>
/** SQL-level parental filter per category. */
@Query("SELECT * FROM movies WHERE provider_id = :providerId AND category_id = :categoryId AND is_user_protected = 0 ORDER BY name ASC")
- fun getByCategoryUnprotected(providerId: Long, categoryId: Long): Flow<List<MovieEntity>>
+ fun getByCategoryUnprotected(providerId: Long, categoryId: Long): Flow<List<MovieBrowseEntity>>
@Query("SELECT * FROM movies WHERE provider_id = :providerId AND category_id = :categoryId ORDER BY name ASC LIMIT :limit OFFSET :offset")
- fun getByCategoryPage(providerId: Long, categoryId: Long, limit: Int, offset: Int): Flow<List<MovieEntity>>
+ fun getByCategoryPage(providerId: Long, categoryId: Long, limit: Int, offset: Int): Flow<List<MovieBrowseEntity>>
@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<MovieEntity>>
+ 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")
- fun getTopRatedPreview(providerId: Long, limit: Int): Flow<List<MovieEntity>>
+ fun getTopRatedPreview(providerId: Long, limit: Int): Flow<List<MovieBrowseEntity>>
+
+ @Query("SELECT * FROM movies WHERE provider_id = :providerId AND category_id = :categoryId ORDER BY rating DESC, name ASC LIMIT :limit")
+ fun getTopRatedByCategoryPreview(providerId: Long, categoryId: Long, limit: Int): Flow<List<MovieBrowseEntity>>
@Query("SELECT * FROM movies WHERE provider_id = :providerId ORDER BY release_date DESC, name ASC LIMIT :limit")
- fun getFreshPreview(providerId: Long, limit: Int): Flow<List<MovieEntity>>
+ fun getFreshPreview(providerId: Long, limit: Int): Flow<List<MovieBrowseEntity>>
+
+ @Query("SELECT * FROM movies WHERE provider_id = :providerId AND category_id = :categoryId ORDER BY release_date DESC, name ASC LIMIT :limit")
+ fun getFreshByCategoryPreview(providerId: Long, categoryId: Long, limit: Int): Flow<List<MovieBrowseEntity>>
+
+ @Query(
+ """
+ SELECT m.* FROM movies m
+ JOIN movies_fts ON m.id = movies_fts.rowid
+ WHERE m.provider_id = :providerId
+ AND movies_fts MATCH :query
+ ORDER BY m.name ASC
+ LIMIT :limit
+ """
+ )
+ fun search(providerId: Long, query: String, limit: Int): Flow<List<MovieBrowseEntity>>
@Query(
"""
SELECT m.* FROM movies m
JOIN movies_fts ON m.id = movies_fts.rowid
WHERE m.provider_id = :providerId
+ AND m.category_id = :categoryId
AND movies_fts MATCH :query
ORDER BY m.name ASC
LIMIT :limit
"""
)
- fun search(providerId: Long, query: String, limit: Int): Flow<List<MovieEntity>>
+ fun searchByCategory(providerId: Long, categoryId: Long, query: String, limit: Int): Flow<List<MovieBrowseEntity>>
@Query("SELECT * FROM movies WHERE id = :id")
suspend fun getById(id: Long): MovieEntity?
+ @Query("SELECT * FROM movies WHERE provider_id = :providerId")
+ suspend fun getByProviderSync(providerId: Long): List<MovieEntity>
+
@Query("SELECT * FROM movies WHERE id IN (:ids)")
- fun getByIds(ids: List<Long>): Flow<List<MovieEntity>>
+ fun getByIds(ids: List<Long>): Flow<List<MovieBrowseEntity>>
@Query("SELECT * FROM movies WHERE provider_id = :providerId AND stream_id = :streamId")
suspend fun getByStreamId(providerId: Long, streamId: Long): MovieEntity?
@@ -368,27 +658,369 @@ interface MovieDao {
}
@Dao
+@RewriteQueriesToDropUnusedColumns
interface SeriesDao {
@Query("SELECT * FROM series WHERE provider_id = :providerId ORDER BY name ASC")
- fun getByProvider(providerId: Long): Flow<List<SeriesEntity>>
+ fun getByProvider(providerId: Long): Flow<List<SeriesBrowseEntity>>
@Query("SELECT * FROM series WHERE provider_id = :providerId ORDER BY name ASC LIMIT :limit OFFSET :offset")
- fun getByProviderPage(providerId: Long, limit: Int, offset: Int): Flow<List<SeriesEntity>>
+ fun getByProviderPage(providerId: Long, limit: Int, offset: Int): Flow<List<SeriesBrowseEntity>>
+
+ @Query(
+ """
+ SELECT series.* FROM series
+ WHERE series.provider_id = :providerId
+ AND EXISTS (
+ SELECT 1 FROM favorites
+ WHERE favorites.content_type = 'SERIES'
+ AND favorites.group_id IS NULL
+ AND favorites.content_id = series.id
+ )
+ ORDER BY series.name ASC
+ LIMIT :limit OFFSET :offset
+ """
+ )
+ fun getFavoritesByProviderPage(providerId: Long, limit: Int, offset: Int): Flow<List<SeriesBrowseEntity>>
+
+ @Query(
+ """
+ SELECT COUNT(*)
+ FROM series
+ WHERE provider_id = :providerId
+ AND EXISTS (
+ SELECT 1 FROM favorites
+ WHERE favorites.content_type = 'SERIES'
+ AND favorites.group_id IS NULL
+ AND favorites.content_id = series.id
+ )
+ """
+ )
+ fun getFavoriteCountByProvider(providerId: Long): Flow<Int>
+
+ @Query(
+ """
+ SELECT series.* FROM series
+ WHERE series.provider_id = :providerId
+ AND EXISTS (
+ SELECT 1 FROM playback_history
+ WHERE playback_history.provider_id = series.provider_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)
+ )
+ 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
+ )
+ )
+ )
+ )
+ ORDER BY series.name ASC
+ LIMIT :limit OFFSET :offset
+ """
+ )
+ fun getInProgressByProviderPage(providerId: Long, limit: Int, offset: Int): Flow<List<SeriesBrowseEntity>>
+
+ @Query(
+ """
+ SELECT COUNT(*)
+ FROM series
+ WHERE provider_id = :providerId
+ AND EXISTS (
+ SELECT 1 FROM playback_history
+ WHERE playback_history.provider_id = series.provider_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)
+ )
+ 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
+ )
+ )
+ )
+ )
+ """
+ )
+ fun getInProgressCountByProvider(providerId: Long): Flow<Int>
+
+ @Query(
+ """
+ SELECT series.* FROM series
+ WHERE 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
+ )
+ )
+ )
+ )
+ ORDER BY series.name ASC
+ LIMIT :limit OFFSET :offset
+ """
+ )
+ fun getUnwatchedByProviderPage(providerId: Long, limit: Int, offset: Int): Flow<List<SeriesBrowseEntity>>
+
+ @Query(
+ """
+ SELECT COUNT(*)
+ FROM series
+ WHERE 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
+ )
+ )
+ )
+ )
+ """
+ )
+ fun getUnwatchedCountByProvider(providerId: Long): Flow<Int>
+
+ @Query(
+ """
+ SELECT series.* FROM series
+ WHERE series.provider_id = :providerId
+ ORDER BY COALESCE((
+ SELECT MAX(playback_history.watch_count)
+ FROM playback_history
+ WHERE playback_history.provider_id = series.provider_id
+ AND (
+ (playback_history.content_type = 'SERIES' AND playback_history.content_id = series.id)
+ OR (
+ playback_history.content_type = 'SERIES_EPISODE'
+ AND EXISTS (
+ SELECT 1 FROM episodes
+ WHERE episodes.id = playback_history.content_id
+ AND episodes.series_id = series.id
+ )
+ )
+ )
+ ), 0) DESC, series.name ASC
+ LIMIT :limit OFFSET :offset
+ """
+ )
+ fun getByWatchCountProviderPage(providerId: Long, limit: Int, offset: Int): Flow<List<SeriesBrowseEntity>>
@Query("SELECT * FROM series WHERE provider_id = :providerId AND category_id = :categoryId ORDER BY name ASC")
- fun getByCategory(providerId: Long, categoryId: Long): Flow<List<SeriesEntity>>
+ fun getByCategory(providerId: Long, categoryId: Long): Flow<List<SeriesBrowseEntity>>
+
+ @Query(
+ """
+ SELECT series.* FROM series
+ WHERE series.provider_id = :providerId
+ AND series.category_id = :categoryId
+ AND EXISTS (
+ SELECT 1 FROM favorites
+ WHERE favorites.content_type = 'SERIES'
+ AND favorites.group_id IS NULL
+ AND favorites.content_id = series.id
+ )
+ ORDER BY series.name ASC
+ LIMIT :limit OFFSET :offset
+ """
+ )
+ fun getFavoritesByCategoryPage(providerId: Long, categoryId: Long, limit: Int, offset: Int): Flow<List<SeriesBrowseEntity>>
+
+ @Query(
+ """
+ SELECT COUNT(*)
+ FROM series
+ WHERE provider_id = :providerId
+ AND category_id = :categoryId
+ AND EXISTS (
+ SELECT 1 FROM favorites
+ WHERE favorites.content_type = 'SERIES'
+ AND favorites.group_id IS NULL
+ AND favorites.content_id = series.id
+ )
+ """
+ )
+ fun getFavoriteCountByCategory(providerId: Long, categoryId: Long): Flow<Int>
+
+ @Query(
+ """
+ SELECT series.* FROM series
+ WHERE series.provider_id = :providerId
+ AND series.category_id = :categoryId
+ AND EXISTS (
+ SELECT 1 FROM playback_history
+ WHERE playback_history.provider_id = series.provider_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)
+ )
+ 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
+ )
+ )
+ )
+ )
+ ORDER BY series.name ASC
+ LIMIT :limit OFFSET :offset
+ """
+ )
+ fun getInProgressByCategoryPage(providerId: Long, categoryId: Long, limit: Int, offset: Int): Flow<List<SeriesBrowseEntity>>
+
+ @Query(
+ """
+ SELECT COUNT(*)
+ FROM series
+ WHERE provider_id = :providerId
+ AND category_id = :categoryId
+ AND EXISTS (
+ SELECT 1 FROM playback_history
+ WHERE playback_history.provider_id = series.provider_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)
+ )
+ 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
+ )
+ )
+ )
+ )
+ """
+ )
+ fun getInProgressCountByCategory(providerId: Long, categoryId: Long): Flow<Int>
+
+ @Query(
+ """
+ SELECT series.* FROM series
+ WHERE series.provider_id = :providerId
+ AND 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
+ )
+ )
+ )
+ )
+ ORDER BY series.name ASC
+ LIMIT :limit OFFSET :offset
+ """
+ )
+ fun getUnwatchedByCategoryPage(providerId: Long, categoryId: Long, limit: Int, offset: Int): Flow<List<SeriesBrowseEntity>>
+
+ @Query(
+ """
+ SELECT COUNT(*)
+ FROM series
+ WHERE provider_id = :providerId
+ AND 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
+ )
+ )
+ )
+ )
+ """
+ )
+ fun getUnwatchedCountByCategory(providerId: Long, categoryId: Long): Flow<Int>
+
+ @Query(
+ """
+ SELECT series.* FROM series
+ WHERE series.provider_id = :providerId
+ AND series.category_id = :categoryId
+ ORDER BY COALESCE((
+ SELECT MAX(playback_history.watch_count)
+ FROM playback_history
+ WHERE playback_history.provider_id = series.provider_id
+ AND (
+ (playback_history.content_type = 'SERIES' AND playback_history.content_id = series.id)
+ OR (
+ playback_history.content_type = 'SERIES_EPISODE'
+ AND EXISTS (
+ SELECT 1 FROM episodes
+ WHERE episodes.id = playback_history.content_id
+ AND episodes.series_id = series.id
+ )
+ )
+ )
+ ), 0) DESC, series.name ASC
+ LIMIT :limit OFFSET :offset
+ """
+ )
+ fun getByWatchCountCategoryPage(providerId: Long, categoryId: Long, limit: Int, offset: Int): Flow<List<SeriesBrowseEntity>>
@Query("SELECT * FROM series WHERE provider_id = :providerId AND category_id = :categoryId ORDER BY name ASC LIMIT :limit OFFSET :offset")
- fun getByCategoryPage(providerId: Long, categoryId: Long, limit: Int, offset: Int): Flow<List<SeriesEntity>>
+ fun getByCategoryPage(providerId: Long, categoryId: Long, limit: Int, offset: Int): Flow<List<SeriesBrowseEntity>>
@Query("SELECT * FROM series WHERE provider_id = :providerId AND category_id = :categoryId ORDER BY name ASC LIMIT :limit")
- fun getByCategoryPreview(providerId: Long, categoryId: Long, limit: Int): Flow<List<SeriesEntity>>
+ fun getByCategoryPreview(providerId: Long, categoryId: Long, limit: Int): Flow<List<SeriesBrowseEntity>>
@Query("SELECT * FROM series WHERE provider_id = :providerId ORDER BY rating DESC, name ASC LIMIT :limit")
- fun getTopRatedPreview(providerId: Long, limit: Int): Flow<List<SeriesEntity>>
+ fun getTopRatedPreview(providerId: Long, limit: Int): Flow<List<SeriesBrowseEntity>>
+
+ @Query("SELECT * FROM series WHERE provider_id = :providerId AND category_id = :categoryId ORDER BY rating DESC, name ASC LIMIT :limit")
+ fun getTopRatedByCategoryPreview(providerId: Long, categoryId: Long, limit: Int): Flow<List<SeriesBrowseEntity>>
@Query("SELECT * FROM series WHERE provider_id = :providerId ORDER BY last_modified DESC, name ASC LIMIT :limit")
- fun getFreshPreview(providerId: Long, limit: Int): Flow<List<SeriesEntity>>
+ fun getFreshPreview(providerId: Long, limit: Int): Flow<List<SeriesBrowseEntity>>
+
+ @Query("SELECT * FROM series WHERE provider_id = :providerId AND category_id = :categoryId ORDER BY last_modified DESC, name ASC LIMIT :limit")
+ fun getFreshByCategoryPreview(providerId: Long, categoryId: Long, limit: Int): Flow<List<SeriesBrowseEntity>>
@Query(
"""
@@ -400,13 +1032,29 @@ interface SeriesDao {
LIMIT :limit
"""
)
- fun search(providerId: Long, query: String, limit: Int): Flow<List<SeriesEntity>>
+ fun search(providerId: Long, query: String, limit: Int): Flow<List<SeriesBrowseEntity>>
+
+ @Query(
+ """
+ SELECT s.* FROM series s
+ JOIN series_fts ON s.id = series_fts.rowid
+ WHERE s.provider_id = :providerId
+ AND s.category_id = :categoryId
+ AND series_fts MATCH :query
+ ORDER BY s.name ASC
+ LIMIT :limit
+ """
+ )
+ fun searchByCategory(providerId: Long, categoryId: Long, query: String, limit: Int): Flow<List<SeriesBrowseEntity>>
@Query("SELECT * FROM series WHERE id = :id")
suspend fun getById(id: Long): SeriesEntity?
+ @Query("SELECT * FROM series WHERE provider_id = :providerId")
+ suspend fun getByProviderSync(providerId: Long): List<SeriesEntity>
+
@Query("SELECT * FROM series WHERE id IN (:ids)")
- fun getByIds(ids: List<Long>): Flow<List<SeriesEntity>>
+ fun getByIds(ids: List<Long>): Flow<List<SeriesBrowseEntity>>
@Query("SELECT * FROM series WHERE provider_id = :providerId AND series_id = :seriesId LIMIT 1")
suspend fun getBySeriesId(providerId: Long, seriesId: Long): SeriesEntity?
@@ -429,6 +1077,9 @@ interface SeriesDao {
@Query("DELETE FROM series WHERE provider_id = :providerId AND category_id = :categoryId")
suspend fun deleteByProviderAndCategory(providerId: Long, categoryId: Long)
+ @Query("DELETE FROM series WHERE id IN (:ids)")
+ suspend fun deleteByIds(ids: List<Long>)
+
@Transaction
suspend fun replaceAll(providerId: Long, series: List<SeriesEntity>) {
val existingByRemoteId = getIdMappings(providerId).associate { it.remoteId to it.id }
@@ -472,12 +1123,13 @@ interface SeriesDao {
@Dao
+@RewriteQueriesToDropUnusedColumns
interface EpisodeDao {
@Query("SELECT * FROM episodes WHERE series_id = :seriesId ORDER BY season_number ASC, episode_number ASC")
- fun getBySeries(seriesId: Long): Flow<List<EpisodeEntity>>
+ fun getBySeries(seriesId: Long): Flow<List<EpisodeBrowseEntity>>
@Query("SELECT * FROM episodes WHERE series_id = :seriesId ORDER BY season_number ASC, episode_number ASC")
- suspend fun getBySeriesSync(seriesId: Long): List<EpisodeEntity>
+ suspend fun getBySeriesSync(seriesId: Long): List<EpisodeBrowseEntity>
@Query("SELECT * FROM episodes WHERE id = :id")
suspend fun getById(id: Long): EpisodeEntity?
@@ -611,12 +1263,18 @@ interface CategoryDao {
@Query("SELECT * FROM categories WHERE provider_id = :providerId AND type = :type ORDER BY id ASC")
fun getByProviderAndType(providerId: Long, type: String): Flow<List<CategoryEntity>>
+ @Query("SELECT * FROM categories WHERE provider_id = :providerId AND type = :type ORDER BY id ASC")
+ suspend fun getByProviderAndTypeSync(providerId: Long, type: String): List<CategoryEntity>
+
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertAll(categories: List<CategoryEntity>)
@Query("DELETE FROM categories WHERE provider_id = :providerId AND type = :type")
suspend fun deleteByProviderAndType(providerId: Long, type: String)
+ @Query("DELETE FROM categories WHERE id IN (:ids)")
+ suspend fun deleteByIds(ids: List<Long>)
+
@Transaction
suspend fun replaceAll(providerId: Long, type: String, categories: List<CategoryEntity>) {
deleteByProviderAndType(providerId, type)
@@ -628,13 +1286,57 @@ interface CategoryDao {
}
@Dao
+@RewriteQueriesToDropUnusedColumns
interface ProgramDao {
- @Query("SELECT * FROM programs WHERE provider_id = :providerId AND channel_id = :channelId AND end_time > :startTime AND start_time < :endTime ORDER BY start_time ASC")
- fun getForChannel(providerId: Long, channelId: String, startTime: Long, endTime: Long): Flow<List<ProgramEntity>>
+ @Query(
+ """
+ SELECT
+ id,
+ provider_id,
+ channel_id,
+ title,
+ CASE
+ WHEN LENGTH(description) > 600 THEN SUBSTR(description, 1, 600) || '...'
+ ELSE description
+ END AS description,
+ start_time,
+ end_time,
+ lang,
+ NULL AS rating,
+ NULL AS image_url,
+ NULL AS genre,
+ NULL AS category,
+ has_archive
+ FROM programs
+ WHERE provider_id = :providerId
+ AND channel_id = :channelId
+ AND end_time > :startTime
+ AND start_time < :endTime
+ ORDER BY start_time ASC
+ """
+ )
+ fun getForChannel(providerId: Long, channelId: String, startTime: Long, endTime: Long): Flow<List<ProgramBrowseEntity>>
@Query(
"""
- SELECT * FROM programs
+ SELECT
+ id,
+ provider_id,
+ channel_id,
+ title,
+ CASE
+ WHEN LENGTH(description) > 600 THEN SUBSTR(description, 1, 600) || '...'
+ ELSE description
+ END AS description,
+ start_time,
+ end_time,
+ lang,
+ NULL AS rating,
+ NULL AS image_url,
+ NULL AS genre,
+ NULL AS category,
+ has_archive
+ FROM programs
WHERE provider_id = :providerId
AND channel_id IN (:channelIds)
AND end_time > :startTime
@@ -642,11 +1344,27 @@ interface ProgramDao {
ORDER BY channel_id ASC, start_time ASC
"""
)
- fun getForChannels(providerId: Long, channelIds: List<String>, startTime: Long, endTime: Long): Flow<List<ProgramEntity>>
+ fun getForChannels(providerId: Long, channelIds: List<String>, startTime: Long, endTime: Long): Flow<List<ProgramBrowseEntity>>
@Query(
"""
- SELECT programs.*
+ SELECT
+ programs.id,
+ programs.provider_id,
+ programs.channel_id,
+ programs.title,
+ CASE
+ WHEN LENGTH(programs.description) > 600 THEN SUBSTR(programs.description, 1, 600) || '...'
+ ELSE programs.description
+ END AS description,
+ programs.start_time,
+ programs.end_time,
+ programs.lang,
+ NULL AS rating,
+ NULL AS image_url,
+ NULL AS genre,
+ NULL AS category,
+ programs.has_archive
FROM programs
INNER JOIN channels
ON channels.provider_id = programs.provider_id
@@ -661,11 +1379,27 @@ interface ProgramDao {
ORDER BY channels.number ASC, programs.channel_id ASC, programs.start_time ASC
"""
)
- fun getForCategory(providerId: Long, categoryId: Long, startTime: Long, endTime: Long): Flow<List<ProgramEntity>>
+ fun getForCategory(providerId: Long, categoryId: Long, startTime: Long, endTime: Long): Flow<List<ProgramBrowseEntity>>
@Query(
"""
- SELECT programs.*
+ SELECT
+ programs.id,
+ programs.provider_id,
+ programs.channel_id,
+ programs.title,
+ CASE
+ WHEN LENGTH(programs.description) > 600 THEN SUBSTR(programs.description, 1, 600) || '...'
+ ELSE programs.description
+ END AS description,
+ programs.start_time,
+ programs.end_time,
+ programs.lang,
+ NULL AS rating,
+ NULL AS image_url,
+ NULL AS genre,
+ NULL AS category,
+ programs.has_archive
FROM programs
WHERE programs.provider_id = :providerId
AND programs.end_time > :startTime
@@ -697,16 +1431,92 @@ interface ProgramDao {
endTime: Long,
categoryId: Long?,
limit: Int
- ): Flow<List<ProgramEntity>>
+ ): Flow<List<ProgramBrowseEntity>>
- @Query("SELECT * FROM programs WHERE provider_id = :providerId AND channel_id = :channelId AND start_time <= :now AND end_time > :now LIMIT 1")
- fun getNowPlaying(providerId: Long, channelId: String, now: Long = System.currentTimeMillis()): Flow<ProgramEntity?>
+ @Query(
+ """
+ SELECT
+ id,
+ provider_id,
+ channel_id,
+ title,
+ CASE
+ WHEN LENGTH(description) > 600 THEN SUBSTR(description, 1, 600) || '...'
+ ELSE description
+ END AS description,
+ start_time,
+ end_time,
+ lang,
+ NULL AS rating,
+ NULL AS image_url,
+ NULL AS genre,
+ NULL AS category,
+ has_archive
+ FROM programs
+ WHERE provider_id = :providerId
+ AND channel_id = :channelId
+ AND start_time <= :now
+ AND end_time > :now
+ LIMIT 1
+ """
+ )
+ fun getNowPlaying(providerId: Long, channelId: String, now: Long = System.currentTimeMillis()): Flow<ProgramBrowseEntity?>
- @Query("SELECT * FROM programs WHERE provider_id = :providerId AND channel_id IN (:channelIds) AND start_time <= :now AND end_time > :now")
- fun getNowPlayingForChannels(providerId: Long, channelIds: List<String>, now: Long = System.currentTimeMillis()): Flow<List<ProgramEntity>>
+ @Query(
+ """
+ SELECT
+ id,
+ provider_id,
+ channel_id,
+ title,
+ CASE
+ WHEN LENGTH(description) > 600 THEN SUBSTR(description, 1, 600) || '...'
+ ELSE description
+ END AS description,
+ start_time,
+ end_time,
+ lang,
+ NULL AS rating,
+ NULL AS image_url,
+ NULL AS genre,
+ NULL AS category,
+ has_archive
+ FROM programs
+ WHERE provider_id = :providerId
+ AND channel_id IN (:channelIds)
+ AND start_time <= :now
+ AND end_time > :now
+ """
+ )
+ fun getNowPlayingForChannels(providerId: Long, channelIds: List<String>, now: Long = System.currentTimeMillis()): Flow<List<ProgramBrowseEntity>>
- @Query("SELECT * FROM programs WHERE provider_id = :providerId AND channel_id IN (:channelIds) AND start_time <= :now AND end_time > :now")
- suspend fun getNowPlayingForChannelsSync(providerId: Long, channelIds: List<String>, now: Long = System.currentTimeMillis()): List<ProgramEntity>
+ @Query(
+ """
+ SELECT
+ id,
+ provider_id,
+ channel_id,
+ title,
+ CASE
+ WHEN LENGTH(description) > 600 THEN SUBSTR(description, 1, 600) || '...'
+ ELSE description
+ END AS description,
+ start_time,
+ end_time,
+ lang,
+ NULL AS rating,
+ NULL AS image_url,
+ NULL AS genre,
+ NULL AS category,
+ has_archive
+ FROM programs
+ WHERE provider_id = :providerId
+ AND channel_id IN (:channelIds)
+ AND start_time <= :now
+ AND end_time > :now
+ """
+ )
+ suspend fun getNowPlayingForChannelsSync(providerId: Long, channelIds: List<String>, now: Long = System.currentTimeMillis()): List<ProgramBrowseEntity>
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertAll(programs: List<ProgramEntity>)
@@ -794,15 +1604,16 @@ interface VirtualGroupDao {
}
@Dao
+@RewriteQueriesToDropUnusedColumns
interface PlaybackHistoryDao {
@Query("SELECT * FROM playback_history ORDER BY last_watched_at DESC LIMIT :limit")
- fun getRecentlyWatched(limit: Int = 100): Flow<List<PlaybackHistoryEntity>>
+ fun getRecentlyWatched(limit: Int = 100): Flow<List<PlaybackHistoryLiteEntity>>
@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<PlaybackHistoryEntity>>
+ fun getRecentlyWatchedByProvider(providerId: 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<PlaybackHistoryEntity>>
+ fun getByProvider(providerId: Long): Flow<List<PlaybackHistoryLiteEntity>>
@Query("SELECT * FROM playback_history ORDER BY last_watched_at DESC")
suspend fun getAllSync(): List<PlaybackHistoryEntity>
diff --git a/data/src/main/java/com/streamvault/data/local/entity/Entities.kt b/data/src/main/java/com/streamvault/data/local/entity/Entities.kt
index 76de65ee..163109fc 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
@@ -70,7 +70,29 @@ data class ChannelEntity(
@ColumnInfo(name = "is_user_protected") val isUserProtected: Boolean = false,
@ColumnInfo(name = "logical_group_id") val logicalGroupId: String = "",
@ColumnInfo(name = "error_count") val errorCount: Int = 0,
- @ColumnInfo(name = "quality_options_json") val qualityOptionsJson: String? = null
+ @ColumnInfo(name = "quality_options_json") val qualityOptionsJson: String? = null,
+ @ColumnInfo(name = "sync_fingerprint") val syncFingerprint: String = ""
+)
+
+data class ChannelBrowseEntity(
+ val id: Long = 0,
+ @ColumnInfo(name = "stream_id") val streamId: Long = 0,
+ val name: String,
+ @ColumnInfo(name = "logo_url") val logoUrl: String? = null,
+ @ColumnInfo(name = "group_title") val groupTitle: String? = null,
+ @ColumnInfo(name = "category_id") val categoryId: Long? = null,
+ @ColumnInfo(name = "category_name") val categoryName: String? = null,
+ @ColumnInfo(name = "stream_url") val streamUrl: String = "",
+ @ColumnInfo(name = "epg_channel_id") val epgChannelId: String? = null,
+ val number: Int = 0,
+ @ColumnInfo(name = "catch_up_supported") val catchUpSupported: Boolean = false,
+ @ColumnInfo(name = "catch_up_days") val catchUpDays: Int = 0,
+ val catchUpSource: String? = null,
+ @ColumnInfo(name = "provider_id") val providerId: Long = 0,
+ @ColumnInfo(name = "is_adult") val isAdult: Boolean = false,
+ @ColumnInfo(name = "is_user_protected") val isUserProtected: Boolean = false,
+ @ColumnInfo(name = "logical_group_id") val logicalGroupId: String = "",
+ @ColumnInfo(name = "error_count") val errorCount: Int = 0
)
@Entity(
@@ -131,6 +153,28 @@ data class MovieEntity(
@ColumnInfo(name = "watch_progress") val watchProgress: Long = 0L,
@ColumnInfo(name = "last_watched_at") val lastWatchedAt: Long = 0L,
@ColumnInfo(name = "is_adult") val isAdult: Boolean = false,
+ @ColumnInfo(name = "is_user_protected") val isUserProtected: Boolean = false,
+ @ColumnInfo(name = "sync_fingerprint") val syncFingerprint: String = ""
+)
+
+data class MovieBrowseEntity(
+ val id: Long = 0,
+ @ColumnInfo(name = "stream_id") val streamId: Long = 0,
+ val name: String,
+ @ColumnInfo(name = "poster_url") val posterUrl: String? = null,
+ @ColumnInfo(name = "category_id") val categoryId: Long? = null,
+ @ColumnInfo(name = "category_name") val categoryName: String? = null,
+ @ColumnInfo(name = "stream_url") val streamUrl: String = "",
+ @ColumnInfo(name = "container_extension") val containerExtension: String? = null,
+ val genre: String? = null,
+ @ColumnInfo(name = "release_date") val releaseDate: String? = null,
+ @ColumnInfo(name = "duration_seconds") val durationSeconds: Int = 0,
+ val rating: Float = 0f,
+ val year: String? = null,
+ @ColumnInfo(name = "provider_id") val providerId: Long = 0,
+ @ColumnInfo(name = "watch_progress") val watchProgress: Long = 0L,
+ @ColumnInfo(name = "last_watched_at") val lastWatchedAt: Long = 0L,
+ @ColumnInfo(name = "is_adult") val isAdult: Boolean = false,
@ColumnInfo(name = "is_user_protected") val isUserProtected: Boolean = false
)
@@ -169,6 +213,23 @@ data class SeriesEntity(
@ColumnInfo(name = "last_modified") val lastModified: Long = 0L,
@ColumnInfo(name = "provider_id") val providerId: Long = 0,
@ColumnInfo(name = "is_adult") val isAdult: Boolean = false,
+ @ColumnInfo(name = "is_user_protected") val isUserProtected: Boolean = false,
+ @ColumnInfo(name = "sync_fingerprint") val syncFingerprint: String = ""
+)
+
+data class SeriesBrowseEntity(
+ val id: Long = 0,
+ @ColumnInfo(name = "series_id") val seriesId: Long = 0,
+ val name: String,
+ @ColumnInfo(name = "poster_url") val posterUrl: String? = null,
+ @ColumnInfo(name = "category_id") val categoryId: Long? = null,
+ @ColumnInfo(name = "category_name") val categoryName: String? = null,
+ val genre: String? = null,
+ @ColumnInfo(name = "release_date") val releaseDate: String? = null,
+ val rating: Float = 0f,
+ @ColumnInfo(name = "last_modified") val lastModified: Long = 0L,
+ @ColumnInfo(name = "provider_id") val providerId: Long = 0,
+ @ColumnInfo(name = "is_adult") val isAdult: Boolean = false,
@ColumnInfo(name = "is_user_protected") val isUserProtected: Boolean = false
)
@@ -235,6 +296,28 @@ data class EpisodeEntity(
@ColumnInfo(name = "is_user_protected") val isUserProtected: Boolean = false
)
+data class EpisodeBrowseEntity(
+ val id: Long = 0,
+ @ColumnInfo(name = "episode_id") val episodeId: Long = 0,
+ val title: String,
+ @ColumnInfo(name = "episode_number") val episodeNumber: Int,
+ @ColumnInfo(name = "season_number") val seasonNumber: Int,
+ @ColumnInfo(name = "stream_url") val streamUrl: String = "",
+ @ColumnInfo(name = "container_extension") val containerExtension: String? = null,
+ @ColumnInfo(name = "cover_url") val coverUrl: String? = null,
+ val plot: String? = null,
+ val duration: String? = null,
+ @ColumnInfo(name = "duration_seconds") val durationSeconds: Int = 0,
+ val rating: Float = 0f,
+ @ColumnInfo(name = "release_date") val releaseDate: String? = null,
+ @ColumnInfo(name = "series_id") val seriesId: Long = 0,
+ @ColumnInfo(name = "provider_id") val providerId: Long = 0,
+ @ColumnInfo(name = "watch_progress") val watchProgress: Long = 0L,
+ @ColumnInfo(name = "last_watched_at") val lastWatchedAt: Long = 0L,
+ @ColumnInfo(name = "is_adult") val isAdult: Boolean = false,
+ @ColumnInfo(name = "is_user_protected") val isUserProtected: Boolean = false
+)
+
@Entity(
tableName = "categories",
foreignKeys = [ForeignKey(
@@ -258,7 +341,146 @@ data class CategoryEntity(
val type: ContentType = ContentType.LIVE,
@ColumnInfo(name = "provider_id") val providerId: Long = 0,
@ColumnInfo(name = "is_adult") val isAdult: Boolean = false,
- @ColumnInfo(name = "is_user_protected") val isUserProtected: Boolean = false
+ @ColumnInfo(name = "is_user_protected") val isUserProtected: Boolean = false,
+ @ColumnInfo(name = "sync_fingerprint") val syncFingerprint: String = ""
+)
+
+@Entity(
+ tableName = "channel_import_stage",
+ primaryKeys = ["session_id", "provider_id", "stream_id"],
+ foreignKeys = [ForeignKey(
+ entity = ProviderEntity::class,
+ parentColumns = ["id"],
+ childColumns = ["provider_id"],
+ onDelete = ForeignKey.CASCADE
+ )],
+ indices = [
+ Index(value = ["provider_id"]),
+ Index(value = ["session_id", "provider_id"])
+ ]
+)
+data class ChannelImportStageEntity(
+ @ColumnInfo(name = "session_id") val sessionId: Long,
+ @ColumnInfo(name = "provider_id") val providerId: Long,
+ @ColumnInfo(name = "stream_id") val streamId: Long,
+ val name: String,
+ @ColumnInfo(name = "logo_url") val logoUrl: String? = null,
+ @ColumnInfo(name = "group_title") val groupTitle: String? = null,
+ @ColumnInfo(name = "category_id") val categoryId: Long? = null,
+ @ColumnInfo(name = "category_name") val categoryName: String? = null,
+ @ColumnInfo(name = "stream_url") val streamUrl: String = "",
+ @ColumnInfo(name = "epg_channel_id") val epgChannelId: String? = null,
+ val number: Int = 0,
+ @ColumnInfo(name = "catch_up_supported") val catchUpSupported: Boolean = false,
+ @ColumnInfo(name = "catch_up_days") val catchUpDays: Int = 0,
+ val catchUpSource: String? = null,
+ @ColumnInfo(name = "is_adult") val isAdult: Boolean = false,
+ @ColumnInfo(name = "logical_group_id") val logicalGroupId: String = "",
+ @ColumnInfo(name = "error_count") val errorCount: Int = 0,
+ @ColumnInfo(name = "sync_fingerprint") val syncFingerprint: String = ""
+)
+
+@Entity(
+ tableName = "movie_import_stage",
+ primaryKeys = ["session_id", "provider_id", "stream_id"],
+ foreignKeys = [ForeignKey(
+ entity = ProviderEntity::class,
+ parentColumns = ["id"],
+ childColumns = ["provider_id"],
+ onDelete = ForeignKey.CASCADE
+ )],
+ indices = [
+ Index(value = ["provider_id"]),
+ Index(value = ["session_id", "provider_id"])
+ ]
+)
+data class MovieImportStageEntity(
+ @ColumnInfo(name = "session_id") val sessionId: Long,
+ @ColumnInfo(name = "provider_id") val providerId: Long,
+ @ColumnInfo(name = "stream_id") val streamId: Long,
+ val name: String,
+ @ColumnInfo(name = "poster_url") val posterUrl: String? = null,
+ @ColumnInfo(name = "backdrop_url") val backdropUrl: String? = null,
+ @ColumnInfo(name = "category_id") val categoryId: Long? = null,
+ @ColumnInfo(name = "category_name") val categoryName: String? = null,
+ @ColumnInfo(name = "stream_url") val streamUrl: String = "",
+ @ColumnInfo(name = "container_extension") val containerExtension: String? = null,
+ val plot: String? = null,
+ val cast: String? = null,
+ val director: String? = null,
+ val genre: String? = null,
+ @ColumnInfo(name = "release_date") val releaseDate: String? = null,
+ val duration: String? = null,
+ @ColumnInfo(name = "duration_seconds") val durationSeconds: Int = 0,
+ val rating: Float = 0f,
+ val year: String? = null,
+ @ColumnInfo(name = "tmdb_id") val tmdbId: Long? = null,
+ @ColumnInfo(name = "youtube_trailer") val youtubeTrailer: String? = null,
+ @ColumnInfo(name = "is_adult") val isAdult: Boolean = false,
+ @ColumnInfo(name = "sync_fingerprint") val syncFingerprint: String = ""
+)
+
+@Entity(
+ tableName = "series_import_stage",
+ primaryKeys = ["session_id", "provider_id", "series_id"],
+ foreignKeys = [ForeignKey(
+ entity = ProviderEntity::class,
+ parentColumns = ["id"],
+ childColumns = ["provider_id"],
+ onDelete = ForeignKey.CASCADE
+ )],
+ indices = [
+ Index(value = ["provider_id"]),
+ Index(value = ["session_id", "provider_id"])
+ ]
+)
+data class SeriesImportStageEntity(
+ @ColumnInfo(name = "session_id") val sessionId: Long,
+ @ColumnInfo(name = "provider_id") val providerId: Long,
+ @ColumnInfo(name = "series_id") val seriesId: Long,
+ val name: String,
+ @ColumnInfo(name = "poster_url") val posterUrl: String? = null,
+ @ColumnInfo(name = "backdrop_url") val backdropUrl: String? = null,
+ @ColumnInfo(name = "category_id") val categoryId: Long? = null,
+ @ColumnInfo(name = "category_name") val categoryName: String? = null,
+ val plot: String? = null,
+ val cast: String? = null,
+ val director: String? = null,
+ val genre: String? = null,
+ @ColumnInfo(name = "release_date") val releaseDate: String? = null,
+ val rating: Float = 0f,
+ @ColumnInfo(name = "tmdb_id") val tmdbId: Long? = null,
+ @ColumnInfo(name = "youtube_trailer") val youtubeTrailer: String? = null,
+ @ColumnInfo(name = "episode_run_time") val episodeRunTime: String? = null,
+ @ColumnInfo(name = "last_modified") val lastModified: Long = 0L,
+ @ColumnInfo(name = "is_adult") val isAdult: Boolean = false,
+ @ColumnInfo(name = "sync_fingerprint") val syncFingerprint: String = ""
+)
+
+@Entity(
+ tableName = "category_import_stage",
+ primaryKeys = ["session_id", "provider_id", "category_id", "type"],
+ foreignKeys = [ForeignKey(
+ entity = ProviderEntity::class,
+ parentColumns = ["id"],
+ childColumns = ["provider_id"],
+ onDelete = ForeignKey.CASCADE
+ )],
+ indices = [
+ Index(value = ["provider_id"]),
+ Index(value = ["session_id", "provider_id"]),
+ Index(value = ["provider_id", "type"])
+ ]
+)
+data class CategoryImportStageEntity(
+ @ColumnInfo(name = "session_id") val sessionId: Long,
+ @ColumnInfo(name = "provider_id") val providerId: Long,
+ @ColumnInfo(name = "category_id") val categoryId: Long,
+ val name: String,
+ @ColumnInfo(name = "parent_id") val parentId: Long? = null,
+ val type: ContentType = ContentType.LIVE,
+ @ColumnInfo(name = "is_adult") val isAdult: Boolean = false,
+ @ColumnInfo(name = "sync_fingerprint") val syncFingerprint: String = ""
)
@Entity(
@@ -289,6 +511,22 @@ data class ProgramEntity(
@ColumnInfo(name = "has_archive") val hasArchive: Boolean = false
)
+data class ProgramBrowseEntity(
+ val id: Long = 0,
+ @ColumnInfo(name = "provider_id") val providerId: Long = 0,
+ @ColumnInfo(name = "channel_id") val channelId: String,
+ val title: String,
+ val description: String = "",
+ @ColumnInfo(name = "start_time") val startTime: Long = 0,
+ @ColumnInfo(name = "end_time") val endTime: Long = 0,
+ val lang: String = "",
+ val rating: String? = null,
+ @ColumnInfo(name = "image_url") val imageUrl: String? = null,
+ val genre: String? = null,
+ val category: String? = null,
+ @ColumnInfo(name = "has_archive") val hasArchive: Boolean = false
+)
+
@Entity(
tableName = "favorites",
foreignKeys = [ForeignKey(
@@ -368,6 +606,24 @@ data class PlaybackHistoryEntity(
@ColumnInfo(name = "episode_number") val episodeNumber: Int? = null
)
+data class PlaybackHistoryLiteEntity(
+ val id: Long = 0,
+ @ColumnInfo(name = "content_id") val contentId: Long,
+ @ColumnInfo(name = "content_type") val contentType: ContentType,
+ @ColumnInfo(name = "provider_id") val providerId: Long,
+ val title: String = "",
+ @ColumnInfo(name = "poster_url") val posterUrl: String? = null,
+ @ColumnInfo(name = "stream_url") val streamUrl: String = "",
+ @ColumnInfo(name = "resume_position_ms") val resumePositionMs: Long = 0,
+ @ColumnInfo(name = "total_duration_ms") val totalDurationMs: Long = 0,
+ @ColumnInfo(name = "last_watched_at") val lastWatchedAt: Long = 0,
+ @ColumnInfo(name = "watch_count") val watchCount: Int = 1,
+ @ColumnInfo(name = "watched_status") val watchedStatus: String = "IN_PROGRESS",
+ @ColumnInfo(name = "series_id") val seriesId: Long? = null,
+ @ColumnInfo(name = "season_number") val seasonNumber: Int? = null,
+ @ColumnInfo(name = "episode_number") val episodeNumber: Int? = null
+)
+
@Entity(
tableName = "sync_metadata",
foreignKeys = [ForeignKey(
@@ -395,6 +651,13 @@ data class SyncMetadataEntity(
@ColumnInfo(name = "movie_sync_mode") val movieSyncMode: String = "UNKNOWN",
@ColumnInfo(name = "movie_warnings_count") val movieWarningsCount: Int = 0,
@ColumnInfo(name = "movie_catalog_stale") val movieCatalogStale: Boolean = false,
+ @ColumnInfo(name = "live_avoid_full_until") val liveAvoidFullUntil: Long = 0,
+ @ColumnInfo(name = "movie_avoid_full_until") val movieAvoidFullUntil: Long = 0,
+ @ColumnInfo(name = "series_avoid_full_until") val seriesAvoidFullUntil: Long = 0,
+ @ColumnInfo(name = "live_sequential_failures_remembered") val liveSequentialFailuresRemembered: Boolean = false,
+ @ColumnInfo(name = "live_healthy_sync_streak") val liveHealthySyncStreak: Int = 0,
@ColumnInfo(name = "movie_parallel_failures_remembered") val movieParallelFailuresRemembered: Boolean = false,
- @ColumnInfo(name = "movie_healthy_sync_streak") val movieHealthySyncStreak: Int = 0
+ @ColumnInfo(name = "movie_healthy_sync_streak") val movieHealthySyncStreak: Int = 0,
+ @ColumnInfo(name = "series_sequential_failures_remembered") val seriesSequentialFailuresRemembered: Boolean = false,
+ @ColumnInfo(name = "series_healthy_sync_streak") val seriesHealthySyncStreak: Int = 0
)
diff --git a/data/src/main/java/com/streamvault/data/manager/RecordingManagerImpl.kt b/data/src/main/java/com/streamvault/data/manager/RecordingManagerImpl.kt
index 6aad317a..ec282c00 100644
--- a/data/src/main/java/com/streamvault/data/manager/RecordingManagerImpl.kt
+++ b/data/src/main/java/com/streamvault/data/manager/RecordingManagerImpl.kt
@@ -338,7 +338,9 @@ class RecordingManagerImpl @Inject constructor(
if (!stateFile.exists()) return emptyList()
return runCatching {
val listType = object : TypeToken<List<RecordingItem>>() {}.type
- gson.fromJson<List<RecordingItem>>(FileInputStream(stateFile).bufferedReader(), listType).orEmpty()
+ FileInputStream(stateFile).bufferedReader().use { reader ->
+ gson.fromJson<List<RecordingItem>>(reader, listType).orEmpty()
+ }
}.getOrDefault(emptyList())
}
diff --git a/data/src/main/java/com/streamvault/data/mapper/EntityMappers.kt b/data/src/main/java/com/streamvault/data/mapper/EntityMappers.kt
index 2aad7393..9221f78b 100644
--- a/data/src/main/java/com/streamvault/data/mapper/EntityMappers.kt
+++ b/data/src/main/java/com/streamvault/data/mapper/EntityMappers.kt
@@ -129,6 +129,34 @@ fun MovieEntity.toDomain() = Movie(
streamId = streamId
)
+fun MovieBrowseEntity.toDomain() = Movie(
+ id = id,
+ name = name,
+ posterUrl = posterUrl,
+ backdropUrl = null,
+ categoryId = categoryId,
+ categoryName = categoryName,
+ streamUrl = streamUrl,
+ containerExtension = containerExtension,
+ plot = null,
+ cast = null,
+ director = null,
+ genre = genre,
+ releaseDate = releaseDate,
+ duration = null,
+ durationSeconds = durationSeconds,
+ rating = rating,
+ year = year,
+ tmdbId = null,
+ youtubeTrailer = null,
+ providerId = providerId,
+ watchProgress = watchProgress,
+ lastWatchedAt = lastWatchedAt,
+ isAdult = isAdult,
+ isUserProtected = isUserProtected,
+ streamId = streamId
+)
+
fun Movie.toEntity() = MovieEntity(
id = id,
streamId = streamId.takeIf { it > 0 } ?: id,
@@ -182,6 +210,29 @@ fun SeriesEntity.toDomain() = Series(
seriesId = seriesId
)
+fun SeriesBrowseEntity.toDomain() = Series(
+ id = id,
+ name = name,
+ posterUrl = posterUrl,
+ backdropUrl = null,
+ categoryId = categoryId,
+ categoryName = categoryName,
+ plot = null,
+ cast = null,
+ director = null,
+ genre = genre,
+ releaseDate = releaseDate,
+ rating = rating,
+ tmdbId = null,
+ youtubeTrailer = null,
+ episodeRunTime = null,
+ lastModified = lastModified,
+ providerId = providerId,
+ isAdult = isAdult,
+ isUserProtected = isUserProtected,
+ seriesId = seriesId
+)
+
fun Series.toEntity() = SeriesEntity(
id = id,
seriesId = seriesId.takeIf { it > 0 } ?: id,
@@ -229,6 +280,28 @@ fun EpisodeEntity.toDomain() = Episode(
episodeId = episodeId
)
+fun EpisodeBrowseEntity.toDomain() = Episode(
+ id = id,
+ title = title,
+ episodeNumber = episodeNumber,
+ seasonNumber = seasonNumber,
+ streamUrl = streamUrl,
+ containerExtension = containerExtension,
+ coverUrl = coverUrl,
+ plot = plot,
+ duration = duration,
+ durationSeconds = durationSeconds,
+ rating = rating,
+ releaseDate = releaseDate,
+ seriesId = seriesId,
+ providerId = providerId,
+ watchProgress = watchProgress,
+ lastWatchedAt = lastWatchedAt,
+ isAdult = isAdult,
+ isUserProtected = isUserProtected,
+ episodeId = episodeId
+)
+
fun Episode.toEntity() = EpisodeEntity(
id = id,
episodeId = episodeId.takeIf { it > 0 } ?: id,
@@ -291,6 +364,22 @@ fun ProgramEntity.toDomain() = Program(
providerId = providerId
)
+fun ProgramBrowseEntity.toDomain() = Program(
+ id = id,
+ channelId = channelId,
+ title = title,
+ description = description,
+ startTime = startTime,
+ endTime = endTime,
+ lang = lang,
+ rating = rating,
+ imageUrl = imageUrl,
+ genre = genre,
+ category = category,
+ hasArchive = hasArchive,
+ providerId = providerId
+)
+
fun Program.toEntity() = ProgramEntity(
id = 0,
channelId = channelId,
@@ -367,6 +456,24 @@ fun PlaybackHistoryEntity.toDomain() = PlaybackHistory(
episodeNumber = episodeNumber
)
+fun PlaybackHistoryLiteEntity.toDomain() = PlaybackHistory(
+ id = id,
+ contentId = contentId,
+ contentType = contentType,
+ providerId = providerId,
+ title = title,
+ posterUrl = posterUrl,
+ streamUrl = streamUrl,
+ resumePositionMs = resumePositionMs,
+ totalDurationMs = totalDurationMs,
+ lastWatchedAt = lastWatchedAt,
+ watchCount = watchCount,
+ watchedStatus = watchedStatus.toPlaybackWatchedStatus(),
+ seriesId = seriesId,
+ seasonNumber = seasonNumber,
+ episodeNumber = episodeNumber
+)
+
fun PlaybackHistory.toEntity() = PlaybackHistoryEntity(
id = id,
contentId = contentId,
@@ -405,8 +512,15 @@ fun SyncMetadataEntity.toDomain() = SyncMetadata(
.getOrDefault(com.streamvault.domain.model.VodSyncMode.UNKNOWN),
movieWarningsCount = movieWarningsCount,
movieCatalogStale = movieCatalogStale,
+ liveAvoidFullUntil = liveAvoidFullUntil,
+ movieAvoidFullUntil = movieAvoidFullUntil,
+ seriesAvoidFullUntil = seriesAvoidFullUntil,
+ liveSequentialFailuresRemembered = liveSequentialFailuresRemembered,
+ liveHealthySyncStreak = liveHealthySyncStreak,
movieParallelFailuresRemembered = movieParallelFailuresRemembered,
- movieHealthySyncStreak = movieHealthySyncStreak
+ movieHealthySyncStreak = movieHealthySyncStreak,
+ seriesSequentialFailuresRemembered = seriesSequentialFailuresRemembered,
+ seriesHealthySyncStreak = seriesHealthySyncStreak
)
fun SyncMetadata.toEntity() = SyncMetadataEntity(
@@ -426,8 +540,15 @@ fun SyncMetadata.toEntity() = SyncMetadataEntity(
movieSyncMode = movieSyncMode.name,
movieWarningsCount = movieWarningsCount,
movieCatalogStale = movieCatalogStale,
+ liveAvoidFullUntil = liveAvoidFullUntil,
+ movieAvoidFullUntil = movieAvoidFullUntil,
+ seriesAvoidFullUntil = seriesAvoidFullUntil,
+ liveSequentialFailuresRemembered = liveSequentialFailuresRemembered,
+ liveHealthySyncStreak = liveHealthySyncStreak,
movieParallelFailuresRemembered = movieParallelFailuresRemembered,
- movieHealthySyncStreak = movieHealthySyncStreak
+ movieHealthySyncStreak = movieHealthySyncStreak,
+ seriesSequentialFailuresRemembered = seriesSequentialFailuresRemembered,
+ seriesHealthySyncStreak = seriesHealthySyncStreak
)
private fun encodeQualityOptions(options: List<ChannelQualityOption>): String? {
diff --git a/data/src/main/java/com/streamvault/data/parser/M3uParser.kt b/data/src/main/java/com/streamvault/data/parser/M3uParser.kt
index e470bede..800250a1 100644
--- a/data/src/main/java/com/streamvault/data/parser/M3uParser.kt
+++ b/data/src/main/java/com/streamvault/data/parser/M3uParser.kt
@@ -369,19 +369,6 @@ class M3uParser {
return attributes
}
- internal fun isVodEntry(entry: M3uEntry): Boolean {
- val url = entry.url.lowercase()
- val group = entry.groupTitle.lowercase()
-
- return url.endsWith(".mp4") ||
- url.endsWith(".mkv") ||
- url.endsWith(".avi") ||
- url.contains("/movie/") ||
- group.contains("movie") ||
- group.contains("vod") ||
- group.contains("film")
- }
-
private fun isAllowedStreamUrl(url: String): Boolean {
val trimmed = url.trim()
if (trimmed.length > 8192) return false
@@ -393,7 +380,18 @@ class M3uParser {
companion object {
/** Exposed for callers outside M3uParser (e.g. SyncManager) to avoid duplicate logic. */
- fun isVodEntry(entry: M3uEntry): Boolean = M3uParser().isVodEntry(entry)
+ fun isVodEntry(entry: M3uEntry): Boolean {
+ val url = entry.url.lowercase()
+ val group = entry.groupTitle.lowercase()
+
+ return url.endsWith(".mp4") ||
+ url.endsWith(".mkv") ||
+ url.endsWith(".avi") ||
+ url.contains("/movie/") ||
+ group.contains("movie") ||
+ group.contains("vod") ||
+ group.contains("film")
+ }
val knownAttributes = setOf(
"tvg-id",
diff --git a/data/src/main/java/com/streamvault/data/remote/dto/LenientJsonSerializers.kt b/data/src/main/java/com/streamvault/data/remote/dto/LenientJsonSerializers.kt
index 9fcf21a1..fe6206ec 100644
--- a/data/src/main/java/com/streamvault/data/remote/dto/LenientJsonSerializers.kt
+++ b/data/src/main/java/com/streamvault/data/remote/dto/LenientJsonSerializers.kt
@@ -3,17 +3,27 @@ package com.streamvault.data.remote.dto
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.KSerializer
import kotlinx.serialization.SerializationException
+import kotlinx.serialization.builtins.ListSerializer
+import kotlinx.serialization.builtins.MapSerializer
+import kotlinx.serialization.builtins.serializer
import kotlinx.serialization.descriptors.PrimitiveKind
import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor
import kotlinx.serialization.descriptors.SerialDescriptor
+import kotlinx.serialization.descriptors.buildClassSerialDescriptor
+import kotlinx.serialization.descriptors.element
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonDecoder
import kotlinx.serialization.json.JsonElement
+import kotlinx.serialization.json.JsonEncoder
import kotlinx.serialization.json.JsonNull
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
+import kotlinx.serialization.json.buildJsonObject
+import kotlinx.serialization.json.decodeFromJsonElement
+import kotlinx.serialization.json.encodeToJsonElement
+import kotlinx.serialization.json.put
@OptIn(ExperimentalSerializationApi::class)
object LenientIntSerializer : KSerializer<Int> {
@@ -142,6 +152,58 @@ object LenientNullableStringListSerializer : KSerializer<List<String>?> {
}
}
+object XtreamSeriesInfoResponseSerializer : KSerializer<XtreamSeriesInfoResponse> {
+ override val descriptor: SerialDescriptor = buildClassSerialDescriptor("XtreamSeriesInfoResponse") {
+ element<XtreamSeriesItem?>("info", isOptional = true)
+ element<Map<String, List<XtreamEpisode>>>("episodes", isOptional = true)
+ element<List<XtreamSeason>>("seasons", isOptional = true)
+ }
+
+ override fun deserialize(decoder: Decoder): XtreamSeriesInfoResponse {
+ val jsonDecoder = decoder as? JsonDecoder
+ ?: throw SerializationException("XtreamSeriesInfoResponseSerializer only supports JSON")
+ val element = jsonDecoder.decodeJsonElement()
+ val obj = element as? JsonObject ?: return XtreamSeriesInfoResponse()
+ val json = jsonDecoder.json
+ val info = obj["info"].decodeSeriesItemOrNull(json)
+ ?: obj.takeIf { it.looksLikeSeriesInfoObject() }?.decodeSeriesItemOrNull(json)
+
+ return XtreamSeriesInfoResponse(
+ info = info,
+ episodes = obj["episodes"].decodeEpisodeMap(json),
+ seasons = obj["seasons"].decodeSeasonList(json)
+ )
+ }
+
+ override fun serialize(encoder: Encoder, value: XtreamSeriesInfoResponse) {
+ val jsonEncoder = encoder as? JsonEncoder
+ ?: throw SerializationException("XtreamSeriesInfoResponseSerializer only supports JSON")
+ jsonEncoder.encodeJsonElement(
+ buildJsonObject {
+ value.info?.let { put("info", jsonEncoder.json.encodeToJsonElement(XtreamSeriesItem.serializer(), it)) }
+ if (value.episodes.isNotEmpty()) {
+ put(
+ "episodes",
+ jsonEncoder.json.encodeToJsonElement(
+ MapSerializer(String.serializer(), ListSerializer(XtreamEpisode.serializer())),
+ value.episodes
+ )
+ )
+ }
+ if (value.seasons.isNotEmpty()) {
+ put(
+ "seasons",
+ jsonEncoder.json.encodeToJsonElement(
+ ListSerializer(XtreamSeason.serializer()),
+ value.seasons
+ )
+ )
+ }
+ }
+ )
+ }
+}
+
private fun decodePrimitive(decoder: Decoder): String? {
return when (decoder) {
is JsonDecoder -> decoder.decodeJsonElement().primitiveContentOrNull()
@@ -189,3 +251,114 @@ private fun String.toLenientStringList(): List<String> {
private fun List<String>.normalizeStringList(): List<String> =
map { it.trim().trim('"', '\'') }
.filter { it.isNotEmpty() && !it.equals("null", ignoreCase = true) }
+
+private fun JsonElement?.decodeSeriesItemOrNull(json: kotlinx.serialization.json.Json): XtreamSeriesItem? {
+ val element = this ?: return null
+ return runCatching { json.decodeFromJsonElement<XtreamSeriesItem>(element) }
+ .getOrNull()
+ ?.takeIf { item ->
+ item.seriesId > 0L ||
+ item.name.isNotBlank() ||
+ !item.cover.isNullOrBlank() ||
+ !item.coverBig.isNullOrBlank() ||
+ !item.movieImage.isNullOrBlank() ||
+ !item.plot.isNullOrBlank() ||
+ !item.description.isNullOrBlank() ||
+ !item.categoryId.isNullOrBlank() ||
+ item.backdropPath.orEmpty().isNotEmpty()
+ }
+}
+
+private fun JsonElement?.decodeEpisodeMap(json: kotlinx.serialization.json.Json): Map<String, List<XtreamEpisode>> {
+ val element = this ?: return emptyMap()
+ return when (element) {
+ JsonNull -> emptyMap()
+ is JsonArray -> element.decodeEpisodeList(json)
+ .groupBySeasonKey()
+ is JsonObject -> {
+ if (element.looksLikeEpisodeObject()) {
+ element.decodeEpisodeList(json).groupBySeasonKey()
+ } else {
+ buildMap {
+ element.forEach { (key, value) ->
+ val episodes = value.decodeEpisodeList(json)
+ if (episodes.isNotEmpty()) {
+ put(key, episodes)
+ }
+ }
+ }.takeIf { it.isNotEmpty() }
+ ?: element.values.flatMap { value -> value.decodeEpisodeList(json) }.groupBySeasonKey()
+ }
+ }
+ else -> emptyMap()
+ }
+}
+
+private fun JsonElement?.decodeEpisodeList(json: kotlinx.serialization.json.Json): List<XtreamEpisode> {
+ val element = this ?: return emptyList()
+ return when (element) {
+ JsonNull -> emptyList()
+ is JsonArray -> element.mapNotNull { value -> value.decodeEpisodeOrNull(json) }
+ is JsonObject -> when {
+ element.looksLikeEpisodeObject() -> listOfNotNull(element.decodeEpisodeOrNull(json))
+ "episodes" in element -> element["episodes"].decodeEpisodeList(json)
+ else -> element.values.flatMap { value -> value.decodeEpisodeList(json) }
+ }
+ else -> emptyList()
+ }
+}
+
+private fun JsonElement.decodeEpisodeOrNull(json: kotlinx.serialization.json.Json): XtreamEpisode? =
+ runCatching { json.decodeFromJsonElement<XtreamEpisode>(this) }.getOrNull()
+
+private fun JsonElement?.decodeSeasonList(json: kotlinx.serialization.json.Json): List<XtreamSeason> {
+ val element = this ?: return emptyList()
+ return when (element) {
+ JsonNull -> emptyList()
+ is JsonArray -> element.mapNotNull { value -> value.decodeSeasonOrNull(json) }
+ is JsonObject -> {
+ if (element.looksLikeSeasonObject()) {
+ listOfNotNull(element.decodeSeasonOrNull(json))
+ } else {
+ element.values.mapNotNull { value -> value.decodeSeasonOrNull(json) }
+ }
+ }
+ else -> emptyList()
+ }
+}
+
+private fun JsonElement.decodeSeasonOrNull(json: kotlinx.serialization.json.Json): XtreamSeason? =
+ runCatching { json.decodeFromJsonElement<XtreamSeason>(this) }.getOrNull()
+
+private fun List<XtreamEpisode>.groupBySeasonKey(): Map<String, List<XtreamEpisode>> =
+ if (isEmpty()) {
+ emptyMap()
+ } else {
+ groupBy { episode -> episode.season.takeIf { it > 0 }?.toString() ?: "0" }
+ .toSortedMap(compareBy(String::toIntOrNull, { it }))
+ }
+
+private fun JsonObject.looksLikeSeriesInfoObject(): Boolean =
+ containsKey("series_id") ||
+ containsKey("name") ||
+ containsKey("cover") ||
+ containsKey("cover_big") ||
+ containsKey("movie_image") ||
+ containsKey("plot") ||
+ containsKey("description") ||
+ containsKey("backdrop_path") ||
+ containsKey("tmdb") ||
+ containsKey("tmdb_id")
+
+private fun JsonObject.looksLikeEpisodeObject(): Boolean =
+ containsKey("episode_num") ||
+ containsKey("season") ||
+ containsKey("container_extension") ||
+ containsKey("title") ||
+ containsKey("info")
+
+private fun JsonObject.looksLikeSeasonObject(): Boolean =
+ containsKey("season_number") ||
+ containsKey("episode_count") ||
+ containsKey("air_date") ||
+ containsKey("cover")
diff --git a/data/src/main/java/com/streamvault/data/remote/dto/XtreamDtos.kt b/data/src/main/java/com/streamvault/data/remote/dto/XtreamDtos.kt
index fea8f5f2..417aa054 100644
--- a/data/src/main/java/com/streamvault/data/remote/dto/XtreamDtos.kt
+++ b/data/src/main/java/com/streamvault/data/remote/dto/XtreamDtos.kt
@@ -77,28 +77,33 @@ data class XtreamSeriesItem(
@SerialName("name") @Serializable(with = LenientStringSerializer::class) val name: String = "",
@SerialName("cover") @Serializable(with = LenientNullableStringSerializer::class) val cover: String? = null,
@SerialName("cover_big") @Serializable(with = LenientNullableStringSerializer::class) val coverBig: String? = null,
+ @SerialName("movie_image") @Serializable(with = LenientNullableStringSerializer::class) val movieImage: String? = null,
@SerialName("plot") @Serializable(with = LenientNullableStringSerializer::class) val plot: String? = null,
+ @SerialName("description") @Serializable(with = LenientNullableStringSerializer::class) val description: String? = null,
@SerialName("cast") @Serializable(with = LenientNullableStringSerializer::class) val cast: String? = null,
@SerialName("director") @Serializable(with = LenientNullableStringSerializer::class) val director: String? = null,
@SerialName("genre") @Serializable(with = LenientNullableStringSerializer::class) val genre: String? = null,
@SerialName("releaseDate") @Serializable(with = LenientNullableStringSerializer::class) val releaseDate: String? = null,
+ @SerialName("releasedate") @Serializable(with = LenientNullableStringSerializer::class) val releaseDateAlt: String? = null,
@SerialName("rating") @Serializable(with = LenientNullableStringSerializer::class) val rating: String? = null,
@SerialName("rating_5based") @Serializable(with = LenientNullableStringSerializer::class) val rating5based: String? = null,
@SerialName("backdrop_path") @Serializable(with = LenientNullableStringListSerializer::class) val backdropPath: List<String>? = null,
@SerialName("youtube_trailer") @Serializable(with = LenientNullableStringSerializer::class) val youtubeTrailer: String? = null,
@SerialName("trailer") @Serializable(with = LenientNullableStringSerializer::class) val trailer: String? = null,
@SerialName("tmdb") @Serializable(with = LenientNullableStringSerializer::class) val tmdb: String? = null,
+ @SerialName("tmdb_id") @Serializable(with = LenientNullableStringSerializer::class) val tmdbId: String? = null,
@SerialName("episode_run_time") @Serializable(with = LenientNullableStringSerializer::class) val episodeRunTime: String? = null,
@SerialName("category_id") @Serializable(with = LenientNullableStringSerializer::class) val categoryId: String? = null,
+ @SerialName("category_name") @Serializable(with = LenientNullableStringSerializer::class) val categoryName: String? = null,
@SerialName("last_modified") @Serializable(with = LenientNullableStringSerializer::class) val lastModified: String? = null,
@SerialName("is_adult") @Serializable(with = LenientNullableBooleanSerializer::class) val isAdult: Boolean? = null
)
-@Serializable
+@Serializable(with = XtreamSeriesInfoResponseSerializer::class)
data class XtreamSeriesInfoResponse(
- @SerialName("info") val info: XtreamSeriesItem? = null,
- @SerialName("episodes") val episodes: Map<String, List<XtreamEpisode>> = emptyMap(),
- @SerialName("seasons") val seasons: List<XtreamSeason> = emptyList()
+ val info: XtreamSeriesItem? = null,
+ val episodes: Map<String, List<XtreamEpisode>> = emptyMap(),
+ val seasons: List<XtreamSeason> = emptyList()
)
@Serializable
@@ -151,6 +156,7 @@ data class XtreamVodInfo(
@SerialName("genre") @Serializable(with = LenientNullableStringSerializer::class) val genre: String? = null,
@SerialName("releasedate") @Serializable(with = LenientNullableStringSerializer::class) val releaseDate: String? = null,
@SerialName("rating") @Serializable(with = LenientNullableStringSerializer::class) val rating: String? = null,
+ @SerialName("rating_5based") @Serializable(with = LenientNullableStringSerializer::class) val rating5based: String? = null,
@SerialName("youtube_trailer") @Serializable(with = LenientNullableStringSerializer::class) val youtubeTrailer: String? = null,
@SerialName("duration_secs") @Serializable(with = LenientIntSerializer::class) val durationSecs: Int = 0,
@SerialName("duration") @Serializable(with = LenientNullableStringSerializer::class) val duration: String? = null,
diff --git a/data/src/main/java/com/streamvault/data/remote/xtream/OkHttpXtreamApiService.kt b/data/src/main/java/com/streamvault/data/remote/xtream/OkHttpXtreamApiService.kt
index 3213f757..52d7f61b 100644
--- a/data/src/main/java/com/streamvault/data/remote/xtream/OkHttpXtreamApiService.kt
+++ b/data/src/main/java/com/streamvault/data/remote/xtream/OkHttpXtreamApiService.kt
@@ -1,5 +1,8 @@
package com.streamvault.data.remote.xtream
+import com.google.gson.JsonParser
+import com.google.gson.stream.JsonReader
+import com.google.gson.stream.JsonToken
import com.streamvault.data.remote.dto.XtreamAuthResponse
import com.streamvault.data.remote.dto.XtreamCategory
import com.streamvault.data.remote.dto.XtreamEpgResponse
@@ -9,19 +12,39 @@ import com.streamvault.data.remote.dto.XtreamStream
import com.streamvault.data.remote.dto.XtreamVodInfoResponse
import com.streamvault.data.remote.NetworkTimeoutConfig
import java.io.IOException
+import java.io.InputStream
+import java.io.InputStreamReader
+import java.io.PushbackInputStream
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
+import kotlinx.serialization.DeserializationStrategy
+import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.json.Json
+import kotlinx.serialization.json.decodeFromStream
import kotlinx.serialization.SerializationException
import okhttp3.OkHttpClient
import okhttp3.Request
+import okhttp3.ResponseBody
import java.net.URI
+import java.nio.charset.Charset
import java.util.concurrent.TimeUnit.SECONDS
+@OptIn(ExperimentalSerializationApi::class)
class OkHttpXtreamApiService(
private val client: OkHttpClient,
private val json: Json
) : XtreamApiService {
+ private companion object {
+ const val PREVIEW_INPUT_LIMIT = 512
+ const val PREVIEW_OUTPUT_LIMIT = 140
+ const val RESPONSE_BUDGET_HEADROOM_BYTES = 1L * 1024L * 1024L
+ const val MAX_FULL_LIVE_CATALOG_BYTES = 96L * 1024L * 1024L
+ const val MAX_FULL_VOD_CATALOG_BYTES = 80L * 1024L * 1024L
+ const val MAX_FULL_SERIES_CATALOG_BYTES = 100L * 1024L * 1024L
+ const val MAX_PARTIAL_CATALOG_BYTES = 40L * 1024L * 1024L
+ const val MAX_EPG_BYTES = 12L * 1024L * 1024L
+ }
+
private enum class RequestProfile {
STANDARD,
HEAVY_CATALOG
@@ -31,7 +54,8 @@ class OkHttpXtreamApiService(
val action: String?,
val host: String?,
val path: String?,
- val hint: String
+ val hint: String,
+ val queryKeys: Set<String>
)
private val heavyCatalogClient: OkHttpClient by lazy {
@@ -46,18 +70,34 @@ class OkHttpXtreamApiService(
override suspend fun getLiveCategories(endpoint: String): List<XtreamCategory> = get(endpoint)
- override suspend fun getLiveStreams(endpoint: String): List<XtreamStream> = get(endpoint)
+ override suspend fun getLiveStreams(endpoint: String): List<XtreamStream> = get(endpoint, RequestProfile.HEAVY_CATALOG)
override suspend fun getVodCategories(endpoint: String): List<XtreamCategory> = get(endpoint)
override suspend fun getVodStreams(endpoint: String): List<XtreamStream> = get(endpoint, RequestProfile.HEAVY_CATALOG)
+ suspend fun streamVodStreams(endpoint: String, onItem: suspend (XtreamStream) -> Unit): Int =
+ streamArray(
+ endpoint = endpoint,
+ profile = RequestProfile.HEAVY_CATALOG,
+ deserializer = XtreamStream.serializer(),
+ onItem = onItem
+ )
+
override suspend fun getVodInfo(endpoint: String): XtreamVodInfoResponse = get(endpoint)
override suspend fun getSeriesCategories(endpoint: String): List<XtreamCategory> = get(endpoint)
override suspend fun getSeriesList(endpoint: String): List<XtreamSeriesItem> = get(endpoint, RequestProfile.HEAVY_CATALOG)
+ suspend fun streamSeriesList(endpoint: String, onItem: suspend (XtreamSeriesItem) -> Unit): Int =
+ streamArray(
+ endpoint = endpoint,
+ profile = RequestProfile.HEAVY_CATALOG,
+ deserializer = XtreamSeriesItem.serializer(),
+ onItem = onItem
+ )
+
override suspend fun getSeriesInfo(endpoint: String): XtreamSeriesInfoResponse = get(endpoint)
override suspend fun getShortEpg(endpoint: String): XtreamEpgResponse = get(endpoint)
@@ -79,27 +119,25 @@ class OkHttpXtreamApiService(
if (!response.isSuccessful) {
val message = "HTTP ${response.code}"
when (response.code) {
- 401, 403 -> throw XtreamAuthenticationException(response.code, message)
+ 401 -> throw XtreamAuthenticationException(response.code, message)
+ 403 -> {
+ if (descriptor.action.isNullOrBlank()) {
+ throw XtreamAuthenticationException(response.code, message)
+ }
+ throw XtreamRequestException(response.code, message)
+ }
in 500..599, 429 -> throw XtreamNetworkException(message)
else -> throw XtreamRequestException(response.code, message)
}
}
- val body = response.body?.string()?.takeIf { it.isNotBlank() }
+ val body = response.body
?: throw XtreamParsingException("Empty response body from ${descriptor.hint}")
- inspectResponseShape(
+ decodeBodyBounded(
body = body,
+ descriptor = descriptor,
contentType = response.header("Content-Type"),
- descriptor = descriptor
- )?.let { throw it }
- try {
- json.decodeFromString<T>(body)
- } catch (e: SerializationException) {
- val preview = sanitizedPreview(body)
- throw XtreamParsingException(
- "Malformed JSON from ${descriptor.hint}${if (preview != null) " (preview=$preview)" else ""}",
- e
- )
- }
+ maxBytes = responseBudgetFor(descriptor)
+ )
}
} catch (e: XtreamApiException) {
throw e
@@ -115,10 +153,16 @@ class OkHttpXtreamApiService(
private fun describeEndpoint(endpoint: String): EndpointDescriptor {
val uri = runCatching { URI(endpoint) }.getOrNull()
- val action = uri?.rawQuery
+ val queryParams = uri?.rawQuery
?.split('&')
- ?.firstOrNull { it.startsWith("action=", ignoreCase = true) }
- ?.substringAfter('=')
+ ?.mapNotNull { token ->
+ val key = token.substringBefore('=', "").trim()
+ if (key.isBlank()) null else key.lowercase() to token.substringAfter('=', "")
+ }
+ .orEmpty()
+ val action = queryParams
+ .firstOrNull { (key, _) -> key == "action" }
+ ?.second
?.takeIf { it.isNotBlank() }
val host = uri?.host
val path = uri?.path?.substringAfterLast('/')?.takeIf { it.isNotBlank() }
@@ -131,8 +175,253 @@ class OkHttpXtreamApiService(
action = action,
host = host,
path = path,
- hint = XtreamUrlFactory.sanitizeLogMessage(hint)
+ hint = XtreamUrlFactory.sanitizeLogMessage(hint),
+ queryKeys = queryParams.mapTo(linkedSetOf()) { (key, _) -> key }
+ )
+ }
+
+ private fun responseBudgetFor(descriptor: EndpointDescriptor): Long? {
+ val action = descriptor.action?.lowercase().orEmpty()
+ val queryKeys = descriptor.queryKeys
+ val isSegmentedCatalogRequest = queryKeys.any { key ->
+ key == "category_id" || key == "page" || key == "offset" || key == "items_per_page" || key == "limit"
+ }
+ return when {
+ (action == "get_live_streams" || action == "get_vod_streams" || action == "get_series") &&
+ isSegmentedCatalogRequest -> MAX_PARTIAL_CATALOG_BYTES
+ action == "get_live_streams" -> MAX_FULL_LIVE_CATALOG_BYTES
+ action == "get_vod_streams" -> MAX_FULL_VOD_CATALOG_BYTES
+ action == "get_series" -> MAX_FULL_SERIES_CATALOG_BYTES
+ action == "get_short_epg" || action == "get_simple_data_table" -> MAX_EPG_BYTES
+ else -> null
+ }
+ }
+
+ private suspend fun <T> streamArray(
+ endpoint: String,
+ profile: RequestProfile,
+ deserializer: DeserializationStrategy<T>,
+ onItem: suspend (T) -> Unit
+ ): Int = withContext(Dispatchers.IO) {
+ val descriptor = describeEndpoint(endpoint)
+ val request = Request.Builder()
+ .url(endpoint)
+ .get()
+ .build()
+ try {
+ val call = clientFor(profile).newCall(request)
+ call.execute().use { response ->
+ if (!response.isSuccessful) {
+ val message = "HTTP ${response.code}"
+ when (response.code) {
+ 401 -> throw XtreamAuthenticationException(response.code, message)
+ 403 -> {
+ if (descriptor.action.isNullOrBlank()) {
+ throw XtreamAuthenticationException(response.code, message)
+ }
+ throw XtreamRequestException(response.code, message)
+ }
+ in 500..599, 429 -> throw XtreamNetworkException(message)
+ else -> throw XtreamRequestException(response.code, message)
+ }
+ }
+ val body = response.body
+ ?: throw XtreamParsingException("Empty response body from ${descriptor.hint}")
+ streamBodyBounded(
+ body = body,
+ descriptor = descriptor,
+ contentType = response.header("Content-Type"),
+ maxBytes = responseBudgetFor(descriptor),
+ deserializer = deserializer,
+ onItem = onItem
+ )
+ }
+ } catch (e: XtreamApiException) {
+ throw e
+ } catch (e: IOException) {
+ throw XtreamNetworkException(XtreamUrlFactory.sanitizeLogMessage(e.message ?: "Network request failed"), e)
+ }
+ }
+
+ private inline fun <reified T> decodeBodyBounded(
+ body: ResponseBody,
+ descriptor: EndpointDescriptor,
+ contentType: String?,
+ maxBytes: Long?
+ ): T {
+ val effectiveMaxBytes = maxBytes?.plus(RESPONSE_BUDGET_HEADROOM_BYTES)
+ val announcedLength = body.contentLength()
+ if (effectiveMaxBytes != null && announcedLength > effectiveMaxBytes) {
+ throw XtreamResponseTooLargeException(
+ hint = descriptor.hint,
+ observedBytes = announcedLength,
+ maxAllowedBytes = effectiveMaxBytes
+ )
+ }
+
+ val charset = body.contentType()?.charset(Charsets.UTF_8) ?: Charsets.UTF_8
+ val input = PushbackInputStream(
+ BoundedInputStream(
+ delegate = body.byteStream(),
+ descriptor = descriptor,
+ maxAllowedBytes = effectiveMaxBytes
+ ),
+ PREVIEW_INPUT_LIMIT
+ )
+ input.use { stream ->
+ val previewBytes = readPreviewBytes(stream)
+ if (previewBytes.isEmpty()) {
+ throw XtreamParsingException("Empty response body from ${descriptor.hint}")
+ }
+ val preview = previewBytes.toString(charset)
+ inspectResponseShape(
+ body = preview,
+ contentType = contentType,
+ descriptor = descriptor
+ )?.let { throw it }
+ stream.unread(previewBytes)
+ while (true) {
+ return try {
+ json.decodeFromStream<T>(stream)
+ } catch (e: SerializationException) {
+ throw XtreamParsingException(
+ "Malformed JSON from ${descriptor.hint}${sanitizedPreview(preview)?.let { " (preview=$it)" } ?: ""}",
+ e
+ )
+ }
+ }
+ }
+ }
+
+ private suspend fun <T> streamBodyBounded(
+ body: ResponseBody,
+ descriptor: EndpointDescriptor,
+ contentType: String?,
+ maxBytes: Long?,
+ deserializer: DeserializationStrategy<T>,
+ onItem: suspend (T) -> Unit
+ ): Int {
+ val effectiveMaxBytes = maxBytes?.plus(RESPONSE_BUDGET_HEADROOM_BYTES)
+ val announcedLength = body.contentLength()
+ if (effectiveMaxBytes != null && announcedLength > effectiveMaxBytes) {
+ throw XtreamResponseTooLargeException(
+ hint = descriptor.hint,
+ observedBytes = announcedLength,
+ maxAllowedBytes = effectiveMaxBytes
+ )
+ }
+
+ val charset = body.contentType()?.charset(Charsets.UTF_8) ?: Charsets.UTF_8
+ val input = PushbackInputStream(
+ BoundedInputStream(
+ delegate = body.byteStream(),
+ descriptor = descriptor,
+ maxAllowedBytes = effectiveMaxBytes
+ ),
+ PREVIEW_INPUT_LIMIT
)
+ input.use { stream ->
+ val previewBytes = readPreviewBytes(stream)
+ if (previewBytes.isEmpty()) {
+ throw XtreamParsingException("Empty response body from ${descriptor.hint}")
+ }
+ val preview = previewBytes.toString(charset)
+ inspectResponseShape(
+ body = preview,
+ contentType = contentType,
+ descriptor = descriptor
+ )?.let { throw it }
+ stream.unread(previewBytes)
+
+ val reader = JsonReader(InputStreamReader(stream, charset))
+ reader.isLenient = true
+ return when (reader.peek()) {
+ JsonToken.BEGIN_ARRAY -> {
+ var emittedCount = 0
+ reader.beginArray()
+ while (reader.hasNext()) {
+ val element = try {
+ JsonParser.parseReader(reader)
+ } catch (e: RuntimeException) {
+ throw XtreamParsingException(
+ "Malformed JSON from ${descriptor.hint}${sanitizedPreview(preview)?.let { " (preview=$it)" } ?: ""}",
+ e
+ )
+ }
+ val item = try {
+ json.decodeFromString(deserializer, element.toString())
+ } catch (e: SerializationException) {
+ throw XtreamParsingException(
+ "Malformed JSON from ${descriptor.hint}${sanitizedPreview(preview)?.let { " (preview=$it)" } ?: ""}",
+ e
+ )
+ }
+ onItem(item)
+ emittedCount++
+ }
+ reader.endArray()
+ emittedCount
+ }
+ JsonToken.NULL -> {
+ reader.nextNull()
+ 0
+ }
+ else -> throw XtreamParsingException(
+ "Expected JSON array from ${descriptor.hint}${sanitizedPreview(preview)?.let { " (preview=$it)" } ?: ""}"
+ )
+ }
+ }
+ }
+
+ private fun readPreviewBytes(input: InputStream): ByteArray {
+ val buffer = ByteArray(PREVIEW_INPUT_LIMIT)
+ var totalRead = 0
+ while (totalRead < PREVIEW_INPUT_LIMIT) {
+ val read = input.read(buffer, totalRead, PREVIEW_INPUT_LIMIT - totalRead)
+ if (read == -1) break
+ totalRead += read
+ }
+ return if (totalRead == buffer.size) buffer else buffer.copyOf(totalRead)
+ }
+
+ private class BoundedInputStream(
+ private val delegate: InputStream,
+ private val descriptor: EndpointDescriptor,
+ private val maxAllowedBytes: Long?
+ ) : InputStream() {
+ private var totalBytesRead = 0L
+
+ override fun read(): Int {
+ val value = delegate.read()
+ if (value != -1) {
+ recordBytesRead(1)
+ }
+ return value
+ }
+
+ override fun read(b: ByteArray, off: Int, len: Int): Int {
+ val read = delegate.read(b, off, len)
+ if (read > 0) {
+ recordBytesRead(read.toLong())
+ }
+ return read
+ }
+
+ override fun close() {
+ delegate.close()
+ }
+
+ private fun recordBytesRead(bytesRead: Long) {
+ totalBytesRead += bytesRead
+ val limit = maxAllowedBytes ?: return
+ if (totalBytesRead > limit) {
+ throw XtreamResponseTooLargeException(
+ hint = descriptor.hint,
+ observedBytes = totalBytesRead,
+ maxAllowedBytes = limit
+ )
+ }
+ }
}
private fun inspectResponseShape(
@@ -162,11 +451,13 @@ class OkHttpXtreamApiService(
}
private fun sanitizedPreview(body: String): String? {
- return body
+ val boundedInput = body
+ .take(PREVIEW_INPUT_LIMIT)
.replace(Regex("\\s+"), " ")
.trim()
+ return boundedInput
.takeIf { it.isNotEmpty() }
- ?.take(140)
+ ?.take(PREVIEW_OUTPUT_LIMIT)
?.let(XtreamUrlFactory::sanitizeLogMessage)
}
}
diff --git a/data/src/main/java/com/streamvault/data/remote/xtream/XtreamApiExceptions.kt b/data/src/main/java/com/streamvault/data/remote/xtream/XtreamApiExceptions.kt
index b4341533..7890b4ce 100644
--- a/data/src/main/java/com/streamvault/data/remote/xtream/XtreamApiExceptions.kt
+++ b/data/src/main/java/com/streamvault/data/remote/xtream/XtreamApiExceptions.kt
@@ -18,4 +18,14 @@ class XtreamRequestException(
val statusCode: Int,
message: String,
cause: Throwable? = null
-) : XtreamApiException(message, cause)
\ No newline at end of file
+) : XtreamApiException(message, cause)
+
+class XtreamResponseTooLargeException(
+ val hint: String,
+ val observedBytes: Long,
+ val maxAllowedBytes: Long,
+ cause: Throwable? = null
+) : XtreamApiException(
+ "Response from $hint exceeded safe in-memory budget (${observedBytes}B > ${maxAllowedBytes}B)",
+ cause
+)
diff --git a/data/src/main/java/com/streamvault/data/remote/xtream/XtreamProvider.kt b/data/src/main/java/com/streamvault/data/remote/xtream/XtreamProvider.kt
index b67868bb..1101652a 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
@@ -16,6 +16,7 @@ import java.time.format.DateTimeFormatterBuilder
import java.time.format.ResolverStyle
import java.util.Base64
import java.util.Locale
+import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
@@ -207,7 +208,7 @@ class XtreamProvider(
releaseDate = info?.releaseDate,
duration = info?.duration,
durationSeconds = info?.durationSecs ?: 0,
- rating = info?.rating?.toFloatOrNull() ?: 0f,
+ rating = normalizeXtreamRatingTenPoint(info?.rating, info?.rating5based),
tmdbId = info?.tmdbId ?: movieData.tmdb?.trim()?.toLongOrNull(),
youtubeTrailer = info?.youtubeTrailer ?: movieData.youtubeTrailer ?: movieData.trailer,
providerId = providerId,
@@ -273,80 +274,78 @@ class XtreamProvider(
}
override suspend fun getSeriesInfo(seriesId: Long): Result<Series> = try {
- val response = api.getSeriesInfo(
- XtreamUrlFactory.buildPlayerApiUrl(
- serverUrl = serverUrl,
- username = username,
- password = password,
- action = "get_series_info",
- extraQueryParams = mapOf("series_id" to seriesId.toString())
- )
- )
+ val response = requestSeriesInfoWithCompatibilityFallback(seriesId)
val info = response.info
-
- if (info == null) {
- Result.error("Series not found")
- } else {
- val adultCategoryIds = loadAdultCategoryIds(ContentType.SERIES)
- val baseSeries = info.toDomain(adultCategoryIds)
- ?: return Result.error("Series payload is invalid")
- val isAdult = resolveAdultFlag(
- explicitAdult = info.isAdult,
- categoryId = info.categoryId?.toLongOrNull(),
- categoryName = null,
- adultCategoryIds = adultCategoryIds
- )
- val seasons = response.episodes.map { (seasonNum, episodes) ->
- val mappedEpisodes = episodes.mapNotNull { ep ->
- val episodeId = ep.id.toLongOrNull()?.takeIf { it > 0 } ?: return@mapNotNull null
- val normalizedExtension = normalizeContainerExtension(ep.containerExtension)
- Episode(
- id = episodeId,
- title = decodeXtreamText(
- ep.title.ifBlank { decodeXtreamNullableText(ep.info?.name) ?: "Episode ${ep.episodeNum}" }
- ),
- episodeNumber = ep.episodeNum,
- seasonNumber = ep.season,
- containerExtension = normalizedExtension,
- coverUrl = sanitizeAssetValue(ep.info?.movieImage),
- plot = decodeXtreamNullableText(ep.info?.plot),
- duration = ep.info?.duration,
- durationSeconds = ep.info?.durationSecs ?: 0,
- rating = ep.info?.rating?.toFloatOrNull() ?: 0f,
- releaseDate = ep.info?.releaseDate,
- seriesId = seriesId,
+ val adultCategoryIds = loadAdultCategoryIds(ContentType.SERIES)
+ val baseSeries = info?.toDomain(
+ adultCategoryIds = adultCategoryIds,
+ fallbackSeriesId = seriesId
+ ) ?: buildFallbackSeriesFromDetails(response, seriesId)
+ ?: return Result.error("Series details are unavailable")
+ val isAdult = resolveAdultFlag(
+ explicitAdult = info?.isAdult,
+ categoryId = info?.categoryId?.toLongOrNull(),
+ categoryName = info?.categoryName,
+ adultCategoryIds = adultCategoryIds
+ )
+ val seasons = response.episodes.map { (seasonNum, episodes) ->
+ 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 normalizedExtension = normalizeContainerExtension(ep.containerExtension)
+ Episode(
+ id = episodeId,
+ title = decodeXtreamText(
+ ep.title.ifBlank { decodeXtreamNullableText(ep.info?.name) ?: "Episode ${ep.episodeNum}" }
+ ),
+ episodeNumber = ep.episodeNum,
+ seasonNumber = ep.season.takeIf { it > 0 } ?: resolvedSeasonNumber,
+ containerExtension = normalizedExtension,
+ coverUrl = sanitizeAssetValue(ep.info?.movieImage),
+ plot = decodeXtreamNullableText(ep.info?.plot),
+ duration = ep.info?.duration,
+ durationSeconds = ep.info?.durationSecs ?: 0,
+ rating = ep.info?.rating?.toFloatOrNull() ?: 0f,
+ releaseDate = ep.info?.releaseDate,
+ seriesId = seriesId,
+ providerId = providerId,
+ streamUrl = XtreamUrlFactory.buildInternalStreamUrl(
providerId = providerId,
- streamUrl = XtreamUrlFactory.buildInternalStreamUrl(
- providerId = providerId,
- kind = XtreamStreamKind.SERIES,
- streamId = episodeId,
- containerExtension = normalizedExtension,
- directSource = sanitizeAssetValue(ep.directSource)
- ),
- isAdult = isAdult,
- isUserProtected = false,
- episodeId = episodeId
- )
- }
- Season(
- seasonNumber = seasonNum.toIntOrNull() ?: 0,
- name = "Season $seasonNum",
- coverUrl = response.seasons.find {
- it.seasonNumber == (seasonNum.toIntOrNull() ?: 0)
- }?.cover,
- episodes = mappedEpisodes,
- episodeCount = mappedEpisodes.size
+ kind = XtreamStreamKind.SERIES,
+ streamId = episodeId,
+ containerExtension = normalizedExtension,
+ directSource = sanitizeAssetValue(ep.directSource)
+ ),
+ isAdult = isAdult,
+ isUserProtected = false,
+ episodeId = episodeId
)
- }.sortedBy { it.seasonNumber }
+ }
+ Season(
+ seasonNumber = resolvedSeasonNumber,
+ name = response.seasons.find { it.seasonNumber == resolvedSeasonNumber }?.name
+ ?.takeIf { it.isNotBlank() }
+ ?: "Season $resolvedSeasonNumber",
+ coverUrl = response.seasons.find { it.seasonNumber == resolvedSeasonNumber }?.cover,
+ airDate = response.seasons.find { it.seasonNumber == resolvedSeasonNumber }?.airDate,
+ episodes = mappedEpisodes,
+ episodeCount = response.seasons.find { it.seasonNumber == resolvedSeasonNumber }?.episodeCount
+ ?.takeIf { it > 0 }
+ ?: mappedEpisodes.size
+ )
+ }.sortedBy { it.seasonNumber }
- Result.success(
- baseSeries.copy(
- seasons = seasons,
- providerId = providerId,
- isAdult = isAdult
- )
+ Result.success(
+ baseSeries.copy(
+ seasons = seasons,
+ providerId = providerId,
+ isAdult = isAdult
)
- }
+ )
+ } catch (e: CancellationException) {
+ throw e
} catch (e: Exception) {
Result.error(XtreamErrorFormatter.message("Failed to load series details", e), e)
}
@@ -450,19 +449,12 @@ class XtreamProvider(
return categories.map { it.toDomain(type) }
}
- suspend fun mapVodStreamsResponse(streams: List<XtreamStream>): List<Movie> {
+ suspend fun mapVodStreamsResponse(streams: List<XtreamStream>): List<Movie> =
+ mapVodStreamsSequence(streams.asSequence()).toList()
+
+ suspend fun mapVodStreamsSequence(streams: Sequence<XtreamStream>): Sequence<Movie> {
val adultCategoryIds = loadAdultCategoryIds(ContentType.MOVIE)
- return streams.mapNotNull { stream ->
- runCatching { stream.toMovie(adultCategoryIds) }
- .onFailure {
- Log.w(
- TAG,
- "Skipping malformed VOD item ${stream.streamId}: " +
- XtreamUrlFactory.sanitizeLogMessage(it.message ?: "mapping failed")
- )
- }
- .getOrNull()
- }
+ return streams.mapNotNull { stream -> mapVodStream(stream, adultCategoryIds) }
}
suspend fun mapLiveStreamsResponse(streams: List<XtreamStream>): List<Channel> {
@@ -480,19 +472,12 @@ class XtreamProvider(
}
}
- suspend fun mapSeriesListResponse(items: List<XtreamSeriesItem>): List<Series> {
+ suspend fun mapSeriesListResponse(items: List<XtreamSeriesItem>): List<Series> =
+ mapSeriesListSequence(items.asSequence()).toList()
+
+ suspend fun mapSeriesListSequence(items: Sequence<XtreamSeriesItem>): Sequence<Series> {
val adultCategoryIds = loadAdultCategoryIds(ContentType.SERIES)
- return items.mapNotNull { item ->
- runCatching { item.toDomain(adultCategoryIds) }
- .onFailure {
- Log.w(
- TAG,
- "Skipping malformed series item ${item.seriesId}: " +
- XtreamUrlFactory.sanitizeLogMessage(it.message ?: "mapping failed")
- )
- }
- .getOrNull()
- }
+ return items.mapNotNull { item -> mapSeriesItem(item, adultCategoryIds) }
}
// ── Mappers ────────────────────────────────────────────────────
@@ -701,7 +686,7 @@ class XtreamProvider(
categoryId = category.id,
categoryName = category.name,
containerExtension = normalizedContainerExtension,
- rating = rating5based?.toFloatOrNull() ?: rating?.toFloatOrNull() ?: 0f,
+ rating = normalizeXtreamRatingTenPoint(rating, rating5based),
tmdbId = tmdb?.trim()?.toLongOrNull(),
youtubeTrailer = youtubeTrailer ?: trailer,
providerId = providerId,
@@ -723,24 +708,42 @@ class XtreamProvider(
)
}
- private fun XtreamSeriesItem.toDomain(adultCategoryIds: Set<Long>): Series? {
- if (seriesId <= 0) return null
- val category = resolveXtreamCategory(ContentType.SERIES, categoryId, null)
- val resolvedName = decodeXtreamNullableText(name)?.ifBlank { null } ?: "Series $seriesId"
+ private fun mapVodStream(
+ stream: XtreamStream,
+ adultCategoryIds: Set<Long>
+ ): Movie? {
+ return runCatching { stream.toMovie(adultCategoryIds) }
+ .onFailure {
+ Log.w(
+ TAG,
+ "Skipping malformed VOD item ${stream.streamId}: " +
+ XtreamUrlFactory.sanitizeLogMessage(it.message ?: "mapping failed")
+ )
+ }
+ .getOrNull()
+ }
+
+ private fun XtreamSeriesItem.toDomain(
+ adultCategoryIds: Set<Long>,
+ fallbackSeriesId: Long? = null
+ ): Series? {
+ val resolvedSeriesId = seriesId.takeIf { it > 0 } ?: fallbackSeriesId ?: return null
+ val category = resolveXtreamCategory(ContentType.SERIES, categoryId, categoryName)
+ val resolvedName = decodeXtreamNullableText(name)?.ifBlank { null } ?: "Series $resolvedSeriesId"
return Series(
id = 0,
name = resolvedName,
- posterUrl = sanitizeAssetValue(coverBig) ?: sanitizeAssetValue(cover),
+ posterUrl = sanitizeAssetValue(coverBig) ?: sanitizeAssetValue(movieImage) ?: sanitizeAssetValue(cover),
backdropUrl = firstUsableAsset(backdropPath),
categoryId = category.id,
categoryName = category.name,
- plot = decodeXtreamNullableText(plot),
+ plot = decodeXtreamNullableText(plot) ?: decodeXtreamNullableText(description),
cast = decodeXtreamNullableText(cast),
director = decodeXtreamNullableText(director),
genre = decodeXtreamNullableText(genre),
- releaseDate = releaseDate,
- rating = rating5based?.toFloatOrNull() ?: rating?.toFloatOrNull() ?: 0f,
- tmdbId = tmdb?.trim()?.toLongOrNull(),
+ releaseDate = releaseDate ?: releaseDateAlt,
+ rating = normalizeXtreamRatingTenPoint(rating, rating5based),
+ tmdbId = tmdb?.trim()?.toLongOrNull() ?: tmdbId?.trim()?.toLongOrNull(),
youtubeTrailer = youtubeTrailer ?: trailer,
episodeRunTime = episodeRunTime,
lastModified = lastModified?.toLongOrNull() ?: 0L,
@@ -752,6 +755,84 @@ class XtreamProvider(
adultCategoryIds = adultCategoryIds
),
isUserProtected = false,
+ seriesId = resolvedSeriesId
+ )
+ }
+
+ private fun mapSeriesItem(
+ item: XtreamSeriesItem,
+ adultCategoryIds: Set<Long>
+ ): Series? {
+ return runCatching { item.toDomain(adultCategoryIds) }
+ .onFailure {
+ Log.w(
+ TAG,
+ "Skipping malformed series item ${item.seriesId}: " +
+ XtreamUrlFactory.sanitizeLogMessage(it.message ?: "mapping failed")
+ )
+ }
+ .getOrNull()
+ }
+
+ private suspend fun requestSeriesInfoWithCompatibilityFallback(seriesId: Long): XtreamSeriesInfoResponse {
+ val primaryAttempt = runCatching { requestSeriesInfo(seriesId, "series_id") }
+ val primaryResponse = primaryAttempt.getOrNull()
+ if (primaryResponse.hasUsableSeriesDetailPayload()) {
+ return requireNotNull(primaryResponse)
+ }
+
+ val primaryFailure = primaryAttempt.exceptionOrNull()
+ val shouldTryLegacyParam = primaryFailure == null ||
+ primaryFailure is XtreamRequestException ||
+ primaryFailure is XtreamParsingException
+ if (!shouldTryLegacyParam) {
+ primaryResponse?.let { return it }
+ primaryFailure?.let { throw it }
+ }
+ val legacyAttempt = runCatching { requestSeriesInfo(seriesId, "series") }
+ val legacyResponse = legacyAttempt.getOrNull()
+ if (legacyResponse.hasUsableSeriesDetailPayload()) {
+ return requireNotNull(legacyResponse)
+ }
+
+ primaryResponse?.let { return it }
+ primaryFailure?.let { throw it }
+ legacyAttempt.exceptionOrNull()?.let { throw it }
+ return legacyResponse ?: XtreamSeriesInfoResponse()
+ }
+
+ private suspend fun requestSeriesInfo(seriesId: Long, queryParamName: String): XtreamSeriesInfoResponse {
+ return api.getSeriesInfo(
+ XtreamUrlFactory.buildPlayerApiUrl(
+ serverUrl = serverUrl,
+ username = username,
+ password = password,
+ action = "get_series_info",
+ extraQueryParams = mapOf(queryParamName to seriesId.toString())
+ )
+ )
+ }
+
+ private fun XtreamSeriesInfoResponse?.hasUsableSeriesDetailPayload(): Boolean =
+ this?.info != null || !this?.episodes.isNullOrEmpty() || !this?.seasons.isNullOrEmpty()
+
+ private fun buildFallbackSeriesFromDetails(
+ response: XtreamSeriesInfoResponse,
+ seriesId: Long
+ ): Series? {
+ if (response.episodes.isEmpty() && response.seasons.isEmpty()) {
+ return null
+ }
+ val fallbackPoster = response.seasons.firstNotNullOfOrNull { season ->
+ sanitizeAssetValue(season.cover)
+ }
+ return Series(
+ id = 0,
+ name = "Series $seriesId",
+ posterUrl = fallbackPoster,
+ providerId = providerId,
+ isAdult = false,
+ isUserProtected = false,
seriesId = seriesId
)
}
@@ -790,6 +871,22 @@ class XtreamProvider(
return values.orEmpty().firstNotNullOfOrNull(::sanitizeAssetValue)
}
+ private fun normalizeXtreamRatingTenPoint(
+ rawTenPoint: String?,
+ rawFivePoint: String?
+ ): Float {
+ val tenPoint = rawTenPoint?.trim()?.toFloatOrNull()?.takeIf { it in 0f..10f }
+ if (tenPoint != null) {
+ return tenPoint
+ }
+ return rawFivePoint
+ ?.trim()
+ ?.toFloatOrNull()
+ ?.takeIf { it in 0f..5f }
+ ?.times(2f)
+ ?: 0f
+ }
+
private fun decodeXtreamText(value: String): String = tryBase64Decode(value).trim()
private fun resolveXtreamCategory(
diff --git a/data/src/main/java/com/streamvault/data/repository/ChannelRepositoryImpl.kt b/data/src/main/java/com/streamvault/data/repository/ChannelRepositoryImpl.kt
index 25c6a1f8..af9a76f7 100644
--- a/data/src/main/java/com/streamvault/data/repository/ChannelRepositoryImpl.kt
+++ b/data/src/main/java/com/streamvault/data/repository/ChannelRepositoryImpl.kt
@@ -2,6 +2,7 @@ package com.streamvault.data.repository
import com.streamvault.data.local.dao.CategoryDao
import com.streamvault.data.local.dao.ChannelDao
+import com.streamvault.data.local.entity.ChannelBrowseEntity
import com.streamvault.data.local.entity.CategoryEntity
import com.streamvault.data.local.entity.ChannelEntity
import com.streamvault.data.mapper.toDomain
@@ -32,17 +33,18 @@ class ChannelRepositoryImpl @Inject constructor(
private val xtreamStreamUrlResolver: XtreamStreamUrlResolver
) : ChannelRepository {
private companion object {
- const val GLOBAL_SEARCH_LIMIT = 320
- const val CATEGORY_SEARCH_LIMIT = 750
+ const val GLOBAL_SEARCH_LIMIT = 200
+ const val CATEGORY_SEARCH_LIMIT = 300
+ const val MIN_SEARCH_QUERY_LENGTH = 2
val QUALITY_HEIGHT_REGEX = Regex("(?<!\\d)(2160|1440|1080|720|576|480|360|240)p?(?!\\d)", RegexOption.IGNORE_CASE)
}
private data class ChannelGroupAccumulator(
- var primary: ChannelEntity,
- val alternatives: MutableList<ChannelEntity> = mutableListOf()
+ var primary: ChannelBrowseEntity,
+ val alternatives: MutableList<ChannelBrowseEntity> = mutableListOf()
)
- private val channelPriorityComparator = compareBy<ChannelEntity>({ it.errorCount }, { it.name.length })
+ private val channelPriorityComparator = compareBy<ChannelBrowseEntity>({ it.errorCount }, { it.name.length })
private val channelNumberComparator = compareBy<Channel>(
{ it.number <= 0 },
{ it.number.takeIf { number -> number > 0 } ?: Int.MAX_VALUE },
@@ -64,8 +66,8 @@ class ChannelRepositoryImpl @Inject constructor(
.map(::sortChannelsByNumber)
override fun searchChannelsByCategory(providerId: Long, categoryId: Long, query: String): Flow<List<Channel>> =
- query.toFtsPrefixQuery().let { ftsQuery ->
- if (ftsQuery.isBlank()) {
+ query.trim().takeIf { it.length >= MIN_SEARCH_QUERY_LENGTH }?.toFtsPrefixQuery().let { ftsQuery ->
+ if (ftsQuery.isNullOrBlank()) {
flowOf(emptyList())
} else {
combine(
@@ -127,8 +129,8 @@ class ChannelRepositoryImpl @Inject constructor(
}
override fun searchChannels(providerId: Long, query: String): Flow<List<Channel>> =
- query.toFtsPrefixQuery().let { ftsQuery ->
- if (ftsQuery.isBlank()) {
+ query.trim().takeIf { it.length >= MIN_SEARCH_QUERY_LENGTH }?.toFtsPrefixQuery().let { ftsQuery ->
+ if (ftsQuery.isNullOrBlank()) {
flowOf(emptyList())
} else combine(
channelDao.search(providerId, ftsQuery, GLOBAL_SEARCH_LIMIT),
@@ -178,7 +180,7 @@ class ChannelRepositoryImpl @Inject constructor(
}
override fun getChannelsByIds(ids: List<Long>): Flow<List<Channel>> =
- channelDao.getByIds(ids).map { entities -> entities.map { it.toDomain() } }
+ channelDao.getByIds(ids).map { entities -> entities.map { it.toBrowseDomain() } }
override suspend fun incrementChannelErrorCount(channelId: Long): Result<Unit> = try {
channelDao.incrementErrorCount(channelId)
@@ -195,7 +197,7 @@ class ChannelRepositoryImpl @Inject constructor(
}
private fun observeChannels(
- source: Flow<List<ChannelEntity>>,
+ source: Flow<List<ChannelBrowseEntity>>,
providerId: Long
): Flow<List<Channel>> = combine(
source,
@@ -209,7 +211,7 @@ class ChannelRepositoryImpl @Inject constructor(
)
}
- private fun groupAndMapChannels(entities: List<ChannelEntity>, unlockedCats: Set<Long>): List<Channel> {
+ private fun groupAndMapChannels(entities: List<ChannelBrowseEntity>, unlockedCats: Set<Long>): List<Channel> {
val grouped = LinkedHashMap<String, ChannelGroupAccumulator>()
entities.forEach { entity ->
val key = channelGroupKey(entity)
@@ -226,18 +228,16 @@ class ChannelRepositoryImpl @Inject constructor(
return grouped.values.map { group ->
val primaryEntity = group.primary
- val primaryDomain = primaryEntity.toDomain()
- val alternativeStreams = (group.alternatives
+ val alternativeStreams = group.alternatives
.sortedWith(channelPriorityComparator)
.map { it.streamUrl }
- + primaryDomain.qualityOptions.mapNotNull { it.url }.filter { it != primaryEntity.streamUrl })
.distinct()
val mergedQualityOptions = buildMergedQualityOptions(
- baseOptions = primaryDomain.qualityOptions,
+ baseOptions = emptyList(),
primaryStreamUrl = primaryEntity.streamUrl,
alternativeStreams = alternativeStreams
)
- val domain = primaryDomain.copy(
+ val domain = primaryEntity.toBrowseDomain().copy(
qualityOptions = mergedQualityOptions,
alternativeStreams = alternativeStreams
)
@@ -251,10 +251,10 @@ class ChannelRepositoryImpl @Inject constructor(
}
private fun applyVisibilityFilter(
- entities: List<ChannelEntity>,
+ entities: List<ChannelBrowseEntity>,
level: Int,
unlockedCats: Set<Long>
- ): List<ChannelEntity> {
+ ): List<ChannelBrowseEntity> {
return if (level == 2) {
entities.filter { entity ->
val isUnlocked = entity.categoryId != null && unlockedCats.contains(entity.categoryId)
@@ -279,14 +279,14 @@ class ChannelRepositoryImpl @Inject constructor(
ChannelNumberingMode.PROVIDER -> channels
}
- private fun channelFlow(providerId: Long, categoryId: Long): Flow<List<ChannelEntity>> =
+ private fun channelFlow(providerId: Long, categoryId: Long): Flow<List<ChannelBrowseEntity>> =
if (categoryId == ChannelRepository.ALL_CHANNELS_ID) {
channelDao.getByProvider(providerId)
} else {
channelDao.getByCategory(providerId, categoryId)
}
- private fun channelFlowWithoutErrors(providerId: Long, categoryId: Long): Flow<List<ChannelEntity>> =
+ private fun channelFlowWithoutErrors(providerId: Long, categoryId: Long): Flow<List<ChannelBrowseEntity>> =
if (categoryId == ChannelRepository.ALL_CHANNELS_ID) {
channelDao.getByProviderWithoutErrors(providerId)
} else {
@@ -315,6 +315,28 @@ class ChannelRepositoryImpl @Inject constructor(
)
}
- private fun channelGroupKey(entity: ChannelEntity): String =
+ private fun channelGroupKey(entity: ChannelBrowseEntity): String =
if (entity.logicalGroupId.isNotBlank()) entity.logicalGroupId else entity.id.toString()
+
+ private fun ChannelBrowseEntity.toBrowseDomain(): Channel =
+ Channel(
+ id = id,
+ name = name,
+ logoUrl = logoUrl,
+ groupTitle = groupTitle,
+ categoryId = categoryId,
+ categoryName = categoryName,
+ streamUrl = streamUrl,
+ epgChannelId = epgChannelId,
+ number = number,
+ catchUpSupported = catchUpSupported,
+ catchUpDays = catchUpDays,
+ catchUpSource = catchUpSource,
+ providerId = providerId,
+ isAdult = isAdult,
+ isUserProtected = isUserProtected,
+ logicalGroupId = logicalGroupId,
+ errorCount = errorCount,
+ streamId = streamId
+ )
}
diff --git a/data/src/main/java/com/streamvault/data/repository/MovieRepositoryImpl.kt b/data/src/main/java/com/streamvault/data/repository/MovieRepositoryImpl.kt
index 1057c73e..0f6dd12f 100644
--- a/data/src/main/java/com/streamvault/data/repository/MovieRepositoryImpl.kt
+++ b/data/src/main/java/com/streamvault/data/repository/MovieRepositoryImpl.kt
@@ -5,7 +5,6 @@ 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.entity.MovieEntity
import com.streamvault.data.local.entity.ProviderEntity
import com.streamvault.data.local.entity.CategoryEntity
import com.streamvault.data.mapper.toEntity
@@ -57,7 +56,9 @@ class MovieRepositoryImpl @Inject constructor(
private val xtreamStreamUrlResolver: XtreamStreamUrlResolver
) : MovieRepository {
private companion object {
- const val SEARCH_RESULT_LIMIT = 320
+ const val SEARCH_RESULT_LIMIT = 200
+ const val MIN_SEARCH_QUERY_LENGTH = 2
+ const val BROWSE_WINDOW_BUFFER = 80
}
private data class CachedXtreamProvider(
@@ -97,7 +98,7 @@ class MovieRepositoryImpl @Inject constructor(
combine(
movieDao.getByCategoryPage(providerId, categoryId, limit, offset),
preferencesRepository.parentalControlLevel
- ) { entities: List<MovieEntity>, level: Int ->
+ ) { entities, level: Int ->
if (level == 2) {
entities.filter { !it.isUserProtected }
} else {
@@ -114,7 +115,7 @@ class MovieRepositoryImpl @Inject constructor(
combine(
movieDao.getByCategoryPreview(providerId, categoryId, limit),
preferencesRepository.parentalControlLevel
- ) { entities: List<MovieEntity>, level: Int ->
+ ) { entities, level: Int ->
if (level == 2) {
entities.filter { !it.isUserProtected }
} else {
@@ -153,7 +154,7 @@ class MovieRepositoryImpl @Inject constructor(
combine(
movieDao.getTopRatedPreview(providerId, limit),
preferencesRepository.parentalControlLevel
- ) { entities: List<MovieEntity>, level: Int ->
+ ) { entities, level: Int ->
if (level == 2) {
entities.filter { !it.isUserProtected }
} else {
@@ -165,7 +166,7 @@ class MovieRepositoryImpl @Inject constructor(
combine(
movieDao.getFreshPreview(providerId, limit),
preferencesRepository.parentalControlLevel
- ) { entities: List<MovieEntity>, level: Int ->
+ ) { entities, level: Int ->
if (level == 2) {
entities.filter { !it.isUserProtected }
} else {
@@ -175,12 +176,13 @@ class MovieRepositoryImpl @Inject constructor(
override fun getRecommendations(providerId: Long, limit: Int): Flow<List<Movie>> =
combine(
- getMovies(providerId),
+ getTopRatedPreview(providerId, limit = maxOf(limit * 6, 48)),
+ getFreshPreview(providerId, limit = maxOf(limit * 6, 48)),
favoriteDao.getAllByType(ContentType.MOVIE.name),
playbackHistoryDao.getRecentlyWatchedByProvider(providerId, limit = maxOf(limit * 4, 24))
- ) { movies, favorites, history ->
+ ) { topRated, fresh, favorites, history ->
buildRecommendations(
- movies = movies,
+ movies = (topRated + fresh).distinctBy { it.id },
favoriteIds = favorites.map { it.contentId }.toSet(),
recentlyWatchedIds = history
.asSequence()
@@ -192,11 +194,25 @@ class MovieRepositoryImpl @Inject constructor(
}
override fun getRelatedContent(providerId: Long, movieId: Long, limit: Int): Flow<List<Movie>> =
- getMovies(providerId).map { movies ->
- buildRelatedContent(
- movies = movies,
- movieId = movieId,
- limit = limit
+ flow {
+ val targetMovie = getMovie(movieId) ?: run {
+ emit(emptyList())
+ return@flow
+ }
+ val categoryFlow = targetMovie.categoryId?.let { categoryId ->
+ getMoviesByCategoryPreview(providerId, categoryId, limit = maxOf(limit * 6, 48))
+ } ?: flowOf(emptyList())
+ emitAll(
+ combine(
+ categoryFlow,
+ getTopRatedPreview(providerId, limit = maxOf(limit * 4, 32))
+ ) { categoryItems, topRated ->
+ buildRelatedContent(
+ movies = (categoryItems + topRated).distinctBy { it.id },
+ movieId = movieId,
+ limit = limit
+ )
+ }
)
}
@@ -229,12 +245,13 @@ class MovieRepositoryImpl @Inject constructor(
query.categoryId?.let { ensureXtreamCategoryLoaded(query.providerId, it) }
emitAll(
combine(
- movieBrowseSource(query.providerId, query.categoryId),
+ movieBrowseSource(query),
+ movieBrowseTotalCount(query),
favoriteDao.getAllByType(ContentType.MOVIE.name),
playbackHistoryDao.getByProvider(query.providerId)
- ) { movies, favorites, history ->
- val favoriteIds = favorites
- .asSequence()
+ ) { movies, totalCount, favorites, history ->
+ val favoriteIds = favorites
+ .asSequence()
.filter { it.groupId == null }
.map { it.contentId }
.toSet()
@@ -259,7 +276,7 @@ class MovieRepositoryImpl @Inject constructor(
PagedResult(
items = browsed.drop(query.offset).take(query.limit),
- totalCount = browsed.size,
+ totalCount = totalCount,
offset = query.offset,
limit = query.limit
)
@@ -269,13 +286,13 @@ class MovieRepositoryImpl @Inject constructor(
}
override fun searchMovies(providerId: Long, query: String): Flow<List<Movie>> =
- query.toFtsPrefixQuery().let { ftsQuery ->
- if (ftsQuery.isBlank()) {
+ query.trim().takeIf { it.length >= MIN_SEARCH_QUERY_LENGTH }?.toFtsPrefixQuery().let { ftsQuery ->
+ if (ftsQuery.isNullOrBlank()) {
flowOf(emptyList())
} else combine(
movieDao.search(providerId, ftsQuery, SEARCH_RESULT_LIMIT),
preferencesRepository.parentalControlLevel
- ) { entities: List<MovieEntity>, level: Int ->
+ ) { entities, level: Int ->
if (level == 2) {
entities.filter { !it.isUserProtected }
} else {
@@ -472,12 +489,222 @@ class MovieRepositoryImpl @Inject constructor(
return left.intersect(right).size.toFloat()
}
- private fun movieBrowseSource(providerId: Long, categoryId: Long?): Flow<List<Movie>> =
- if (categoryId == null) {
- getMovies(providerId)
+ private fun movieBrowseSource(query: LibraryBrowseQuery): Flow<List<Movie>> {
+ val normalizedSearch = query.searchQuery.trim()
+ val fetchLimit = browseFetchLimit(query)
+ val fastFlow = when {
+ normalizedSearch.length >= MIN_SEARCH_QUERY_LENGTH -> {
+ val ftsQuery = normalizedSearch.toFtsPrefixQuery() ?: return flowOf(emptyList())
+ query.categoryId?.let { categoryId ->
+ combine(
+ movieDao.searchByCategory(query.providerId, categoryId, ftsQuery, SEARCH_RESULT_LIMIT),
+ preferencesRepository.parentalControlLevel
+ ) { entities, level ->
+ if (level == 2) entities.filter { !it.isUserProtected } else entities
+ }.map { entities ->
+ entities.map { it.toDomain() }
+ .rankSearchResults(normalizedSearch) { it.name }
+ }
+ } ?: searchMovies(query.providerId, normalizedSearch)
+ }
+ 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) -> {
+ when {
+ query.sortBy == LibrarySortBy.RATING || query.filterBy.type == LibraryFilterType.TOP_RATED -> {
+ query.categoryId?.let { categoryId ->
+ flow {
+ ensureXtreamCategoryLoaded(query.providerId, categoryId)
+ emitAll(
+ combine(
+ movieDao.getTopRatedByCategoryPreview(query.providerId, categoryId, fetchLimit),
+ preferencesRepository.parentalControlLevel
+ ) { entities, level ->
+ if (level == 2) entities.filter { !it.isUserProtected } else entities
+ }.map { entities -> entities.map { it.toDomain() } }
+ )
+ }
+ } ?: getTopRatedPreview(query.providerId, fetchLimit)
+ }
+ query.sortBy == LibrarySortBy.RELEASE || query.sortBy == LibrarySortBy.UPDATED || query.filterBy.type == LibraryFilterType.RECENTLY_UPDATED -> {
+ query.categoryId?.let { categoryId ->
+ flow {
+ ensureXtreamCategoryLoaded(query.providerId, categoryId)
+ emitAll(
+ combine(
+ movieDao.getFreshByCategoryPreview(query.providerId, categoryId, fetchLimit),
+ preferencesRepository.parentalControlLevel
+ ) { entities, level ->
+ if (level == 2) entities.filter { !it.isUserProtected } else entities
+ }.map { entities -> entities.map { it.toDomain() } }
+ )
+ }
+ } ?: getFreshPreview(query.providerId, fetchLimit)
+ }
+ else -> {
+ query.categoryId?.let { categoryId ->
+ flow {
+ ensureXtreamCategoryLoaded(query.providerId, categoryId)
+ emitAll(
+ combine(
+ movieDao.getByCategoryPage(query.providerId, categoryId, fetchLimit, 0),
+ preferencesRepository.parentalControlLevel
+ ) { entities, level ->
+ if (level == 2) entities.filter { !it.isUserProtected } else entities
+ }.map { entities -> entities.map { it.toDomain() } }
+ )
+ }
+ } ?: combine(
+ movieDao.getByProviderPage(query.providerId, fetchLimit, 0),
+ preferencesRepository.parentalControlLevel
+ ) { entities, level ->
+ if (level == 2) entities.filter { !it.isUserProtected } else entities
+ }.map { entities -> entities.map { it.toDomain() } }
+ }
+ }
+ }
+ normalizedSearch.isBlank() &&
+ query.filterBy.type == LibraryFilterType.FAVORITES &&
+ query.sortBy in setOf(LibrarySortBy.LIBRARY, LibrarySortBy.TITLE) -> {
+ query.categoryId?.let { categoryId ->
+ flow {
+ ensureXtreamCategoryLoaded(query.providerId, categoryId)
+ emitAll(
+ combine(
+ movieDao.getFavoritesByCategoryPage(query.providerId, categoryId, fetchLimit, 0),
+ preferencesRepository.parentalControlLevel
+ ) { entities, level ->
+ if (level == 2) entities.filter { !it.isUserProtected } else entities
+ }.map { entities -> entities.map { it.toDomain() } }
+ )
+ }
+ } ?: combine(
+ movieDao.getFavoritesByProviderPage(query.providerId, fetchLimit, 0),
+ preferencesRepository.parentalControlLevel
+ ) { entities, level ->
+ if (level == 2) entities.filter { !it.isUserProtected } else entities
+ }.map { entities -> entities.map { it.toDomain() } }
+ }
+ normalizedSearch.isBlank() &&
+ query.filterBy.type == LibraryFilterType.IN_PROGRESS &&
+ query.sortBy in setOf(LibrarySortBy.LIBRARY, LibrarySortBy.TITLE) -> {
+ query.categoryId?.let { categoryId ->
+ flow {
+ ensureXtreamCategoryLoaded(query.providerId, categoryId)
+ emitAll(
+ combine(
+ movieDao.getInProgressByCategoryPage(query.providerId, categoryId, fetchLimit, 0),
+ preferencesRepository.parentalControlLevel
+ ) { entities, level ->
+ if (level == 2) entities.filter { !it.isUserProtected } else entities
+ }.map { entities -> entities.map { it.toDomain() } }
+ )
+ }
+ } ?: combine(
+ movieDao.getInProgressByProviderPage(query.providerId, fetchLimit, 0),
+ preferencesRepository.parentalControlLevel
+ ) { entities, level ->
+ if (level == 2) entities.filter { !it.isUserProtected } else entities
+ }.map { entities -> entities.map { it.toDomain() } }
+ }
+ normalizedSearch.isBlank() &&
+ query.filterBy.type == LibraryFilterType.UNWATCHED &&
+ query.sortBy in setOf(LibrarySortBy.LIBRARY, LibrarySortBy.TITLE) -> {
+ query.categoryId?.let { categoryId ->
+ flow {
+ ensureXtreamCategoryLoaded(query.providerId, categoryId)
+ emitAll(
+ combine(
+ movieDao.getUnwatchedByCategoryPage(query.providerId, categoryId, fetchLimit, 0),
+ preferencesRepository.parentalControlLevel
+ ) { entities, level ->
+ if (level == 2) entities.filter { !it.isUserProtected } else entities
+ }.map { entities -> entities.map { it.toDomain() } }
+ )
+ }
+ } ?: combine(
+ movieDao.getUnwatchedByProviderPage(query.providerId, fetchLimit, 0),
+ preferencesRepository.parentalControlLevel
+ ) { entities, level ->
+ if (level == 2) entities.filter { !it.isUserProtected } else entities
+ }.map { entities -> entities.map { it.toDomain() } }
+ }
+ normalizedSearch.isBlank() &&
+ query.filterBy.type == LibraryFilterType.ALL &&
+ query.sortBy == LibrarySortBy.WATCH_COUNT -> {
+ query.categoryId?.let { categoryId ->
+ flow {
+ ensureXtreamCategoryLoaded(query.providerId, categoryId)
+ emitAll(
+ combine(
+ movieDao.getByWatchCountCategoryPage(query.providerId, categoryId, fetchLimit, 0),
+ preferencesRepository.parentalControlLevel
+ ) { entities, level ->
+ if (level == 2) entities.filter { !it.isUserProtected } else entities
+ }.map { entities -> entities.map { it.toDomain() } }
+ )
+ }
+ } ?: combine(
+ movieDao.getByWatchCountProviderPage(query.providerId, fetchLimit, 0),
+ preferencesRepository.parentalControlLevel
+ ) { entities, level ->
+ if (level == 2) entities.filter { !it.isUserProtected } else entities
+ }.map { entities -> entities.map { it.toDomain() } }
+ }
+ else -> null
+ }
+
+ val categoryId = query.categoryId
+ return fastFlow ?: if (categoryId == null) {
+ getMovies(query.providerId)
} else {
- getMoviesByCategory(providerId, categoryId)
+ getMoviesByCategory(query.providerId, categoryId)
}
+ }
+
+ private fun movieBrowseTotalCount(query: LibraryBrowseQuery): Flow<Int> {
+ val normalizedSearch = query.searchQuery.trim()
+ return when {
+ normalizedSearch.length >= MIN_SEARCH_QUERY_LENGTH -> movieBrowseSource(query).map { it.size }
+ normalizedSearch.isBlank() &&
+ query.filterBy.type == LibraryFilterType.FAVORITES &&
+ query.sortBy in setOf(LibrarySortBy.LIBRARY, LibrarySortBy.TITLE) -> {
+ query.categoryId?.let { categoryId ->
+ movieDao.getFavoriteCountByCategory(query.providerId, categoryId)
+ } ?: movieDao.getFavoriteCountByProvider(query.providerId)
+ }
+ normalizedSearch.isBlank() &&
+ query.filterBy.type == LibraryFilterType.IN_PROGRESS &&
+ query.sortBy in setOf(LibrarySortBy.LIBRARY, LibrarySortBy.TITLE) -> {
+ query.categoryId?.let { categoryId ->
+ movieDao.getInProgressCountByCategory(query.providerId, categoryId)
+ } ?: movieDao.getInProgressCountByProvider(query.providerId)
+ }
+ normalizedSearch.isBlank() &&
+ query.filterBy.type == LibraryFilterType.UNWATCHED &&
+ query.sortBy in setOf(LibrarySortBy.LIBRARY, LibrarySortBy.TITLE) -> {
+ query.categoryId?.let { categoryId ->
+ movieDao.getUnwatchedCountByCategory(query.providerId, categoryId)
+ } ?: movieDao.getUnwatchedCountByProvider(query.providerId)
+ }
+ normalizedSearch.isBlank() &&
+ query.filterBy.type == LibraryFilterType.ALL &&
+ query.sortBy == LibrarySortBy.WATCH_COUNT -> {
+ query.categoryId?.let { categoryId ->
+ movieDao.getCountByCategory(query.providerId, categoryId)
+ } ?: movieDao.getCount(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 ->
+ movieDao.getCountByCategory(query.providerId, categoryId)
+ } ?: movieDao.getCount(query.providerId)
+ }
+ else -> movieBrowseSource(query).map { it.size }
+ }
+ }
+
+ private fun browseFetchLimit(query: LibraryBrowseQuery): Int =
+ (query.offset + query.limit + BROWSE_WINDOW_BUFFER).coerceAtMost(SEARCH_RESULT_LIMIT)
private fun applyMovieBrowseQuery(
movies: List<Movie>,
@@ -520,7 +747,7 @@ class MovieRepositoryImpl @Inject constructor(
private fun movieMatchesSearch(movie: Movie, searchQuery: String): Boolean {
val normalizedQuery = searchQuery.trim().lowercase()
if (normalizedQuery.isBlank()) return true
- return sequenceOf(movie.name, movie.plot, movie.genre, movie.cast, movie.director, movie.categoryName)
+ return sequenceOf(movie.name, movie.genre, movie.categoryName, movie.year)
.filterNotNull()
.any { value -> value.lowercase().contains(normalizedQuery) }
}
diff --git a/data/src/main/java/com/streamvault/data/repository/PlaybackHistoryRepositoryImpl.kt b/data/src/main/java/com/streamvault/data/repository/PlaybackHistoryRepositoryImpl.kt
index 488f9b10..f4f83d30 100644
--- a/data/src/main/java/com/streamvault/data/repository/PlaybackHistoryRepositoryImpl.kt
+++ b/data/src/main/java/com/streamvault/data/repository/PlaybackHistoryRepositoryImpl.kt
@@ -10,8 +10,6 @@ import com.streamvault.domain.model.PlaybackHistory
import com.streamvault.domain.model.PlaybackWatchedStatus
import com.streamvault.domain.model.Result
import com.streamvault.domain.repository.PlaybackHistoryRepository
-import com.streamvault.domain.util.DEFAULT_PLAYBACK_COMPLETION_THRESHOLD
-import com.streamvault.domain.util.isPlaybackComplete
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map
@@ -188,3 +186,16 @@ class PlaybackHistoryRepositoryImpl @Inject constructor(
}
}
}
+
+private const val DEFAULT_PLAYBACK_COMPLETION_THRESHOLD = 0.95f
+
+private fun isPlaybackComplete(
+ progressMs: Long,
+ totalDurationMs: Long,
+ threshold: Float = DEFAULT_PLAYBACK_COMPLETION_THRESHOLD
+): Boolean {
+ if (progressMs <= 0L || totalDurationMs <= 0L) {
+ return false
+ }
+ return progressMs >= (totalDurationMs * threshold).toLong()
+}
diff --git a/data/src/main/java/com/streamvault/data/repository/ProviderRepositoryImpl.kt b/data/src/main/java/com/streamvault/data/repository/ProviderRepositoryImpl.kt
index f0fb94b2..95e8a537 100644
--- a/data/src/main/java/com/streamvault/data/repository/ProviderRepositoryImpl.kt
+++ b/data/src/main/java/com/streamvault/data/repository/ProviderRepositoryImpl.kt
@@ -28,7 +28,6 @@ class ProviderRepositoryImpl @Inject constructor(
private val syncManager: SyncManager,
private val syncMetadataRepository: SyncMetadataRepository
) : ProviderRepository {
-
override fun getProviders(): Flow<List<Provider>> =
providerDao.getAll().map { entities -> entities.map { it.toPublicDomain() } }
@@ -56,6 +55,7 @@ class ProviderRepositoryImpl @Inject constructor(
// ProgramEntity still has no provider FK, so it requires explicit cleanup.
programDao.deleteByProvider(id)
providerDao.delete(id)
+ syncManager.onProviderDeleted(id)
Result.success(Unit)
} catch (e: Exception) {
Result.error("Failed to delete provider: ${e.message}", e)
@@ -123,7 +123,6 @@ 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) {
@@ -136,12 +135,8 @@ class ProviderRepositoryImpl @Inject constructor(
}
is Result.Error -> {
updateProviderSyncStatus(providerData.id, ProviderStatus.ERROR)
- if (existingProvider == null) {
- // Rollback: if this was a new provider and initial sync failed, don't leave it in the database
- providerDao.delete(providerData.id)
- }
Result.error(
- "Provider authenticated, but initial sync failed: ${syncResult.message}",
+ "Provider login succeeded, but initial sync failed. The provider was saved and can be retried from Settings: ${syncResult.message}",
syncResult.exception
)
}
@@ -203,7 +198,6 @@ class ProviderRepositoryImpl @Inject constructor(
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) {
@@ -216,12 +210,8 @@ class ProviderRepositoryImpl @Inject constructor(
}
is Result.Error -> {
updateProviderSyncStatus(providerData.id, ProviderStatus.ERROR)
- if (existingProvider == null) {
- // Rollback: if this was a new provider and initial sync failed, don't leave it in the database
- providerDao.delete(providerData.id)
- }
Result.error(
- "Playlist saved, but initial sync failed: ${syncResult.message}",
+ "Playlist saved, but initial sync failed. The provider was saved and can be retried from Settings: ${syncResult.message}",
syncResult.exception
)
}
diff --git a/data/src/main/java/com/streamvault/data/repository/SeriesRepositoryImpl.kt b/data/src/main/java/com/streamvault/data/repository/SeriesRepositoryImpl.kt
index fc58657b..ad7f86ea 100644
--- a/data/src/main/java/com/streamvault/data/repository/SeriesRepositoryImpl.kt
+++ b/data/src/main/java/com/streamvault/data/repository/SeriesRepositoryImpl.kt
@@ -42,7 +42,9 @@ class SeriesRepositoryImpl @Inject constructor(
private val xtreamStreamUrlResolver: XtreamStreamUrlResolver
) : SeriesRepository {
private companion object {
- const val SEARCH_RESULT_LIMIT = 320
+ const val SEARCH_RESULT_LIMIT = 200
+ const val MIN_SEARCH_QUERY_LENGTH = 2
+ const val BROWSE_WINDOW_BUFFER = 80
}
private data class CachedXtreamProvider(
@@ -58,13 +60,13 @@ class SeriesRepositoryImpl @Inject constructor(
combine(
seriesDao.getByProvider(providerId),
preferencesRepository.parentalControlLevel
- ) { entities: List<SeriesEntity>, level: Int ->
+ ) { entities, level: Int ->
if (level == 2) {
entities.filter { !it.isUserProtected }
} else {
entities
}
- }.map { list: List<SeriesEntity> -> list.map { it.toDomain() } }
+ }.map { list -> list.map { it.toDomain() } }
override fun getSeriesByCategory(providerId: Long, categoryId: Long): Flow<List<Series>> =
flow {
@@ -73,13 +75,13 @@ class SeriesRepositoryImpl @Inject constructor(
combine(
seriesDao.getByCategory(providerId, categoryId),
preferencesRepository.parentalControlLevel
- ) { entities: List<SeriesEntity>, level: Int ->
+ ) { entities, level: Int ->
if (level == 2) {
entities.filter { !it.isUserProtected }
} else {
entities
}
- }.map { list: List<SeriesEntity> -> list.map { it.toDomain() } }
+ }.map { list -> list.map { it.toDomain() } }
)
}
@@ -94,13 +96,13 @@ class SeriesRepositoryImpl @Inject constructor(
combine(
seriesDao.getByCategoryPage(providerId, categoryId, limit, offset),
preferencesRepository.parentalControlLevel
- ) { entities: List<SeriesEntity>, level: Int ->
+ ) { entities, level: Int ->
if (level == 2) {
entities.filter { !it.isUserProtected }
} else {
entities
}
- }.map { list: List<SeriesEntity> -> list.map { it.toDomain() } }
+ }.map { list -> list.map { it.toDomain() } }
)
}
@@ -111,13 +113,13 @@ class SeriesRepositoryImpl @Inject constructor(
combine(
seriesDao.getByCategoryPreview(providerId, categoryId, limit),
preferencesRepository.parentalControlLevel
- ) { entities: List<SeriesEntity>, level: Int ->
+ ) { entities, level: Int ->
if (level == 2) {
entities.filter { !it.isUserProtected }
} else {
entities
}
- }.map { list: List<SeriesEntity> -> list.map { it.toDomain() } }
+ }.map { list -> list.map { it.toDomain() } }
)
}
@@ -150,25 +152,25 @@ class SeriesRepositoryImpl @Inject constructor(
combine(
seriesDao.getTopRatedPreview(providerId, limit),
preferencesRepository.parentalControlLevel
- ) { entities: List<SeriesEntity>, level: Int ->
+ ) { entities, level: Int ->
if (level == 2) {
entities.filter { !it.isUserProtected }
} else {
entities
}
- }.map { list: List<SeriesEntity> -> list.map { it.toDomain() } }
+ }.map { list -> list.map { it.toDomain() } }
override fun getFreshPreview(providerId: Long, limit: Int): Flow<List<Series>> =
combine(
seriesDao.getFreshPreview(providerId, limit),
preferencesRepository.parentalControlLevel
- ) { entities: List<SeriesEntity>, level: Int ->
+ ) { entities, level: Int ->
if (level == 2) {
entities.filter { !it.isUserProtected }
} else {
entities
}
- }.map { list: List<SeriesEntity> -> list.map { it.toDomain() } }
+ }.map { list -> list.map { it.toDomain() } }
override fun getSeriesByIds(ids: List<Long>): Flow<List<Series>> =
seriesDao.getByIds(ids).map { entities -> entities.map { it.toDomain() } }
@@ -199,10 +201,11 @@ class SeriesRepositoryImpl @Inject constructor(
query.categoryId?.let { ensureXtreamCategoryLoaded(query.providerId, it) }
emitAll(
combine(
- seriesBrowseSource(query.providerId, query.categoryId),
+ seriesBrowseSource(query),
+ seriesBrowseTotalCount(query),
favoriteDao.getAllByType(ContentType.SERIES.name),
playbackHistoryDao.getByProvider(query.providerId)
- ) { series, favorites, history ->
+ ) { series, totalCount, favorites, history ->
val favoriteIds = favorites
.asSequence()
.filter { it.groupId == null }
@@ -235,7 +238,7 @@ class SeriesRepositoryImpl @Inject constructor(
PagedResult(
items = browsed.drop(query.offset).take(query.limit),
- totalCount = browsed.size,
+ totalCount = totalCount,
offset = query.offset,
limit = query.limit
)
@@ -245,19 +248,19 @@ class SeriesRepositoryImpl @Inject constructor(
}
override fun searchSeries(providerId: Long, query: String): Flow<List<Series>> =
- query.toFtsPrefixQuery().let { ftsQuery ->
- if (ftsQuery.isBlank()) {
+ query.trim().takeIf { it.length >= MIN_SEARCH_QUERY_LENGTH }?.toFtsPrefixQuery().let { ftsQuery ->
+ if (ftsQuery.isNullOrBlank()) {
flowOf(emptyList())
} else combine(
seriesDao.search(providerId, ftsQuery, SEARCH_RESULT_LIMIT),
preferencesRepository.parentalControlLevel
- ) { entities: List<SeriesEntity>, level: Int ->
+ ) { entities, level: Int ->
if (level == 2) {
entities.filter { !it.isUserProtected }
} else {
entities
}
- }.map { list: List<SeriesEntity> ->
+ }.map { list ->
list.map { it.toDomain() }
.rankSearchResults(query) { it.name }
}
@@ -374,11 +377,7 @@ class SeriesRepositoryImpl @Inject constructor(
}
is Result.Error -> {
val localSeries = buildSeriesWithPersistedEpisodes(seriesEntity)
- if (localSeries.seasons.isNotEmpty()) {
- Result.success(localSeries)
- } else {
- Result.error(remoteResult.message, remoteResult.exception)
- }
+ Result.success(localSeries)
}
is Result.Loading -> Result.error("Unexpected loading state")
}
@@ -430,12 +429,222 @@ class SeriesRepositoryImpl @Inject constructor(
return seriesEntity.toDomain().copy(seasons = seasons)
}
- private fun seriesBrowseSource(providerId: Long, categoryId: Long?): Flow<List<Series>> =
- if (categoryId == null) {
- getSeries(providerId)
+ private fun seriesBrowseSource(query: LibraryBrowseQuery): Flow<List<Series>> {
+ val normalizedSearch = query.searchQuery.trim()
+ val fetchLimit = browseFetchLimit(query)
+ val fastFlow = when {
+ normalizedSearch.length >= MIN_SEARCH_QUERY_LENGTH -> {
+ val ftsQuery = normalizedSearch.toFtsPrefixQuery() ?: return flowOf(emptyList())
+ query.categoryId?.let { categoryId ->
+ combine(
+ seriesDao.searchByCategory(query.providerId, categoryId, ftsQuery, SEARCH_RESULT_LIMIT),
+ preferencesRepository.parentalControlLevel
+ ) { entities, level ->
+ if (level == 2) entities.filter { !it.isUserProtected } else entities
+ }.map { entities ->
+ entities.map { it.toDomain() }
+ .rankSearchResults(normalizedSearch) { it.name }
+ }
+ } ?: searchSeries(query.providerId, normalizedSearch)
+ }
+ 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) -> {
+ when {
+ query.sortBy == LibrarySortBy.RATING || query.filterBy.type == LibraryFilterType.TOP_RATED -> {
+ query.categoryId?.let { categoryId ->
+ flow {
+ ensureXtreamCategoryLoaded(query.providerId, categoryId)
+ emitAll(
+ combine(
+ seriesDao.getTopRatedByCategoryPreview(query.providerId, categoryId, fetchLimit),
+ preferencesRepository.parentalControlLevel
+ ) { entities, level ->
+ if (level == 2) entities.filter { !it.isUserProtected } else entities
+ }.map { entities -> entities.map { it.toDomain() } }
+ )
+ }
+ } ?: getTopRatedPreview(query.providerId, fetchLimit)
+ }
+ query.sortBy == LibrarySortBy.RELEASE || query.sortBy == LibrarySortBy.UPDATED || query.filterBy.type == LibraryFilterType.RECENTLY_UPDATED -> {
+ query.categoryId?.let { categoryId ->
+ flow {
+ ensureXtreamCategoryLoaded(query.providerId, categoryId)
+ emitAll(
+ combine(
+ seriesDao.getFreshByCategoryPreview(query.providerId, categoryId, fetchLimit),
+ preferencesRepository.parentalControlLevel
+ ) { entities, level ->
+ if (level == 2) entities.filter { !it.isUserProtected } else entities
+ }.map { entities -> entities.map { it.toDomain() } }
+ )
+ }
+ } ?: getFreshPreview(query.providerId, fetchLimit)
+ }
+ else -> {
+ query.categoryId?.let { categoryId ->
+ flow {
+ ensureXtreamCategoryLoaded(query.providerId, categoryId)
+ emitAll(
+ combine(
+ seriesDao.getByCategoryPage(query.providerId, categoryId, fetchLimit, 0),
+ preferencesRepository.parentalControlLevel
+ ) { entities, level ->
+ if (level == 2) entities.filter { !it.isUserProtected } else entities
+ }.map { entities -> entities.map { it.toDomain() } }
+ )
+ }
+ } ?: combine(
+ seriesDao.getByProviderPage(query.providerId, fetchLimit, 0),
+ preferencesRepository.parentalControlLevel
+ ) { entities, level ->
+ if (level == 2) entities.filter { !it.isUserProtected } else entities
+ }.map { entities -> entities.map { it.toDomain() } }
+ }
+ }
+ }
+ normalizedSearch.isBlank() &&
+ query.filterBy.type == LibraryFilterType.FAVORITES &&
+ query.sortBy in setOf(LibrarySortBy.LIBRARY, LibrarySortBy.TITLE) -> {
+ query.categoryId?.let { categoryId ->
+ flow {
+ ensureXtreamCategoryLoaded(query.providerId, categoryId)
+ emitAll(
+ combine(
+ seriesDao.getFavoritesByCategoryPage(query.providerId, categoryId, fetchLimit, 0),
+ preferencesRepository.parentalControlLevel
+ ) { entities, level ->
+ if (level == 2) entities.filter { !it.isUserProtected } else entities
+ }.map { entities -> entities.map { it.toDomain() } }
+ )
+ }
+ } ?: combine(
+ seriesDao.getFavoritesByProviderPage(query.providerId, fetchLimit, 0),
+ preferencesRepository.parentalControlLevel
+ ) { entities, level ->
+ if (level == 2) entities.filter { !it.isUserProtected } else entities
+ }.map { entities -> entities.map { it.toDomain() } }
+ }
+ normalizedSearch.isBlank() &&
+ query.filterBy.type == LibraryFilterType.IN_PROGRESS &&
+ query.sortBy in setOf(LibrarySortBy.LIBRARY, LibrarySortBy.TITLE) -> {
+ query.categoryId?.let { categoryId ->
+ flow {
+ ensureXtreamCategoryLoaded(query.providerId, categoryId)
+ emitAll(
+ combine(
+ seriesDao.getInProgressByCategoryPage(query.providerId, categoryId, fetchLimit, 0),
+ preferencesRepository.parentalControlLevel
+ ) { entities, level ->
+ if (level == 2) entities.filter { !it.isUserProtected } else entities
+ }.map { entities -> entities.map { it.toDomain() } }
+ )
+ }
+ } ?: combine(
+ seriesDao.getInProgressByProviderPage(query.providerId, fetchLimit, 0),
+ preferencesRepository.parentalControlLevel
+ ) { entities, level ->
+ if (level == 2) entities.filter { !it.isUserProtected } else entities
+ }.map { entities -> entities.map { it.toDomain() } }
+ }
+ normalizedSearch.isBlank() &&
+ query.filterBy.type == LibraryFilterType.UNWATCHED &&
+ query.sortBy in setOf(LibrarySortBy.LIBRARY, LibrarySortBy.TITLE) -> {
+ query.categoryId?.let { categoryId ->
+ flow {
+ ensureXtreamCategoryLoaded(query.providerId, categoryId)
+ emitAll(
+ combine(
+ seriesDao.getUnwatchedByCategoryPage(query.providerId, categoryId, fetchLimit, 0),
+ preferencesRepository.parentalControlLevel
+ ) { entities, level ->
+ if (level == 2) entities.filter { !it.isUserProtected } else entities
+ }.map { entities -> entities.map { it.toDomain() } }
+ )
+ }
+ } ?: combine(
+ seriesDao.getUnwatchedByProviderPage(query.providerId, fetchLimit, 0),
+ preferencesRepository.parentalControlLevel
+ ) { entities, level ->
+ if (level == 2) entities.filter { !it.isUserProtected } else entities
+ }.map { entities -> entities.map { it.toDomain() } }
+ }
+ normalizedSearch.isBlank() &&
+ query.filterBy.type == LibraryFilterType.ALL &&
+ query.sortBy == LibrarySortBy.WATCH_COUNT -> {
+ query.categoryId?.let { categoryId ->
+ flow {
+ ensureXtreamCategoryLoaded(query.providerId, categoryId)
+ emitAll(
+ combine(
+ seriesDao.getByWatchCountCategoryPage(query.providerId, categoryId, fetchLimit, 0),
+ preferencesRepository.parentalControlLevel
+ ) { entities, level ->
+ if (level == 2) entities.filter { !it.isUserProtected } else entities
+ }.map { entities -> entities.map { it.toDomain() } }
+ )
+ }
+ } ?: combine(
+ seriesDao.getByWatchCountProviderPage(query.providerId, fetchLimit, 0),
+ preferencesRepository.parentalControlLevel
+ ) { entities, level ->
+ if (level == 2) entities.filter { !it.isUserProtected } else entities
+ }.map { entities -> entities.map { it.toDomain() } }
+ }
+ else -> null
+ }
+
+ val categoryId = query.categoryId
+ return fastFlow ?: if (categoryId == null) {
+ getSeries(query.providerId)
} else {
- getSeriesByCategory(providerId, categoryId)
+ getSeriesByCategory(query.providerId, categoryId)
}
+ }
+
+ private fun seriesBrowseTotalCount(query: LibraryBrowseQuery): Flow<Int> {
+ val normalizedSearch = query.searchQuery.trim()
+ return when {
+ normalizedSearch.length >= MIN_SEARCH_QUERY_LENGTH -> seriesBrowseSource(query).map { it.size }
+ normalizedSearch.isBlank() &&
+ query.filterBy.type == LibraryFilterType.FAVORITES &&
+ query.sortBy in setOf(LibrarySortBy.LIBRARY, LibrarySortBy.TITLE) -> {
+ query.categoryId?.let { categoryId ->
+ seriesDao.getFavoriteCountByCategory(query.providerId, categoryId)
+ } ?: seriesDao.getFavoriteCountByProvider(query.providerId)
+ }
+ normalizedSearch.isBlank() &&
+ query.filterBy.type == LibraryFilterType.IN_PROGRESS &&
+ query.sortBy in setOf(LibrarySortBy.LIBRARY, LibrarySortBy.TITLE) -> {
+ query.categoryId?.let { categoryId ->
+ seriesDao.getInProgressCountByCategory(query.providerId, categoryId)
+ } ?: seriesDao.getInProgressCountByProvider(query.providerId)
+ }
+ normalizedSearch.isBlank() &&
+ query.filterBy.type == LibraryFilterType.UNWATCHED &&
+ query.sortBy in setOf(LibrarySortBy.LIBRARY, LibrarySortBy.TITLE) -> {
+ query.categoryId?.let { categoryId ->
+ seriesDao.getUnwatchedCountByCategory(query.providerId, categoryId)
+ } ?: seriesDao.getUnwatchedCountByProvider(query.providerId)
+ }
+ normalizedSearch.isBlank() &&
+ query.filterBy.type == LibraryFilterType.ALL &&
+ query.sortBy == LibrarySortBy.WATCH_COUNT -> {
+ query.categoryId?.let { categoryId ->
+ seriesDao.getCountByCategory(query.providerId, categoryId)
+ } ?: seriesDao.getCount(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 ->
+ seriesDao.getCountByCategory(query.providerId, categoryId)
+ } ?: seriesDao.getCount(query.providerId)
+ }
+ else -> seriesBrowseSource(query).map { it.size }
+ }
+ }
+
+ private fun browseFetchLimit(query: LibraryBrowseQuery): Int =
+ (query.offset + query.limit + BROWSE_WINDOW_BUFFER).coerceAtMost(SEARCH_RESULT_LIMIT)
private fun applySeriesBrowseQuery(
series: List<Series>,
@@ -476,7 +685,7 @@ class SeriesRepositoryImpl @Inject constructor(
private fun seriesMatchesSearch(series: Series, searchQuery: String): Boolean {
val normalizedQuery = searchQuery.trim().lowercase()
if (normalizedQuery.isBlank()) return true
- return sequenceOf(series.name, series.plot, series.genre, series.cast, series.director, series.categoryName)
+ return sequenceOf(series.name, series.genre, series.categoryName)
.filterNotNull()
.any { value -> value.lowercase().contains(normalizedQuery) }
}
diff --git a/data/src/main/java/com/streamvault/data/sync.zip b/data/src/main/java/com/streamvault/data/sync.zip
new file mode 100644
index 00000000..bcc2a4f8
Binary files /dev/null and b/data/src/main/java/com/streamvault/data/sync.zip differ
diff --git a/data/src/main/java/com/streamvault/data/sync/SyncCatalogStore.kt b/data/src/main/java/com/streamvault/data/sync/SyncCatalogStore.kt
new file mode 100644
index 00000000..335a4d68
--- /dev/null
+++ b/data/src/main/java/com/streamvault/data/sync/SyncCatalogStore.kt
@@ -0,0 +1,560 @@
+package com.streamvault.data.sync
+
+import com.streamvault.data.local.DatabaseTransactionRunner
+import com.streamvault.data.local.dao.CatalogSyncDao
+import com.streamvault.data.local.dao.MovieDao
+import com.streamvault.data.local.entity.CategoryEntity
+import com.streamvault.data.local.entity.CategoryImportStageEntity
+import com.streamvault.data.local.entity.ChannelEntity
+import com.streamvault.data.local.entity.ChannelImportStageEntity
+import com.streamvault.data.local.entity.MovieEntity
+import com.streamvault.data.local.entity.MovieImportStageEntity
+import com.streamvault.data.local.entity.SeriesEntity
+import com.streamvault.data.local.entity.SeriesImportStageEntity
+import java.net.URI
+import java.security.MessageDigest
+import java.util.concurrent.atomic.AtomicLong
+
+internal class SyncCatalogStore(
+ private val movieDao: MovieDao,
+ private val catalogSyncDao: CatalogSyncDao,
+ private val transactionRunner: DatabaseTransactionRunner
+) {
+ private val sessionIds = AtomicLong(System.currentTimeMillis())
+ private val digest = ThreadLocal.withInitial { MessageDigest.getInstance("SHA-256") }
+
+ fun newSessionId(): Long = sessionIds.incrementAndGet()
+
+ suspend fun replaceLiveCatalog(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") }
+ applyChannels(providerId, sessionId)
+ }
+ return stagedChannels.size
+ } finally {
+ clearSession(providerId, sessionId)
+ }
+ }
+
+ suspend fun replaceMovieCatalog(providerId: Long, categories: List<CategoryEntity>?, movies: Sequence<MovieEntity>): Int {
+ val sessionId = newSessionId()
+ try {
+ clearProviderStaging(providerId)
+ categories?.let { stageCategories(providerId, sessionId, it) }
+ val acceptedCount = stageMovieSequence(providerId, sessionId, movies)
+ transactionRunner.inTransaction {
+ categories?.let { applyCategories(providerId, sessionId, "MOVIE") }
+ applyMovies(providerId, sessionId)
+ }
+ movieDao.restoreWatchProgress(providerId)
+ return acceptedCount
+ } finally {
+ clearSession(providerId, sessionId)
+ }
+ }
+
+ suspend fun replaceSeriesCatalog(providerId: Long, categories: List<CategoryEntity>?, series: Sequence<SeriesEntity>): Int {
+ val sessionId = newSessionId()
+ try {
+ clearProviderStaging(providerId)
+ categories?.let { stageCategories(providerId, sessionId, it) }
+ val acceptedCount = stageSeriesSequence(providerId, sessionId, series)
+ transactionRunner.inTransaction {
+ categories?.let { applyCategories(providerId, sessionId, "SERIES") }
+ applySeries(providerId, sessionId)
+ }
+ return acceptedCount
+ } finally {
+ clearSession(providerId, sessionId)
+ }
+ }
+
+ suspend fun applyStagedMovieCatalog(providerId: Long, sessionId: Long, categories: List<CategoryEntity>?) {
+ try {
+ transactionRunner.inTransaction {
+ categories?.let { stageCategories(providerId, sessionId, it) }
+ categories?.let { applyCategories(providerId, sessionId, "MOVIE") }
+ applyMovies(providerId, sessionId)
+ }
+ movieDao.restoreWatchProgress(providerId)
+ } finally {
+ clearSession(providerId, sessionId)
+ }
+ }
+
+ suspend fun applyStagedSeriesCatalog(providerId: Long, sessionId: Long, categories: List<CategoryEntity>?) {
+ try {
+ transactionRunner.inTransaction {
+ categories?.let { stageCategories(providerId, sessionId, it) }
+ categories?.let { applyCategories(providerId, sessionId, "SERIES") }
+ applySeries(providerId, sessionId)
+ }
+ } finally {
+ clearSession(providerId, sessionId)
+ }
+ }
+
+ suspend fun replaceCategories(providerId: Long, type: String, categories: List<CategoryEntity>) {
+ val sessionId = newSessionId()
+ try {
+ clearProviderStaging(providerId)
+ stageCategories(providerId, sessionId, categories)
+ transactionRunner.inTransaction {
+ applyCategories(providerId, sessionId, type)
+ }
+ } finally {
+ clearSession(providerId, sessionId)
+ }
+ }
+
+ suspend fun stageChannelBatch(providerId: Long, sessionId: Long, channels: List<ChannelEntity>) {
+ insertStageRows(buildChannelStages(providerId, sessionId, channels), catalogSyncDao::insertChannelStages)
+ }
+
+ suspend fun stageMovieBatch(providerId: Long, sessionId: Long, movies: List<MovieEntity>) {
+ insertStageRows(buildMovieStages(providerId, sessionId, movies), catalogSyncDao::insertMovieStages)
+ }
+
+ suspend fun stageSeriesBatch(providerId: Long, sessionId: Long, series: List<SeriesEntity>) {
+ insertStageRows(buildSeriesStages(providerId, sessionId, series), catalogSyncDao::insertSeriesStages)
+ }
+
+ suspend fun stageCategories(providerId: Long, sessionId: Long, categories: List<CategoryEntity>) {
+ val rows = categories
+ .distinctBy { it.categoryId to it.type }
+ .map { category ->
+ CategoryImportStageEntity(
+ sessionId = sessionId,
+ providerId = providerId,
+ categoryId = category.categoryId,
+ name = category.name,
+ parentId = category.parentId,
+ type = category.type,
+ isAdult = category.isAdult,
+ syncFingerprint = categoryFingerprint(category)
+ )
+ }
+ insertStageRows(rows, catalogSyncDao::insertCategoryStages)
+ }
+
+ suspend fun finalizeStagedImport(
+ providerId: Long,
+ sessionId: Long,
+ liveCategories: List<CategoryEntity>?,
+ movieCategories: List<CategoryEntity>?,
+ includeLive: Boolean,
+ includeMovies: Boolean
+ ) {
+ transactionRunner.inTransaction {
+ if (includeLive) {
+ stageCategories(providerId, sessionId, liveCategories.orEmpty())
+ applyCategories(providerId, sessionId, "LIVE")
+ applyChannels(providerId, sessionId)
+ }
+ if (includeMovies) {
+ stageCategories(providerId, sessionId, movieCategories.orEmpty())
+ applyCategories(providerId, sessionId, "MOVIE")
+ applyMovies(providerId, sessionId)
+ }
+ }
+ if (includeMovies) {
+ movieDao.restoreWatchProgress(providerId)
+ }
+ }
+
+ suspend fun discardStagedImport(providerId: Long, sessionId: Long) {
+ clearSession(providerId, sessionId)
+ }
+
+ suspend fun clearProviderStaging(providerId: Long) {
+ catalogSyncDao.clearProviderChannelStages(providerId)
+ catalogSyncDao.clearProviderMovieStages(providerId)
+ catalogSyncDao.clearProviderSeriesStages(providerId)
+ catalogSyncDao.clearProviderCategoryStages(providerId)
+ }
+
+ private suspend fun applyCategories(providerId: Long, sessionId: Long, type: String) {
+ catalogSyncDao.updateChangedCategoriesFromStage(providerId, sessionId, type)
+ catalogSyncDao.insertMissingCategoriesFromStage(providerId, sessionId, type)
+ catalogSyncDao.deleteStaleCategoriesForStage(providerId, sessionId, type)
+ }
+
+ private suspend fun applyChannels(providerId: Long, sessionId: Long) {
+ catalogSyncDao.updateChangedChannelsFromStage(providerId, sessionId)
+ catalogSyncDao.insertMissingChannelsFromStage(providerId, sessionId)
+ catalogSyncDao.deleteStaleChannelsForStage(providerId, sessionId)
+ }
+
+ private suspend fun applyMovies(providerId: Long, sessionId: Long) {
+ catalogSyncDao.updateChangedMoviesFromStage(providerId, sessionId)
+ catalogSyncDao.insertMissingMoviesFromStage(providerId, sessionId)
+ catalogSyncDao.deleteStaleMoviesForStage(providerId, sessionId)
+ }
+
+ private suspend fun applySeries(providerId: Long, sessionId: Long) {
+ catalogSyncDao.updateChangedSeriesFromStage(providerId, sessionId)
+ catalogSyncDao.insertMissingSeriesFromStage(providerId, sessionId)
+ catalogSyncDao.deleteStaleSeriesForStage(providerId, sessionId)
+ }
+
+ private suspend fun clearSession(providerId: Long, sessionId: Long) {
+ catalogSyncDao.clearChannelStages(providerId, sessionId)
+ catalogSyncDao.clearMovieStages(providerId, sessionId)
+ catalogSyncDao.clearSeriesStages(providerId, sessionId)
+ catalogSyncDao.clearCategoryStages(providerId, sessionId)
+ }
+
+ private fun buildChannelStages(
+ providerId: Long,
+ sessionId: Long,
+ channels: List<ChannelEntity>
+ ): List<ChannelImportStageEntity> {
+ return channels
+ .distinctBy { it.streamId }
+ .map { channel ->
+ ChannelImportStageEntity(
+ sessionId = sessionId,
+ providerId = providerId,
+ streamId = channel.streamId,
+ name = channel.name,
+ logoUrl = channel.logoUrl,
+ groupTitle = channel.groupTitle,
+ categoryId = channel.categoryId,
+ categoryName = channel.categoryName,
+ streamUrl = channel.streamUrl,
+ epgChannelId = channel.epgChannelId,
+ number = channel.number,
+ catchUpSupported = channel.catchUpSupported,
+ catchUpDays = channel.catchUpDays,
+ catchUpSource = channel.catchUpSource,
+ isAdult = channel.isAdult,
+ logicalGroupId = channel.logicalGroupId,
+ errorCount = channel.errorCount,
+ syncFingerprint = channelFingerprint(channel)
+ )
+ }
+ }
+
+ private fun buildMovieStages(
+ providerId: Long,
+ sessionId: Long,
+ movies: List<MovieEntity>
+ ): List<MovieImportStageEntity> {
+ return movies
+ .distinctBy { it.streamId }
+ .map { movie ->
+ 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 = movieFingerprint(movie)
+ )
+ }
+ }
+
+ private fun buildSeriesStages(
+ providerId: Long,
+ sessionId: Long,
+ series: List<SeriesEntity>
+ ): List<SeriesImportStageEntity> {
+ return series
+ .distinctBy { it.seriesId }
+ .map { item ->
+ SeriesImportStageEntity(
+ sessionId = sessionId,
+ providerId = providerId,
+ seriesId = item.seriesId,
+ name = item.name,
+ posterUrl = item.posterUrl,
+ backdropUrl = item.backdropUrl,
+ categoryId = item.categoryId,
+ categoryName = item.categoryName,
+ plot = item.plot,
+ cast = item.cast,
+ director = item.director,
+ genre = item.genre,
+ releaseDate = item.releaseDate,
+ rating = item.rating,
+ tmdbId = item.tmdbId,
+ youtubeTrailer = item.youtubeTrailer,
+ episodeRunTime = item.episodeRunTime,
+ lastModified = item.lastModified,
+ isAdult = item.isAdult,
+ syncFingerprint = seriesFingerprint(item)
+ )
+ }
+ }
+
+ private suspend fun stageMovieSequence(
+ providerId: Long,
+ sessionId: Long,
+ movies: Sequence<MovieEntity>
+ ): Int {
+ return stageDistinctRows(
+ items = movies,
+ keySelector = { movie -> movie.streamId },
+ stageBuilder = { movie -> movieStageEntity(providerId, sessionId, movie) },
+ insert = catalogSyncDao::insertMovieStages
+ )
+ }
+
+ private suspend fun stageSeriesSequence(
+ providerId: Long,
+ sessionId: Long,
+ series: Sequence<SeriesEntity>
+ ): Int {
+ return stageDistinctRows(
+ items = series,
+ keySelector = { item -> item.seriesId },
+ stageBuilder = { item -> seriesStageEntity(providerId, sessionId, item) },
+ insert = catalogSyncDao::insertSeriesStages
+ )
+ }
+
+ private suspend fun <T, K, S> stageDistinctRows(
+ items: Sequence<T>,
+ keySelector: (T) -> K,
+ stageBuilder: (T) -> S,
+ insert: suspend (List<S>) -> Unit
+ ): Int {
+ val seenKeys = HashSet<K>()
+ val batch = ArrayList<S>(STAGE_BATCH_SIZE)
+ var acceptedCount = 0
+
+ items.forEach { item ->
+ if (!seenKeys.add(keySelector(item))) {
+ return@forEach
+ }
+ batch += stageBuilder(item)
+ acceptedCount++
+ if (batch.size >= STAGE_BATCH_SIZE) {
+ insert(batch)
+ batch.clear()
+ }
+ }
+
+ if (batch.isNotEmpty()) {
+ insert(batch)
+ }
+
+ return acceptedCount
+ }
+
+ private suspend fun <T> insertStageRows(
+ rows: List<T>,
+ insert: suspend (List<T>) -> Unit
+ ) {
+ rows.chunked(STAGE_BATCH_SIZE).forEach { chunk ->
+ if (chunk.isNotEmpty()) {
+ insert(chunk)
+ }
+ }
+ }
+
+ private fun movieStageEntity(
+ providerId: Long,
+ sessionId: Long,
+ movie: MovieEntity
+ ): MovieImportStageEntity {
+ return 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 = movieFingerprint(movie)
+ )
+ }
+
+ private fun seriesStageEntity(
+ providerId: Long,
+ sessionId: Long,
+ item: SeriesEntity
+ ): SeriesImportStageEntity {
+ return SeriesImportStageEntity(
+ sessionId = sessionId,
+ providerId = providerId,
+ seriesId = item.seriesId,
+ name = item.name,
+ posterUrl = item.posterUrl,
+ backdropUrl = item.backdropUrl,
+ categoryId = item.categoryId,
+ categoryName = item.categoryName,
+ plot = item.plot,
+ cast = item.cast,
+ director = item.director,
+ genre = item.genre,
+ releaseDate = item.releaseDate,
+ rating = item.rating,
+ tmdbId = item.tmdbId,
+ youtubeTrailer = item.youtubeTrailer,
+ episodeRunTime = item.episodeRunTime,
+ lastModified = item.lastModified,
+ isAdult = item.isAdult,
+ syncFingerprint = seriesFingerprint(item)
+ )
+ }
+
+ private fun channelFingerprint(channel: ChannelEntity): String {
+ return fingerprint(
+ normalizeText(channel.name),
+ normalizeUrl(channel.logoUrl),
+ normalizeText(channel.groupTitle),
+ channel.categoryId?.toString().orEmpty(),
+ normalizeText(channel.categoryName),
+ normalizeUrl(channel.streamUrl),
+ normalizeText(channel.epgChannelId),
+ channel.number.toString(),
+ channel.catchUpSupported.toString(),
+ channel.catchUpDays.toString(),
+ normalizeUrl(channel.catchUpSource),
+ channel.isAdult.toString()
+ )
+ }
+
+ private fun movieFingerprint(movie: MovieEntity): String {
+ return fingerprint(
+ normalizeText(movie.name),
+ normalizeUrl(movie.posterUrl),
+ normalizeUrl(movie.backdropUrl),
+ movie.categoryId?.toString().orEmpty(),
+ normalizeText(movie.categoryName),
+ normalizeUrl(movie.streamUrl),
+ normalizeText(movie.containerExtension),
+ normalizeText(movie.plot),
+ normalizeText(movie.cast),
+ normalizeText(movie.director),
+ normalizeText(movie.genre),
+ normalizeText(movie.releaseDate),
+ normalizeText(movie.duration),
+ movie.durationSeconds.toString(),
+ movie.rating.toString(),
+ normalizeText(movie.year),
+ movie.tmdbId?.toString().orEmpty(),
+ normalizeUrl(movie.youtubeTrailer),
+ movie.isAdult.toString()
+ )
+ }
+
+ private fun seriesFingerprint(series: SeriesEntity): String {
+ return fingerprint(
+ normalizeText(series.name),
+ normalizeUrl(series.posterUrl),
+ normalizeUrl(series.backdropUrl),
+ series.categoryId?.toString().orEmpty(),
+ normalizeText(series.categoryName),
+ normalizeText(series.plot),
+ normalizeText(series.cast),
+ normalizeText(series.director),
+ normalizeText(series.genre),
+ normalizeText(series.releaseDate),
+ series.rating.toString(),
+ series.tmdbId?.toString().orEmpty(),
+ normalizeUrl(series.youtubeTrailer),
+ normalizeText(series.episodeRunTime),
+ series.lastModified.toString(),
+ series.isAdult.toString()
+ )
+ }
+
+ private fun categoryFingerprint(category: CategoryEntity): String {
+ return fingerprint(
+ category.categoryId.toString(),
+ normalizeText(category.name),
+ category.parentId?.toString().orEmpty(),
+ category.type.name,
+ category.isAdult.toString()
+ )
+ }
+
+ private fun fingerprint(vararg values: String): String {
+ val messageDigest = requireNotNull(digest.get())
+ messageDigest.reset()
+ values.forEach { value ->
+ messageDigest.update(value.toByteArray(Charsets.UTF_8))
+ messageDigest.update(0)
+ }
+ return messageDigest.digest().joinToString("") { byte -> "%02x".format(byte.toInt() and 0xff) }
+ }
+
+ private fun normalizeText(value: String?): String {
+ return value
+ .orEmpty()
+ .trim()
+ .replace(Regex("\\s+"), " ")
+ .lowercase()
+ }
+
+ private fun normalizeUrl(value: String?): String {
+ val url = value?.trim().orEmpty()
+ if (url.isEmpty()) {
+ return ""
+ }
+ val parsed = runCatching { URI(url) }.getOrNull()
+ val scheme = parsed?.scheme?.lowercase().orEmpty()
+ val host = parsed?.host?.lowercase().orEmpty()
+ val path = parsed?.path.orEmpty().trimEnd('/')
+ val query = parsed?.query
+ ?.split('&')
+ ?.mapNotNull { pair ->
+ val key = pair.substringBefore('=').lowercase()
+ val normalizedValue = pair.substringAfter('=', "")
+ when (key) {
+ "token", "auth", "password", "username" -> null
+ else -> "$key=$normalizedValue"
+ }
+ }
+ ?.sorted()
+ ?.joinToString("&")
+ .orEmpty()
+ return listOf(scheme, host, path, query)
+ .joinToString("|")
+ .ifBlank { url.lowercase() }
+ }
+
+ private companion object {
+ private const val STAGE_BATCH_SIZE = 500
+ }
+}
diff --git a/data/src/main/java/com/streamvault/data/sync/SyncErrorSanitizer.kt b/data/src/main/java/com/streamvault/data/sync/SyncErrorSanitizer.kt
new file mode 100644
index 00000000..25b1e0a6
--- /dev/null
+++ b/data/src/main/java/com/streamvault/data/sync/SyncErrorSanitizer.kt
@@ -0,0 +1,86 @@
+package com.streamvault.data.sync
+
+import com.streamvault.data.remote.xtream.XtreamAuthenticationException
+import com.streamvault.data.remote.xtream.XtreamNetworkException
+import com.streamvault.data.remote.xtream.XtreamParsingException
+import com.streamvault.data.remote.xtream.XtreamRequestException
+import com.streamvault.data.remote.xtream.XtreamResponseTooLargeException
+import java.io.InterruptedIOException
+import java.net.ConnectException
+import java.net.NoRouteToHostException
+import java.net.SocketException
+import java.net.SocketTimeoutException
+import java.net.URI
+import java.net.UnknownHostException
+import javax.net.ssl.SSLException
+
+internal class SyncErrorSanitizer {
+ fun userMessage(error: Throwable?, fallback: String): String {
+ val projected = when (error) {
+ null -> fallback
+ is XtreamAuthenticationException -> "Provider authentication failed."
+ is XtreamParsingException -> "Provider returned an unreadable response."
+ is XtreamResponseTooLargeException -> "Provider returned an oversized catalog response."
+ is XtreamRequestException -> classifyRequest(error.statusCode)
+ is SocketTimeoutException,
+ is InterruptedIOException -> "Provider timed out."
+ is UnknownHostException,
+ is ConnectException,
+ is NoRouteToHostException,
+ is SSLException -> "Provider connection failed."
+ is SocketException -> "Provider connection was interrupted."
+ is XtreamNetworkException -> "Provider connection failed."
+ is IllegalStateException -> classifyIllegalState(error.message, fallback)
+ else -> fallback
+ }
+ return sanitize(projected).ifBlank { fallback }
+ }
+
+ fun throwableMessage(error: Throwable?): String = sanitize(error?.message)
+
+ fun sanitize(message: String?): String {
+ if (message.isNullOrBlank()) {
+ return "<empty>"
+ }
+ return message
+ .replace(Regex("""https?://[^\s]+""", RegexOption.IGNORE_CASE)) { match ->
+ redactUrl(match.value)
+ }
+ .replace(Regex("""([?&](username|password|token|auth|key)=[^&\s]+)""", RegexOption.IGNORE_CASE), "<redacted-param>")
+ .replace(Regex("""(?i)\b(user(name)?|password|token|auth|key)\s*[=:]\s*[^,\s]+"""), "<redacted-credential>")
+ }
+
+ private fun redactUrl(url: String): String {
+ return runCatching {
+ val parsed = URI(url)
+ val scheme = parsed.scheme ?: "https"
+ val host = parsed.host ?: return@runCatching "<redacted-url>"
+ val path = parsed.path.orEmpty()
+ "$scheme://$host$path"
+ }.getOrDefault("<redacted-url>")
+ }
+
+ private fun classifyRequest(statusCode: Int): String {
+ return when (statusCode) {
+ 401 -> "Provider authentication failed."
+ 403, 429 -> "Provider is temporarily busy."
+ 404 -> "Provider endpoint was not found."
+ 408 -> "Provider is temporarily busy."
+ in 500..599 -> "Provider server is temporarily unavailable."
+ else -> "Provider rejected the request."
+ }
+ }
+
+ private fun classifyIllegalState(message: String?, fallback: String): String {
+ val normalized = message.orEmpty().lowercase()
+ return when {
+ normalized.contains("empty") && normalized.contains("catalog") -> "Provider returned an empty catalog."
+ normalized.contains("playlist") && normalized.contains("http") -> "Playlist download failed."
+ normalized.contains("epg") -> "Guide download failed."
+ normalized.contains("invalid") && normalized.contains("payload") -> "Provider returned invalid catalog data."
+ normalized.contains("secure") || normalized.contains("insecure") -> "Provider URL was rejected by security checks."
+ normalized.contains("authentication") -> "Provider authentication failed."
+ else -> fallback
+ }
+ }
+}
diff --git a/data/src/main/java/com/streamvault/data/sync/SyncManager.kt b/data/src/main/java/com/streamvault/data/sync/SyncManager.kt
index faf7331a..6e4b23d5 100644
--- a/data/src/main/java/com/streamvault/data/sync/SyncManager.kt
+++ b/data/src/main/java/com/streamvault/data/sync/SyncManager.kt
@@ -1,6 +1,8 @@
package com.streamvault.data.sync
import android.util.Log
+import com.streamvault.data.local.DatabaseTransactionRunner
+import com.streamvault.data.local.dao.CatalogSyncDao
import com.streamvault.data.local.dao.CategoryDao
import com.streamvault.data.local.dao.ChannelDao
import com.streamvault.data.local.dao.MovieDao
@@ -10,6 +12,7 @@ import com.streamvault.data.local.dao.SeriesDao
import com.streamvault.data.local.entity.CategoryEntity
import com.streamvault.data.local.entity.ChannelEntity
import com.streamvault.data.local.entity.MovieEntity
+import com.streamvault.data.local.entity.SeriesEntity
import com.streamvault.data.mapper.toDomain
import com.streamvault.data.mapper.toEntity
import com.streamvault.data.parser.M3uParser
@@ -21,6 +24,7 @@ import com.streamvault.data.remote.xtream.XtreamAuthenticationException
import com.streamvault.data.remote.xtream.XtreamNetworkException
import com.streamvault.data.remote.xtream.XtreamParsingException
import com.streamvault.data.remote.xtream.XtreamRequestException
+import com.streamvault.data.remote.xtream.XtreamResponseTooLargeException
import com.streamvault.data.remote.xtream.XtreamApiService
import com.streamvault.data.remote.xtream.XtreamProvider
import com.streamvault.data.remote.xtream.XtreamUrlFactory
@@ -39,21 +43,18 @@ import com.streamvault.domain.model.VodSyncMode
import com.streamvault.domain.repository.EpgRepository
import com.streamvault.domain.repository.SyncMetadataRepository
import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
-import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
-import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map
-import kotlinx.coroutines.flow.update
import kotlinx.coroutines.withContext
+import kotlinx.coroutines.withTimeout
import kotlinx.coroutines.sync.Mutex
-import kotlinx.coroutines.sync.Semaphore
-import kotlinx.coroutines.sync.withPermit
import kotlinx.coroutines.sync.withLock
import kotlinx.serialization.json.Json
import okhttp3.OkHttpClient
@@ -62,9 +63,9 @@ import okhttp3.Response
import java.io.BufferedInputStream
import java.io.IOException
import java.io.InputStream
+import java.net.URI
import java.security.MessageDigest
import java.util.concurrent.ConcurrentHashMap
-import java.util.concurrent.TimeUnit.MINUTES
import java.util.zip.GZIPInputStream
import javax.inject.Inject
import javax.inject.Singleton
@@ -72,16 +73,22 @@ import kotlin.random.Random
import kotlin.system.measureTimeMillis
private const val TAG = "SyncManager"
-private const val XTREAM_LIVE_CATEGORY_SYNC_MAX_CONCURRENCY = 4
-private const val XTREAM_CATALOG_TIMEOUT_MINUTES = 5L
-private const val XTREAM_CATALOG_PAGE_SIZE = 1000
+private const val XTREAM_CATALOG_PAGE_SIZE = 250
private const val XTREAM_CATALOG_MAX_PAGES = 200
+private const val XTREAM_FALLBACK_STAGE_BATCH_SIZE = 500
private const val MOVIE_CATEGORY_SEQUENTIAL_MODE_WARNING =
"Movies category-bulk sync downgraded to sequential mode after provider stress signals."
private const val LIVE_CATEGORY_SEQUENTIAL_MODE_WARNING =
"Live category sync downgraded to sequential mode after provider stress signals."
private const val SERIES_CATEGORY_SEQUENTIAL_MODE_WARNING =
"Series category sync downgraded to sequential mode after provider stress signals."
+private const val MOVIE_PAGED_SEQUENTIAL_MODE_WARNING =
+ "Movies paged sync downgraded to sequential mode after provider stress signals."
+private const val SERIES_PAGED_SEQUENTIAL_MODE_WARNING =
+ "Series paged sync downgraded to sequential mode after provider stress signals."
+private const val XTREAM_RECOVERY_ABORT_WARNING_SUFFIX =
+ "recovery stopped early after repeated provider stress signals; keeping recovered results."
+private const val XTREAM_AVOID_FULL_CATALOG_COOLDOWN_MILLIS = 6 * 60 * 60 * 1000L
enum class SyncRepairSection {
EPG,
@@ -97,11 +104,13 @@ class SyncManager @Inject constructor(
private val seriesDao: SeriesDao,
private val programDao: ProgramDao,
private val categoryDao: CategoryDao,
+ private val catalogSyncDao: CatalogSyncDao,
private val xtreamJson: Json,
private val m3uParser: M3uParser,
private val epgRepository: EpgRepository,
private val okHttpClient: OkHttpClient,
- private val syncMetadataRepository: SyncMetadataRepository
+ private val syncMetadataRepository: SyncMetadataRepository,
+ private val transactionRunner: DatabaseTransactionRunner
) {
private data class SyncOutcome(
val partial: Boolean = false,
@@ -135,30 +144,77 @@ class SyncManager @Inject constructor(
) : CatalogStrategyResult<Nothing>
}
+ private data class XtreamStrategyFeedback(
+ val preferredSegmentedFirst: Boolean = false,
+ val attemptedFullCatalog: Boolean = false,
+ val fullCatalogUnsafe: Boolean = false,
+ val segmentedStressDetected: Boolean = false
+ )
+
private data class MovieCatalogSyncResult(
val catalogResult: CatalogStrategyResult<Movie>,
val categories: List<CategoryEntity>?,
val syncMode: VodSyncMode,
- val warnings: List<String> = emptyList()
+ val warnings: List<String> = emptyList(),
+ val strategyFeedback: XtreamStrategyFeedback = XtreamStrategyFeedback(),
+ val stagedSessionId: Long? = null,
+ val stagedAcceptedCount: Int = 0
)
private data class CatalogSyncPayload<T>(
val catalogResult: CatalogStrategyResult<T>,
val categories: List<CategoryEntity>?,
- val warnings: List<String> = emptyList()
+ val warnings: List<String> = emptyList(),
+ val strategyFeedback: XtreamStrategyFeedback = XtreamStrategyFeedback(),
+ val stagedSessionId: Long? = null,
+ val stagedAcceptedCount: Int = 0
)
- private data class MovieProviderAdaptation(
+ private data class SequentialProviderAdaptation(
val rememberSequential: Boolean,
val healthyStreak: Int
)
+ private sealed interface Attempt<out T> {
+ data class Success<T>(val value: T) : Attempt<T>
+ data class Failure(val error: Exception) : Attempt<Nothing>
+ }
+
private sealed interface CategoryFetchOutcome<out T> {
data class Success<T>(val categoryName: String, val items: List<T>) : CategoryFetchOutcome<T>
data class Empty(val categoryName: String) : CategoryFetchOutcome<Nothing>
data class Failure(val categoryName: String, val error: Throwable) : CategoryFetchOutcome<Nothing>
}
+ private data class TimedCategoryOutcome<T>(
+ val category: XtreamCategory,
+ val outcome: CategoryFetchOutcome<T>,
+ val elapsedMs: Long
+ )
+
+ private sealed interface PageFetchOutcome<out T> {
+ data class Success<T>(val items: List<T>, val rawCount: Int) : PageFetchOutcome<T>
+ data class Empty(val page: Int) : PageFetchOutcome<Nothing>
+ data class Failure(val page: Int, val error: Throwable) : PageFetchOutcome<Nothing>
+ }
+
+ private data class TimedPageOutcome<T>(
+ val page: Int,
+ val outcome: PageFetchOutcome<T>,
+ val elapsedMs: Long
+ )
+
+ private data class CategoryExecutionPlan<T>(
+ val outcomes: List<TimedCategoryOutcome<T>>,
+ val warnings: List<String> = emptyList()
+ )
+
+ private data class PageExecutionPlan<T>(
+ val outcomes: List<TimedPageOutcome<T>>,
+ val warnings: List<String> = emptyList(),
+ val stoppedEarly: Boolean = false
+ )
+
private data class M3uImportStats(
val header: M3uParser.M3uHeader,
val liveCount: Int,
@@ -222,33 +278,43 @@ class SyncManager @Inject constructor(
}
}
- private val _syncState = MutableStateFlow<SyncState>(SyncState.Idle)
- val syncState: StateFlow<SyncState> = _syncState.asStateFlow()
- private val _syncStatesByProvider = MutableStateFlow<Map<Long, SyncState>>(emptyMap())
- val syncStatesByProvider: StateFlow<Map<Long, SyncState>> = _syncStatesByProvider.asStateFlow()
+ private val syncStateTracker = SyncStateTracker()
+ private val syncErrorSanitizer = SyncErrorSanitizer()
+ private val xtreamAdaptiveSyncPolicy = XtreamAdaptiveSyncPolicy()
+ private val syncCatalogStore = SyncCatalogStore(
+ movieDao = movieDao,
+ catalogSyncDao = catalogSyncDao,
+ transactionRunner = transactionRunner
+ )
+ val syncState: StateFlow<SyncState> = syncStateTracker.aggregateState
+ val syncStatesByProvider: StateFlow<Map<Long, SyncState>> = syncStateTracker.statesByProvider
private val providerSyncMutexes = ConcurrentHashMap<Long, Mutex>()
- private val xtreamCatalogApiService: XtreamApiService by lazy {
+ private val xtreamCatalogHttpService: OkHttpXtreamApiService by lazy {
OkHttpXtreamApiService(
- client = okHttpClient.newBuilder()
- .connectTimeout(XTREAM_CATALOG_TIMEOUT_MINUTES, MINUTES)
- .readTimeout(XTREAM_CATALOG_TIMEOUT_MINUTES, MINUTES)
- .writeTimeout(XTREAM_CATALOG_TIMEOUT_MINUTES, MINUTES)
- .build(),
+ client = okHttpClient,
json = xtreamJson
)
}
+ private val xtreamCatalogApiService: XtreamApiService by lazy { xtreamCatalogHttpService }
fun syncStateForProvider(providerId: Long): Flow<SyncState> =
syncStatesByProvider.map { states -> states[providerId] ?: SyncState.Idle }
fun currentSyncState(providerId: Long): SyncState =
- _syncStatesByProvider.value[providerId] ?: SyncState.Idle
+ syncStateTracker.current(providerId)
private suspend fun <T> withProviderLock(providerId: Long, block: suspend () -> T): T {
val mutex = providerSyncMutexes.computeIfAbsent(providerId) { Mutex() }
return mutex.withLock { block() }
}
+ suspend fun onProviderDeleted(providerId: Long) {
+ syncStateTracker.reset(providerId)
+ providerSyncMutexes.remove(providerId)
+ xtreamAdaptiveSyncPolicy.forgetProvider(providerId)
+ syncCatalogStore.clearProviderStaging(providerId)
+ }
+
suspend fun sync(
providerId: Long,
force: Boolean = false,
@@ -280,21 +346,52 @@ class SyncManager @Inject constructor(
SyncState.Success()
})
com.streamvault.domain.model.Result.success(Unit)
+ } catch (e: CancellationException) {
+ resetState(providerId)
+ throw e
} catch (e: Exception) {
- Log.e(TAG, "Sync failed for provider $providerId: ${redactUrlForLogs(e.message)}")
+ val safeMessage = syncErrorSanitizer.userMessage(e, "Sync failed")
+ Log.e(TAG, "Sync failed for provider $providerId: ${syncErrorSanitizer.throwableMessage(e)}")
updateSyncStatusMetadata(providerId = providerId, status = "ERROR")
- publishSyncState(providerId, SyncState.Error(e.message ?: "Unknown error", e))
- com.streamvault.domain.model.Result.error(e.message ?: "Sync failed", e)
+ publishSyncState(providerId, SyncState.Error(safeMessage, e))
+ com.streamvault.domain.model.Result.error(safeMessage, e)
}
}
- fun resetState(providerId: Long? = null) {
- if (providerId == null) {
- _syncStatesByProvider.value = emptyMap()
- } else {
- _syncStatesByProvider.update { states -> states - providerId }
+ private class FallbackCategoryCollector(
+ private val providerId: Long,
+ private val type: ContentType
+ ) {
+ private val categories = LinkedHashMap<Long, CategoryEntity>()
+
+ fun record(categoryId: Long?, categoryName: String?, isAdult: Boolean) {
+ val resolvedCategoryId = categoryId ?: return
+ val resolvedCategoryName = categoryName?.trim().takeUnless { it.isNullOrEmpty() }
+ ?: "Category $resolvedCategoryId"
+ categories.putIfAbsent(
+ resolvedCategoryId,
+ CategoryEntity(
+ categoryId = resolvedCategoryId,
+ name = resolvedCategoryName,
+ parentId = 0,
+ type = type,
+ providerId = providerId,
+ isAdult = isAdult || AdultContentClassifier.isAdultCategoryName(resolvedCategoryName)
+ )
+ )
}
- _syncState.value = SyncState.Idle
+
+ fun entities(): List<CategoryEntity> = categories.values.toList()
+ }
+
+ private data class StagedCatalogSnapshot(
+ val sessionId: Long?,
+ val acceptedCount: Int,
+ val fallbackCategories: List<CategoryEntity>?
+ )
+
+ fun resetState(providerId: Long? = null) {
+ syncStateTracker.reset(providerId)
}
suspend fun retrySection(
@@ -320,11 +417,15 @@ class SyncManager @Inject constructor(
updateSyncStatusMetadata(providerId = providerId, status = "SUCCESS")
publishSyncState(providerId, SyncState.Success())
com.streamvault.domain.model.Result.success(Unit)
+ } catch (e: CancellationException) {
+ resetState(providerId)
+ throw e
} catch (e: Exception) {
- Log.e(TAG, "Section retry failed for provider $providerId [$section]: ${redactUrlForLogs(e.message)}")
+ val safeMessage = syncErrorSanitizer.userMessage(e, "Retry failed")
+ Log.e(TAG, "Section retry failed for provider $providerId [$section]: ${syncErrorSanitizer.throwableMessage(e)}")
updateSyncStatusMetadata(providerId = providerId, status = "ERROR")
- publishSyncState(providerId, SyncState.Error(e.message ?: "Retry failed", e))
- com.streamvault.domain.model.Result.error(e.message ?: "Retry failed", e)
+ publishSyncState(providerId, SyncState.Error(safeMessage, e))
+ com.streamvault.domain.model.Result.error(safeMessage, e)
}
}
@@ -348,25 +449,60 @@ class SyncManager @Inject constructor(
val liveSyncResult = syncXtreamLiveCatalog(
provider = provider,
api = api,
+ existingMetadata = metadata,
onProgress = onProgress
)
+ val liveSequentialStress = liveSyncResult.strategyFeedback.segmentedStressDetected
+ val liveProviderAdaptation = updateSequentialProviderAdaptation(
+ previousRemembered = metadata.liveSequentialFailuresRemembered,
+ previousHealthyStreak = metadata.liveHealthySyncStreak,
+ sawSequentialStress = liveSequentialStress
+ )
+ val liveAvoidFullUntil = updateAvoidFullUntil(
+ previousAvoidFullUntil = metadata.liveAvoidFullUntil,
+ now = now,
+ feedback = liveSyncResult.strategyFeedback
+ )
when (val liveResult = liveSyncResult.catalogResult) {
is CatalogStrategyResult.Success -> {
- liveSyncResult.categories?.let { categoryDao.replaceAll(provider.id, "LIVE", it) }
- channelDao.replaceAll(provider.id, liveResult.items.map { it.toEntity() })
- metadata = metadata.copy(lastLiveSync = now, liveCount = liveResult.items.size)
+ val acceptedCount = syncCatalogStore.replaceLiveCatalog(
+ providerId = provider.id,
+ categories = liveSyncResult.categories,
+ channels = liveResult.items.map { it.toEntity() }
+ )
+ metadata = metadata.copy(
+ lastLiveSync = now,
+ liveCount = acceptedCount,
+ liveAvoidFullUntil = liveAvoidFullUntil,
+ liveSequentialFailuresRemembered = liveProviderAdaptation.rememberSequential,
+ liveHealthySyncStreak = liveProviderAdaptation.healthyStreak
+ )
warnings += liveSyncResult.warnings + liveResult.warnings
}
is CatalogStrategyResult.Partial -> {
- liveSyncResult.categories?.let { categoryDao.replaceAll(provider.id, "LIVE", it) }
- channelDao.replaceAll(provider.id, liveResult.items.map { it.toEntity() })
- metadata = metadata.copy(lastLiveSync = now, liveCount = liveResult.items.size)
+ val acceptedCount = syncCatalogStore.replaceLiveCatalog(
+ providerId = provider.id,
+ categories = liveSyncResult.categories,
+ channels = liveResult.items.map { it.toEntity() }
+ )
+ metadata = metadata.copy(
+ lastLiveSync = now,
+ liveCount = acceptedCount,
+ liveAvoidFullUntil = liveAvoidFullUntil,
+ liveSequentialFailuresRemembered = metadata.liveSequentialFailuresRemembered || liveSequentialStress,
+ liveHealthySyncStreak = 0
+ )
warnings += liveSyncResult.warnings + liveResult.warnings + listOf("Live TV sync completed partially.")
}
is CatalogStrategyResult.EmptyValid -> {
val existingChannelCount = channelDao.getCount(provider.id).first()
Log.w(TAG, "Live TV sync kept existing catalog for provider ${provider.id}: empty valid result, existingCount=$existingChannelCount")
+ metadata = metadata.copy(
+ liveAvoidFullUntil = liveAvoidFullUntil,
+ liveSequentialFailuresRemembered = metadata.liveSequentialFailuresRemembered || liveSequentialStress,
+ liveHealthySyncStreak = 0
+ )
warnings += liveSyncResult.warnings + liveResult.warnings +
if (existingChannelCount > 0) {
listOf("Live TV refresh returned an empty valid catalog; keeping previous channel library.")
@@ -380,6 +516,11 @@ class SyncManager @Inject constructor(
is CatalogStrategyResult.Failure -> {
val existingChannelCount = channelDao.getCount(provider.id).first()
Log.w(TAG, "Live TV sync preserved previous catalog for provider ${provider.id}: strategy=${liveResult.strategyName}, existingCount=$existingChannelCount, reason=${sanitizeThrowableMessage(liveResult.error)}")
+ metadata = metadata.copy(
+ liveAvoidFullUntil = liveAvoidFullUntil,
+ liveSequentialFailuresRemembered = metadata.liveSequentialFailuresRemembered || liveSequentialStress || shouldRememberSequentialPreference(liveResult.error),
+ liveHealthySyncStreak = 0
+ )
warnings += liveSyncResult.warnings + liveResult.warnings +
if (existingChannelCount > 0) {
listOf("Live TV sync degraded; keeping previous channel library.")
@@ -387,7 +528,9 @@ class SyncManager @Inject constructor(
listOf("Live TV sync failed before any usable channel catalog was available.")
}
if (existingChannelCount == 0) {
- throw IllegalStateException("Failed to fetch live streams: ${liveResult.error.message}")
+ throw IllegalStateException(
+ "Failed to fetch live streams: ${syncErrorSanitizer.throwableMessage(liveResult.error)}"
+ )
}
}
}
@@ -402,41 +545,59 @@ class SyncManager @Inject constructor(
existingMetadata = metadata,
onProgress = onProgress
)
- val sawSequentialStress = (movieSyncResult.warnings + strategyWarnings(movieSyncResult.catalogResult))
- .any { warning -> warning.contains(MOVIE_CATEGORY_SEQUENTIAL_MODE_WARNING, ignoreCase = true) }
- val healthyMovieProviderAdaptation = updateMovieProviderAdaptation(
+ val sawSequentialStress = movieSyncResult.strategyFeedback.segmentedStressDetected
+ val healthyMovieProviderAdaptation = updateSequentialProviderAdaptation(
previousRemembered = metadata.movieParallelFailuresRemembered,
previousHealthyStreak = metadata.movieHealthySyncStreak,
sawSequentialStress = sawSequentialStress
)
+ val movieAvoidFullUntil = updateAvoidFullUntil(
+ previousAvoidFullUntil = metadata.movieAvoidFullUntil,
+ now = now,
+ feedback = movieSyncResult.strategyFeedback
+ )
when (val catalogResult = movieSyncResult.catalogResult) {
is CatalogStrategyResult.Success -> {
- movieSyncResult.categories?.let { categoryDao.replaceAll(provider.id, "MOVIE", it) }
- movieDao.replaceAll(provider.id, catalogResult.items.map { movie -> movie.toEntity() })
+ val acceptedCount = movieSyncResult.stagedSessionId?.let { sessionId ->
+ syncCatalogStore.applyStagedMovieCatalog(provider.id, sessionId, movieSyncResult.categories)
+ movieSyncResult.stagedAcceptedCount
+ } ?: syncCatalogStore.replaceMovieCatalog(
+ providerId = provider.id,
+ categories = movieSyncResult.categories,
+ movies = catalogResult.items.asSequence().map { movie -> movie.toEntity() }
+ )
metadata = metadata.copy(
lastMovieSync = now,
lastMovieAttempt = now,
lastMovieSuccess = now,
- movieCount = catalogResult.items.size,
+ movieCount = acceptedCount,
movieSyncMode = movieSyncResult.syncMode,
movieWarningsCount = (movieSyncResult.warnings + catalogResult.warnings).size,
movieCatalogStale = false,
+ movieAvoidFullUntil = movieAvoidFullUntil,
movieParallelFailuresRemembered = healthyMovieProviderAdaptation.rememberSequential,
movieHealthySyncStreak = healthyMovieProviderAdaptation.healthyStreak
)
}
is CatalogStrategyResult.Partial -> {
- movieSyncResult.categories?.let { categoryDao.replaceAll(provider.id, "MOVIE", it) }
- movieDao.replaceAll(provider.id, catalogResult.items.map { movie -> movie.toEntity() })
+ val acceptedCount = movieSyncResult.stagedSessionId?.let { sessionId ->
+ syncCatalogStore.applyStagedMovieCatalog(provider.id, sessionId, movieSyncResult.categories)
+ movieSyncResult.stagedAcceptedCount
+ } ?: syncCatalogStore.replaceMovieCatalog(
+ providerId = provider.id,
+ categories = movieSyncResult.categories,
+ movies = catalogResult.items.asSequence().map { movie -> movie.toEntity() }
+ )
metadata = metadata.copy(
lastMovieSync = now,
lastMovieAttempt = now,
lastMoviePartial = now,
- movieCount = catalogResult.items.size,
+ movieCount = acceptedCount,
movieSyncMode = movieSyncResult.syncMode,
movieWarningsCount = (movieSyncResult.warnings + catalogResult.warnings).size,
movieCatalogStale = true,
+ movieAvoidFullUntil = movieAvoidFullUntil,
movieParallelFailuresRemembered = metadata.movieParallelFailuresRemembered || sawSequentialStress,
movieHealthySyncStreak = 0
)
@@ -450,6 +611,7 @@ class SyncManager @Inject constructor(
movieSyncMode = movieSyncResult.syncMode,
movieWarningsCount = (movieSyncResult.warnings + catalogResult.warnings).size,
movieCatalogStale = existingMovieCount > 0 || movieSyncResult.syncMode == VodSyncMode.LAZY_BY_CATEGORY,
+ movieAvoidFullUntil = movieAvoidFullUntil,
movieParallelFailuresRemembered = metadata.movieParallelFailuresRemembered || sawSequentialStress,
movieHealthySyncStreak = 0
)
@@ -468,7 +630,7 @@ class SyncManager @Inject constructor(
metadata.movieSyncMode
}
if (movieSyncResult.syncMode == VodSyncMode.LAZY_BY_CATEGORY) {
- movieSyncResult.categories?.let { categoryDao.replaceAll(provider.id, "MOVIE", it) }
+ movieSyncResult.categories?.let { syncCatalogStore.replaceCategories(provider.id, "MOVIE", it) }
}
Log.w(TAG, "Movies sync preserved previous catalog for provider ${provider.id}: strategy=${catalogResult.strategyName}, existingCount=$existingMovieCount, mode=${movieSyncResult.syncMode}, reason=${sanitizeThrowableMessage(catalogResult.error)}")
metadata = metadata.copy(
@@ -476,6 +638,7 @@ class SyncManager @Inject constructor(
movieSyncMode = finalMode,
movieWarningsCount = (movieSyncResult.warnings + catalogResult.warnings).size,
movieCatalogStale = existingMovieCount > 0 || movieSyncResult.syncMode == VodSyncMode.LAZY_BY_CATEGORY,
+ movieAvoidFullUntil = movieAvoidFullUntil,
movieParallelFailuresRemembered = metadata.movieParallelFailuresRemembered || sawSequentialStress || shouldRememberSequentialPreference(catalogResult.error),
movieHealthySyncStreak = 0
)
@@ -486,7 +649,9 @@ class SyncManager @Inject constructor(
listOf("Movies sync failed before any usable movie catalog was available.")
}
if (existingMovieCount == 0 && movieSyncResult.syncMode != VodSyncMode.LAZY_BY_CATEGORY) {
- throw IllegalStateException("Failed to fetch movie catalog: ${catalogResult.error.message}")
+ throw IllegalStateException(
+ "Failed to fetch movie catalog: ${syncErrorSanitizer.throwableMessage(catalogResult.error)}"
+ )
}
}
}
@@ -498,25 +663,66 @@ class SyncManager @Inject constructor(
val seriesSyncResult = syncXtreamSeriesCatalog(
provider = provider,
api = api,
+ existingMetadata = metadata,
onProgress = onProgress
)
+ val seriesSequentialStress = seriesSyncResult.strategyFeedback.segmentedStressDetected
+ val seriesProviderAdaptation = updateSequentialProviderAdaptation(
+ previousRemembered = metadata.seriesSequentialFailuresRemembered,
+ previousHealthyStreak = metadata.seriesHealthySyncStreak,
+ sawSequentialStress = seriesSequentialStress
+ )
+ val seriesAvoidFullUntil = updateAvoidFullUntil(
+ previousAvoidFullUntil = metadata.seriesAvoidFullUntil,
+ now = now,
+ feedback = seriesSyncResult.strategyFeedback
+ )
when (val seriesResult = seriesSyncResult.catalogResult) {
is CatalogStrategyResult.Success -> {
- seriesSyncResult.categories?.let { categoryDao.replaceAll(provider.id, "SERIES", it) }
- seriesDao.replaceAll(provider.id, seriesResult.items.map { it.toEntity() })
- metadata = metadata.copy(lastSeriesSync = now, seriesCount = seriesResult.items.size)
+ val acceptedCount = seriesSyncResult.stagedSessionId?.let { sessionId ->
+ syncCatalogStore.applyStagedSeriesCatalog(provider.id, sessionId, seriesSyncResult.categories)
+ seriesSyncResult.stagedAcceptedCount
+ } ?: syncCatalogStore.replaceSeriesCatalog(
+ providerId = provider.id,
+ categories = seriesSyncResult.categories,
+ series = seriesResult.items.asSequence().map { it.toEntity() }
+ )
+ metadata = metadata.copy(
+ lastSeriesSync = now,
+ seriesCount = acceptedCount,
+ seriesAvoidFullUntil = seriesAvoidFullUntil,
+ seriesSequentialFailuresRemembered = seriesProviderAdaptation.rememberSequential,
+ seriesHealthySyncStreak = seriesProviderAdaptation.healthyStreak
+ )
warnings += seriesSyncResult.warnings + seriesResult.warnings
}
is CatalogStrategyResult.Partial -> {
- seriesSyncResult.categories?.let { categoryDao.replaceAll(provider.id, "SERIES", it) }
- seriesDao.replaceAll(provider.id, seriesResult.items.map { it.toEntity() })
- metadata = metadata.copy(lastSeriesSync = now, seriesCount = seriesResult.items.size)
+ val acceptedCount = seriesSyncResult.stagedSessionId?.let { sessionId ->
+ syncCatalogStore.applyStagedSeriesCatalog(provider.id, sessionId, seriesSyncResult.categories)
+ seriesSyncResult.stagedAcceptedCount
+ } ?: syncCatalogStore.replaceSeriesCatalog(
+ providerId = provider.id,
+ categories = seriesSyncResult.categories,
+ series = seriesResult.items.asSequence().map { it.toEntity() }
+ )
+ metadata = metadata.copy(
+ lastSeriesSync = now,
+ seriesCount = acceptedCount,
+ seriesAvoidFullUntil = seriesAvoidFullUntil,
+ seriesSequentialFailuresRemembered = metadata.seriesSequentialFailuresRemembered || seriesSequentialStress,
+ seriesHealthySyncStreak = 0
+ )
warnings += seriesSyncResult.warnings + seriesResult.warnings + listOf("Series sync completed partially.")
}
is CatalogStrategyResult.EmptyValid -> {
val existingSeriesCount = seriesDao.getCount(provider.id).first()
Log.w(TAG, "Series sync kept existing catalog for provider ${provider.id}: empty valid result, existingCount=$existingSeriesCount")
+ metadata = metadata.copy(
+ seriesAvoidFullUntil = seriesAvoidFullUntil,
+ seriesSequentialFailuresRemembered = metadata.seriesSequentialFailuresRemembered || seriesSequentialStress,
+ seriesHealthySyncStreak = 0
+ )
warnings += seriesSyncResult.warnings + seriesResult.warnings +
if (existingSeriesCount > 0) {
listOf("Series refresh returned an empty valid catalog; keeping previous series library.")
@@ -529,15 +735,29 @@ class SyncManager @Inject constructor(
}
is CatalogStrategyResult.Failure -> {
val existingSeriesCount = seriesDao.getCount(provider.id).first()
+ val enteringLazyMode = seriesResult.strategyName == "lazy_by_category" && !seriesSyncResult.categories.isNullOrEmpty()
+ if (enteringLazyMode) {
+ seriesSyncResult.categories?.let { syncCatalogStore.replaceCategories(provider.id, "SERIES", it) }
+ }
Log.w(TAG, "Series sync preserved previous catalog for provider ${provider.id}: strategy=${seriesResult.strategyName}, existingCount=$existingSeriesCount, reason=${sanitizeThrowableMessage(seriesResult.error)}")
+ metadata = metadata.copy(
+ lastSeriesSync = if (enteringLazyMode) now else metadata.lastSeriesSync,
+ seriesAvoidFullUntil = seriesAvoidFullUntil,
+ seriesSequentialFailuresRemembered = metadata.seriesSequentialFailuresRemembered || seriesSequentialStress || shouldRememberSequentialPreference(seriesResult.error),
+ seriesHealthySyncStreak = 0
+ )
warnings += seriesSyncResult.warnings + seriesResult.warnings +
- if (existingSeriesCount > 0) {
+ if (enteringLazyMode) {
+ listOf("Series entered lazy category-only mode.")
+ } else if (existingSeriesCount > 0) {
listOf("Series sync degraded; keeping previous series library.")
} else {
listOf("Series sync failed before any usable series catalog was available.")
}
- if (existingSeriesCount == 0) {
- throw IllegalStateException("Failed to fetch series catalog: ${seriesResult.error.message}")
+ if (existingSeriesCount == 0 && !enteringLazyMode) {
+ throw IllegalStateException(
+ "Failed to fetch series catalog: ${syncErrorSanitizer.throwableMessage(seriesResult.error)}"
+ )
}
}
}
@@ -564,6 +784,8 @@ class SyncManager @Inject constructor(
if (epgCount == 0) {
warnings.add("EPG imported zero programs; live guide will fall back to on-demand Xtream data.")
}
+ } catch (e: CancellationException) {
+ throw e
} catch (e: Exception) {
Log.e(TAG, "EPG sync failed (non-fatal): ${sanitizeThrowableMessage(e)}")
warnings.add("EPG XMLTV sync failed; live guide will fall back to on-demand Xtream data.")
@@ -621,6 +843,8 @@ class SyncManager @Inject constructor(
epgCount = programDao.countByProvider(provider.id)
)
syncMetadataRepository.updateMetadata(metadata)
+ } catch (e: CancellationException) {
+ throw e
} catch (e: Exception) {
Log.e(TAG, "EPG sync failed (non-fatal): ${sanitizeThrowableMessage(e)}")
warnings.add("EPG sync failed")
@@ -681,47 +905,66 @@ class SyncManager @Inject constructor(
existingMetadata = currentMetadata,
onProgress = onProgress
)
- val sawSequentialStress = (movieSyncResult.warnings + strategyWarnings(movieSyncResult.catalogResult))
- .any { warning -> warning.contains(MOVIE_CATEGORY_SEQUENTIAL_MODE_WARNING, ignoreCase = true) }
- val healthyMovieProviderAdaptation = updateMovieProviderAdaptation(
+ val sawSequentialStress = movieSyncResult.strategyFeedback.segmentedStressDetected
+ val healthyMovieProviderAdaptation = updateSequentialProviderAdaptation(
previousRemembered = currentMetadata.movieParallelFailuresRemembered,
previousHealthyStreak = currentMetadata.movieHealthySyncStreak,
sawSequentialStress = sawSequentialStress
)
val movieWarnings = movieSyncResult.warnings + strategyWarnings(movieSyncResult.catalogResult)
+ val movieAvoidFullUntil = updateAvoidFullUntil(
+ previousAvoidFullUntil = currentMetadata.movieAvoidFullUntil,
+ now = now,
+ feedback = movieSyncResult.strategyFeedback
+ )
val metadata = currentMetadata.copy(
lastMovieAttempt = now,
movieSyncMode = movieSyncResult.syncMode,
movieWarningsCount = movieWarnings.size,
movieCatalogStale = movieSyncResult.syncMode == VodSyncMode.LAZY_BY_CATEGORY,
+ movieAvoidFullUntil = movieAvoidFullUntil,
movieParallelFailuresRemembered = currentMetadata.movieParallelFailuresRemembered || sawSequentialStress
)
when (val catalogResult = movieSyncResult.catalogResult) {
is CatalogStrategyResult.Success -> {
- movieSyncResult.categories?.let { categoryDao.replaceAll(provider.id, "MOVIE", it) }
- movieDao.replaceAll(provider.id, catalogResult.items.map { movie -> movie.toEntity() })
+ val acceptedCount = movieSyncResult.stagedSessionId?.let { sessionId ->
+ syncCatalogStore.applyStagedMovieCatalog(provider.id, sessionId, movieSyncResult.categories)
+ movieSyncResult.stagedAcceptedCount
+ } ?: syncCatalogStore.replaceMovieCatalog(
+ providerId = provider.id,
+ categories = movieSyncResult.categories,
+ movies = catalogResult.items.asSequence().map { movie -> movie.toEntity() }
+ )
syncMetadataRepository.updateMetadata(
metadata.copy(
lastMovieSync = now,
lastMovieSuccess = now,
- movieCount = catalogResult.items.size,
+ movieCount = acceptedCount,
movieCatalogStale = false,
+ movieAvoidFullUntil = movieAvoidFullUntil,
movieParallelFailuresRemembered = healthyMovieProviderAdaptation.rememberSequential,
movieHealthySyncStreak = healthyMovieProviderAdaptation.healthyStreak
)
)
}
is CatalogStrategyResult.Partial -> {
- movieSyncResult.categories?.let { categoryDao.replaceAll(provider.id, "MOVIE", it) }
- movieDao.replaceAll(provider.id, catalogResult.items.map { movie -> movie.toEntity() })
+ val acceptedCount = movieSyncResult.stagedSessionId?.let { sessionId ->
+ syncCatalogStore.applyStagedMovieCatalog(provider.id, sessionId, movieSyncResult.categories)
+ movieSyncResult.stagedAcceptedCount
+ } ?: syncCatalogStore.replaceMovieCatalog(
+ providerId = provider.id,
+ categories = movieSyncResult.categories,
+ movies = catalogResult.items.asSequence().map { movie -> movie.toEntity() }
+ )
syncMetadataRepository.updateMetadata(
metadata.copy(
lastMovieSync = now,
lastMoviePartial = now,
- movieCount = catalogResult.items.size,
+ movieCount = acceptedCount,
movieCatalogStale = true,
+ movieAvoidFullUntil = movieAvoidFullUntil,
movieParallelFailuresRemembered = currentMetadata.movieParallelFailuresRemembered || sawSequentialStress,
movieHealthySyncStreak = 0
)
@@ -732,6 +975,7 @@ class SyncManager @Inject constructor(
syncMetadataRepository.updateMetadata(
metadata.copy(
movieCatalogStale = existingMovieCount > 0 || movieSyncResult.syncMode == VodSyncMode.LAZY_BY_CATEGORY,
+ movieAvoidFullUntil = movieAvoidFullUntil,
movieParallelFailuresRemembered = currentMetadata.movieParallelFailuresRemembered || sawSequentialStress,
movieHealthySyncStreak = 0
)
@@ -747,16 +991,20 @@ class SyncManager @Inject constructor(
is CatalogStrategyResult.Failure -> {
val existingMovieCount = movieDao.getCount(provider.id).first()
if (movieSyncResult.syncMode == VodSyncMode.LAZY_BY_CATEGORY) {
- movieSyncResult.categories?.let { categoryDao.replaceAll(provider.id, "MOVIE", it) }
+ movieSyncResult.categories?.let { syncCatalogStore.replaceCategories(provider.id, "MOVIE", it) }
}
syncMetadataRepository.updateMetadata(
metadata.copy(
movieCatalogStale = existingMovieCount > 0 || movieSyncResult.syncMode == VodSyncMode.LAZY_BY_CATEGORY,
+ movieAvoidFullUntil = movieAvoidFullUntil,
movieParallelFailuresRemembered = currentMetadata.movieParallelFailuresRemembered || sawSequentialStress || shouldRememberSequentialPreference(catalogResult.error),
movieHealthySyncStreak = 0
)
)
- throw IllegalStateException(catalogResult.error.message ?: "Failed to fetch VOD streams", catalogResult.error)
+ throw IllegalStateException(
+ syncErrorSanitizer.userMessage(catalogResult.error, "Failed to fetch VOD streams"),
+ catalogResult.error
+ )
}
}
}
@@ -792,31 +1040,74 @@ class SyncManager @Inject constructor(
}
progress(provider.id, onProgress, "Retrying Series...")
val api = createXtreamSyncProvider(provider)
+ val currentMetadata = syncMetadataRepository.getMetadata(provider.id) ?: SyncMetadata(provider.id)
val seriesSyncResult = syncXtreamSeriesCatalog(
provider = provider,
api = api,
+ existingMetadata = currentMetadata,
onProgress = onProgress
)
val now = System.currentTimeMillis()
- val currentMetadata = syncMetadataRepository.getMetadata(provider.id) ?: SyncMetadata(provider.id)
+ val seriesSequentialStress = seriesSyncResult.strategyFeedback.segmentedStressDetected
+ val seriesProviderAdaptation = updateSequentialProviderAdaptation(
+ previousRemembered = currentMetadata.seriesSequentialFailuresRemembered,
+ previousHealthyStreak = currentMetadata.seriesHealthySyncStreak,
+ sawSequentialStress = seriesSequentialStress
+ )
+ val seriesAvoidFullUntil = updateAvoidFullUntil(
+ previousAvoidFullUntil = currentMetadata.seriesAvoidFullUntil,
+ now = now,
+ feedback = seriesSyncResult.strategyFeedback
+ )
when (val seriesResult = seriesSyncResult.catalogResult) {
is CatalogStrategyResult.Success -> {
- seriesSyncResult.categories?.let { categoryDao.replaceAll(provider.id, "SERIES", it) }
- seriesDao.replaceAll(provider.id, seriesResult.items.map { it.toEntity() })
+ val acceptedCount = seriesSyncResult.stagedSessionId?.let { sessionId ->
+ syncCatalogStore.applyStagedSeriesCatalog(provider.id, sessionId, seriesSyncResult.categories)
+ seriesSyncResult.stagedAcceptedCount
+ } ?: syncCatalogStore.replaceSeriesCatalog(
+ providerId = provider.id,
+ categories = seriesSyncResult.categories,
+ series = seriesResult.items.asSequence().map { it.toEntity() }
+ )
syncMetadataRepository.updateMetadata(
- currentMetadata.copy(lastSeriesSync = now, seriesCount = seriesResult.items.size)
+ currentMetadata.copy(
+ lastSeriesSync = now,
+ seriesCount = acceptedCount,
+ seriesAvoidFullUntil = seriesAvoidFullUntil,
+ seriesSequentialFailuresRemembered = seriesProviderAdaptation.rememberSequential,
+ seriesHealthySyncStreak = seriesProviderAdaptation.healthyStreak
+ )
)
}
is CatalogStrategyResult.Partial -> {
- seriesSyncResult.categories?.let { categoryDao.replaceAll(provider.id, "SERIES", it) }
- seriesDao.replaceAll(provider.id, seriesResult.items.map { it.toEntity() })
+ val acceptedCount = seriesSyncResult.stagedSessionId?.let { sessionId ->
+ syncCatalogStore.applyStagedSeriesCatalog(provider.id, sessionId, seriesSyncResult.categories)
+ seriesSyncResult.stagedAcceptedCount
+ } ?: syncCatalogStore.replaceSeriesCatalog(
+ providerId = provider.id,
+ categories = seriesSyncResult.categories,
+ series = seriesResult.items.asSequence().map { it.toEntity() }
+ )
syncMetadataRepository.updateMetadata(
- currentMetadata.copy(lastSeriesSync = now, seriesCount = seriesResult.items.size)
+ currentMetadata.copy(
+ lastSeriesSync = now,
+ seriesCount = acceptedCount,
+ seriesAvoidFullUntil = seriesAvoidFullUntil,
+ seriesSequentialFailuresRemembered = currentMetadata.seriesSequentialFailuresRemembered || seriesSequentialStress,
+ seriesHealthySyncStreak = 0
+ )
)
}
is CatalogStrategyResult.EmptyValid -> {
val existingSeriesCount = seriesDao.getCount(provider.id).first()
+ syncMetadataRepository.updateMetadata(
+ currentMetadata.copy(
+ seriesAvoidFullUntil = seriesAvoidFullUntil,
+ seriesSequentialFailuresRemembered = currentMetadata.seriesSequentialFailuresRemembered || seriesSequentialStress,
+ seriesHealthySyncStreak = 0
+ )
+ )
throw IllegalStateException(
if (existingSeriesCount > 0) {
"Series refresh returned an empty catalog; existing library was preserved."
@@ -826,7 +1117,24 @@ class SyncManager @Inject constructor(
)
}
is CatalogStrategyResult.Failure -> {
- throw IllegalStateException(seriesResult.error.message ?: "Failed to fetch series list", seriesResult.error)
+ val enteringLazyMode = seriesResult.strategyName == "lazy_by_category" && !seriesSyncResult.categories.isNullOrEmpty()
+ if (enteringLazyMode) {
+ seriesSyncResult.categories?.let { syncCatalogStore.replaceCategories(provider.id, "SERIES", it) }
+ }
+ syncMetadataRepository.updateMetadata(
+ currentMetadata.copy(
+ lastSeriesSync = if (enteringLazyMode) now else currentMetadata.lastSeriesSync,
+ seriesAvoidFullUntil = seriesAvoidFullUntil,
+ seriesSequentialFailuresRemembered = currentMetadata.seriesSequentialFailuresRemembered || seriesSequentialStress || shouldRememberSequentialPreference(seriesResult.error),
+ seriesHealthySyncStreak = 0
+ )
+ )
+ if (!enteringLazyMode) {
+ throw IllegalStateException(
+ syncErrorSanitizer.userMessage(seriesResult.error, "Failed to fetch series list"),
+ seriesResult.error
+ )
+ }
}
}
}
@@ -847,79 +1155,142 @@ class SyncManager @Inject constructor(
?.map { category -> category.toEntity(provider.id) }
?.takeIf { it.isNotEmpty() }
- val fullResult = loadXtreamMoviesFull(provider, api)
- when (fullResult) {
- is CatalogStrategyResult.Success -> return MovieCatalogSyncResult(
- catalogResult = fullResult,
- categories = resolvedCategories ?: buildFallbackMovieCategories(provider.id, fullResult.items),
- syncMode = VodSyncMode.FULL
- ).also {
- Log.i(TAG, "Xtream movies strategy selected FULL for provider ${provider.id} with ${fullResult.items.size} items.")
- }
- is CatalogStrategyResult.Partial -> return MovieCatalogSyncResult(
- catalogResult = fullResult,
- categories = resolvedCategories ?: buildFallbackMovieCategories(provider.id, fullResult.items),
- syncMode = VodSyncMode.FULL,
- warnings = emptyList()
- ).also {
- Log.w(TAG, "Xtream movies strategy selected FULL(partial) for provider ${provider.id} with ${fullResult.items.size} items.")
- }
- else -> Unit
- }
+ var fullPayload = CatalogSyncPayload<Movie>(
+ catalogResult = CatalogStrategyResult.EmptyValid("full"),
+ categories = null
+ )
+ var pagedPayload = CatalogSyncPayload<Movie>(
+ catalogResult = CatalogStrategyResult.EmptyValid("paged"),
+ categories = null
+ )
+ var categoryPayload = CatalogSyncPayload<Movie>(
+ catalogResult = CatalogStrategyResult.EmptyValid("category_bulk"),
+ categories = null
+ )
- val categoryResult = loadXtreamMoviesByCategory(
+ progress(provider.id, onProgress, "Preparing Movies category sync...")
+ categoryPayload = loadXtreamMoviesByCategory(
provider = provider,
api = api,
rawCategories = rawVodCategories.orEmpty(),
onProgress = onProgress,
preferSequential = existingMetadata.movieParallelFailuresRemembered
)
- when (categoryResult) {
+ when (val categoryResult = categoryPayload.catalogResult) {
is CatalogStrategyResult.Success -> return MovieCatalogSyncResult(
catalogResult = categoryResult,
- categories = resolvedCategories ?: buildFallbackMovieCategories(provider.id, categoryResult.items),
+ categories = resolvedCategories ?: categoryPayload.categories,
syncMode = VodSyncMode.CATEGORY_BULK,
- warnings = strategyWarnings(fullResult)
+ warnings = strategyWarnings(fullPayload.catalogResult) + strategyWarnings(pagedPayload.catalogResult),
+ strategyFeedback = XtreamStrategyFeedback(
+ preferredSegmentedFirst = true,
+ segmentedStressDetected = sawSegmentedStress(
+ warnings = strategyWarnings(fullPayload.catalogResult) + strategyWarnings(pagedPayload.catalogResult),
+ result = categoryResult,
+ sequentialWarnings = setOf(MOVIE_CATEGORY_SEQUENTIAL_MODE_WARNING, MOVIE_PAGED_SEQUENTIAL_MODE_WARNING)
+ )
+ ),
+ stagedSessionId = categoryPayload.stagedSessionId,
+ stagedAcceptedCount = categoryPayload.stagedAcceptedCount
).also {
- Log.i(TAG, "Xtream movies strategy selected CATEGORY_BULK for provider ${provider.id} with ${categoryResult.items.size} items.")
+ Log.i(TAG, "Xtream movies strategy selected CATEGORY_BULK for provider ${provider.id} with ${categoryPayload.stagedAcceptedCount} items.")
}
is CatalogStrategyResult.Partial -> return MovieCatalogSyncResult(
catalogResult = categoryResult,
- categories = resolvedCategories ?: buildFallbackMovieCategories(provider.id, categoryResult.items),
+ categories = resolvedCategories ?: categoryPayload.categories,
syncMode = VodSyncMode.CATEGORY_BULK,
- warnings = strategyWarnings(fullResult)
+ warnings = strategyWarnings(fullPayload.catalogResult) + strategyWarnings(pagedPayload.catalogResult),
+ strategyFeedback = XtreamStrategyFeedback(
+ preferredSegmentedFirst = true,
+ segmentedStressDetected = sawSegmentedStress(
+ warnings = strategyWarnings(fullPayload.catalogResult) + strategyWarnings(pagedPayload.catalogResult),
+ result = categoryResult,
+ sequentialWarnings = setOf(MOVIE_CATEGORY_SEQUENTIAL_MODE_WARNING, MOVIE_PAGED_SEQUENTIAL_MODE_WARNING)
+ )
+ ),
+ stagedSessionId = categoryPayload.stagedSessionId,
+ stagedAcceptedCount = categoryPayload.stagedAcceptedCount
).also {
- Log.w(TAG, "Xtream movies strategy selected CATEGORY_BULK(partial) for provider ${provider.id} with ${categoryResult.items.size} items.")
+ Log.w(TAG, "Xtream movies strategy selected CATEGORY_BULK(partial) for provider ${provider.id} with ${categoryPayload.stagedAcceptedCount} items.")
}
else -> Unit
}
- val pagedResult = loadXtreamMoviesByPage(provider, api, onProgress)
- when (pagedResult) {
- is CatalogStrategyResult.Success -> return MovieCatalogSyncResult(
- catalogResult = pagedResult,
- categories = resolvedCategories ?: buildFallbackMovieCategories(provider.id, pagedResult.items),
- syncMode = VodSyncMode.PAGED,
- warnings = strategyWarnings(fullResult) + strategyWarnings(categoryResult)
- ).also {
- Log.i(TAG, "Xtream movies strategy selected PAGED for provider ${provider.id} with ${pagedResult.items.size} items.")
+ if (resolvedCategories.isNullOrEmpty()) {
+ progress(provider.id, onProgress, "Checking Movies paged catalog...")
+ pagedPayload = loadXtreamMoviesByPage(provider, api, onProgress)
+ when (val pagedResult = pagedPayload.catalogResult) {
+ is CatalogStrategyResult.Success -> return MovieCatalogSyncResult(
+ catalogResult = pagedResult,
+ categories = pagedPayload.categories,
+ syncMode = VodSyncMode.PAGED,
+ warnings = strategyWarnings(fullPayload.catalogResult) + strategyWarnings(categoryPayload.catalogResult),
+ strategyFeedback = XtreamStrategyFeedback(
+ preferredSegmentedFirst = true,
+ segmentedStressDetected = sawSegmentedStress(
+ warnings = strategyWarnings(fullPayload.catalogResult) + strategyWarnings(categoryPayload.catalogResult),
+ result = pagedResult,
+ sequentialWarnings = setOf(MOVIE_PAGED_SEQUENTIAL_MODE_WARNING, MOVIE_CATEGORY_SEQUENTIAL_MODE_WARNING)
+ )
+ ),
+ stagedSessionId = pagedPayload.stagedSessionId,
+ stagedAcceptedCount = pagedPayload.stagedAcceptedCount
+ ).also {
+ Log.i(TAG, "Xtream movies strategy selected PAGED for provider ${provider.id} with ${pagedPayload.stagedAcceptedCount} items.")
+ }
+ is CatalogStrategyResult.Partial -> return MovieCatalogSyncResult(
+ catalogResult = pagedResult,
+ categories = pagedPayload.categories,
+ syncMode = VodSyncMode.PAGED,
+ warnings = strategyWarnings(fullPayload.catalogResult) + strategyWarnings(categoryPayload.catalogResult),
+ strategyFeedback = XtreamStrategyFeedback(
+ preferredSegmentedFirst = true,
+ segmentedStressDetected = sawSegmentedStress(
+ warnings = strategyWarnings(fullPayload.catalogResult) + strategyWarnings(categoryPayload.catalogResult),
+ result = pagedResult,
+ sequentialWarnings = setOf(MOVIE_PAGED_SEQUENTIAL_MODE_WARNING, MOVIE_CATEGORY_SEQUENTIAL_MODE_WARNING)
+ )
+ ),
+ stagedSessionId = pagedPayload.stagedSessionId,
+ stagedAcceptedCount = pagedPayload.stagedAcceptedCount
+ ).also {
+ Log.w(TAG, "Xtream movies strategy selected PAGED(partial) for provider ${provider.id} with ${pagedPayload.stagedAcceptedCount} items.")
+ }
+ else -> Unit
}
- is CatalogStrategyResult.Partial -> return MovieCatalogSyncResult(
- catalogResult = pagedResult,
- categories = resolvedCategories ?: buildFallbackMovieCategories(provider.id, pagedResult.items),
- syncMode = VodSyncMode.PAGED,
- warnings = strategyWarnings(fullResult) + strategyWarnings(categoryResult)
+ }
+
+ progress(provider.id, onProgress, "Checking Movies full catalog...")
+ fullPayload = loadXtreamMoviesFull(provider, api)
+ when (val fullResult = fullPayload.catalogResult) {
+ is CatalogStrategyResult.Success -> return MovieCatalogSyncResult(
+ catalogResult = fullResult,
+ categories = resolvedCategories ?: fullPayload.categories,
+ syncMode = VodSyncMode.FULL,
+ warnings = strategyWarnings(categoryPayload.catalogResult) + strategyWarnings(pagedPayload.catalogResult),
+ strategyFeedback = XtreamStrategyFeedback(
+ preferredSegmentedFirst = true,
+ attemptedFullCatalog = true,
+ fullCatalogUnsafe = false
+ ),
+ stagedSessionId = fullPayload.stagedSessionId,
+ stagedAcceptedCount = fullPayload.stagedAcceptedCount
).also {
- Log.w(TAG, "Xtream movies strategy selected PAGED(partial) for provider ${provider.id} with ${pagedResult.items.size} items.")
+ val itemCount = fullPayload.stagedAcceptedCount.takeIf { it > 0 } ?: fullResult.items.size
+ Log.i(TAG, "Xtream movies strategy selected FULL for provider ${provider.id} with $itemCount items.")
}
else -> Unit
}
val lazyWarnings = buildList {
- addAll(strategyWarnings(fullResult))
- addAll(strategyWarnings(categoryResult))
- addAll(strategyWarnings(pagedResult))
- add("Movies entered lazy category-only mode after full, category-bulk, and paged strategies failed.")
+ addAll(strategyWarnings(categoryPayload.catalogResult))
+ addAll(strategyWarnings(fullPayload.catalogResult))
+ if (!resolvedCategories.isNullOrEmpty()) {
+ add("Movies entered lazy category-only mode after category-bulk and full strategies failed.")
+ } else {
+ addAll(strategyWarnings(pagedPayload.catalogResult))
+ add("Movies entered lazy category-only mode after category-bulk, paged, and full strategies failed.")
+ }
}
Log.w(
TAG,
@@ -935,7 +1306,12 @@ class SyncManager @Inject constructor(
),
categories = resolvedCategories,
syncMode = VodSyncMode.LAZY_BY_CATEGORY,
- warnings = lazyWarnings
+ warnings = lazyWarnings,
+ strategyFeedback = XtreamStrategyFeedback(
+ preferredSegmentedFirst = true,
+ attemptedFullCatalog = true,
+ segmentedStressDetected = true
+ )
)
} else {
MovieCatalogSyncResult(
@@ -946,7 +1322,12 @@ class SyncManager @Inject constructor(
),
categories = null,
syncMode = VodSyncMode.UNKNOWN,
- warnings = lazyWarnings
+ warnings = lazyWarnings,
+ strategyFeedback = XtreamStrategyFeedback(
+ preferredSegmentedFirst = true,
+ attemptedFullCatalog = true,
+ segmentedStressDetected = true
+ )
)
}
}
@@ -954,26 +1335,84 @@ class SyncManager @Inject constructor(
private suspend fun loadXtreamMoviesFull(
provider: Provider,
api: XtreamProvider
- ): CatalogStrategyResult<Movie> {
- var fullMovies: List<Movie>? = null
+ ): CatalogSyncPayload<Movie> {
+ val fallbackCollector = FallbackCategoryCollector(provider.id, ContentType.MOVIE)
+ val seenStreamIds = HashSet<Long>()
+ val rawBatch = ArrayList<XtreamStream>(XTREAM_FALLBACK_STAGE_BATCH_SIZE)
+ var stagedSessionId: Long? = null
+ var acceptedCount = 0
+ var streamedRawCount = 0
var fullMoviesFailure: Throwable? = null
+
+ suspend fun flushRawBatch() {
+ if (rawBatch.isEmpty()) return
+ val staged = stageMovieSequence(
+ providerId = provider.id,
+ items = api.mapVodStreamsSequence(rawBatch.asSequence()),
+ seenStreamIds = seenStreamIds,
+ fallbackCollector = fallbackCollector,
+ sessionId = stagedSessionId
+ )
+ stagedSessionId = staged.sessionId
+ acceptedCount += staged.acceptedCount
+ rawBatch.clear()
+ }
+
val fullMoviesElapsedMs = measureTimeMillis {
- runCatching {
- retryXtreamCatalogTransient { api.getVodStreams().getOrThrow("VOD streams") }
- }.onSuccess { movies ->
- fullMovies = movies
- }.onFailure { error ->
- fullMoviesFailure = error
+ when (val attempt = attemptNonCancellation {
+ retryXtreamCatalogTransient(provider.id) {
+ executeXtreamRequest(provider.id, XtreamAdaptiveSyncPolicy.Stage.HEAVY) {
+ xtreamCatalogHttpService.streamVodStreams(
+ XtreamUrlFactory.buildPlayerApiUrl(
+ serverUrl = provider.serverUrl,
+ username = provider.username,
+ password = provider.password,
+ action = "get_vod_streams"
+ )
+ ) { stream ->
+ rawBatch += stream
+ streamedRawCount++
+ if (rawBatch.size >= XTREAM_FALLBACK_STAGE_BATCH_SIZE) {
+ flushRawBatch()
+ }
+ }.also {
+ flushRawBatch()
+ }
+ }
+ }
+ }) {
+ is Attempt.Success -> Unit
+ is Attempt.Failure -> {
+ fullMoviesFailure = attempt.error
+ stagedSessionId?.let { sessionId ->
+ syncCatalogStore.discardStagedImport(provider.id, sessionId)
+ stagedSessionId = null
+ }
+ }
}
}
- if (!fullMovies.isNullOrEmpty()) {
+ if (streamedRawCount > 0) {
Log.i(
TAG,
- "Xtream movies full catalog succeeded for provider ${provider.id} in ${fullMoviesElapsedMs}ms with ${fullMovies!!.size} items."
+ "Xtream movies full catalog succeeded for provider ${provider.id} in ${fullMoviesElapsedMs}ms with $acceptedCount accepted items from $streamedRawCount raw items."
)
- return CatalogStrategyResult.Success(
- strategyName = "full",
- items = fullMovies!!
+ if (acceptedCount == 0) {
+ return CatalogSyncPayload(
+ catalogResult = CatalogStrategyResult.EmptyValid(
+ strategyName = "full",
+ warnings = listOf("Movies full catalog returned raw items but none were usable after mapping.")
+ ),
+ categories = null
+ )
+ }
+ return CatalogSyncPayload(
+ catalogResult = CatalogStrategyResult.Success(
+ strategyName = "full",
+ items = emptyList()
+ ),
+ categories = fallbackCollector.entities().takeIf { it.isNotEmpty() },
+ stagedSessionId = stagedSessionId,
+ stagedAcceptedCount = acceptedCount
)
}
return if (fullMoviesFailure != null) {
@@ -982,14 +1421,17 @@ class SyncManager @Inject constructor(
section = "movies",
stage = "full catalog",
elapsedMs = fullMoviesElapsedMs,
- itemCount = fullMovies?.size,
+ itemCount = streamedRawCount,
error = fullMoviesFailure,
nextStep = "category-bulk"
)
- CatalogStrategyResult.Failure(
- strategyName = "full",
- error = fullMoviesFailure!!,
- warnings = listOf("Movies full catalog request failed: ${sanitizeThrowableMessage(fullMoviesFailure)}")
+ CatalogSyncPayload(
+ catalogResult = CatalogStrategyResult.Failure(
+ strategyName = "full",
+ error = fullMoviesFailure!!,
+ warnings = listOf(fullCatalogFallbackWarning("Movies", fullMoviesFailure))
+ ),
+ categories = null
)
} else {
logXtreamCatalogFallback(
@@ -997,13 +1439,16 @@ class SyncManager @Inject constructor(
section = "movies",
stage = "full catalog",
elapsedMs = fullMoviesElapsedMs,
- itemCount = fullMovies?.size,
+ itemCount = streamedRawCount,
error = null,
nextStep = "category-bulk"
)
- CatalogStrategyResult.EmptyValid(
- strategyName = "full",
- warnings = listOf("Movies full catalog returned an empty valid result.")
+ CatalogSyncPayload(
+ catalogResult = CatalogStrategyResult.EmptyValid(
+ strategyName = "full",
+ warnings = listOf("Movies full catalog returned an empty valid result.")
+ ),
+ categories = null
)
}
}
@@ -1011,43 +1456,68 @@ class SyncManager @Inject constructor(
private suspend fun syncXtreamLiveCatalog(
provider: Provider,
api: XtreamProvider,
+ existingMetadata: SyncMetadata,
onProgress: ((String) -> Unit)?
): CatalogSyncPayload<Channel> {
Log.i(TAG, "Xtream live strategy start for provider ${provider.id}.")
- val rawLiveCategories = runCatching {
- retryTransient {
- xtreamCatalogApiService.getLiveCategories(
- XtreamUrlFactory.buildPlayerApiUrl(
- serverUrl = provider.serverUrl,
- username = provider.username,
- password = provider.password,
- action = "get_live_categories"
+ val rawLiveCategories = when (val attempt = attemptNonCancellation {
+ retryXtreamCatalogTransient(provider.id) {
+ executeXtreamRequest(provider.id, XtreamAdaptiveSyncPolicy.Stage.LIGHTWEIGHT) {
+ xtreamCatalogApiService.getLiveCategories(
+ XtreamUrlFactory.buildPlayerApiUrl(
+ serverUrl = provider.serverUrl,
+ username = provider.username,
+ password = provider.password,
+ action = "get_live_categories"
+ )
)
- )
+ }
}
- }.onFailure { error ->
- Log.w(TAG, "Xtream live categories request failed for provider ${provider.id}: ${sanitizeThrowableMessage(error)}")
- }.getOrNull()
+ }) {
+ is Attempt.Success -> attempt.value
+ is Attempt.Failure -> {
+ Log.w(TAG, "Xtream live categories request failed for provider ${provider.id}: ${sanitizeThrowableMessage(attempt.error)}")
+ null
+ }
+ }
val resolvedCategories = rawLiveCategories
?.let { categories -> api.mapCategories(ContentType.LIVE, categories) }
?.map { category -> category.toEntity(provider.id) }
?.takeIf { it.isNotEmpty() }
-
- val fullResult = loadXtreamLiveFull(provider, api)
+ var fullResult: CatalogStrategyResult<Channel> = CatalogStrategyResult.EmptyValid("full")
+ var categoryResult: CatalogStrategyResult<Channel> = CatalogStrategyResult.EmptyValid("category_bulk")
+ progress(provider.id, onProgress, "Downloading Live TV...")
+ fullResult = loadXtreamLiveFull(provider, api)
when (fullResult) {
is CatalogStrategyResult.Success -> return CatalogSyncPayload(
catalogResult = fullResult,
- categories = resolvedCategories ?: buildFallbackLiveCategories(provider.id, fullResult.items)
+ categories = resolvedCategories ?: buildFallbackLiveCategories(provider.id, fullResult.items),
+ warnings = emptyList(),
+ strategyFeedback = XtreamStrategyFeedback(
+ attemptedFullCatalog = true,
+ fullCatalogUnsafe = false
+ )
)
is CatalogStrategyResult.Partial -> return CatalogSyncPayload(
catalogResult = fullResult,
categories = resolvedCategories ?: buildFallbackLiveCategories(provider.id, fullResult.items),
- warnings = emptyList()
+ warnings = emptyList(),
+ strategyFeedback = XtreamStrategyFeedback(
+ attemptedFullCatalog = true,
+ fullCatalogUnsafe = false
+ )
)
else -> Unit
}
- val categoryResult = loadXtreamLiveByCategory(provider, api, rawLiveCategories.orEmpty(), onProgress, preferSequential = false)
+ progress(provider.id, onProgress, "Downloading Live TV by category...")
+ categoryResult = loadXtreamLiveByCategory(
+ provider,
+ api,
+ rawLiveCategories.orEmpty(),
+ onProgress,
+ preferSequential = existingMetadata.liveSequentialFailuresRemembered
+ )
return CatalogSyncPayload(
catalogResult = categoryResult,
categories = when (categoryResult) {
@@ -1055,7 +1525,16 @@ class SyncManager @Inject constructor(
is CatalogStrategyResult.Partial -> resolvedCategories ?: buildFallbackLiveCategories(provider.id, categoryResult.items)
else -> null
},
- warnings = strategyWarnings(fullResult)
+ warnings = strategyWarnings(fullResult),
+ strategyFeedback = XtreamStrategyFeedback(
+ attemptedFullCatalog = true,
+ fullCatalogUnsafe = (fullResult as? CatalogStrategyResult.Failure)?.error?.let(::shouldAvoidFullCatalogStrategy) == true,
+ segmentedStressDetected = sawSegmentedStress(
+ warnings = strategyWarnings(fullResult),
+ result = categoryResult,
+ sequentialWarnings = setOf(LIVE_CATEGORY_SEQUENTIAL_MODE_WARNING)
+ )
+ )
)
}
@@ -1066,12 +1545,15 @@ class SyncManager @Inject constructor(
var fullChannels: List<Channel>? = null
var fullChannelsFailure: Throwable? = null
val fullChannelsElapsedMs = measureTimeMillis {
- runCatching {
- retryXtreamCatalogTransient { api.getLiveStreams().getOrThrow("Live streams") }
- }.onSuccess { channels ->
- fullChannels = channels
- }.onFailure { error ->
- fullChannelsFailure = error
+ when (val attempt = attemptNonCancellation {
+ retryXtreamCatalogTransient(provider.id) {
+ executeXtreamRequest(provider.id, XtreamAdaptiveSyncPolicy.Stage.HEAVY) {
+ api.getLiveStreams().getOrThrow("Live streams")
+ }
+ }
+ }) {
+ is Attempt.Success -> fullChannels = attempt.value
+ is Attempt.Failure -> fullChannelsFailure = attempt.error
}
}
if (!fullChannels.isNullOrEmpty()) {
@@ -1091,7 +1573,7 @@ class SyncManager @Inject constructor(
CatalogStrategyResult.Failure(
strategyName = "full",
error = fullChannelsFailure!!,
- warnings = listOf("Live full catalog request failed: ${sanitizeThrowableMessage(fullChannelsFailure)}")
+ warnings = listOf(fullCatalogFallbackWarning("Live TV", fullChannelsFailure))
)
} else {
logXtreamCatalogFallback(
@@ -1126,81 +1608,50 @@ class SyncManager @Inject constructor(
)
}
- val concurrency = if (preferSequential) 1 else XTREAM_LIVE_CATEGORY_SYNC_MAX_CONCURRENCY
- val semaphore = Semaphore(concurrency)
- val progressCounter = java.util.concurrent.atomic.AtomicInteger(0)
- val failureCount = java.util.concurrent.atomic.AtomicInteger(0)
- val fastFailureCount = java.util.concurrent.atomic.AtomicInteger(0)
- val warnings = mutableListOf<String>()
- val warningsMutex = Mutex()
- progress(provider.id, onProgress, "Downloading Live TV 0/${categories.size}...")
-
- val categoryOutcomes = coroutineScope {
- categories.map { category ->
- async {
- semaphore.withPermit {
- rateLimitXtreamCatalogRequest()
- var rawStreams: List<XtreamStream> = emptyList()
- var categoryFailure: Throwable? = null
- val elapsedMs = measureTimeMillis {
- runCatching {
- retryXtreamCatalogTransient {
- xtreamCatalogApiService.getLiveStreams(
- XtreamUrlFactory.buildPlayerApiUrl(
- serverUrl = provider.serverUrl,
- username = provider.username,
- password = provider.password,
- action = "get_live_streams",
- extraQueryParams = mapOf("category_id" to category.categoryId)
- )
- )
- }
- }.onSuccess { streams ->
- rawStreams = streams
- }.onFailure { error ->
- categoryFailure = error
- }
- }
+ val concurrency = xtreamAdaptiveSyncPolicy.concurrencyFor(
+ providerId = provider.id,
+ workloadSize = categories.size,
+ preferSequential = preferSequential,
+ stage = XtreamAdaptiveSyncPolicy.Stage.CATEGORY
+ )
+ progress(provider.id, onProgress, "Downloading Live TV by category 0/${categories.size}...")
- val completed = progressCounter.incrementAndGet()
- progress(provider.id, onProgress, "Downloading Live TV $completed/${categories.size}...")
-
- when {
- categoryFailure != null -> {
- failureCount.incrementAndGet()
- if (elapsedMs <= 5_000L) fastFailureCount.incrementAndGet()
- val failure = categoryFailure!!
- warningsMutex.withLock {
- warnings += "Live category '${category.categoryName}' failed: ${sanitizeThrowableMessage(failure)}"
- }
- Log.w(TAG, "Xtream live category '${category.categoryName}' failed after ${elapsedMs}ms: ${sanitizeThrowableMessage(failure)}")
- CategoryFetchOutcome.Failure(category.categoryName, failure)
- }
- rawStreams.isEmpty() -> {
- Log.i(TAG, "Xtream live category '${category.categoryName}' completed in ${elapsedMs}ms with a valid empty result.")
- CategoryFetchOutcome.Empty(category.categoryName)
- }
- else -> {
- Log.i(TAG, "Xtream live category '${category.categoryName}' completed in ${elapsedMs}ms with ${rawStreams.size} raw items.")
- CategoryFetchOutcome.Success(category.categoryName, api.mapLiveStreamsResponse(rawStreams))
- }
- }
- }
- }
- }.awaitAll()
+ val executionPlan = executeCategoryRecoveryPlan(
+ provider = provider,
+ categories = categories,
+ initialConcurrency = concurrency,
+ sectionLabel = "Live TV",
+ sequentialModeWarning = LIVE_CATEGORY_SEQUENTIAL_MODE_WARNING,
+ onProgress = onProgress,
+ fetch = { category -> fetchLiveCategoryOutcome(provider, api, category) }
+ )
+ var timedOutcomes = executionPlan.outcomes
+
+ val categoryOutcomes = timedOutcomes.map { it.outcome }
+ val failureCount = timedOutcomes.count { it.outcome is CategoryFetchOutcome.Failure }
+ val fastFailureCount = timedOutcomes.count {
+ it.elapsedMs <= 5_000L && it.outcome is CategoryFetchOutcome.Failure
}
- if (concurrency > 1 && shouldDowngradeCategorySync(categories.size, failureCount.get(), fastFailureCount.get(), categoryOutcomes)) {
- Log.w(TAG, "Xtream live category sync is downgrading to sequential mode for provider ${provider.id}.")
- return when (val sequentialResult = loadXtreamLiveByCategory(provider, api, rawCategories, onProgress, preferSequential = true)) {
- is CatalogStrategyResult.Success -> sequentialResult.copy(warnings = sequentialResult.warnings + LIVE_CATEGORY_SEQUENTIAL_MODE_WARNING)
- is CatalogStrategyResult.Partial -> sequentialResult.copy(warnings = sequentialResult.warnings + LIVE_CATEGORY_SEQUENTIAL_MODE_WARNING)
- is CatalogStrategyResult.Failure -> sequentialResult.copy(warnings = sequentialResult.warnings + LIVE_CATEGORY_SEQUENTIAL_MODE_WARNING)
- is CatalogStrategyResult.EmptyValid -> sequentialResult.copy(warnings = sequentialResult.warnings + LIVE_CATEGORY_SEQUENTIAL_MODE_WARNING)
- }
+ val downgradeRecommended = shouldDowngradeCategorySync(categories.size, failureCount, fastFailureCount, categoryOutcomes)
+ var fallbackWarnings = executionPlan.warnings
+ if (concurrency > 1 && shouldRetryFailedCategories(categories.size, failureCount, downgradeRecommended, categoryOutcomes)) {
+ Log.w(TAG, "Xtream live category sync is continuing in sequential mode for failed categories on provider ${provider.id}.")
+ timedOutcomes = continueFailedCategoryOutcomes(
+ provider = provider,
+ timedOutcomes = timedOutcomes,
+ fetchSequentially = { category -> fetchLiveCategoryOutcome(provider, api, category) }
+ )
+ fallbackWarnings = (fallbackWarnings + if (downgradeRecommended) listOf(LIVE_CATEGORY_SEQUENTIAL_MODE_WARNING) else emptyList()).distinct()
}
- val channels = categoryOutcomes
+ val finalOutcomes = timedOutcomes.map { it.outcome }
+ val warnings = finalOutcomes
+ .filterIsInstance<CategoryFetchOutcome.Failure>()
+ .map { failure -> categoryFailureWarning("Live TV", failure.categoryName, failure.error) } +
+ fallbackWarnings
+
+ val channels = finalOutcomes
.asSequence()
.filterIsInstance<CategoryFetchOutcome.Success<Channel>>()
.flatMap { it.items.asSequence() }
@@ -1208,9 +1659,9 @@ class SyncManager @Inject constructor(
.associateBy { it.streamId }
.values
.toList()
- val failedCategories = categoryOutcomes.count { it is CategoryFetchOutcome.Failure }
- val emptyCategories = categoryOutcomes.count { it is CategoryFetchOutcome.Empty }
- val successfulCategories = categoryOutcomes.count { it is CategoryFetchOutcome.Success }
+ val failedCategories = finalOutcomes.count { it is CategoryFetchOutcome.Failure }
+ val emptyCategories = finalOutcomes.count { it is CategoryFetchOutcome.Empty }
+ val successfulCategories = finalOutcomes.count { it is CategoryFetchOutcome.Success }
Log.i(TAG, "Xtream live category strategy summary for provider ${provider.id}: successful=$successfulCategories empty=$emptyCategories failed=$failedCategories dedupedChannels=${channels.size} concurrency=$concurrency")
return when {
@@ -1234,93 +1685,55 @@ class SyncManager @Inject constructor(
rawCategories: List<XtreamCategory>,
onProgress: ((String) -> Unit)?,
preferSequential: Boolean
- ): CatalogStrategyResult<Movie> {
+ ): CatalogSyncPayload<Movie> {
val categories = rawCategories.filter { it.categoryId.isNotBlank() }
if (categories.isEmpty()) {
- return CatalogStrategyResult.Failure(
- strategyName = "category_bulk",
- error = IllegalStateException("No VOD categories available"),
- warnings = listOf("Movies category-bulk strategy was unavailable because no categories were returned.")
+ return CatalogSyncPayload(
+ catalogResult = CatalogStrategyResult.Failure(
+ strategyName = "category_bulk",
+ error = IllegalStateException("No VOD categories available"),
+ warnings = listOf("Movies category-bulk strategy was unavailable because no categories were returned.")
+ ),
+ categories = null
)
}
- val concurrency = if (preferSequential) 1 else xtreamCategorySyncConcurrency(categories.size)
- val semaphore = Semaphore(concurrency)
- val progressCounter = java.util.concurrent.atomic.AtomicInteger(0)
- val failureCount = java.util.concurrent.atomic.AtomicInteger(0)
- val fastFailureCount = java.util.concurrent.atomic.AtomicInteger(0)
- val warnings = mutableListOf<String>()
- val warningsMutex = Mutex()
- progress(provider.id, onProgress, "Downloading Movies 0/${categories.size}...")
-
- val categoryOutcomes = coroutineScope {
- categories.map { category ->
- async {
- semaphore.withPermit {
- rateLimitXtreamCatalogRequest()
- var rawStreams: List<XtreamStream> = emptyList()
- var categoryFailure: Throwable? = null
- val elapsedMs = measureTimeMillis {
- runCatching {
- retryXtreamCatalogTransient {
- xtreamCatalogApiService.getVodStreams(
- XtreamUrlFactory.buildPlayerApiUrl(
- serverUrl = provider.serverUrl,
- username = provider.username,
- password = provider.password,
- action = "get_vod_streams",
- extraQueryParams = mapOf("category_id" to category.categoryId)
- )
- )
- }
- }.onSuccess { streams ->
- rawStreams = streams
- }.onFailure { error ->
- categoryFailure = error
- }
- }
+ val concurrency = xtreamAdaptiveSyncPolicy.concurrencyFor(
+ providerId = provider.id,
+ workloadSize = categories.size,
+ preferSequential = preferSequential,
+ stage = XtreamAdaptiveSyncPolicy.Stage.CATEGORY
+ )
+ progress(provider.id, onProgress, "Downloading Movies by category 0/${categories.size}...")
- val completed = progressCounter.incrementAndGet()
- progress(provider.id, onProgress, "Downloading Movies $completed/${categories.size}...")
-
- when {
- categoryFailure != null -> {
- failureCount.incrementAndGet()
- if (elapsedMs <= 5_000L) fastFailureCount.incrementAndGet()
- val failure = categoryFailure!!
- warningsMutex.withLock {
- warnings += "Category '${category.categoryName}' failed: ${failure.message}"
- }
- Log.w(
- TAG,
- "Xtream movie category '${category.categoryName}' failed after ${elapsedMs}ms: ${failure::class.java.simpleName}: ${failure.message}"
- )
- CategoryFetchOutcome.Failure(category.categoryName, failure)
- }
- rawStreams.isEmpty() -> {
- Log.i(TAG, "Xtream movie category '${category.categoryName}' completed in ${elapsedMs}ms with a valid empty result.")
- CategoryFetchOutcome.Empty(category.categoryName)
- }
- else -> {
- Log.i(TAG, "Xtream movie category '${category.categoryName}' completed in ${elapsedMs}ms with ${rawStreams.size} raw items.")
- CategoryFetchOutcome.Success(category.categoryName, api.mapVodStreamsResponse(rawStreams))
- }
- }
- }
- }
- }.awaitAll()
+ val executionPlan = executeCategoryRecoveryPlan(
+ provider = provider,
+ categories = categories,
+ initialConcurrency = concurrency,
+ sectionLabel = "Movies",
+ sequentialModeWarning = MOVIE_CATEGORY_SEQUENTIAL_MODE_WARNING,
+ onProgress = onProgress,
+ fetch = { category -> fetchMovieCategoryOutcome(provider, api, category) }
+ )
+ var timedOutcomes = executionPlan.outcomes
+
+ val categoryOutcomes = timedOutcomes.map { it.outcome }
+ val failureCount = timedOutcomes.count { it.outcome is CategoryFetchOutcome.Failure }
+ val fastFailureCount = timedOutcomes.count {
+ it.elapsedMs <= 5_000L && it.outcome is CategoryFetchOutcome.Failure
}
- if (concurrency > 1 && shouldDowngradeCategorySync(
- totalCategories = categories.size,
- failures = failureCount.get(),
- fastFailures = fastFailureCount.get(),
- outcomes = categoryOutcomes
- )
- ) {
+ val downgradeRecommended = shouldDowngradeCategorySync(
+ totalCategories = categories.size,
+ failures = failureCount,
+ fastFailures = fastFailureCount,
+ outcomes = categoryOutcomes
+ )
+ var fallbackWarnings = executionPlan.warnings
+ if (concurrency > 1 && shouldRetryFailedCategories(categories.size, failureCount, downgradeRecommended, categoryOutcomes)) {
val downgradeReasons = buildList {
- add("failures=${failureCount.get()}/${categories.size}")
- if (fastFailureCount.get() > 0) add("fastFailures=${fastFailureCount.get()}")
+ add("failures=$failureCount/${categories.size}")
+ if (fastFailureCount > 0) add("fastFailures=$fastFailureCount")
val providerStressSignals = categoryOutcomes.count { outcome ->
outcome is CategoryFetchOutcome.Failure && shouldRememberSequentialPreference(outcome.error)
}
@@ -1328,65 +1741,82 @@ class SyncManager @Inject constructor(
}.joinToString(", ")
Log.w(
TAG,
- "Xtream movie category sync is downgrading to sequential mode for provider ${provider.id}: $downgradeReasons"
+ "Xtream movie category sync is continuing in sequential mode for failed categories on provider ${provider.id}: $downgradeReasons"
)
- return when (val sequentialResult = loadXtreamMoviesByCategory(
+ timedOutcomes = continueFailedCategoryOutcomes(
provider = provider,
- api = api,
- rawCategories = rawCategories,
- onProgress = onProgress,
- preferSequential = true
- )) {
- is CatalogStrategyResult.Success -> sequentialResult.copy(
- warnings = sequentialResult.warnings + MOVIE_CATEGORY_SEQUENTIAL_MODE_WARNING
- )
- is CatalogStrategyResult.Partial -> sequentialResult.copy(
- warnings = sequentialResult.warnings + MOVIE_CATEGORY_SEQUENTIAL_MODE_WARNING
- )
- is CatalogStrategyResult.Failure -> sequentialResult.copy(
- warnings = sequentialResult.warnings + MOVIE_CATEGORY_SEQUENTIAL_MODE_WARNING
- )
- is CatalogStrategyResult.EmptyValid -> sequentialResult.copy(
- warnings = sequentialResult.warnings + MOVIE_CATEGORY_SEQUENTIAL_MODE_WARNING
- )
- }
+ timedOutcomes = timedOutcomes,
+ fetchSequentially = { category -> fetchMovieCategoryOutcome(provider, api, category) }
+ )
+ fallbackWarnings = (fallbackWarnings + if (downgradeRecommended) listOf(MOVIE_CATEGORY_SEQUENTIAL_MODE_WARNING) else emptyList()).distinct()
}
- val movies = categoryOutcomes
- .asSequence()
+ val finalOutcomes = timedOutcomes.map { it.outcome }
+ val warnings = finalOutcomes
+ .filterIsInstance<CategoryFetchOutcome.Failure>()
+ .map { failure -> categoryFailureWarning("Movies", failure.categoryName, failure.error) } +
+ fallbackWarnings
+
+ val seenStreamIds = HashSet<Long>()
+ val fallbackCollector = FallbackCategoryCollector(provider.id, ContentType.MOVIE)
+ var sessionId: Long? = null
+ var acceptedCount = 0
+ finalOutcomes
.filterIsInstance<CategoryFetchOutcome.Success<Movie>>()
- .flatMap { it.items.asSequence() }
- .filter { it.streamId > 0L }
- .associateBy { it.streamId }
- .values
- .toList()
+ .forEach { success ->
+ val staged = stageMovieItems(
+ providerId = provider.id,
+ items = success.items,
+ seenStreamIds = seenStreamIds,
+ fallbackCollector = fallbackCollector,
+ sessionId = sessionId
+ )
+ sessionId = staged.sessionId
+ acceptedCount += staged.acceptedCount
+ }
- val failedCategories = categoryOutcomes.count { it is CategoryFetchOutcome.Failure }
- val successfulCategories = categoryOutcomes.count { it is CategoryFetchOutcome.Success }
- val emptyCategories = categoryOutcomes.count { it is CategoryFetchOutcome.Empty }
+ val failedCategories = finalOutcomes.count { it is CategoryFetchOutcome.Failure }
+ val successfulCategories = finalOutcomes.count { it is CategoryFetchOutcome.Success }
+ val emptyCategories = finalOutcomes.count { it is CategoryFetchOutcome.Empty }
Log.i(
TAG,
- "Xtream movie category strategy summary for provider ${provider.id}: successful=$successfulCategories empty=$emptyCategories failed=$failedCategories dedupedMovies=${movies.size} concurrency=$concurrency"
+ "Xtream movie category strategy summary for provider ${provider.id}: successful=$successfulCategories empty=$emptyCategories failed=$failedCategories dedupedMovies=$acceptedCount concurrency=$concurrency"
)
return when {
- movies.isNotEmpty() && failedCategories == 0 -> CatalogStrategyResult.Success(
- strategyName = "category_bulk",
- items = movies,
- warnings = warnings.toList()
+ acceptedCount > 0 && failedCategories == 0 -> CatalogSyncPayload(
+ catalogResult = CatalogStrategyResult.Success(
+ strategyName = "category_bulk",
+ items = emptyList(),
+ warnings = warnings.toList()
+ ),
+ categories = fallbackCollector.entities().takeIf { it.isNotEmpty() },
+ stagedSessionId = sessionId,
+ stagedAcceptedCount = acceptedCount
)
- movies.isNotEmpty() -> CatalogStrategyResult.Partial(
- strategyName = "category_bulk",
- items = movies,
- warnings = warnings.toList()
+ acceptedCount > 0 -> CatalogSyncPayload(
+ catalogResult = CatalogStrategyResult.Partial(
+ strategyName = "category_bulk",
+ items = emptyList(),
+ warnings = warnings.toList()
+ ),
+ categories = fallbackCollector.entities().takeIf { it.isNotEmpty() },
+ stagedSessionId = sessionId,
+ stagedAcceptedCount = acceptedCount
)
- failedCategories > 0 -> CatalogStrategyResult.Failure(
- strategyName = "category_bulk",
- error = IllegalStateException("Movie category-bulk sync failed for all usable categories"),
- warnings = warnings.toList()
+ failedCategories > 0 -> CatalogSyncPayload(
+ catalogResult = CatalogStrategyResult.Failure(
+ strategyName = "category_bulk",
+ error = IllegalStateException("Movie category-bulk sync failed for all usable categories"),
+ warnings = warnings.toList()
+ ),
+ categories = null
)
- else -> CatalogStrategyResult.EmptyValid(
- strategyName = "category_bulk",
- warnings = listOf("All movie categories returned valid empty results.")
+ else -> CatalogSyncPayload(
+ catalogResult = CatalogStrategyResult.EmptyValid(
+ strategyName = "category_bulk",
+ warnings = listOf("All movie categories returned valid empty results.")
+ ),
+ categories = null
)
}
}
@@ -1395,190 +1825,410 @@ class SyncManager @Inject constructor(
provider: Provider,
api: XtreamProvider,
onProgress: ((String) -> Unit)?
- ): CatalogStrategyResult<Movie> {
- val moviesByStreamId = LinkedHashMap<Long, Movie>()
+ ): CatalogSyncPayload<Movie> {
+ val seenStreamIds = HashSet<Long>()
+ val fallbackCollector = FallbackCategoryCollector(provider.id, ContentType.MOVIE)
val warnings = mutableListOf<String>()
- var sawValidPage = false
- for (page in 1..XTREAM_CATALOG_MAX_PAGES) {
- progress(provider.id, onProgress, "Downloading Movies page $page...")
- rateLimitXtreamCatalogRequest()
- var rawStreams: List<XtreamStream> = emptyList()
- var pageFailure: Throwable? = null
- val pageElapsedMs = measureTimeMillis {
- runCatching {
- retryXtreamCatalogTransient {
- xtreamCatalogApiService.getVodStreams(
- XtreamUrlFactory.buildPlayerApiUrl(
- serverUrl = provider.serverUrl,
- username = provider.username,
- password = provider.password,
- action = "get_vod_streams",
- extraQueryParams = paginationParamsForPage(page)
- )
- )
- }
- }.onSuccess { streams ->
- rawStreams = streams
- }.onFailure { error ->
- pageFailure = error
+ var sessionId: Long? = null
+ var acceptedCount = 0
+ var nextPage = 1
+ var stopPaging = false
+ var forceSequential = false
+
+ while (nextPage <= XTREAM_CATALOG_MAX_PAGES && !stopPaging) {
+ val remainingPages = XTREAM_CATALOG_MAX_PAGES - nextPage + 1
+ val concurrency = xtreamAdaptiveSyncPolicy.concurrencyFor(
+ providerId = provider.id,
+ workloadSize = remainingPages,
+ preferSequential = forceSequential,
+ stage = XtreamAdaptiveSyncPolicy.Stage.PAGED
+ )
+ val pageWindow = (nextPage until (nextPage + concurrency))
+ .takeWhile { it <= XTREAM_CATALOG_MAX_PAGES }
+ progress(
+ provider.id,
+ onProgress,
+ if (pageWindow.size == 1) {
+ "Downloading Movies by page ${pageWindow.first()}..."
+ } else {
+ "Downloading Movies by page ${pageWindow.first()}-${pageWindow.last()}..."
}
- }
+ )
- if (pageFailure != null) {
- val failure = pageFailure!!
- Log.w(
- TAG,
- "Xtream paged movie request failed for provider ${provider.id} on page $page after ${pageElapsedMs}ms: ${failure::class.java.simpleName}: ${failure.message}"
+ var timedOutcomes = coroutineScope {
+ pageWindow.map { page ->
+ async { fetchMoviePageOutcome(provider, api, page) }
+ }.awaitAll()
+ }
+ val failures = timedOutcomes.count { it.outcome is PageFetchOutcome.Failure }
+ val recoveryPlan = evaluatePageRecoveryPlan(
+ provider = provider,
+ sectionLabel = "Movies",
+ pageWindow = pageWindow,
+ outcomes = timedOutcomes,
+ sequentialModeWarning = MOVIE_PAGED_SEQUENTIAL_MODE_WARNING
+ )
+ forceSequential = forceSequential || recoveryPlan.warnings.any { it == MOVIE_PAGED_SEQUENTIAL_MODE_WARNING }
+ warnings += recoveryPlan.warnings
+ if (recoveryPlan.stoppedEarly) {
+ stopPaging = true
+ }
+ if (!recoveryPlan.stoppedEarly && concurrency > 1 && shouldRetryFailedPages(pageWindow.size, failures, timedOutcomes.map { it.outcome })) {
+ timedOutcomes = continueFailedPageOutcomes(
+ provider = provider,
+ timedOutcomes = timedOutcomes,
+ fetchSequentially = { page -> fetchMoviePageOutcome(provider, api, page) }
)
- return if (page == 1 || moviesByStreamId.isEmpty()) {
- CatalogStrategyResult.Failure(
- strategyName = "paged",
- error = failure,
- warnings = listOf("Movie paging failed on the first page: ${failure.message}")
- )
- } else {
- warnings += "Movie paging failed on page $page: ${failure.message}"
- CatalogStrategyResult.Partial(
- strategyName = "paged",
- items = moviesByStreamId.values.toList(),
- warnings = warnings.toList()
- )
- }
}
- Log.i(
- TAG,
- "Xtream paged movie request for provider ${provider.id} page $page completed in ${pageElapsedMs}ms with ${rawStreams.size} raw items."
- )
+ var terminalFailure: Throwable? = null
+ var terminalFailurePage: Int? = null
+ timedOutcomes.sortedBy { it.page }.forEach { timedOutcome ->
+ when (val outcome = timedOutcome.outcome) {
+ is PageFetchOutcome.Success -> {
+ val staged = stageMovieItems(
+ providerId = provider.id,
+ items = outcome.items,
+ seenStreamIds = seenStreamIds,
+ fallbackCollector = fallbackCollector,
+ sessionId = sessionId
+ )
+ sessionId = staged.sessionId
+ acceptedCount += staged.acceptedCount
+ val newItems = staged.acceptedCount
+ if (outcome.rawCount < XTREAM_CATALOG_PAGE_SIZE || newItems == 0) {
+ stopPaging = true
+ }
+ }
+ is PageFetchOutcome.Empty -> {
+ stopPaging = true
+ }
+ is PageFetchOutcome.Failure -> {
+ warnings += pagingFailureWarning("Movies", outcome.page, outcome.error)
+ if (terminalFailure == null) {
+ terminalFailure = outcome.error
+ terminalFailurePage = outcome.page
+ }
+ }
+ }
+ }
- if (rawStreams.isEmpty()) {
- return when {
- moviesByStreamId.isNotEmpty() -> CatalogStrategyResult.Success(
- strategyName = "paged",
- items = moviesByStreamId.values.toList(),
- warnings = warnings.toList()
- )
- sawValidPage -> CatalogStrategyResult.EmptyValid(
- strategyName = "paged",
- warnings = listOf("Paged movie catalog returned no items.")
+ if (terminalFailure != null) {
+ return if (acceptedCount == 0) {
+ CatalogSyncPayload(
+ catalogResult = CatalogStrategyResult.Failure(
+ strategyName = "paged",
+ error = terminalFailure!!,
+ warnings = listOf(
+ pagingFailureWarning("Movies", terminalFailurePage ?: nextPage, terminalFailure!!)
+ )
+ )
+ ,
+ categories = null
)
- else -> CatalogStrategyResult.EmptyValid(
- strategyName = "paged",
- warnings = listOf("Paged movie catalog is unsupported or empty on this provider.")
+ } else {
+ CatalogSyncPayload(
+ catalogResult = CatalogStrategyResult.Partial(
+ strategyName = "paged",
+ items = emptyList(),
+ warnings = warnings.toList()
+ ),
+ categories = fallbackCollector.entities().takeIf { it.isNotEmpty() },
+ stagedSessionId = sessionId,
+ stagedAcceptedCount = acceptedCount
)
}
}
- sawValidPage = true
- val mappedMovies = api.mapVodStreamsResponse(rawStreams)
- val beforeCount = moviesByStreamId.size
- mappedMovies.forEach { movie ->
- if (movie.streamId > 0L) {
- moviesByStreamId[movie.streamId] = movie
- }
- }
- val newItems = moviesByStreamId.size - beforeCount
- if (rawStreams.size < XTREAM_CATALOG_PAGE_SIZE || newItems == 0) {
- break
- }
+ nextPage = pageWindow.last() + 1
}
- return moviesByStreamId.values.toList()
- .takeIf { it.isNotEmpty() }
- ?.let { items ->
- Log.i(TAG, "Xtream paged movie strategy completed for provider ${provider.id} with ${items.size} deduped items.")
- CatalogStrategyResult.Success("paged", items, warnings.toList())
- }
- ?: CatalogStrategyResult.EmptyValid(
- strategyName = "paged",
- warnings = listOf("Paged movie catalog completed without items.")
+ return if (acceptedCount > 0) {
+ Log.i(TAG, "Xtream paged movie strategy completed for provider ${provider.id} with $acceptedCount deduped items.")
+ CatalogSyncPayload(
+ catalogResult = CatalogStrategyResult.Success("paged", emptyList(), warnings.toList()),
+ categories = fallbackCollector.entities().takeIf { it.isNotEmpty() },
+ stagedSessionId = sessionId,
+ stagedAcceptedCount = acceptedCount
)
+ } else {
+ CatalogSyncPayload(
+ catalogResult = CatalogStrategyResult.EmptyValid(
+ strategyName = "paged",
+ warnings = listOf("Paged movie catalog completed without items.")
+ ),
+ categories = null
+ )
+ }
}
private suspend fun syncXtreamSeriesCatalog(
provider: Provider,
api: XtreamProvider,
+ existingMetadata: SyncMetadata,
onProgress: ((String) -> Unit)?
): CatalogSyncPayload<Series> {
Log.i(TAG, "Xtream series strategy start for provider ${provider.id}.")
- val rawSeriesCategories = runCatching {
- retryTransient {
- xtreamCatalogApiService.getSeriesCategories(
- XtreamUrlFactory.buildPlayerApiUrl(
- serverUrl = provider.serverUrl,
- username = provider.username,
- password = provider.password,
- action = "get_series_categories"
+ val rawSeriesCategories = when (val attempt = attemptNonCancellation {
+ retryXtreamCatalogTransient(provider.id) {
+ executeXtreamRequest(provider.id, XtreamAdaptiveSyncPolicy.Stage.LIGHTWEIGHT) {
+ xtreamCatalogApiService.getSeriesCategories(
+ XtreamUrlFactory.buildPlayerApiUrl(
+ serverUrl = provider.serverUrl,
+ username = provider.username,
+ password = provider.password,
+ action = "get_series_categories"
+ )
)
- )
+ }
}
- }.onFailure { error ->
- Log.w(TAG, "Xtream series categories request failed for provider ${provider.id}: ${sanitizeThrowableMessage(error)}")
- }.getOrNull()
+ }) {
+ is Attempt.Success -> attempt.value
+ is Attempt.Failure -> {
+ Log.w(TAG, "Xtream series categories request failed for provider ${provider.id}: ${sanitizeThrowableMessage(attempt.error)}")
+ null
+ }
+ }
val resolvedCategories = rawSeriesCategories
?.let { categories -> api.mapCategories(ContentType.SERIES, categories) }
?.map { category -> category.toEntity(provider.id) }
?.takeIf { it.isNotEmpty() }
+ var fullPayload = CatalogSyncPayload<Series>(
+ catalogResult = CatalogStrategyResult.EmptyValid("full"),
+ categories = null
+ )
+ var pagedPayload = CatalogSyncPayload<Series>(
+ catalogResult = CatalogStrategyResult.EmptyValid("paged"),
+ categories = null
+ )
+ var categoryPayload = CatalogSyncPayload<Series>(
+ catalogResult = CatalogStrategyResult.EmptyValid("category_bulk"),
+ categories = null
+ )
- val fullResult = loadXtreamSeriesFull(provider, api)
- when (fullResult) {
- is CatalogStrategyResult.Success -> return CatalogSyncPayload(
- catalogResult = fullResult,
- categories = resolvedCategories ?: buildFallbackSeriesCategories(provider.id, fullResult.items)
+ if (!resolvedCategories.isNullOrEmpty()) {
+ progress(provider.id, onProgress, "Preparing Series category sync...")
+ categoryPayload = loadXtreamSeriesByCategory(
+ provider,
+ api,
+ rawSeriesCategories.orEmpty(),
+ onProgress,
+ preferSequential = existingMetadata.seriesSequentialFailuresRemembered
)
+ when (val categoryResult = categoryPayload.catalogResult) {
+ is CatalogStrategyResult.Success,
+ is CatalogStrategyResult.Partial -> return CatalogSyncPayload(
+ catalogResult = categoryResult,
+ categories = resolvedCategories ?: categoryPayload.categories,
+ warnings = strategyWarnings(fullPayload.catalogResult),
+ strategyFeedback = XtreamStrategyFeedback(
+ preferredSegmentedFirst = true,
+ segmentedStressDetected = sawSegmentedStress(
+ warnings = strategyWarnings(fullPayload.catalogResult),
+ result = categoryResult,
+ sequentialWarnings = setOf(SERIES_CATEGORY_SEQUENTIAL_MODE_WARNING)
+ )
+ ),
+ stagedSessionId = categoryPayload.stagedSessionId,
+ stagedAcceptedCount = categoryPayload.stagedAcceptedCount
+ )
+ else -> Unit
+ }
+ }
+
+ progress(provider.id, onProgress, "Checking Series paged catalog...")
+ pagedPayload = loadXtreamSeriesByPage(provider, api, onProgress)
+ when (val pagedResult = pagedPayload.catalogResult) {
+ is CatalogStrategyResult.Success,
is CatalogStrategyResult.Partial -> return CatalogSyncPayload(
- catalogResult = fullResult,
- categories = resolvedCategories ?: buildFallbackSeriesCategories(provider.id, fullResult.items),
- warnings = emptyList()
+ catalogResult = pagedResult,
+ categories = resolvedCategories ?: pagedPayload.categories,
+ warnings = strategyWarnings(fullPayload.catalogResult) + strategyWarnings(categoryPayload.catalogResult),
+ strategyFeedback = XtreamStrategyFeedback(
+ preferredSegmentedFirst = true,
+ segmentedStressDetected = sawSegmentedStress(
+ warnings = strategyWarnings(fullPayload.catalogResult) + strategyWarnings(categoryPayload.catalogResult),
+ result = pagedResult,
+ sequentialWarnings = setOf(SERIES_CATEGORY_SEQUENTIAL_MODE_WARNING, SERIES_PAGED_SEQUENTIAL_MODE_WARNING)
+ )
+ ),
+ stagedSessionId = pagedPayload.stagedSessionId,
+ stagedAcceptedCount = pagedPayload.stagedAcceptedCount
)
else -> Unit
}
- val categoryResult = loadXtreamSeriesByCategory(provider, api, rawSeriesCategories.orEmpty(), onProgress, preferSequential = false)
- when (categoryResult) {
- is CatalogStrategyResult.Success -> return CatalogSyncPayload(
- catalogResult = categoryResult,
- categories = resolvedCategories ?: buildFallbackSeriesCategories(provider.id, categoryResult.items),
- warnings = strategyWarnings(fullResult)
+ if (resolvedCategories.isNullOrEmpty()) {
+ progress(provider.id, onProgress, "Preparing Series category sync...")
+ categoryPayload = loadXtreamSeriesByCategory(
+ provider,
+ api,
+ rawSeriesCategories.orEmpty(),
+ onProgress,
+ preferSequential = existingMetadata.seriesSequentialFailuresRemembered
)
- is CatalogStrategyResult.Partial -> return CatalogSyncPayload(
- catalogResult = categoryResult,
- categories = resolvedCategories ?: buildFallbackSeriesCategories(provider.id, categoryResult.items),
- warnings = strategyWarnings(fullResult)
+ when (val categoryResult = categoryPayload.catalogResult) {
+ is CatalogStrategyResult.Success,
+ is CatalogStrategyResult.Partial -> return CatalogSyncPayload(
+ catalogResult = categoryResult,
+ categories = categoryPayload.categories,
+ warnings = strategyWarnings(fullPayload.catalogResult) + strategyWarnings(pagedPayload.catalogResult),
+ strategyFeedback = XtreamStrategyFeedback(
+ preferredSegmentedFirst = true,
+ segmentedStressDetected = sawSegmentedStress(
+ warnings = strategyWarnings(fullPayload.catalogResult) + strategyWarnings(pagedPayload.catalogResult),
+ result = categoryResult,
+ sequentialWarnings = setOf(SERIES_CATEGORY_SEQUENTIAL_MODE_WARNING, SERIES_PAGED_SEQUENTIAL_MODE_WARNING)
+ )
+ ),
+ stagedSessionId = categoryPayload.stagedSessionId,
+ stagedAcceptedCount = categoryPayload.stagedAcceptedCount
+ )
+ else -> Unit
+ }
+ }
+
+ progress(provider.id, onProgress, "Checking Series full catalog...")
+ fullPayload = loadXtreamSeriesFull(provider, api)
+ when (val fullResult = fullPayload.catalogResult) {
+ is CatalogStrategyResult.Success -> return CatalogSyncPayload(
+ catalogResult = fullResult,
+ categories = resolvedCategories ?: fullPayload.categories,
+ warnings = strategyWarnings(categoryPayload.catalogResult) + strategyWarnings(pagedPayload.catalogResult),
+ strategyFeedback = XtreamStrategyFeedback(
+ preferredSegmentedFirst = true,
+ attemptedFullCatalog = true,
+ fullCatalogUnsafe = false
+ ),
+ stagedSessionId = fullPayload.stagedSessionId,
+ stagedAcceptedCount = fullPayload.stagedAcceptedCount
)
else -> Unit
}
- val pagedResult = loadXtreamSeriesByPage(provider, api, onProgress)
- return CatalogSyncPayload(
- catalogResult = pagedResult,
- categories = when (pagedResult) {
- is CatalogStrategyResult.Success -> resolvedCategories ?: buildFallbackSeriesCategories(provider.id, pagedResult.items)
- is CatalogStrategyResult.Partial -> resolvedCategories ?: buildFallbackSeriesCategories(provider.id, pagedResult.items)
- else -> null
- },
- warnings = strategyWarnings(fullResult) + strategyWarnings(categoryResult)
+ val lazyWarnings = buildList {
+ addAll(strategyWarnings(categoryPayload.catalogResult))
+ addAll(strategyWarnings(pagedPayload.catalogResult))
+ addAll(strategyWarnings(fullPayload.catalogResult))
+ add("Series entered lazy category-only mode after category-bulk, paged, and full strategies failed.")
+ }
+ Log.w(
+ TAG,
+ "Xtream series strategy exhausted for provider ${provider.id}. categoriesAvailable=${!resolvedCategories.isNullOrEmpty()} finalMode=${if (!resolvedCategories.isNullOrEmpty()) "lazy_by_category" else "unavailable"}"
)
+
+ return if (!resolvedCategories.isNullOrEmpty()) {
+ CatalogSyncPayload(
+ catalogResult = CatalogStrategyResult.Failure(
+ strategyName = "lazy_by_category",
+ error = IllegalStateException("Series catalog strategies failed; exposing categories only"),
+ warnings = lazyWarnings
+ ),
+ categories = resolvedCategories,
+ warnings = lazyWarnings,
+ strategyFeedback = XtreamStrategyFeedback(
+ preferredSegmentedFirst = true,
+ attemptedFullCatalog = true,
+ segmentedStressDetected = true
+ )
+ )
+ } else {
+ CatalogSyncPayload(
+ catalogResult = CatalogStrategyResult.Failure(
+ strategyName = "series",
+ error = IllegalStateException("Series catalog strategies failed and no categories were available"),
+ warnings = lazyWarnings
+ ),
+ categories = null,
+ warnings = lazyWarnings,
+ strategyFeedback = XtreamStrategyFeedback(
+ preferredSegmentedFirst = true,
+ attemptedFullCatalog = true,
+ segmentedStressDetected = true
+ )
+ )
+ }
}
private suspend fun loadXtreamSeriesFull(
provider: Provider,
api: XtreamProvider
- ): CatalogStrategyResult<Series> {
- var fullSeries: List<Series>? = null
+ ): CatalogSyncPayload<Series> {
+ val fallbackCollector = FallbackCategoryCollector(provider.id, ContentType.SERIES)
+ val seenSeriesIds = HashSet<Long>()
+ val rawBatch = ArrayList<XtreamSeriesItem>(XTREAM_FALLBACK_STAGE_BATCH_SIZE)
+ var stagedSessionId: Long? = null
+ var acceptedCount = 0
+ var streamedRawCount = 0
var fullSeriesFailure: Throwable? = null
+
+ suspend fun flushRawBatch() {
+ if (rawBatch.isEmpty()) return
+ val staged = stageSeriesSequence(
+ providerId = provider.id,
+ items = api.mapSeriesListSequence(rawBatch.asSequence()),
+ seenSeriesIds = seenSeriesIds,
+ fallbackCollector = fallbackCollector,
+ sessionId = stagedSessionId
+ )
+ stagedSessionId = staged.sessionId
+ acceptedCount += staged.acceptedCount
+ rawBatch.clear()
+ }
+
val fullSeriesElapsedMs = measureTimeMillis {
- runCatching {
- retryXtreamCatalogTransient { api.getSeriesList().getOrThrow("Series list") }
- }.onSuccess { series ->
- fullSeries = series
- }.onFailure { error ->
- fullSeriesFailure = error
+ when (val attempt = attemptNonCancellation {
+ retryXtreamCatalogTransient(provider.id) {
+ executeXtreamRequest(provider.id, XtreamAdaptiveSyncPolicy.Stage.HEAVY) {
+ xtreamCatalogHttpService.streamSeriesList(
+ XtreamUrlFactory.buildPlayerApiUrl(
+ serverUrl = provider.serverUrl,
+ username = provider.username,
+ password = provider.password,
+ action = "get_series"
+ )
+ ) { item ->
+ rawBatch += item
+ streamedRawCount++
+ if (rawBatch.size >= XTREAM_FALLBACK_STAGE_BATCH_SIZE) {
+ flushRawBatch()
+ }
+ }.also {
+ flushRawBatch()
+ }
+ }
+ }
+ }) {
+ is Attempt.Success -> Unit
+ is Attempt.Failure -> {
+ fullSeriesFailure = attempt.error
+ stagedSessionId?.let { sessionId ->
+ syncCatalogStore.discardStagedImport(provider.id, sessionId)
+ stagedSessionId = null
+ }
+ }
}
}
- if (!fullSeries.isNullOrEmpty()) {
- Log.i(TAG, "Xtream series full catalog succeeded for provider ${provider.id} in ${fullSeriesElapsedMs}ms with ${fullSeries!!.size} items.")
- return CatalogStrategyResult.Success("full", fullSeries!!)
+ if (streamedRawCount > 0) {
+ Log.i(
+ TAG,
+ "Xtream series full catalog succeeded for provider ${provider.id} in ${fullSeriesElapsedMs}ms with $acceptedCount accepted items from $streamedRawCount raw items."
+ )
+ if (acceptedCount == 0) {
+ return CatalogSyncPayload(
+ catalogResult = CatalogStrategyResult.EmptyValid(
+ strategyName = "full",
+ warnings = listOf("Series full catalog returned raw items but none were usable after mapping.")
+ ),
+ categories = null
+ )
+ }
+ return CatalogSyncPayload(
+ catalogResult = CatalogStrategyResult.Success("full", emptyList()),
+ categories = fallbackCollector.entities().takeIf { it.isNotEmpty() },
+ stagedSessionId = stagedSessionId,
+ stagedAcceptedCount = acceptedCount
+ )
}
return if (fullSeriesFailure != null) {
logXtreamCatalogFallback(
@@ -1586,14 +2236,17 @@ class SyncManager @Inject constructor(
section = "series",
stage = "full catalog",
elapsedMs = fullSeriesElapsedMs,
- itemCount = fullSeries?.size,
+ itemCount = streamedRawCount,
error = fullSeriesFailure,
nextStep = "category-bulk"
)
- CatalogStrategyResult.Failure(
- strategyName = "full",
- error = fullSeriesFailure!!,
- warnings = listOf("Series full catalog request failed: ${sanitizeThrowableMessage(fullSeriesFailure)}")
+ CatalogSyncPayload(
+ catalogResult = CatalogStrategyResult.Failure(
+ strategyName = "full",
+ error = fullSeriesFailure!!,
+ warnings = listOf(fullCatalogFallbackWarning("Series", fullSeriesFailure))
+ ),
+ categories = null
)
} else {
logXtreamCatalogFallback(
@@ -1601,13 +2254,16 @@ class SyncManager @Inject constructor(
section = "series",
stage = "full catalog",
elapsedMs = fullSeriesElapsedMs,
- itemCount = fullSeries?.size,
+ itemCount = streamedRawCount,
error = null,
nextStep = "category-bulk"
)
- CatalogStrategyResult.EmptyValid(
- strategyName = "full",
- warnings = listOf("Series full catalog returned an empty valid result.")
+ CatalogSyncPayload(
+ catalogResult = CatalogStrategyResult.EmptyValid(
+ strategyName = "full",
+ warnings = listOf("Series full catalog returned an empty valid result.")
+ ),
+ categories = null
)
}
}
@@ -1618,114 +2274,111 @@ class SyncManager @Inject constructor(
rawCategories: List<XtreamCategory>,
onProgress: ((String) -> Unit)?,
preferSequential: Boolean
- ): CatalogStrategyResult<Series> {
+ ): CatalogSyncPayload<Series> {
val categories = rawCategories.filter { it.categoryId.isNotBlank() }
if (categories.isEmpty()) {
- return CatalogStrategyResult.Failure(
- strategyName = "category_bulk",
- error = IllegalStateException("No series categories available"),
- warnings = listOf("Series category-bulk strategy was unavailable because no categories were returned.")
+ return CatalogSyncPayload(
+ catalogResult = CatalogStrategyResult.Failure(
+ strategyName = "category_bulk",
+ error = IllegalStateException("No series categories available"),
+ warnings = listOf("Series category-bulk strategy was unavailable because no categories were returned.")
+ ),
+ categories = null
)
}
- val concurrency = if (preferSequential) 1 else xtreamCategorySyncConcurrency(categories.size)
- val semaphore = Semaphore(concurrency)
- val progressCounter = java.util.concurrent.atomic.AtomicInteger(0)
- val failureCount = java.util.concurrent.atomic.AtomicInteger(0)
- val fastFailureCount = java.util.concurrent.atomic.AtomicInteger(0)
- val warnings = mutableListOf<String>()
- val warningsMutex = Mutex()
- progress(provider.id, onProgress, "Downloading Series 0/${categories.size}...")
-
- val categoryOutcomes = coroutineScope {
- categories.map { category ->
- async {
- semaphore.withPermit {
- rateLimitXtreamCatalogRequest()
- var rawSeries: List<XtreamSeriesItem> = emptyList()
- var categoryFailure: Throwable? = null
- val elapsedMs = measureTimeMillis {
- runCatching {
- retryXtreamCatalogTransient {
- xtreamCatalogApiService.getSeriesList(
- XtreamUrlFactory.buildPlayerApiUrl(
- serverUrl = provider.serverUrl,
- username = provider.username,
- password = provider.password,
- action = "get_series",
- extraQueryParams = mapOf("category_id" to category.categoryId)
- )
- )
- }
- }.onSuccess { series ->
- rawSeries = series
- }.onFailure { error ->
- categoryFailure = error
- }
- }
+ val concurrency = xtreamAdaptiveSyncPolicy.concurrencyFor(
+ providerId = provider.id,
+ workloadSize = categories.size,
+ preferSequential = preferSequential,
+ stage = XtreamAdaptiveSyncPolicy.Stage.CATEGORY
+ )
+ progress(provider.id, onProgress, "Downloading Series by category 0/${categories.size}...")
- val completed = progressCounter.incrementAndGet()
- progress(provider.id, onProgress, "Downloading Series $completed/${categories.size}...")
-
- when {
- categoryFailure != null -> {
- failureCount.incrementAndGet()
- if (elapsedMs <= 5_000L) fastFailureCount.incrementAndGet()
- val failure = categoryFailure!!
- warningsMutex.withLock {
- warnings += "Series category '${category.categoryName}' failed: ${sanitizeThrowableMessage(failure)}"
- }
- Log.w(TAG, "Xtream series category '${category.categoryName}' failed after ${elapsedMs}ms: ${sanitizeThrowableMessage(failure)}")
- CategoryFetchOutcome.Failure(category.categoryName, failure)
- }
- rawSeries.isEmpty() -> {
- Log.i(TAG, "Xtream series category '${category.categoryName}' completed in ${elapsedMs}ms with a valid empty result.")
- CategoryFetchOutcome.Empty(category.categoryName)
- }
- else -> {
- Log.i(TAG, "Xtream series category '${category.categoryName}' completed in ${elapsedMs}ms with ${rawSeries.size} raw items.")
- CategoryFetchOutcome.Success(category.categoryName, api.mapSeriesListResponse(rawSeries))
- }
- }
- }
- }
- }.awaitAll()
+ val executionPlan = executeCategoryRecoveryPlan(
+ provider = provider,
+ categories = categories,
+ initialConcurrency = concurrency,
+ sectionLabel = "Series",
+ sequentialModeWarning = SERIES_CATEGORY_SEQUENTIAL_MODE_WARNING,
+ onProgress = onProgress,
+ fetch = { category -> fetchSeriesCategoryOutcome(provider, api, category) }
+ )
+ var timedOutcomes = executionPlan.outcomes
+
+ val categoryOutcomes = timedOutcomes.map { it.outcome }
+ val failureCount = timedOutcomes.count { it.outcome is CategoryFetchOutcome.Failure }
+ val fastFailureCount = timedOutcomes.count {
+ it.elapsedMs <= 5_000L && it.outcome is CategoryFetchOutcome.Failure
}
- if (concurrency > 1 && shouldDowngradeCategorySync(categories.size, failureCount.get(), fastFailureCount.get(), categoryOutcomes)) {
- Log.w(TAG, "Xtream series category sync is downgrading to sequential mode for provider ${provider.id}.")
- return when (val sequentialResult = loadXtreamSeriesByCategory(provider, api, rawCategories, onProgress, preferSequential = true)) {
- is CatalogStrategyResult.Success -> sequentialResult.copy(warnings = sequentialResult.warnings + SERIES_CATEGORY_SEQUENTIAL_MODE_WARNING)
- is CatalogStrategyResult.Partial -> sequentialResult.copy(warnings = sequentialResult.warnings + SERIES_CATEGORY_SEQUENTIAL_MODE_WARNING)
- is CatalogStrategyResult.Failure -> sequentialResult.copy(warnings = sequentialResult.warnings + SERIES_CATEGORY_SEQUENTIAL_MODE_WARNING)
- is CatalogStrategyResult.EmptyValid -> sequentialResult.copy(warnings = sequentialResult.warnings + SERIES_CATEGORY_SEQUENTIAL_MODE_WARNING)
- }
+ val downgradeRecommended = shouldDowngradeCategorySync(categories.size, failureCount, fastFailureCount, categoryOutcomes)
+ var fallbackWarnings = executionPlan.warnings
+ if (concurrency > 1 && shouldRetryFailedCategories(categories.size, failureCount, downgradeRecommended, categoryOutcomes)) {
+ Log.w(TAG, "Xtream series category sync is continuing in sequential mode for failed categories on provider ${provider.id}.")
+ timedOutcomes = continueFailedCategoryOutcomes(
+ provider = provider,
+ timedOutcomes = timedOutcomes,
+ fetchSequentially = { category -> fetchSeriesCategoryOutcome(provider, api, category) }
+ )
+ fallbackWarnings = (fallbackWarnings + if (downgradeRecommended) listOf(SERIES_CATEGORY_SEQUENTIAL_MODE_WARNING) else emptyList()).distinct()
}
- val series = categoryOutcomes
- .asSequence()
+ val finalOutcomes = timedOutcomes.map { it.outcome }
+ val warnings = finalOutcomes
+ .filterIsInstance<CategoryFetchOutcome.Failure>()
+ .map { failure -> categoryFailureWarning("Series", failure.categoryName, failure.error) } +
+ fallbackWarnings
+
+ val seenSeriesIds = HashSet<Long>()
+ val fallbackCollector = FallbackCategoryCollector(provider.id, ContentType.SERIES)
+ var sessionId: Long? = null
+ var acceptedCount = 0
+ finalOutcomes
.filterIsInstance<CategoryFetchOutcome.Success<Series>>()
- .flatMap { it.items.asSequence() }
- .filter { it.seriesId > 0L }
- .associateBy { it.seriesId }
- .values
- .toList()
- val failedCategories = categoryOutcomes.count { it is CategoryFetchOutcome.Failure }
- val emptyCategories = categoryOutcomes.count { it is CategoryFetchOutcome.Empty }
- val successfulCategories = categoryOutcomes.count { it is CategoryFetchOutcome.Success }
- Log.i(TAG, "Xtream series category strategy summary for provider ${provider.id}: successful=$successfulCategories empty=$emptyCategories failed=$failedCategories dedupedSeries=${series.size} concurrency=$concurrency")
+ .forEach { success ->
+ val staged = stageSeriesItems(
+ providerId = provider.id,
+ items = success.items,
+ seenSeriesIds = seenSeriesIds,
+ fallbackCollector = fallbackCollector,
+ sessionId = sessionId
+ )
+ sessionId = staged.sessionId
+ acceptedCount += staged.acceptedCount
+ }
+ val failedCategories = finalOutcomes.count { it is CategoryFetchOutcome.Failure }
+ val emptyCategories = finalOutcomes.count { it is CategoryFetchOutcome.Empty }
+ val successfulCategories = finalOutcomes.count { it is CategoryFetchOutcome.Success }
+ Log.i(TAG, "Xtream series category strategy summary for provider ${provider.id}: successful=$successfulCategories empty=$emptyCategories failed=$failedCategories dedupedSeries=$acceptedCount concurrency=$concurrency")
return when {
- series.isNotEmpty() && failedCategories == 0 -> CatalogStrategyResult.Success("category_bulk", series, warnings.toList())
- series.isNotEmpty() -> CatalogStrategyResult.Partial("category_bulk", series, warnings.toList())
- failedCategories > 0 -> CatalogStrategyResult.Failure(
- strategyName = "category_bulk",
- error = IllegalStateException("Series category-bulk sync failed for all usable categories"),
- warnings = warnings.toList()
+ acceptedCount > 0 && failedCategories == 0 -> CatalogSyncPayload(
+ catalogResult = CatalogStrategyResult.Success("category_bulk", emptyList(), warnings.toList()),
+ categories = fallbackCollector.entities().takeIf { it.isNotEmpty() },
+ stagedSessionId = sessionId,
+ stagedAcceptedCount = acceptedCount
)
- else -> CatalogStrategyResult.EmptyValid(
- strategyName = "category_bulk",
- warnings = listOf("All series categories returned valid empty results.")
+ acceptedCount > 0 -> CatalogSyncPayload(
+ catalogResult = CatalogStrategyResult.Partial("category_bulk", emptyList(), warnings.toList()),
+ categories = fallbackCollector.entities().takeIf { it.isNotEmpty() },
+ stagedSessionId = sessionId,
+ stagedAcceptedCount = acceptedCount
+ )
+ failedCategories > 0 -> CatalogSyncPayload(
+ catalogResult = CatalogStrategyResult.Failure(
+ strategyName = "category_bulk",
+ error = IllegalStateException("Series category-bulk sync failed for all usable categories"),
+ warnings = warnings.toList()
+ ),
+ categories = null
+ )
+ else -> CatalogSyncPayload(
+ catalogResult = CatalogStrategyResult.EmptyValid(
+ strategyName = "category_bulk",
+ warnings = listOf("All series categories returned valid empty results.")
+ ),
+ categories = null
)
}
}
@@ -1734,84 +2387,140 @@ class SyncManager @Inject constructor(
provider: Provider,
api: XtreamProvider,
onProgress: ((String) -> Unit)?
- ): CatalogStrategyResult<Series> {
- val seriesById = LinkedHashMap<Long, Series>()
+ ): CatalogSyncPayload<Series> {
+ val seenSeriesIds = HashSet<Long>()
+ val fallbackCollector = FallbackCategoryCollector(provider.id, ContentType.SERIES)
val warnings = mutableListOf<String>()
- var sawValidPage = false
- for (page in 1..XTREAM_CATALOG_MAX_PAGES) {
- progress(provider.id, onProgress, "Downloading Series page $page...")
- rateLimitXtreamCatalogRequest()
- var rawSeries: List<XtreamSeriesItem> = emptyList()
- var pageFailure: Throwable? = null
- val pageElapsedMs = measureTimeMillis {
- runCatching {
- retryXtreamCatalogTransient {
- xtreamCatalogApiService.getSeriesList(
- XtreamUrlFactory.buildPlayerApiUrl(
- serverUrl = provider.serverUrl,
- username = provider.username,
- password = provider.password,
- action = "get_series",
- extraQueryParams = paginationParamsForPage(page)
- )
+ var sessionId: Long? = null
+ var acceptedCount = 0
+ var nextPage = 1
+ var stopPaging = false
+ var forceSequential = false
+
+ while (nextPage <= XTREAM_CATALOG_MAX_PAGES && !stopPaging) {
+ val remainingPages = XTREAM_CATALOG_MAX_PAGES - nextPage + 1
+ val concurrency = xtreamAdaptiveSyncPolicy.concurrencyFor(
+ providerId = provider.id,
+ workloadSize = remainingPages,
+ preferSequential = forceSequential,
+ stage = XtreamAdaptiveSyncPolicy.Stage.PAGED
+ )
+ val pageWindow = (nextPage until (nextPage + concurrency))
+ .takeWhile { it <= XTREAM_CATALOG_MAX_PAGES }
+ progress(
+ provider.id,
+ onProgress,
+ if (pageWindow.size == 1) {
+ "Downloading Series by page ${pageWindow.first()}..."
+ } else {
+ "Downloading Series by page ${pageWindow.first()}-${pageWindow.last()}..."
+ }
+ )
+
+ var timedOutcomes = coroutineScope {
+ pageWindow.map { page ->
+ async { fetchSeriesPageOutcome(provider, api, page) }
+ }.awaitAll()
+ }
+ val failures = timedOutcomes.count { it.outcome is PageFetchOutcome.Failure }
+ val recoveryPlan = evaluatePageRecoveryPlan(
+ provider = provider,
+ sectionLabel = "Series",
+ pageWindow = pageWindow,
+ outcomes = timedOutcomes,
+ sequentialModeWarning = SERIES_PAGED_SEQUENTIAL_MODE_WARNING
+ )
+ forceSequential = forceSequential || recoveryPlan.warnings.any { it == SERIES_PAGED_SEQUENTIAL_MODE_WARNING }
+ warnings += recoveryPlan.warnings
+ if (recoveryPlan.stoppedEarly) {
+ stopPaging = true
+ }
+ if (!recoveryPlan.stoppedEarly && concurrency > 1 && shouldRetryFailedPages(pageWindow.size, failures, timedOutcomes.map { it.outcome })) {
+ timedOutcomes = continueFailedPageOutcomes(
+ provider = provider,
+ timedOutcomes = timedOutcomes,
+ fetchSequentially = { page -> fetchSeriesPageOutcome(provider, api, page) }
+ )
+ }
+
+ var terminalFailure: Throwable? = null
+ var terminalFailurePage: Int? = null
+ timedOutcomes.sortedBy { it.page }.forEach { timedOutcome ->
+ when (val outcome = timedOutcome.outcome) {
+ is PageFetchOutcome.Success -> {
+ val staged = stageSeriesItems(
+ providerId = provider.id,
+ items = outcome.items,
+ seenSeriesIds = seenSeriesIds,
+ fallbackCollector = fallbackCollector,
+ sessionId = sessionId
)
+ sessionId = staged.sessionId
+ acceptedCount += staged.acceptedCount
+ val newItems = staged.acceptedCount
+ if (outcome.rawCount < XTREAM_CATALOG_PAGE_SIZE || newItems == 0) {
+ stopPaging = true
+ }
+ }
+ is PageFetchOutcome.Empty -> {
+ stopPaging = true
+ }
+ is PageFetchOutcome.Failure -> {
+ warnings += pagingFailureWarning("Series", outcome.page, outcome.error)
+ if (terminalFailure == null) {
+ terminalFailure = outcome.error
+ terminalFailurePage = outcome.page
+ }
}
- }.onSuccess { series ->
- rawSeries = series
- }.onFailure { error ->
- pageFailure = error
}
}
- if (pageFailure != null) {
- val failure = pageFailure!!
- Log.w(TAG, "Xtream paged series request failed for provider ${provider.id} on page $page after ${pageElapsedMs}ms: ${sanitizeThrowableMessage(failure)}")
- return if (page == 1 || seriesById.isEmpty()) {
- CatalogStrategyResult.Failure(
- strategyName = "paged",
- error = failure,
- warnings = listOf("Series paging failed on the first page: ${sanitizeThrowableMessage(failure)}")
+ if (terminalFailure != null) {
+ return if (acceptedCount == 0) {
+ CatalogSyncPayload(
+ catalogResult = CatalogStrategyResult.Failure(
+ strategyName = "paged",
+ error = terminalFailure!!,
+ warnings = listOf(
+ pagingFailureWarning("Series", terminalFailurePage ?: nextPage, terminalFailure!!)
+ )
+ )
+ ,
+ categories = null
)
} else {
- warnings += "Series paging failed on page $page: ${sanitizeThrowableMessage(failure)}"
- CatalogStrategyResult.Partial(
- strategyName = "paged",
- items = seriesById.values.toList(),
- warnings = warnings.toList()
+ CatalogSyncPayload(
+ catalogResult = CatalogStrategyResult.Partial(
+ strategyName = "paged",
+ items = emptyList(),
+ warnings = warnings.toList()
+ ),
+ categories = fallbackCollector.entities().takeIf { it.isNotEmpty() },
+ stagedSessionId = sessionId,
+ stagedAcceptedCount = acceptedCount
)
}
}
- Log.i(TAG, "Xtream paged series request for provider ${provider.id} page $page completed in ${pageElapsedMs}ms with ${rawSeries.size} raw items.")
- if (rawSeries.isEmpty()) {
- return when {
- seriesById.isNotEmpty() -> CatalogStrategyResult.Success("paged", seriesById.values.toList(), warnings.toList())
- sawValidPage -> CatalogStrategyResult.EmptyValid("paged", listOf("Paged series catalog returned no items."))
- else -> CatalogStrategyResult.EmptyValid("paged", listOf("Paged series catalog is unsupported or empty on this provider."))
- }
- }
-
- sawValidPage = true
- val mappedSeries = api.mapSeriesListResponse(rawSeries)
- val beforeCount = seriesById.size
- mappedSeries.forEach { item ->
- if (item.seriesId > 0L) {
- seriesById[item.seriesId] = item
- }
- }
- val newItems = seriesById.size - beforeCount
- if (rawSeries.size < XTREAM_CATALOG_PAGE_SIZE || newItems == 0) {
- break
- }
+ nextPage = pageWindow.last() + 1
}
- return seriesById.values.toList()
- .takeIf { it.isNotEmpty() }
- ?.let { items -> CatalogStrategyResult.Success("paged", items, warnings.toList()) }
- ?: CatalogStrategyResult.EmptyValid(
- strategyName = "paged",
- warnings = listOf("Paged series catalog completed without items.")
+ return if (acceptedCount > 0) {
+ CatalogSyncPayload(
+ catalogResult = CatalogStrategyResult.Success("paged", emptyList(), warnings.toList()),
+ categories = fallbackCollector.entities().takeIf { it.isNotEmpty() },
+ stagedSessionId = sessionId,
+ stagedAcceptedCount = acceptedCount
)
+ } else {
+ CatalogSyncPayload(
+ catalogResult = CatalogStrategyResult.EmptyValid(
+ strategyName = "paged",
+ warnings = listOf("Paged series catalog completed without items.")
+ ),
+ categories = null
+ )
+ }
}
private suspend fun updateSyncStatusMetadata(providerId: Long, status: String) {
@@ -1831,8 +2540,8 @@ class SyncManager @Inject constructor(
throw IllegalStateException(message)
}
progress(provider.id, onProgress, "Downloading Playlist...")
- val existingChannelIds = if (includeLive) channelDao.getIdMappings(provider.id).associate { it.remoteId to it.id } else emptyMap()
- val existingMovieIds = if (includeMovies) movieDao.getIdMappings(provider.id).associate { it.remoteId to it.id } else emptyMap()
+ syncCatalogStore.clearProviderStaging(provider.id)
+ val sessionId = syncCatalogStore.newSessionId()
val stableLongHasher = StableLongHasher()
val liveCategories = CategoryAccumulator(provider.id, ContentType.LIVE, stableLongHasher)
val movieCategories = CategoryAccumulator(provider.id, ContentType.MOVIE, stableLongHasher)
@@ -1848,108 +2557,129 @@ class SyncManager @Inject constructor(
val warnings = mutableListOf<String>()
var insecureStreamCount = 0
- openPlaylistStream(provider) { streamed ->
- progress(provider.id, onProgress, "Parsing Playlist...")
- maybeDecompressPlaylist(streamed).use { input ->
- m3uParser.parseStreaming(
- inputStream = input,
- onHeader = { parsedHeader ->
- val secureEpgUrl = parsedHeader.tvgUrl?.takeIf { UrlSecurityPolicy.isSecureRemoteUrl(it) }
- if (parsedHeader.tvgUrl != null && secureEpgUrl == null) {
- warnings += "Ignored insecure EPG URL from playlist header."
- }
- header = parsedHeader.copy(tvgUrl = secureEpgUrl)
- }
- ) { entry ->
- parsedCount++
- if (parsedCount >= nextMilestone) {
- progress(provider.id, onProgress, "Imported $parsedCount playlist entries...")
- nextMilestone += PROGRESS_INTERVAL
- }
- if (!UrlSecurityPolicy.isAllowedStreamEntryUrl(entry.url)) {
- insecureStreamCount++
- return@parseStreaming
- }
-
- val safeLogoUrl = UrlSecurityPolicy.sanitizeImportedAssetUrl(entry.tvgLogo)
- val safeCatchUpSource = UrlSecurityPolicy.sanitizeImportedAssetUrl(entry.catchUpSource)
-
- if (isVodEntry(entry)) {
- if (!includeMovies) {
- return@parseStreaming
+ try {
+ openPlaylistStream(provider) { streamed ->
+ progress(provider.id, onProgress, "Parsing Playlist...")
+ maybeDecompressPlaylist(streamed).use { input ->
+ m3uParser.parseStreaming(
+ inputStream = input,
+ onHeader = { parsedHeader ->
+ val secureEpgUrl = parsedHeader.tvgUrl?.takeIf { UrlSecurityPolicy.isSecureRemoteUrl(it) }
+ if (parsedHeader.tvgUrl != null && secureEpgUrl == null) {
+ warnings += "Ignored insecure EPG URL from playlist header."
+ }
+ header = parsedHeader.copy(tvgUrl = secureEpgUrl)
}
- val groupTitle = entry.groupTitle.ifBlank { "Uncategorized" }
- val stableStreamId = stableId(provider.id, entry.tvgId, entry.url, stableLongHasher)
- val categoryId = movieCategories.idFor(groupTitle)
- val isAdult = AdultContentClassifier.isAdultCategoryName(groupTitle)
- seenMovieStreamIds?.add(stableStreamId)
- movieBatch.add(
- MovieEntity(
- id = existingMovieIds[stableStreamId] ?: 0L,
- streamId = stableStreamId,
- name = entry.name,
- posterUrl = safeLogoUrl,
- categoryId = categoryId,
- categoryName = groupTitle,
- streamUrl = entry.url,
- providerId = provider.id,
- rating = entry.rating?.toFloatOrNull() ?: 0f,
- year = entry.year,
- genre = entry.genre,
- isAdult = isAdult
- )
- )
- movieCount++
- if (movieBatch.size >= batchSize) {
- flushMovieBatch(movieBatch)
+ ) { entry ->
+ parsedCount++
+ if (parsedCount >= nextMilestone) {
+ progress(provider.id, onProgress, "Imported $parsedCount playlist entries...")
+ nextMilestone += PROGRESS_INTERVAL
}
- } else {
- if (!includeLive) {
+ if (!UrlSecurityPolicy.isAllowedStreamEntryUrl(entry.url)) {
+ insecureStreamCount++
return@parseStreaming
}
- val groupTitle = entry.groupTitle.ifBlank { "Uncategorized" }
- val stableStreamId = stableId(provider.id, entry.tvgId, entry.url, stableLongHasher)
- val categoryId = liveCategories.idFor(groupTitle)
- val isAdult = AdultContentClassifier.isAdultCategoryName(groupTitle)
- seenLiveStreamIds?.add(stableStreamId)
- channelBatch.add(
- ChannelEntity(
- id = existingChannelIds[stableStreamId] ?: 0L,
- streamId = stableStreamId,
- name = entry.name,
- logoUrl = safeLogoUrl,
+
+ val safeLogoUrl = UrlSecurityPolicy.sanitizeImportedAssetUrl(entry.tvgLogo)
+ val safeCatchUpSource = UrlSecurityPolicy.sanitizeImportedAssetUrl(entry.catchUpSource)
+
+ if (isVodEntry(entry)) {
+ if (!includeMovies) {
+ return@parseStreaming
+ }
+ val groupTitle = entry.groupTitle.ifBlank { "Uncategorized" }
+ val stableStreamId = stableId(
+ providerId = provider.id,
+ contentType = ContentType.MOVIE,
+ tvgId = entry.tvgId,
+ url = entry.url,
+ title = entry.name,
groupTitle = groupTitle,
- categoryId = categoryId,
- categoryName = groupTitle,
- epgChannelId = entry.tvgId ?: entry.tvgName,
- number = entry.tvgChno ?: 0,
- streamUrl = entry.url,
- catchUpSupported = entry.catchUp != null,
- catchUpDays = entry.catchUpDays ?: 0,
- catchUpSource = safeCatchUpSource,
+ hasher = stableLongHasher
+ )
+ if (seenMovieStreamIds?.add(stableStreamId) != true) {
+ return@parseStreaming
+ }
+ val categoryId = movieCategories.idFor(groupTitle)
+ val isAdult = AdultContentClassifier.isAdultCategoryName(groupTitle)
+ movieBatch.add(
+ MovieEntity(
+ streamId = stableStreamId,
+ name = entry.name,
+ posterUrl = safeLogoUrl,
+ categoryId = categoryId,
+ categoryName = groupTitle,
+ streamUrl = entry.url,
+ providerId = provider.id,
+ rating = entry.rating?.toFloatOrNull() ?: 0f,
+ year = entry.year,
+ genre = entry.genre,
+ isAdult = isAdult
+ )
+ )
+ movieCount++
+ if (movieBatch.size >= batchSize) {
+ flushMovieBatch(provider.id, sessionId, movieBatch)
+ }
+ } else {
+ if (!includeLive) {
+ return@parseStreaming
+ }
+ val groupTitle = entry.groupTitle.ifBlank { "Uncategorized" }
+ val stableStreamId = stableId(
providerId = provider.id,
- isAdult = isAdult
+ contentType = ContentType.LIVE,
+ tvgId = entry.tvgId,
+ url = entry.url,
+ title = entry.name,
+ groupTitle = groupTitle,
+ hasher = stableLongHasher
)
- )
- liveCount++
- if (channelBatch.size >= batchSize) {
- flushChannelBatch(channelBatch)
+ if (seenLiveStreamIds?.add(stableStreamId) != true) {
+ return@parseStreaming
+ }
+ val categoryId = liveCategories.idFor(groupTitle)
+ val isAdult = AdultContentClassifier.isAdultCategoryName(groupTitle)
+ channelBatch.add(
+ ChannelEntity(
+ streamId = stableStreamId,
+ name = entry.name,
+ logoUrl = safeLogoUrl,
+ groupTitle = groupTitle,
+ categoryId = categoryId,
+ categoryName = groupTitle,
+ epgChannelId = entry.tvgId ?: entry.tvgName,
+ number = entry.tvgChno ?: 0,
+ streamUrl = entry.url,
+ catchUpSupported = entry.catchUp != null,
+ catchUpDays = entry.catchUpDays ?: 0,
+ catchUpSource = safeCatchUpSource,
+ providerId = provider.id,
+ isAdult = isAdult
+ )
+ )
+ liveCount++
+ if (channelBatch.size >= batchSize) {
+ flushChannelBatch(provider.id, sessionId, channelBatch)
+ }
}
}
}
}
- }
- flushChannelBatch(channelBatch)
- flushMovieBatch(movieBatch)
- if (includeLive) {
- categoryDao.replaceAll(provider.id, "LIVE", liveCategories.entities())
- pruneStaleChannels(existingChannelIds, seenLiveStreamIds.orEmpty())
- }
- if (includeMovies) {
- categoryDao.replaceAll(provider.id, "MOVIE", movieCategories.entities())
- pruneStaleMovies(existingMovieIds, seenMovieStreamIds.orEmpty())
- movieDao.restoreWatchProgress(provider.id)
+ flushChannelBatch(provider.id, sessionId, channelBatch)
+ flushMovieBatch(provider.id, sessionId, movieBatch)
+ syncCatalogStore.finalizeStagedImport(
+ providerId = provider.id,
+ sessionId = sessionId,
+ liveCategories = if (includeLive) liveCategories.entities() else null,
+ movieCategories = if (includeMovies) movieCategories.entities() else null,
+ includeLive = includeLive,
+ includeMovies = includeMovies
+ )
+ } finally {
+ syncCatalogStore.discardStagedImport(provider.id, sessionId)
}
if (insecureStreamCount > 0) {
@@ -2023,74 +2753,50 @@ class SyncManager @Inject constructor(
}
}
- private suspend fun flushChannelBatch(batch: MutableList<ChannelEntity>) {
+ private suspend fun flushChannelBatch(providerId: Long, sessionId: Long, batch: MutableList<ChannelEntity>) {
if (batch.isEmpty()) {
return
}
- channelDao.insertAll(batch.distinctBy { it.streamId })
+ syncCatalogStore.stageChannelBatch(providerId, sessionId, batch)
batch.clear()
}
- private suspend fun flushMovieBatch(batch: MutableList<MovieEntity>) {
+ private suspend fun flushMovieBatch(providerId: Long, sessionId: Long, batch: MutableList<MovieEntity>) {
if (batch.isEmpty()) {
return
}
- movieDao.insertAll(batch.distinctBy { it.streamId })
+ syncCatalogStore.stageMovieBatch(providerId, sessionId, batch)
batch.clear()
}
- private suspend fun pruneStaleChannels(
- existingChannelIds: Map<Long, Long>,
- seenStreamIds: Set<Long>
- ) {
- val staleIds = existingChannelIds
- .filterKeys { it !in seenStreamIds }
- .values
-
- staleIds.chunked(900).forEach { chunk ->
- if (chunk.isNotEmpty()) {
- channelDao.deleteByIds(chunk)
+ private suspend fun fetchXtreamVodCategories(provider: Provider): List<XtreamCategory>? {
+ return when (val attempt = attemptNonCancellation {
+ retryXtreamCatalogTransient(provider.id) {
+ executeXtreamRequest(provider.id, XtreamAdaptiveSyncPolicy.Stage.LIGHTWEIGHT) {
+ xtreamCatalogApiService.getVodCategories(
+ XtreamUrlFactory.buildPlayerApiUrl(
+ serverUrl = provider.serverUrl,
+ username = provider.username,
+ password = provider.password,
+ action = "get_vod_categories"
+ )
+ )
+ }
+ }
+ }) {
+ is Attempt.Success -> attempt.value
+ is Attempt.Failure -> {
+ Log.w(TAG, "Xtream VOD categories request failed for provider ${provider.id}: ${sanitizeThrowableMessage(attempt.error)}")
+ null
}
}
}
- private suspend fun pruneStaleMovies(
- existingMovieIds: Map<Long, Long>,
- seenStreamIds: Set<Long>
- ) {
- val staleIds = existingMovieIds
- .filterKeys { it !in seenStreamIds }
- .values
-
- staleIds.chunked(900).forEach { chunk ->
- if (chunk.isNotEmpty()) {
- movieDao.deleteByIds(chunk)
- }
- }
- }
-
- private suspend fun fetchXtreamVodCategories(provider: Provider): List<XtreamCategory>? {
- return runCatching {
- retryTransient {
- xtreamCatalogApiService.getVodCategories(
- XtreamUrlFactory.buildPlayerApiUrl(
- serverUrl = provider.serverUrl,
- username = provider.username,
- password = provider.password,
- action = "get_vod_categories"
- )
- )
- }
- }.onFailure { error ->
- Log.w(TAG, "Xtream VOD categories request failed for provider ${provider.id}: ${error::class.java.simpleName}: ${sanitizeThrowableMessage(error)}")
- }.getOrNull()
- }
-
- private fun strategyWarnings(result: CatalogStrategyResult<*>): List<String> = when (result) {
- is CatalogStrategyResult.Success -> result.warnings
- is CatalogStrategyResult.Partial -> result.warnings
- is CatalogStrategyResult.Failure -> result.warnings
- is CatalogStrategyResult.EmptyValid -> result.warnings
+ private fun strategyWarnings(result: CatalogStrategyResult<*>): List<String> = when (result) {
+ is CatalogStrategyResult.Success -> result.warnings
+ is CatalogStrategyResult.Partial -> result.warnings
+ is CatalogStrategyResult.Failure -> result.warnings
+ is CatalogStrategyResult.EmptyValid -> result.warnings
}
private fun <T> shouldDowngradeCategorySync(
@@ -2110,8 +2816,38 @@ class SyncManager @Inject constructor(
firstWindowFailures >= minOf(3, firstWindow.size)
}
+ private fun <T> shouldRetryFailedCategories(
+ totalCategories: Int,
+ failures: Int,
+ downgradeRecommended: Boolean,
+ outcomes: List<CategoryFetchOutcome<T>>
+ ): Boolean {
+ if (totalCategories <= 1 || failures == 0) {
+ return false
+ }
+ val stressFailures = outcomes.count { outcome ->
+ outcome is CategoryFetchOutcome.Failure && shouldRememberSequentialPreference(outcome.error)
+ }
+ return downgradeRecommended || stressFailures > 0 || failures <= minOf(2, totalCategories)
+ }
+
+ private fun <T> shouldRetryFailedPages(
+ totalPages: Int,
+ failures: Int,
+ outcomes: List<PageFetchOutcome<T>>
+ ): Boolean {
+ if (totalPages <= 1 || failures == 0) {
+ return false
+ }
+ val stressFailures = outcomes.count { outcome ->
+ outcome is PageFetchOutcome.Failure && shouldRememberSequentialPreference(outcome.error)
+ }
+ return stressFailures > 0 || failures <= minOf(2, totalPages)
+ }
+
private fun shouldRememberSequentialPreference(error: Throwable): Boolean {
- return error is XtreamAuthenticationException ||
+ return xtreamAdaptiveSyncPolicy.isProviderStress(error) ||
+ error is XtreamAuthenticationException ||
error is XtreamParsingException ||
(error is XtreamRequestException && error.statusCode in setOf(403, 429)) ||
(error is XtreamNetworkException && error.message.orEmpty().contains("reset", ignoreCase = true))
@@ -2126,40 +2862,148 @@ class SyncManager @Inject constructor(
)
}
- private suspend fun rateLimitXtreamCatalogRequest() {
- delay(250L)
- }
-
- private fun updateMovieProviderAdaptation(
+ private fun updateSequentialProviderAdaptation(
previousRemembered: Boolean,
previousHealthyStreak: Int,
sawSequentialStress: Boolean
- ): MovieProviderAdaptation {
+ ): SequentialProviderAdaptation {
if (sawSequentialStress) {
- return MovieProviderAdaptation(rememberSequential = true, healthyStreak = 0)
+ return SequentialProviderAdaptation(rememberSequential = true, healthyStreak = 0)
}
if (!previousRemembered) {
- return MovieProviderAdaptation(rememberSequential = false, healthyStreak = 0)
+ return SequentialProviderAdaptation(rememberSequential = false, healthyStreak = 0)
}
val nextHealthyStreak = (previousHealthyStreak + 1).coerceAtMost(2)
return if (nextHealthyStreak >= 2) {
- MovieProviderAdaptation(rememberSequential = false, healthyStreak = 0)
+ SequentialProviderAdaptation(rememberSequential = false, healthyStreak = 0)
} else {
- MovieProviderAdaptation(rememberSequential = true, healthyStreak = nextHealthyStreak)
+ SequentialProviderAdaptation(rememberSequential = true, healthyStreak = nextHealthyStreak)
}
}
+ private fun updateAvoidFullUntil(
+ previousAvoidFullUntil: Long,
+ now: Long,
+ feedback: XtreamStrategyFeedback
+ ): Long {
+ return when {
+ feedback.attemptedFullCatalog && feedback.fullCatalogUnsafe -> now + XTREAM_AVOID_FULL_CATALOG_COOLDOWN_MILLIS
+ feedback.attemptedFullCatalog -> 0L
+ feedback.preferredSegmentedFirst && feedback.segmentedStressDetected -> 0L
+ previousAvoidFullUntil <= now -> 0L
+ else -> previousAvoidFullUntil
+ }
+ }
+
+ private fun shouldPreferSegmentedLiveSync(
+ metadata: SyncMetadata,
+ now: Long
+ ): Boolean {
+ return metadata.liveAvoidFullUntil > now
+ }
+
+ private fun shouldPreferSegmentedMovieSync(
+ metadata: SyncMetadata,
+ now: Long
+ ): Boolean {
+ return metadata.movieAvoidFullUntil > now
+ }
+
+ private fun shouldPreferSegmentedSeriesSync(
+ metadata: SyncMetadata,
+ now: Long
+ ): Boolean {
+ return metadata.seriesAvoidFullUntil > now
+ }
+
+ private fun shouldAvoidFullCatalogStrategy(error: Throwable): Boolean {
+ return when (error) {
+ is XtreamResponseTooLargeException,
+ is XtreamParsingException -> true
+ is java.net.SocketTimeoutException,
+ is java.io.InterruptedIOException -> true
+ is XtreamNetworkException ->
+ error.message.orEmpty().contains("timed out", ignoreCase = true)
+ is IllegalStateException -> {
+ val normalized = error.message.orEmpty().lowercase()
+ normalized.contains("oversized") ||
+ normalized.contains("safe in-memory budget") ||
+ normalized.contains("unreadable response") ||
+ normalized.contains("invalid catalog data")
+ }
+ else -> false
+ }
+ }
+
+ private fun sawSegmentedStress(
+ warnings: List<String>,
+ result: CatalogStrategyResult<*>,
+ sequentialWarnings: Set<String>
+ ): Boolean {
+ val warningMatched = warnings.any { warning ->
+ sequentialWarnings.any { marker -> warning.contains(marker, ignoreCase = true) }
+ }
+ val resultWarningMatched = strategyWarnings(result).any { warning ->
+ sequentialWarnings.any { marker -> warning.contains(marker, ignoreCase = true) }
+ }
+ val failureMatched = (
+ (result as? CatalogStrategyResult.Failure)
+ ?.error
+ ?.let(::shouldRememberSequentialPreference)
+ ) == true
+ return warningMatched || resultWarningMatched || failureMatched
+ }
+
private fun stableId(
providerId: Long,
+ contentType: ContentType,
tvgId: String?,
url: String,
+ title: String,
+ groupTitle: String?,
hasher: StableLongHasher
): Long {
- return if (!tvgId.isNullOrBlank()) {
- hasher.hash("$providerId:tvg:$tvgId")
+ val normalizedUrl = normalizeUrlForIdentity(url)
+ val normalizedTvgId = tvgId?.trim()?.lowercase().orEmpty()
+ val normalizedTitle = normalizeTextForIdentity(title)
+ val normalizedGroup = normalizeTextForIdentity(groupTitle)
+ val identity = if (normalizedTvgId.isNotBlank()) {
+ "$providerId|${contentType.name}|tvg=$normalizedTvgId|url=$normalizedUrl"
} else {
- hasher.hash("$providerId:url:$url")
+ "$providerId|${contentType.name}|url=$normalizedUrl|title=$normalizedTitle|group=$normalizedGroup"
}
+ return hasher.hash(identity)
+ }
+
+ private fun normalizeUrlForIdentity(url: String): String {
+ val parsed = runCatching { URI(url) }.getOrNull()
+ val scheme = parsed?.scheme?.lowercase().orEmpty()
+ val host = parsed?.host?.lowercase().orEmpty()
+ val path = parsed?.path.orEmpty().trimEnd('/')
+ val query = parsed?.query
+ ?.split('&')
+ ?.mapNotNull { pair ->
+ val key = pair.substringBefore('=').lowercase()
+ val value = pair.substringAfter('=', "")
+ when (key) {
+ "token", "auth", "password", "username" -> null
+ else -> "$key=$value"
+ }
+ }
+ ?.sorted()
+ ?.joinToString("&")
+ .orEmpty()
+ return listOf(scheme, host, path, query)
+ .joinToString("|")
+ .ifBlank { url.trim().lowercase() }
+ }
+
+ private fun normalizeTextForIdentity(value: String?): String {
+ return value
+ .orEmpty()
+ .lowercase()
+ .replace(Regex("\\s+"), " ")
+ .trim()
}
private fun buildFallbackMovieCategories(providerId: Long, movies: List<Movie>): List<CategoryEntity> {
@@ -2222,6 +3066,152 @@ class SyncManager @Inject constructor(
.toList()
}
+ private suspend fun stageMovieItems(
+ providerId: Long,
+ items: List<Movie>,
+ seenStreamIds: MutableSet<Long>,
+ fallbackCollector: FallbackCategoryCollector,
+ sessionId: Long?
+ ): StagedCatalogSnapshot {
+ var resolvedSessionId = sessionId
+ val acceptedEntities = ArrayList<MovieEntity>(items.size)
+ items.forEach { movie ->
+ val streamId = movieKey(movie)
+ if (streamId <= 0L || !seenStreamIds.add(streamId)) {
+ return@forEach
+ }
+ fallbackCollector.record(movie.categoryId, movie.categoryName, movie.isAdult)
+ acceptedEntities += movie.toEntity()
+ }
+ if (acceptedEntities.isNotEmpty()) {
+ if (resolvedSessionId == null) {
+ syncCatalogStore.clearProviderStaging(providerId)
+ resolvedSessionId = syncCatalogStore.newSessionId()
+ }
+ syncCatalogStore.stageMovieBatch(providerId, requireNotNull(resolvedSessionId), acceptedEntities)
+ }
+ return StagedCatalogSnapshot(
+ sessionId = resolvedSessionId,
+ acceptedCount = acceptedEntities.size,
+ fallbackCategories = fallbackCollector.entities().takeIf { it.isNotEmpty() }
+ )
+ }
+
+ private suspend fun stageSeriesItems(
+ providerId: Long,
+ items: List<Series>,
+ seenSeriesIds: MutableSet<Long>,
+ fallbackCollector: FallbackCategoryCollector,
+ sessionId: Long?
+ ): StagedCatalogSnapshot {
+ var resolvedSessionId = sessionId
+ val acceptedEntities = ArrayList<SeriesEntity>(items.size)
+ items.forEach { item ->
+ val seriesId = seriesKey(item)
+ if (seriesId <= 0L || !seenSeriesIds.add(seriesId)) {
+ return@forEach
+ }
+ fallbackCollector.record(item.categoryId, item.categoryName, item.isAdult)
+ acceptedEntities += item.toEntity()
+ }
+ if (acceptedEntities.isNotEmpty()) {
+ if (resolvedSessionId == null) {
+ syncCatalogStore.clearProviderStaging(providerId)
+ resolvedSessionId = syncCatalogStore.newSessionId()
+ }
+ syncCatalogStore.stageSeriesBatch(providerId, requireNotNull(resolvedSessionId), acceptedEntities)
+ }
+ return StagedCatalogSnapshot(
+ sessionId = resolvedSessionId,
+ acceptedCount = acceptedEntities.size,
+ fallbackCategories = fallbackCollector.entities().takeIf { it.isNotEmpty() }
+ )
+ }
+
+ private suspend fun stageMovieSequence(
+ providerId: Long,
+ items: Sequence<Movie>,
+ seenStreamIds: MutableSet<Long>,
+ fallbackCollector: FallbackCategoryCollector,
+ sessionId: Long?
+ ): StagedCatalogSnapshot {
+ val batch = ArrayList<Movie>(XTREAM_FALLBACK_STAGE_BATCH_SIZE)
+ var currentSessionId = sessionId
+ var acceptedCount = 0
+
+ suspend fun flushBatch() {
+ if (batch.isEmpty()) return
+ val staged = stageMovieItems(
+ providerId = providerId,
+ items = batch,
+ seenStreamIds = seenStreamIds,
+ fallbackCollector = fallbackCollector,
+ sessionId = currentSessionId
+ )
+ currentSessionId = staged.sessionId
+ acceptedCount += staged.acceptedCount
+ batch.clear()
+ }
+
+ items.forEach { movie ->
+ batch += movie
+ if (batch.size >= XTREAM_FALLBACK_STAGE_BATCH_SIZE) {
+ flushBatch()
+ }
+ }
+ flushBatch()
+
+ return StagedCatalogSnapshot(
+ sessionId = currentSessionId,
+ acceptedCount = acceptedCount,
+ fallbackCategories = fallbackCollector.entities().takeIf { it.isNotEmpty() }
+ )
+ }
+
+ private suspend fun stageSeriesSequence(
+ providerId: Long,
+ items: Sequence<Series>,
+ seenSeriesIds: MutableSet<Long>,
+ fallbackCollector: FallbackCategoryCollector,
+ sessionId: Long?
+ ): StagedCatalogSnapshot {
+ val batch = ArrayList<Series>(XTREAM_FALLBACK_STAGE_BATCH_SIZE)
+ var currentSessionId = sessionId
+ var acceptedCount = 0
+
+ suspend fun flushBatch() {
+ if (batch.isEmpty()) return
+ val staged = stageSeriesItems(
+ providerId = providerId,
+ items = batch,
+ seenSeriesIds = seenSeriesIds,
+ fallbackCollector = fallbackCollector,
+ sessionId = currentSessionId
+ )
+ currentSessionId = staged.sessionId
+ acceptedCount += staged.acceptedCount
+ batch.clear()
+ }
+
+ items.forEach { series ->
+ batch += series
+ if (batch.size >= XTREAM_FALLBACK_STAGE_BATCH_SIZE) {
+ flushBatch()
+ }
+ }
+ flushBatch()
+
+ return StagedCatalogSnapshot(
+ sessionId = currentSessionId,
+ acceptedCount = acceptedCount,
+ fallbackCategories = fallbackCollector.entities().takeIf { it.isNotEmpty() }
+ )
+ }
+
+ private fun movieKey(movie: Movie): Long = movie.streamId.takeIf { it > 0L } ?: movie.id
+
+ private fun seriesKey(item: Series): Long = item.seriesId.takeIf { it > 0L } ?: item.id
+
/** Delegates to M3uParser to avoid duplicate logic. */
internal fun isVodEntry(entry: M3uParser.M3uEntry): Boolean = M3uParser.isVodEntry(entry)
@@ -2231,14 +3221,13 @@ class SyncManager @Inject constructor(
}
private fun publishSyncState(providerId: Long, state: SyncState) {
- _syncState.value = state
- _syncStatesByProvider.update { states -> states + (providerId to state) }
+ syncStateTracker.publish(providerId, state)
}
private fun redactUrlForLogs(url: String?): String {
if (url.isNullOrBlank()) return "<empty>"
return runCatching {
- val parsed = java.net.URI(url)
+ val parsed = URI(url)
val scheme = parsed.scheme ?: "http"
val host = parsed.host ?: return@runCatching "<redacted>"
val path = parsed.path.orEmpty()
@@ -2247,16 +3236,169 @@ class SyncManager @Inject constructor(
}
private fun sanitizeThrowableMessage(error: Throwable?): String {
- return sanitizeLogMessage(error?.message)
+ return syncErrorSanitizer.throwableMessage(error)
}
private fun sanitizeLogMessage(message: String?): String {
- if (message.isNullOrBlank()) {
- return "<empty>"
+ return syncErrorSanitizer.sanitize(message)
+ }
+
+ private fun fullCatalogFallbackWarning(sectionLabel: String, error: Throwable?): String {
+ return when (error) {
+ is XtreamResponseTooLargeException ->
+ "$sectionLabel full catalog was too large for one request, so sync continued with a safer segmented mode."
+ else ->
+ "$sectionLabel full catalog request failed, so sync continued with a safer fallback mode."
+ }
+ }
+
+ private fun categoryFailureWarning(sectionLabel: String, categoryName: String, error: Throwable): String {
+ val safeCategoryName = sanitizeLogMessage(categoryName).takeIf { it.isNotBlank() } ?: "Unknown"
+ return when (error) {
+ is XtreamResponseTooLargeException ->
+ "$sectionLabel category '$safeCategoryName' was too large to load safely."
+ else ->
+ "$sectionLabel category '$safeCategoryName' failed: " +
+ syncErrorSanitizer.userMessage(error, "Provider request failed.")
+ }
+ }
+
+ private fun pagingFailureWarning(sectionLabel: String, page: Int, error: Throwable): String {
+ return when (error) {
+ is XtreamResponseTooLargeException ->
+ "$sectionLabel paging response on page $page was too large to load safely."
+ else ->
+ "$sectionLabel paging failed on page $page: " +
+ syncErrorSanitizer.userMessage(error, "Provider request failed.")
+ }
+ }
+
+ private suspend fun <T> executeCategoryRecoveryPlan(
+ provider: Provider,
+ categories: List<XtreamCategory>,
+ initialConcurrency: Int,
+ sectionLabel: String,
+ sequentialModeWarning: String,
+ onProgress: ((String) -> Unit)?,
+ fetch: suspend (XtreamCategory) -> TimedCategoryOutcome<T>
+ ): CategoryExecutionPlan<T> {
+ if (categories.isEmpty()) {
+ return CategoryExecutionPlan(emptyList())
+ }
+
+ val outcomes = mutableListOf<TimedCategoryOutcome<T>>()
+ val warnings = mutableListOf<String>()
+ var nextIndex = 0
+ var forceSequential = initialConcurrency <= 1
+ var consecutiveSequentialStressFailures = 0
+ var stoppedEarly = false
+
+ while (nextIndex < categories.size && !stoppedEarly) {
+ val windowConcurrency = if (forceSequential) 1 else initialConcurrency
+ val window = categories.subList(nextIndex, minOf(nextIndex + windowConcurrency, categories.size))
+ val windowOutcomes = coroutineScope {
+ window.map { category ->
+ async { fetch(category) }
+ }.awaitAll()
+ }
+ outcomes += windowOutcomes
+ nextIndex += window.size
+
+ val completed = outcomes.size
+ progress(provider.id, onProgress, "Downloading $sectionLabel by category $completed/${categories.size}...")
+
+ if (!forceSequential && shouldRecoverRemainingCategoryRequests(categories.size, completed, outcomes.map { it.outcome })) {
+ forceSequential = true
+ warnings += sequentialModeWarning
+ Log.w(
+ TAG,
+ "Xtream $sectionLabel category sync is switching remaining categories to sequential mode for provider ${provider.id} after $completed/${categories.size} categories."
+ )
+ }
+
+ if (forceSequential) {
+ windowOutcomes.forEach { timedOutcome ->
+ val isStressFailure = (timedOutcome.outcome as? CategoryFetchOutcome.Failure)
+ ?.error
+ ?.let(::shouldRememberSequentialPreference)
+ ?: false
+ consecutiveSequentialStressFailures = if (isStressFailure) {
+ consecutiveSequentialStressFailures + 1
+ } else {
+ 0
+ }
+ }
+ if (consecutiveSequentialStressFailures >= 3 && nextIndex < categories.size) {
+ warnings += "$sectionLabel $XTREAM_RECOVERY_ABORT_WARNING_SUFFIX"
+ Log.w(
+ TAG,
+ "Xtream $sectionLabel category sync stopped early for provider ${provider.id} after repeated sequential stress failures. completed=$completed total=${categories.size}"
+ )
+ stoppedEarly = true
+ }
+ }
+ }
+
+ return CategoryExecutionPlan(outcomes = outcomes, warnings = warnings.distinct())
+ }
+
+ private fun <T> shouldRecoverRemainingCategoryRequests(
+ totalCategories: Int,
+ processedCategories: Int,
+ outcomes: List<CategoryFetchOutcome<T>>
+ ): Boolean {
+ if (processedCategories >= totalCategories || processedCategories <= 1) {
+ return false
+ }
+ val processedOutcomes = outcomes.take(processedCategories)
+ val failures = processedOutcomes.count { it is CategoryFetchOutcome.Failure }
+ val stressFailures = processedOutcomes.count { outcome ->
+ outcome is CategoryFetchOutcome.Failure && shouldRememberSequentialPreference(outcome.error)
+ }
+ val recentWindow = processedOutcomes.takeLast(minOf(4, processedOutcomes.size))
+ val recentStressFailures = recentWindow.count { outcome ->
+ outcome is CategoryFetchOutcome.Failure && shouldRememberSequentialPreference(outcome.error)
+ }
+ val failureRatio = failures.toFloat() / processedCategories.toFloat()
+ return recentStressFailures >= minOf(2, recentWindow.size) ||
+ stressFailures >= minOf(3, processedCategories) ||
+ (processedCategories >= 6 && failureRatio >= 0.34f)
+ }
+
+ private fun <T> evaluatePageRecoveryPlan(
+ provider: Provider,
+ sectionLabel: String,
+ pageWindow: List<Int>,
+ outcomes: List<TimedPageOutcome<T>>,
+ sequentialModeWarning: String
+ ): PageExecutionPlan<T> {
+ if (pageWindow.isEmpty()) {
+ return PageExecutionPlan(emptyList())
+ }
+ val warnings = mutableListOf<String>()
+ val stressFailures = outcomes.count { outcome ->
+ (outcome.outcome as? PageFetchOutcome.Failure)
+ ?.error
+ ?.let(::shouldRememberSequentialPreference)
+ ?: false
+ }
+ val stoppedEarly = stressFailures >= minOf(3, pageWindow.size)
+ val shouldDegrade = !stoppedEarly && pageWindow.size > 1 && stressFailures >= minOf(2, pageWindow.size)
+ if (shouldDegrade) {
+ warnings += sequentialModeWarning
+ Log.w(
+ TAG,
+ "Xtream $sectionLabel paged sync is switching remaining pages to sequential mode for provider ${provider.id} after window ${pageWindow.first()}-${pageWindow.last()}."
+ )
+ }
+ if (stoppedEarly) {
+ warnings += "$sectionLabel $XTREAM_RECOVERY_ABORT_WARNING_SUFFIX"
+ Log.w(
+ TAG,
+ "Xtream $sectionLabel paged sync stopped early for provider ${provider.id} after repeated stress failures in window ${pageWindow.first()}-${pageWindow.last()}."
+ )
}
- return message
- .replace(Regex("""https?://\S+""", RegexOption.IGNORE_CASE), "<redacted-url>")
- .replace(Regex("""([?&](username|password|token)=[^&\s]+)""", RegexOption.IGNORE_CASE), "<redacted-param>")
+ return PageExecutionPlan(outcomes = outcomes, warnings = warnings.distinct(), stoppedEarly = stoppedEarly)
}
private suspend fun <T> retryTransient(
@@ -2266,12 +3408,14 @@ class SyncManager @Inject constructor(
): T {
var attempt = 0
var delayMs = initialDelayMs
- var lastError: Throwable? = null
+ var lastError: Exception? = null
while (attempt < maxAttempts) {
try {
return block()
- } catch (t: Throwable) {
+ } catch (e: CancellationException) {
+ throw e
+ } catch (t: Exception) {
lastError = t
attempt++
if (attempt >= maxAttempts || !isRetryable(t)) {
@@ -2285,23 +3429,59 @@ class SyncManager @Inject constructor(
throw lastError ?: IllegalStateException("Unknown sync retry failure")
}
- private suspend fun <T> retryXtreamCatalogTransient(block: suspend () -> T): T {
+ private suspend fun <T> attemptNonCancellation(block: suspend () -> T): Attempt<T> {
+ return try {
+ Attempt.Success(block())
+ } catch (e: CancellationException) {
+ throw e
+ } catch (e: Exception) {
+ Attempt.Failure(e)
+ }
+ }
+
+ private suspend fun <T> executeXtreamRequest(
+ providerId: Long,
+ stage: XtreamAdaptiveSyncPolicy.Stage,
+ block: suspend () -> T
+ ): T {
+ xtreamAdaptiveSyncPolicy.awaitTurn(providerId, stage)
+ return try {
+ val timeoutMs = xtreamAdaptiveSyncPolicy.timeoutFor(providerId, stage)
+ val result = if (timeoutMs != null) {
+ withTimeout(timeoutMs) {
+ block()
+ }
+ } else {
+ block()
+ }
+ xtreamAdaptiveSyncPolicy.recordSuccess(providerId)
+ result
+ } catch (e: CancellationException) {
+ throw e
+ } catch (e: Exception) {
+ xtreamAdaptiveSyncPolicy.recordFailure(providerId, e)
+ throw e
+ }
+ }
+
+ private suspend fun <T> retryXtreamCatalogTransient(providerId: Long, block: suspend () -> T): T {
var attempt = 0
- var delayMs = 1_000L
- var lastError: Throwable? = null
+ var lastError: Exception? = null
while (attempt < 3) {
try {
return block()
- } catch (t: Throwable) {
+ } catch (e: CancellationException) {
+ throw e
+ } catch (t: Exception) {
lastError = t
attempt++
if (attempt >= 3 || !isXtreamCatalogRetryable(t, attempt)) {
throw t
}
+ val delayMs = xtreamAdaptiveSyncPolicy.retryDelayFor(providerId, attempt)
val jitterMs = Random.nextLong(0L, (delayMs / 3L).coerceAtLeast(1L) + 1L)
delay(delayMs + jitterMs)
- delayMs = (delayMs * 2).coerceAtMost(8_000L)
}
}
@@ -2327,8 +3507,10 @@ class SyncManager @Inject constructor(
private fun isXtreamCatalogRetryable(error: Throwable, attempt: Int): Boolean {
return when (error) {
is XtreamAuthenticationException -> false
+ is XtreamResponseTooLargeException -> false
is XtreamParsingException -> attempt == 1
- is XtreamRequestException -> error.statusCode == 408 || error.statusCode == 409 || error.statusCode in 500..599
+ is XtreamRequestException ->
+ error.statusCode in setOf(403, 408, 409, 429) || error.statusCode in 500..599
is XtreamNetworkException -> true
is IOException -> true
else -> isRetryable(error)
@@ -2337,13 +3519,6 @@ class SyncManager @Inject constructor(
companion object {
private const val PROGRESS_INTERVAL = 5_000
- private const val XTREAM_CATEGORY_SYNC_MAX_CONCURRENCY = 2
- }
-
- private fun xtreamCategorySyncConcurrency(categoryCount: Int): Int {
- return categoryCount
- .coerceAtLeast(1)
- .coerceAtMost(XTREAM_CATEGORY_SYNC_MAX_CONCURRENCY)
}
private fun createXtreamSyncProvider(provider: Provider): XtreamProvider {
@@ -2386,4 +3561,292 @@ class SyncManager @Inject constructor(
throw Exception("Unexpected loading state for $resourceName")
}
}
+
+ private suspend fun fetchLiveCategoryOutcome(
+ provider: Provider,
+ api: XtreamProvider,
+ category: XtreamCategory
+ ): TimedCategoryOutcome<Channel> {
+ var rawStreams: List<XtreamStream> = emptyList()
+ var categoryFailure: Throwable? = null
+ val elapsedMs = measureTimeMillis {
+ when (val attempt = attemptNonCancellation {
+ retryXtreamCatalogTransient(provider.id) {
+ executeXtreamRequest(provider.id, XtreamAdaptiveSyncPolicy.Stage.CATEGORY) {
+ xtreamCatalogApiService.getLiveStreams(
+ XtreamUrlFactory.buildPlayerApiUrl(
+ serverUrl = provider.serverUrl,
+ username = provider.username,
+ password = provider.password,
+ action = "get_live_streams",
+ extraQueryParams = mapOf("category_id" to category.categoryId)
+ )
+ )
+ }
+ }
+ }) {
+ is Attempt.Success -> rawStreams = attempt.value
+ is Attempt.Failure -> categoryFailure = attempt.error
+ }
+ }
+ val outcome = when {
+ categoryFailure != null -> {
+ Log.w(TAG, "Xtream live category '${category.categoryName}' failed after ${elapsedMs}ms: ${sanitizeThrowableMessage(categoryFailure)}")
+ CategoryFetchOutcome.Failure(category.categoryName, categoryFailure!!)
+ }
+ rawStreams.isEmpty() -> {
+ Log.i(TAG, "Xtream live category '${category.categoryName}' completed in ${elapsedMs}ms with a valid empty result.")
+ CategoryFetchOutcome.Empty(category.categoryName)
+ }
+ else -> {
+ Log.i(TAG, "Xtream live category '${category.categoryName}' completed in ${elapsedMs}ms with ${rawStreams.size} raw items.")
+ CategoryFetchOutcome.Success(category.categoryName, api.mapLiveStreamsResponse(rawStreams))
+ }
+ }
+ return TimedCategoryOutcome(category, outcome, elapsedMs)
+ }
+
+ private suspend fun fetchMovieCategoryOutcome(
+ provider: Provider,
+ api: XtreamProvider,
+ category: XtreamCategory
+ ): TimedCategoryOutcome<Movie> {
+ var rawStreams: List<XtreamStream> = emptyList()
+ var categoryFailure: Throwable? = null
+ val elapsedMs = measureTimeMillis {
+ when (val attempt = attemptNonCancellation {
+ retryXtreamCatalogTransient(provider.id) {
+ executeXtreamRequest(provider.id, XtreamAdaptiveSyncPolicy.Stage.CATEGORY) {
+ xtreamCatalogApiService.getVodStreams(
+ XtreamUrlFactory.buildPlayerApiUrl(
+ serverUrl = provider.serverUrl,
+ username = provider.username,
+ password = provider.password,
+ action = "get_vod_streams",
+ extraQueryParams = mapOf("category_id" to category.categoryId)
+ )
+ )
+ }
+ }
+ }) {
+ is Attempt.Success -> rawStreams = attempt.value
+ is Attempt.Failure -> categoryFailure = attempt.error
+ }
+ }
+ val outcome = when {
+ categoryFailure != null -> {
+ Log.w(TAG, "Xtream movie category '${category.categoryName}' failed after ${elapsedMs}ms: ${sanitizeThrowableMessage(categoryFailure)}")
+ CategoryFetchOutcome.Failure(category.categoryName, categoryFailure!!)
+ }
+ rawStreams.isEmpty() -> {
+ Log.i(TAG, "Xtream movie category '${category.categoryName}' completed in ${elapsedMs}ms with a valid empty result.")
+ CategoryFetchOutcome.Empty(category.categoryName)
+ }
+ else -> {
+ Log.i(TAG, "Xtream movie category '${category.categoryName}' completed in ${elapsedMs}ms with ${rawStreams.size} raw items.")
+ CategoryFetchOutcome.Success(category.categoryName, api.mapVodStreamsResponse(rawStreams))
+ }
+ }
+ return TimedCategoryOutcome(category, outcome, elapsedMs)
+ }
+
+ private suspend fun fetchSeriesCategoryOutcome(
+ provider: Provider,
+ api: XtreamProvider,
+ category: XtreamCategory
+ ): TimedCategoryOutcome<Series> {
+ var rawSeries: List<XtreamSeriesItem> = emptyList()
+ var categoryFailure: Throwable? = null
+ val elapsedMs = measureTimeMillis {
+ when (val attempt = attemptNonCancellation {
+ retryXtreamCatalogTransient(provider.id) {
+ executeXtreamRequest(provider.id, XtreamAdaptiveSyncPolicy.Stage.CATEGORY) {
+ xtreamCatalogApiService.getSeriesList(
+ XtreamUrlFactory.buildPlayerApiUrl(
+ serverUrl = provider.serverUrl,
+ username = provider.username,
+ password = provider.password,
+ action = "get_series",
+ extraQueryParams = mapOf("category_id" to category.categoryId)
+ )
+ )
+ }
+ }
+ }) {
+ is Attempt.Success -> rawSeries = attempt.value
+ is Attempt.Failure -> categoryFailure = attempt.error
+ }
+ }
+ val outcome = when {
+ categoryFailure != null -> {
+ Log.w(TAG, "Xtream series category '${category.categoryName}' failed after ${elapsedMs}ms: ${sanitizeThrowableMessage(categoryFailure)}")
+ CategoryFetchOutcome.Failure(category.categoryName, categoryFailure!!)
+ }
+ rawSeries.isEmpty() -> {
+ Log.i(TAG, "Xtream series category '${category.categoryName}' completed in ${elapsedMs}ms with a valid empty result.")
+ CategoryFetchOutcome.Empty(category.categoryName)
+ }
+ else -> {
+ Log.i(TAG, "Xtream series category '${category.categoryName}' completed in ${elapsedMs}ms with ${rawSeries.size} raw items.")
+ CategoryFetchOutcome.Success(category.categoryName, api.mapSeriesListResponse(rawSeries))
+ }
+ }
+ return TimedCategoryOutcome(category, outcome, elapsedMs)
+ }
+
+ private suspend fun fetchMoviePageOutcome(
+ provider: Provider,
+ api: XtreamProvider,
+ page: Int
+ ): TimedPageOutcome<Movie> {
+ var rawStreams: List<XtreamStream> = emptyList()
+ var pageFailure: Throwable? = null
+ val elapsedMs = measureTimeMillis {
+ when (val attempt = attemptNonCancellation {
+ retryXtreamCatalogTransient(provider.id) {
+ executeXtreamRequest(provider.id, XtreamAdaptiveSyncPolicy.Stage.PAGED) {
+ xtreamCatalogApiService.getVodStreams(
+ XtreamUrlFactory.buildPlayerApiUrl(
+ serverUrl = provider.serverUrl,
+ username = provider.username,
+ password = provider.password,
+ action = "get_vod_streams",
+ extraQueryParams = paginationParamsForPage(page)
+ )
+ )
+ }
+ }
+ }) {
+ is Attempt.Success -> rawStreams = attempt.value
+ is Attempt.Failure -> pageFailure = attempt.error
+ }
+ }
+ val outcome = when {
+ pageFailure != null -> {
+ Log.w(
+ TAG,
+ "Xtream paged movie request failed for provider ${provider.id} on page $page after ${elapsedMs}ms: ${sanitizeThrowableMessage(pageFailure)}"
+ )
+ PageFetchOutcome.Failure(page, pageFailure!!)
+ }
+ rawStreams.isEmpty() -> {
+ Log.i(
+ TAG,
+ "Xtream paged movie request for provider ${provider.id} page $page completed in ${elapsedMs}ms with a valid empty result."
+ )
+ PageFetchOutcome.Empty(page)
+ }
+ else -> {
+ Log.i(
+ TAG,
+ "Xtream paged movie request for provider ${provider.id} page $page completed in ${elapsedMs}ms with ${rawStreams.size} raw items."
+ )
+ PageFetchOutcome.Success(api.mapVodStreamsResponse(rawStreams), rawStreams.size)
+ }
+ }
+ return TimedPageOutcome(page = page, outcome = outcome, elapsedMs = elapsedMs)
+ }
+
+ private suspend fun fetchSeriesPageOutcome(
+ provider: Provider,
+ api: XtreamProvider,
+ page: Int
+ ): TimedPageOutcome<Series> {
+ var rawSeries: List<XtreamSeriesItem> = emptyList()
+ var pageFailure: Throwable? = null
+ val elapsedMs = measureTimeMillis {
+ when (val attempt = attemptNonCancellation {
+ retryXtreamCatalogTransient(provider.id) {
+ executeXtreamRequest(provider.id, XtreamAdaptiveSyncPolicy.Stage.PAGED) {
+ xtreamCatalogApiService.getSeriesList(
+ XtreamUrlFactory.buildPlayerApiUrl(
+ serverUrl = provider.serverUrl,
+ username = provider.username,
+ password = provider.password,
+ action = "get_series",
+ extraQueryParams = paginationParamsForPage(page)
+ )
+ )
+ }
+ }
+ }) {
+ is Attempt.Success -> rawSeries = attempt.value
+ is Attempt.Failure -> pageFailure = attempt.error
+ }
+ }
+ val outcome = when {
+ pageFailure != null -> {
+ Log.w(
+ TAG,
+ "Xtream paged series request failed for provider ${provider.id} on page $page after ${elapsedMs}ms: ${sanitizeThrowableMessage(pageFailure)}"
+ )
+ PageFetchOutcome.Failure(page, pageFailure!!)
+ }
+ rawSeries.isEmpty() -> {
+ Log.i(
+ TAG,
+ "Xtream paged series request for provider ${provider.id} page $page completed in ${elapsedMs}ms with a valid empty result."
+ )
+ PageFetchOutcome.Empty(page)
+ }
+ else -> {
+ Log.i(
+ TAG,
+ "Xtream paged series request for provider ${provider.id} page $page completed in ${elapsedMs}ms with ${rawSeries.size} raw items."
+ )
+ PageFetchOutcome.Success(api.mapSeriesListResponse(rawSeries), rawSeries.size)
+ }
+ }
+ return TimedPageOutcome(page = page, outcome = outcome, elapsedMs = elapsedMs)
+ }
+
+ private suspend fun <T> continueFailedPageOutcomes(
+ provider: Provider,
+ timedOutcomes: List<TimedPageOutcome<T>>,
+ fetchSequentially: suspend (Int) -> TimedPageOutcome<T>
+ ): List<TimedPageOutcome<T>> {
+ val failedPages = timedOutcomes
+ .filter { it.outcome is PageFetchOutcome.Failure }
+ .map { it.page }
+ if (failedPages.isEmpty()) {
+ return timedOutcomes
+ }
+ val replacements = LinkedHashMap<Int, TimedPageOutcome<T>>()
+ failedPages.forEach { page ->
+ replacements[page] = fetchSequentially(page)
+ }
+ return timedOutcomes.map { existing ->
+ replacements[existing.page] ?: existing
+ }.also {
+ Log.i(
+ TAG,
+ "Xtream continuation fallback kept ${timedOutcomes.size - failedPages.size} successful page results for provider ${provider.id} and retried only ${failedPages.size} failed pages."
+ )
+ }
+ }
+
+ private suspend fun <T> continueFailedCategoryOutcomes(
+ provider: Provider,
+ timedOutcomes: List<TimedCategoryOutcome<T>>,
+ fetchSequentially: suspend (XtreamCategory) -> TimedCategoryOutcome<T>
+ ): List<TimedCategoryOutcome<T>> {
+ val failedCategories = timedOutcomes
+ .filter { it.outcome is CategoryFetchOutcome.Failure }
+ .map { it.category }
+ if (failedCategories.isEmpty()) {
+ return timedOutcomes
+ }
+ val replacements = LinkedHashMap<String, TimedCategoryOutcome<T>>()
+ failedCategories.forEach { category ->
+ replacements[category.categoryId] = fetchSequentially(category)
+ }
+ return timedOutcomes.map { existing ->
+ replacements[existing.category.categoryId] ?: existing
+ }.also {
+ Log.i(
+ TAG,
+ "Xtream continuation fallback kept ${timedOutcomes.size - failedCategories.size} successful category results for provider ${provider.id} and retried only ${failedCategories.size} failed categories."
+ )
+ }
+ }
}
diff --git a/data/src/main/java/com/streamvault/data/sync/SyncStateTracker.kt b/data/src/main/java/com/streamvault/data/sync/SyncStateTracker.kt
new file mode 100644
index 00000000..35aa7c17
--- /dev/null
+++ b/data/src/main/java/com/streamvault/data/sync/SyncStateTracker.kt
@@ -0,0 +1,95 @@
+package com.streamvault.data.sync
+
+import com.streamvault.domain.model.SyncState
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.map
+import kotlinx.coroutines.flow.stateIn
+import kotlinx.coroutines.flow.SharingStarted
+import kotlinx.coroutines.flow.update
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+
+internal class SyncStateTracker {
+ private data class ProviderStateSnapshot(
+ val state: SyncState,
+ val updatedAt: Long = System.currentTimeMillis()
+ )
+
+ private val scope = CoroutineScope(Dispatchers.Default)
+ private val providerSnapshots = MutableStateFlow<Map<Long, ProviderStateSnapshot>>(emptyMap())
+
+ val statesByProvider: StateFlow<Map<Long, SyncState>> = providerSnapshots
+ .map { snapshots -> snapshots.mapValues { it.value.state } }
+ .stateIn(scope, SharingStarted.Eagerly, emptyMap())
+
+ val aggregateState: StateFlow<SyncState> = providerSnapshots
+ .map { snapshots -> aggregate(snapshots) }
+ .stateIn(scope, SharingStarted.Eagerly, SyncState.Idle)
+
+ fun current(providerId: Long): SyncState = providerSnapshots.value[providerId]?.state ?: SyncState.Idle
+
+ fun publish(providerId: Long, state: SyncState) {
+ providerSnapshots.update { snapshots ->
+ snapshots + (providerId to ProviderStateSnapshot(state))
+ }
+ }
+
+ fun reset(providerId: Long? = null) {
+ providerSnapshots.update { snapshots ->
+ if (providerId == null) {
+ emptyMap()
+ } else {
+ snapshots - providerId
+ }
+ }
+ }
+
+ private fun aggregate(snapshots: Map<Long, ProviderStateSnapshot>): SyncState {
+ if (snapshots.isEmpty()) {
+ return SyncState.Idle
+ }
+ val values = snapshots.values.toList()
+ val syncing = values.filter { it.state is SyncState.Syncing }
+ val errors = values.filter { it.state is SyncState.Error }
+ val partials = values.filter { it.state is SyncState.Partial }
+ if (syncing.isNotEmpty()) {
+ val representative = syncing.maxByOrNull { it.updatedAt }?.state as? SyncState.Syncing
+ val phaseSuffix = representative?.phase?.takeIf { it.isNotBlank() }?.let { " · $it" }.orEmpty()
+ val errorSuffix = errors.takeIf { it.isNotEmpty() }?.let { " · ${it.size} failing" }.orEmpty()
+ val partialSuffix = partials.takeIf { it.isNotEmpty() }?.let { " · ${it.size} partial" }.orEmpty()
+ return SyncState.Syncing("Syncing ${syncing.size} provider${if (syncing.size == 1) "" else "s"}$phaseSuffix$errorSuffix$partialSuffix")
+ }
+ if (errors.isNotEmpty()) {
+ if (errors.size == 1 && partials.isEmpty()) {
+ return errors.single().state
+ }
+ val latestError = errors.maxByOrNull { it.updatedAt }?.state as? SyncState.Error
+ val summary = buildString {
+ append("${errors.size} provider sync")
+ append(if (errors.size == 1) " failed" else "s failed")
+ if (partials.isNotEmpty()) {
+ append(" · ${partials.size} partial")
+ }
+ }
+ return SyncState.Error(summary, latestError?.cause)
+ }
+ if (partials.isNotEmpty()) {
+ if (partials.size == 1) {
+ return partials.single().state
+ }
+ val warnings = partials
+ .asSequence()
+ .map { it.state as SyncState.Partial }
+ .flatMap { it.warnings.asSequence() }
+ .distinct()
+ .toList()
+ return SyncState.Partial(
+ message = "${partials.size} provider syncs completed with warnings",
+ warnings = warnings,
+ timestamp = partials.maxOf { (it.state as SyncState.Partial).timestamp }
+ )
+ }
+ return values.maxByOrNull { it.updatedAt }?.state ?: SyncState.Idle
+ }
+}
diff --git a/data/src/main/java/com/streamvault/data/sync/XtreamAdaptiveSyncPolicy.kt b/data/src/main/java/com/streamvault/data/sync/XtreamAdaptiveSyncPolicy.kt
new file mode 100644
index 00000000..0972d40a
--- /dev/null
+++ b/data/src/main/java/com/streamvault/data/sync/XtreamAdaptiveSyncPolicy.kt
@@ -0,0 +1,232 @@
+package com.streamvault.data.sync
+
+import com.streamvault.data.remote.xtream.XtreamAuthenticationException
+import com.streamvault.data.remote.xtream.XtreamNetworkException
+import com.streamvault.data.remote.xtream.XtreamRequestException
+import java.io.IOException
+import java.util.concurrent.ConcurrentHashMap
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.sync.Mutex
+import kotlinx.coroutines.sync.withLock
+
+internal class XtreamAdaptiveSyncPolicy {
+ private companion object {
+ const val MAX_SEGMENTED_CONCURRENCY = 4
+ }
+
+ enum class Stage(val timeoutMs: Long?) {
+ LIGHTWEIGHT(15_000L),
+ CATEGORY(35_000L),
+ PAGED(40_000L),
+ HEAVY(null)
+ }
+
+ private data class ProviderHealth(
+ val stressLevel: Int = 0,
+ val backoffUntilMs: Long = 0L,
+ val successStreak: Int = 0,
+ val timeoutStreak: Int = 0,
+ val resetStreak: Int = 0,
+ val connectionFailureStreak: Int = 0
+ )
+
+ private class ProviderPacingState {
+ val mutex = Mutex()
+ var nextSegmentedRequestStartMs: Long = 0L
+ }
+
+ private val providerHealth = ConcurrentHashMap<Long, ProviderHealth>()
+ private val providerPacing = ConcurrentHashMap<Long, ProviderPacingState>()
+
+ suspend fun awaitTurn(providerId: Long, stage: Stage) {
+ val waitMs = (providerHealth[providerId]?.backoffUntilMs ?: 0L) - System.currentTimeMillis()
+ if (waitMs > 0L) {
+ delay(waitMs)
+ }
+ val requestSpacingMs = segmentedRequestSpacingFor(providerId, stage)
+ if (requestSpacingMs <= 0L) {
+ return
+ }
+ val pacingState = providerPacing.computeIfAbsent(providerId) { ProviderPacingState() }
+ pacingState.mutex.withLock {
+ val now = System.currentTimeMillis()
+ val pacingWaitMs = (pacingState.nextSegmentedRequestStartMs - now).coerceAtLeast(0L)
+ if (pacingWaitMs > 0L) {
+ delay(pacingWaitMs)
+ }
+ pacingState.nextSegmentedRequestStartMs = System.currentTimeMillis() + requestSpacingMs
+ }
+ }
+
+ fun timeoutFor(providerId: Long, stage: Stage): Long? = stage.timeoutMs
+
+ fun concurrencyFor(
+ providerId: Long,
+ workloadSize: Int,
+ preferSequential: Boolean,
+ stage: Stage
+ ): Int {
+ if (preferSequential || workloadSize <= 1) {
+ return 1
+ }
+ val health = providerHealth[providerId] ?: ProviderHealth()
+ val base = when (stage) {
+ Stage.LIGHTWEIGHT -> 1
+ Stage.CATEGORY -> when {
+ workloadSize <= 3 -> 1
+ workloadSize <= 8 -> 2
+ workloadSize <= 18 -> 2
+ workloadSize <= 36 -> 3
+ else -> 4
+ }
+ Stage.PAGED -> when {
+ workloadSize <= 3 -> 1
+ workloadSize <= 10 -> 2
+ workloadSize <= 25 -> 2
+ workloadSize <= 60 -> 3
+ else -> 4
+ }
+ Stage.HEAVY -> 1
+ }
+ val adjusted = when {
+ health.stressLevel >= 5 -> 1
+ health.stressLevel >= 4 -> (base / 3).coerceAtLeast(1)
+ health.stressLevel >= 3 -> (base / 2).coerceAtLeast(1)
+ health.stressLevel >= 2 -> (base - 2).coerceAtLeast(1)
+ health.stressLevel >= 1 -> (base - 1).coerceAtLeast(1)
+ else -> base
+ }
+ val boosted = if (health.stressLevel == 0 && health.successStreak >= 4 && stage != Stage.HEAVY) {
+ adjusted + 1
+ } else {
+ adjusted
+ }
+ return boosted.coerceIn(1, MAX_SEGMENTED_CONCURRENCY).coerceAtMost(workloadSize)
+ }
+
+ fun recordSuccess(providerId: Long) {
+ providerHealth.compute(providerId) { _, current ->
+ val state = current ?: ProviderHealth()
+ val nextSuccessStreak = (state.successStreak + 1).coerceAtMost(6)
+ val recoveredStress = if (nextSuccessStreak >= 2) {
+ (state.stressLevel - 1).coerceAtLeast(0)
+ } else {
+ state.stressLevel
+ }
+ state.copy(
+ stressLevel = recoveredStress,
+ backoffUntilMs = if (recoveredStress == 0) 0L else state.backoffUntilMs,
+ successStreak = nextSuccessStreak,
+ timeoutStreak = 0,
+ resetStreak = 0,
+ connectionFailureStreak = 0
+ )
+ }
+ }
+
+ fun recordFailure(providerId: Long, error: Throwable) {
+ providerHealth.compute(providerId) { _, current ->
+ val state = current ?: ProviderHealth()
+ val signal = classify(error)
+ val nextStress = when (signal) {
+ StressSignal.THROTTLED -> (state.stressLevel + 2).coerceAtMost(5)
+ StressSignal.TIMEOUT,
+ StressSignal.CONNECTION_RESET,
+ StressSignal.CONNECTION_FAILURE -> (state.stressLevel + 1).coerceAtMost(5)
+ StressSignal.NONE -> state.stressLevel
+ }
+ val nextTimeoutStreak = if (signal == StressSignal.TIMEOUT) state.timeoutStreak + 1 else 0
+ val nextResetStreak = if (signal == StressSignal.CONNECTION_RESET) state.resetStreak + 1 else 0
+ val nextConnectionFailureStreak = if (signal == StressSignal.CONNECTION_FAILURE) state.connectionFailureStreak + 1 else 0
+ val extraStress = when {
+ nextTimeoutStreak >= 2 || nextResetStreak >= 2 || nextConnectionFailureStreak >= 2 -> 1
+ else -> 0
+ }
+ val finalStress = (nextStress + extraStress).coerceAtMost(5)
+ val backoffMs = when {
+ signal == StressSignal.THROTTLED -> 900L + (1_100L * finalStress)
+ signal == StressSignal.TIMEOUT -> 350L * finalStress
+ signal == StressSignal.CONNECTION_RESET || signal == StressSignal.CONNECTION_FAILURE -> 250L * finalStress
+ else -> 0L
+ }
+ state.copy(
+ stressLevel = finalStress,
+ backoffUntilMs = System.currentTimeMillis() + backoffMs,
+ successStreak = 0,
+ timeoutStreak = nextTimeoutStreak,
+ resetStreak = nextResetStreak,
+ connectionFailureStreak = nextConnectionFailureStreak
+ )
+ }
+ }
+
+ fun retryDelayFor(providerId: Long, attempt: Int): Long {
+ val health = providerHealth[providerId] ?: ProviderHealth()
+ val base = when (attempt) {
+ 1 -> 150L
+ 2 -> 500L
+ else -> 1_200L
+ }
+ val stressExtra = when {
+ health.stressLevel >= 4 -> 1_600L
+ health.stressLevel >= 3 -> 900L
+ health.stressLevel >= 2 -> 450L
+ health.stressLevel >= 1 -> 150L
+ else -> 0L
+ }
+ return base + stressExtra
+ }
+
+ fun forgetProvider(providerId: Long) {
+ providerHealth.remove(providerId)
+ providerPacing.remove(providerId)
+ }
+
+ fun isProviderStress(error: Throwable): Boolean = classify(error) != StressSignal.NONE
+
+ private enum class StressSignal {
+ NONE,
+ THROTTLED,
+ TIMEOUT,
+ CONNECTION_RESET,
+ CONNECTION_FAILURE
+ }
+
+ private fun classify(error: Throwable): StressSignal {
+ return when {
+ error is XtreamAuthenticationException -> StressSignal.THROTTLED
+ error is XtreamRequestException && error.statusCode in setOf(403, 429) -> StressSignal.THROTTLED
+ messageContains(error, "timeout") || messageContains(error, "timed out") -> StressSignal.TIMEOUT
+ messageContains(error, "connection reset") || messageContains(error, "reset by peer") -> StressSignal.CONNECTION_RESET
+ messageContains(error, "connection refused") ||
+ messageContains(error, "failed to connect") ||
+ messageContains(error, "unable to resolve host") ||
+ messageContains(error, "broken pipe") -> StressSignal.CONNECTION_FAILURE
+ error is XtreamNetworkException || error is IOException -> StressSignal.TIMEOUT
+ else -> StressSignal.NONE
+ }
+ }
+
+ private fun segmentedRequestSpacingFor(providerId: Long, stage: Stage): Long {
+ if (stage != Stage.CATEGORY && stage != Stage.PAGED) {
+ return 0L
+ }
+ val health = providerHealth[providerId] ?: ProviderHealth()
+ val baseSpacingMs = when (stage) {
+ Stage.CATEGORY -> 250L
+ Stage.PAGED -> 180L
+ else -> 0L
+ }
+ val stressSpacingMs = when {
+ health.stressLevel >= 4 -> 900L
+ health.stressLevel >= 3 -> 650L
+ health.stressLevel >= 2 -> 400L
+ health.stressLevel >= 1 -> 200L
+ else -> 0L
+ }
+ return baseSpacingMs + stressSpacingMs
+ }
+
+ private fun messageContains(error: Throwable, needle: String): Boolean =
+ error.message.orEmpty().contains(needle, ignoreCase = true)
+}
diff --git a/data/src/main/java/com/streamvault/data/sync2.zip b/data/src/main/java/com/streamvault/data/sync2.zip
new file mode 100644
index 00000000..592640ee
Binary files /dev/null and b/data/src/main/java/com/streamvault/data/sync2.zip differ
diff --git a/data/src/test/java/com/streamvault/data/remote/xtream/OkHttpXtreamApiServiceTest.kt b/data/src/test/java/com/streamvault/data/remote/xtream/OkHttpXtreamApiServiceTest.kt
index edee896f..b3993012 100644
--- a/data/src/test/java/com/streamvault/data/remote/xtream/OkHttpXtreamApiServiceTest.kt
+++ b/data/src/test/java/com/streamvault/data/remote/xtream/OkHttpXtreamApiServiceTest.kt
@@ -1,6 +1,7 @@
package com.streamvault.data.remote.xtream
import com.google.common.truth.Truth.assertThat
+import com.streamvault.data.remote.dto.XtreamSeriesInfoResponse
import java.net.SocketTimeoutException
import kotlinx.coroutines.test.runTest
import kotlinx.serialization.json.Json
@@ -14,7 +15,12 @@ import org.junit.Test
class OkHttpXtreamApiServiceTest {
- private val json = Json { ignoreUnknownKeys = true }
+ private val json = Json {
+ ignoreUnknownKeys = true
+ isLenient = true
+ explicitNulls = false
+ coerceInputValues = true
+ }
@Test
fun `get classifies 401 as authentication error`() = runTest {
@@ -43,7 +49,7 @@ class OkHttpXtreamApiServiceTest {
}.exceptionOrNull()
assertThat(failure).isInstanceOf(XtreamParsingException::class.java)
- assertThat(failure).hasMessageThat().contains("malformed")
+ assertThat(failure).hasMessageThat().contains("Malformed JSON")
}
@Test
@@ -63,6 +69,64 @@ class OkHttpXtreamApiServiceTest {
assertThat(failure).hasMessageThat().contains("timed out")
}
+ @Test
+ fun `streamVodStreams decodes array incrementally`() = runTest {
+ val service = OkHttpXtreamApiService(
+ client = clientReturning(
+ statusCode = 200,
+ body = """
+ [
+ {"stream_id": "101", "name": "Movie One", "container_extension": "mp4"},
+ {"stream_id": "102", "name": "Movie Two", "container_extension": "mkv"}
+ ]
+ """.trimIndent()
+ ),
+ json = json
+ )
+ val seenIds = mutableListOf<Long>()
+
+ val count = service.streamVodStreams("https://example.test/player_api.php?action=get_vod_streams") { item ->
+ seenIds += item.streamId
+ }
+
+ assertThat(count).isEqualTo(2)
+ assertThat(seenIds).containsExactly(101L, 102L).inOrder()
+ }
+
+ @Test
+ fun `series info parser tolerates flattened info and nested episode objects`() {
+ val payload = """
+ {
+ "name": "Example Series",
+ "cover_big": "https://img.example.test/cover.jpg",
+ "releasedate": "2024-04-01",
+ "episodes": {
+ "1": {
+ "101": {
+ "id": "101",
+ "episode_num": "1",
+ "title": "Pilot",
+ "season": "1",
+ "container_extension": "mp4",
+ "info": {
+ "plot": "First episode"
+ }
+ }
+ }
+ }
+ }
+ """.trimIndent()
+
+ val response = json.decodeFromString<XtreamSeriesInfoResponse>(payload)
+
+ assertThat(response.info).isNotNull()
+ assertThat(response.info?.name).isEqualTo("Example Series")
+ assertThat(response.info?.releaseDateAlt).isEqualTo("2024-04-01")
+ assertThat(response.episodes.keys).containsExactly("1")
+ assertThat(response.episodes["1"]).hasSize(1)
+ assertThat(response.episodes["1"]?.first()?.title).isEqualTo("Pilot")
+ }
+
private fun clientReturning(statusCode: Int, body: String): OkHttpClient {
return OkHttpClient.Builder()
.addInterceptor { chain ->
@@ -76,4 +140,4 @@ class OkHttpXtreamApiServiceTest {
}
.build()
}
-}
\ No newline at end of file
+}
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.kt
index bcde66b4..90bb156e 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
@@ -258,6 +258,138 @@ class XtreamProviderTest {
assertThat(movie.isAdult).isTrue()
}
+ @Test
+ fun `vod list and details both normalize ratings to ten point scale`() = runBlocking {
+ val provider = XtreamProvider(
+ providerId = 42,
+ api = FakeXtreamApiService(
+ vodStreams = listOf(
+ XtreamStream(
+ name = "Movie",
+ streamId = 55,
+ rating = "10.0",
+ rating5based = "5"
+ )
+ ),
+ vodInfo = XtreamVodInfoResponse(
+ info = XtreamVodInfo(
+ rating = "10.0",
+ rating5based = "5"
+ ),
+ movieData = XtreamVodMovieData(
+ streamId = 55,
+ name = "Movie"
+ )
+ )
+ ),
+ serverUrl = "https://example.com",
+ username = "user",
+ password = "pass"
+ )
+
+ val gridMovie = provider.getVodStreams().getOrNull().orEmpty().single()
+ val detailMovie = provider.getVodInfo(55).getOrNull()
+
+ assertThat(gridMovie.rating).isEqualTo(10f)
+ assertThat(detailMovie?.rating).isEqualTo(10f)
+ }
+
+ @Test
+ fun `getSeriesInfo falls back to legacy series query parameter when primary payload is empty`() = runBlocking {
+ val requestedEndpoints = mutableListOf<String>()
+ val provider = XtreamProvider(
+ providerId = 42,
+ api = object : XtreamApiService {
+ override suspend fun authenticate(endpoint: String): XtreamAuthResponse =
+ XtreamAuthResponse(XtreamUserInfo(auth = 1), XtreamServerInfo())
+
+ override suspend fun getLiveCategories(endpoint: String): List<XtreamCategory> = emptyList()
+
+ override suspend fun getLiveStreams(endpoint: String): List<XtreamStream> = emptyList()
+
+ override suspend fun getVodCategories(endpoint: String): List<XtreamCategory> = emptyList()
+
+ override suspend fun getVodStreams(endpoint: String): List<XtreamStream> = emptyList()
+
+ override suspend fun getVodInfo(endpoint: String): XtreamVodInfoResponse = XtreamVodInfoResponse()
+
+ override suspend fun getSeriesCategories(endpoint: String): List<XtreamCategory> = emptyList()
+
+ override suspend fun getSeriesList(endpoint: String): List<XtreamSeriesItem> = emptyList()
+
+ override suspend fun getSeriesInfo(endpoint: String): XtreamSeriesInfoResponse {
+ requestedEndpoints += endpoint
+ return if (endpoint.contains("series_id=77")) {
+ XtreamSeriesInfoResponse()
+ } else {
+ XtreamSeriesInfoResponse(
+ info = XtreamSeriesItem(name = "Fallback Series"),
+ episodes = mapOf(
+ "1" to listOf(
+ XtreamEpisode(
+ id = "501",
+ episodeNum = 1,
+ title = "Episode One",
+ season = 1,
+ containerExtension = "mp4"
+ )
+ )
+ )
+ )
+ }
+ }
+
+ override suspend fun getShortEpg(endpoint: String): XtreamEpgResponse = XtreamEpgResponse()
+
+ override suspend fun getFullEpg(endpoint: String): XtreamEpgResponse = XtreamEpgResponse()
+ },
+ serverUrl = "https://example.com",
+ username = "user",
+ password = "pass"
+ )
+
+ val series = provider.getSeriesInfo(77).getOrNull()
+
+ assertThat(series).isNotNull()
+ assertThat(series?.name).isEqualTo("Fallback Series")
+ assertThat(series?.seasons).hasSize(1)
+ assertThat(requestedEndpoints).hasSize(2)
+ assertThat(requestedEndpoints.first()).contains("series_id=77")
+ assertThat(requestedEndpoints.last()).contains("series=77")
+ }
+
+ @Test
+ fun `getSeriesInfo builds usable series from episodes when info block is missing`() = runBlocking {
+ val provider = XtreamProvider(
+ providerId = 42,
+ api = FakeXtreamApiService(
+ seriesInfo = XtreamSeriesInfoResponse(
+ episodes = mapOf(
+ "1" to listOf(
+ XtreamEpisode(
+ id = "701",
+ episodeNum = 1,
+ title = "Pilot",
+ season = 1,
+ containerExtension = "mp4"
+ )
+ )
+ )
+ )
+ ),
+ serverUrl = "https://example.com",
+ username = "user",
+ password = "pass"
+ )
+
+ val series = provider.getSeriesInfo(88).getOrNull()
+
+ assertThat(series).isNotNull()
+ assertThat(series?.seriesId).isEqualTo(88L)
+ assertThat(series?.seasons).hasSize(1)
+ assertThat(series?.seasons?.first()?.episodes).hasSize(1)
+ }
+
private class FakeXtreamApiService(
private val authResponse: XtreamAuthResponse = XtreamAuthResponse(XtreamUserInfo(auth = 1), XtreamServerInfo()),
private val liveCategories: List<XtreamCategory> = emptyList(),
diff --git a/data/src/test/java/com/streamvault/data/repository/EpgRepositoryImplTest.kt b/data/src/test/java/com/streamvault/data/repository/EpgRepositoryImplTest.kt
index df1667a2..dfee6f92 100644
--- a/data/src/test/java/com/streamvault/data/repository/EpgRepositoryImplTest.kt
+++ b/data/src/test/java/com/streamvault/data/repository/EpgRepositoryImplTest.kt
@@ -3,6 +3,7 @@ package com.streamvault.data.repository
import com.google.common.truth.Truth.assertThat
import com.streamvault.data.local.DatabaseTransactionRunner
import com.streamvault.data.local.dao.ProgramDao
+import com.streamvault.data.local.entity.ProgramBrowseEntity
import com.streamvault.data.local.entity.ProgramEntity
import com.streamvault.data.parser.XmltvParser
import com.streamvault.domain.model.Program
@@ -44,7 +45,7 @@ class EpgRepositoryImplTest {
whenever(programDao.searchPrograms(any(), any(), any(), any(), anyOrNull(), any())).thenReturn(
flowOf(
listOf(
- ProgramEntity(
+ ProgramBrowseEntity(
id = 1L,
providerId = 7L,
channelId = "one",
@@ -52,7 +53,7 @@ class EpgRepositoryImplTest {
startTime = 10L,
endTime = 20L
),
- ProgramEntity(
+ ProgramBrowseEntity(
id = 2L,
providerId = 7L,
channelId = "two",
@@ -156,4 +157,4 @@ class EpgRepositoryImplTest {
.build()
}
.build()
-}
\ No newline at end of file
+}
diff --git a/data/src/test/java/com/streamvault/data/repository/MovieRepositoryImplTest.kt b/data/src/test/java/com/streamvault/data/repository/MovieRepositoryImplTest.kt
index 2bfb1388..33570b64 100644
--- a/data/src/test/java/com/streamvault/data/repository/MovieRepositoryImplTest.kt
+++ b/data/src/test/java/com/streamvault/data/repository/MovieRepositoryImplTest.kt
@@ -7,8 +7,9 @@ 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.entity.FavoriteEntity
+import com.streamvault.data.local.entity.MovieBrowseEntity
import com.streamvault.data.local.entity.MovieEntity
-import com.streamvault.data.local.entity.PlaybackHistoryEntity
+import com.streamvault.data.local.entity.PlaybackHistoryLiteEntity
import com.streamvault.data.local.entity.ProviderEntity
import com.streamvault.data.preferences.PreferencesRepository
import com.streamvault.data.remote.dto.XtreamCategory
@@ -45,7 +46,6 @@ class MovieRepositoryImplTest {
id = 1L,
name = "Space Run",
genre = "Action, Sci-Fi",
- cast = "Ava Stone",
categoryId = 10L,
rating = 7.2f
)
@@ -53,7 +53,6 @@ class MovieRepositoryImplTest {
id = 2L,
name = "Galaxy Pursuit",
genre = "Sci-Fi Action",
- cast = "Ava Stone",
categoryId = 10L,
rating = 8.8f
)
@@ -61,17 +60,18 @@ class MovieRepositoryImplTest {
id = 3L,
name = "Quiet Tea",
genre = "Drama",
- cast = "Noah Reed",
categoryId = 11L,
rating = 9.5f
)
- stubVisibleMovies(listOf(watchedMovie, recommendedMovie, unrelatedMovie))
+ whenever(preferencesRepository.parentalControlLevel).thenReturn(flowOf(0))
+ whenever(movieDao.getTopRatedPreview(7L, 48)).thenReturn(flowOf(listOf(recommendedMovie, unrelatedMovie, watchedMovie)))
+ whenever(movieDao.getFreshPreview(7L, 48)).thenReturn(flowOf(listOf(recommendedMovie, unrelatedMovie, watchedMovie)))
whenever(favoriteDao.getAllByType(ContentType.MOVIE.name)).thenReturn(flowOf(emptyList()))
- whenever(playbackHistoryDao.getRecentlyWatchedByProvider(eq(7L), any())).thenReturn(
+ whenever(playbackHistoryDao.getRecentlyWatchedByProvider(eq(7L), eq(24))).thenReturn(
flowOf(
listOf(
- PlaybackHistoryEntity(
+ PlaybackHistoryLiteEntity(
contentId = watchedMovie.id,
contentType = ContentType.MOVIE,
providerId = 7L,
@@ -92,12 +92,11 @@ class MovieRepositoryImplTest {
}
@Test
- fun `getRelatedContent ranks shared genre and cast ahead of category only matches`() = runTest {
+ fun `getRelatedContent ranks shared genre ahead of category only matches`() = runTest {
val targetMovie = movieEntity(
id = 1L,
name = "Space Run",
genre = "Action, Sci-Fi",
- cast = "Ava Stone",
categoryId = 10L,
rating = 7.2f
)
@@ -105,7 +104,6 @@ class MovieRepositoryImplTest {
id = 2L,
name = "Galaxy Pursuit",
genre = "Sci-Fi Action",
- cast = "Ava Stone",
categoryId = 10L,
rating = 8.8f
)
@@ -113,12 +111,23 @@ class MovieRepositoryImplTest {
id = 3L,
name = "Harbor Escape",
genre = "Thriller",
- cast = "Milo Hart",
categoryId = 10L,
rating = 9.0f
)
- stubVisibleMovies(listOf(targetMovie, closeMatch, categoryOnly))
+ whenever(preferencesRepository.parentalControlLevel).thenReturn(flowOf(0))
+ whenever(movieDao.getCountByCategory(7L, 10L)).thenReturn(flowOf(1))
+ whenever(movieDao.getById(targetMovie.id)).thenReturn(
+ movieRecord(
+ id = targetMovie.id,
+ name = targetMovie.name,
+ genre = targetMovie.genre.orEmpty(),
+ categoryId = targetMovie.categoryId ?: 0L,
+ rating = targetMovie.rating
+ )
+ )
+ whenever(movieDao.getByCategoryPreview(7L, 10L, 48)).thenReturn(flowOf(listOf(targetMovie, closeMatch, categoryOnly)))
+ whenever(movieDao.getTopRatedPreview(7L, 32)).thenReturn(flowOf(listOf(closeMatch, categoryOnly)))
val repository = createRepository()
@@ -176,16 +185,27 @@ class MovieRepositoryImplTest {
xtreamStreamUrlResolver = xtreamStreamUrlResolver
)
- private fun stubVisibleMovies(movies: List<MovieEntity>) {
- whenever(preferencesRepository.parentalControlLevel).thenReturn(flowOf(0))
- whenever(movieDao.getByProvider(7L)).thenReturn(flowOf(movies))
- }
-
private fun movieEntity(
id: Long,
name: String,
genre: String,
- cast: String,
+ categoryId: Long,
+ rating: Float
+ ) = MovieBrowseEntity(
+ id = id,
+ streamId = id,
+ name = name,
+ genre = genre,
+ categoryId = categoryId,
+ providerId = 7L,
+ rating = rating,
+ streamUrl = "https://example.com/$id.m3u8"
+ )
+
+ private fun movieRecord(
+ id: Long,
+ name: String,
+ genre: String,
categoryId: Long,
rating: Float
) = MovieEntity(
@@ -193,7 +213,6 @@ class MovieRepositoryImplTest {
streamId = id,
name = name,
genre = genre,
- cast = cast,
categoryId = categoryId,
providerId = 7L,
rating = rating,
diff --git a/data/src/test/java/com/streamvault/data/repository/SeriesRepositoryImplTest.kt b/data/src/test/java/com/streamvault/data/repository/SeriesRepositoryImplTest.kt
index 757c4214..97a4ec62 100644
--- a/data/src/test/java/com/streamvault/data/repository/SeriesRepositoryImplTest.kt
+++ b/data/src/test/java/com/streamvault/data/repository/SeriesRepositoryImplTest.kt
@@ -12,6 +12,7 @@ import com.streamvault.data.local.entity.ProviderEntity
import com.streamvault.data.preferences.PreferencesRepository
import com.streamvault.data.remote.dto.XtreamCategory
import com.streamvault.data.remote.dto.XtreamSeriesItem
+import com.streamvault.data.remote.xtream.XtreamParsingException
import com.streamvault.data.remote.xtream.XtreamApiService
import com.streamvault.data.remote.xtream.XtreamStreamUrlResolver
import com.streamvault.domain.model.ProviderStatus
@@ -111,6 +112,42 @@ class SeriesRepositoryImplTest {
assertThat(series.seriesId).isEqualTo(301L)
}
+ @Test
+ fun `getSeriesDetails returns local series when xtream details fail`() = runTest {
+ val seriesEntity = SeriesEntity(
+ id = 15L,
+ seriesId = 301L,
+ name = "Stored Series",
+ posterUrl = "https://img.example.test/poster.jpg",
+ providerId = 7L
+ )
+ whenever(seriesDao.getById(301L)).thenReturn(null)
+ whenever(seriesDao.getBySeriesId(7L, 301L)).thenReturn(seriesEntity)
+ whenever(providerDao.getById(7L)).thenReturn(
+ ProviderEntity(
+ id = 7L,
+ name = "Xtream",
+ type = ProviderType.XTREAM_CODES,
+ serverUrl = "http://example.com",
+ username = "user",
+ password = "pass",
+ status = ProviderStatus.ACTIVE
+ )
+ )
+ whenever(episodeDao.getBySeriesSync(15L)).thenReturn(emptyList())
+ whenever(xtreamApiService.getSeriesInfo(any())).thenThrow(RuntimeException("bad response"))
+
+ val repository = createRepository()
+
+ val result = repository.getSeriesDetails(7L, 301L)
+
+ assertThat(result).isInstanceOf(com.streamvault.domain.model.Result.Success::class.java)
+ val series = (result as com.streamvault.domain.model.Result.Success).data
+ assertThat(series.id).isEqualTo(15L)
+ assertThat(series.name).isEqualTo("Stored Series")
+ assertThat(series.posterUrl).isEqualTo("https://img.example.test/poster.jpg")
+ }
+
private fun createRepository() = SeriesRepositoryImpl(
seriesDao = seriesDao,
episodeDao = episodeDao,
diff --git a/data/src/test/java/com/streamvault/data/sync/SyncManagerTest.kt b/data/src/test/java/com/streamvault/data/sync/SyncManagerTest.kt
index ab34dd2d..d5477f04 100644
--- a/data/src/test/java/com/streamvault/data/sync/SyncManagerTest.kt
+++ b/data/src/test/java/com/streamvault/data/sync/SyncManagerTest.kt
@@ -1,6 +1,8 @@
package com.streamvault.data.sync
import com.google.common.truth.Truth.assertThat
+import com.streamvault.data.local.DatabaseTransactionRunner
+import com.streamvault.data.local.dao.CatalogSyncDao
import com.streamvault.data.local.dao.CategoryDao
import com.streamvault.data.local.dao.ChannelDao
import com.streamvault.data.local.dao.MovieDao
@@ -9,8 +11,6 @@ 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.parser.M3uParser
-import com.streamvault.data.remote.xtream.XtreamApiService
-import com.streamvault.data.remote.dto.XtreamStream
import com.streamvault.domain.model.SyncState
import com.streamvault.domain.model.Result
import com.streamvault.domain.model.ProviderType
@@ -20,21 +20,24 @@ import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.flowOf
+import kotlinx.coroutines.test.advanceUntilIdle
import kotlinx.coroutines.test.runTest
+import kotlinx.serialization.json.Json
+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.any
-import org.mockito.kotlin.anyOrNull
import org.mockito.kotlin.atLeast
import org.mockito.kotlin.atLeastOnce
import org.mockito.kotlin.argumentCaptor
import org.mockito.kotlin.eq
import org.mockito.kotlin.mock
-import org.mockito.kotlin.never
import org.mockito.kotlin.verify
-import org.mockito.kotlin.whenever
import java.util.zip.GZIPOutputStream
/**
@@ -95,6 +98,44 @@ class SyncManagerTest {
}
}
+ private class FakeXtreamBackend {
+ private data class StubbedResponse(
+ val code: Int,
+ val body: String,
+ val contentType: String = "application/json"
+ )
+
+ private val stubs = mutableMapOf<String, StubbedResponse>()
+ val requestedActions = mutableListOf<String>()
+
+ fun respond(action: String, body: String, code: Int = 200) {
+ stubs[action] = StubbedResponse(code = code, body = body)
+ }
+
+ fun requestCount(): Int = requestedActions.size
+
+ fun okHttpClient(): OkHttpClient {
+ return OkHttpClient.Builder()
+ .addInterceptor { chain ->
+ val request = chain.request()
+ val action = request.url.queryParameter("action").orEmpty()
+ requestedActions += action
+ val stub = stubs[action] ?: StubbedResponse(
+ code = 500,
+ body = """{"error":"missing stub for $action"}"""
+ )
+ Response.Builder()
+ .request(request)
+ .protocol(Protocol.HTTP_1_1)
+ .code(stub.code)
+ .message(if (stub.code in 200..299) "OK" else "ERROR")
+ .body(stub.body.toResponseBody(stub.contentType.toMediaType()))
+ .build()
+ }
+ .build()
+ }
+ }
+
// Mockito mocks — all return defaults (null/0/Unit), which will cause
// the sync pipeline to throw and transition to Error state.
private val channelDao: ChannelDao = mock()
@@ -102,9 +143,16 @@ class SyncManagerTest {
private val seriesDao: SeriesDao = mock()
private val programDao: ProgramDao = mock()
private val categoryDao: CategoryDao = mock()
- private val xtreamApi: XtreamApiService = mock()
+ private val catalogSyncDao: CatalogSyncDao = mock()
private val epgRepo: EpgRepository = mock()
- private val okHttp: OkHttpClient = mock()
+ private val xtreamBackend = FakeXtreamBackend()
+ private val xtreamJson = Json {
+ ignoreUnknownKeys = true
+ isLenient = true
+ }
+ private val transactionRunner = object : DatabaseTransactionRunner {
+ override suspend fun <T> inTransaction(block: suspend () -> T): T = block()
+ }
private val syncMetadataRepo = FakeSyncMetadataRepository()
private fun buildManager(
@@ -124,11 +172,13 @@ class SyncManagerTest {
seriesDao = seriesDao,
programDao = programDao,
categoryDao = categoryDao,
- xtreamApiService = xtreamApi,
+ catalogSyncDao = catalogSyncDao,
+ xtreamJson = xtreamJson,
m3uParser = M3uParser(),
epgRepository = epgRepo,
- okHttpClient = okHttp,
- syncMetadataRepository = syncMetadataRepo
+ okHttpClient = xtreamBackend.okHttpClient(),
+ syncMetadataRepository = syncMetadataRepo,
+ transactionRunner = transactionRunner
)
// ── Initial state ───────────────────────────────────────────────
@@ -136,7 +186,7 @@ class SyncManagerTest {
@Test
fun `initialState_isIdle`() = runTest {
val mgr = buildManager()
- assertThat(mgr.syncState.first()).isEqualTo(SyncState.Idle)
+ assertThat(mgr.currentSyncState(1L)).isEqualTo(SyncState.Idle)
}
// ── Provider not found ──────────────────────────────────────────
@@ -149,7 +199,7 @@ class SyncManagerTest {
assertThat(result.isError).isTrue()
// State must NOT transition away from Idle (no provider = nothing to sync)
- assertThat(mgr.syncState.first()).isEqualTo(SyncState.Idle)
+ assertThat(mgr.currentSyncState(99L)).isEqualTo(SyncState.Idle)
}
// ── Xtream sync failure ─────────────────────────────────────────
@@ -161,8 +211,9 @@ class SyncManagerTest {
// The Xtream path calls XtreamProvider(xtreamApi,...).getLiveCategories()
// Since xtreamApi is a mock with null returns, the call throws → manager catches → Error
mgr.sync(1L)
+ advanceUntilIdle()
- assertThat(mgr.syncState.first()).isInstanceOf(SyncState.Error::class.java)
+ assertThat(mgr.currentSyncState(1L)).isInstanceOf(SyncState.Error::class.java)
}
@Test
@@ -173,8 +224,9 @@ class SyncManagerTest {
// before this coroutine resumes. We verify the terminal state is Error —
// that's only reachable via Syncing, proving the full transition happened.
mgr.sync(1L)
+ advanceUntilIdle()
- val finalState = mgr.syncState.first()
+ val finalState = mgr.currentSyncState(1L)
assertThat(finalState).isInstanceOf(SyncState.Error::class.java)
}
@@ -182,8 +234,9 @@ class SyncManagerTest {
fun `sync_xtream_errorHasNonEmptyMessage`() = runTest {
val mgr = buildManager(providerType = ProviderType.XTREAM_CODES)
mgr.sync(1L)
+ advanceUntilIdle()
- val state = mgr.syncState.first() as? SyncState.Error
+ val state = mgr.currentSyncState(1L) as? SyncState.Error
assertThat(state).isNotNull()
assertThat(state!!.message).isNotEmpty()
}
@@ -203,10 +256,10 @@ class SyncManagerTest {
)
val result = mgr.sync(1L, force = false)
+ advanceUntilIdle()
assertThat(result.isSuccess).isTrue()
- verify(xtreamApi, never()).getLiveCategories(any())
- verify(xtreamApi, never()).getLiveStreams(any())
+ assertThat(xtreamBackend.requestCount()).isEqualTo(0)
}
@Test
@@ -221,34 +274,35 @@ class SyncManagerTest {
lastEpgSync = now
)
)
- whenever(xtreamApi.getVodCategories(any())).thenThrow(RuntimeException("categories unavailable"))
- whenever(xtreamApi.getVodStreams(any())).thenReturn(
- listOf(
- XtreamStream(
- name = "Movie One",
- streamId = 101,
- categoryId = "vod-action",
- categoryName = "Action",
- containerExtension = "mp4"
- )
- )
+ xtreamBackend.respond(action = "get_vod_categories", body = """{"error":"categories unavailable"}""", code = 500)
+ xtreamBackend.respond(
+ action = "get_vod_streams",
+ body = """
+ [
+ {
+ "name": "Movie One",
+ "stream_id": 101,
+ "category_id": "vod-action",
+ "category_name": "Action",
+ "container_extension": "mp4"
+ }
+ ]
+ """.trimIndent()
)
val result = mgr.sync(1L, force = false)
+ advanceUntilIdle()
assertThat(result.isSuccess).isTrue()
- val categoriesCaptor = argumentCaptor<List<com.streamvault.data.local.entity.CategoryEntity>>()
- verify(categoryDao).replaceAll(eq(1L), eq("MOVIE"), categoriesCaptor.capture())
- assertThat(categoriesCaptor.firstValue).hasSize(1)
- assertThat(categoriesCaptor.firstValue.first().name).isEqualTo("Action")
- assertThat(categoriesCaptor.firstValue.first().categoryId).isGreaterThan(0L)
+ val categoriesCaptor = argumentCaptor<List<com.streamvault.data.local.entity.CategoryImportStageEntity>>()
+ verify(catalogSyncDao, atLeastOnce()).insertCategoryStages(categoriesCaptor.capture())
+ val movieCategories = categoriesCaptor.allValues.flatten().filter { it.type.name == "MOVIE" }
+ assertThat(movieCategories).hasSize(1)
+ assertThat(movieCategories.first().name).isEqualTo("Action")
}
@Test
fun `sync_m3u_fileImport_batchesAndDiscoversEpg`() = runTest {
- whenever(channelDao.getIdMappings(1L)).thenReturn(emptyList())
- whenever(movieDao.getIdMappings(1L)).thenReturn(emptyList())
-
val playlist = tempFolder.newFile("playlist.m3u")
playlist.writeText(buildString {
append("#EXTM3U x-tvg-url=\"https://epg.example.com/guide.xml\"\n")
@@ -264,20 +318,18 @@ class SyncManagerTest {
val mgr = buildManager(providerType = ProviderType.M3U, providerEntity = provider)
val result = mgr.sync(1L, force = true)
+ advanceUntilIdle()
if (result is Result.Error) {
error(result.message)
}
assertThat(result.isSuccess).isTrue()
- verify(channelDao, atLeast(3)).insertAll(any())
- verify(movieDao, atLeastOnce()).insertAll(any())
+ verify(catalogSyncDao, atLeast(3)).insertChannelStages(any())
+ verify(catalogSyncDao, atLeastOnce()).insertMovieStages(any())
}
@Test
fun `sync_m3u_gzipFileImport_succeeds`() = runTest {
- whenever(channelDao.getIdMappings(1L)).thenReturn(emptyList())
- whenever(movieDao.getIdMappings(1L)).thenReturn(emptyList())
-
val gzFile = tempFolder.newFile("playlist.m3u.gz")
GZIPOutputStream(gzFile.outputStream()).bufferedWriter(Charsets.UTF_8).use { writer ->
writer.write("#EXTM3U\n")
@@ -289,19 +341,17 @@ class SyncManagerTest {
val mgr = buildManager(providerType = ProviderType.M3U, providerEntity = provider)
val result = mgr.sync(1L, force = true)
+ advanceUntilIdle()
if (result is Result.Error) {
error(result.message)
}
assertThat(result.isSuccess).isTrue()
- verify(channelDao, atLeastOnce()).insertAll(any())
+ verify(catalogSyncDao, atLeastOnce()).insertChannelStages(any())
}
@Test
fun `sync_m3u_ignores_insecure_streams_and_header_epg`() = runTest {
- whenever(channelDao.getIdMappings(1L)).thenReturn(emptyList())
- whenever(movieDao.getIdMappings(1L)).thenReturn(emptyList())
-
val playlist = tempFolder.newFile("mixed-playlist.m3u")
playlist.writeText(
"""
@@ -317,12 +367,13 @@ class SyncManagerTest {
val mgr = buildManager(providerType = ProviderType.M3U, providerEntity = provider)
val result = mgr.sync(1L, force = true)
+ advanceUntilIdle()
assertThat(result.isSuccess).isTrue()
- val state = mgr.syncState.first()
+ val state = mgr.currentSyncState(1L)
assertThat(state).isInstanceOf(SyncState.Partial::class.java)
- val insertedChannels = argumentCaptor<List<com.streamvault.data.local.entity.ChannelEntity>>()
- verify(channelDao, atLeastOnce()).insertAll(insertedChannels.capture())
+ val insertedChannels = argumentCaptor<List<com.streamvault.data.local.entity.ChannelImportStageEntity>>()
+ verify(catalogSyncDao, atLeastOnce()).insertChannelStages(insertedChannels.capture())
assertThat(insertedChannels.allValues.flatten()).hasSize(1)
assertThat((state as SyncState.Partial).warnings).contains("Ignored insecure EPG URL from playlist header.")
}
@@ -335,8 +386,9 @@ class SyncManagerTest {
// OkHttpClient mock: newCall() returns null → NullPointerException → Error
mgr.sync(1L)
+ advanceUntilIdle()
- assertThat(mgr.syncState.first()).isInstanceOf(SyncState.Error::class.java)
+ assertThat(mgr.currentSyncState(1L)).isInstanceOf(SyncState.Error::class.java)
}
// ── Reset state ─────────────────────────────────────────────────
@@ -345,12 +397,14 @@ class SyncManagerTest {
fun `resetState_afterError_returnsToIdle`() = runTest {
val mgr = buildManager()
mgr.sync(1L) // fails → Error
+ advanceUntilIdle()
- assertThat(mgr.syncState.first()).isInstanceOf(SyncState.Error::class.java)
+ assertThat(mgr.currentSyncState(1L)).isInstanceOf(SyncState.Error::class.java)
mgr.resetState()
+ advanceUntilIdle()
- assertThat(mgr.syncState.first()).isEqualTo(SyncState.Idle)
+ assertThat(mgr.currentSyncState(1L)).isEqualTo(SyncState.Idle)
}
@Test
@@ -359,7 +413,7 @@ class SyncManagerTest {
mgr.resetState() // should be a no-op
- assertThat(mgr.syncState.first()).isEqualTo(SyncState.Idle)
+ assertThat(mgr.currentSyncState(1L)).isEqualTo(SyncState.Idle)
}
// ── isVodEntry (SyncManager is the canonical source) ───────────
diff --git a/domain/src/main/java/com/streamvault/domain/model/SyncMetadata.kt b/domain/src/main/java/com/streamvault/domain/model/SyncMetadata.kt
index d8177d3e..71895222 100644
--- a/domain/src/main/java/com/streamvault/domain/model/SyncMetadata.kt
+++ b/domain/src/main/java/com/streamvault/domain/model/SyncMetadata.kt
@@ -25,8 +25,15 @@ data class SyncMetadata(
val movieSyncMode: VodSyncMode = VodSyncMode.UNKNOWN,
val movieWarningsCount: Int = 0,
val movieCatalogStale: Boolean = false,
+ val liveAvoidFullUntil: Long = 0,
+ val movieAvoidFullUntil: Long = 0,
+ val seriesAvoidFullUntil: Long = 0,
+ val liveSequentialFailuresRemembered: Boolean = false,
+ val liveHealthySyncStreak: Int = 0,
val movieParallelFailuresRemembered: Boolean = false,
- val movieHealthySyncStreak: Int = 0
+ val movieHealthySyncStreak: Int = 0,
+ val seriesSequentialFailuresRemembered: Boolean = false,
+ val seriesHealthySyncStreak: Int = 0
) {
init {
require(liveCount >= 0) { "liveCount must be non-negative" }
@@ -34,6 +41,11 @@ data class SyncMetadata(
require(seriesCount >= 0) { "seriesCount must be non-negative" }
require(epgCount >= 0) { "epgCount must be non-negative" }
require(movieWarningsCount >= 0) { "movieWarningsCount must be non-negative" }
+ require(liveAvoidFullUntil >= 0) { "liveAvoidFullUntil must be non-negative" }
+ require(movieAvoidFullUntil >= 0) { "movieAvoidFullUntil must be non-negative" }
+ require(seriesAvoidFullUntil >= 0) { "seriesAvoidFullUntil must be non-negative" }
+ require(liveHealthySyncStreak >= 0) { "liveHealthySyncStreak must be non-negative" }
require(movieHealthySyncStreak >= 0) { "movieHealthySyncStreak must be non-negative" }
+ require(seriesHealthySyncStreak >= 0) { "seriesHealthySyncStreak must be non-negative" }
}
}
diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml
index b264fe89..363dfd90 100644
--- a/gradle/libs.versions.toml
+++ b/gradle/libs.versions.toml
@@ -23,6 +23,7 @@ datastore = "1.2.1"
security-crypto = "1.1.0-alpha06"
gson = "2.11.0"
kotlinx-serialization = "1.9.0"
+leakcanary = "2.14"
work = "2.11.1"
appcompat = "1.7.1"
mediarouter = "1.8.1"
@@ -77,6 +78,7 @@ okhttp = { group = "com.squareup.okhttp3", name = "okhttp", version.ref = "okhtt
okhttp-logging = { group = "com.squareup.okhttp3", name = "logging-interceptor", version.ref = "okhttp" }
gson = { group = "com.google.code.gson", name = "gson", version.ref = "gson" }
kotlinx-serialization-json = { group = "org.jetbrains.kotlinx", name = "kotlinx-serialization-json", version.ref = "kotlinx-serialization" }
+leakcanary-android = { group = "com.squareup.leakcanary", name = "leakcanary-android", version.ref = "leakcanary" }
# Image Loading
coil-compose = { group = "io.coil-kt.coil3", name = "coil-compose", version.ref = "coil" }
diff --git a/player/src/main/java/com/streamvault/player/Media3PlayerEngine.kt b/player/src/main/java/com/streamvault/player/Media3PlayerEngine.kt
index cd377b8b..e2aa3f24 100644
--- a/player/src/main/java/com/streamvault/player/Media3PlayerEngine.kt
+++ b/player/src/main/java/com/streamvault/player/Media3PlayerEngine.kt
@@ -96,6 +96,7 @@ class Media3PlayerEngine @Inject constructor(
private var playbackStarted = false
private var retryAttempt = 0
private var retryJob: Job? = null
+ private var retryGeneration = 0L
private val _playbackState = MutableStateFlow(PlaybackState.IDLE)
override val playbackState: StateFlow<PlaybackState> = _playbackState.asStateFlow()
@@ -144,12 +145,14 @@ class Media3PlayerEngine @Inject constructor(
override val isMuted: StateFlow<Boolean> = audioFocusController.isMuted
private val statsCollector = PlayerStatsCollector(
- scope = scope,
+ scopeProvider = { scope },
currentPosition = _currentPosition,
duration = _duration,
videoFormat = _videoFormat,
playerStats = _playerStats
- )
+ ).also {
+ it.bind { exoPlayer }
+ }
private val dataSourceFactoryProvider = PlayerDataSourceFactoryProvider(okHttpClient)
private val mediaSourceFactory = PlayerMediaSourceFactory(dataSourceFactoryProvider)
private val preloadCoordinator = PreloadCoordinator()
@@ -323,7 +326,6 @@ class Media3PlayerEngine @Inject constructor(
supervisorJob.cancel()
supervisorJob = SupervisorJob()
scope = CoroutineScope(Dispatchers.Main.immediate + supervisorJob)
- statsCollector.bind { exoPlayer }
}
private fun prepareInternal(
@@ -333,6 +335,8 @@ class Media3PlayerEngine @Inject constructor(
autoPlay: Boolean
) {
retryJob?.cancel()
+ retryJob = null
+ retryGeneration++
lastStreamInfo = streamInfo
val mediaId = mediaSourceFactory.mediaIdFor(streamInfo)
if (!preserveRetryState || lastMediaId != mediaId) {
@@ -599,6 +603,8 @@ class Media3PlayerEngine @Inject constructor(
}
private fun handlePlaybackError(error: PlaybackException) {
+ retryJob?.cancel()
+ retryJob = null
val streamInfo = lastStreamInfo
val mediaId = lastMediaId
val retryPolicy = currentRetryPolicy
@@ -628,6 +634,7 @@ class Media3PlayerEngine @Inject constructor(
val nextAttempt = retryAttempt + 1
if (retryPolicy.shouldRetry(error, retryContext, playbackStarted, nextAttempt)) {
val delayMs = retryPolicy.retryDelayMs(error, nextAttempt)
+ val scheduledRetryGeneration = retryGeneration
retryAttempt = nextAttempt
_retryStatus.value = PlayerRetryStatus(
attempt = nextAttempt,
@@ -640,6 +647,14 @@ class Media3PlayerEngine @Inject constructor(
)
retryJob = scope.launch {
delay(delayMs)
+ if (
+ scheduledRetryGeneration != retryGeneration ||
+ lastMediaId != mediaId ||
+ retryAttempt != nextAttempt
+ ) {
+ return@launch
+ }
+ retryJob = null
prepareInternal(streamInfo, preserveRetryState = true, seekPositionMs = null, autoPlay = true)
}
return
diff --git a/player/src/main/java/com/streamvault/player/stats/PlayerStatsCollector.kt b/player/src/main/java/com/streamvault/player/stats/PlayerStatsCollector.kt
index 30512bc4..df488b7c 100644
--- a/player/src/main/java/com/streamvault/player/stats/PlayerStatsCollector.kt
+++ b/player/src/main/java/com/streamvault/player/stats/PlayerStatsCollector.kt
@@ -5,22 +5,28 @@ import androidx.media3.exoplayer.ExoPlayer
import com.streamvault.domain.model.VideoFormat
import com.streamvault.player.PlayerStats
import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
+import kotlinx.coroutines.withContext
class PlayerStatsCollector(
- private val scope: CoroutineScope,
+ private val scopeProvider: () -> CoroutineScope,
private val currentPosition: MutableStateFlow<Long>,
private val duration: MutableStateFlow<Long>,
private val videoFormat: MutableStateFlow<VideoFormat>,
private val playerStats: MutableStateFlow<PlayerStats>
) {
- private var positionJob: Job? = null
- private var bufferedJob: Job? = null
- private var statsJob: Job? = null
+ private data class PlayerSnapshot(
+ val currentPosition: Long,
+ val duration: Long,
+ val bufferedDurationMs: Long?
+ )
+
+ private var pollingJob: Job? = null
private var playerProvider: (() -> ExoPlayer?)? = null
private var lastVideoFormat: Format? = null
private var lastAudioFormat: Format? = null
@@ -69,58 +75,77 @@ class PlayerStatsCollector(
fun start() {
stop()
- positionJob = scope.launch {
+ pollingJob = scopeProvider().launch(Dispatchers.Default) {
+ var bufferedUpdateElapsedMs = BUFFERED_UPDATE_INTERVAL_MS
+ var statsUpdateElapsedMs = STATS_UPDATE_INTERVAL_MS
while (isActive) {
- playerProvider?.invoke()?.let { player ->
- currentPosition.value = player.currentPosition
- duration.value = player.duration.coerceAtLeast(0L)
- }
- delay(250L)
- }
- }
- bufferedJob = scope.launch {
- while (isActive) {
- playerProvider?.invoke()?.let { player ->
- val bufferedDuration = (player.bufferedPosition - player.currentPosition).coerceAtLeast(0L)
- playerStats.value = playerStats.value.copy(bufferedDurationMs = bufferedDuration)
+ val shouldUpdateBuffered = bufferedUpdateElapsedMs >= BUFFERED_UPDATE_INTERVAL_MS
+ val shouldUpdateStats = statsUpdateElapsedMs >= STATS_UPDATE_INTERVAL_MS
+ val snapshot = readPlayerSnapshot(shouldUpdateBuffered)
+
+ if (snapshot != null) {
+ currentPosition.value = snapshot.currentPosition
+ duration.value = snapshot.duration
+
+ snapshot.bufferedDurationMs?.let { bufferedDuration ->
+ playerStats.value = playerStats.value.copy(bufferedDurationMs = bufferedDuration)
+ bufferedUpdateElapsedMs = 0L
+ }
+
+ if (shouldUpdateStats) {
+ val video = lastVideoFormat
+ val audio = lastAudioFormat
+ videoFormat.value = VideoFormat(
+ width = video?.width?.takeIf { it > 0 } ?: 0,
+ height = video?.height?.takeIf { it > 0 } ?: 0,
+ frameRate = lastFrameRate,
+ bitrate = video?.bitrate?.takeIf { it > 0 } ?: 0,
+ codecV = video?.sampleMimeType ?: video?.codecs,
+ codecA = audio?.sampleMimeType ?: audio?.codecs
+ )
+ playerStats.value = playerStats.value.copy(
+ videoCodec = video?.sampleMimeType ?: video?.codecs ?: playerStats.value.videoCodec,
+ audioCodec = audio?.sampleMimeType ?: audio?.codecs ?: playerStats.value.audioCodec,
+ videoBitrate = video?.bitrate?.takeIf { it > 0 } ?: playerStats.value.videoBitrate,
+ droppedFrames = droppedFrames,
+ width = video?.width?.takeIf { it > 0 } ?: playerStats.value.width,
+ height = video?.height?.takeIf { it > 0 } ?: playerStats.value.height,
+ bandwidthEstimate = lastBandwidthEstimate
+ )
+ statsUpdateElapsedMs = 0L
+ }
}
- delay(500L)
+ delay(POSITION_UPDATE_INTERVAL_MS)
+ bufferedUpdateElapsedMs += POSITION_UPDATE_INTERVAL_MS
+ statsUpdateElapsedMs += POSITION_UPDATE_INTERVAL_MS
}
}
- statsJob = scope.launch {
- while (isActive) {
- playerProvider?.invoke()?.let { player ->
- val video = lastVideoFormat
- val audio = lastAudioFormat
- videoFormat.value = VideoFormat(
- width = video?.width?.takeIf { it > 0 } ?: 0,
- height = video?.height?.takeIf { it > 0 } ?: 0,
- frameRate = lastFrameRate,
- bitrate = video?.bitrate?.takeIf { it > 0 } ?: 0,
- codecV = video?.sampleMimeType ?: video?.codecs,
- codecA = audio?.sampleMimeType ?: audio?.codecs
- )
- playerStats.value = playerStats.value.copy(
- videoCodec = video?.sampleMimeType ?: video?.codecs ?: playerStats.value.videoCodec,
- audioCodec = audio?.sampleMimeType ?: audio?.codecs ?: playerStats.value.audioCodec,
- videoBitrate = video?.bitrate?.takeIf { it > 0 } ?: playerStats.value.videoBitrate,
- droppedFrames = droppedFrames,
- width = video?.width?.takeIf { it > 0 } ?: playerStats.value.width,
- height = video?.height?.takeIf { it > 0 } ?: playerStats.value.height,
- bandwidthEstimate = lastBandwidthEstimate
- )
- }
- delay(1000L)
+ }
+
+ private suspend fun readPlayerSnapshot(includeBufferedDuration: Boolean): PlayerSnapshot? {
+ return withContext(Dispatchers.Main.immediate) {
+ playerProvider?.invoke()?.let { player ->
+ PlayerSnapshot(
+ currentPosition = player.currentPosition,
+ duration = player.duration.coerceAtLeast(0L),
+ bufferedDurationMs = if (includeBufferedDuration) {
+ (player.bufferedPosition - player.currentPosition).coerceAtLeast(0L)
+ } else {
+ null
+ }
+ )
}
}
}
fun stop() {
- positionJob?.cancel()
- bufferedJob?.cancel()
- statsJob?.cancel()
- positionJob = null
- bufferedJob = null
- statsJob = null
+ pollingJob?.cancel()
+ pollingJob = null
+ }
+
+ private companion object {
+ private const val POSITION_UPDATE_INTERVAL_MS = 250L
+ private const val BUFFERED_UPDATE_INTERVAL_MS = 500L
+ private const val STATS_UPDATE_INTERVAL_MS = 1000L
}
}
diff --git a/scripts/capture-runtime-validation.ps1 b/scripts/capture-runtime-validation.ps1
new file mode 100644
index 00000000..3e89c9d8
--- /dev/null
+++ b/scripts/capture-runtime-validation.ps1
@@ -0,0 +1,53 @@
+param(
+ [string]$Scenario = "manual",
+ [string]$PackageName = "com.streamvault.app",
+ [string]$OutputRoot = "artifacts/runtime-validation"
+)
+
+$ErrorActionPreference = "Stop"
+
+function Require-Command {
+ param([string]$Name)
+ if (-not (Get-Command $Name -ErrorAction SilentlyContinue)) {
+ throw "Required command '$Name' was not found."
+ }
+}
+
+Require-Command adb
+
+$adbState = (& adb get-state 2>$null)
+if ($LASTEXITCODE -ne 0 -or $adbState.Trim() -ne "device") {
+ throw "No connected Android device was found. Connect a device and ensure 'adb get-state' returns 'device'."
+}
+
+$timestamp = Get-Date -Format "yyyyMMdd-HHmmss"
+$safeScenario = ($Scenario -replace "[^A-Za-z0-9._-]", "_")
+$outputDir = Join-Path $OutputRoot "$timestamp-$safeScenario"
+New-Item -ItemType Directory -Path $outputDir -Force | Out-Null
+
+Write-Host "Capturing runtime diagnostics for scenario '$Scenario' into $outputDir"
+
+& adb shell dumpsys meminfo $PackageName | Out-File (Join-Path $outputDir "meminfo.txt") -Encoding utf8
+& adb shell dumpsys gfxinfo $PackageName framestats | Out-File (Join-Path $outputDir "gfxinfo-framestats.txt") -Encoding utf8
+& adb shell dumpsys activity processes | Out-File (Join-Path $outputDir "activity-processes.txt") -Encoding utf8
+& adb shell dumpsys thermalservice | Out-File (Join-Path $outputDir "thermalservice.txt") -Encoding utf8
+& adb shell top -n 1 -o PID,RES,CPU%,ARGS | Out-File (Join-Path $outputDir "top.txt") -Encoding utf8
+
+$runtimeLogPath = Join-Path $outputDir "runtime-memory.log"
+$runAsOutput = & adb shell run-as $PackageName cat files/diagnostics/runtime-memory.log 2>&1
+if ($LASTEXITCODE -eq 0) {
+ $runAsOutput | Out-File $runtimeLogPath -Encoding utf8
+} else {
+ $runAsOutput | Out-File (Join-Path $outputDir "run-as-error.txt") -Encoding utf8
+}
+
+& adb logcat -d LeakCanary:V RuntimeDiagnostics:I AndroidRuntime:E *:S | Out-File (Join-Path $outputDir "targeted-logcat.txt") -Encoding utf8
+
+@"
+scenario=$Scenario
+package=$PackageName
+capturedAt=$timestamp
+deviceState=$adbState
+"@ | Out-File (Join-Path $outputDir "capture-metadata.txt") -Encoding utf8
+
+Write-Host "Capture complete."