Skip to content

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

Add provider sync and Xtream indexing groundwork

David Nashashbadedf00fb0a
diff --git a/.codex/hooks.json b/.codex/hooks.json
deleted file mode 100644
index f905deab..00000000
--- a/.codex/hooks.json
+++ /dev/null
@@ -1,15 +0,0 @@
-{
- "hooks": {
- "PreToolUse": [
- {
- "matcher": "Bash",
- "hooks": [
- {
- "type": "command",
- "command": "graphify hook-check"
- }
- ]
- }
- ]
- }
-}
\ No newline at end of file
diff --git a/app/src/main/java/com/streamvault/app/StreamVaultApp.kt b/app/src/main/java/com/streamvault/app/StreamVaultApp.kt
index af93e88b..196d95db 100644
--- a/app/src/main/java/com/streamvault/app/StreamVaultApp.kt
+++ b/app/src/main/java/com/streamvault/app/StreamVaultApp.kt
@@ -27,6 +27,7 @@ import androidx.work.PeriodicWorkRequestBuilder
import androidx.work.WorkManager
import com.streamvault.data.manager.recording.RecordingReconcileWorker
import com.streamvault.data.sync.ProviderSyncWorker
+import com.streamvault.data.sync.XtreamIndexWorker
import com.streamvault.player.timeshift.TimeshiftDiskManager
import javax.inject.Inject
@@ -72,6 +73,9 @@ class StreamVaultApp : Application(), SingletonImageLoader.Factory {
)
ProviderSyncWorker.enqueuePeriodic(this)
+ ProviderSyncWorker.enqueueLaunchStaleCheck(this)
+ XtreamIndexWorker.enqueuePeriodic(this)
+ XtreamIndexWorker.enqueueLaunchStaleCheck(this)
RecordingReconcileWorker.enqueuePeriodic(this)
RecordingReconcileWorker.enqueueOneShot(this)
}
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 ee0543bc..3b4184ba 100644
--- a/app/src/main/java/com/streamvault/app/di/DatabaseModule.kt
+++ b/app/src/main/java/com/streamvault/app/di/DatabaseModule.kt
@@ -85,7 +85,8 @@ object DatabaseModule {
StreamVaultDatabase.MIGRATION_43_44,
StreamVaultDatabase.MIGRATION_44_45,
StreamVaultDatabase.MIGRATION_45_46,
- StreamVaultDatabase.MIGRATION_46_47
+ StreamVaultDatabase.MIGRATION_46_47,
+ StreamVaultDatabase.MIGRATION_47_48
)
// NOTE: fallbackToDestructiveMigration() intentionally removed.
// All future schema changes MUST add a corresponding Migration in StreamVaultDatabase.
@@ -105,6 +106,7 @@ object DatabaseModule {
@Provides fun providePlaybackHistoryDao(db: StreamVaultDatabase): PlaybackHistoryDao = db.playbackHistoryDao()
@Provides fun provideTmdbIdentityDao(db: StreamVaultDatabase): TmdbIdentityDao = db.tmdbIdentityDao()
@Provides fun provideSearchHistoryDao(db: StreamVaultDatabase): SearchHistoryDao = db.searchHistoryDao()
+ @Provides fun provideSearchDao(db: StreamVaultDatabase): SearchDao = db.searchDao()
@Provides fun provideSyncMetadataDao(db: StreamVaultDatabase): SyncMetadataDao = db.syncMetadataDao()
@Provides fun provideMovieCategoryHydrationDao(db: StreamVaultDatabase): MovieCategoryHydrationDao = db.movieCategoryHydrationDao()
@Provides fun provideSeriesCategoryHydrationDao(db: StreamVaultDatabase): SeriesCategoryHydrationDao = db.seriesCategoryHydrationDao()
@@ -120,4 +122,6 @@ object DatabaseModule {
@Provides fun provideProgramReminderDao(db: StreamVaultDatabase): ProgramReminderDao = db.programReminderDao()
@Provides fun provideRecordingStorageDao(db: StreamVaultDatabase): RecordingStorageDao = db.recordingStorageDao()
@Provides fun providePlaybackCompatibilityDao(db: StreamVaultDatabase): PlaybackCompatibilityDao = db.playbackCompatibilityDao()
+ @Provides fun provideXtreamContentIndexDao(db: StreamVaultDatabase): XtreamContentIndexDao = db.xtreamContentIndexDao()
+ @Provides fun provideXtreamIndexJobDao(db: StreamVaultDatabase): XtreamIndexJobDao = db.xtreamIndexJobDao()
}
diff --git a/app/src/main/java/com/streamvault/app/di/NetworkModule.kt b/app/src/main/java/com/streamvault/app/di/NetworkModule.kt
index 93069b84..5f95d7b8 100644
--- a/app/src/main/java/com/streamvault/app/di/NetworkModule.kt
+++ b/app/src/main/java/com/streamvault/app/di/NetworkModule.kt
@@ -3,9 +3,13 @@ package com.streamvault.app.di
import android.content.Context
import android.content.pm.ApplicationInfo
import android.util.Log
+import com.streamvault.app.BuildConfig
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.streamvault.data.remote.NetworkTimeoutConfig
+import com.streamvault.data.remote.http.DefaultUserAgentInterceptor
+import com.streamvault.data.remote.http.buildAppRequestProfile
+import com.streamvault.data.remote.http.buildAppUserAgent
import com.streamvault.data.remote.stalker.OkHttpStalkerApiService
import com.streamvault.data.remote.stalker.StalkerApiService
import com.streamvault.data.remote.xtream.XtreamApiService
@@ -36,6 +40,7 @@ object NetworkModule {
fun provideOkHttpClient(
@ApplicationContext context: Context
): OkHttpClient {
+ val appUserAgent = buildAppUserAgent(BuildConfig.VERSION_NAME)
val isDebuggable = (context.applicationInfo.flags and ApplicationInfo.FLAG_DEBUGGABLE) != 0
val loggingLevel = if (isDebuggable) {
HttpLoggingInterceptor.Level.BASIC
@@ -59,6 +64,7 @@ object NetworkModule {
.connectTimeout(NetworkTimeoutConfig.CONNECT_TIMEOUT_SECONDS, SECONDS)
.readTimeout(NetworkTimeoutConfig.READ_TIMEOUT_SECONDS, SECONDS)
.writeTimeout(NetworkTimeoutConfig.WRITE_TIMEOUT_SECONDS, SECONDS)
+ .addInterceptor(DefaultUserAgentInterceptor(appUserAgent))
.addInterceptor(httpLogger)
.followRedirects(true)
.followSslRedirects(true)
@@ -73,7 +79,11 @@ object NetworkModule {
@Provides
@Singleton
fun provideXtreamApiService(okHttpClient: OkHttpClient, xtreamJson: Json): XtreamApiService =
- OkHttpXtreamApiService(okHttpClient, xtreamJson)
+ OkHttpXtreamApiService(
+ client = okHttpClient,
+ json = xtreamJson,
+ defaultRequestProfile = buildAppRequestProfile(BuildConfig.VERSION_NAME, ownerTag = "app/xtream")
+ )
@Provides
@Singleton
diff --git a/app/src/main/java/com/streamvault/app/di/RepositoryModule.kt b/app/src/main/java/com/streamvault/app/di/RepositoryModule.kt
index 3ce81ee8..51252339 100644
--- a/app/src/main/java/com/streamvault/app/di/RepositoryModule.kt
+++ b/app/src/main/java/com/streamvault/app/di/RepositoryModule.kt
@@ -42,6 +42,9 @@ abstract class RepositoryModule {
@Binds @Singleton
abstract fun bindSeriesRepository(impl: SeriesRepositoryImpl): SeriesRepository
+ @Binds @Singleton
+ abstract fun bindSearchRepository(impl: SearchRepositoryImpl): SearchRepository
+
@Binds @Singleton
abstract fun bindEpgRepository(impl: EpgRepositoryImpl): EpgRepository
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/home/HomeSidebarComponents.kt b/app/src/main/java/com/streamvault/app/ui/screens/home/HomeSidebarComponents.kt
index 1fe3907b..e01696c2 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/home/HomeSidebarComponents.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/home/HomeSidebarComponents.kt
@@ -41,6 +41,7 @@ import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
+import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.tv.material3.Border
import androidx.tv.material3.ButtonDefaults
import androidx.tv.material3.ClickableSurfaceDefaults
@@ -123,6 +124,10 @@ internal fun LivePreviewPane(
errorMessage: String?,
modifier: Modifier = Modifier
) {
+ val renderSurfaceType by (playerEngine?.renderSurfaceType)?.collectAsStateWithLifecycle(
+ initialValue = PlayerRenderSurfaceType.SURFACE_VIEW
+ ) ?: remember { mutableStateOf(PlayerRenderSurfaceType.SURFACE_VIEW) }
+
Surface(
modifier = modifier,
shape = RoundedCornerShape(18.dp),
@@ -151,7 +156,7 @@ internal fun LivePreviewPane(
PlayerRenderView(
playerEngine = playerEngine,
resizeMode = PlayerSurfaceResizeMode.FIT,
- surfaceType = PlayerRenderSurfaceType.SURFACE_VIEW,
+ surfaceType = renderSurfaceType,
modifier = Modifier.fillMaxSize()
)
} else {
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 7b3eeced..2858ca7c 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
@@ -1012,6 +1012,8 @@ class HomeViewModel @Inject constructor(
is Result.Success -> {
if (!isActivePreviewSession(previewVersion, channel.id)) return@launch
engine.stop()
+ engine.setDecoderMode(preferencesRepository.playerDecoderMode.first())
+ engine.setSurfaceMode(preferencesRepository.playerSurfaceMode.first())
engine.prepare(result.data)
engine.setVolume(1f)
engine.play()
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 612b092e..9e6f46a7 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
@@ -198,14 +198,14 @@ fun MoviesScreen(
subtitle = stringResource(R.string.home_add_first_provider_subtitle)
)
}
- } else if (!uiState.hasActiveProvider || (uiState.moviesByCategory.isEmpty() && uiState.libraryCount == 0 && uiState.searchQuery.isBlank() && !uiState.isLoadingPreviewRows)) {
+ } else if (!uiState.hasActiveProvider || (uiState.selectedCategory == null && uiState.moviesByCategory.isEmpty() && uiState.libraryCount == 0 && uiState.searchQuery.isBlank() && !uiState.isLoadingPreviewRows)) {
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
AppMessageState(
title = stringResource(R.string.vod_sync_needed_title),
subtitle = stringResource(R.string.vod_sync_needed_subtitle)
)
}
- } else if (uiState.moviesByCategory.isEmpty() && !uiState.isLoadingPreviewRows) {
+ } else if (uiState.selectedCategory == null && uiState.searchQuery.isBlank() && uiState.moviesByCategory.isEmpty() && !uiState.isLoadingPreviewRows) {
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
AppMessageState(
title = stringResource(R.string.movies_no_found),
@@ -853,6 +853,20 @@ private fun MoviesVodContent(
}
}
}
+ } else if (filteredGridMovies.isEmpty()) {
+ item(span = { GridItemSpan(maxLineSpan) }) {
+ Box(
+ modifier = Modifier
+ .fillMaxWidth()
+ .height(loadingSectionHeight),
+ contentAlignment = Alignment.Center
+ ) {
+ AppMessageState(
+ title = stringResource(R.string.movies_no_found),
+ subtitle = stringResource(R.string.movies_no_found_subtitle)
+ )
+ }
+ }
} else {
gridItems(filteredGridMovies, key = { it.id }) { movie ->
val isLocked = isMovieLocked(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 26523ba8..0129d9e2 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
@@ -47,11 +47,13 @@ import com.streamvault.app.util.isPlaybackComplete
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
import kotlinx.coroutines.ExperimentalCoroutinesApi
+import kotlinx.coroutines.FlowPreview
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.combine
+import kotlinx.coroutines.flow.debounce
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.distinctUntilChangedBy
import kotlinx.coroutines.flow.filterNotNull
@@ -70,7 +72,7 @@ enum class MovieLibraryLens {
}
@HiltViewModel
-@OptIn(ExperimentalCoroutinesApi::class)
+@OptIn(ExperimentalCoroutinesApi::class, FlowPreview::class)
class MoviesViewModel @Inject constructor(
private val providerRepository: ProviderRepository,
private val movieRepository: MovieRepository,
@@ -92,6 +94,12 @@ class MoviesViewModel @Inject constructor(
val uiState: StateFlow<MoviesUiState> = _uiState.asStateFlow()
private val _searchQuery = MutableStateFlow("")
+ private val searchQueryForBrowse = _searchQuery
+ .map { it.trim() }
+ .distinctUntilChanged()
+ .debounce { query ->
+ if (query.isBlank() || query.length < MIN_SEARCH_QUERY_LENGTH) 0L else 300L
+ }
private val _selectedCategoryLoadLimit = MutableStateFlow(VodBrowseDefaults.SELECTED_CATEGORY_PAGE_SIZE)
private val _selectedLibraryFilterType = MutableStateFlow(LibraryFilterType.ALL)
private val _selectedLibrarySortBy = MutableStateFlow(LibrarySortBy.LIBRARY)
@@ -172,7 +180,7 @@ class MoviesViewModel @Inject constructor(
hiddenCategoryIds = hiddenCategoryIds,
categorySortMode = sortMode
)
- }.combine(_searchQuery) { dependencies, query ->
+ }.combine(searchQueryForBrowse) { dependencies, query ->
MovieCatalogParams(
providerId = provider.id,
allFavorites = dependencies.allFavorites,
@@ -182,7 +190,7 @@ class MoviesViewModel @Inject constructor(
libraryCount = dependencies.libraryCount,
hiddenCategoryIds = dependencies.hiddenCategoryIds,
categorySortMode = dependencies.categorySortMode,
- query = query.trim()
+ query = query
)
}
.distinctUntilChangedBy { params ->
@@ -322,14 +330,14 @@ class MoviesViewModel @Inject constructor(
combine(
_uiState.map { it.selectedCategory }.distinctUntilChanged(),
_selectedCategoryLoadLimit,
- _searchQuery,
+ searchQueryForBrowse,
_selectedLibraryFilterType,
_selectedLibrarySortBy
) { selectedCategory, loadLimit, query, filterType, sortBy ->
SelectedMovieBrowseSelection(
selectedCategory = selectedCategory,
loadLimit = loadLimit,
- query = query.trim(),
+ query = query,
filterType = filterType,
sortBy = sortBy
)
@@ -997,9 +1005,7 @@ class MoviesViewModel @Inject constructor(
if (request.selectedCategory.isNullOrBlank()) {
return SelectedMovieCategorySnapshot()
}
- if (request.query.isNotBlank() && request.query.length < MIN_SEARCH_QUERY_LENGTH) {
- return SelectedMovieCategorySnapshot()
- }
+ val effectiveQuery = request.query.takeIf { it.trim().length >= MIN_SEARCH_QUERY_LENGTH }.orEmpty()
val globalFavoriteIds = request.allFavorites
.asSequence()
@@ -1015,7 +1021,7 @@ class MoviesViewModel @Inject constructor(
providerId = request.providerId,
sortBy = request.sortBy,
filterBy = LibraryFilterBy(type = request.filterType),
- searchQuery = request.query,
+ searchQuery = effectiveQuery,
limit = request.loadLimit,
offset = 0
)
@@ -1034,7 +1040,7 @@ 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) {
+ val fetchIds = if (effectiveQuery.isBlank() && request.filterType == LibraryFilterType.ALL && request.sortBy == LibrarySortBy.LIBRARY) {
ids.take(request.loadLimit + FAVORITE_ID_FETCH_BUFFER)
} else {
ids
@@ -1050,7 +1056,7 @@ class MoviesViewModel @Inject constructor(
items,
request.filterType,
request.sortBy,
- request.query
+ effectiveQuery
)
Triple(
filteredItems.take(request.loadLimit),
@@ -1067,7 +1073,7 @@ 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) {
+ val fetchIds = if (effectiveQuery.isBlank() && request.filterType == LibraryFilterType.ALL && request.sortBy == LibrarySortBy.LIBRARY) {
ids.take(request.loadLimit + FAVORITE_ID_FETCH_BUFFER)
} else {
ids
@@ -1083,7 +1089,7 @@ class MoviesViewModel @Inject constructor(
items,
request.filterType,
request.sortBy,
- request.query
+ effectiveQuery
)
Triple(
filteredItems.take(request.loadLimit),
@@ -1100,7 +1106,7 @@ class MoviesViewModel @Inject constructor(
categoryId = providerCategory.id,
sortBy = request.sortBy,
filterBy = LibraryFilterBy(type = request.filterType),
- searchQuery = request.query,
+ searchQuery = effectiveQuery,
limit = request.loadLimit,
offset = 0
)
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/multiview/MultiViewScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/multiview/MultiViewScreen.kt
index 22a22bf8..671b99cc 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/multiview/MultiViewScreen.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/multiview/MultiViewScreen.kt
@@ -102,8 +102,8 @@ fun MultiViewScreen(
var showReplacementPicker by remember { mutableStateOf(false) }
var showControls by rememberSaveable { mutableStateOf(false) }
val occupiedSlots = remember(uiState.slots) { uiState.slots.filterNot { it.isEmpty } }
- val useCenteredTwoSlotLayout = uiState.centerTwoSlotLayout && occupiedSlots.size == 2
- val visibleSlots = if (useCenteredTwoSlotLayout) occupiedSlots else uiState.slots
+ val useCenteredCompactLayout = uiState.centerTwoSlotLayout && occupiedSlots.size in 1..2
+ val visibleSlots = if (useCenteredCompactLayout) occupiedSlots else uiState.slots
val firstVisibleSlotIndex = visibleSlots.firstOrNull()?.index ?: 0
BackHandler(enabled = showReplacementPicker) {
@@ -138,8 +138,8 @@ fun MultiViewScreen(
}
}
- LaunchedEffect(useCenteredTwoSlotLayout, firstVisibleSlotIndex, uiState.focusedSlotIndex) {
- if (useCenteredTwoSlotLayout && visibleSlots.none { it.index == uiState.focusedSlotIndex }) {
+ LaunchedEffect(useCenteredCompactLayout, firstVisibleSlotIndex, uiState.focusedSlotIndex) {
+ if (useCenteredCompactLayout && visibleSlots.none { it.index == uiState.focusedSlotIndex }) {
viewModel.setFocus(firstVisibleSlotIndex)
}
}
@@ -223,8 +223,8 @@ fun MultiViewScreen(
}
Column(modifier = Modifier.fillMaxSize()) {
- if (useCenteredTwoSlotLayout) {
- CenteredTwoSlotLayout(
+ if (useCenteredCompactLayout) {
+ CenteredCompactLayout(
slots = visibleSlots,
focusedSlotIndex = uiState.focusedSlotIndex,
showSelectionBorder = uiState.showSelectionBorder,
@@ -362,7 +362,7 @@ private fun StandardMultiViewGrid(
}
@Composable
-private fun CenteredTwoSlotLayout(
+private fun CenteredCompactLayout(
slots: List<MultiViewSlot>,
focusedSlotIndex: Int,
showSelectionBorder: Boolean,
@@ -376,28 +376,52 @@ private fun CenteredTwoSlotLayout(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.Center
) {
- Row(
- modifier = Modifier
- .fillMaxWidth()
- .padding(horizontal = 72.dp),
- horizontalArrangement = Arrangement.spacedBy(12.dp)
- ) {
- slots.forEachIndexed { index, slot ->
+ if (slots.size == 1) {
+ Box(
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(horizontal = 72.dp),
+ contentAlignment = Alignment.Center
+ ) {
GridPlayerCell(
- slot = slot,
- slotIndex = slot.index,
+ slot = slots.first(),
+ slotIndex = slots.first().index,
focusedSlotIndex = focusedSlotIndex,
showSelectionBorder = showSelectionBorder,
showControls = showControls,
onClick = onSlotClick,
onFocused = onSlotFocused,
- firstSlotFocusRequester = if (index == 0) firstSlotFocusRequester else null,
+ firstSlotFocusRequester = firstSlotFocusRequester,
firstControlFocusRequester = firstControlFocusRequester,
modifier = Modifier
- .weight(1f)
+ .fillMaxWidth(0.5f)
.aspectRatio(16f / 9f)
)
}
+ } else {
+ Row(
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(horizontal = 72.dp),
+ horizontalArrangement = Arrangement.spacedBy(12.dp)
+ ) {
+ slots.forEachIndexed { index, slot ->
+ GridPlayerCell(
+ slot = slot,
+ slotIndex = slot.index,
+ focusedSlotIndex = focusedSlotIndex,
+ showSelectionBorder = showSelectionBorder,
+ showControls = showControls,
+ onClick = onSlotClick,
+ onFocused = onSlotFocused,
+ firstSlotFocusRequester = if (index == 0) firstSlotFocusRequester else null,
+ firstControlFocusRequester = firstControlFocusRequester,
+ modifier = Modifier
+ .weight(1f)
+ .aspectRatio(16f / 9f)
+ )
+ }
+ }
}
}
}
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/multiview/MultiViewViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/multiview/MultiViewViewModel.kt
index 19e1b11b..f3f9d2ec 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/multiview/MultiViewViewModel.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/multiview/MultiViewViewModel.kt
@@ -80,7 +80,10 @@ class MultiViewViewModel @Inject constructor(
init {
viewModelScope.launch {
- preferencesRepository.playerAudioVideoOffsetMs.collect {
+ combine(
+ preferencesRepository.playerAudioVideoSyncEnabled,
+ preferencesRepository.playerAudioVideoOffsetMs
+ ) { _, _ -> Unit }.collect {
applyAudioVideoOffsetsToActiveEngines()
}
}
@@ -267,7 +270,11 @@ class MultiViewViewModel @Inject constructor(
val channel = slot.channel
?: throw IllegalStateException("Missing channel for slot ${slot.index}")
- localEngine.setAudioVideoOffsetMs(effectiveAudioVideoOffsetForChannel(channel.id))
+ val avSyncEnabled = preferencesRepository.playerAudioVideoSyncEnabled.first()
+ localEngine.setAudioVideoSyncEnabled(avSyncEnabled)
+ localEngine.setAudioVideoOffsetMs(
+ if (avSyncEnabled) effectiveAudioVideoOffsetForChannel(channel.id) else 0
+ )
val streamInfo = when (val result = channelRepository.getStreamInfo(channel)) {
is Result.Success -> result.data
is Result.Error -> throw IllegalStateException(result.message)
@@ -643,6 +650,7 @@ class MultiViewViewModel @Inject constructor(
}
private suspend fun effectiveAudioVideoOffsetForChannel(channelId: Long): Int {
+ if (!preferencesRepository.playerAudioVideoSyncEnabled.first()) return 0
val globalOffset = preferencesRepository.playerAudioVideoOffsetMs.first()
if (channelId <= 0L) return globalOffset
return preferencesRepository.observeAudioVideoOffsetForChannel(channelId).first() ?: globalOffset
@@ -653,7 +661,9 @@ class MultiViewViewModel @Inject constructor(
playerEngines.forEach { (index, engine) ->
val channelId = slots.getOrNull(index)?.channel?.id ?: return@forEach
viewModelScope.launch {
- engine.setAudioVideoOffsetMs(effectiveAudioVideoOffsetForChannel(channelId))
+ val enabled = preferencesRepository.playerAudioVideoSyncEnabled.first()
+ engine.setAudioVideoSyncEnabled(enabled)
+ engine.setAudioVideoOffsetMs(if (enabled) effectiveAudioVideoOffsetForChannel(channelId) else 0)
}
}
}
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 6edf0f02..93ad2861 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
@@ -207,6 +207,7 @@ fun PlayerScreen(
val isMuted by viewModel.isMuted.collectAsStateWithLifecycle()
val mediaTitle by viewModel.mediaTitle.collectAsStateWithLifecycle()
val playbackSpeed by viewModel.playbackSpeed.collectAsStateWithLifecycle()
+ val audioVideoSyncEnabled by viewModel.audioVideoSyncEnabled.collectAsStateWithLifecycle()
val audioVideoOffsetState by viewModel.audioVideoOffsetUiState.collectAsStateWithLifecycle()
val castConnectionState by viewModel.castConnectionState.collectAsStateWithLifecycle()
val seekPreview by viewModel.seekPreview.collectAsStateWithLifecycle()
@@ -265,6 +266,13 @@ fun PlayerScreen(
}
}
+ LaunchedEffect(audioVideoSyncEnabled) {
+ if (!audioVideoSyncEnabled && showAudioVideoOffsetDialog) {
+ showAudioVideoOffsetDialog = false
+ viewModel.dismissAudioVideoOffsetPreview()
+ }
+ }
+
LaunchedEffect(isInPictureInPictureMode) {
if (isInPictureInPictureMode) {
viewModel.closeOverlays()
@@ -1025,6 +1033,7 @@ fun PlayerScreen(
onOpenStopPlaybackTimer = { showStopPlaybackTimerDialog = true },
onOpenIdleStandbyTimer = { showIdleStandbyTimerDialog = true },
onOpenAudioVideoSync = { showAudioVideoOffsetDialog = true },
+ audioVideoSyncEnabled = audioVideoSyncEnabled,
showEpisodesAction = canOpenEpisodePicker,
onOpenEpisodes = { showEpisodePicker = true },
onOpenSplitScreen = { showSplitDialog = true },
@@ -1154,7 +1163,9 @@ fun PlayerScreen(
}
)
PlayerAudioVideoOffsetDialog(
- visible = showAudioVideoOffsetDialog && castConnectionState != CastConnectionState.CONNECTED,
+ visible = showAudioVideoOffsetDialog &&
+ audioVideoSyncEnabled &&
+ castConnectionState != CastConnectionState.CONNECTED,
state = audioVideoOffsetState,
canSaveChannel = currentChannel != null,
onDismiss = {
@@ -1334,6 +1345,7 @@ fun PlayerScreen(
onOpenVideoTracks = { showTrackSelection = TrackType.VIDEO },
onOpenVariants = { showVariantSelection = true },
onOpenAudioVideoSync = { showAudioVideoOffsetDialog = true },
+ audioVideoSyncEnabled = audioVideoSyncEnabled,
onEnterPictureInPicture = enterPictureInPicture,
isCastConnected = castConnectionState == CastConnectionState.CONNECTED,
onCast = { viewModel.castCurrentMedia { mainActivity?.openCastRouteChooser() } },
@@ -1409,6 +1421,7 @@ private fun PlayerControlsOverlayHost(
onOpenStopPlaybackTimer: () -> Unit,
onOpenIdleStandbyTimer: () -> Unit,
onOpenAudioVideoSync: () -> Unit,
+ audioVideoSyncEnabled: Boolean,
showEpisodesAction: Boolean,
onOpenEpisodes: () -> Unit,
onOpenSplitScreen: () -> Unit,
@@ -1470,6 +1483,7 @@ private fun PlayerControlsOverlayHost(
onOpenStopPlaybackTimer = onOpenStopPlaybackTimer,
onOpenIdleStandbyTimer = onOpenIdleStandbyTimer,
onOpenAudioVideoSync = onOpenAudioVideoSync,
+ audioVideoSyncEnabled = audioVideoSyncEnabled,
showEpisodesAction = showEpisodesAction,
onOpenEpisodes = onOpenEpisodes,
onOpenSplitScreen = onOpenSplitScreen,
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 8d83ad32..d476358b 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
@@ -558,8 +558,9 @@ class PlayerViewModel @Inject constructor(
preferencesRepository.playerAudioVideoOffsetMs,
channelOffsetFlow,
audioVideoOffsetPreviewMs,
+ activePlayerEngineFlow.flatMapLatest { it.audioVideoSyncEnabled },
activePlayerEngineFlow
- ) { globalOffset, channelOffset, previewOffset, engine ->
+ ) { globalOffset, channelOffset, previewOffset, enabled, engine ->
val effectiveOffset = (previewOffset ?: channelOffset ?: globalOffset)
.coerceIn(AUDIO_VIDEO_OFFSET_MIN_MS, AUDIO_VIDEO_OFFSET_MAX_MS)
AudioVideoOffsetSnapshot(
@@ -567,7 +568,8 @@ class PlayerViewModel @Inject constructor(
channelOverrideMs = channelOffset,
previewOffsetMs = previewOffset,
effectiveOffsetMs = effectiveOffset,
- engine = engine
+ engine = engine,
+ enabled = enabled
)
}.collect { snapshot ->
_audioVideoOffsetUiState.value = PlayerAudioVideoOffsetUiState(
@@ -848,6 +850,7 @@ class PlayerViewModel @Inject constructor(
val isMuted: StateFlow<Boolean> = activeEngineState(false) { it.isMuted }
val mediaTitle: StateFlow<String?> = activeEngineState<String?>(null) { it.mediaTitle }
val playbackSpeed: StateFlow<Float> = activeEngineState(1f) { it.playbackSpeed }
+ val audioVideoSyncEnabled: StateFlow<Boolean> = activeEngineState(false) { it.audioVideoSyncEnabled }
val preventStandbyDuringPlayback: StateFlow<Boolean> by lazy(LazyThreadSafetyMode.NONE) {
preferencesRepository.preventStandbyDuringPlayback
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModelModels.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModelModels.kt
index 4080b64f..e5c2c1e3 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModelModels.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModelModels.kt
@@ -51,6 +51,8 @@ data class PlayerDiagnosticsUiState(
val streamClassLabel: String = "Primary",
val playbackStateLabel: String = "Idle",
val audioVideoOffsetMs: Int = 0,
+ val audioVideoSyncEnabled: Boolean = false,
+ val audioVideoSyncSinkActive: Boolean = false,
val alternativeStreamCount: Int = 0,
val channelErrorCount: Int = 0,
val archiveSupportLabel: String = "",
@@ -211,7 +213,8 @@ internal data class AudioVideoOffsetSnapshot(
val channelOverrideMs: Int?,
val previewOffsetMs: Int?,
val effectiveOffsetMs: Int,
- val engine: com.streamvault.player.PlayerEngine
+ val engine: com.streamvault.player.PlayerEngine,
+ val enabled: Boolean
)
internal data class PlayerUiTimeouts(
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerAuxiliaryOverlays.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerAuxiliaryOverlays.kt
index 981d7d80..60959412 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerAuxiliaryOverlays.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerAuxiliaryOverlays.kt
@@ -754,6 +754,12 @@ fun DiagnosticsOverlay(
}
PlayerOverlaySectionLabel(stringResource(R.string.player_diagnostics_section_audio))
PlayerMetaRow(stringResource(R.string.player_diagnostics_audio_codec), stats.audioCodec)
+ val avSyncPathLabel = when {
+ !diagnostics.audioVideoSyncEnabled -> stringResource(R.string.player_diagnostics_av_sync_stock)
+ diagnostics.audioVideoSyncSinkActive -> stringResource(R.string.player_diagnostics_av_sync_custom)
+ else -> stringResource(R.string.player_diagnostics_av_sync_waiting)
+ }
+ PlayerMetaRow(stringResource(R.string.player_diagnostics_av_sync), avSyncPathLabel)
PlayerMetaRow(stringResource(R.string.player_diagnostics_av_offset), formatOffsetLabel(diagnostics.audioVideoOffsetMs))
PlayerOverlaySectionLabel(stringResource(R.string.player_diagnostics_section_recovery))
diagnostics.lastFailureReason?.let { reason ->
@@ -939,4 +945,4 @@ fun CategoryListOverlay(
}
}
}
-}
\ No newline at end of file
+}
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerChannelInfoOverlay.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerChannelInfoOverlay.kt
index 7c348da9..9755718f 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerChannelInfoOverlay.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerChannelInfoOverlay.kt
@@ -102,6 +102,7 @@ fun ChannelInfoOverlay(
onOpenVideoTracks: () -> Unit = {},
onOpenVariants: () -> Unit = {},
onOpenAudioVideoSync: () -> Unit = {},
+ audioVideoSyncEnabled: Boolean = false,
onEnterPictureInPicture: () -> Unit = {},
isCastConnected: Boolean = false,
onCast: () -> Unit = {},
@@ -444,7 +445,7 @@ fun ChannelInfoOverlay(
)
}
}
- if (!isCastConnected) {
+ if (audioVideoSyncEnabled && !isCastConnected) {
item {
QuickActionButton(
icon = "A/V",
@@ -1011,4 +1012,4 @@ private fun CompactMenuActionButton(
modifier = Modifier.padding(horizontal = 14.dp, vertical = 10.dp)
)
}
-}
\ No newline at end of file
+}
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 1e02cd96..950ce5c0 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
@@ -135,6 +135,7 @@ fun PlayerControlsOverlay(
onOpenStopPlaybackTimer: () -> Unit = {},
onOpenIdleStandbyTimer: () -> Unit = {},
onOpenAudioVideoSync: () -> Unit = {},
+ audioVideoSyncEnabled: Boolean = false,
showEpisodesAction: Boolean = false,
onOpenEpisodes: () -> Unit = {},
onOpenSplitScreen: () -> Unit,
@@ -221,6 +222,7 @@ fun PlayerControlsOverlay(
onOpenStopPlaybackTimer = onOpenStopPlaybackTimer,
onOpenIdleStandbyTimer = onOpenIdleStandbyTimer,
onOpenAudioVideoSync = onOpenAudioVideoSync,
+ audioVideoSyncEnabled = audioVideoSyncEnabled,
showEpisodesAction = showEpisodesAction,
onOpenEpisodes = onOpenEpisodes,
onOpenSplitScreen = onOpenSplitScreen,
@@ -549,6 +551,7 @@ private fun PlayerBottomBar(
onOpenStopPlaybackTimer: () -> Unit,
onOpenIdleStandbyTimer: () -> Unit,
onOpenAudioVideoSync: () -> Unit,
+ audioVideoSyncEnabled: Boolean,
showEpisodesAction: Boolean,
onOpenEpisodes: () -> Unit,
onOpenSplitScreen: () -> Unit,
@@ -638,6 +641,7 @@ private fun PlayerBottomBar(
onOpenStopPlaybackTimer = onOpenStopPlaybackTimer,
onOpenIdleStandbyTimer = onOpenIdleStandbyTimer,
onOpenAudioVideoSync = onOpenAudioVideoSync,
+ audioVideoSyncEnabled = audioVideoSyncEnabled,
onOpenSplitScreen = onOpenSplitScreen,
onEnterPictureInPicture = onEnterPictureInPicture,
onToggleMute = onToggleMute,
@@ -679,6 +683,7 @@ private fun PlayerBottomBar(
onOpenStopPlaybackTimer = onOpenStopPlaybackTimer,
onOpenIdleStandbyTimer = onOpenIdleStandbyTimer,
onOpenAudioVideoSync = onOpenAudioVideoSync,
+ audioVideoSyncEnabled = audioVideoSyncEnabled,
showEpisodesAction = showEpisodesAction,
onOpenEpisodes = onOpenEpisodes,
onEnterPictureInPicture = onEnterPictureInPicture,
@@ -728,6 +733,7 @@ private fun PlayerLiveInfo(
onOpenStopPlaybackTimer: () -> Unit,
onOpenIdleStandbyTimer: () -> Unit,
onOpenAudioVideoSync: () -> Unit,
+ audioVideoSyncEnabled: Boolean,
onOpenSplitScreen: () -> Unit,
onEnterPictureInPicture: () -> Unit,
onToggleMute: () -> Unit,
@@ -804,7 +810,7 @@ private fun PlayerLiveInfo(
if (videoQualityCount > 0) {
add(PlayerActionSpec(stringResource(R.string.player_video_quality), onOpenVideoTracks))
}
- if (!isCastConnected) {
+ if (audioVideoSyncEnabled && !isCastConnected) {
add(PlayerActionSpec(stringResource(R.string.player_av_sync_short), onOpenAudioVideoSync))
}
add(PlayerActionSpec(stringResource(R.string.multiview_nav), onOpenSplitScreen))
@@ -955,6 +961,7 @@ private fun PlayerVodInfo(
isMuted: Boolean,
playbackSpeed: Float,
sleepTimerUiState: SleepTimerUiState,
+ audioVideoSyncEnabled: Boolean,
playButtonFocusRequester: FocusRequester,
quickActionsFocusRequester: FocusRequester,
onSeekToPosition: (Long) -> Unit,
@@ -1039,7 +1046,7 @@ private fun PlayerVodInfo(
onOpenPlaybackSpeed
)
)
- if (!isCastConnected) {
+ if (audioVideoSyncEnabled && !isCastConnected) {
add(PlayerActionSpec(stringResource(R.string.player_av_sync_short), onOpenAudioVideoSync))
}
add(PlayerActionSpec(
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 9d899d7b..d2014235 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
@@ -353,7 +353,6 @@ fun ProviderSetupScreen(
onLoginXtream = { viewModel.loginXtream(serverUrl, username, password, name) },
onLoginStalker = { viewModel.loginStalker(serverUrl, stalkerMacAddress, name, stalkerDeviceProfile, stalkerDeviceTimezone, stalkerDeviceLocale) },
onAddM3u = { viewModel.addM3u(m3uUrl, name) },
- onToggleFastSync = { viewModel.updateXtreamFastSyncEnabled(!uiState.xtreamFastSyncEnabled) },
onToggleM3uVodClassification = { viewModel.updateM3uVodClassificationEnabled(!uiState.m3uVodClassificationEnabled) },
onSelectEpgSyncMode = viewModel::updateEpgSyncMode,
showImportBackupButton = !uiState.isEditing,
@@ -390,7 +389,6 @@ fun ProviderSetupScreen(
onLoginXtream = { viewModel.loginXtream(serverUrl, username, password, name) },
onLoginStalker = { viewModel.loginStalker(serverUrl, stalkerMacAddress, name, stalkerDeviceProfile, stalkerDeviceTimezone, stalkerDeviceLocale) },
onAddM3u = { viewModel.addM3u(m3uUrl, name) },
- onToggleFastSync = { viewModel.updateXtreamFastSyncEnabled(!uiState.xtreamFastSyncEnabled) },
onToggleM3uVodClassification = { viewModel.updateM3uVodClassificationEnabled(!uiState.m3uVodClassificationEnabled) },
onSelectEpgSyncMode = viewModel::updateEpgSyncMode,
showImportBackupButton = !uiState.isEditing,
@@ -470,7 +468,6 @@ private fun ProviderFormContent(
onLoginXtream: () -> Unit,
onLoginStalker: () -> Unit,
onAddM3u: () -> Unit,
- onToggleFastSync: () -> Unit,
onToggleM3uVodClassification: () -> Unit,
onSelectEpgSyncMode: (ProviderEpgSyncMode) -> Unit,
showImportBackupButton: Boolean,
@@ -540,7 +537,6 @@ private fun ProviderFormContent(
AdvancedProviderOptionsSection(
sourceType = sourceType,
uiState = uiState,
- onToggleFastSync = onToggleFastSync,
onToggleM3uVodClassification = onToggleM3uVodClassification,
onSelectEpgSyncMode = onSelectEpgSyncMode,
stalkerDeviceProfile = stalkerDeviceProfile,
@@ -586,7 +582,6 @@ private fun ProviderFormContent(
AdvancedProviderOptionsSection(
sourceType = sourceType,
uiState = uiState,
- onToggleFastSync = onToggleFastSync,
onToggleM3uVodClassification = onToggleM3uVodClassification,
onSelectEpgSyncMode = onSelectEpgSyncMode,
stalkerDeviceProfile = stalkerDeviceProfile,
@@ -617,7 +612,6 @@ private fun ProviderFormContent(
AdvancedProviderOptionsSection(
sourceType = sourceType,
uiState = uiState,
- onToggleFastSync = onToggleFastSync,
onToggleM3uVodClassification = onToggleM3uVodClassification,
onSelectEpgSyncMode = onSelectEpgSyncMode,
stalkerDeviceProfile = stalkerDeviceProfile,
@@ -653,7 +647,6 @@ private fun ProviderFormContent(
AdvancedProviderOptionsSection(
sourceType = sourceType,
uiState = uiState,
- onToggleFastSync = onToggleFastSync,
onToggleM3uVodClassification = onToggleM3uVodClassification,
onSelectEpgSyncMode = onSelectEpgSyncMode,
stalkerDeviceProfile = stalkerDeviceProfile,
@@ -690,7 +683,6 @@ private fun ProviderFormContent(
private fun AdvancedProviderOptionsSection(
sourceType: SourceType,
uiState: ProviderSetupState,
- onToggleFastSync: () -> Unit,
onToggleM3uVodClassification: () -> Unit,
onSelectEpgSyncMode: (ProviderEpgSyncMode) -> Unit,
stalkerDeviceProfile: String,
@@ -708,9 +700,8 @@ private fun AdvancedProviderOptionsSection(
SourceType.M3U_FILE -> ProviderEpgSyncMode.UPFRONT
}
- LaunchedEffect(uiState.isEditing, uiState.epgSyncMode, uiState.xtreamFastSyncEnabled, sourceType) {
+ LaunchedEffect(uiState.isEditing, uiState.epgSyncMode, sourceType) {
val hasNonDefaultSelection = ((sourceType == SourceType.XTREAM || sourceType == SourceType.STALKER) && uiState.epgSyncMode != defaultEpgSyncMode) ||
- (sourceType == SourceType.XTREAM && !uiState.xtreamFastSyncEnabled) ||
((sourceType == SourceType.M3U_URL || sourceType == SourceType.M3U_FILE) && !uiState.m3uVodClassificationEnabled) ||
(sourceType == SourceType.STALKER && (stalkerDeviceProfile.isNotBlank() || stalkerDeviceTimezone.isNotBlank() || stalkerDeviceLocale.isNotBlank()))
if (uiState.isEditing && hasNonDefaultSelection) {
@@ -774,53 +765,6 @@ private fun AdvancedProviderOptionsSection(
AnimatedVisibility(visible = showAdvancedOptions) {
Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
- if (sourceType == SourceType.XTREAM) {
- Surface(
- onClick = onToggleFastSync,
- modifier = Modifier
- .fillMaxWidth()
- .mouseClickable(onClick = onToggleFastSync),
- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(12.dp)),
- colors = ClickableSurfaceDefaults.colors(
- containerColor = if (uiState.xtreamFastSyncEnabled) Primary.copy(alpha = 0.1f) else Surface,
- focusedContainerColor = Primary.copy(alpha = 0.22f)
- ),
- border = ClickableSurfaceDefaults.border(
- border = Border(
- BorderStroke(
- 1.dp,
- if (uiState.xtreamFastSyncEnabled) Primary.copy(alpha = 0.4f) else SurfaceHighlight
- )
- ),
- focusedBorder = Border(BorderStroke(3.dp, PrimaryLight))
- ),
- scale = ClickableSurfaceDefaults.scale(focusedScale = 1f)
- ) {
- Row(
- modifier = Modifier.padding(horizontal = 16.dp, vertical = 12.dp),
- horizontalArrangement = Arrangement.spacedBy(12.dp),
- verticalAlignment = Alignment.CenterVertically
- ) {
- Column(modifier = Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(4.dp)) {
- Text(
- text = androidx.compose.ui.res.stringResource(R.string.setup_xtream_fast_sync_label),
- style = MaterialTheme.typography.titleSmall,
- color = TextPrimary
- )
- Text(
- text = androidx.compose.ui.res.stringResource(R.string.setup_xtream_fast_sync_helper),
- style = MaterialTheme.typography.bodySmall,
- color = OnSurfaceDim
- )
- }
- Switch(
- checked = uiState.xtreamFastSyncEnabled,
- onCheckedChange = { onToggleFastSync() }
- )
- }
- }
- }
-
if (sourceType == SourceType.M3U_URL || sourceType == SourceType.M3U_FILE) {
Surface(
onClick = onToggleM3uVodClassification,
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 abe3313d..fd96453b 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
@@ -100,7 +100,6 @@ class ProviderSetupViewModel @Inject constructor(
stalkerDeviceLocale = provider.stalkerDeviceLocale,
epgSyncMode = provider.epgSyncMode,
hasCustomizedEpgSyncMode = true,
- xtreamFastSyncEnabled = provider.xtreamFastSyncEnabled,
m3uVodClassificationEnabled = provider.m3uVodClassificationEnabled,
selectedTab = when (provider.type) {
ProviderType.XTREAM_CODES -> 0
@@ -118,10 +117,6 @@ class ProviderSetupViewModel @Inject constructor(
_uiState.update { it.copy(m3uTab = tab) }
}
- fun updateXtreamFastSyncEnabled(enabled: Boolean) {
- _uiState.update { it.copy(xtreamFastSyncEnabled = enabled) }
- }
-
fun updateM3uVodClassificationEnabled(enabled: Boolean) {
_uiState.update { it.copy(m3uVodClassificationEnabled = enabled) }
}
@@ -226,7 +221,7 @@ class ProviderSetupViewModel @Inject constructor(
username = username,
password = password,
name = name,
- xtreamFastSyncEnabled = _uiState.value.xtreamFastSyncEnabled,
+ xtreamFastSyncEnabled = false,
epgSyncMode = _uiState.value.epgSyncMode,
existingProviderId = existingId
),
@@ -658,7 +653,6 @@ data class ProviderSetupState(
val backupImportPlan: BackupImportPlan = BackupImportPlan(),
val epgSyncMode: ProviderEpgSyncMode = ProviderEpgSyncMode.BACKGROUND,
val hasCustomizedEpgSyncMode: Boolean = false,
- val xtreamFastSyncEnabled: Boolean = true,
val m3uVodClassificationEnabled: Boolean = false
)
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 f0228735..2d32ae5c 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
@@ -154,7 +154,7 @@ class SearchViewModel @Inject constructor(
unlockedCategoryIds
) { provider, query, tab, level, unlockedIds ->
SearchFilterParams(provider, query, tab, level, unlockedIds)
- }.flatMapLatest { params ->
+ }.distinctUntilChanged().flatMapLatest { params ->
val provider = params.provider
val query = params.query
val tab = params.tab
@@ -197,6 +197,17 @@ class SearchViewModel @Inject constructor(
queryLength = trimmedQueryLength,
unlockedCategoryIds = unlockedIds
)
+ }.onStart {
+ emit(
+ SearchUiState(
+ isLoading = true,
+ hasSearched = true,
+ parentalControlLevel = level,
+ hasActiveProvider = true,
+ queryLength = trimmedQueryLength,
+ unlockedCategoryIds = unlockedIds
+ )
+ )
}
}
}.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), SearchUiState())
@@ -567,6 +578,15 @@ fun SearchScreen(
}
}
+ uiState.isLoading -> {
+ item {
+ SearchMessageState(
+ title = stringResource(R.string.search_loading_title),
+ subtitle = stringResource(R.string.search_loading_subtitle)
+ )
+ }
+ }
+
uiState.isEmpty && uiState.hasSearchError -> {
item {
SearchMessageState(
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 38cc93e4..9d7dffe5 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
@@ -197,14 +197,14 @@ fun SeriesScreen(
subtitle = stringResource(R.string.home_add_first_provider_subtitle)
)
}
- } else if (!uiState.hasActiveProvider || (uiState.seriesByCategory.isEmpty() && uiState.libraryCount == 0 && uiState.searchQuery.isBlank() && !uiState.isLoadingPreviewRows)) {
+ } else if (!uiState.hasActiveProvider || (uiState.selectedCategory == null && uiState.seriesByCategory.isEmpty() && uiState.libraryCount == 0 && uiState.searchQuery.isBlank() && !uiState.isLoadingPreviewRows)) {
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
AppMessageState(
title = stringResource(R.string.vod_sync_needed_title),
subtitle = stringResource(R.string.vod_sync_needed_subtitle)
)
}
- } else if (uiState.seriesByCategory.isEmpty() && !uiState.isLoadingPreviewRows) {
+ } else if (uiState.selectedCategory == null && uiState.searchQuery.isBlank() && uiState.seriesByCategory.isEmpty() && !uiState.isLoadingPreviewRows) {
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
AppMessageState(
title = stringResource(R.string.series_no_found),
@@ -845,6 +845,20 @@ private fun SeriesVodContent(
}
}
}
+ } else if (filteredGridSeries.isEmpty()) {
+ item(span = { GridItemSpan(maxLineSpan) }) {
+ Box(
+ modifier = Modifier
+ .fillMaxWidth()
+ .height(loadingSectionHeight),
+ contentAlignment = Alignment.Center
+ ) {
+ AppMessageState(
+ title = stringResource(R.string.series_no_found),
+ subtitle = stringResource(R.string.series_no_found_subtitle)
+ )
+ }
+ }
} else {
gridItems(filteredGridSeries, key = { it.id }) { series ->
val isLocked = isSeriesLocked(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 f2d2f01b..7d625a40 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
@@ -46,11 +46,13 @@ import com.streamvault.app.ui.screens.vod.VodBrowseDefaults
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
import kotlinx.coroutines.ExperimentalCoroutinesApi
+import kotlinx.coroutines.FlowPreview
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.combine
+import kotlinx.coroutines.flow.debounce
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.distinctUntilChangedBy
import kotlinx.coroutines.flow.filterNotNull
@@ -69,7 +71,7 @@ enum class SeriesLibraryLens {
}
@HiltViewModel
-@OptIn(ExperimentalCoroutinesApi::class)
+@OptIn(ExperimentalCoroutinesApi::class, FlowPreview::class)
class SeriesViewModel @Inject constructor(
private val providerRepository: ProviderRepository,
private val seriesRepository: SeriesRepository,
@@ -91,6 +93,12 @@ class SeriesViewModel @Inject constructor(
val uiState: StateFlow<SeriesUiState> = _uiState.asStateFlow()
private val _searchQuery = MutableStateFlow("")
+ private val searchQueryForBrowse = _searchQuery
+ .map { it.trim() }
+ .distinctUntilChanged()
+ .debounce { query ->
+ if (query.isBlank() || query.length < MIN_SEARCH_QUERY_LENGTH) 0L else 300L
+ }
private val _selectedCategoryLoadLimit = MutableStateFlow(VodBrowseDefaults.SELECTED_CATEGORY_PAGE_SIZE)
private val _selectedLibraryFilterType = MutableStateFlow(LibraryFilterType.ALL)
private val _selectedLibrarySortBy = MutableStateFlow(LibrarySortBy.LIBRARY)
@@ -171,7 +179,7 @@ class SeriesViewModel @Inject constructor(
hiddenCategoryIds = hiddenCategoryIds,
categorySortMode = sortMode
)
- }.combine(_searchQuery) { dependencies, query ->
+ }.combine(searchQueryForBrowse) { dependencies, query ->
SeriesCatalogParams(
providerId = provider.id,
allFavorites = dependencies.allFavorites,
@@ -181,7 +189,7 @@ class SeriesViewModel @Inject constructor(
libraryCount = dependencies.libraryCount,
hiddenCategoryIds = dependencies.hiddenCategoryIds,
categorySortMode = dependencies.categorySortMode,
- query = query.trim()
+ query = query
)
}
.distinctUntilChangedBy { params ->
@@ -324,14 +332,14 @@ class SeriesViewModel @Inject constructor(
combine(
_uiState.map { it.selectedCategory }.distinctUntilChanged(),
_selectedCategoryLoadLimit,
- _searchQuery,
+ searchQueryForBrowse,
_selectedLibraryFilterType,
_selectedLibrarySortBy
) { selectedCategory, loadLimit, query, filterType, sortBy ->
SelectedSeriesBrowseSelection(
selectedCategory = selectedCategory,
loadLimit = loadLimit,
- query = query.trim(),
+ query = query,
filterType = filterType,
sortBy = sortBy
)
@@ -1002,9 +1010,7 @@ class SeriesViewModel @Inject constructor(
if (request.selectedCategory.isNullOrBlank()) {
return SelectedSeriesCategorySnapshot()
}
- if (request.query.isNotBlank() && request.query.length < MIN_SEARCH_QUERY_LENGTH) {
- return SelectedSeriesCategorySnapshot()
- }
+ val effectiveQuery = request.query.takeIf { it.trim().length >= MIN_SEARCH_QUERY_LENGTH }.orEmpty()
val globalFavoriteIds = request.allFavorites
.asSequence()
@@ -1020,7 +1026,7 @@ class SeriesViewModel @Inject constructor(
providerId = request.providerId,
sortBy = request.sortBy,
filterBy = LibraryFilterBy(type = request.filterType),
- searchQuery = request.query,
+ searchQuery = effectiveQuery,
limit = request.loadLimit,
offset = 0
)
@@ -1039,7 +1045,7 @@ 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) {
+ val fetchIds = if (effectiveQuery.isBlank() && request.filterType == LibraryFilterType.ALL && request.sortBy == LibrarySortBy.LIBRARY) {
ids.take(request.loadLimit + FAVORITE_ID_FETCH_BUFFER)
} else {
ids
@@ -1056,11 +1062,11 @@ class SeriesViewModel @Inject constructor(
request.history,
request.filterType,
request.sortBy,
- request.query
+ effectiveQuery
)
Triple(
filteredItems.take(request.loadLimit),
- if (fetchIds === ids) filteredItems.size else ids.size,
+ if (fetchIds.size == ids.size) filteredItems.size else ids.size,
false
)
}
@@ -1073,7 +1079,7 @@ 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) {
+ val fetchIds = if (effectiveQuery.isBlank() && request.filterType == LibraryFilterType.ALL && request.sortBy == LibrarySortBy.LIBRARY) {
ids.take(request.loadLimit + FAVORITE_ID_FETCH_BUFFER)
} else {
ids
@@ -1090,11 +1096,11 @@ class SeriesViewModel @Inject constructor(
request.history,
request.filterType,
request.sortBy,
- request.query
+ effectiveQuery
)
Triple(
filteredItems.take(request.loadLimit),
- if (fetchIds === ids) filteredItems.size else ids.size,
+ if (fetchIds.size == ids.size) filteredItems.size else ids.size,
false
)
} else {
@@ -1107,7 +1113,7 @@ class SeriesViewModel @Inject constructor(
categoryId = providerCategory.id,
sortBy = request.sortBy,
filterBy = LibraryFilterBy(type = request.filterType),
- searchQuery = request.query,
+ searchQuery = effectiveQuery,
limit = request.loadLimit,
offset = 0
)
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsPlaybackSection.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsPlaybackSection.kt
index 6036504f..437dbd99 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsPlaybackSection.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsPlaybackSection.kt
@@ -222,11 +222,35 @@ internal fun LazyListScope.settingsPlaybackSection(
value = defaultIdleTimerLabel,
onClick = { onShowDefaultIdleTimerDialogChange(true) }
)
- ClickableSettingsRow(
- label = stringResource(R.string.settings_audio_video_sync_default),
- value = audioVideoOffsetLabel,
- onClick = { onShowAudioVideoOffsetDialogChange(true) }
- )
+ TvClickableSurface(
+ onClick = { viewModel.setPlayerAudioVideoSyncEnabled(!uiState.playerAudioVideoSyncEnabled) },
+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(8.dp)),
+ colors = ClickableSurfaceDefaults.colors(
+ containerColor = Color.Transparent,
+ focusedContainerColor = Primary.copy(alpha = 0.15f)
+ ),
+ scale = ClickableSurfaceDefaults.scale(focusedScale = 1f),
+ modifier = Modifier.fillMaxWidth()
+ ) {
+ Row(
+ modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp, vertical = 12.dp),
+ horizontalArrangement = Arrangement.SpaceBetween,
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ Column(modifier = Modifier.weight(1f)) {
+ Text(text = stringResource(R.string.settings_audio_video_sync_enabled), style = MaterialTheme.typography.bodyMedium, color = OnSurface)
+ Text(text = stringResource(R.string.settings_audio_video_sync_enabled_subtitle), style = MaterialTheme.typography.bodySmall, color = OnBackground.copy(alpha = 0.6f))
+ }
+ Switch(checked = uiState.playerAudioVideoSyncEnabled, onCheckedChange = { viewModel.setPlayerAudioVideoSyncEnabled(it) })
+ }
+ }
+ if (uiState.playerAudioVideoSyncEnabled) {
+ ClickableSettingsRow(
+ label = stringResource(R.string.settings_audio_video_sync_default),
+ value = audioVideoOffsetLabel,
+ onClick = { onShowAudioVideoOffsetDialogChange(true) }
+ )
+ }
HorizontalDivider(color = Color.White.copy(alpha = 0.07f), modifier = Modifier.padding(vertical = 4.dp))
TvClickableSurface(
onClick = { viewModel.setCenterTwoSlotMultiviewLayout(!uiState.centerTwoSlotMultiviewLayout) },
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsPlayerPreferenceDialogs.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsPlayerPreferenceDialogs.kt
index 31a39ff3..c5d7cdc0 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsPlayerPreferenceDialogs.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsPlayerPreferenceDialogs.kt
@@ -78,7 +78,7 @@ internal fun SettingsPlayerPreferenceDialogs(
}
}
- if (showAudioVideoOffsetDialog) {
+ if (showAudioVideoOffsetDialog && uiState.playerAudioVideoSyncEnabled) {
AudioVideoOffsetValueDialog(
title = stringResource(R.string.settings_audio_video_sync_default),
subtitle = stringResource(R.string.settings_audio_video_sync_default_subtitle),
@@ -247,4 +247,4 @@ private fun AppTimeFormat.labelResId(): Int = when (this) {
AppTimeFormat.SYSTEM -> R.string.settings_time_format_system
AppTimeFormat.TWELVE_HOUR -> R.string.settings_time_format_12h
AppTimeFormat.TWENTY_FOUR_HOUR -> R.string.settings_time_format_24h
-}
\ No newline at end of file
+}
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsPreferenceModels.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsPreferenceModels.kt
index bd193ed5..49c8871e 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsPreferenceModels.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsPreferenceModels.kt
@@ -22,8 +22,8 @@ enum class ProviderWarningAction {
}
enum class ProviderSyncSelection {
- ALL,
- FAST,
+ SYNC_NOW,
+ REBUILD_INDEX,
TV,
MOVIES,
SERIES,
@@ -42,6 +42,7 @@ internal data class SettingsPreferenceSnapshot(
val playerDecoderMode: DecoderMode,
val playerSurfaceMode: PlayerSurfaceMode,
val playerPlaybackSpeed: Float,
+ val playerAudioVideoSyncEnabled: Boolean,
val playerAudioVideoOffsetMs: Int,
val centerTwoSlotMultiviewLayout: Boolean,
val playerControlsTimeoutSeconds: Int,
@@ -94,8 +95,8 @@ internal data class SettingsPreferenceSnapshot(
)
internal fun ProviderSyncSelection.label(application: Application): String = when (this) {
- ProviderSyncSelection.ALL -> application.getString(R.string.settings_sync_option_all)
- ProviderSyncSelection.FAST -> application.getString(R.string.settings_sync_option_fast)
+ ProviderSyncSelection.SYNC_NOW -> application.getString(R.string.settings_sync_option_sync_now)
+ ProviderSyncSelection.REBUILD_INDEX -> application.getString(R.string.settings_sync_option_rebuild_index)
ProviderSyncSelection.TV -> application.getString(R.string.settings_sync_option_tv)
ProviderSyncSelection.MOVIES -> application.getString(R.string.settings_sync_option_movies)
ProviderSyncSelection.SERIES -> application.getString(R.string.settings_sync_option_series)
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsPreferenceSnapshotMapper.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsPreferenceSnapshotMapper.kt
index c090bb7c..f9e850df 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsPreferenceSnapshotMapper.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsPreferenceSnapshotMapper.kt
@@ -14,6 +14,7 @@ internal fun SettingsUiState.applyPreferenceSnapshot(snapshot: SettingsPreferenc
playerDecoderMode = snapshot.playerDecoderMode,
playerSurfaceMode = snapshot.playerSurfaceMode,
playerPlaybackSpeed = snapshot.playerPlaybackSpeed,
+ playerAudioVideoSyncEnabled = snapshot.playerAudioVideoSyncEnabled,
playerAudioVideoOffsetMs = snapshot.playerAudioVideoOffsetMs,
centerTwoSlotMultiviewLayout = snapshot.centerTwoSlotMultiviewLayout,
playerControlsTimeoutSeconds = snapshot.playerControlsTimeoutSeconds,
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsProviderActions.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsProviderActions.kt
index f924056d..f8f1605e 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsProviderActions.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsProviderActions.kt
@@ -67,7 +67,7 @@ internal class SettingsProviderActions(
refreshProvider(
scope = scope,
providerId = providerId,
- syncMode = SettingsProviderSyncMode.QUICK,
+ syncMode = SettingsProviderSyncMode.SYNC_NOW,
progressPrefix = "Refreshing ${provider.name}..."
)
} else {
@@ -244,7 +244,7 @@ internal class SettingsProviderActions(
fun refreshProvider(
scope: CoroutineScope,
providerId: Long,
- syncMode: SettingsProviderSyncMode = SettingsProviderSyncMode.QUICK,
+ syncMode: SettingsProviderSyncMode = SettingsProviderSyncMode.SYNC_NOW,
progressPrefix: String? = null
) {
scope.launch {
@@ -258,8 +258,8 @@ internal class SettingsProviderActions(
}
try {
when (syncMode) {
- SettingsProviderSyncMode.QUICK -> runQuickSync(providerId, providerName)
- SettingsProviderSyncMode.FULL -> runFullSync(providerId, providerName)
+ SettingsProviderSyncMode.SYNC_NOW -> runSyncNow(providerId, providerName)
+ SettingsProviderSyncMode.REBUILD_INDEX -> runRebuildIndex(providerId, providerName)
}
} catch (e: Exception) {
uiState.update {
@@ -274,7 +274,7 @@ internal class SettingsProviderActions(
}
}
- private suspend fun runQuickSync(providerId: Long, providerName: String?) {
+ private suspend fun runSyncNow(providerId: Long, providerName: String?) {
val provider = providerRepository.getProvider(providerId)
val pendingXtreamTextRefreshGeneration = provider
?.takeIf { it.type == ProviderType.XTREAM_CODES }
@@ -288,13 +288,13 @@ internal class SettingsProviderActions(
SyncProviderCommand(
providerId = providerId,
force = pendingXtreamTextRefreshGeneration != null,
- movieFastSyncOverride = true,
+ movieFastSyncOverride = null,
epgSyncModeOverride = ProviderEpgSyncMode.BACKGROUND
),
onProgress = { message ->
uiState.update { state ->
state.copy(
- syncProgress = mapQuickSyncProgress(message),
+ syncProgress = mapSyncNowProgress(message),
syncingProviderName = providerName
)
}
@@ -351,11 +351,11 @@ internal class SettingsProviderActions(
syncProgress = null,
syncingProviderName = null,
userMessage = when {
- result is SyncProviderResult.Error -> "Quick sync failed: ${result.message}"
- (result as? SyncProviderResult.Success)?.isPartial == true -> "Quick sync completed with warnings: $warningsMessage"
- pendingXtreamTextRefreshGeneration != null -> "Quick sync completed and reapplied Xtream text decoding"
+ result is SyncProviderResult.Error -> "Sync failed: ${result.message}"
+ (result as? SyncProviderResult.Success)?.isPartial == true -> "Sync completed with warnings: $warningsMessage"
+ pendingXtreamTextRefreshGeneration != null -> "Sync completed and reapplied Xtream text decoding"
!catalogRefreshed -> "Library already up to date"
- else -> "Quick sync completed"
+ else -> "Sync completed"
},
syncWarningsByProvider = when {
result is SyncProviderResult.Error -> state.syncWarningsByProvider - providerId
@@ -366,7 +366,7 @@ internal class SettingsProviderActions(
}
}
- private suspend fun runFullSync(providerId: Long, providerName: String?) {
+ private suspend fun runRebuildIndex(providerId: Long, providerName: String?) {
val provider = providerRepository.getProvider(providerId)
val pendingXtreamTextRefreshGeneration = provider
?.takeIf { it.type == ProviderType.XTREAM_CODES }
@@ -375,47 +375,54 @@ internal class SettingsProviderActions(
val appliedGeneration = preferencesRepository.getXtreamTextImportAppliedGeneration(currentProvider.id)
currentGeneration.takeIf { it > appliedGeneration }
}
- val result = syncProvider(
- SyncProviderCommand(
- providerId = providerId,
- force = true,
- movieFastSyncOverride = null,
- epgSyncModeOverride = null
- ),
- onProgress = { message ->
+ val result = if (provider?.type == ProviderType.XTREAM_CODES) {
+ syncManager.rebuildXtreamIndex(providerId) { message ->
uiState.update { state ->
state.copy(syncProgress = message, syncingProviderName = providerName)
}
}
- )
- if (result !is SyncProviderResult.Error) {
+ } else {
+ val syncResult = syncProvider(
+ SyncProviderCommand(
+ providerId = providerId,
+ force = true,
+ movieFastSyncOverride = null,
+ epgSyncModeOverride = null
+ ),
+ onProgress = { message ->
+ uiState.update { state ->
+ state.copy(syncProgress = message, syncingProviderName = providerName)
+ }
+ }
+ )
+ when (syncResult) {
+ is SyncProviderResult.Success -> Result.success(Unit)
+ is SyncProviderResult.Error -> Result.error(syncResult.message, syncResult.exception)
+ }
+ }
+ if (result !is Result.Error) {
pendingXtreamTextRefreshGeneration?.let { generation ->
preferencesRepository.markXtreamTextImportApplied(providerId, generation)
}
- tvInputChannelSyncManager.refreshTvInputCatalog()
}
uiState.update { state ->
- val partialWarnings = (result as? SyncProviderResult.Success)?.warnings.orEmpty()
- val warningsMessage = partialWarnings.take(3).joinToString(separator = ", ").ifBlank { "Some sections are incomplete." }
state.copy(
isSyncing = false,
syncProgress = null,
syncingProviderName = null,
userMessage = when {
- result is SyncProviderResult.Error -> "Refresh failed: ${result.message}"
- (result as? SyncProviderResult.Success)?.isPartial == true -> "Refresh completed with warnings: $warningsMessage"
- else -> "Provider refreshed successfully"
+ result is Result.Error -> "Rebuild index failed: ${result.message}"
+ else -> "Index rebuild queued"
},
syncWarningsByProvider = when {
- result is SyncProviderResult.Error -> state.syncWarningsByProvider - providerId
- (result as? SyncProviderResult.Success)?.isPartial == true -> state.syncWarningsByProvider + (providerId to partialWarnings)
+ result is Result.Error -> state.syncWarningsByProvider - providerId
else -> state.syncWarningsByProvider - providerId
}
)
}
}
- private fun mapQuickSyncProgress(message: String): String = when (message) {
+ private fun mapSyncNowProgress(message: String): String = when (message) {
"Downloading Movies..." -> "Checking Movies..."
"Downloading Series..." -> "Checking Series..."
else -> message
@@ -440,6 +447,6 @@ internal class SettingsProviderActions(
}
enum class SettingsProviderSyncMode {
- QUICK,
- FULL
+ SYNC_NOW,
+ REBUILD_INDEX
}
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsProviderSyncDialogs.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsProviderSyncDialogs.kt
index 433a63aa..4585dc6b 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsProviderSyncDialogs.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsProviderSyncDialogs.kt
@@ -49,8 +49,13 @@ internal fun ProviderSyncOptionsDialog(
style = MaterialTheme.typography.bodyMedium,
color = OnSurface
)
- SyncOptionButton(stringResource(R.string.settings_sync_option_fast)) {
- onSelect(ProviderSyncSelection.FAST)
+ SyncOptionButton(stringResource(R.string.settings_sync_option_sync_now)) {
+ onSelect(ProviderSyncSelection.SYNC_NOW)
+ }
+ if (provider.type == ProviderType.XTREAM_CODES) {
+ SyncOptionButton(stringResource(R.string.settings_sync_option_rebuild_index)) {
+ onSelect(ProviderSyncSelection.REBUILD_INDEX)
+ }
}
availableSyncSelections(provider).forEach { option ->
SyncOptionButton(text = syncSelectionLabel(option)) {
@@ -142,10 +147,10 @@ private fun SyncOptionButton(
@Composable
private fun syncSelectionLabel(selection: ProviderSyncSelection): String = when (selection) {
- ProviderSyncSelection.ALL -> stringResource(R.string.settings_sync_option_all)
- ProviderSyncSelection.FAST -> stringResource(R.string.settings_sync_option_fast)
+ ProviderSyncSelection.SYNC_NOW -> stringResource(R.string.settings_sync_option_sync_now)
+ ProviderSyncSelection.REBUILD_INDEX -> stringResource(R.string.settings_sync_option_rebuild_index)
ProviderSyncSelection.TV -> stringResource(R.string.settings_sync_option_tv)
ProviderSyncSelection.MOVIES -> stringResource(R.string.settings_sync_option_movies)
ProviderSyncSelection.SERIES -> stringResource(R.string.settings_sync_option_series)
ProviderSyncSelection.EPG -> stringResource(R.string.settings_sync_option_epg)
-}
\ No newline at end of file
+}
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsStateBindings.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsStateBindings.kt
index b8ae3ff8..ba4fff6d 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsStateBindings.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsStateBindings.kt
@@ -41,6 +41,7 @@ internal fun observeSettingsPreferenceSnapshot(
playerDecoderMode = DecoderMode.AUTO,
playerSurfaceMode = com.streamvault.domain.model.PlayerSurfaceMode.AUTO,
playerPlaybackSpeed = 1f,
+ playerAudioVideoSyncEnabled = false,
playerAudioVideoOffsetMs = 0,
centerTwoSlotMultiviewLayout = false,
playerControlsTimeoutSeconds = 5,
@@ -105,6 +106,8 @@ internal fun observeSettingsPreferenceSnapshot(
snapshot.copy(playerSurfaceMode = surfaceMode)
}.combine(preferencesRepository.playerPlaybackSpeed) { snapshot, playerPlaybackSpeed ->
snapshot.copy(playerPlaybackSpeed = playerPlaybackSpeed)
+ }.combine(preferencesRepository.playerAudioVideoSyncEnabled) { snapshot, enabled ->
+ snapshot.copy(playerAudioVideoSyncEnabled = enabled)
}.combine(preferencesRepository.playerAudioVideoOffsetMs) { snapshot, playerAudioVideoOffsetMs ->
snapshot.copy(playerAudioVideoOffsetMs = playerAudioVideoOffsetMs)
}.combine(preferencesRepository.multiViewCenterTwoSlotLayout) { snapshot, centerTwoSlotLayout ->
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsSyncActions.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsSyncActions.kt
index 28a9807b..7563eb05 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsSyncActions.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsSyncActions.kt
@@ -5,6 +5,7 @@ import com.streamvault.app.R
import com.streamvault.app.tvinput.TvInputChannelSyncManager
import com.streamvault.data.sync.SyncManager
import com.streamvault.data.sync.SyncRepairSection
+import com.streamvault.domain.model.ProviderType
import com.streamvault.domain.model.Result
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.MutableStateFlow
@@ -21,8 +22,11 @@ internal class SettingsSyncActions(
fun syncProviderSection(scope: CoroutineScope, providerId: Long, selection: ProviderSyncSelection) {
scope.launch {
when (selection) {
- ProviderSyncSelection.ALL -> refreshProvider(scope, providerId, SettingsProviderSyncMode.FULL)
- ProviderSyncSelection.FAST -> refreshProvider(scope, providerId, SettingsProviderSyncMode.QUICK)
+ ProviderSyncSelection.SYNC_NOW -> runSectionSync(
+ providerId = providerId,
+ selections = syncNowSelections(providerId)
+ )
+ ProviderSyncSelection.REBUILD_INDEX -> refreshProvider(scope, providerId, SettingsProviderSyncMode.REBUILD_INDEX)
else -> runSectionSync(providerId, listOf(selection))
}
}
@@ -105,7 +109,8 @@ internal class SettingsSyncActions(
providerId: Long,
selections: List<ProviderSyncSelection>
) {
- val providerName = uiState.value.providers.firstOrNull { it.id == providerId }?.name
+ val provider = uiState.value.providers.firstOrNull { it.id == providerId }
+ val providerName = provider?.name
uiState.update {
it.copy(
isSyncing = true,
@@ -123,7 +128,7 @@ internal class SettingsSyncActions(
ProviderSyncSelection.MOVIES -> SyncRepairSection.MOVIES
ProviderSyncSelection.SERIES -> SyncRepairSection.SERIES
ProviderSyncSelection.EPG -> SyncRepairSection.EPG
- ProviderSyncSelection.ALL, ProviderSyncSelection.FAST -> null
+ ProviderSyncSelection.SYNC_NOW, ProviderSyncSelection.REBUILD_INDEX -> null
} ?: return@forEach
uiState.update { state ->
@@ -140,13 +145,12 @@ internal class SettingsSyncActions(
uiState.update { state -> state.copy(syncProgress = progress, syncingProviderName = providerName) }
}) {
is Result.Error -> failures += "${selection.label(appContext)}: ${result.message}"
- else -> completed += selection.label(appContext)
+ else -> completed += selection.completionLabel(isXtream = provider?.type == ProviderType.XTREAM_CODES)
}
}
if (completed.any {
- it == appContext.getString(R.string.settings_sync_option_all) ||
- it == appContext.getString(R.string.settings_sync_option_tv)
+ it == appContext.getString(R.string.settings_sync_option_tv)
}
) {
tvInputChannelSyncManager.refreshTvInputCatalog()
@@ -185,4 +189,22 @@ internal class SettingsSyncActions(
}
}
}
+
+ private fun syncNowSelections(providerId: Long): List<ProviderSyncSelection> {
+ val provider = uiState.value.providers.firstOrNull { it.id == providerId }
+ return buildList {
+ add(ProviderSyncSelection.TV)
+ add(ProviderSyncSelection.MOVIES)
+ if (provider?.type == ProviderType.XTREAM_CODES) {
+ add(ProviderSyncSelection.SERIES)
+ }
+ add(ProviderSyncSelection.EPG)
+ }
+ }
+
+ private fun ProviderSyncSelection.completionLabel(isXtream: Boolean): String = when {
+ isXtream && this == ProviderSyncSelection.MOVIES -> "Movies index queued"
+ isXtream && this == ProviderSyncSelection.SERIES -> "Series index queued"
+ else -> label(appContext)
+ }
}
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsUiStateModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsUiStateModel.kt
index 029eeb3b..d169c3ac 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsUiStateModel.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsUiStateModel.kt
@@ -44,6 +44,7 @@ data class SettingsUiState(
val playerDecoderMode: DecoderMode = DecoderMode.AUTO,
val playerSurfaceMode: PlayerSurfaceMode = PlayerSurfaceMode.AUTO,
val playerPlaybackSpeed: Float = 1f,
+ val playerAudioVideoSyncEnabled: Boolean = false,
val playerAudioVideoOffsetMs: Int = 0,
val centerTwoSlotMultiviewLayout: Boolean = false,
val playerControlsTimeoutSeconds: Int = 5,
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsViewModel.kt
index be05ead2..33b07d25 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsViewModel.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsViewModel.kt
@@ -16,6 +16,8 @@ import com.streamvault.app.update.AppUpdateDownloadStatus
import com.streamvault.app.update.AppUpdateInstaller
import com.streamvault.app.update.GitHubReleaseChecker
import com.streamvault.app.update.GitHubReleaseInfo
+import com.streamvault.data.local.dao.XtreamIndexJobDao
+import com.streamvault.data.local.entity.XtreamIndexJobEntity
import com.streamvault.data.preferences.PreferencesRepository
import com.streamvault.data.sync.SyncManager
import com.streamvault.data.sync.SyncRepairSection
@@ -67,6 +69,8 @@ import kotlinx.coroutines.launch
import kotlin.math.max
import javax.inject.Inject
+private const val XTREAM_INDEX_STATUS_PREFIX = "Xtream index:"
+
@HiltViewModel
@OptIn(ExperimentalCoroutinesApi::class)
class SettingsViewModel @Inject constructor(
@@ -81,6 +85,7 @@ class SettingsViewModel @Inject constructor(
private val recordingManager: RecordingManager,
private val parentalControlManager: ParentalControlManager,
private val syncManager: SyncManager,
+ private val xtreamIndexJobDao: XtreamIndexJobDao,
private val syncMetadataRepository: SyncMetadataRepository,
private val playbackHistoryRepository: com.streamvault.domain.repository.PlaybackHistoryRepository,
private val watchNextManager: WatchNextManager,
@@ -142,6 +147,7 @@ class SettingsViewModel @Inject constructor(
init {
registerPreferenceObservers()
+ registerXtreamIndexJobObserver()
registerSettingsAppUpdateObservers(
scope = viewModelScope,
preferencesRepository = preferencesRepository,
@@ -198,6 +204,49 @@ class SettingsViewModel @Inject constructor(
}
}
+ private fun registerXtreamIndexJobObserver() {
+ viewModelScope.launch {
+ xtreamIndexJobDao.observeAll().collect { jobs ->
+ val jobWarningsByProvider = jobs
+ .groupBy { it.providerId }
+ .mapValues { (_, providerJobs) ->
+ providerJobs.mapNotNull { job -> job.toSettingsStatusMessage() }
+ }
+ .filterValues { it.isNotEmpty() }
+
+ _uiState.update { state ->
+ val providerIds = state.providers.map { it.id }.toSet()
+ val preservedWarnings = state.syncWarningsByProvider
+ .filterKeys { it in providerIds }
+ .mapValues { (_, warnings) ->
+ warnings.filterNot { warning -> warning.startsWith(XTREAM_INDEX_STATUS_PREFIX) }
+ }
+ .filterValues { it.isNotEmpty() }
+ state.copy(syncWarningsByProvider = preservedWarnings + jobWarningsByProvider)
+ }
+ }
+ }
+ }
+
+ private fun XtreamIndexJobEntity.toSettingsStatusMessage(): String? {
+ val label = when (section) {
+ "LIVE" -> "Live TV"
+ "MOVIE" -> "Movies"
+ "SERIES" -> "Series"
+ "EPG" -> "EPG"
+ else -> section.lowercase().replaceFirstChar { it.titlecase() }
+ }
+ return when (state) {
+ "QUEUED" -> "$XTREAM_INDEX_STATUS_PREFIX $label queued"
+ "RUNNING" -> "$XTREAM_INDEX_STATUS_PREFIX $label indexing"
+ "PARTIAL" -> "$XTREAM_INDEX_STATUS_PREFIX $label partial: ${indexedRows} indexed"
+ "STALE" -> "$XTREAM_INDEX_STATUS_PREFIX $label stale"
+ "FAILED_RETRYABLE" -> "$XTREAM_INDEX_STATUS_PREFIX $label retryable failed${lastError?.let { ": $it" }.orEmpty()}"
+ "FAILED_PERMANENT" -> "$XTREAM_INDEX_STATUS_PREFIX $label permanently failed${lastError?.let { ": $it" }.orEmpty()}"
+ else -> null
+ }
+ }
+
fun setActiveProvider(providerId: Long) {
providerActions.setActiveProvider(viewModelScope, providerId)
}
@@ -445,6 +494,12 @@ class SettingsViewModel @Inject constructor(
}
}
+ fun setPlayerAudioVideoSyncEnabled(enabled: Boolean) {
+ viewModelScope.launch {
+ preferencesRepository.setPlayerAudioVideoSyncEnabled(enabled)
+ }
+ }
+
fun setCenterTwoSlotMultiviewLayout(enabled: Boolean) {
viewModelScope.launch {
preferencesRepository.setMultiViewCenterTwoSlotLayout(enabled)
@@ -689,7 +744,7 @@ class SettingsViewModel @Inject constructor(
fun refreshProvider(
providerId: Long,
- syncMode: SettingsProviderSyncMode = SettingsProviderSyncMode.QUICK
+ syncMode: SettingsProviderSyncMode = SettingsProviderSyncMode.SYNC_NOW
) {
providerActions.refreshProvider(viewModelScope, providerId, syncMode)
}
diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml
index 0bc7b846..ac2bd375 100644
--- a/app/src/main/res/values-ar/strings.xml
+++ b/app/src/main/res/values-ar/strings.xml
@@ -728,8 +728,6 @@
<string name="setup_advanced_options_helper">تحكم في كيفية جلب بيانات الدليل أثناء إعداد المزوّد وتحديثه.</string>
<string name="setup_advanced_options_show">إظهار</string>
<string name="setup_advanced_options_hide">إخفاء</string>
- <string name="setup_xtream_fast_sync_label">مزامنة سريعة</string>
- <string name="setup_xtream_fast_sync_helper">Xtream فقط. يحمّل فئات VOD أولًا ويجلب صفوف الأفلام عند الطلب. موصى به للمزوّدين الكبار جدًا.</string>
<string name="setup_m3u_vod_classification_label">تصنيف VOD في M3U</string>
<string name="setup_m3u_vod_classification_helper">M3U فقط. استخدم رابط قائمة التشغيل واستدلالات group-title لفرز الإدخالات المطابقة ضمن الأفلام بدلًا من البث المباشر.</string>
<string name="setup_epg_sync_mode_label">مزامنة EPG</string>
diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml
index d8af9b96..89e79fbb 100644
--- a/app/src/main/res/values-cs/strings.xml
+++ b/app/src/main/res/values-cs/strings.xml
@@ -728,8 +728,6 @@
<string name="setup_advanced_options_helper">Určete, jak se při nastavení a obnovení poskytovatele načítají data průvodce.</string>
<string name="setup_advanced_options_show">Zobrazit</string>
<string name="setup_advanced_options_hide">Skrýt</string>
- <string name="setup_xtream_fast_sync_label">Rychlá synchronizace</string>
- <string name="setup_xtream_fast_sync_helper">Pouze Xtream. Nejprve načte kategorie VOD a řádky filmů načítá podle potřeby. Doporučeno pro velmi velké poskytovatele.</string>
<string name="setup_m3u_vod_classification_label">Klasifikace VOD v M3U</string>
<string name="setup_m3u_vod_classification_helper">Pouze M3U. Použijte URL playlistu a heuristiku group-title k zařazení odpovídajících položek do Filmů místo Živého TV.</string>
<string name="setup_epg_sync_mode_label">Synchronizace EPG</string>
diff --git a/app/src/main/res/values-da/strings.xml b/app/src/main/res/values-da/strings.xml
index f7d14482..34aec5ce 100644
--- a/app/src/main/res/values-da/strings.xml
+++ b/app/src/main/res/values-da/strings.xml
@@ -728,8 +728,6 @@
<string name="setup_advanced_options_helper">Styr, hvordan guide-data hentes under opsætning og opdatering af udbyder.</string>
<string name="setup_advanced_options_show">Vis</string>
<string name="setup_advanced_options_hide">Skjul</string>
- <string name="setup_xtream_fast_sync_label">Hurtig synkronisering</string>
- <string name="setup_xtream_fast_sync_helper">Kun Xtream. Indlæser først VOD-kategorier og henter filmrækker efter behov. Anbefales til meget store udbydere.</string>
<string name="setup_m3u_vod_classification_label">M3U VOD-klassificering</string>
<string name="setup_m3u_vod_classification_helper">Kun M3U. Brug playlist-URL og group-title-heuristik til at sortere matchende poster i Film i stedet for Live TV.</string>
<string name="setup_epg_sync_mode_label">EPG-synkronisering</string>
diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml
index 8e07f0ea..cb32c220 100644
--- a/app/src/main/res/values-de/strings.xml
+++ b/app/src/main/res/values-de/strings.xml
@@ -728,8 +728,6 @@
<string name="setup_advanced_options_helper">Steuere, wie Guide-Daten während der Anbieter-Einrichtung und Aktualisierung abgerufen werden.</string>
<string name="setup_advanced_options_show">Anzeigen</string>
<string name="setup_advanced_options_hide">Ausblenden</string>
- <string name="setup_xtream_fast_sync_label">Schnelle Synchronisierung</string>
- <string name="setup_xtream_fast_sync_helper">Nur Xtream. Lädt zuerst VOD-Kategorien und ruft Filmzeilen bei Bedarf ab. Empfohlen für sehr große Anbieter.</string>
<string name="setup_m3u_vod_classification_label">M3U-VOD-Klassifizierung</string>
<string name="setup_m3u_vod_classification_helper">Nur M3U. Verwende die Playlist-URL und group-title-Heuristiken, um passende Einträge statt Live-TV in Filme einzuordnen.</string>
<string name="setup_epg_sync_mode_label">EPG-Synchronisierung</string>
diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml
index 76742d8b..c4eb60c5 100644
--- a/app/src/main/res/values-el/strings.xml
+++ b/app/src/main/res/values-el/strings.xml
@@ -728,8 +728,6 @@
<string name="setup_advanced_options_helper">Ελέγξτε πώς γίνεται η λήψη των δεδομένων οδηγού κατά την εγκατάσταση και την ανανέωση του παρόχου.</string>
<string name="setup_advanced_options_show">Εμφάνιση</string>
<string name="setup_advanced_options_hide">Απόκρυψη</string>
- <string name="setup_xtream_fast_sync_label">Γρήγορος συγχρονισμός</string>
- <string name="setup_xtream_fast_sync_helper">Μόνο Xtream. Φορτώνει τις κατηγορίες VOD πρώτα και ανακτά σειρές ταινιών κατά παραγγελία. Συνιστάται για πολύ μεγάλους παρόχους.</string>
<string name="setup_m3u_vod_classification_label">Ταξινόμηση VOD M3U</string>
<string name="setup_m3u_vod_classification_helper">Μόνο για M3U. Χρησιμοποιεί τη διεύθυνση URL της playlist και ευρετικές με βάση το group-title για να ταξινομεί τις αντίστοιχες εγγραφές στις Ταινίες αντί για Ζωντανή TV.</string>
<string name="setup_epg_sync_mode_label">Συγχρονισμός EPG</string>
diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml
index 34803d7f..7a250269 100644
--- a/app/src/main/res/values-es/strings.xml
+++ b/app/src/main/res/values-es/strings.xml
@@ -728,8 +728,6 @@
<string name="setup_advanced_options_helper">Controla cómo se obtienen los datos de la guía durante la configuración y actualización del proveedor.</string>
<string name="setup_advanced_options_show">Mostrar</string>
<string name="setup_advanced_options_hide">Ocultar</string>
- <string name="setup_xtream_fast_sync_label">Sincronización rápida</string>
- <string name="setup_xtream_fast_sync_helper">Solo Xtream. Carga primero las categorías VOD y obtiene las filas de películas bajo demanda. Recomendado para proveedores muy grandes.</string>
<string name="setup_m3u_vod_classification_label">Clasificación VOD de M3U</string>
<string name="setup_m3u_vod_classification_helper">Solo M3U. Usa la URL de la lista y heurísticas de group-title para clasificar las entradas coincidentes en Películas en lugar de TV en directo.</string>
<string name="setup_epg_sync_mode_label">Sincronización de EPG</string>
diff --git a/app/src/main/res/values-fi/strings.xml b/app/src/main/res/values-fi/strings.xml
index 4c72ba4f..9382fbf7 100644
--- a/app/src/main/res/values-fi/strings.xml
+++ b/app/src/main/res/values-fi/strings.xml
@@ -728,8 +728,6 @@
<string name="setup_advanced_options_helper">Määritä, miten opastiedot haetaan palveluntarjoajan asetuksissa ja päivityksessä.</string>
<string name="setup_advanced_options_show">Näytä</string>
<string name="setup_advanced_options_hide">Piilota</string>
- <string name="setup_xtream_fast_sync_label">Nopea synkronointi</string>
- <string name="setup_xtream_fast_sync_helper">Vain Xtream. Lataa ensin VOD-luokat ja hakee elokuvarivit tarvittaessa. Suositeltu erittäin suurille palveluntarjoajille.</string>
<string name="setup_m3u_vod_classification_label">M3U VOD -luokittelu</string>
<string name="setup_m3u_vod_classification_helper">Vain M3U. Käytä soittolistan URL-osoitetta ja group-title-heuristiikkaa lajitellaksesi vastaavat kohteet Elokuvat-kategoriaan Live TV:n sijaan.</string>
<string name="setup_epg_sync_mode_label">EPG-synkronointi</string>
diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml
index 34009524..2844f5fa 100644
--- a/app/src/main/res/values-fr/strings.xml
+++ b/app/src/main/res/values-fr/strings.xml
@@ -728,8 +728,6 @@
<string name="setup_advanced_options_helper">Contrôlez la façon dont les données du guide sont récupérées lors de la configuration et de l’actualisation du fournisseur.</string>
<string name="setup_advanced_options_show">Afficher</string>
<string name="setup_advanced_options_hide">Masquer</string>
- <string name="setup_xtream_fast_sync_label">Synchronisation rapide</string>
- <string name="setup_xtream_fast_sync_helper">Xtream uniquement. Charge d’abord les catégories VOD et récupère les lignes de films à la demande. Recommandé pour les fournisseurs très volumineux.</string>
<string name="setup_m3u_vod_classification_label">Classification VOD M3U</string>
<string name="setup_m3u_vod_classification_helper">M3U uniquement. Utilise l’URL de la playlist et les heuristiques group-title pour classer les entrées correspondantes dans Films au lieu de TV en direct.</string>
<string name="setup_epg_sync_mode_label">Synchronisation EPG</string>
diff --git a/app/src/main/res/values-hu/strings.xml b/app/src/main/res/values-hu/strings.xml
index 81813ee0..d3f9d88d 100644
--- a/app/src/main/res/values-hu/strings.xml
+++ b/app/src/main/res/values-hu/strings.xml
@@ -728,8 +728,6 @@
<string name="setup_advanced_options_helper">Szabályozza, hogyan történjen az útmutatóadatok lekérése a szolgáltató beállítása és frissítése során.</string>
<string name="setup_advanced_options_show">Megjelenítés</string>
<string name="setup_advanced_options_hide">Elrejtés</string>
- <string name="setup_xtream_fast_sync_label">Gyors szinkronizálás</string>
- <string name="setup_xtream_fast_sync_helper">Csak Xtream. Először betölti a VOD kategóriákat, majd igény szerint lekéri a film sorokat. Nagyon nagy szolgáltatókhoz ajánlott.</string>
<string name="setup_m3u_vod_classification_label">M3U VOD besorolás</string>
<string name="setup_m3u_vod_classification_helper">Csak M3U. A playlist URL és a group-title heurisztikák alapján a megfelelő elemeket a Filmek közé sorolja az Élő TV helyett.</string>
<string name="setup_epg_sync_mode_label">EPG szinkronizálás</string>
diff --git a/app/src/main/res/values-in/strings.xml b/app/src/main/res/values-in/strings.xml
index 8fdb6859..e3d37637 100644
--- a/app/src/main/res/values-in/strings.xml
+++ b/app/src/main/res/values-in/strings.xml
@@ -728,8 +728,6 @@
<string name="setup_advanced_options_helper">Atur cara data panduan diambil saat penyiapan dan penyegaran penyedia.</string>
<string name="setup_advanced_options_show">Tampilkan</string>
<string name="setup_advanced_options_hide">Sembunyikan</string>
- <string name="setup_xtream_fast_sync_label">Sinkronisasi Cepat</string>
- <string name="setup_xtream_fast_sync_helper">Hanya Xtream. Memuat kategori VOD terlebih dahulu dan mengambil baris film sesuai permintaan. Direkomendasikan untuk penyedia yang sangat besar.</string>
<string name="setup_m3u_vod_classification_label">Klasifikasi VOD M3U</string>
<string name="setup_m3u_vod_classification_helper">Hanya M3U. Gunakan URL playlist dan heuristik group-title untuk mengurutkan entri yang cocok ke Film, bukan TV Langsung.</string>
<string name="setup_epg_sync_mode_label">Sinkronisasi EPG</string>
diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml
index 06191a40..afeb8de6 100644
--- a/app/src/main/res/values-it/strings.xml
+++ b/app/src/main/res/values-it/strings.xml
@@ -728,8 +728,6 @@
<string name="setup_advanced_options_helper">Controlla come vengono recuperati i dati della guida durante la configurazione e l\'aggiornamento del provider.</string>
<string name="setup_advanced_options_show">Mostra</string>
<string name="setup_advanced_options_hide">Nascondi</string>
- <string name="setup_xtream_fast_sync_label">Sincronizzazione veloce</string>
- <string name="setup_xtream_fast_sync_helper">Solo Xtream. Carica prima le categorie VOD e recupera le righe di film su richiesta. Consigliato per fornitori molto grandi.</string>
<string name="setup_m3u_vod_classification_label">Classificazione VOD M3U</string>
<string name="setup_m3u_vod_classification_helper">Solo M3U. Usa l\'URL della playlist e le euristiche di group-title per ordinare le voci corrispondenti in Film invece che in Live TV.</string>
<string name="setup_epg_sync_mode_label">Sincronizzazione EPG</string>
diff --git a/app/src/main/res/values-iw/strings.xml b/app/src/main/res/values-iw/strings.xml
index 3964fd7e..7a6830bc 100644
--- a/app/src/main/res/values-iw/strings.xml
+++ b/app/src/main/res/values-iw/strings.xml
@@ -728,8 +728,6 @@
<string name="setup_advanced_options_helper">שליטה באופן שבו נתוני המדריך נשלפים במהלך הגדרת הספק ורענון.</string>
<string name="setup_advanced_options_show">הצג</string>
<string name="setup_advanced_options_hide">הסתר</string>
- <string name="setup_xtream_fast_sync_label">סנכרון מהיר</string>
- <string name="setup_xtream_fast_sync_helper">ל-Xtream בלבד. טוען תחילה קטגוריות VOD ומביא את שורות הסרטים לפי דרישה. מומלץ לספקים גדולים מאוד.</string>
<string name="setup_m3u_vod_classification_label">סיווג VOD של M3U</string>
<string name="setup_m3u_vod_classification_helper">ל-M3U בלבד. השתמשו בכתובת ה-URL של הפלייליסט ובכללי group-title כדי למיין פריטים תואמים לסרטים במקום ל-Live TV.</string>
<string name="setup_epg_sync_mode_label">סנכרון EPG</string>
diff --git a/app/src/main/res/values-ja/strings.xml b/app/src/main/res/values-ja/strings.xml
index 6451c8f3..1aee1789 100644
--- a/app/src/main/res/values-ja/strings.xml
+++ b/app/src/main/res/values-ja/strings.xml
@@ -728,8 +728,6 @@
<string name="setup_advanced_options_helper">プロバイダー設定と更新時の番組表データ取得方法を管理します。</string>
<string name="setup_advanced_options_show">表示</string>
<string name="setup_advanced_options_hide">非表示</string>
- <string name="setup_xtream_fast_sync_label">高速同期</string>
- <string name="setup_xtream_fast_sync_helper">エクストリームのみ。最初に VOD カテゴリをロードし、オンデマンドで映画行をフェッチします。非常に大規模なプロバイダーに推奨されます。</string>
<string name="setup_m3u_vod_classification_label">M3U VOD分類</string>
<string name="setup_m3u_vod_classification_helper">M3Uのみ。プレイリストURLとgroup-titleの条件で一致する項目をライブTVではなく映画に分類します。</string>
<string name="setup_epg_sync_mode_label">EPG同期</string>
diff --git a/app/src/main/res/values-ko/strings.xml b/app/src/main/res/values-ko/strings.xml
index a001612c..dd8d9eb3 100644
--- a/app/src/main/res/values-ko/strings.xml
+++ b/app/src/main/res/values-ko/strings.xml
@@ -728,8 +728,6 @@
<string name="setup_advanced_options_helper">공급자 설정 및 새로고침 중 가이드 데이터를 가져오는 방식을 제어합니다.</string>
<string name="setup_advanced_options_show">표시</string>
<string name="setup_advanced_options_hide">숨기기</string>
- <string name="setup_xtream_fast_sync_label">빠른 동기화</string>
- <string name="setup_xtream_fast_sync_helper">엑스트림 전용입니다. VOD 카테고리를 먼저 로드하고 요청 시 영화 행을 가져옵니다. 규모가 매우 큰 공급자에게 권장됩니다.</string>
<string name="setup_m3u_vod_classification_label">M3U VOD 분류</string>
<string name="setup_m3u_vod_classification_helper">M3U 전용. 재생목록 URL과 group-title 휴리스틱을 사용해 일치하는 항목을 라이브 TV 대신 영화로 분류합니다.</string>
<string name="setup_epg_sync_mode_label">EPG 동기화</string>
diff --git a/app/src/main/res/values-nb/strings.xml b/app/src/main/res/values-nb/strings.xml
index 7eec6856..1d0f97fc 100644
--- a/app/src/main/res/values-nb/strings.xml
+++ b/app/src/main/res/values-nb/strings.xml
@@ -728,8 +728,6 @@
<string name="setup_advanced_options_helper">Kontroller hvordan guide-data hentes under oppsett og oppdatering av leverandøren.</string>
<string name="setup_advanced_options_show">Vis</string>
<string name="setup_advanced_options_hide">Skjul</string>
- <string name="setup_xtream_fast_sync_label">Rask synkronisering</string>
- <string name="setup_xtream_fast_sync_helper">Kun Xtream. Laster først VOD-kategorier og henter filmrader ved behov. Anbefales for svært store leverandører.</string>
<string name="setup_m3u_vod_classification_label">M3U VOD-klassifisering</string>
<string name="setup_m3u_vod_classification_helper">Kun M3U. Bruk spilleliste-URL og group-title-heuristikk for å sortere treff i Filmer i stedet for direktesendt TV.</string>
<string name="setup_epg_sync_mode_label">EPG-synk</string>
diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml
index cf42d5f1..b38cf6bf 100644
--- a/app/src/main/res/values-nl/strings.xml
+++ b/app/src/main/res/values-nl/strings.xml
@@ -728,8 +728,6 @@
<string name="setup_advanced_options_helper">Bepaal hoe gidsgegevens worden opgehaald tijdens providerinstelling en verversing.</string>
<string name="setup_advanced_options_show">Tonen</string>
<string name="setup_advanced_options_hide">Verbergen</string>
- <string name="setup_xtream_fast_sync_label">Snelle synchronisatie</string>
- <string name="setup_xtream_fast_sync_helper">Alleen Xtream. Laadt eerst VOD-categorieën en haalt filmregels op aanvraag op. Aanbevolen voor zeer grote providers.</string>
<string name="setup_m3u_vod_classification_label">M3U VOD-classificatie</string>
<string name="setup_m3u_vod_classification_helper">Alleen M3U. Gebruik de playlist-URL en group-title-heuristieken om overeenkomende items te sorteren in Films in plaats van Live TV.</string>
<string name="setup_epg_sync_mode_label">EPG-synchronisatie</string>
diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml
index 59b65e38..dd89322a 100644
--- a/app/src/main/res/values-pl/strings.xml
+++ b/app/src/main/res/values-pl/strings.xml
@@ -728,8 +728,6 @@
<string name="setup_advanced_options_helper">Kontroluj, jak pobierane są dane przewodnika podczas konfiguracji i odświeżania dostawcy.</string>
<string name="setup_advanced_options_show">Pokaż</string>
<string name="setup_advanced_options_hide">Ukryj</string>
- <string name="setup_xtream_fast_sync_label">Szybka synchronizacja</string>
- <string name="setup_xtream_fast_sync_helper">Tylko Xtreme. Najpierw ładuje kategorie VOD, a na żądanie pobiera wiersze filmów. Zalecane dla bardzo dużych dostawców.</string>
<string name="setup_m3u_vod_classification_label">Klasyfikacja VOD M3U</string>
<string name="setup_m3u_vod_classification_helper">Tylko M3U. Użyj adresu URL playlisty i heurystyki group-title, aby sortować pasujące pozycje do Filmów zamiast Telewizji na żywo.</string>
<string name="setup_epg_sync_mode_label">Synchronizacja EPG</string>
diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml
index 8b2149b7..f71e004a 100644
--- a/app/src/main/res/values-pt/strings.xml
+++ b/app/src/main/res/values-pt/strings.xml
@@ -728,8 +728,6 @@
<string name="setup_advanced_options_helper">Controle como os dados do guia são obtidos durante a configuração e atualização do provedor.</string>
<string name="setup_advanced_options_show">Mostrar</string>
<string name="setup_advanced_options_hide">Ocultar</string>
- <string name="setup_xtream_fast_sync_label">Sincronização rápida</string>
- <string name="setup_xtream_fast_sync_helper">Somente Xtream. Carrega as categorias VOD primeiro e busca as linhas do filme sob demanda. Recomendado para fornecedores muito grandes.</string>
<string name="setup_m3u_vod_classification_label">Classificação de VOD M3U</string>
<string name="setup_m3u_vod_classification_helper">Somente M3U. Use a URL da playlist e heurísticas de group-title para classificar entradas correspondentes em Filmes em vez de TV ao vivo.</string>
<string name="setup_epg_sync_mode_label">Sincronização do EPG</string>
diff --git a/app/src/main/res/values-ro/strings.xml b/app/src/main/res/values-ro/strings.xml
index 78df6107..eb5346aa 100644
--- a/app/src/main/res/values-ro/strings.xml
+++ b/app/src/main/res/values-ro/strings.xml
@@ -728,8 +728,6 @@
<string name="setup_advanced_options_helper">Controlați cum sunt preluate datele ghidului în timpul configurării și actualizării furnizorului.</string>
<string name="setup_advanced_options_show">Afișează</string>
<string name="setup_advanced_options_hide">Ascunde</string>
- <string name="setup_xtream_fast_sync_label">Sincronizare rapidă</string>
- <string name="setup_xtream_fast_sync_helper">Doar Xtream. Încarcă mai întâi categoriile VOD și preia la cerere rândurile pentru filme. Recomandat pentru furnizori foarte mari.</string>
<string name="setup_m3u_vod_classification_label">Clasificare VOD M3U</string>
<string name="setup_m3u_vod_classification_helper">Doar M3U. Folosiți URL-ul playlistului și euristicile group-title pentru a sorta intrările potrivite în Filme, nu în Live TV.</string>
<string name="setup_epg_sync_mode_label">Sincronizare EPG</string>
diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml
index 4eb8fa43..b470508d 100644
--- a/app/src/main/res/values-ru/strings.xml
+++ b/app/src/main/res/values-ru/strings.xml
@@ -728,8 +728,6 @@
<string name="setup_advanced_options_helper">Управляйте тем, как загружаются данные телепрограммы при настройке и обновлении провайдера.</string>
<string name="setup_advanced_options_show">Показать</string>
<string name="setup_advanced_options_hide">Скрыть</string>
- <string name="setup_xtream_fast_sync_label">Быстрая синхронизация</string>
- <string name="setup_xtream_fast_sync_helper">Только Хтрим. Сначала загружает категории VOD и извлекает строки фильмов по запросу. Рекомендуется для очень крупных провайдеров.</string>
<string name="setup_m3u_vod_classification_label">Классификация VOD в M3U</string>
<string name="setup_m3u_vod_classification_helper">Только для M3U. Используйте URL плейлиста и эвристику group-title, чтобы сортировать подходящие записи в Фильмы вместо Live TV.</string>
<string name="setup_epg_sync_mode_label">Синхронизация EPG</string>
diff --git a/app/src/main/res/values-sv/strings.xml b/app/src/main/res/values-sv/strings.xml
index 96d02285..615e1726 100644
--- a/app/src/main/res/values-sv/strings.xml
+++ b/app/src/main/res/values-sv/strings.xml
@@ -728,8 +728,6 @@
<string name="setup_advanced_options_helper">Styr hur guide-data hämtas vid leverantörsinställning och uppdatering.</string>
<string name="setup_advanced_options_show">Visa</string>
<string name="setup_advanced_options_hide">Dölj</string>
- <string name="setup_xtream_fast_sync_label">Snabb synk</string>
- <string name="setup_xtream_fast_sync_helper">Endast Xtream. Läser in VOD-kategorier först och hämtar filmrader vid behov. Rekommenderas för mycket stora leverantörer.</string>
<string name="setup_m3u_vod_classification_label">M3U VOD-klassificering</string>
<string name="setup_m3u_vod_classification_helper">Endast M3U. Använd playlist-URL och group-title-heuristik för att sortera matchande poster till Filmer i stället för Live-TV.</string>
<string name="setup_epg_sync_mode_label">EPG-synk</string>
diff --git a/app/src/main/res/values-tr/strings.xml b/app/src/main/res/values-tr/strings.xml
index 758137cf..376c8d36 100644
--- a/app/src/main/res/values-tr/strings.xml
+++ b/app/src/main/res/values-tr/strings.xml
@@ -728,8 +728,6 @@
<string name="setup_advanced_options_helper">Sağlayıcı kurulumu ve yenileme sırasında rehber verilerinin nasıl alındığını kontrol edin.</string>
<string name="setup_advanced_options_show">Göster</string>
<string name="setup_advanced_options_hide">Gizle</string>
- <string name="setup_xtream_fast_sync_label">Hızlı Senkronizasyon</string>
- <string name="setup_xtream_fast_sync_helper">Yalnızca Xtream. Önce VOD kategorilerini yükler ve film satırlarını gerektiğinde getirir. Çok büyük sağlayıcılar için önerilir.</string>
<string name="setup_m3u_vod_classification_label">M3U VOD Sınıflandırması</string>
<string name="setup_m3u_vod_classification_helper">Yalnızca M3U. Eşleşen girişleri Canlı TV yerine Filmler\'e ayırmak için oynatma listesi URL\'si ve group-title sezgisel kurallarını kullanın.</string>
<string name="setup_epg_sync_mode_label">EPG Senkronizasyonu</string>
diff --git a/app/src/main/res/values-uk/strings.xml b/app/src/main/res/values-uk/strings.xml
index 0add0b32..5567b76c 100644
--- a/app/src/main/res/values-uk/strings.xml
+++ b/app/src/main/res/values-uk/strings.xml
@@ -728,8 +728,6 @@
<string name="setup_advanced_options_helper">Керуйте тим, як завантажуються дані телегіда під час налаштування та оновлення провайдера.</string>
<string name="setup_advanced_options_show">Показати</string>
<string name="setup_advanced_options_hide">Сховати</string>
- <string name="setup_xtream_fast_sync_label">Швидка синхронізація</string>
- <string name="setup_xtream_fast_sync_helper">Лише Xtream. Спочатку завантажує категорії VOD, а рядки фільмів отримує за потреби. Рекомендовано для дуже великих провайдерів.</string>
<string name="setup_m3u_vod_classification_label">Класифікація VOD у M3U</string>
<string name="setup_m3u_vod_classification_helper">Лише M3U. Використовуйте URL плейлиста та евристику group-title, щоб сортувати відповідні записи в Фільми замість Live TV.</string>
<string name="setup_epg_sync_mode_label">Синхронізація EPG</string>
diff --git a/app/src/main/res/values-vi/strings.xml b/app/src/main/res/values-vi/strings.xml
index c59141cf..10a17034 100644
--- a/app/src/main/res/values-vi/strings.xml
+++ b/app/src/main/res/values-vi/strings.xml
@@ -728,8 +728,6 @@
<string name="setup_advanced_options_helper">Kiểm soát cách dữ liệu hướng dẫn được tải trong quá trình thiết lập và làm mới nhà cung cấp.</string>
<string name="setup_advanced_options_show">Hiện</string>
<string name="setup_advanced_options_hide">Ẩn</string>
- <string name="setup_xtream_fast_sync_label">Đồng bộ nhanh</string>
- <string name="setup_xtream_fast_sync_helper">Chỉ dành cho Xtream. Tải trước danh mục VOD và lấy các dòng phim theo nhu cầu. Khuyến nghị cho nhà cung cấp rất lớn.</string>
<string name="setup_m3u_vod_classification_label">Phân loại VOD M3U</string>
<string name="setup_m3u_vod_classification_helper">Chỉ dành cho M3U. Dùng URL playlist và các quy tắc group-title để sắp xếp các mục phù hợp vào Phim thay vì Truyền hình trực tiếp.</string>
<string name="setup_epg_sync_mode_label">Đồng bộ EPG</string>
diff --git a/app/src/main/res/values-zh/strings.xml b/app/src/main/res/values-zh/strings.xml
index 9a96b656..60e3af29 100644
--- a/app/src/main/res/values-zh/strings.xml
+++ b/app/src/main/res/values-zh/strings.xml
@@ -728,8 +728,6 @@
<string name="setup_advanced_options_helper">控制在提供商设置和刷新期间如何获取节目指南数据。</string>
<string name="setup_advanced_options_show">显示</string>
<string name="setup_advanced_options_hide">隐藏</string>
- <string name="setup_xtream_fast_sync_label">快速同步</string>
- <string name="setup_xtream_fast_sync_helper">仅限 Xstream。首先加载 VOD 类别并按需获取电影行。推荐给非常大的提供商。</string>
<string name="setup_m3u_vod_classification_label">M3U VOD 分类</string>
<string name="setup_m3u_vod_classification_helper">仅适用于 M3U。使用播放列表 URL 和 group-title 规则将匹配项归类到电影而非直播电视。</string>
<string name="setup_epg_sync_mode_label">EPG 同步</string>
diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml
index 39998428..d41c8afc 100644
--- a/app/src/main/res/values/strings.xml
+++ b/app/src/main/res/values/strings.xml
@@ -377,8 +377,10 @@
<string name="settings_default_playback_speed">Default Playback Speed</string>
<string name="settings_audio_video_sync_default">A/V Sync Default</string>
<string name="settings_audio_video_sync_default_subtitle">Positive values delay audio relative to video.</string>
- <string name="settings_multiview_center_two_slot_layout">Center 2-Channel Multiview</string>
- <string name="settings_multiview_center_two_slot_layout_subtitle">When exactly two multiview slots are active, place them side by side in the middle of the screen instead of using the top row of the 2x2 grid.</string>
+ <string name="settings_audio_video_sync_enabled">Enable A/V Sync Adjustment</string>
+ <string name="settings_audio_video_sync_enabled_subtitle">Experimental. Turn on only if audio and video are out of sync; some devices may have playback issues.</string>
+ <string name="settings_multiview_center_two_slot_layout">Center 1-2 Channel Multiview</string>
+ <string name="settings_multiview_center_two_slot_layout_subtitle">When one or two multiview slots are active, center them on screen instead of using the default 2x2 grid.</string>
<string name="settings_media_session">System Media Session</string>
<string name="settings_media_session_subtitle">Expose playback to Android system media controls. Disable this if playback crashes on a specific device when opening the player.</string>
<string name="settings_live_timeshift">Enable Local Live Rewind</string>
@@ -577,13 +579,15 @@
<string name="settings_sync_dialog_subtitle">Choose what to refresh for this provider.</string>
<string name="settings_sync_option_all">Sync All</string>
<string name="settings_sync_option_fast">Quick Sync</string>
+ <string name="settings_sync_option_sync_now">Sync Now</string>
+ <string name="settings_sync_option_rebuild_index">Rebuild Index</string>
<string name="settings_syncing_preparing">Preparing sync...</string>
<string name="settings_syncing_section">Syncing %1$s...</string>
- <string name="settings_sync_option_tv">Sync TV</string>
- <string name="settings_sync_option_movies">Sync Movies</string>
- <string name="settings_sync_option_series">Sync Series</string>
- <string name="settings_sync_option_epg">Sync EPG</string>
- <string name="settings_sync_option_custom">Custom Sync</string>
+ <string name="settings_sync_option_tv">Live TV</string>
+ <string name="settings_sync_option_movies">Movies</string>
+ <string name="settings_sync_option_series">Series</string>
+ <string name="settings_sync_option_epg">EPG</string>
+ <string name="settings_sync_option_custom">Custom Sections</string>
<string name="settings_sync_custom_title">Custom Sync for %1$s</string>
<string name="settings_sync_custom_subtitle">Pick one or more sections to refresh.</string>
<string name="settings_sync_custom_required">Choose at least one section to sync.</string>
@@ -805,6 +809,8 @@
<string name="search_type_to_search">Type at least 2 characters to search</string>
<string name="search_no_results">No results found for \'%1$s\'</string>
<string name="search_no_results_title">No matches</string>
+ <string name="search_loading_title">Searching library...</string>
+ <string name="search_loading_subtitle">Checking indexed live TV, movies, and series.</string>
<string name="search_error_title">Search unavailable</string>
<string name="search_error_subtitle">Some results could not be loaded. Try again.</string>
<string name="search_ready_title">Search the library</string>
@@ -874,8 +880,6 @@
<string name="setup_advanced_options_helper">Control how guide data is fetched during provider setup and refresh.</string>
<string name="setup_advanced_options_show">Show</string>
<string name="setup_advanced_options_hide">Hide</string>
- <string name="setup_xtream_fast_sync_label">Fast Sync</string>
- <string name="setup_xtream_fast_sync_helper">Xtream only. Loads VOD categories first and fetches movie rows on demand. Recommended for very large providers.</string>
<string name="setup_m3u_vod_classification_label">M3U VOD Classification</string>
<string name="setup_m3u_vod_classification_helper">M3U only. Use playlist URL and group-title heuristics to sort matching entries into Movies instead of Live TV.</string>
<string name="setup_epg_sync_mode_label">EPG Sync</string>
@@ -1040,6 +1044,10 @@
<string name="player_diagnostics_video_codec">Video Codec</string>
<string name="player_diagnostics_audio_codec">Audio Codec</string>
<string name="player_diagnostics_av_offset">A/V Offset</string>
+ <string name="player_diagnostics_av_sync">A/V Sync</string>
+ <string name="player_diagnostics_av_sync_stock">Off (stock audio path)</string>
+ <string name="player_diagnostics_av_sync_custom">On (custom sync path)</string>
+ <string name="player_diagnostics_av_sync_waiting">On (waiting for playback restart)</string>
<string name="player_diagnostics_video_bitrate">Video Bitrate</string>
<string name="player_diagnostics_dropped_frames">Dropped Frames</string>
<string name="player_diagnostics_last_failure">Last Failure</string>
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 3a585dd8..e224a356 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
@@ -17,10 +17,13 @@ import com.streamvault.domain.usecase.SearchContent
import com.streamvault.domain.usecase.SearchContentResult
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.test.advanceUntilIdle
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.resetMain
+import kotlinx.coroutines.test.runCurrent
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.test.setMain
import kotlinx.coroutines.launch
@@ -133,6 +136,52 @@ class SearchViewModelTest {
collectorJob.cancel()
}
+ @Test
+ fun `ui state reports loading while search results are pending`() = runTest {
+ whenever(providerRepository.getActiveProvider()).thenReturn(
+ flowOf(
+ Provider(
+ id = 5L,
+ name = "Provider",
+ type = ProviderType.M3U,
+ serverUrl = "http://test"
+ )
+ )
+ )
+ whenever(searchContent.invoke(any(), any(), any(), any())).thenReturn(
+ flow {
+ delay(1_000)
+ emit(SearchContentResult(channels = listOf(Channel(id = 1L, name = "News", streamUrl = "http://stream", providerId = 5L))))
+ }
+ )
+
+ viewModel = SearchViewModel(
+ providerRepository,
+ searchContent,
+ preferencesRepository,
+ parentalControlManager,
+ favoriteRepository,
+ categoryRepository,
+ recordingManager
+ )
+
+ val collectorJob = backgroundScope.launch { viewModel.uiState.collect { } }
+ advanceUntilIdle()
+ viewModel.onQueryChange("news")
+ testScheduler.advanceTimeBy(400)
+ runCurrent()
+
+ assertThat(viewModel.uiState.value.isLoading).isTrue()
+ assertThat(viewModel.uiState.value.hasSearched).isTrue()
+
+ testScheduler.advanceTimeBy(1_000)
+ advanceUntilIdle()
+
+ assertThat(viewModel.uiState.value.isLoading).isFalse()
+ assertThat(viewModel.uiState.value.channels.map { it.id }).containsExactly(1L)
+ collectorJob.cancel()
+ }
+
@Test
fun `search results flow through the shared search use case`() = runTest {
whenever(providerRepository.getActiveProvider()).thenReturn(
diff --git a/data/schemas/com.streamvault.data.local.StreamVaultDatabase/48.json b/data/schemas/com.streamvault.data.local.StreamVaultDatabase/48.json
new file mode 100644
index 00000000..d99b0605
--- /dev/null
+++ b/data/schemas/com.streamvault.data.local.StreamVaultDatabase/48.json
@@ -0,0 +1,4798 @@
+{
+ "formatVersion": 1,
+ "database": {
+ "version": 48,
+ "identityHash": "c19c7c6865a5ad9c6bfe36f493cdad03",
+ "entities": [
+ {
+ "tableName": "providers",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `type` TEXT NOT NULL, `server_url` TEXT NOT NULL, `username` TEXT NOT NULL, `password` TEXT NOT NULL, `m3u_url` TEXT NOT NULL, `epg_url` TEXT NOT NULL, `stalker_mac_address` TEXT NOT NULL, `stalker_device_profile` TEXT NOT NULL, `stalker_device_timezone` TEXT NOT NULL, `stalker_device_locale` TEXT NOT NULL, `is_active` INTEGER NOT NULL, `max_connections` INTEGER NOT NULL, `expiration_date` INTEGER, `api_version` TEXT, `allowed_output_formats_json` TEXT NOT NULL, `epg_sync_mode` TEXT NOT NULL, `xtream_fast_sync_enabled` INTEGER NOT NULL, `m3u_vod_classification_enabled` INTEGER NOT NULL, `status` TEXT NOT NULL, `last_synced_at` INTEGER NOT NULL, `created_at` INTEGER NOT NULL)",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "type",
+ "columnName": "type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "serverUrl",
+ "columnName": "server_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "username",
+ "columnName": "username",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "password",
+ "columnName": "password",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "m3uUrl",
+ "columnName": "m3u_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "epgUrl",
+ "columnName": "epg_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerMacAddress",
+ "columnName": "stalker_mac_address",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerDeviceProfile",
+ "columnName": "stalker_device_profile",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerDeviceTimezone",
+ "columnName": "stalker_device_timezone",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerDeviceLocale",
+ "columnName": "stalker_device_locale",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isActive",
+ "columnName": "is_active",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "maxConnections",
+ "columnName": "max_connections",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "expirationDate",
+ "columnName": "expiration_date",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "apiVersion",
+ "columnName": "api_version",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "allowedOutputFormatsJson",
+ "columnName": "allowed_output_formats_json",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "epgSyncMode",
+ "columnName": "epg_sync_mode",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "xtreamFastSyncEnabled",
+ "columnName": "xtream_fast_sync_enabled",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "m3uVodClassificationEnabled",
+ "columnName": "m3u_vod_classification_enabled",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "status",
+ "columnName": "status",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastSyncedAt",
+ "columnName": "last_synced_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "createdAt",
+ "columnName": "created_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_providers_server_url_username_stalker_mac_address",
+ "unique": true,
+ "columnNames": [
+ "server_url",
+ "username",
+ "stalker_mac_address"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_providers_server_url_username_stalker_mac_address` ON `${TABLE_NAME}` (`server_url`, `username`, `stalker_mac_address`)"
+ }
+ ]
+ },
+ {
+ "tableName": "channels",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `stream_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `logo_url` TEXT, `group_title` TEXT, `category_id` INTEGER, `category_name` TEXT, `stream_url` TEXT NOT NULL, `epg_channel_id` TEXT, `number` INTEGER NOT NULL, `catch_up_supported` INTEGER NOT NULL, `catch_up_days` INTEGER NOT NULL, `catchUpSource` TEXT, `provider_id` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, `logical_group_id` TEXT NOT NULL, `error_count` INTEGER NOT NULL, `quality_options_json` TEXT, `sync_fingerprint` TEXT NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "streamId",
+ "columnName": "stream_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "logoUrl",
+ "columnName": "logo_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "groupTitle",
+ "columnName": "group_title",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "categoryId",
+ "columnName": "category_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "categoryName",
+ "columnName": "category_name",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "streamUrl",
+ "columnName": "stream_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "epgChannelId",
+ "columnName": "epg_channel_id",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "number",
+ "columnName": "number",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "catchUpSupported",
+ "columnName": "catch_up_supported",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "catchUpDays",
+ "columnName": "catch_up_days",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "catchUpSource",
+ "columnName": "catchUpSource",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isAdult",
+ "columnName": "is_adult",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isUserProtected",
+ "columnName": "is_user_protected",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "logicalGroupId",
+ "columnName": "logical_group_id",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "errorCount",
+ "columnName": "error_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "qualityOptionsJson",
+ "columnName": "quality_options_json",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "syncFingerprint",
+ "columnName": "sync_fingerprint",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_channels_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_channels_provider_id_category_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "category_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_provider_id_category_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`)"
+ },
+ {
+ "name": "index_channels_provider_id_stream_id",
+ "unique": true,
+ "columnNames": [
+ "provider_id",
+ "stream_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_channels_provider_id_stream_id` ON `${TABLE_NAME}` (`provider_id`, `stream_id`)"
+ },
+ {
+ "name": "index_channels_logical_group_id",
+ "unique": false,
+ "columnNames": [
+ "logical_group_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_logical_group_id` ON `${TABLE_NAME}` (`logical_group_id`)"
+ },
+ {
+ "name": "index_channels_provider_id_category_id_logical_group_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "category_id",
+ "logical_group_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_provider_id_category_id_logical_group_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`, `logical_group_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "channel_preferences",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `channel_id` INTEGER NOT NULL, `aspect_ratio` TEXT, `audio_video_offset_ms` INTEGER, `updated_at` INTEGER NOT NULL, FOREIGN KEY(`channel_id`) REFERENCES `channels`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "channelId",
+ "columnName": "channel_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "aspectRatio",
+ "columnName": "aspect_ratio",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "audioVideoOffsetMs",
+ "columnName": "audio_video_offset_ms",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "updatedAt",
+ "columnName": "updated_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_channel_preferences_channel_id",
+ "unique": true,
+ "columnNames": [
+ "channel_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_channel_preferences_channel_id` ON `${TABLE_NAME}` (`channel_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "channels",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "channel_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "channels_fts",
+ "createSql": "CREATE VIRTUAL TABLE IF NOT EXISTS `${TABLE_NAME}` USING FTS4(`name` TEXT NOT NULL, content=`channels`)",
+ "fields": [
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": []
+ },
+ "ftsVersion": "FTS4",
+ "ftsOptions": {
+ "tokenizer": "simple",
+ "tokenizerArgs": [],
+ "contentTable": "channels",
+ "languageIdColumnName": "",
+ "matchInfo": "FTS4",
+ "notIndexedColumns": [],
+ "prefixSizes": [],
+ "preferredOrder": "ASC"
+ },
+ "contentSyncTriggers": [
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_BEFORE_UPDATE BEFORE UPDATE ON `channels` BEGIN DELETE FROM `channels_fts` WHERE `docid`=OLD.`rowid`; END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_BEFORE_DELETE BEFORE DELETE ON `channels` BEGIN DELETE FROM `channels_fts` WHERE `docid`=OLD.`rowid`; END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_AFTER_UPDATE AFTER UPDATE ON `channels` BEGIN INSERT INTO `channels_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_AFTER_INSERT AFTER INSERT ON `channels` BEGIN INSERT INTO `channels_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END"
+ ]
+ },
+ {
+ "tableName": "movies",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `stream_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `poster_url` TEXT, `backdrop_url` TEXT, `category_id` INTEGER, `category_name` TEXT, `stream_url` TEXT NOT NULL, `container_extension` TEXT, `plot` TEXT, `cast` TEXT, `director` TEXT, `genre` TEXT, `release_date` TEXT, `duration` TEXT, `duration_seconds` INTEGER NOT NULL, `rating` REAL NOT NULL, `year` TEXT, `tmdb_id` INTEGER, `youtube_trailer` TEXT, `provider_id` INTEGER NOT NULL, `watch_progress` INTEGER NOT NULL, `watch_count` INTEGER NOT NULL, `last_watched_at` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, `added_at` INTEGER NOT NULL, `cache_state` TEXT NOT NULL, `detail_hydrated_at` INTEGER NOT NULL, `remote_stale_at` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "streamId",
+ "columnName": "stream_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "posterUrl",
+ "columnName": "poster_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "backdropUrl",
+ "columnName": "backdrop_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "categoryId",
+ "columnName": "category_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "categoryName",
+ "columnName": "category_name",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "streamUrl",
+ "columnName": "stream_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "containerExtension",
+ "columnName": "container_extension",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "plot",
+ "columnName": "plot",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "cast",
+ "columnName": "cast",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "director",
+ "columnName": "director",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "genre",
+ "columnName": "genre",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "releaseDate",
+ "columnName": "release_date",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "duration",
+ "columnName": "duration",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "durationSeconds",
+ "columnName": "duration_seconds",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "rating",
+ "columnName": "rating",
+ "affinity": "REAL",
+ "notNull": true
+ },
+ {
+ "fieldPath": "year",
+ "columnName": "year",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "tmdbId",
+ "columnName": "tmdb_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "youtubeTrailer",
+ "columnName": "youtube_trailer",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "watchProgress",
+ "columnName": "watch_progress",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "watchCount",
+ "columnName": "watch_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastWatchedAt",
+ "columnName": "last_watched_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isAdult",
+ "columnName": "is_adult",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isUserProtected",
+ "columnName": "is_user_protected",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "syncFingerprint",
+ "columnName": "sync_fingerprint",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "addedAt",
+ "columnName": "added_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "cacheState",
+ "columnName": "cache_state",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "detailHydratedAt",
+ "columnName": "detail_hydrated_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "remoteStaleAt",
+ "columnName": "remote_stale_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_movies_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_movies_provider_id_category_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "category_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id_category_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`)"
+ },
+ {
+ "name": "index_movies_provider_id_stream_id",
+ "unique": true,
+ "columnNames": [
+ "provider_id",
+ "stream_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_movies_provider_id_stream_id` ON `${TABLE_NAME}` (`provider_id`, `stream_id`)"
+ },
+ {
+ "name": "index_movies_provider_id_name_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "name",
+ "id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id_name_id` ON `${TABLE_NAME}` (`provider_id`, `name`, `id`)"
+ },
+ {
+ "name": "index_movies_provider_id_category_id_name_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "category_id",
+ "name",
+ "id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id_category_id_name_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`, `name`, `id`)"
+ },
+ {
+ "name": "index_movies_provider_id_rating_name_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "rating",
+ "name",
+ "id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id_rating_name_id` ON `${TABLE_NAME}` (`provider_id`, `rating`, `name`, `id`)"
+ },
+ {
+ "name": "index_movies_provider_id_added_at_release_date_name_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "added_at",
+ "release_date",
+ "name",
+ "id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id_added_at_release_date_name_id` ON `${TABLE_NAME}` (`provider_id`, `added_at`, `release_date`, `name`, `id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "movies_fts",
+ "createSql": "CREATE VIRTUAL TABLE IF NOT EXISTS `${TABLE_NAME}` USING FTS4(`name` TEXT NOT NULL, content=`movies`)",
+ "fields": [
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": []
+ },
+ "ftsVersion": "FTS4",
+ "ftsOptions": {
+ "tokenizer": "simple",
+ "tokenizerArgs": [],
+ "contentTable": "movies",
+ "languageIdColumnName": "",
+ "matchInfo": "FTS4",
+ "notIndexedColumns": [],
+ "prefixSizes": [],
+ "preferredOrder": "ASC"
+ },
+ "contentSyncTriggers": [
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_movies_fts_BEFORE_UPDATE BEFORE UPDATE ON `movies` BEGIN DELETE FROM `movies_fts` WHERE `docid`=OLD.`rowid`; END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_movies_fts_BEFORE_DELETE BEFORE DELETE ON `movies` BEGIN DELETE FROM `movies_fts` WHERE `docid`=OLD.`rowid`; END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_movies_fts_AFTER_UPDATE AFTER UPDATE ON `movies` BEGIN INSERT INTO `movies_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_movies_fts_AFTER_INSERT AFTER INSERT ON `movies` BEGIN INSERT INTO `movies_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END"
+ ]
+ },
+ {
+ "tableName": "series",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `series_id` INTEGER NOT NULL, `provider_series_id` TEXT, `name` TEXT NOT NULL, `poster_url` TEXT, `backdrop_url` TEXT, `category_id` INTEGER, `category_name` TEXT, `plot` TEXT, `cast` TEXT, `director` TEXT, `genre` TEXT, `release_date` TEXT, `rating` REAL NOT NULL, `tmdb_id` INTEGER, `youtube_trailer` TEXT, `episode_run_time` TEXT, `last_modified` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, `cache_state` TEXT NOT NULL, `detail_hydrated_at` INTEGER NOT NULL, `remote_stale_at` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "seriesId",
+ "columnName": "series_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerSeriesId",
+ "columnName": "provider_series_id",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "posterUrl",
+ "columnName": "poster_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "backdropUrl",
+ "columnName": "backdrop_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "categoryId",
+ "columnName": "category_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "categoryName",
+ "columnName": "category_name",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "plot",
+ "columnName": "plot",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "cast",
+ "columnName": "cast",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "director",
+ "columnName": "director",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "genre",
+ "columnName": "genre",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "releaseDate",
+ "columnName": "release_date",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "rating",
+ "columnName": "rating",
+ "affinity": "REAL",
+ "notNull": true
+ },
+ {
+ "fieldPath": "tmdbId",
+ "columnName": "tmdb_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "youtubeTrailer",
+ "columnName": "youtube_trailer",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "episodeRunTime",
+ "columnName": "episode_run_time",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "lastModified",
+ "columnName": "last_modified",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isAdult",
+ "columnName": "is_adult",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isUserProtected",
+ "columnName": "is_user_protected",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "syncFingerprint",
+ "columnName": "sync_fingerprint",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "cacheState",
+ "columnName": "cache_state",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "detailHydratedAt",
+ "columnName": "detail_hydrated_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "remoteStaleAt",
+ "columnName": "remote_stale_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_series_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_series_provider_id_category_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "category_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_provider_id_category_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`)"
+ },
+ {
+ "name": "index_series_provider_id_series_id",
+ "unique": true,
+ "columnNames": [
+ "provider_id",
+ "series_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_series_provider_id_series_id` ON `${TABLE_NAME}` (`provider_id`, `series_id`)"
+ },
+ {
+ "name": "index_series_provider_id_name_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "name",
+ "id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_provider_id_name_id` ON `${TABLE_NAME}` (`provider_id`, `name`, `id`)"
+ },
+ {
+ "name": "index_series_provider_id_category_id_name_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "category_id",
+ "name",
+ "id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_provider_id_category_id_name_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`, `name`, `id`)"
+ },
+ {
+ "name": "index_series_provider_id_rating_name_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "rating",
+ "name",
+ "id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_provider_id_rating_name_id` ON `${TABLE_NAME}` (`provider_id`, `rating`, `name`, `id`)"
+ },
+ {
+ "name": "index_series_provider_id_last_modified_name_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "last_modified",
+ "name",
+ "id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_provider_id_last_modified_name_id` ON `${TABLE_NAME}` (`provider_id`, `last_modified`, `name`, `id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "series_fts",
+ "createSql": "CREATE VIRTUAL TABLE IF NOT EXISTS `${TABLE_NAME}` USING FTS4(`name` TEXT NOT NULL, content=`series`)",
+ "fields": [
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": []
+ },
+ "ftsVersion": "FTS4",
+ "ftsOptions": {
+ "tokenizer": "simple",
+ "tokenizerArgs": [],
+ "contentTable": "series",
+ "languageIdColumnName": "",
+ "matchInfo": "FTS4",
+ "notIndexedColumns": [],
+ "prefixSizes": [],
+ "preferredOrder": "ASC"
+ },
+ "contentSyncTriggers": [
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_series_fts_BEFORE_UPDATE BEFORE UPDATE ON `series` BEGIN DELETE FROM `series_fts` WHERE `docid`=OLD.`rowid`; END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_series_fts_BEFORE_DELETE BEFORE DELETE ON `series` BEGIN DELETE FROM `series_fts` WHERE `docid`=OLD.`rowid`; END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_series_fts_AFTER_UPDATE AFTER UPDATE ON `series` BEGIN INSERT INTO `series_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_series_fts_AFTER_INSERT AFTER INSERT ON `series` BEGIN INSERT INTO `series_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END"
+ ]
+ },
+ {
+ "tableName": "episodes",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `episode_id` INTEGER NOT NULL, `title` TEXT NOT NULL, `episode_number` INTEGER NOT NULL, `season_number` INTEGER NOT NULL, `stream_url` TEXT NOT NULL, `container_extension` TEXT, `cover_url` TEXT, `plot` TEXT, `duration` TEXT, `duration_seconds` INTEGER NOT NULL, `rating` REAL NOT NULL, `release_date` TEXT, `series_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `watch_progress` INTEGER NOT NULL, `last_watched_at` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`series_id`) REFERENCES `series`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "episodeId",
+ "columnName": "episode_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "title",
+ "columnName": "title",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "episodeNumber",
+ "columnName": "episode_number",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "seasonNumber",
+ "columnName": "season_number",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "streamUrl",
+ "columnName": "stream_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "containerExtension",
+ "columnName": "container_extension",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "coverUrl",
+ "columnName": "cover_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "plot",
+ "columnName": "plot",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "duration",
+ "columnName": "duration",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "durationSeconds",
+ "columnName": "duration_seconds",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "rating",
+ "columnName": "rating",
+ "affinity": "REAL",
+ "notNull": true
+ },
+ {
+ "fieldPath": "releaseDate",
+ "columnName": "release_date",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "seriesId",
+ "columnName": "series_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "watchProgress",
+ "columnName": "watch_progress",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastWatchedAt",
+ "columnName": "last_watched_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isAdult",
+ "columnName": "is_adult",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isUserProtected",
+ "columnName": "is_user_protected",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_episodes_series_id",
+ "unique": false,
+ "columnNames": [
+ "series_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_episodes_series_id` ON `${TABLE_NAME}` (`series_id`)"
+ },
+ {
+ "name": "index_episodes_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_episodes_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_episodes_provider_id_episode_id",
+ "unique": true,
+ "columnNames": [
+ "provider_id",
+ "episode_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_episodes_provider_id_episode_id` ON `${TABLE_NAME}` (`provider_id`, `episode_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ },
+ {
+ "table": "series",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "series_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "categories",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `category_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `parent_id` INTEGER, `type` TEXT NOT NULL, `provider_id` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "categoryId",
+ "columnName": "category_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "parentId",
+ "columnName": "parent_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "type",
+ "columnName": "type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isAdult",
+ "columnName": "is_adult",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isUserProtected",
+ "columnName": "is_user_protected",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "syncFingerprint",
+ "columnName": "sync_fingerprint",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_categories_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_categories_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_categories_provider_id_type",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "type"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_categories_provider_id_type` ON `${TABLE_NAME}` (`provider_id`, `type`)"
+ },
+ {
+ "name": "index_categories_provider_id_category_id_type",
+ "unique": true,
+ "columnNames": [
+ "provider_id",
+ "category_id",
+ "type"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_categories_provider_id_category_id_type` ON `${TABLE_NAME}` (`provider_id`, `category_id`, `type`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "channel_import_stage",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`session_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `stream_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `logo_url` TEXT, `group_title` TEXT, `category_id` INTEGER, `category_name` TEXT, `stream_url` TEXT NOT NULL, `epg_channel_id` TEXT, `number` INTEGER NOT NULL, `catch_up_supported` INTEGER NOT NULL, `catch_up_days` INTEGER NOT NULL, `catchUpSource` TEXT, `is_adult` INTEGER NOT NULL, `logical_group_id` TEXT NOT NULL, `error_count` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, PRIMARY KEY(`session_id`, `provider_id`, `stream_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "sessionId",
+ "columnName": "session_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "streamId",
+ "columnName": "stream_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "logoUrl",
+ "columnName": "logo_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "groupTitle",
+ "columnName": "group_title",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "categoryId",
+ "columnName": "category_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "categoryName",
+ "columnName": "category_name",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "streamUrl",
+ "columnName": "stream_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "epgChannelId",
+ "columnName": "epg_channel_id",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "number",
+ "columnName": "number",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "catchUpSupported",
+ "columnName": "catch_up_supported",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "catchUpDays",
+ "columnName": "catch_up_days",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "catchUpSource",
+ "columnName": "catchUpSource",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "isAdult",
+ "columnName": "is_adult",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "logicalGroupId",
+ "columnName": "logical_group_id",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "errorCount",
+ "columnName": "error_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "syncFingerprint",
+ "columnName": "sync_fingerprint",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "session_id",
+ "provider_id",
+ "stream_id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_channel_import_stage_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channel_import_stage_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_channel_import_stage_session_id_provider_id",
+ "unique": false,
+ "columnNames": [
+ "session_id",
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channel_import_stage_session_id_provider_id` ON `${TABLE_NAME}` (`session_id`, `provider_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "movie_import_stage",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`session_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `stream_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `poster_url` TEXT, `backdrop_url` TEXT, `category_id` INTEGER, `category_name` TEXT, `stream_url` TEXT NOT NULL, `container_extension` TEXT, `plot` TEXT, `cast` TEXT, `director` TEXT, `genre` TEXT, `release_date` TEXT, `duration` TEXT, `duration_seconds` INTEGER NOT NULL, `rating` REAL NOT NULL, `year` TEXT, `tmdb_id` INTEGER, `youtube_trailer` TEXT, `is_adult` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, `added_at` INTEGER NOT NULL, PRIMARY KEY(`session_id`, `provider_id`, `stream_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "sessionId",
+ "columnName": "session_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "streamId",
+ "columnName": "stream_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "posterUrl",
+ "columnName": "poster_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "backdropUrl",
+ "columnName": "backdrop_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "categoryId",
+ "columnName": "category_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "categoryName",
+ "columnName": "category_name",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "streamUrl",
+ "columnName": "stream_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "containerExtension",
+ "columnName": "container_extension",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "plot",
+ "columnName": "plot",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "cast",
+ "columnName": "cast",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "director",
+ "columnName": "director",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "genre",
+ "columnName": "genre",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "releaseDate",
+ "columnName": "release_date",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "duration",
+ "columnName": "duration",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "durationSeconds",
+ "columnName": "duration_seconds",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "rating",
+ "columnName": "rating",
+ "affinity": "REAL",
+ "notNull": true
+ },
+ {
+ "fieldPath": "year",
+ "columnName": "year",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "tmdbId",
+ "columnName": "tmdb_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "youtubeTrailer",
+ "columnName": "youtube_trailer",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "isAdult",
+ "columnName": "is_adult",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "syncFingerprint",
+ "columnName": "sync_fingerprint",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "addedAt",
+ "columnName": "added_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "session_id",
+ "provider_id",
+ "stream_id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_movie_import_stage_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movie_import_stage_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_movie_import_stage_session_id_provider_id",
+ "unique": false,
+ "columnNames": [
+ "session_id",
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movie_import_stage_session_id_provider_id` ON `${TABLE_NAME}` (`session_id`, `provider_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "series_import_stage",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`session_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `series_id` INTEGER NOT NULL, `provider_series_id` TEXT, `provider_series_key` TEXT NOT NULL, `name` TEXT NOT NULL, `poster_url` TEXT, `backdrop_url` TEXT, `category_id` INTEGER, `category_name` TEXT, `plot` TEXT, `cast` TEXT, `director` TEXT, `genre` TEXT, `release_date` TEXT, `rating` REAL NOT NULL, `tmdb_id` INTEGER, `youtube_trailer` TEXT, `episode_run_time` TEXT, `last_modified` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, PRIMARY KEY(`session_id`, `provider_id`, `provider_series_key`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "sessionId",
+ "columnName": "session_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "seriesId",
+ "columnName": "series_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerSeriesId",
+ "columnName": "provider_series_id",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "providerSeriesKey",
+ "columnName": "provider_series_key",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "posterUrl",
+ "columnName": "poster_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "backdropUrl",
+ "columnName": "backdrop_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "categoryId",
+ "columnName": "category_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "categoryName",
+ "columnName": "category_name",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "plot",
+ "columnName": "plot",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "cast",
+ "columnName": "cast",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "director",
+ "columnName": "director",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "genre",
+ "columnName": "genre",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "releaseDate",
+ "columnName": "release_date",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "rating",
+ "columnName": "rating",
+ "affinity": "REAL",
+ "notNull": true
+ },
+ {
+ "fieldPath": "tmdbId",
+ "columnName": "tmdb_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "youtubeTrailer",
+ "columnName": "youtube_trailer",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "episodeRunTime",
+ "columnName": "episode_run_time",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "lastModified",
+ "columnName": "last_modified",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isAdult",
+ "columnName": "is_adult",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "syncFingerprint",
+ "columnName": "sync_fingerprint",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "session_id",
+ "provider_id",
+ "provider_series_key"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_series_import_stage_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_import_stage_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_series_import_stage_session_id_provider_id",
+ "unique": false,
+ "columnNames": [
+ "session_id",
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_import_stage_session_id_provider_id` ON `${TABLE_NAME}` (`session_id`, `provider_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "category_import_stage",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`session_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `category_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `parent_id` INTEGER, `type` TEXT NOT NULL, `is_adult` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, PRIMARY KEY(`session_id`, `provider_id`, `category_id`, `type`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "sessionId",
+ "columnName": "session_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "categoryId",
+ "columnName": "category_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "parentId",
+ "columnName": "parent_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "type",
+ "columnName": "type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isAdult",
+ "columnName": "is_adult",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "syncFingerprint",
+ "columnName": "sync_fingerprint",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "session_id",
+ "provider_id",
+ "category_id",
+ "type"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_category_import_stage_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_category_import_stage_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_category_import_stage_session_id_provider_id",
+ "unique": false,
+ "columnNames": [
+ "session_id",
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_category_import_stage_session_id_provider_id` ON `${TABLE_NAME}` (`session_id`, `provider_id`)"
+ },
+ {
+ "name": "index_category_import_stage_provider_id_type",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "type"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_category_import_stage_provider_id_type` ON `${TABLE_NAME}` (`provider_id`, `type`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "programs",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `channel_id` TEXT NOT NULL, `title` TEXT NOT NULL, `description` TEXT NOT NULL, `start_time` INTEGER NOT NULL, `end_time` INTEGER NOT NULL, `lang` TEXT NOT NULL, `rating` TEXT, `image_url` TEXT, `genre` TEXT, `category` TEXT, `has_archive` INTEGER NOT NULL)",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "channelId",
+ "columnName": "channel_id",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "title",
+ "columnName": "title",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "description",
+ "columnName": "description",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "startTime",
+ "columnName": "start_time",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "endTime",
+ "columnName": "end_time",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lang",
+ "columnName": "lang",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "rating",
+ "columnName": "rating",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "imageUrl",
+ "columnName": "image_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "genre",
+ "columnName": "genre",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "category",
+ "columnName": "category",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "hasArchive",
+ "columnName": "has_archive",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_programs_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_programs_provider_id_channel_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "channel_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_channel_id` ON `${TABLE_NAME}` (`provider_id`, `channel_id`)"
+ },
+ {
+ "name": "index_programs_provider_id_end_time_channel_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "end_time",
+ "channel_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_end_time_channel_id` ON `${TABLE_NAME}` (`provider_id`, `end_time`, `channel_id`)"
+ },
+ {
+ "name": "index_programs_provider_id_start_time_end_time",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "start_time",
+ "end_time"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_start_time_end_time` ON `${TABLE_NAME}` (`provider_id`, `start_time`, `end_time`)"
+ },
+ {
+ "name": "index_programs_start_time",
+ "unique": false,
+ "columnNames": [
+ "start_time"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_start_time` ON `${TABLE_NAME}` (`start_time`)"
+ },
+ {
+ "name": "index_programs_provider_id_channel_id_start_time",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "channel_id",
+ "start_time"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_channel_id_start_time` ON `${TABLE_NAME}` (`provider_id`, `channel_id`, `start_time`)"
+ },
+ {
+ "name": "index_programs_provider_id_channel_id_start_time_end_time",
+ "unique": true,
+ "columnNames": [
+ "provider_id",
+ "channel_id",
+ "start_time",
+ "end_time"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_programs_provider_id_channel_id_start_time_end_time` ON `${TABLE_NAME}` (`provider_id`, `channel_id`, `start_time`, `end_time`)"
+ }
+ ]
+ },
+ {
+ "tableName": "favorites",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `content_id` INTEGER NOT NULL, `content_type` TEXT NOT NULL, `position` INTEGER NOT NULL, `group_id` INTEGER, `group_key` INTEGER NOT NULL, `added_at` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`group_id`) REFERENCES `virtual_groups`(`id`) ON UPDATE NO ACTION ON DELETE SET NULL )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "contentId",
+ "columnName": "content_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "contentType",
+ "columnName": "content_type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "position",
+ "columnName": "position",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "groupId",
+ "columnName": "group_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "groupKey",
+ "columnName": "group_key",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "addedAt",
+ "columnName": "added_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_favorites_provider_id_content_id_content_type_group_key",
+ "unique": true,
+ "columnNames": [
+ "provider_id",
+ "content_id",
+ "content_type",
+ "group_key"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_favorites_provider_id_content_id_content_type_group_key` ON `${TABLE_NAME}` (`provider_id`, `content_id`, `content_type`, `group_key`)"
+ },
+ {
+ "name": "index_favorites_provider_id_content_type_group_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "content_type",
+ "group_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_favorites_provider_id_content_type_group_id` ON `${TABLE_NAME}` (`provider_id`, `content_type`, `group_id`)"
+ },
+ {
+ "name": "index_favorites_group_id_position",
+ "unique": false,
+ "columnNames": [
+ "group_id",
+ "position"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_favorites_group_id_position` ON `${TABLE_NAME}` (`group_id`, `position`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ },
+ {
+ "table": "virtual_groups",
+ "onDelete": "SET NULL",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "group_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "virtual_groups",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `icon_emoji` TEXT, `position` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `content_type` TEXT NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "iconEmoji",
+ "columnName": "icon_emoji",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "position",
+ "columnName": "position",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "createdAt",
+ "columnName": "created_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "contentType",
+ "columnName": "content_type",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_virtual_groups_provider_id_content_type",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "content_type"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_virtual_groups_provider_id_content_type` ON `${TABLE_NAME}` (`provider_id`, `content_type`)"
+ },
+ {
+ "name": "index_virtual_groups_position",
+ "unique": false,
+ "columnNames": [
+ "position"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_virtual_groups_position` ON `${TABLE_NAME}` (`position`)"
+ },
+ {
+ "name": "index_virtual_groups_content_type",
+ "unique": false,
+ "columnNames": [
+ "content_type"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_virtual_groups_content_type` ON `${TABLE_NAME}` (`content_type`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "playback_history",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `content_id` INTEGER NOT NULL, `content_type` TEXT NOT NULL, `provider_id` INTEGER NOT NULL, `title` TEXT NOT NULL, `poster_url` TEXT, `stream_url` TEXT NOT NULL, `resume_position_ms` INTEGER NOT NULL, `total_duration_ms` INTEGER NOT NULL, `last_watched_at` INTEGER NOT NULL, `watch_count` INTEGER NOT NULL, `watched_status` TEXT NOT NULL, `series_id` INTEGER, `season_number` INTEGER, `episode_number` INTEGER, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "contentId",
+ "columnName": "content_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "contentType",
+ "columnName": "content_type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "title",
+ "columnName": "title",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "posterUrl",
+ "columnName": "poster_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "streamUrl",
+ "columnName": "stream_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "resumePositionMs",
+ "columnName": "resume_position_ms",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "totalDurationMs",
+ "columnName": "total_duration_ms",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastWatchedAt",
+ "columnName": "last_watched_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "watchCount",
+ "columnName": "watch_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "watchedStatus",
+ "columnName": "watched_status",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "seriesId",
+ "columnName": "series_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "seasonNumber",
+ "columnName": "season_number",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "episodeNumber",
+ "columnName": "episode_number",
+ "affinity": "INTEGER"
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_playback_history_content_id_content_type_provider_id",
+ "unique": true,
+ "columnNames": [
+ "content_id",
+ "content_type",
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_playback_history_content_id_content_type_provider_id` ON `${TABLE_NAME}` (`content_id`, `content_type`, `provider_id`)"
+ },
+ {
+ "name": "index_playback_history_last_watched_at",
+ "unique": false,
+ "columnNames": [
+ "last_watched_at"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_history_last_watched_at` ON `${TABLE_NAME}` (`last_watched_at`)"
+ },
+ {
+ "name": "index_playback_history_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_history_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_playback_history_provider_id_content_type_content_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "content_type",
+ "content_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_history_provider_id_content_type_content_id` ON `${TABLE_NAME}` (`provider_id`, `content_type`, `content_id`)"
+ },
+ {
+ "name": "index_playback_history_provider_id_content_type_last_watched_at",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "content_type",
+ "last_watched_at"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_history_provider_id_content_type_last_watched_at` ON `${TABLE_NAME}` (`provider_id`, `content_type`, `last_watched_at`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "tmdb_identity",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`tmdb_id` INTEGER NOT NULL, `content_type` TEXT NOT NULL, `canonical_provider_id` INTEGER NOT NULL, `first_seen_at` INTEGER NOT NULL, PRIMARY KEY(`tmdb_id`, `content_type`), FOREIGN KEY(`canonical_provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "tmdbId",
+ "columnName": "tmdb_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "contentType",
+ "columnName": "content_type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "canonicalProviderId",
+ "columnName": "canonical_provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "firstSeenAt",
+ "columnName": "first_seen_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "tmdb_id",
+ "content_type"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_tmdb_identity_content_type",
+ "unique": false,
+ "columnNames": [
+ "content_type"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_tmdb_identity_content_type` ON `${TABLE_NAME}` (`content_type`)"
+ },
+ {
+ "name": "index_tmdb_identity_canonical_provider_id",
+ "unique": false,
+ "columnNames": [
+ "canonical_provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_tmdb_identity_canonical_provider_id` ON `${TABLE_NAME}` (`canonical_provider_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "canonical_provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "search_history",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `query` TEXT NOT NULL, `content_scope` TEXT NOT NULL, `provider_id` INTEGER NOT NULL, `used_at` INTEGER NOT NULL, `use_count` INTEGER NOT NULL)",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "query",
+ "columnName": "query",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "contentScope",
+ "columnName": "content_scope",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "usedAt",
+ "columnName": "used_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "useCount",
+ "columnName": "use_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_search_history_content_scope_provider_id_used_at",
+ "unique": false,
+ "columnNames": [
+ "content_scope",
+ "provider_id",
+ "used_at"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_search_history_content_scope_provider_id_used_at` ON `${TABLE_NAME}` (`content_scope`, `provider_id`, `used_at`)"
+ },
+ {
+ "name": "index_search_history_used_at",
+ "unique": false,
+ "columnNames": [
+ "used_at"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_search_history_used_at` ON `${TABLE_NAME}` (`used_at`)"
+ },
+ {
+ "name": "index_search_history_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_search_history_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_search_history_query_content_scope_provider_id",
+ "unique": true,
+ "columnNames": [
+ "query",
+ "content_scope",
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_search_history_query_content_scope_provider_id` ON `${TABLE_NAME}` (`query`, `content_scope`, `provider_id`)"
+ }
+ ]
+ },
+ {
+ "tableName": "sync_metadata",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `last_live_sync` INTEGER NOT NULL, `last_live_success` INTEGER NOT NULL, `last_movie_sync` INTEGER NOT NULL, `last_series_sync` INTEGER NOT NULL, `last_series_success` INTEGER NOT NULL, `last_epg_sync` INTEGER NOT NULL, `last_epg_success` INTEGER NOT NULL, `last_movie_attempt` INTEGER NOT NULL, `last_movie_success` INTEGER NOT NULL, `last_movie_partial` INTEGER NOT NULL, `live_count` INTEGER NOT NULL, `movie_count` INTEGER NOT NULL, `series_count` INTEGER NOT NULL, `epg_count` INTEGER NOT NULL, `last_sync_status` TEXT NOT NULL, `movie_sync_mode` TEXT NOT NULL, `movie_warnings_count` INTEGER NOT NULL, `movie_catalog_stale` INTEGER NOT NULL, `live_avoid_full_until` INTEGER NOT NULL, `movie_avoid_full_until` INTEGER NOT NULL, `series_avoid_full_until` INTEGER NOT NULL, `live_sequential_failures_remembered` INTEGER NOT NULL, `live_healthy_sync_streak` INTEGER NOT NULL, `movie_parallel_failures_remembered` INTEGER NOT NULL, `movie_healthy_sync_streak` INTEGER NOT NULL, `series_sequential_failures_remembered` INTEGER NOT NULL, `series_healthy_sync_streak` INTEGER NOT NULL, PRIMARY KEY(`provider_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastLiveSync",
+ "columnName": "last_live_sync",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastLiveSuccess",
+ "columnName": "last_live_success",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastMovieSync",
+ "columnName": "last_movie_sync",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastSeriesSync",
+ "columnName": "last_series_sync",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastSeriesSuccess",
+ "columnName": "last_series_success",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastEpgSync",
+ "columnName": "last_epg_sync",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastEpgSuccess",
+ "columnName": "last_epg_success",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastMovieAttempt",
+ "columnName": "last_movie_attempt",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastMovieSuccess",
+ "columnName": "last_movie_success",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastMoviePartial",
+ "columnName": "last_movie_partial",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "liveCount",
+ "columnName": "live_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "movieCount",
+ "columnName": "movie_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "seriesCount",
+ "columnName": "series_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "epgCount",
+ "columnName": "epg_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastSyncStatus",
+ "columnName": "last_sync_status",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "movieSyncMode",
+ "columnName": "movie_sync_mode",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "movieWarningsCount",
+ "columnName": "movie_warnings_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "movieCatalogStale",
+ "columnName": "movie_catalog_stale",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "liveAvoidFullUntil",
+ "columnName": "live_avoid_full_until",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "movieAvoidFullUntil",
+ "columnName": "movie_avoid_full_until",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "seriesAvoidFullUntil",
+ "columnName": "series_avoid_full_until",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "liveSequentialFailuresRemembered",
+ "columnName": "live_sequential_failures_remembered",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "liveHealthySyncStreak",
+ "columnName": "live_healthy_sync_streak",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "movieParallelFailuresRemembered",
+ "columnName": "movie_parallel_failures_remembered",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "movieHealthySyncStreak",
+ "columnName": "movie_healthy_sync_streak",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "seriesSequentialFailuresRemembered",
+ "columnName": "series_sequential_failures_remembered",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "seriesHealthySyncStreak",
+ "columnName": "series_healthy_sync_streak",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "provider_id"
+ ]
+ },
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "movie_category_hydration",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `category_id` INTEGER NOT NULL, `last_hydrated_at` INTEGER NOT NULL, `item_count` INTEGER NOT NULL, `last_status` TEXT NOT NULL, `last_error` TEXT, `last_loaded_page` INTEGER NOT NULL, `total_pages` INTEGER NOT NULL, `is_complete` INTEGER NOT NULL, `page_size` INTEGER NOT NULL, PRIMARY KEY(`provider_id`, `category_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "categoryId",
+ "columnName": "category_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastHydratedAt",
+ "columnName": "last_hydrated_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "itemCount",
+ "columnName": "item_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastStatus",
+ "columnName": "last_status",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastError",
+ "columnName": "last_error",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "lastLoadedPage",
+ "columnName": "last_loaded_page",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "totalPages",
+ "columnName": "total_pages",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isComplete",
+ "columnName": "is_complete",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "pageSize",
+ "columnName": "page_size",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "provider_id",
+ "category_id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_movie_category_hydration_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movie_category_hydration_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "series_category_hydration",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `category_id` INTEGER NOT NULL, `last_hydrated_at` INTEGER NOT NULL, `item_count` INTEGER NOT NULL, `last_status` TEXT NOT NULL, `last_error` TEXT, `last_loaded_page` INTEGER NOT NULL, `total_pages` INTEGER NOT NULL, `is_complete` INTEGER NOT NULL, `page_size` INTEGER NOT NULL, PRIMARY KEY(`provider_id`, `category_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "categoryId",
+ "columnName": "category_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastHydratedAt",
+ "columnName": "last_hydrated_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "itemCount",
+ "columnName": "item_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastStatus",
+ "columnName": "last_status",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastError",
+ "columnName": "last_error",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "lastLoadedPage",
+ "columnName": "last_loaded_page",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "totalPages",
+ "columnName": "total_pages",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isComplete",
+ "columnName": "is_complete",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "pageSize",
+ "columnName": "page_size",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "provider_id",
+ "category_id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_series_category_hydration_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_category_hydration_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "epg_sources",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `url` TEXT NOT NULL, `enabled` INTEGER NOT NULL, `last_refresh_at` INTEGER NOT NULL, `last_success_at` INTEGER NOT NULL, `last_error` TEXT, `priority` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, `etag` TEXT, `last_modified_header` TEXT)",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "url",
+ "columnName": "url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "enabled",
+ "columnName": "enabled",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastRefreshAt",
+ "columnName": "last_refresh_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastSuccessAt",
+ "columnName": "last_success_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastError",
+ "columnName": "last_error",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "priority",
+ "columnName": "priority",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "createdAt",
+ "columnName": "created_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "updatedAt",
+ "columnName": "updated_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "etag",
+ "columnName": "etag",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "lastModifiedHeader",
+ "columnName": "last_modified_header",
+ "affinity": "TEXT"
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_epg_sources_url",
+ "unique": true,
+ "columnNames": [
+ "url"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_epg_sources_url` ON `${TABLE_NAME}` (`url`)"
+ }
+ ]
+ },
+ {
+ "tableName": "provider_epg_sources",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `epg_source_id` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `enabled` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`epg_source_id`) REFERENCES `epg_sources`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "epgSourceId",
+ "columnName": "epg_source_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "priority",
+ "columnName": "priority",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "enabled",
+ "columnName": "enabled",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_provider_epg_sources_provider_id_epg_source_id",
+ "unique": true,
+ "columnNames": [
+ "provider_id",
+ "epg_source_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_provider_epg_sources_provider_id_epg_source_id` ON `${TABLE_NAME}` (`provider_id`, `epg_source_id`)"
+ },
+ {
+ "name": "index_provider_epg_sources_epg_source_id",
+ "unique": false,
+ "columnNames": [
+ "epg_source_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_provider_epg_sources_epg_source_id` ON `${TABLE_NAME}` (`epg_source_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ },
+ {
+ "table": "epg_sources",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "epg_source_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "epg_channels",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `epg_source_id` INTEGER NOT NULL, `xmltv_channel_id` TEXT NOT NULL, `display_name` TEXT NOT NULL, `normalized_name` TEXT NOT NULL, `icon_url` TEXT, FOREIGN KEY(`epg_source_id`) REFERENCES `epg_sources`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "epgSourceId",
+ "columnName": "epg_source_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "xmltvChannelId",
+ "columnName": "xmltv_channel_id",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "displayName",
+ "columnName": "display_name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "normalizedName",
+ "columnName": "normalized_name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "iconUrl",
+ "columnName": "icon_url",
+ "affinity": "TEXT"
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_epg_channels_epg_source_id_xmltv_channel_id",
+ "unique": true,
+ "columnNames": [
+ "epg_source_id",
+ "xmltv_channel_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_epg_channels_epg_source_id_xmltv_channel_id` ON `${TABLE_NAME}` (`epg_source_id`, `xmltv_channel_id`)"
+ },
+ {
+ "name": "index_epg_channels_epg_source_id",
+ "unique": false,
+ "columnNames": [
+ "epg_source_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_channels_epg_source_id` ON `${TABLE_NAME}` (`epg_source_id`)"
+ },
+ {
+ "name": "index_epg_channels_normalized_name",
+ "unique": false,
+ "columnNames": [
+ "normalized_name"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_channels_normalized_name` ON `${TABLE_NAME}` (`normalized_name`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "epg_sources",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "epg_source_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "epg_programmes",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `epg_source_id` INTEGER NOT NULL, `xmltv_channel_id` TEXT NOT NULL, `start_time` INTEGER NOT NULL, `end_time` INTEGER NOT NULL, `title` TEXT NOT NULL, `subtitle` TEXT, `description` TEXT NOT NULL, `category` TEXT, `lang` TEXT NOT NULL, `rating` TEXT, `image_url` TEXT, `episode_info` TEXT, FOREIGN KEY(`epg_source_id`) REFERENCES `epg_sources`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "epgSourceId",
+ "columnName": "epg_source_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "xmltvChannelId",
+ "columnName": "xmltv_channel_id",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "startTime",
+ "columnName": "start_time",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "endTime",
+ "columnName": "end_time",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "title",
+ "columnName": "title",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "subtitle",
+ "columnName": "subtitle",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "description",
+ "columnName": "description",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "category",
+ "columnName": "category",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "lang",
+ "columnName": "lang",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "rating",
+ "columnName": "rating",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "imageUrl",
+ "columnName": "image_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "episodeInfo",
+ "columnName": "episode_info",
+ "affinity": "TEXT"
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_epg_programmes_epg_source_id_xmltv_channel_id_start_time",
+ "unique": false,
+ "columnNames": [
+ "epg_source_id",
+ "xmltv_channel_id",
+ "start_time"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_programmes_epg_source_id_xmltv_channel_id_start_time` ON `${TABLE_NAME}` (`epg_source_id`, `xmltv_channel_id`, `start_time`)"
+ },
+ {
+ "name": "index_epg_programmes_epg_source_id_xmltv_channel_id_start_time_end_time",
+ "unique": true,
+ "columnNames": [
+ "epg_source_id",
+ "xmltv_channel_id",
+ "start_time",
+ "end_time"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_epg_programmes_epg_source_id_xmltv_channel_id_start_time_end_time` ON `${TABLE_NAME}` (`epg_source_id`, `xmltv_channel_id`, `start_time`, `end_time`)"
+ },
+ {
+ "name": "index_epg_programmes_epg_source_id",
+ "unique": false,
+ "columnNames": [
+ "epg_source_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_programmes_epg_source_id` ON `${TABLE_NAME}` (`epg_source_id`)"
+ },
+ {
+ "name": "index_epg_programmes_start_time",
+ "unique": false,
+ "columnNames": [
+ "start_time"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_programmes_start_time` ON `${TABLE_NAME}` (`start_time`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "epg_sources",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "epg_source_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "channel_epg_mappings",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_channel_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `source_type` TEXT NOT NULL, `epg_source_id` INTEGER, `xmltv_channel_id` TEXT, `match_type` TEXT, `confidence` REAL NOT NULL, `matched_at` INTEGER NOT NULL, `failed_attempts` INTEGER NOT NULL, `source` TEXT, `is_manual_override` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerChannelId",
+ "columnName": "provider_channel_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "sourceType",
+ "columnName": "source_type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "epgSourceId",
+ "columnName": "epg_source_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "xmltvChannelId",
+ "columnName": "xmltv_channel_id",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "matchType",
+ "columnName": "match_type",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "confidence",
+ "columnName": "confidence",
+ "affinity": "REAL",
+ "notNull": true
+ },
+ {
+ "fieldPath": "matchedAt",
+ "columnName": "matched_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "failedAttempts",
+ "columnName": "failed_attempts",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "source",
+ "columnName": "source",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "isManualOverride",
+ "columnName": "is_manual_override",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "updatedAt",
+ "columnName": "updated_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_channel_epg_mappings_provider_id_provider_channel_id",
+ "unique": true,
+ "columnNames": [
+ "provider_id",
+ "provider_channel_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_channel_epg_mappings_provider_id_provider_channel_id` ON `${TABLE_NAME}` (`provider_id`, `provider_channel_id`)"
+ },
+ {
+ "name": "index_channel_epg_mappings_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channel_epg_mappings_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "combined_m3u_profiles",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `enabled` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL)",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "enabled",
+ "columnName": "enabled",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "createdAt",
+ "columnName": "created_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "updatedAt",
+ "columnName": "updated_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ }
+ },
+ {
+ "tableName": "combined_m3u_profile_members",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `profile_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `enabled` INTEGER NOT NULL, FOREIGN KEY(`profile_id`) REFERENCES `combined_m3u_profiles`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "profileId",
+ "columnName": "profile_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "priority",
+ "columnName": "priority",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "enabled",
+ "columnName": "enabled",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_combined_m3u_profile_members_profile_id",
+ "unique": false,
+ "columnNames": [
+ "profile_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_combined_m3u_profile_members_profile_id` ON `${TABLE_NAME}` (`profile_id`)"
+ },
+ {
+ "name": "index_combined_m3u_profile_members_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_combined_m3u_profile_members_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_combined_m3u_profile_members_profile_id_provider_id",
+ "unique": true,
+ "columnNames": [
+ "profile_id",
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_combined_m3u_profile_members_profile_id_provider_id` ON `${TABLE_NAME}` (`profile_id`, `provider_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "combined_m3u_profiles",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "profile_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ },
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "recording_schedules",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, `channel_name` TEXT NOT NULL, `stream_url` TEXT NOT NULL, `program_title` TEXT, `requested_start_ms` INTEGER NOT NULL, `requested_end_ms` INTEGER NOT NULL, `recurrence` TEXT NOT NULL, `recurring_rule_id` TEXT, `enabled` INTEGER NOT NULL, `is_manual` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "channelId",
+ "columnName": "channel_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "channelName",
+ "columnName": "channel_name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "streamUrl",
+ "columnName": "stream_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "programTitle",
+ "columnName": "program_title",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "requestedStartMs",
+ "columnName": "requested_start_ms",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "requestedEndMs",
+ "columnName": "requested_end_ms",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "recurrence",
+ "columnName": "recurrence",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "recurringRuleId",
+ "columnName": "recurring_rule_id",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "enabled",
+ "columnName": "enabled",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isManual",
+ "columnName": "is_manual",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "priority",
+ "columnName": "priority",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "createdAt",
+ "columnName": "created_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "updatedAt",
+ "columnName": "updated_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_recording_schedules_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_schedules_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_recording_schedules_enabled_requested_start_ms",
+ "unique": false,
+ "columnNames": [
+ "enabled",
+ "requested_start_ms"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_schedules_enabled_requested_start_ms` ON `${TABLE_NAME}` (`enabled`, `requested_start_ms`)"
+ },
+ {
+ "name": "index_recording_schedules_recurring_rule_id",
+ "unique": false,
+ "columnNames": [
+ "recurring_rule_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_schedules_recurring_rule_id` ON `${TABLE_NAME}` (`recurring_rule_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "recording_runs",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `schedule_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, `channel_name` TEXT NOT NULL, `stream_url` TEXT NOT NULL, `program_title` TEXT, `scheduled_start_ms` INTEGER NOT NULL, `scheduled_end_ms` INTEGER NOT NULL, `recurrence` TEXT NOT NULL, `recurring_rule_id` TEXT, `status` TEXT NOT NULL, `source_type` TEXT NOT NULL, `resolved_url` TEXT, `headers_json` TEXT NOT NULL, `user_agent` TEXT, `expiration_time` INTEGER, `provider_label` TEXT, `output_uri` TEXT, `output_display_path` TEXT, `bytes_written` INTEGER NOT NULL, `average_throughput_bps` INTEGER NOT NULL, `retry_count` INTEGER NOT NULL, `last_progress_at_ms` INTEGER, `failure_category` TEXT NOT NULL, `failure_reason` TEXT, `terminal_at_ms` INTEGER, `started_at_ms` INTEGER, `ended_at_ms` INTEGER, `schedule_enabled` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `alarm_start_at_ms` INTEGER, `alarm_stop_at_ms` INTEGER, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`schedule_id`) REFERENCES `recording_schedules`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "scheduleId",
+ "columnName": "schedule_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "channelId",
+ "columnName": "channel_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "channelName",
+ "columnName": "channel_name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "streamUrl",
+ "columnName": "stream_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "programTitle",
+ "columnName": "program_title",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "scheduledStartMs",
+ "columnName": "scheduled_start_ms",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "scheduledEndMs",
+ "columnName": "scheduled_end_ms",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "recurrence",
+ "columnName": "recurrence",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "recurringRuleId",
+ "columnName": "recurring_rule_id",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "status",
+ "columnName": "status",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "sourceType",
+ "columnName": "source_type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "resolvedUrl",
+ "columnName": "resolved_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "headersJson",
+ "columnName": "headers_json",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "userAgent",
+ "columnName": "user_agent",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "expirationTime",
+ "columnName": "expiration_time",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "providerLabel",
+ "columnName": "provider_label",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "outputUri",
+ "columnName": "output_uri",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "outputDisplayPath",
+ "columnName": "output_display_path",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "bytesWritten",
+ "columnName": "bytes_written",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "averageThroughputBytesPerSecond",
+ "columnName": "average_throughput_bps",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "retryCount",
+ "columnName": "retry_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastProgressAtMs",
+ "columnName": "last_progress_at_ms",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "failureCategory",
+ "columnName": "failure_category",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "failureReason",
+ "columnName": "failure_reason",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "terminalAtMs",
+ "columnName": "terminal_at_ms",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "startedAtMs",
+ "columnName": "started_at_ms",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "endedAtMs",
+ "columnName": "ended_at_ms",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "scheduleEnabled",
+ "columnName": "schedule_enabled",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "priority",
+ "columnName": "priority",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "alarmStartAtMs",
+ "columnName": "alarm_start_at_ms",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "alarmStopAtMs",
+ "columnName": "alarm_stop_at_ms",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "createdAt",
+ "columnName": "created_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "updatedAt",
+ "columnName": "updated_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_recording_runs_schedule_id",
+ "unique": false,
+ "columnNames": [
+ "schedule_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_schedule_id` ON `${TABLE_NAME}` (`schedule_id`)"
+ },
+ {
+ "name": "index_recording_runs_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_recording_runs_status_scheduled_start_ms",
+ "unique": false,
+ "columnNames": [
+ "status",
+ "scheduled_start_ms"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_status_scheduled_start_ms` ON `${TABLE_NAME}` (`status`, `scheduled_start_ms`)"
+ },
+ {
+ "name": "index_recording_runs_alarm_start_at_ms",
+ "unique": false,
+ "columnNames": [
+ "alarm_start_at_ms"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_alarm_start_at_ms` ON `${TABLE_NAME}` (`alarm_start_at_ms`)"
+ },
+ {
+ "name": "index_recording_runs_alarm_stop_at_ms",
+ "unique": false,
+ "columnNames": [
+ "alarm_stop_at_ms"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_alarm_stop_at_ms` ON `${TABLE_NAME}` (`alarm_stop_at_ms`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "recording_schedules",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "schedule_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ },
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "program_reminders",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `channel_id` TEXT NOT NULL, `channel_name` TEXT NOT NULL, `program_title` TEXT NOT NULL, `program_start_time` INTEGER NOT NULL, `remind_at` INTEGER NOT NULL, `lead_time_minutes` INTEGER NOT NULL, `is_dismissed` INTEGER NOT NULL, `notified_at` INTEGER, `created_at` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "channelId",
+ "columnName": "channel_id",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "channelName",
+ "columnName": "channel_name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "programTitle",
+ "columnName": "program_title",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "programStartTime",
+ "columnName": "program_start_time",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "remindAt",
+ "columnName": "remind_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "leadTimeMinutes",
+ "columnName": "lead_time_minutes",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isDismissed",
+ "columnName": "is_dismissed",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "notifiedAt",
+ "columnName": "notified_at",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "createdAt",
+ "columnName": "created_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_program_reminders_provider_id_remind_at",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "remind_at"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_program_reminders_provider_id_remind_at` ON `${TABLE_NAME}` (`provider_id`, `remind_at`)"
+ },
+ {
+ "name": "index_program_reminders_is_dismissed_notified_at_remind_at",
+ "unique": false,
+ "columnNames": [
+ "is_dismissed",
+ "notified_at",
+ "remind_at"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_program_reminders_is_dismissed_notified_at_remind_at` ON `${TABLE_NAME}` (`is_dismissed`, `notified_at`, `remind_at`)"
+ },
+ {
+ "name": "index_program_reminders_provider_id_channel_id_program_start_time",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "channel_id",
+ "program_start_time"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_program_reminders_provider_id_channel_id_program_start_time` ON `${TABLE_NAME}` (`provider_id`, `channel_id`, `program_start_time`)"
+ },
+ {
+ "name": "index_program_reminders_provider_id_channel_id_program_title_program_start_time",
+ "unique": true,
+ "columnNames": [
+ "provider_id",
+ "channel_id",
+ "program_title",
+ "program_start_time"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_program_reminders_provider_id_channel_id_program_title_program_start_time` ON `${TABLE_NAME}` (`provider_id`, `channel_id`, `program_title`, `program_start_time`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "recording_storage",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER NOT NULL, `tree_uri` TEXT, `display_name` TEXT, `output_directory` TEXT, `available_bytes` INTEGER, `is_writable` INTEGER NOT NULL, `file_name_pattern` TEXT NOT NULL, `retention_days` INTEGER, `max_simultaneous_recordings` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, PRIMARY KEY(`id`))",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "treeUri",
+ "columnName": "tree_uri",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "displayName",
+ "columnName": "display_name",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "outputDirectory",
+ "columnName": "output_directory",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "availableBytes",
+ "columnName": "available_bytes",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "isWritable",
+ "columnName": "is_writable",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "fileNamePattern",
+ "columnName": "file_name_pattern",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "retentionDays",
+ "columnName": "retention_days",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "maxSimultaneousRecordings",
+ "columnName": "max_simultaneous_recordings",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "updatedAt",
+ "columnName": "updated_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "id"
+ ]
+ }
+ },
+ {
+ "tableName": "playback_compatibility_records",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `device_fingerprint` TEXT NOT NULL, `device_model` TEXT NOT NULL, `android_sdk` INTEGER NOT NULL, `stream_type` TEXT NOT NULL, `video_mime_type` TEXT NOT NULL, `resolution_bucket` TEXT NOT NULL, `decoder_name` TEXT NOT NULL, `surface_type` TEXT NOT NULL, `failure_type` TEXT NOT NULL, `last_failed_at` INTEGER NOT NULL, `last_succeeded_at` INTEGER NOT NULL, `failure_count` INTEGER NOT NULL, `success_count` INTEGER NOT NULL)",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "deviceFingerprint",
+ "columnName": "device_fingerprint",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "deviceModel",
+ "columnName": "device_model",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "androidSdk",
+ "columnName": "android_sdk",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "streamType",
+ "columnName": "stream_type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "videoMimeType",
+ "columnName": "video_mime_type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "resolutionBucket",
+ "columnName": "resolution_bucket",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "decoderName",
+ "columnName": "decoder_name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "surfaceType",
+ "columnName": "surface_type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "failureType",
+ "columnName": "failure_type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastFailedAt",
+ "columnName": "last_failed_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastSucceededAt",
+ "columnName": "last_succeeded_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "failureCount",
+ "columnName": "failure_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "successCount",
+ "columnName": "success_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_playback_compatibility_records_device_fingerprint_stream_type_video_mime_type_resolution_bucket_decoder_name_surface_type",
+ "unique": true,
+ "columnNames": [
+ "device_fingerprint",
+ "stream_type",
+ "video_mime_type",
+ "resolution_bucket",
+ "decoder_name",
+ "surface_type"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_playback_compatibility_records_device_fingerprint_stream_type_video_mime_type_resolution_bucket_decoder_name_surface_type` ON `${TABLE_NAME}` (`device_fingerprint`, `stream_type`, `video_mime_type`, `resolution_bucket`, `decoder_name`, `surface_type`)"
+ },
+ {
+ "name": "index_playback_compatibility_records_device_fingerprint_stream_type_video_mime_type_resolution_bucket",
+ "unique": false,
+ "columnNames": [
+ "device_fingerprint",
+ "stream_type",
+ "video_mime_type",
+ "resolution_bucket"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_compatibility_records_device_fingerprint_stream_type_video_mime_type_resolution_bucket` ON `${TABLE_NAME}` (`device_fingerprint`, `stream_type`, `video_mime_type`, `resolution_bucket`)"
+ },
+ {
+ "name": "index_playback_compatibility_records_last_failed_at",
+ "unique": false,
+ "columnNames": [
+ "last_failed_at"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_compatibility_records_last_failed_at` ON `${TABLE_NAME}` (`last_failed_at`)"
+ },
+ {
+ "name": "index_playback_compatibility_records_last_succeeded_at",
+ "unique": false,
+ "columnNames": [
+ "last_succeeded_at"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_compatibility_records_last_succeeded_at` ON `${TABLE_NAME}` (`last_succeeded_at`)"
+ }
+ ]
+ },
+ {
+ "tableName": "xtream_content_index",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `content_type` TEXT NOT NULL, `remote_id` TEXT NOT NULL, `local_content_id` INTEGER, `name` TEXT NOT NULL, `category_id` INTEGER, `category_name` TEXT, `image_url` TEXT, `container_extension` TEXT, `rating` REAL NOT NULL, `added_at` INTEGER NOT NULL, `remote_updated_at` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `indexed_at` INTEGER NOT NULL, `detail_hydrated_at` INTEGER NOT NULL, `stale_state` TEXT NOT NULL, `error_state` TEXT, `sync_fingerprint` TEXT NOT NULL, PRIMARY KEY(`provider_id`, `content_type`, `remote_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": "contentType",
+ "columnName": "content_type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "remoteId",
+ "columnName": "remote_id",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "localContentId",
+ "columnName": "local_content_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "categoryId",
+ "columnName": "category_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "categoryName",
+ "columnName": "category_name",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "imageUrl",
+ "columnName": "image_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "containerExtension",
+ "columnName": "container_extension",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "rating",
+ "columnName": "rating",
+ "affinity": "REAL",
+ "notNull": true
+ },
+ {
+ "fieldPath": "addedAt",
+ "columnName": "added_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "remoteUpdatedAt",
+ "columnName": "remote_updated_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isAdult",
+ "columnName": "is_adult",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "indexedAt",
+ "columnName": "indexed_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "detailHydratedAt",
+ "columnName": "detail_hydrated_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "staleState",
+ "columnName": "stale_state",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "errorState",
+ "columnName": "error_state",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "syncFingerprint",
+ "columnName": "sync_fingerprint",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "provider_id",
+ "content_type",
+ "remote_id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_xtream_content_index_provider_id_content_type",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "content_type"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_xtream_content_index_provider_id_content_type` ON `${TABLE_NAME}` (`provider_id`, `content_type`)"
+ },
+ {
+ "name": "index_xtream_content_index_provider_id_content_type_category_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "content_type",
+ "category_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_xtream_content_index_provider_id_content_type_category_id` ON `${TABLE_NAME}` (`provider_id`, `content_type`, `category_id`)"
+ },
+ {
+ "name": "index_xtream_content_index_provider_id_content_type_name",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "content_type",
+ "name"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_xtream_content_index_provider_id_content_type_name` ON `${TABLE_NAME}` (`provider_id`, `content_type`, `name`)"
+ },
+ {
+ "name": "index_xtream_content_index_provider_id_content_type_local_content_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "content_type",
+ "local_content_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_xtream_content_index_provider_id_content_type_local_content_id` ON `${TABLE_NAME}` (`provider_id`, `content_type`, `local_content_id`)"
+ },
+ {
+ "name": "index_xtream_content_index_provider_id_indexed_at",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "indexed_at"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_xtream_content_index_provider_id_indexed_at` ON `${TABLE_NAME}` (`provider_id`, `indexed_at`)"
+ },
+ {
+ "name": "index_xtream_content_index_stale_state",
+ "unique": false,
+ "columnNames": [
+ "stale_state"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_xtream_content_index_stale_state` ON `${TABLE_NAME}` (`stale_state`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "xtream_index_jobs",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `section` TEXT NOT NULL, `state` TEXT NOT NULL, `total_categories` INTEGER NOT NULL, `completed_categories` INTEGER NOT NULL, `next_category_index` INTEGER NOT NULL, `failed_categories` INTEGER NOT NULL, `indexed_rows` INTEGER NOT NULL, `skipped_malformed_rows` INTEGER NOT NULL, `deleted_pruned_rows` INTEGER NOT NULL, `priority_category_id` INTEGER, `priority_requested_at` INTEGER NOT NULL, `last_error` TEXT, `last_attempt_at` INTEGER NOT NULL, `last_success_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, PRIMARY KEY(`provider_id`, `section`), 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": "section",
+ "columnName": "section",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "state",
+ "columnName": "state",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "totalCategories",
+ "columnName": "total_categories",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "completedCategories",
+ "columnName": "completed_categories",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "nextCategoryIndex",
+ "columnName": "next_category_index",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "failedCategories",
+ "columnName": "failed_categories",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "indexedRows",
+ "columnName": "indexed_rows",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "skippedMalformedRows",
+ "columnName": "skipped_malformed_rows",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "deletedPrunedRows",
+ "columnName": "deleted_pruned_rows",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "priorityCategoryId",
+ "columnName": "priority_category_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "priorityRequestedAt",
+ "columnName": "priority_requested_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastError",
+ "columnName": "last_error",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "lastAttemptAt",
+ "columnName": "last_attempt_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastSuccessAt",
+ "columnName": "last_success_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "updatedAt",
+ "columnName": "updated_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "provider_id",
+ "section"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_xtream_index_jobs_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_xtream_index_jobs_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_xtream_index_jobs_section",
+ "unique": false,
+ "columnNames": [
+ "section"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_xtream_index_jobs_section` ON `${TABLE_NAME}` (`section`)"
+ },
+ {
+ "name": "index_xtream_index_jobs_state",
+ "unique": false,
+ "columnNames": [
+ "state"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_xtream_index_jobs_state` ON `${TABLE_NAME}` (`state`)"
+ },
+ {
+ "name": "index_xtream_index_jobs_updated_at",
+ "unique": false,
+ "columnNames": [
+ "updated_at"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_xtream_index_jobs_updated_at` ON `${TABLE_NAME}` (`updated_at`)"
+ }
+ ],
+ "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, 'c19c7c6865a5ad9c6bfe36f493cdad03')"
+ ]
+ }
+}
\ No newline at end of file
diff --git a/data/src/androidTest/java/com/streamvault/data/local/StreamVaultDatabaseMigrationTest.kt b/data/src/androidTest/java/com/streamvault/data/local/StreamVaultDatabaseMigrationTest.kt
index cb31d21e..609191b3 100644
--- a/data/src/androidTest/java/com/streamvault/data/local/StreamVaultDatabaseMigrationTest.kt
+++ b/data/src/androidTest/java/com/streamvault/data/local/StreamVaultDatabaseMigrationTest.kt
@@ -567,6 +567,165 @@ class StreamVaultDatabaseMigrationTest {
migratedDb.close()
}
+ @Test
+ fun migrate47To48_createsXtreamIndexBackfillsRowsAndMarksSummaryState() {
+ migrationTestHelper.createDatabase("streamvault-47-48-test", 47).apply {
+ execSQL(
+ """
+ INSERT INTO providers (
+ id, name, type, server_url, username, password, m3u_url, epg_url,
+ stalker_mac_address, stalker_device_profile, stalker_device_timezone, stalker_device_locale,
+ is_active, max_connections, expiration_date, api_version, allowed_output_formats_json,
+ epg_sync_mode, xtream_fast_sync_enabled, m3u_vod_classification_enabled, status,
+ last_synced_at, created_at
+ ) VALUES (
+ 1, 'Xtream Provider', 'XTREAM_CODES', 'https://provider.example.com', 'demo', 'secret', '', '',
+ '', '', '', '', 1, 1, NULL, NULL, '[]',
+ 'UPFRONT', 1, 0, 'ACTIVE', 1234, 1000
+ )
+ """.trimIndent()
+ )
+ execSQL(
+ """
+ INSERT INTO channels (
+ 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,
+ quality_options_json, sync_fingerprint
+ ) VALUES (
+ 10, 1001, 'News One', 'https://provider.example.com/news.png', 'News', 5, 'News',
+ 'https://provider.example.com/live/1001', NULL, 1, 0, 0, NULL,
+ 1, 0, 0, '', 0, NULL, 'live-fp'
+ )
+ """.trimIndent()
+ )
+ execSQL(
+ """
+ INSERT INTO categories (
+ id, category_id, name, parent_id, type, provider_id, is_adult, is_user_protected, sync_fingerprint
+ ) VALUES
+ (101, 5, 'News', NULL, 'LIVE', 1, 0, 0, 'cat-live'),
+ (102, 6, 'Movies', NULL, 'MOVIE', 1, 0, 0, 'cat-movies'),
+ (103, 7, 'Series', NULL, 'SERIES', 1, 0, 0, 'cat-series')
+ """.trimIndent()
+ )
+ execSQL(
+ """
+ INSERT INTO movies (
+ id, 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, watch_count, last_watched_at, is_adult,
+ is_user_protected, sync_fingerprint, added_at
+ ) VALUES (
+ 20, 2001, 'Thin Movie', 'https://provider.example.com/thin.jpg', NULL, 6, 'Movies',
+ 'https://provider.example.com/movie/2001.mp4', 'mp4', NULL, NULL, NULL, NULL, NULL,
+ NULL, 0, 6.5, NULL, NULL, NULL,
+ 1, 0, 0, 0, 0, 0, 'movie-thin-fp', 111
+ )
+ """.trimIndent()
+ )
+ execSQL(
+ """
+ INSERT INTO movies (
+ id, 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, watch_count, last_watched_at, is_adult,
+ is_user_protected, sync_fingerprint, added_at
+ ) VALUES (
+ 21, 2002, 'Rich Movie', 'https://provider.example.com/rich.jpg', NULL, 6, 'Movies',
+ 'https://provider.example.com/movie/2002.mp4', 'mp4', 'Plot', NULL, NULL, 'Drama', NULL,
+ '90 min', 5400, 7.5, '2025', 9876, NULL,
+ 1, 0, 0, 0, 0, 0, 'movie-rich-fp', 222
+ )
+ """.trimIndent()
+ )
+ execSQL(
+ """
+ INSERT INTO series (
+ id, series_id, provider_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
+ ) VALUES (
+ 30, 3001, NULL, 'Thin Series', 'https://provider.example.com/thin-series.jpg', NULL, 7,
+ 'Series', NULL, NULL, NULL, NULL, NULL, 6.0, NULL,
+ NULL, NULL, 333, 1, 0, 0, 'series-thin-fp'
+ )
+ """.trimIndent()
+ )
+ execSQL(
+ """
+ INSERT INTO series (
+ id, series_id, provider_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
+ ) VALUES (
+ 31, 3002, 'provider-series-3002', 'Rich Series', 'https://provider.example.com/rich-series.jpg', NULL, 7,
+ 'Series', 'Plot', NULL, NULL, 'Drama', NULL, 8.0, 12345,
+ NULL, '45', 444, 1, 0, 0, 'series-rich-fp'
+ )
+ """.trimIndent()
+ )
+ execSQL(
+ """
+ INSERT INTO sync_metadata (
+ provider_id, last_live_sync, last_live_success, last_movie_sync, last_series_sync,
+ last_series_success, last_epg_sync, last_epg_success, last_movie_attempt,
+ last_movie_success, last_movie_partial, live_count, movie_count, series_count,
+ epg_count, last_sync_status, movie_sync_mode, movie_warnings_count, movie_catalog_stale,
+ live_avoid_full_until, movie_avoid_full_until, series_avoid_full_until,
+ live_sequential_failures_remembered, live_healthy_sync_streak,
+ movie_parallel_failures_remembered, movie_healthy_sync_streak,
+ series_sequential_failures_remembered, series_healthy_sync_streak
+ ) VALUES (
+ 1, 1200, 1200, 1300, 1400,
+ 1400, 1500, 1500, 1300,
+ 1300, 0, 1, 2, 2,
+ 3, 'SUCCESS', 'FULL', 0, 0,
+ 0, 0, 0,
+ 0, 0,
+ 0, 0,
+ 0, 0
+ )
+ """.trimIndent()
+ )
+ close()
+ }
+
+ val migratedDb = migrationTestHelper.runMigrationsAndValidate(
+ "streamvault-47-48-test",
+ 48,
+ true,
+ StreamVaultDatabase.MIGRATION_47_48
+ )
+
+ assertEquals(1, countRows(migratedDb, "SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = 'xtream_content_index'"))
+ assertEquals(1, countRows(migratedDb, "SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = 'xtream_index_jobs'"))
+ assertEquals(1, countRows(migratedDb, "SELECT COUNT(*) FROM sqlite_master WHERE type = 'index' AND name = 'index_xtream_content_index_provider_id_content_type_local_content_id'"))
+ assertEquals(1, countRows(migratedDb, "SELECT COUNT(*) FROM pragma_table_info('movies') WHERE name = 'cache_state'"))
+ assertEquals(1, countRows(migratedDb, "SELECT COUNT(*) FROM pragma_table_info('series') WHERE name = 'detail_hydrated_at'"))
+ assertEquals(5, countRows(migratedDb, "SELECT COUNT(*) FROM xtream_content_index WHERE provider_id = 1"))
+ assertEquals(1, countRows(migratedDb, "SELECT COUNT(*) FROM xtream_content_index WHERE content_type = 'LIVE' AND remote_id = '1001' AND image_url LIKE '%news.png'"))
+ assertEquals(1, countRows(migratedDb, "SELECT COUNT(*) FROM xtream_content_index WHERE content_type = 'SERIES' AND remote_id = 'provider-series-3002'"))
+ assertEquals(1, countRows(migratedDb, "SELECT COUNT(*) FROM movies WHERE id = 20 AND cache_state = 'SUMMARY_ONLY'"))
+ assertEquals(1, countRows(migratedDb, "SELECT COUNT(*) FROM movies WHERE id = 21 AND cache_state = 'DETAIL_HYDRATED'"))
+ assertEquals(1234, countRows(migratedDb, "SELECT detail_hydrated_at FROM movies WHERE id = 21"))
+ assertEquals(0, countRows(migratedDb, "SELECT detail_hydrated_at FROM movies WHERE id = 20"))
+ assertEquals(1, countRows(migratedDb, "SELECT COUNT(*) FROM series WHERE id = 30 AND cache_state = 'SUMMARY_ONLY'"))
+ assertEquals(1, countRows(migratedDb, "SELECT COUNT(*) FROM series WHERE id = 31 AND cache_state = 'DETAIL_HYDRATED'"))
+ assertEquals(1234, countRows(migratedDb, "SELECT detail_hydrated_at FROM series WHERE id = 31"))
+ assertEquals(0, countRows(migratedDb, "SELECT detail_hydrated_at FROM series WHERE id = 30"))
+ assertEquals(4, countRows(migratedDb, "SELECT COUNT(*) FROM xtream_index_jobs WHERE provider_id = 1"))
+ assertEquals(2, countRows(migratedDb, "SELECT indexed_rows FROM xtream_index_jobs WHERE provider_id = 1 AND section = 'MOVIE'"))
+ assertEquals(1, countRows(migratedDb, "SELECT total_categories FROM xtream_index_jobs WHERE provider_id = 1 AND section = 'MOVIE'"))
+ assertEquals(1, countRows(migratedDb, "SELECT completed_categories FROM xtream_index_jobs WHERE provider_id = 1 AND section = 'MOVIE'"))
+
+ migratedDb.close()
+ }
+
@Test
fun migrate34To35_createsSearchHistoryTable() {
migrationTestHelper.createDatabase("streamvault-34-35-test", 34).close()
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 890627da..c836c616 100644
--- a/data/src/main/java/com/streamvault/data/local/StreamVaultDatabase.kt
+++ b/data/src/main/java/com/streamvault/data/local/StreamVaultDatabase.kt
@@ -44,9 +44,11 @@ import com.streamvault.data.local.entity.*
RecordingRunEntity::class,
ProgramReminderEntity::class,
RecordingStorageEntity::class,
- PlaybackCompatibilityRecordEntity::class
+ PlaybackCompatibilityRecordEntity::class,
+ XtreamContentIndexEntity::class,
+ XtreamIndexJobEntity::class
],
- version = 47,
+ version = 48,
exportSchema = true // ← was false; schema JSON now tracked in version control
)
@TypeConverters(RoomEnumConverters::class)
@@ -65,6 +67,7 @@ abstract class StreamVaultDatabase : RoomDatabase() {
abstract fun playbackHistoryDao(): PlaybackHistoryDao
abstract fun tmdbIdentityDao(): TmdbIdentityDao
abstract fun searchHistoryDao(): SearchHistoryDao
+ abstract fun searchDao(): SearchDao
abstract fun syncMetadataDao(): SyncMetadataDao
abstract fun movieCategoryHydrationDao(): MovieCategoryHydrationDao
abstract fun seriesCategoryHydrationDao(): SeriesCategoryHydrationDao
@@ -80,6 +83,8 @@ abstract class StreamVaultDatabase : RoomDatabase() {
abstract fun programReminderDao(): ProgramReminderDao
abstract fun recordingStorageDao(): RecordingStorageDao
abstract fun playbackCompatibilityDao(): PlaybackCompatibilityDao
+ abstract fun xtreamContentIndexDao(): XtreamContentIndexDao
+ abstract fun xtreamIndexJobDao(): XtreamIndexJobDao
companion object {
/**
@@ -2151,5 +2156,315 @@ abstract class StreamVaultDatabase : RoomDatabase() {
database.execSQL("CREATE INDEX IF NOT EXISTS index_playback_history_provider_id_content_type_last_watched_at ON playback_history(provider_id, content_type, last_watched_at)")
}
}
+
+ /**
+ * Migration 47 -> 48: create the Xtream summary index and section job state tables.
+ * Existing Xtream live/movie/series rows are backfilled without deleting or remapping
+ * the playable/detail tables that favorites and history already reference.
+ */
+ val MIGRATION_47_48 = object : Migration(47, 48) {
+ override fun migrate(database: SupportSQLiteDatabase) {
+ database.execSQL("ALTER TABLE movies ADD COLUMN cache_state TEXT NOT NULL DEFAULT 'DETAIL_HYDRATED'")
+ database.execSQL("ALTER TABLE movies ADD COLUMN detail_hydrated_at INTEGER NOT NULL DEFAULT 0")
+ database.execSQL("ALTER TABLE movies ADD COLUMN remote_stale_at INTEGER NOT NULL DEFAULT 0")
+ database.execSQL("ALTER TABLE series ADD COLUMN cache_state TEXT NOT NULL DEFAULT 'DETAIL_HYDRATED'")
+ database.execSQL("ALTER TABLE series ADD COLUMN detail_hydrated_at INTEGER NOT NULL DEFAULT 0")
+ database.execSQL("ALTER TABLE series ADD COLUMN remote_stale_at INTEGER NOT NULL DEFAULT 0")
+
+ database.execSQL(
+ """
+ UPDATE movies
+ SET cache_state = 'SUMMARY_ONLY'
+ WHERE COALESCE(plot, '') = ''
+ AND COALESCE(cast, '') = ''
+ AND COALESCE(director, '') = ''
+ AND COALESCE(genre, '') = ''
+ AND COALESCE(duration, '') = ''
+ AND duration_seconds = 0
+ AND tmdb_id IS NULL
+ """.trimIndent()
+ )
+ database.execSQL(
+ """
+ UPDATE series
+ SET cache_state = 'SUMMARY_ONLY'
+ WHERE COALESCE(plot, '') = ''
+ AND COALESCE(cast, '') = ''
+ AND COALESCE(director, '') = ''
+ AND COALESCE(genre, '') = ''
+ AND COALESCE(episode_run_time, '') = ''
+ AND tmdb_id IS NULL
+ """.trimIndent()
+ )
+ database.execSQL(
+ """
+ UPDATE movies
+ SET detail_hydrated_at = COALESCE(
+ (SELECT providers.last_synced_at FROM providers WHERE providers.id = movies.provider_id),
+ 0
+ )
+ WHERE cache_state = 'DETAIL_HYDRATED'
+ """.trimIndent()
+ )
+ database.execSQL(
+ """
+ UPDATE series
+ SET detail_hydrated_at = COALESCE(
+ (SELECT providers.last_synced_at FROM providers WHERE providers.id = series.provider_id),
+ 0
+ )
+ WHERE cache_state = 'DETAIL_HYDRATED'
+ """.trimIndent()
+ )
+
+ database.execSQL(
+ """
+ CREATE TABLE IF NOT EXISTS xtream_content_index (
+ provider_id INTEGER NOT NULL,
+ content_type TEXT NOT NULL,
+ remote_id TEXT NOT NULL,
+ local_content_id INTEGER,
+ name TEXT NOT NULL,
+ category_id INTEGER,
+ category_name TEXT,
+ image_url TEXT,
+ container_extension TEXT,
+ rating REAL NOT NULL,
+ added_at INTEGER NOT NULL,
+ remote_updated_at INTEGER NOT NULL,
+ is_adult INTEGER NOT NULL,
+ indexed_at INTEGER NOT NULL,
+ detail_hydrated_at INTEGER NOT NULL,
+ stale_state TEXT NOT NULL,
+ error_state TEXT,
+ sync_fingerprint TEXT NOT NULL,
+ PRIMARY KEY(provider_id, content_type, remote_id),
+ FOREIGN KEY(provider_id) REFERENCES providers(id) ON DELETE CASCADE
+ )
+ """.trimIndent()
+ )
+ database.execSQL("CREATE INDEX IF NOT EXISTS index_xtream_content_index_provider_id_content_type ON xtream_content_index(provider_id, content_type)")
+ database.execSQL("CREATE INDEX IF NOT EXISTS index_xtream_content_index_provider_id_content_type_category_id ON xtream_content_index(provider_id, content_type, category_id)")
+ database.execSQL("CREATE INDEX IF NOT EXISTS index_xtream_content_index_provider_id_content_type_name ON xtream_content_index(provider_id, content_type, name)")
+ database.execSQL("CREATE INDEX IF NOT EXISTS index_xtream_content_index_provider_id_content_type_local_content_id ON xtream_content_index(provider_id, content_type, local_content_id)")
+ database.execSQL("CREATE INDEX IF NOT EXISTS index_xtream_content_index_provider_id_indexed_at ON xtream_content_index(provider_id, indexed_at)")
+ database.execSQL("CREATE INDEX IF NOT EXISTS index_xtream_content_index_stale_state ON xtream_content_index(stale_state)")
+
+ database.execSQL(
+ """
+ CREATE TABLE IF NOT EXISTS xtream_index_jobs (
+ provider_id INTEGER NOT NULL,
+ section TEXT NOT NULL,
+ state TEXT NOT NULL,
+ total_categories INTEGER NOT NULL,
+ completed_categories INTEGER NOT NULL,
+ next_category_index INTEGER NOT NULL,
+ failed_categories INTEGER NOT NULL,
+ indexed_rows INTEGER NOT NULL,
+ skipped_malformed_rows INTEGER NOT NULL,
+ deleted_pruned_rows INTEGER NOT NULL,
+ priority_category_id INTEGER,
+ priority_requested_at INTEGER NOT NULL,
+ last_error TEXT,
+ last_attempt_at INTEGER NOT NULL,
+ last_success_at INTEGER NOT NULL,
+ updated_at INTEGER NOT NULL,
+ PRIMARY KEY(provider_id, section),
+ FOREIGN KEY(provider_id) REFERENCES providers(id) ON DELETE CASCADE
+ )
+ """.trimIndent()
+ )
+ database.execSQL("CREATE INDEX IF NOT EXISTS index_xtream_index_jobs_provider_id ON xtream_index_jobs(provider_id)")
+ database.execSQL("CREATE INDEX IF NOT EXISTS index_xtream_index_jobs_section ON xtream_index_jobs(section)")
+ database.execSQL("CREATE INDEX IF NOT EXISTS index_xtream_index_jobs_state ON xtream_index_jobs(state)")
+ database.execSQL("CREATE INDEX IF NOT EXISTS index_xtream_index_jobs_updated_at ON xtream_index_jobs(updated_at)")
+
+ database.execSQL(
+ """
+ INSERT OR REPLACE INTO xtream_content_index (
+ provider_id, content_type, remote_id, local_content_id, name, category_id,
+ category_name, image_url, container_extension, rating, added_at, remote_updated_at,
+ is_adult, indexed_at, detail_hydrated_at, stale_state, error_state, sync_fingerprint
+ )
+ SELECT
+ c.provider_id,
+ 'LIVE',
+ CAST(c.stream_id AS TEXT),
+ c.id,
+ c.name,
+ c.category_id,
+ c.category_name,
+ c.logo_url,
+ NULL,
+ 0,
+ 0,
+ 0,
+ c.is_adult,
+ COALESCE(p.last_synced_at, 0),
+ COALESCE(p.last_synced_at, 0),
+ 'ACTIVE',
+ NULL,
+ c.sync_fingerprint
+ FROM channels c
+ JOIN providers p ON p.id = c.provider_id
+ WHERE p.type = 'XTREAM_CODES'
+ """.trimIndent()
+ )
+ database.execSQL(
+ """
+ INSERT OR REPLACE INTO xtream_content_index (
+ provider_id, content_type, remote_id, local_content_id, name, category_id,
+ category_name, image_url, container_extension, rating, added_at, remote_updated_at,
+ is_adult, indexed_at, detail_hydrated_at, stale_state, error_state, sync_fingerprint
+ )
+ SELECT
+ m.provider_id,
+ 'MOVIE',
+ CAST(m.stream_id AS TEXT),
+ m.id,
+ m.name,
+ m.category_id,
+ m.category_name,
+ m.poster_url,
+ m.container_extension,
+ m.rating,
+ m.added_at,
+ 0,
+ m.is_adult,
+ COALESCE(p.last_synced_at, 0),
+ CASE WHEN m.cache_state = 'DETAIL_HYDRATED' THEN COALESCE(p.last_synced_at, 0) ELSE 0 END,
+ 'ACTIVE',
+ NULL,
+ m.sync_fingerprint
+ FROM movies m
+ JOIN providers p ON p.id = m.provider_id
+ WHERE p.type = 'XTREAM_CODES'
+ """.trimIndent()
+ )
+ database.execSQL(
+ """
+ INSERT OR REPLACE INTO xtream_content_index (
+ provider_id, content_type, remote_id, local_content_id, name, category_id,
+ category_name, image_url, container_extension, rating, added_at, remote_updated_at,
+ is_adult, indexed_at, detail_hydrated_at, stale_state, error_state, sync_fingerprint
+ )
+ SELECT
+ s.provider_id,
+ 'SERIES',
+ COALESCE(s.provider_series_id, CAST(s.series_id AS TEXT)),
+ s.id,
+ s.name,
+ s.category_id,
+ s.category_name,
+ s.poster_url,
+ NULL,
+ s.rating,
+ 0,
+ s.last_modified,
+ s.is_adult,
+ COALESCE(p.last_synced_at, 0),
+ CASE WHEN s.cache_state = 'DETAIL_HYDRATED' THEN COALESCE(p.last_synced_at, 0) ELSE 0 END,
+ 'ACTIVE',
+ NULL,
+ s.sync_fingerprint
+ FROM series s
+ JOIN providers p ON p.id = s.provider_id
+ WHERE p.type = 'XTREAM_CODES'
+ """.trimIndent()
+ )
+
+ database.execSQL(
+ """
+ INSERT OR REPLACE INTO xtream_index_jobs (
+ provider_id, section, state, total_categories, completed_categories, next_category_index, failed_categories,
+ indexed_rows, skipped_malformed_rows, deleted_pruned_rows, priority_category_id, priority_requested_at, last_error,
+ last_attempt_at, last_success_at, updated_at
+ )
+ SELECT
+ p.id,
+ section.name,
+ CASE
+ WHEN section.name = 'LIVE' AND (
+ COALESCE(NULLIF(sm.last_live_success, 0), NULLIF(sm.last_live_sync, 0), 0) > 0
+ OR (SELECT COUNT(*) FROM channels c WHERE c.provider_id = p.id) > 0
+ ) THEN 'SUCCESS'
+ WHEN section.name = 'MOVIE' AND (
+ COALESCE(NULLIF(sm.last_movie_success, 0), NULLIF(sm.last_movie_sync, 0), 0) > 0
+ OR (SELECT COUNT(*) FROM movies m WHERE m.provider_id = p.id) > 0
+ ) THEN 'SUCCESS'
+ WHEN section.name = 'SERIES' AND (
+ COALESCE(NULLIF(sm.last_series_success, 0), NULLIF(sm.last_series_sync, 0), 0) > 0
+ OR (SELECT COUNT(*) FROM series s WHERE s.provider_id = p.id) > 0
+ ) THEN 'SUCCESS'
+ WHEN section.name = 'EPG' AND COALESCE(NULLIF(sm.last_epg_success, 0), NULLIF(sm.last_epg_sync, 0), 0) > 0 THEN 'SUCCESS'
+ ELSE 'IDLE'
+ END,
+ CASE section.name
+ WHEN 'LIVE' THEN (SELECT COUNT(*) FROM categories cat WHERE cat.provider_id = p.id AND cat.type = 'LIVE')
+ WHEN 'MOVIE' THEN (SELECT COUNT(*) FROM categories cat WHERE cat.provider_id = p.id AND cat.type = 'MOVIE')
+ WHEN 'SERIES' THEN (SELECT COUNT(*) FROM categories cat WHERE cat.provider_id = p.id AND cat.type = 'SERIES')
+ ELSE 0
+ END,
+ CASE
+ WHEN section.name = 'LIVE' AND (SELECT COUNT(*) FROM channels c WHERE c.provider_id = p.id) > 0
+ THEN (SELECT COUNT(*) FROM categories cat WHERE cat.provider_id = p.id AND cat.type = 'LIVE')
+ WHEN section.name = 'MOVIE' AND (SELECT COUNT(*) FROM movies m WHERE m.provider_id = p.id) > 0
+ THEN (SELECT COUNT(*) FROM categories cat WHERE cat.provider_id = p.id AND cat.type = 'MOVIE')
+ WHEN section.name = 'SERIES' AND (SELECT COUNT(*) FROM series s WHERE s.provider_id = p.id) > 0
+ THEN (SELECT COUNT(*) FROM categories cat WHERE cat.provider_id = p.id AND cat.type = 'SERIES')
+ ELSE 0
+ END,
+ CASE
+ WHEN section.name = 'LIVE' AND (SELECT COUNT(*) FROM channels c WHERE c.provider_id = p.id) > 0
+ THEN (SELECT COUNT(*) FROM categories cat WHERE cat.provider_id = p.id AND cat.type = 'LIVE')
+ WHEN section.name = 'MOVIE' AND (SELECT COUNT(*) FROM movies m WHERE m.provider_id = p.id) > 0
+ THEN (SELECT COUNT(*) FROM categories cat WHERE cat.provider_id = p.id AND cat.type = 'MOVIE')
+ WHEN section.name = 'SERIES' AND (SELECT COUNT(*) FROM series s WHERE s.provider_id = p.id) > 0
+ THEN (SELECT COUNT(*) FROM categories cat WHERE cat.provider_id = p.id AND cat.type = 'SERIES')
+ ELSE 0
+ END,
+ 0,
+ CASE section.name
+ WHEN 'LIVE' THEN (SELECT COUNT(*) FROM channels c WHERE c.provider_id = p.id)
+ WHEN 'MOVIE' THEN (SELECT COUNT(*) FROM movies m WHERE m.provider_id = p.id)
+ WHEN 'SERIES' THEN (SELECT COUNT(*) FROM series s WHERE s.provider_id = p.id)
+ WHEN 'EPG' THEN COALESCE(sm.epg_count, 0)
+ ELSE 0
+ END,
+ 0,
+ 0,
+ NULL,
+ 0,
+ NULL,
+ CASE section.name
+ WHEN 'LIVE' THEN COALESCE(sm.last_live_sync, 0)
+ WHEN 'MOVIE' THEN COALESCE(NULLIF(sm.last_movie_attempt, 0), sm.last_movie_sync, 0)
+ WHEN 'SERIES' THEN COALESCE(sm.last_series_sync, 0)
+ WHEN 'EPG' THEN COALESCE(sm.last_epg_sync, 0)
+ ELSE 0
+ END,
+ CASE section.name
+ WHEN 'LIVE' THEN COALESCE(NULLIF(sm.last_live_success, 0), sm.last_live_sync, 0)
+ WHEN 'MOVIE' THEN COALESCE(NULLIF(sm.last_movie_success, 0), sm.last_movie_sync, 0)
+ WHEN 'SERIES' THEN COALESCE(NULLIF(sm.last_series_success, 0), sm.last_series_sync, 0)
+ WHEN 'EPG' THEN COALESCE(NULLIF(sm.last_epg_success, 0), sm.last_epg_sync, 0)
+ ELSE 0
+ END,
+ COALESCE(p.last_synced_at, 0)
+ FROM providers p
+ CROSS JOIN (
+ SELECT 'LIVE' AS name
+ UNION ALL SELECT 'MOVIE'
+ UNION ALL SELECT 'SERIES'
+ UNION ALL SELECT 'EPG'
+ ) section
+ LEFT JOIN sync_metadata sm ON sm.provider_id = p.id
+ WHERE p.type = 'XTREAM_CODES'
+ """.trimIndent()
+ )
+
+ validateForeignKeys(database, "xtream_content_index", "xtream_index_jobs")
+ }
+ }
}
}
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 f4f09aea..46c56b37 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
@@ -274,9 +274,9 @@ abstract class ChannelDao {
FROM channels c
WHERE c.provider_id = :providerId
AND (
- c.name LIKE :queryLike ESCAPE '\\'
- OR COALESCE(c.group_title, '') LIKE :queryLike ESCAPE '\\'
- OR COALESCE(c.category_name, '') LIKE :queryLike ESCAPE '\\'
+ c.name LIKE :queryLike ESCAPE '\'
+ OR COALESCE(c.group_title, '') LIKE :queryLike ESCAPE '\'
+ OR COALESCE(c.category_name, '') LIKE :queryLike ESCAPE '\'
)
ORDER BY c.name ASC
LIMIT :limit
@@ -309,9 +309,9 @@ abstract class ChannelDao {
WHERE c.provider_id = :providerId
AND c.category_id = :categoryId
AND (
- c.name LIKE :queryLike ESCAPE '\\'
- OR COALESCE(c.group_title, '') LIKE :queryLike ESCAPE '\\'
- OR COALESCE(c.category_name, '') LIKE :queryLike ESCAPE '\\'
+ c.name LIKE :queryLike ESCAPE '\'
+ OR COALESCE(c.group_title, '') LIKE :queryLike ESCAPE '\'
+ OR COALESCE(c.category_name, '') LIKE :queryLike ESCAPE '\'
)
ORDER BY c.name ASC
LIMIT :limit
@@ -1181,6 +1181,62 @@ interface MovieDao {
limit: Int
): 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
+ AND (:includeProtected != 0 OR m.is_user_protected = 0)
+ ORDER BY
+ CASE
+ WHEN LOWER(m.name) = LOWER(:rawQuery) THEN 0
+ WHEN LOWER(m.name) LIKE LOWER(:prefixLike) ESCAPE '\' THEN 1
+ ELSE 2
+ END ASC,
+ m.name ASC
+ LIMIT :limit OFFSET :offset
+ """
+ )
+ suspend fun searchPage(
+ providerId: Long,
+ query: String,
+ rawQuery: String,
+ prefixLike: String,
+ includeProtected: Int,
+ limit: Int,
+ offset: Int
+ ): 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
+ AND (:includeProtected != 0 OR m.is_user_protected = 0)
+ ORDER BY
+ CASE
+ WHEN LOWER(m.name) = LOWER(:rawQuery) THEN 0
+ WHEN LOWER(m.name) LIKE LOWER(:prefixLike) ESCAPE '\' THEN 1
+ ELSE 2
+ END ASC,
+ m.name ASC
+ LIMIT :limit OFFSET :offset
+ """
+ )
+ suspend fun searchByCategoryPage(
+ providerId: Long,
+ categoryId: Long,
+ query: String,
+ rawQuery: String,
+ prefixLike: String,
+ includeProtected: Int,
+ limit: Int,
+ offset: Int
+ ): List<MovieBrowseEntity>
+
@Query(
"""
SELECT m.* FROM movies m
@@ -1198,10 +1254,10 @@ interface MovieDao {
SELECT m.* FROM movies m
WHERE m.provider_id = :providerId
AND (
- m.name LIKE :queryLike ESCAPE '\\'
- OR COALESCE(m.genre, '') LIKE :queryLike ESCAPE '\\'
- OR COALESCE(m.category_name, '') LIKE :queryLike ESCAPE '\\'
- OR COALESCE(m.year, '') LIKE :queryLike ESCAPE '\\'
+ m.name LIKE :queryLike ESCAPE '\'
+ OR COALESCE(m.genre, '') LIKE :queryLike ESCAPE '\'
+ OR COALESCE(m.category_name, '') LIKE :queryLike ESCAPE '\'
+ OR COALESCE(m.year, '') LIKE :queryLike ESCAPE '\'
)
ORDER BY m.name ASC
LIMIT :limit
@@ -1228,10 +1284,10 @@ interface MovieDao {
WHERE m.provider_id = :providerId
AND m.category_id = :categoryId
AND (
- m.name LIKE :queryLike ESCAPE '\\'
- OR COALESCE(m.genre, '') LIKE :queryLike ESCAPE '\\'
- OR COALESCE(m.category_name, '') LIKE :queryLike ESCAPE '\\'
- OR COALESCE(m.year, '') LIKE :queryLike ESCAPE '\\'
+ m.name LIKE :queryLike ESCAPE '\'
+ OR COALESCE(m.genre, '') LIKE :queryLike ESCAPE '\'
+ OR COALESCE(m.category_name, '') LIKE :queryLike ESCAPE '\'
+ OR COALESCE(m.year, '') LIKE :queryLike ESCAPE '\'
)
ORDER BY m.name ASC
LIMIT :limit
@@ -1254,6 +1310,9 @@ interface MovieDao {
@Query("SELECT * FROM movies WHERE provider_id = :providerId AND stream_id = :streamId")
suspend fun getByStreamId(providerId: Long, streamId: Long): MovieEntity?
+ @Query("SELECT * FROM movies WHERE provider_id = :providerId AND stream_id IN (:streamIds)")
+ suspend fun getByStreamIds(providerId: Long, streamIds: List<Long>): List<MovieEntity>
+
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertAll(movies: List<MovieEntity>)
@@ -2089,6 +2148,62 @@ interface SeriesDao {
limit: Int
): List<SeriesBrowseEntity>
+ @Query(
+ """
+ SELECT s.* FROM series s
+ JOIN series_fts ON s.id = series_fts.rowid
+ WHERE s.provider_id = :providerId
+ AND series_fts MATCH :query
+ AND (:includeProtected != 0 OR s.is_user_protected = 0)
+ ORDER BY
+ CASE
+ WHEN LOWER(s.name) = LOWER(:rawQuery) THEN 0
+ WHEN LOWER(s.name) LIKE LOWER(:prefixLike) ESCAPE '\' THEN 1
+ ELSE 2
+ END ASC,
+ s.name ASC
+ LIMIT :limit OFFSET :offset
+ """
+ )
+ suspend fun searchPage(
+ providerId: Long,
+ query: String,
+ rawQuery: String,
+ prefixLike: String,
+ includeProtected: Int,
+ limit: Int,
+ offset: Int
+ ): 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
+ AND (:includeProtected != 0 OR s.is_user_protected = 0)
+ ORDER BY
+ CASE
+ WHEN LOWER(s.name) = LOWER(:rawQuery) THEN 0
+ WHEN LOWER(s.name) LIKE LOWER(:prefixLike) ESCAPE '\' THEN 1
+ ELSE 2
+ END ASC,
+ s.name ASC
+ LIMIT :limit OFFSET :offset
+ """
+ )
+ suspend fun searchByCategoryPage(
+ providerId: Long,
+ categoryId: Long,
+ query: String,
+ rawQuery: String,
+ prefixLike: String,
+ includeProtected: Int,
+ limit: Int,
+ offset: Int
+ ): List<SeriesBrowseEntity>
+
@Query(
"""
SELECT s.* FROM series s
@@ -2106,9 +2221,9 @@ interface SeriesDao {
SELECT s.* FROM series s
WHERE s.provider_id = :providerId
AND (
- s.name LIKE :queryLike ESCAPE '\\'
- OR COALESCE(s.genre, '') LIKE :queryLike ESCAPE '\\'
- OR COALESCE(s.category_name, '') LIKE :queryLike ESCAPE '\\'
+ s.name LIKE :queryLike ESCAPE '\'
+ OR COALESCE(s.genre, '') LIKE :queryLike ESCAPE '\'
+ OR COALESCE(s.category_name, '') LIKE :queryLike ESCAPE '\'
)
ORDER BY s.name ASC
LIMIT :limit
@@ -2135,9 +2250,9 @@ interface SeriesDao {
WHERE s.provider_id = :providerId
AND s.category_id = :categoryId
AND (
- s.name LIKE :queryLike ESCAPE '\\'
- OR COALESCE(s.genre, '') LIKE :queryLike ESCAPE '\\'
- OR COALESCE(s.category_name, '') LIKE :queryLike ESCAPE '\\'
+ s.name LIKE :queryLike ESCAPE '\'
+ OR COALESCE(s.genre, '') LIKE :queryLike ESCAPE '\'
+ OR COALESCE(s.category_name, '') LIKE :queryLike ESCAPE '\'
)
ORDER BY s.name ASC
LIMIT :limit
@@ -2160,6 +2275,9 @@ interface SeriesDao {
@Query("SELECT * FROM series WHERE provider_id = :providerId AND series_id = :seriesId LIMIT 1")
suspend fun getBySeriesId(providerId: Long, seriesId: Long): SeriesEntity?
+ @Query("SELECT * FROM series WHERE provider_id = :providerId AND series_id IN (:seriesIds)")
+ suspend fun getBySeriesIds(providerId: Long, seriesIds: List<Long>): List<SeriesEntity>
+
@Query("SELECT * FROM series WHERE provider_id = :providerId AND provider_series_id = :providerSeriesId LIMIT 1")
suspend fun getByProviderSeriesId(providerId: Long, providerSeriesId: String): SeriesEntity?
diff --git a/data/src/main/java/com/streamvault/data/local/dao/SearchDao.kt b/data/src/main/java/com/streamvault/data/local/dao/SearchDao.kt
new file mode 100644
index 00000000..d8c301a5
--- /dev/null
+++ b/data/src/main/java/com/streamvault/data/local/dao/SearchDao.kt
@@ -0,0 +1,164 @@
+package com.streamvault.data.local.dao
+
+import androidx.room.ColumnInfo
+import androidx.room.Dao
+import androidx.room.Query
+import kotlinx.coroutines.flow.Flow
+
+data class SearchHitEntity(
+ @ColumnInfo(name = "content_type") val contentType: String,
+ @ColumnInfo(name = "content_id") val contentId: Long,
+ @ColumnInfo(name = "title") val title: String,
+ @ColumnInfo(name = "section_rank") val sectionRank: Int,
+ @ColumnInfo(name = "match_rank") val matchRank: Int
+)
+
+@Dao
+abstract class SearchDao {
+ @Query(
+ """
+ SELECT * FROM (
+ SELECT 'LIVE' AS content_type,
+ c.id AS content_id,
+ c.name AS title,
+ 0 AS section_rank,
+ CASE
+ WHEN LOWER(c.name) = LOWER(:rawQuery) THEN 0
+ WHEN LOWER(c.name) LIKE LOWER(:prefixLike) ESCAPE '\' THEN 1
+ ELSE 2
+ END AS match_rank
+ FROM channels c
+ JOIN channels_fts ON c.id = channels_fts.rowid
+ WHERE c.provider_id = :providerId
+ AND channels_fts MATCH :ftsQuery
+ ORDER BY match_rank ASC, c.name ASC
+ LIMIT :limitPerSection
+ )
+ UNION ALL
+ SELECT * FROM (
+ SELECT 'MOVIE' AS content_type,
+ m.id AS content_id,
+ m.name AS title,
+ 1 AS section_rank,
+ CASE
+ WHEN LOWER(m.name) = LOWER(:rawQuery) THEN 0
+ WHEN LOWER(m.name) LIKE LOWER(:prefixLike) ESCAPE '\' THEN 1
+ ELSE 2
+ END AS match_rank
+ FROM movies m
+ JOIN movies_fts ON m.id = movies_fts.rowid
+ WHERE m.provider_id = :providerId
+ AND movies_fts MATCH :ftsQuery
+ ORDER BY match_rank ASC, m.name ASC
+ LIMIT :limitPerSection
+ )
+ UNION ALL
+ SELECT * FROM (
+ SELECT 'SERIES' AS content_type,
+ s.id AS content_id,
+ s.name AS title,
+ 2 AS section_rank,
+ CASE
+ WHEN LOWER(s.name) = LOWER(:rawQuery) THEN 0
+ WHEN LOWER(s.name) LIKE LOWER(:prefixLike) ESCAPE '\' THEN 1
+ ELSE 2
+ END AS match_rank
+ FROM series s
+ JOIN series_fts ON s.id = series_fts.rowid
+ WHERE s.provider_id = :providerId
+ AND series_fts MATCH :ftsQuery
+ ORDER BY match_rank ASC, s.name ASC
+ LIMIT :limitPerSection
+ )
+ ORDER BY section_rank ASC, match_rank ASC, title ASC
+ """
+ )
+ abstract fun searchAll(
+ providerId: Long,
+ ftsQuery: String,
+ rawQuery: String,
+ prefixLike: String,
+ limitPerSection: Int
+ ): Flow<List<SearchHitEntity>>
+
+ @Query(
+ """
+ SELECT 'LIVE' AS content_type,
+ c.id AS content_id,
+ c.name AS title,
+ 0 AS section_rank,
+ CASE
+ WHEN LOWER(c.name) = LOWER(:rawQuery) THEN 0
+ WHEN LOWER(c.name) LIKE LOWER(:prefixLike) ESCAPE '\' THEN 1
+ ELSE 2
+ END AS match_rank
+ FROM channels c
+ JOIN channels_fts ON c.id = channels_fts.rowid
+ WHERE c.provider_id = :providerId
+ AND channels_fts MATCH :ftsQuery
+ ORDER BY match_rank ASC, c.name ASC
+ LIMIT :limitPerSection
+ """
+ )
+ abstract fun searchLive(
+ providerId: Long,
+ ftsQuery: String,
+ rawQuery: String,
+ prefixLike: String,
+ limitPerSection: Int
+ ): Flow<List<SearchHitEntity>>
+
+ @Query(
+ """
+ SELECT 'MOVIE' AS content_type,
+ m.id AS content_id,
+ m.name AS title,
+ 1 AS section_rank,
+ CASE
+ WHEN LOWER(m.name) = LOWER(:rawQuery) THEN 0
+ WHEN LOWER(m.name) LIKE LOWER(:prefixLike) ESCAPE '\' THEN 1
+ ELSE 2
+ END AS match_rank
+ FROM movies m
+ JOIN movies_fts ON m.id = movies_fts.rowid
+ WHERE m.provider_id = :providerId
+ AND movies_fts MATCH :ftsQuery
+ ORDER BY match_rank ASC, m.name ASC
+ LIMIT :limitPerSection
+ """
+ )
+ abstract fun searchMovies(
+ providerId: Long,
+ ftsQuery: String,
+ rawQuery: String,
+ prefixLike: String,
+ limitPerSection: Int
+ ): Flow<List<SearchHitEntity>>
+
+ @Query(
+ """
+ SELECT 'SERIES' AS content_type,
+ s.id AS content_id,
+ s.name AS title,
+ 2 AS section_rank,
+ CASE
+ WHEN LOWER(s.name) = LOWER(:rawQuery) THEN 0
+ WHEN LOWER(s.name) LIKE LOWER(:prefixLike) ESCAPE '\' THEN 1
+ ELSE 2
+ END AS match_rank
+ FROM series s
+ JOIN series_fts ON s.id = series_fts.rowid
+ WHERE s.provider_id = :providerId
+ AND series_fts MATCH :ftsQuery
+ ORDER BY match_rank ASC, s.name ASC
+ LIMIT :limitPerSection
+ """
+ )
+ abstract fun searchSeries(
+ providerId: Long,
+ ftsQuery: String,
+ rawQuery: String,
+ prefixLike: String,
+ limitPerSection: Int
+ ): Flow<List<SearchHitEntity>>
+}
diff --git a/data/src/main/java/com/streamvault/data/local/dao/XtreamIndexDaos.kt b/data/src/main/java/com/streamvault/data/local/dao/XtreamIndexDaos.kt
new file mode 100644
index 00000000..a563f2ed
--- /dev/null
+++ b/data/src/main/java/com/streamvault/data/local/dao/XtreamIndexDaos.kt
@@ -0,0 +1,190 @@
+package com.streamvault.data.local.dao
+
+import androidx.room.Dao
+import androidx.room.Insert
+import androidx.room.OnConflictStrategy
+import androidx.room.Query
+import androidx.room.Transaction
+import com.streamvault.data.local.entity.XtreamContentIndexEntity
+import com.streamvault.data.local.entity.XtreamIndexJobEntity
+import kotlinx.coroutines.flow.Flow
+
+@Dao
+abstract class XtreamContentIndexDao {
+ @Query(
+ """
+ SELECT * FROM xtream_content_index
+ WHERE provider_id = :providerId AND content_type = :contentType
+ ORDER BY name COLLATE NOCASE ASC
+ """
+ )
+ abstract fun observeByProviderAndType(
+ providerId: Long,
+ contentType: String
+ ): Flow<List<XtreamContentIndexEntity>>
+
+ @Query(
+ """
+ SELECT * FROM xtream_content_index
+ WHERE provider_id = :providerId
+ AND content_type = :contentType
+ AND remote_id = :remoteId
+ LIMIT 1
+ """
+ )
+ abstract suspend fun getByRemoteId(
+ providerId: Long,
+ contentType: String,
+ remoteId: String
+ ): XtreamContentIndexEntity?
+
+ @Insert(onConflict = OnConflictStrategy.REPLACE)
+ abstract suspend fun upsert(entity: XtreamContentIndexEntity)
+
+ @Insert(onConflict = OnConflictStrategy.REPLACE)
+ abstract suspend fun upsertAll(entities: List<XtreamContentIndexEntity>)
+
+ @Query(
+ """
+ UPDATE xtream_content_index
+ SET local_content_id = :localContentId,
+ image_url = COALESCE(:imageUrl, image_url),
+ detail_hydrated_at = :detailHydratedAt,
+ error_state = NULL
+ WHERE provider_id = :providerId
+ AND content_type = :contentType
+ AND remote_id = :remoteId
+ """
+ )
+ abstract suspend fun markDetailHydrated(
+ providerId: Long,
+ contentType: String,
+ remoteId: String,
+ localContentId: Long,
+ imageUrl: String?,
+ detailHydratedAt: Long
+ ): Int
+
+ @Query(
+ """
+ UPDATE xtream_content_index
+ SET error_state = :errorState
+ WHERE provider_id = :providerId
+ AND content_type = :contentType
+ AND remote_id = :remoteId
+ """
+ )
+ abstract suspend fun markDetailHydrationError(
+ providerId: Long,
+ contentType: String,
+ remoteId: String,
+ errorState: String
+ ): Int
+
+ @Query(
+ """
+ UPDATE xtream_content_index
+ SET stale_state = 'STALE_REMOTE',
+ error_state = NULL
+ WHERE provider_id = :providerId
+ AND content_type IN ('MOVIE', 'SERIES')
+ """
+ )
+ abstract suspend fun markVodAndSeriesRowsStaleForRebuild(providerId: Long): Int
+
+ @Query("DELETE FROM xtream_content_index WHERE provider_id = :providerId")
+ abstract suspend fun deleteByProvider(providerId: Long): Int
+
+ @Query("DELETE FROM xtream_content_index WHERE provider_id = :providerId AND content_type = :contentType")
+ abstract suspend fun deleteByProviderAndType(providerId: Long, contentType: String): Int
+
+ @Query(
+ """
+ DELETE FROM xtream_content_index
+ WHERE content_type = 'LIVE'
+ AND local_content_id IS NOT NULL
+ AND NOT EXISTS (
+ SELECT 1
+ FROM channels
+ WHERE channels.id = xtream_content_index.local_content_id
+ AND channels.provider_id = xtream_content_index.provider_id
+ )
+ """
+ )
+ protected abstract suspend fun pruneOrphanLiveRows(): Int
+
+ @Query(
+ """
+ DELETE FROM xtream_content_index
+ WHERE content_type = 'MOVIE'
+ AND local_content_id IS NOT NULL
+ AND NOT EXISTS (
+ SELECT 1
+ FROM movies
+ WHERE movies.id = xtream_content_index.local_content_id
+ AND movies.provider_id = xtream_content_index.provider_id
+ )
+ """
+ )
+ protected abstract suspend fun pruneOrphanMovieRows(): Int
+
+ @Query(
+ """
+ DELETE FROM xtream_content_index
+ WHERE content_type = 'SERIES'
+ AND local_content_id IS NOT NULL
+ AND NOT EXISTS (
+ SELECT 1
+ FROM series
+ WHERE series.id = xtream_content_index.local_content_id
+ AND series.provider_id = xtream_content_index.provider_id
+ )
+ """
+ )
+ protected abstract suspend fun pruneOrphanSeriesRows(): Int
+
+ @Transaction
+ open suspend fun pruneOrphanLocalContentRows(): Int =
+ pruneOrphanLiveRows() + pruneOrphanMovieRows() + pruneOrphanSeriesRows()
+}
+
+@Dao
+interface XtreamIndexJobDao {
+ @Query("SELECT * FROM xtream_index_jobs ORDER BY provider_id ASC, section ASC")
+ fun observeAll(): Flow<List<XtreamIndexJobEntity>>
+
+ @Query("SELECT * FROM xtream_index_jobs WHERE provider_id = :providerId ORDER BY section ASC")
+ fun observeForProvider(providerId: Long): Flow<List<XtreamIndexJobEntity>>
+
+ @Query("SELECT * FROM xtream_index_jobs WHERE provider_id = :providerId AND section = :section")
+ suspend fun get(providerId: Long, section: String): XtreamIndexJobEntity?
+
+ @Insert(onConflict = OnConflictStrategy.REPLACE)
+ suspend fun upsert(entity: XtreamIndexJobEntity)
+
+ @Insert(onConflict = OnConflictStrategy.REPLACE)
+ suspend fun upsertAll(entities: List<XtreamIndexJobEntity>)
+
+ @Query(
+ """
+ UPDATE xtream_index_jobs
+ SET priority_category_id = :categoryId,
+ priority_requested_at = :requestedAt,
+ state = CASE
+ WHEN state IN ('IDLE', 'SUCCESS', 'STALE', 'FAILED_RETRYABLE', 'PARTIAL') THEN 'QUEUED'
+ ELSE state
+ END,
+ updated_at = :requestedAt
+ WHERE provider_id = :providerId AND section = :section
+ """
+ )
+ suspend fun requestCategoryPriority(
+ providerId: Long,
+ section: String,
+ categoryId: Long,
+ requestedAt: Long
+ ): Int
+
+ @Query("DELETE FROM xtream_index_jobs WHERE provider_id = :providerId")
+ suspend fun deleteByProvider(providerId: Long): Int
+}
diff --git a/data/src/main/java/com/streamvault/data/local/entity/Entities.kt b/data/src/main/java/com/streamvault/data/local/entity/Entities.kt
index 632734b6..a87b694f 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
@@ -218,7 +218,10 @@ data class MovieEntity(
@ColumnInfo(name = "is_adult") val isAdult: Boolean = false,
@ColumnInfo(name = "is_user_protected") val isUserProtected: Boolean = false,
@ColumnInfo(name = "sync_fingerprint") val syncFingerprint: String = "",
- @ColumnInfo(name = "added_at") val addedAt: Long = 0L
+ @ColumnInfo(name = "added_at") val addedAt: Long = 0L,
+ @ColumnInfo(name = "cache_state") val cacheState: String = "DETAIL_HYDRATED",
+ @ColumnInfo(name = "detail_hydrated_at") val detailHydratedAt: Long = 0L,
+ @ColumnInfo(name = "remote_stale_at") val remoteStaleAt: Long = 0L
)
data class MovieBrowseEntity(
@@ -284,7 +287,10 @@ data class SeriesEntity(
@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 = ""
+ @ColumnInfo(name = "sync_fingerprint") val syncFingerprint: String = "",
+ @ColumnInfo(name = "cache_state") val cacheState: String = "DETAIL_HYDRATED",
+ @ColumnInfo(name = "detail_hydrated_at") val detailHydratedAt: Long = 0L,
+ @ColumnInfo(name = "remote_stale_at") val remoteStaleAt: Long = 0L
)
data class SeriesBrowseEntity(
diff --git a/data/src/main/java/com/streamvault/data/local/entity/XtreamIndexEntities.kt b/data/src/main/java/com/streamvault/data/local/entity/XtreamIndexEntities.kt
new file mode 100644
index 00000000..596502a9
--- /dev/null
+++ b/data/src/main/java/com/streamvault/data/local/entity/XtreamIndexEntities.kt
@@ -0,0 +1,81 @@
+package com.streamvault.data.local.entity
+
+import androidx.room.ColumnInfo
+import androidx.room.Entity
+import androidx.room.ForeignKey
+import androidx.room.Index
+import com.streamvault.domain.model.ContentType
+
+@Entity(
+ tableName = "xtream_content_index",
+ primaryKeys = ["provider_id", "content_type", "remote_id"],
+ foreignKeys = [ForeignKey(
+ entity = ProviderEntity::class,
+ parentColumns = ["id"],
+ childColumns = ["provider_id"],
+ onDelete = ForeignKey.CASCADE
+ )],
+ indices = [
+ Index(value = ["provider_id", "content_type"]),
+ Index(value = ["provider_id", "content_type", "category_id"]),
+ Index(value = ["provider_id", "content_type", "name"]),
+ Index(value = ["provider_id", "content_type", "local_content_id"]),
+ Index(value = ["provider_id", "indexed_at"]),
+ Index(value = ["stale_state"])
+ ]
+)
+data class XtreamContentIndexEntity(
+ @ColumnInfo(name = "provider_id") val providerId: Long,
+ @ColumnInfo(name = "content_type") val contentType: ContentType,
+ @ColumnInfo(name = "remote_id") val remoteId: String,
+ @ColumnInfo(name = "local_content_id") val localContentId: Long? = null,
+ val name: String,
+ @ColumnInfo(name = "category_id") val categoryId: Long? = null,
+ @ColumnInfo(name = "category_name") val categoryName: String? = null,
+ @ColumnInfo(name = "image_url") val imageUrl: String? = null,
+ @ColumnInfo(name = "container_extension") val containerExtension: String? = null,
+ val rating: Float = 0f,
+ @ColumnInfo(name = "added_at") val addedAt: Long = 0L,
+ @ColumnInfo(name = "remote_updated_at") val remoteUpdatedAt: Long = 0L,
+ @ColumnInfo(name = "is_adult") val isAdult: Boolean = false,
+ @ColumnInfo(name = "indexed_at") val indexedAt: Long = 0L,
+ @ColumnInfo(name = "detail_hydrated_at") val detailHydratedAt: Long = 0L,
+ @ColumnInfo(name = "stale_state") val staleState: String = "ACTIVE",
+ @ColumnInfo(name = "error_state") val errorState: String? = null,
+ @ColumnInfo(name = "sync_fingerprint") val syncFingerprint: String = ""
+)
+
+@Entity(
+ tableName = "xtream_index_jobs",
+ primaryKeys = ["provider_id", "section"],
+ foreignKeys = [ForeignKey(
+ entity = ProviderEntity::class,
+ parentColumns = ["id"],
+ childColumns = ["provider_id"],
+ onDelete = ForeignKey.CASCADE
+ )],
+ indices = [
+ Index(value = ["provider_id"]),
+ Index(value = ["section"]),
+ Index(value = ["state"]),
+ Index(value = ["updated_at"])
+ ]
+)
+data class XtreamIndexJobEntity(
+ @ColumnInfo(name = "provider_id") val providerId: Long,
+ val section: String,
+ val state: String = "IDLE",
+ @ColumnInfo(name = "total_categories") val totalCategories: Int = 0,
+ @ColumnInfo(name = "completed_categories") val completedCategories: Int = 0,
+ @ColumnInfo(name = "next_category_index") val nextCategoryIndex: Int = 0,
+ @ColumnInfo(name = "failed_categories") val failedCategories: Int = 0,
+ @ColumnInfo(name = "indexed_rows") val indexedRows: Int = 0,
+ @ColumnInfo(name = "skipped_malformed_rows") val skippedMalformedRows: Int = 0,
+ @ColumnInfo(name = "deleted_pruned_rows") val deletedPrunedRows: Int = 0,
+ @ColumnInfo(name = "priority_category_id") val priorityCategoryId: Long? = null,
+ @ColumnInfo(name = "priority_requested_at") val priorityRequestedAt: Long = 0L,
+ @ColumnInfo(name = "last_error") val lastError: String? = null,
+ @ColumnInfo(name = "last_attempt_at") val lastAttemptAt: Long = 0L,
+ @ColumnInfo(name = "last_success_at") val lastSuccessAt: Long = 0L,
+ @ColumnInfo(name = "updated_at") val updatedAt: Long = 0L
+)
diff --git a/data/src/main/java/com/streamvault/data/manager/BackupManagerImpl.kt b/data/src/main/java/com/streamvault/data/manager/BackupManagerImpl.kt
index 23efde8c..e6bb747b 100644
--- a/data/src/main/java/com/streamvault/data/manager/BackupManagerImpl.kt
+++ b/data/src/main/java/com/streamvault/data/manager/BackupManagerImpl.kt
@@ -87,6 +87,7 @@ class BackupManagerImpl @Inject constructor(
"playerDecoderMode" to preferencesRepository.playerDecoderMode.first().name,
"playerSurfaceMode" to preferencesRepository.playerSurfaceMode.first().name,
"playerPlaybackSpeed" to preferencesRepository.playerPlaybackSpeed.first().toString(),
+ "playerAudioVideoSyncEnabled" to preferencesRepository.playerAudioVideoSyncEnabled.first().toString(),
"playerAudioVideoOffsetMs" to preferencesRepository.playerAudioVideoOffsetMs.first().toString(),
"preferredAudioLanguage" to (preferencesRepository.preferredAudioLanguage.first() ?: "auto"),
"playerSubtitleTextScale" to preferencesRepository.playerSubtitleTextScale.first().toString(),
@@ -510,6 +511,8 @@ class BackupManagerImpl @Inject constructor(
}
}
prefs["playerPlaybackSpeed"]?.toFloatOrNull()?.let { preferencesRepository.setPlayerPlaybackSpeed(it) }
+ prefs["playerAudioVideoSyncEnabled"]?.toBooleanStrictOrNull()
+ ?.let { preferencesRepository.setPlayerAudioVideoSyncEnabled(it) }
prefs["playerAudioVideoOffsetMs"]?.toIntOrNull()?.let {
preferencesRepository.setPlayerAudioVideoOffsetMs(it)
}
diff --git a/data/src/main/java/com/streamvault/data/preferences/PreferencesRepository.kt b/data/src/main/java/com/streamvault/data/preferences/PreferencesRepository.kt
index 45059353..dd08f7f3 100644
--- a/data/src/main/java/com/streamvault/data/preferences/PreferencesRepository.kt
+++ b/data/src/main/java/com/streamvault/data/preferences/PreferencesRepository.kt
@@ -119,6 +119,7 @@ class PreferencesRepository @Inject constructor(
val PLAYER_DECODER_MODE = stringPreferencesKey("player_decoder_mode")
val PLAYER_SURFACE_MODE = stringPreferencesKey("player_surface_mode")
val PLAYER_PLAYBACK_SPEED = stringPreferencesKey("player_playback_speed")
+ val PLAYER_AUDIO_VIDEO_SYNC_ENABLED = booleanPreferencesKey("player_av_sync_enabled")
val PLAYER_AUDIO_VIDEO_OFFSET_MS = intPreferencesKey("player_av_offset_ms")
val PREFERRED_AUDIO_LANGUAGE = stringPreferencesKey("preferred_audio_language")
val PLAYER_SUBTITLE_TEXT_SCALE = stringPreferencesKey("player_subtitle_text_scale")
@@ -284,6 +285,10 @@ class PreferencesRepository @Inject constructor(
.coerceIn(AUDIO_VIDEO_OFFSET_MIN_MS, AUDIO_VIDEO_OFFSET_MAX_MS)
}
+ val playerAudioVideoSyncEnabled: Flow<Boolean> = context.dataStore.data.map { preferences ->
+ preferences[PreferencesKeys.PLAYER_AUDIO_VIDEO_SYNC_ENABLED] ?: false
+ }
+
val preferredAudioLanguage: Flow<String?> = context.dataStore.data.map { preferences ->
preferences[PreferencesKeys.PREFERRED_AUDIO_LANGUAGE]
?.trim()
@@ -762,6 +767,12 @@ class PreferencesRepository @Inject constructor(
}
}
+ suspend fun setPlayerAudioVideoSyncEnabled(enabled: Boolean) {
+ context.dataStore.edit { preferences ->
+ preferences[PreferencesKeys.PLAYER_AUDIO_VIDEO_SYNC_ENABLED] = enabled
+ }
+ }
+
suspend fun setPreferredAudioLanguage(languageTag: String?) {
context.dataStore.edit { preferences ->
val normalized = languageTag
diff --git a/data/src/main/java/com/streamvault/data/remote/http/RequestIdentity.kt b/data/src/main/java/com/streamvault/data/remote/http/RequestIdentity.kt
new file mode 100644
index 00000000..867616ac
--- /dev/null
+++ b/data/src/main/java/com/streamvault/data/remote/http/RequestIdentity.kt
@@ -0,0 +1,87 @@
+package com.streamvault.data.remote.http
+
+import okhttp3.Interceptor
+import okhttp3.Request
+
+const val USER_AGENT_HEADER = "User-Agent"
+private val DIAGNOSTIC_HEADER_ALLOWLIST = setOf(
+ USER_AGENT_HEADER.lowercase(),
+ "accept",
+ "accept-encoding",
+ "referer",
+ "if-none-match",
+ "if-modified-since"
+)
+
+data class HttpRequestProfile(
+ val userAgent: String? = null,
+ val headers: Map<String, String> = emptyMap(),
+ val ownerTag: String? = null
+) {
+ fun mergedWithDefaults(defaultProfile: HttpRequestProfile): HttpRequestProfile =
+ HttpRequestProfile(
+ userAgent = userAgent?.takeIf { it.isNotBlank() } ?: defaultProfile.userAgent,
+ headers = defaultProfile.headers + headers,
+ ownerTag = ownerTag?.takeIf { it.isNotBlank() } ?: defaultProfile.ownerTag
+ )
+}
+
+fun Request.withRequestProfile(profile: HttpRequestProfile): Request {
+ val builder = newBuilder()
+ if (header(USER_AGENT_HEADER).isNullOrBlank()) {
+ profile.userAgent?.takeIf { it.isNotBlank() }?.let { builder.header(USER_AGENT_HEADER, it) }
+ }
+ profile.headers.forEach { (name, value) ->
+ if (name.isBlank() || value.isBlank()) return@forEach
+ if (header(name).isNullOrBlank()) {
+ builder.header(name, value)
+ }
+ }
+ return builder.build()
+}
+
+fun Request.safeRequestIdentitySummary(profile: HttpRequestProfile? = null): String {
+ val ownerSummary = profile?.ownerTag?.takeIf { it.isNotBlank() }?.let { "owner=$it, " }.orEmpty()
+ val userAgent = header(USER_AGENT_HEADER)?.takeIf { it.isNotBlank() } ?: "<none>"
+ val safeHeaders = headers.names()
+ .asSequence()
+ .map { it.trim() }
+ .filter { it.isNotEmpty() }
+ .filter { name ->
+ val normalized = name.lowercase()
+ normalized in DIAGNOSTIC_HEADER_ALLOWLIST && normalized != USER_AGENT_HEADER.lowercase()
+ }
+ .sorted()
+ .toList()
+ return buildString {
+ append(ownerSummary)
+ append("userAgent=")
+ append(userAgent)
+ append(", headers=")
+ append(safeHeaders)
+ }
+}
+
+class DefaultUserAgentInterceptor(
+ private val userAgent: String
+) : Interceptor {
+ override fun intercept(chain: Interceptor.Chain) =
+ chain.proceed(
+ chain.request().withRequestProfile(
+ HttpRequestProfile(userAgent = userAgent)
+ )
+ )
+}
+
+fun buildAppUserAgent(versionName: String?): String {
+ val normalizedVersion = versionName?.trim().orEmpty().ifBlank { "dev" }
+ return "StreamVault/$normalizedVersion (Android; Media3; OkHttp)"
+}
+
+fun buildAppRequestProfile(
+ versionName: String?,
+ ownerTag: String
+): HttpRequestProfile = HttpRequestProfile(
+ userAgent = buildAppUserAgent(versionName),
+ ownerTag = ownerTag
+)
\ No newline at end of file
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 f455d925..4c441099 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,6 @@
package com.streamvault.data.remote.xtream
+import android.util.Log
import com.google.gson.JsonParser
import com.google.gson.stream.JsonReader
import com.google.gson.stream.JsonToken
@@ -11,6 +12,9 @@ import com.streamvault.data.remote.dto.XtreamSeriesItem
import com.streamvault.data.remote.dto.XtreamStream
import com.streamvault.data.remote.dto.XtreamVodInfoResponse
import com.streamvault.data.remote.NetworkTimeoutConfig
+import com.streamvault.data.remote.http.HttpRequestProfile
+import com.streamvault.data.remote.http.safeRequestIdentitySummary
+import com.streamvault.data.remote.http.withRequestProfile
import java.io.IOException
import java.io.InputStream
import java.io.InputStreamReader
@@ -32,9 +36,11 @@ import java.util.concurrent.TimeUnit.SECONDS
@OptIn(ExperimentalSerializationApi::class)
class OkHttpXtreamApiService(
private val client: OkHttpClient,
- private val json: Json
+ private val json: Json,
+ private val defaultRequestProfile: HttpRequestProfile = HttpRequestProfile()
) : XtreamApiService {
private companion object {
+ const val TAG = "OkHttpXtreamApi"
const val PREVIEW_INPUT_LIMIT = 512
const val PREVIEW_OUTPUT_LIMIT = 140
const val RESPONSE_BUDGET_HEADROOM_BYTES = 1L * 1024L * 1024L
@@ -66,66 +72,121 @@ class OkHttpXtreamApiService(
.build()
}
- override suspend fun authenticate(endpoint: String): XtreamAuthResponse = get(endpoint)
+ override suspend fun authenticate(
+ endpoint: String,
+ requestProfile: HttpRequestProfile
+ ): XtreamAuthResponse = get(endpoint, requestProfile = requestProfile)
- override suspend fun getLiveCategories(endpoint: String): List<XtreamCategory> = get(endpoint)
+ override suspend fun getLiveCategories(
+ endpoint: String,
+ requestProfile: HttpRequestProfile
+ ): List<XtreamCategory> = get(endpoint, requestProfile = requestProfile)
- override suspend fun getLiveStreams(endpoint: String): List<XtreamStream> = get(endpoint, RequestProfile.HEAVY_CATALOG)
+ override suspend fun getLiveStreams(
+ endpoint: String,
+ requestProfile: HttpRequestProfile
+ ): List<XtreamStream> = get(endpoint, RequestProfile.HEAVY_CATALOG, requestProfile)
- override suspend fun getVodCategories(endpoint: String): List<XtreamCategory> = get(endpoint)
+ override suspend fun getVodCategories(
+ endpoint: String,
+ requestProfile: HttpRequestProfile
+ ): List<XtreamCategory> = get(endpoint, requestProfile = requestProfile)
- override suspend fun getVodStreams(endpoint: String): List<XtreamStream> = get(endpoint, RequestProfile.HEAVY_CATALOG)
+ override suspend fun getVodStreams(
+ endpoint: String,
+ requestProfile: HttpRequestProfile
+ ): List<XtreamStream> = get(endpoint, RequestProfile.HEAVY_CATALOG, requestProfile)
- suspend fun streamVodStreams(endpoint: String, onItem: suspend (XtreamStream) -> Unit): Int =
+ override suspend fun streamVodStreams(
+ endpoint: String,
+ requestProfile: HttpRequestProfile,
+ onItem: suspend (XtreamStream) -> Unit
+ ): Int =
streamArray(
endpoint = endpoint,
profile = RequestProfile.HEAVY_CATALOG,
+ requestProfile = requestProfile,
deserializer = XtreamStream.serializer(),
onItem = onItem
)
- suspend fun streamLiveStreams(endpoint: String, onItem: suspend (XtreamStream) -> Unit): Int =
+ suspend fun streamLiveStreams(
+ endpoint: String,
+ requestProfile: HttpRequestProfile = HttpRequestProfile(),
+ onItem: suspend (XtreamStream) -> Unit
+ ): Int =
streamArray(
endpoint = endpoint,
profile = RequestProfile.HEAVY_CATALOG,
+ requestProfile = requestProfile,
deserializer = XtreamStream.serializer(),
onItem = onItem
)
- override suspend fun getVodInfo(endpoint: String): XtreamVodInfoResponse = get(endpoint)
+ override suspend fun getVodInfo(
+ endpoint: String,
+ requestProfile: HttpRequestProfile
+ ): XtreamVodInfoResponse = get(endpoint, requestProfile = requestProfile)
- override suspend fun getSeriesCategories(endpoint: String): List<XtreamCategory> = get(endpoint)
+ override suspend fun getSeriesCategories(
+ endpoint: String,
+ requestProfile: HttpRequestProfile
+ ): List<XtreamCategory> = get(endpoint, requestProfile = requestProfile)
- override suspend fun getSeriesList(endpoint: String): List<XtreamSeriesItem> = get(endpoint, RequestProfile.HEAVY_CATALOG)
+ override suspend fun getSeriesList(
+ endpoint: String,
+ requestProfile: HttpRequestProfile
+ ): List<XtreamSeriesItem> = get(endpoint, RequestProfile.HEAVY_CATALOG, requestProfile)
- suspend fun streamSeriesList(endpoint: String, onItem: suspend (XtreamSeriesItem) -> Unit): Int =
+ override suspend fun streamSeriesList(
+ endpoint: String,
+ requestProfile: HttpRequestProfile,
+ onItem: suspend (XtreamSeriesItem) -> Unit
+ ): Int =
streamArray(
endpoint = endpoint,
profile = RequestProfile.HEAVY_CATALOG,
+ requestProfile = requestProfile,
deserializer = XtreamSeriesItem.serializer(),
onItem = onItem
)
- override suspend fun getSeriesInfo(endpoint: String): XtreamSeriesInfoResponse = get(endpoint)
+ override suspend fun getSeriesInfo(
+ endpoint: String,
+ requestProfile: HttpRequestProfile
+ ): XtreamSeriesInfoResponse = get(endpoint, requestProfile = requestProfile)
- override suspend fun getShortEpg(endpoint: String): XtreamEpgResponse = get(endpoint)
+ override suspend fun getShortEpg(
+ endpoint: String,
+ requestProfile: HttpRequestProfile
+ ): XtreamEpgResponse = get(endpoint, requestProfile = requestProfile)
- override suspend fun getFullEpg(endpoint: String): XtreamEpgResponse = get(endpoint)
+ override suspend fun getFullEpg(
+ endpoint: String,
+ requestProfile: HttpRequestProfile
+ ): XtreamEpgResponse = get(endpoint, requestProfile = requestProfile)
private suspend inline fun <reified T> get(
endpoint: String,
- profile: RequestProfile = RequestProfile.STANDARD
+ profile: RequestProfile = RequestProfile.STANDARD,
+ requestProfile: HttpRequestProfile = HttpRequestProfile()
): T = withContext(Dispatchers.IO) {
val descriptor = describeEndpoint(endpoint)
+ val effectiveRequestProfile = requestProfile.mergedWithDefaults(defaultRequestProfile)
val request = Request.Builder()
.url(endpoint)
.get()
.build()
+ .withRequestProfile(effectiveRequestProfile)
try {
val call = clientFor(profile).newCall(request)
call.execute().use { response ->
if (!response.isSuccessful) {
val message = "HTTP ${response.code}"
+ Log.w(
+ TAG,
+ "Xtream request failed for ${descriptor.hint} (${response.request.safeRequestIdentitySummary(effectiveRequestProfile)}): $message"
+ )
when (response.code) {
401 -> throw XtreamAuthenticationException(response.code, message)
403 -> {
@@ -150,6 +211,10 @@ class OkHttpXtreamApiService(
} catch (e: XtreamApiException) {
throw e
} catch (e: IOException) {
+ Log.w(
+ TAG,
+ "Xtream request network failure for ${descriptor.hint} (${request.safeRequestIdentitySummary(effectiveRequestProfile)}): ${XtreamUrlFactory.sanitizeLogMessage(e.message ?: "Network request failed")}"
+ )
throw XtreamNetworkException(XtreamUrlFactory.sanitizeLogMessage(e.message ?: "Network request failed"), e)
}
}
@@ -208,19 +273,26 @@ class OkHttpXtreamApiService(
private suspend fun <T> streamArray(
endpoint: String,
profile: RequestProfile,
+ requestProfile: HttpRequestProfile,
deserializer: DeserializationStrategy<T>,
onItem: suspend (T) -> Unit
): Int = withContext(Dispatchers.IO) {
val descriptor = describeEndpoint(endpoint)
+ val effectiveRequestProfile = requestProfile.mergedWithDefaults(defaultRequestProfile)
val request = Request.Builder()
.url(endpoint)
.get()
.build()
+ .withRequestProfile(effectiveRequestProfile)
try {
val call = clientFor(profile).newCall(request)
call.execute().use { response ->
if (!response.isSuccessful) {
val message = "HTTP ${response.code}"
+ Log.w(
+ TAG,
+ "Xtream streamed request failed for ${descriptor.hint} (${response.request.safeRequestIdentitySummary(effectiveRequestProfile)}): $message"
+ )
when (response.code) {
401 -> throw XtreamAuthenticationException(response.code, message)
403 -> {
@@ -247,6 +319,10 @@ class OkHttpXtreamApiService(
} catch (e: XtreamApiException) {
throw e
} catch (e: IOException) {
+ Log.w(
+ TAG,
+ "Xtream streamed request network failure for ${descriptor.hint} (${request.safeRequestIdentitySummary(effectiveRequestProfile)}): ${XtreamUrlFactory.sanitizeLogMessage(e.message ?: "Network request failed")}"
+ )
throw XtreamNetworkException(XtreamUrlFactory.sanitizeLogMessage(e.message ?: "Network request failed"), e)
}
}
diff --git a/data/src/main/java/com/streamvault/data/remote/xtream/XtreamApiService.kt b/data/src/main/java/com/streamvault/data/remote/xtream/XtreamApiService.kt
index a48bbe52..d041a1be 100644
--- a/data/src/main/java/com/streamvault/data/remote/xtream/XtreamApiService.kt
+++ b/data/src/main/java/com/streamvault/data/remote/xtream/XtreamApiService.kt
@@ -1,5 +1,6 @@
package com.streamvault.data.remote.xtream
+import com.streamvault.data.remote.http.HttpRequestProfile
import com.streamvault.data.remote.dto.XtreamAuthResponse
import com.streamvault.data.remote.dto.XtreamCategory
import com.streamvault.data.remote.dto.XtreamEpgResponse
@@ -12,25 +13,76 @@ import com.streamvault.data.remote.dto.XtreamVodInfoResponse
* Xtream Codes player API abstraction.
*/
interface XtreamApiService {
- suspend fun authenticate(endpoint: String): XtreamAuthResponse
+ suspend fun authenticate(
+ endpoint: String,
+ requestProfile: HttpRequestProfile = HttpRequestProfile()
+ ): XtreamAuthResponse
- suspend fun getLiveCategories(endpoint: String): List<XtreamCategory>
+ suspend fun getLiveCategories(
+ endpoint: String,
+ requestProfile: HttpRequestProfile = HttpRequestProfile()
+ ): List<XtreamCategory>
- suspend fun getLiveStreams(endpoint: String): List<XtreamStream>
+ suspend fun getLiveStreams(
+ endpoint: String,
+ requestProfile: HttpRequestProfile = HttpRequestProfile()
+ ): List<XtreamStream>
- suspend fun getVodCategories(endpoint: String): List<XtreamCategory>
+ suspend fun getVodCategories(
+ endpoint: String,
+ requestProfile: HttpRequestProfile = HttpRequestProfile()
+ ): List<XtreamCategory>
- suspend fun getVodStreams(endpoint: String): List<XtreamStream>
+ suspend fun getVodStreams(
+ endpoint: String,
+ requestProfile: HttpRequestProfile = HttpRequestProfile()
+ ): List<XtreamStream>
- suspend fun getVodInfo(endpoint: String): XtreamVodInfoResponse
+ suspend fun streamVodStreams(
+ endpoint: String,
+ requestProfile: HttpRequestProfile = HttpRequestProfile(),
+ onItem: suspend (XtreamStream) -> Unit
+ ): Int =
+ getVodStreams(endpoint, requestProfile).also { streams ->
+ streams.forEach { stream -> onItem(stream) }
+ }.size
- suspend fun getSeriesCategories(endpoint: String): List<XtreamCategory>
+ suspend fun getVodInfo(
+ endpoint: String,
+ requestProfile: HttpRequestProfile = HttpRequestProfile()
+ ): XtreamVodInfoResponse
- suspend fun getSeriesList(endpoint: String): List<XtreamSeriesItem>
+ suspend fun getSeriesCategories(
+ endpoint: String,
+ requestProfile: HttpRequestProfile = HttpRequestProfile()
+ ): List<XtreamCategory>
- suspend fun getSeriesInfo(endpoint: String): XtreamSeriesInfoResponse
+ suspend fun getSeriesList(
+ endpoint: String,
+ requestProfile: HttpRequestProfile = HttpRequestProfile()
+ ): List<XtreamSeriesItem>
- suspend fun getShortEpg(endpoint: String): XtreamEpgResponse
+ suspend fun streamSeriesList(
+ endpoint: String,
+ requestProfile: HttpRequestProfile = HttpRequestProfile(),
+ onItem: suspend (XtreamSeriesItem) -> Unit
+ ): Int =
+ getSeriesList(endpoint, requestProfile).also { items ->
+ items.forEach { item -> onItem(item) }
+ }.size
- suspend fun getFullEpg(endpoint: String): XtreamEpgResponse
+ suspend fun getSeriesInfo(
+ endpoint: String,
+ requestProfile: HttpRequestProfile = HttpRequestProfile()
+ ): XtreamSeriesInfoResponse
+
+ suspend fun getShortEpg(
+ endpoint: String,
+ requestProfile: HttpRequestProfile = HttpRequestProfile()
+ ): XtreamEpgResponse
+
+ suspend fun getFullEpg(
+ endpoint: String,
+ requestProfile: HttpRequestProfile = HttpRequestProfile()
+ ): XtreamEpgResponse
}
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 02e1fe8b..85191c2f 100644
--- a/data/src/main/java/com/streamvault/data/remote/xtream/XtreamProvider.kt
+++ b/data/src/main/java/com/streamvault/data/remote/xtream/XtreamProvider.kt
@@ -1,6 +1,7 @@
package com.streamvault.data.remote.xtream
import android.util.Log
+import com.streamvault.data.remote.http.HttpRequestProfile
import com.streamvault.data.remote.dto.*
import com.streamvault.data.util.AdultContentClassifier
import com.streamvault.domain.model.*
@@ -36,6 +37,7 @@ class XtreamProvider(
) : IptvProvider {
companion object {
private const val TAG = "XtreamProvider"
+ private const val STREAM_SUMMARY_BATCH_SIZE = 500
/**
* Offset-aware formatters for Xtream EPG textual timestamps.
@@ -84,10 +86,12 @@ class XtreamProvider(
private var liveOutputFormats: List<String> = normalizeAllowedOutputFormats(allowedOutputFormats)
private val adultCategoryCache = mutableMapOf<ContentType, Set<Long>>()
private val adultCategoryCacheMutex = Mutex()
+ private val requestProfile = HttpRequestProfile(ownerTag = "provider:$providerId/xtream")
override suspend fun authenticate(): Result<Provider> = try {
val response = api.authenticate(
- XtreamUrlFactory.buildPlayerApiUrl(serverUrl, username, password)
+ XtreamUrlFactory.buildPlayerApiUrl(serverUrl, username, password),
+ requestProfile
)
serverInfo = response.serverInfo
liveOutputFormats = normalizeAllowedOutputFormats(response.userInfo.allowedOutputFormats)
@@ -133,7 +137,8 @@ class XtreamProvider(
override suspend fun getLiveCategories(): Result<List<Category>> = try {
val categories = api.getLiveCategories(
- XtreamUrlFactory.buildPlayerApiUrl(serverUrl, username, password, action = "get_live_categories")
+ XtreamUrlFactory.buildPlayerApiUrl(serverUrl, username, password, action = "get_live_categories"),
+ requestProfile
)
cacheAdultCategoryIds(ContentType.LIVE, categories)
Result.success(categories.map { it.toDomain(ContentType.LIVE) })
@@ -150,7 +155,8 @@ class XtreamProvider(
password = password,
action = "get_live_streams",
extraQueryParams = mapOf("category_id" to categoryId?.toString())
- )
+ ),
+ requestProfile
)
Result.success(
streams.mapNotNull { stream ->
@@ -173,7 +179,8 @@ class XtreamProvider(
override suspend fun getVodCategories(): Result<List<Category>> = try {
val categories = api.getVodCategories(
- XtreamUrlFactory.buildPlayerApiUrl(serverUrl, username, password, action = "get_vod_categories")
+ XtreamUrlFactory.buildPlayerApiUrl(serverUrl, username, password, action = "get_vod_categories"),
+ requestProfile
)
cacheAdultCategoryIds(ContentType.MOVIE, categories)
Result.success(categories.map { it.toDomain(ContentType.MOVIE) })
@@ -190,7 +197,8 @@ class XtreamProvider(
password = password,
action = "get_vod_streams",
extraQueryParams = mapOf("category_id" to categoryId?.toString())
- )
+ ),
+ requestProfile
)
Result.success(
streams.mapNotNull { stream ->
@@ -209,6 +217,42 @@ class XtreamProvider(
Result.error(XtreamErrorFormatter.message("Failed to load VOD", e), e)
}
+ suspend fun streamVodSummaries(
+ categoryId: Long? = null,
+ batchSize: Int = STREAM_SUMMARY_BATCH_SIZE,
+ adultCategoryIds: Set<Long>? = null,
+ onBatch: suspend (List<Movie>) -> Unit
+ ): Result<Int> = try {
+ val resolvedAdultCategoryIds = adultCategoryIds ?: loadAdultCategoryIds(ContentType.MOVIE)
+ val buffer = mutableListOf<Movie>()
+ var acceptedCount = 0
+ api.streamVodStreams(
+ XtreamUrlFactory.buildPlayerApiUrl(
+ serverUrl = serverUrl,
+ username = username,
+ password = password,
+ action = "get_vod_streams",
+ extraQueryParams = mapOf("category_id" to categoryId?.toString())
+ ),
+ requestProfile
+ ) { stream ->
+ mapVodStream(stream, resolvedAdultCategoryIds)?.let { movie ->
+ buffer += movie
+ acceptedCount++
+ if (buffer.size >= batchSize) {
+ onBatch(buffer.toList())
+ buffer.clear()
+ }
+ }
+ }
+ if (buffer.isNotEmpty()) {
+ onBatch(buffer.toList())
+ }
+ Result.success(acceptedCount)
+ } catch (e: Exception) {
+ Result.error(XtreamErrorFormatter.message("Failed to stream VOD index", e), e)
+ }
+
override suspend fun getVodInfo(vodId: Long): Result<Movie> = try {
val response = api.getVodInfo(
XtreamUrlFactory.buildPlayerApiUrl(
@@ -217,7 +261,8 @@ class XtreamProvider(
password = password,
action = "get_vod_info",
extraQueryParams = mapOf("vod_id" to vodId.toString())
- )
+ ),
+ requestProfile
)
val movieData = response.movieData
val info = response.info
@@ -276,7 +321,8 @@ class XtreamProvider(
override suspend fun getSeriesCategories(): Result<List<Category>> = try {
val categories = api.getSeriesCategories(
- XtreamUrlFactory.buildPlayerApiUrl(serverUrl, username, password, action = "get_series_categories")
+ XtreamUrlFactory.buildPlayerApiUrl(serverUrl, username, password, action = "get_series_categories"),
+ requestProfile
)
cacheAdultCategoryIds(ContentType.SERIES, categories)
Result.success(categories.map { it.toDomain(ContentType.SERIES) })
@@ -293,7 +339,8 @@ class XtreamProvider(
password = password,
action = "get_series",
extraQueryParams = mapOf("category_id" to categoryId?.toString())
- )
+ ),
+ requestProfile
)
Result.success(
items.mapNotNull { item ->
@@ -312,6 +359,42 @@ class XtreamProvider(
Result.error(XtreamErrorFormatter.message("Failed to load series", e), e)
}
+ suspend fun streamSeriesSummaries(
+ categoryId: Long? = null,
+ batchSize: Int = STREAM_SUMMARY_BATCH_SIZE,
+ adultCategoryIds: Set<Long>? = null,
+ onBatch: suspend (List<Series>) -> Unit
+ ): Result<Int> = try {
+ val resolvedAdultCategoryIds = adultCategoryIds ?: loadAdultCategoryIds(ContentType.SERIES)
+ val buffer = mutableListOf<Series>()
+ var acceptedCount = 0
+ api.streamSeriesList(
+ XtreamUrlFactory.buildPlayerApiUrl(
+ serverUrl = serverUrl,
+ username = username,
+ password = password,
+ action = "get_series",
+ extraQueryParams = mapOf("category_id" to categoryId?.toString())
+ ),
+ requestProfile
+ ) { item ->
+ mapSeriesItem(item, resolvedAdultCategoryIds)?.let { series ->
+ buffer += series
+ acceptedCount++
+ if (buffer.size >= batchSize) {
+ onBatch(buffer.toList())
+ buffer.clear()
+ }
+ }
+ }
+ if (buffer.isNotEmpty()) {
+ onBatch(buffer.toList())
+ }
+ Result.success(acceptedCount)
+ } catch (e: Exception) {
+ Result.error(XtreamErrorFormatter.message("Failed to stream series index", e), e)
+ }
+
override suspend fun getSeriesInfo(seriesId: Long): Result<Series> = try {
val response = requestSeriesInfoWithCompatibilityFallback(seriesId)
val info = response.info
@@ -404,7 +487,8 @@ class XtreamProvider(
password = password,
action = "get_simple_data_table",
extraQueryParams = mapOf("stream_id" to streamId.toString())
- )
+ ),
+ requestProfile
)
Result.success(response.epgListings.mapNotNull { it.toDomainOrNull() })
} catch (e: Exception) {
@@ -423,7 +507,8 @@ class XtreamProvider(
"stream_id" to streamId.toString(),
"limit" to limit.toString()
)
- )
+ ),
+ requestProfile
)
Result.success(response.epgListings.mapNotNull { it.toDomainOrNull() })
} catch (e: Exception) {
@@ -554,13 +639,16 @@ class XtreamProvider(
val categories = runCatching {
when (type) {
ContentType.LIVE -> api.getLiveCategories(
- XtreamUrlFactory.buildPlayerApiUrl(serverUrl, username, password, action = "get_live_categories")
+ XtreamUrlFactory.buildPlayerApiUrl(serverUrl, username, password, action = "get_live_categories"),
+ requestProfile
)
ContentType.MOVIE -> api.getVodCategories(
- XtreamUrlFactory.buildPlayerApiUrl(serverUrl, username, password, action = "get_vod_categories")
+ XtreamUrlFactory.buildPlayerApiUrl(serverUrl, username, password, action = "get_vod_categories"),
+ requestProfile
)
ContentType.SERIES -> api.getSeriesCategories(
- XtreamUrlFactory.buildPlayerApiUrl(serverUrl, username, password, action = "get_series_categories")
+ XtreamUrlFactory.buildPlayerApiUrl(serverUrl, username, password, action = "get_series_categories"),
+ requestProfile
)
ContentType.SERIES_EPISODE -> emptyList()
}
@@ -877,7 +965,8 @@ class XtreamProvider(
password = password,
action = "get_series_info",
extraQueryParams = mapOf(queryParamName to seriesId.toString())
- )
+ ),
+ requestProfile
)
}
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 543cebb7..23a6d902 100644
--- a/data/src/main/java/com/streamvault/data/repository/ChannelRepositoryImpl.kt
+++ b/data/src/main/java/com/streamvault/data/repository/ChannelRepositoryImpl.kt
@@ -34,10 +34,10 @@ import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.withContext
import kotlinx.coroutines.flow.Flow
-import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.emitAll
import kotlinx.coroutines.flow.first
+import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.flowOn
@@ -364,13 +364,15 @@ class ChannelRepositoryImpl @Inject constructor(
} else if (categoryId == ChannelRepository.ALL_CHANNELS_ID) {
safeSearchFlow(
source = channelDao.search(providerId, ftsQuery, limit),
- fallback = channelDao.searchFallback(providerId, query.trim().toSqlLikePattern(), limit),
+ fallback = { channelDao.searchFallback(providerId, query.trim().toSqlLikePattern(), limit) },
rawQuery = query.trim()
)
} else {
safeSearchFlow(
source = channelDao.searchByCategory(providerId, categoryId, ftsQuery, limit),
- fallback = channelDao.searchByCategoryFallback(providerId, categoryId, query.trim().toSqlLikePattern(), limit),
+ fallback = {
+ channelDao.searchByCategoryFallback(providerId, categoryId, query.trim().toSqlLikePattern(), limit)
+ },
rawQuery = query.trim()
)
}
@@ -689,17 +691,22 @@ class ChannelRepositoryImpl @Inject constructor(
private fun safeSearchFlow(
source: Flow<List<ChannelBrowseEntity>>,
- fallback: Flow<List<ChannelBrowseEntity>>,
+ fallback: () -> Flow<List<ChannelBrowseEntity>>,
rawQuery: String
- ): Flow<List<ChannelBrowseEntity>> =
- source.catch { error ->
- if (error is SQLiteException) {
- Log.w(TAG, "FTS channel search failed for query '$rawQuery'; falling back to LIKE search", error)
- emitAll(fallback)
- } else {
- throw error
+ ): Flow<List<ChannelBrowseEntity>> = flow {
+ try {
+ source.collect { ftsRows ->
+ if (ftsRows.isEmpty()) {
+ emitAll(fallback())
+ } else {
+ emit(ftsRows)
+ }
}
+ } catch (error: SQLiteException) {
+ Log.w(TAG, "FTS channel search failed for query '$rawQuery'; using LIKE-only search", error)
+ emitAll(fallback())
}
+ }
private fun String.toSqlLikePattern(): String {
val escaped = buildString(length) {
diff --git a/data/src/main/java/com/streamvault/data/repository/EpgSourceRepositoryImpl.kt b/data/src/main/java/com/streamvault/data/repository/EpgSourceRepositoryImpl.kt
index 28f2e802..cd7d7e4e 100644
--- a/data/src/main/java/com/streamvault/data/repository/EpgSourceRepositoryImpl.kt
+++ b/data/src/main/java/com/streamvault/data/repository/EpgSourceRepositoryImpl.kt
@@ -24,6 +24,9 @@ import com.streamvault.domain.model.EpgOverrideCandidate
import com.streamvault.domain.model.EpgSourceType
import com.streamvault.data.parser.XmltvParser
import com.streamvault.data.util.UrlSecurityPolicy
+import com.streamvault.data.remote.http.HttpRequestProfile
+import com.streamvault.data.remote.http.safeRequestIdentitySummary
+import com.streamvault.data.remote.http.withRequestProfile
import com.streamvault.domain.model.ChannelEpgMapping
import com.streamvault.domain.model.ContentType
import com.streamvault.domain.model.EpgResolutionSummary
@@ -240,6 +243,7 @@ class EpgSourceRepositoryImpl @Inject constructor(
// This prevents double-decompression when the URL ends in .gz:
// OkHttp would silently decompress gzip responses, and then
// maybeDecompressGzip() would try again — corrupting the stream.
+ val requestProfile = HttpRequestProfile(ownerTag = "epg-source:$sourceId")
val request = Request.Builder()
.url(source.url)
.header("Accept-Encoding", "identity")
@@ -248,6 +252,7 @@ class EpgSourceRepositoryImpl @Inject constructor(
source.lastModifiedHeader?.let { header("If-Modified-Since", it) }
}
.build()
+ .withRequestProfile(requestProfile)
val response = epgHttpClient.newCall(request).execute()
if (response.code == 304) {
@@ -261,6 +266,10 @@ class EpgSourceRepositoryImpl @Inject constructor(
}
if (!response.isSuccessful) {
+ Log.w(
+ TAG,
+ "EPG request failed for source $sourceId (${response.request.safeRequestIdentitySummary(requestProfile)}): HTTP ${response.code}"
+ )
val err = "HTTP ${response.code}"
response.close()
epgSourceDao.updateRefreshError(sourceId, err)
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 a553b229..6c7b8acf 100644
--- a/data/src/main/java/com/streamvault/data/repository/MovieRepositoryImpl.kt
+++ b/data/src/main/java/com/streamvault/data/repository/MovieRepositoryImpl.kt
@@ -9,6 +9,7 @@ import com.streamvault.data.local.dao.MovieCategoryHydrationDao
import com.streamvault.data.local.dao.MovieDao
import com.streamvault.data.local.dao.PlaybackHistoryDao
import com.streamvault.data.local.dao.ProviderDao
+import com.streamvault.data.local.dao.XtreamContentIndexDao
import com.streamvault.data.local.entity.ProviderEntity
import com.streamvault.data.local.entity.CategoryEntity
import com.streamvault.data.local.entity.MovieBrowseEntity
@@ -23,6 +24,7 @@ import com.streamvault.data.remote.xtream.XtreamStreamUrlResolver
import com.streamvault.data.remote.xtream.XtreamProvider
import com.streamvault.data.security.CredentialCrypto
import com.streamvault.data.sync.ContentCachePolicy
+import com.streamvault.data.sync.SyncManager
import com.streamvault.data.util.rankSearchResults
import com.streamvault.data.util.toFtsPrefixQuery
import com.streamvault.domain.model.Category
@@ -38,7 +40,6 @@ import com.streamvault.domain.model.Result
import com.streamvault.domain.model.Result.Success
import com.streamvault.domain.model.StreamInfo
import com.streamvault.domain.model.StreamType
-import com.streamvault.domain.model.VodSyncMode
import com.streamvault.domain.repository.MovieRepository
import com.streamvault.domain.repository.PlaybackHistoryRepository
import com.streamvault.domain.repository.SyncMetadataRepository
@@ -55,10 +56,9 @@ import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOf
+import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.map
-import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.launch
-import kotlinx.coroutines.withTimeout
import java.util.concurrent.ConcurrentHashMap
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
@@ -81,6 +81,8 @@ class MovieRepositoryImpl @Inject constructor(
private val xtreamStreamUrlResolver: XtreamStreamUrlResolver,
private val movieCategoryHydrationDao: MovieCategoryHydrationDao,
private val syncMetadataRepository: SyncMetadataRepository,
+ private val xtreamContentIndexDao: XtreamContentIndexDao,
+ private val syncManager: SyncManager,
private val transactionRunner: DatabaseTransactionRunner
) : MovieRepository {
private companion object {
@@ -89,12 +91,14 @@ class MovieRepositoryImpl @Inject constructor(
const val SEARCH_OVERSAMPLE_LIMIT = 500
const val MIN_SEARCH_QUERY_LENGTH = 2
const val BROWSE_WINDOW_BUFFER = 80
- const val XTREAM_MOVIE_HYDRATION_TIMEOUT_MILLIS = 60_000L
const val XTREAM_CATEGORY_HYDRATION_CONCURRENCY = 1
const val XTREAM_EMPTY_CATEGORY_RETRY_COOLDOWN_MILLIS = 30_000L
const val CURSOR_BATCH_SIZE = 40
const val STALKER_PREVIEW_REQUIRED_COUNT_THRESHOLD = 24
const val STALKER_PREVIEW_MAX_REMOTE_PAGES = 2
+ const val DETAIL_REFRESH_TTL_MILLIS = 14L * 24L * 60L * 60L * 1000L
+ const val CACHE_STATE_SUMMARY_ONLY = "SUMMARY_ONLY"
+ const val CACHE_STATE_DETAIL_HYDRATED = "DETAIL_HYDRATED"
}
private data class CachedXtreamProvider(
@@ -328,7 +332,8 @@ class MovieRepositoryImpl @Inject constructor(
override fun browseMovies(query: LibraryBrowseQuery): Flow<PagedResult<Movie>> {
return flow {
- query.categoryId?.let {
+ val normalizedSearch = query.searchQuery.trim()
+ query.categoryId?.takeIf { normalizedSearch.length < MIN_SEARCH_QUERY_LENGTH }?.let {
ensureXtreamCategoryLoaded(
query.providerId,
it,
@@ -338,7 +343,7 @@ class MovieRepositoryImpl @Inject constructor(
)
}
emit(fetchMovieBrowseResult(query))
- }
+ }.flowOn(Dispatchers.IO)
}
override fun searchMovies(providerId: Long, query: String): Flow<List<Movie>> =
@@ -347,8 +352,10 @@ class MovieRepositoryImpl @Inject constructor(
flowOf(emptyList())
} else combine(
safeMovieSearchFlow(
- source = movieDao.search(providerId, ftsQuery, SEARCH_OVERSAMPLE_LIMIT),
- fallback = movieDao.searchFallback(providerId, query.trim().toSqlLikePattern(), SEARCH_OVERSAMPLE_LIMIT),
+ source = movieDao.search(providerId, ftsQuery, SEARCH_RESULT_LIMIT),
+ fallback = {
+ movieDao.searchFallback(providerId, query.trim().toSqlLikePattern(), SEARCH_RESULT_LIMIT)
+ },
rawQuery = query.trim()
),
preferencesRepository.parentalControlLevel
@@ -377,6 +384,10 @@ class MovieRepositoryImpl @Inject constructor(
val provider = providerDao.getById(providerId)
?: return Result.error("Provider not found")
+ if (provider.type == ProviderType.XTREAM_CODES && movieEntity.hasFreshXtreamDetails()) {
+ return Result.success(movieEntity.toDomain())
+ }
+
val remoteMovieResult = try {
when (provider.type) {
ProviderType.XTREAM_CODES -> getOrCreateXtreamProvider(providerId, provider).getVodInfo(movieEntity.streamId)
@@ -384,6 +395,14 @@ class MovieRepositoryImpl @Inject constructor(
ProviderType.M3U -> return Result.success(movieEntity.toDomain())
}
} catch (e: Exception) {
+ if (provider.type == ProviderType.XTREAM_CODES) {
+ xtreamContentIndexDao.markDetailHydrationError(
+ providerId = providerId,
+ contentType = ContentType.MOVIE.name,
+ remoteId = movieEntity.streamId.toString(),
+ errorState = "DETAIL_FAILED_RETRYABLE"
+ )
+ }
return Result.success(movieEntity.toDomain())
}
@@ -406,12 +425,32 @@ class MovieRepositoryImpl @Inject constructor(
rating = if (remoteMovie.rating > 0f) remoteMovie.rating else movieEntity.rating,
year = remoteMovie.year ?: movieEntity.year,
tmdbId = remoteMovie.tmdbId ?: movieEntity.tmdbId,
- youtubeTrailer = remoteMovie.youtubeTrailer ?: movieEntity.youtubeTrailer
+ youtubeTrailer = remoteMovie.youtubeTrailer ?: movieEntity.youtubeTrailer,
+ cacheState = CACHE_STATE_DETAIL_HYDRATED,
+ detailHydratedAt = System.currentTimeMillis()
)
movieDao.update(updatedMovie)
+ xtreamContentIndexDao.markDetailHydrated(
+ providerId = providerId,
+ contentType = ContentType.MOVIE.name,
+ remoteId = movieEntity.streamId.toString(),
+ localContentId = movieEntity.id,
+ imageUrl = updatedMovie.posterUrl,
+ detailHydratedAt = updatedMovie.detailHydratedAt
+ )
Result.success((movieDao.getById(movieEntity.id) ?: updatedMovie).toDomain())
}
- is Result.Error -> Result.success(movieEntity.toDomain())
+ is Result.Error -> {
+ if (provider.type == ProviderType.XTREAM_CODES) {
+ xtreamContentIndexDao.markDetailHydrationError(
+ providerId = providerId,
+ contentType = ContentType.MOVIE.name,
+ remoteId = movieEntity.streamId.toString(),
+ errorState = "DETAIL_FAILED_RETRYABLE"
+ )
+ }
+ Result.success(movieEntity.toDomain())
+ }
is Result.Loading -> Result.error("Unexpected loading state")
}
}
@@ -557,12 +596,14 @@ class MovieRepositoryImpl @Inject constructor(
combine(
safeMovieSearchFlow(
source = movieDao.searchByCategory(query.providerId, categoryId, ftsQuery, SEARCH_OVERSAMPLE_LIMIT),
- fallback = movieDao.searchByCategoryFallback(
- query.providerId,
- categoryId,
- normalizedSearch.toSqlLikePattern(),
- SEARCH_OVERSAMPLE_LIMIT
- ),
+ fallback = {
+ movieDao.searchByCategoryFallback(
+ query.providerId,
+ categoryId,
+ normalizedSearch.toSqlLikePattern(),
+ SEARCH_OVERSAMPLE_LIMIT
+ )
+ },
rawQuery = normalizedSearch
),
preferencesRepository.parentalControlLevel
@@ -803,6 +844,48 @@ class MovieRepositoryImpl @Inject constructor(
(query.offset + query.limit + BROWSE_WINDOW_BUFFER).coerceAtMost(SEARCH_RESULT_LIMIT)
private suspend fun fetchMovieBrowseResult(query: LibraryBrowseQuery): PagedResult<Movie> {
+ val normalizedSearch = query.searchQuery.trim()
+ if (normalizedSearch.length >= MIN_SEARCH_QUERY_LENGTH && supportsFastMovieSearchBrowse(query)) {
+ return fetchFastMovieSearchBrowseResult(query, normalizedSearch)
+ }
+
+ if (normalizedSearch.length >= MIN_SEARCH_QUERY_LENGTH) {
+ val searchResults = movieBrowseSource(query).first()
+ val favoriteIds = favoriteDao.getAllByType(query.providerId, ContentType.MOVIE.name)
+ .first()
+ .asSequence()
+ .filter { it.groupId == null }
+ .map { it.contentId }
+ .toSet()
+ val history = playbackHistoryDao.getByProvider(query.providerId).first()
+ val inProgressIds = history
+ .asSequence()
+ .filter { it.contentType == ContentType.MOVIE }
+ .filter { it.resumePositionMs > 0L && (it.totalDurationMs <= 0L || !moviePlaybackComplete(it.resumePositionMs, it.totalDurationMs)) }
+ .map { it.contentId }
+ .toSet()
+ val watchCounts = history
+ .asSequence()
+ .filter { it.contentType == ContentType.MOVIE }
+ .associate { it.contentId to it.watchCount }
+ val filteredResults = applyMovieBrowseQuery(
+ movies = searchResults,
+ query = query,
+ favoriteIds = favoriteIds,
+ inProgressIds = inProgressIds,
+ watchCounts = watchCounts
+ )
+ val items = filteredResults.drop(query.offset).take(query.limit)
+
+ return PagedResult(
+ items = items,
+ totalCount = filteredResults.size,
+ offset = query.offset,
+ limit = query.limit,
+ hasMoreRemote = false
+ )
+ }
+
val totalCount = movieBrowseTotalCount(query).first()
val favoriteIds = favoriteDao.getAllByType(query.providerId, ContentType.MOVIE.name)
.first()
@@ -854,6 +937,59 @@ class MovieRepositoryImpl @Inject constructor(
)
}
+ private suspend fun fetchFastMovieSearchBrowseResult(
+ query: LibraryBrowseQuery,
+ normalizedSearch: String
+ ): PagedResult<Movie> {
+ val ftsQuery = normalizedSearch.toFtsPrefixQuery() ?: return PagedResult(
+ items = emptyList(),
+ totalCount = 0,
+ offset = query.offset,
+ limit = query.limit
+ )
+ val includeProtected = if (preferencesRepository.parentalControlLevel.first() >= 3) 0 else 1
+ val pageLimit = query.limit + 1
+ val rows = query.categoryId?.let { categoryId ->
+ movieDao.searchByCategoryPage(
+ providerId = query.providerId,
+ categoryId = categoryId,
+ query = ftsQuery,
+ rawQuery = normalizedSearch,
+ prefixLike = normalizedSearch.toSqlPrefixLikePattern(),
+ includeProtected = includeProtected,
+ limit = pageLimit,
+ offset = query.offset
+ )
+ } ?: movieDao.searchPage(
+ providerId = query.providerId,
+ query = ftsQuery,
+ rawQuery = normalizedSearch,
+ prefixLike = normalizedSearch.toSqlPrefixLikePattern(),
+ includeProtected = includeProtected,
+ limit = pageLimit,
+ offset = query.offset
+ )
+ val hasMore = rows.size > query.limit
+ val favoriteIds = favoriteDao.getAllByType(query.providerId, ContentType.MOVIE.name)
+ .first()
+ .asSequence()
+ .filter { it.groupId == null }
+ .map { it.contentId }
+ .toSet()
+ val items = rows
+ .take(query.limit)
+ .map { it.toDomain() }
+ .map { movie -> if (movie.id in favoriteIds) movie.copy(isFavorite = true) else movie }
+
+ return PagedResult(
+ items = items,
+ totalCount = query.offset + items.size + if (hasMore) 1 else 0,
+ offset = query.offset,
+ limit = query.limit,
+ hasMoreRemote = hasMore
+ )
+ }
+
private suspend fun fetchMovieCursorWindow(
query: LibraryBrowseQuery,
favoriteIds: Set<Long>
@@ -1010,6 +1146,10 @@ class MovieRepositoryImpl @Inject constructor(
}
}
+ private fun supportsFastMovieSearchBrowse(query: LibraryBrowseQuery): Boolean =
+ query.filterBy.type == LibraryFilterType.ALL &&
+ query.sortBy in setOf(LibrarySortBy.LIBRARY, LibrarySortBy.TITLE)
+
private fun movieMatchesFilter(movie: Movie, filterType: LibraryFilterType, inProgressIds: Set<Long>): Boolean = when (filterType) {
LibraryFilterType.ALL -> true
LibraryFilterType.FAVORITES -> movie.isFavorite
@@ -1029,17 +1169,22 @@ class MovieRepositoryImpl @Inject constructor(
private fun safeMovieSearchFlow(
source: Flow<List<MovieBrowseEntity>>,
- fallback: Flow<List<MovieBrowseEntity>>,
+ fallback: () -> Flow<List<MovieBrowseEntity>>,
rawQuery: String
- ): Flow<List<MovieBrowseEntity>> =
- source.catch { error ->
- if (error is SQLiteException) {
- Log.w(TAG, "FTS movie search failed for query '$rawQuery'; falling back to LIKE search", error)
- emitAll(fallback)
- } else {
- throw error
+ ): Flow<List<MovieBrowseEntity>> = flow {
+ try {
+ source.collect { ftsRows ->
+ if (ftsRows.isEmpty()) {
+ emit(emptyList())
+ } else {
+ emit(ftsRows)
+ }
}
+ } catch (error: SQLiteException) {
+ Log.w(TAG, "FTS movie search failed for queryLength=${rawQuery.length}; using LIKE-only search", error)
+ emitAll(fallback())
}
+ }
private fun String.toSqlLikePattern(): String {
val escaped = buildString(length) {
@@ -1053,6 +1198,18 @@ class MovieRepositoryImpl @Inject constructor(
return "%$escaped%"
}
+ private fun String.toSqlPrefixLikePattern(): String {
+ val escaped = buildString(length) {
+ [email protected] { char ->
+ when (char) {
+ '%', '_', '\\' -> append('\\')
+ }
+ append(char)
+ }
+ }
+ return "$escaped%"
+ }
+
private suspend fun ensureXtreamCategoryLoaded(
providerId: Long,
categoryId: Long,
@@ -1068,6 +1225,14 @@ class MovieRepositoryImpl @Inject constructor(
val localCount = movieDao.getCountByCategory(providerId, categoryId).first()
val hydration = movieCategoryHydrationDao.get(providerId, categoryId)
+ if (provider.type == ProviderType.XTREAM_CODES) {
+ if (localCount > 0) {
+ freshXtreamCategories.add(key)
+ } else {
+ syncManager.prioritizeXtreamIndexCategory(providerId, ContentType.MOVIE, categoryId)
+ }
+ return
+ }
if (provider.type == ProviderType.STALKER_PORTAL) {
hydrateStalkerMovieCategoryToCount(
providerId = providerId,
@@ -1080,40 +1245,6 @@ class MovieRepositoryImpl @Inject constructor(
)
return
}
- val hasFreshHydration = hydration?.isFresh() == true &&
- (localCount > 0 || hydration.itemCount == 0) &&
- !forceRefresh
- if (hasFreshHydration) {
- freshXtreamCategories.add(key)
- return
- }
-
- if (localCount > 0 && !forceRefresh && refreshStaleInBackground && shouldUsePersistedCategoryHydration(provider, providerId)) {
- freshXtreamCategories.remove(key)
- triggerXtreamCategoryHydration(
- providerId = providerId,
- categoryId = categoryId,
- fetchIfMissing = false,
- refreshStaleInBackground = true
- )
- return
- }
-
- if (localCount > 0 && !forceRefresh && !shouldUsePersistedCategoryHydration(provider, providerId)) {
- return
- }
-
- if (!fetchIfMissing && localCount == 0) {
- triggerXtreamCategoryHydration(
- providerId = providerId,
- categoryId = categoryId,
- fetchIfMissing = true,
- refreshStaleInBackground = true
- )
- return
- }
-
- hydrateXtreamCategory(providerId, categoryId, provider, forceRefresh = forceRefresh)
}
private fun triggerXtreamCategoryHydration(
@@ -1132,6 +1263,9 @@ class MovieRepositoryImpl @Inject constructor(
if (provider.type != ProviderType.XTREAM_CODES && provider.type != ProviderType.STALKER_PORTAL) {
return@launch
}
+ if (provider.type == ProviderType.XTREAM_CODES) {
+ return@launch
+ }
val localCount = movieDao.getCountByCategory(providerId, categoryId).first()
val hydration = movieCategoryHydrationDao.get(providerId, categoryId)
if (provider.type == ProviderType.STALKER_PORTAL) {
@@ -1146,107 +1280,12 @@ class MovieRepositoryImpl @Inject constructor(
)
return@launch
}
- if (hydration?.isFresh() == true && (localCount > 0 || hydration.itemCount == 0)) return@launch
- if (localCount == 0 && hydration?.isEmptyRetryCoolingDown() == true) return@launch
- if (localCount == 0 && !fetchIfMissing) return@launch
- if (localCount > 0 && !refreshStaleInBackground && !fetchIfMissing) return@launch
- if (!shouldUsePersistedCategoryHydration(provider, providerId) && localCount > 0) {
- return@launch
- }
- hydrateXtreamCategory(providerId, categoryId, provider, forceRefresh = localCount > 0)
} finally {
backgroundRefreshes.remove(key)
}
}
}
- private suspend fun hydrateXtreamCategory(
- providerId: Long,
- categoryId: Long,
- provider: ProviderEntity,
- forceRefresh: Boolean
- ) {
- val key = "$providerId:$categoryId"
- val lock = xtreamCategoryLoadLocks.getOrPut(key) { Mutex() }
- lock.withLock {
- val localCount = movieDao.getCountByCategory(providerId, categoryId).first()
- val hydration = movieCategoryHydrationDao.get(providerId, categoryId)
- if (!forceRefresh && hydration?.isFresh() == true && (localCount > 0 || hydration.itemCount == 0)) {
- freshXtreamCategories.add(key)
- return
- }
-
- runCatching {
- val result = withTimeout(XTREAM_MOVIE_HYDRATION_TIMEOUT_MILLIS) {
- if (provider.type == ProviderType.XTREAM_CODES) {
- getOrCreateXtreamProvider(providerId, provider).getVodStreams(categoryId)
- } else {
- return@withTimeout Success(emptyList())
- }
- }
- when (result) {
- is Success -> {
- val entities = result.data.map { movie -> movie.toEntity() }
- val lazyXtreamHydration = provider.type == ProviderType.XTREAM_CODES &&
- shouldUsePersistedCategoryHydration(provider, providerId)
- if (lazyXtreamHydration && entities.isEmpty()) {
- movieCategoryHydrationDao.upsert(
- MovieCategoryHydrationEntity(
- providerId = providerId,
- categoryId = categoryId,
- lastHydratedAt = System.currentTimeMillis(),
- itemCount = localCount,
- lastStatus = "EMPTY_RETRY",
- lastError = "Xtream category returned an empty result; retry pending.",
- lastLoadedPage = 0,
- totalPages = 0,
- isComplete = false,
- pageSize = 0
- )
- )
- freshXtreamCategories.remove(key)
- } else {
- transactionRunner.inTransaction {
- movieDao.replaceCategory(providerId, categoryId, entities)
- movieCategoryHydrationDao.upsert(
- MovieCategoryHydrationEntity(
- providerId = providerId,
- categoryId = categoryId,
- lastHydratedAt = System.currentTimeMillis(),
- itemCount = entities.size,
- lastStatus = "SUCCESS",
- lastError = null,
- lastLoadedPage = 1,
- totalPages = 1,
- isComplete = true,
- pageSize = entities.size
- )
- )
- }
- freshXtreamCategories.add(key)
- }
- }
- else -> Unit
- }
- }.onFailure { error ->
- movieCategoryHydrationDao.upsert(
- MovieCategoryHydrationEntity(
- providerId = providerId,
- categoryId = categoryId,
- lastHydratedAt = hydration?.lastHydratedAt ?: 0L,
- itemCount = localCount,
- lastStatus = "ERROR",
- lastError = error.message,
- lastLoadedPage = hydration?.lastLoadedPage ?: 0,
- totalPages = hydration?.totalPages ?: 0,
- isComplete = hydration?.isComplete ?: false,
- pageSize = hydration?.pageSize ?: 0
- )
- )
- }
- }
- }
-
private suspend fun hydrateStalkerMovieCategoryToCount(
providerId: Long,
categoryId: Long,
@@ -1326,8 +1365,12 @@ class MovieRepositoryImpl @Inject constructor(
}
}
- private suspend fun shouldUsePersistedCategoryHydration(provider: ProviderEntity, providerId: Long): Boolean {
- return syncMetadataRepository.getMetadata(providerId)?.movieSyncMode == VodSyncMode.LAZY_BY_CATEGORY
+ private fun com.streamvault.data.local.entity.MovieEntity.hasFreshXtreamDetails(now: Long = System.currentTimeMillis()): Boolean {
+ if (cacheState == CACHE_STATE_SUMMARY_ONLY) return false
+ if (detailHydratedAt <= 0L) return false
+ if (remoteStaleAt > 0L) return false
+ if (ContentCachePolicy.shouldRefresh(detailHydratedAt, DETAIL_REFRESH_TTL_MILLIS, now)) return false
+ return true
}
private fun MovieCategoryHydrationEntity.isFresh(now: Long = System.currentTimeMillis()): Boolean {
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 5f81a2a7..c4cd2367 100644
--- a/data/src/main/java/com/streamvault/data/repository/ProviderRepositoryImpl.kt
+++ b/data/src/main/java/com/streamvault/data/repository/ProviderRepositoryImpl.kt
@@ -174,7 +174,7 @@ class ProviderRepositoryImpl @Inject constructor(
username = normalizedUsername,
password = effectivePassword,
epgSyncMode = epgSyncMode,
- xtreamFastSyncEnabled = xtreamFastSyncEnabled,
+ xtreamFastSyncEnabled = false,
isActive = true,
lastSyncedAt = 0,
createdAt = existingProvider.createdAt
@@ -185,7 +185,7 @@ class ProviderRepositoryImpl @Inject constructor(
val newData = authResult.data.copy(
name = normalizedName.ifBlank { authResult.data.name },
epgSyncMode = epgSyncMode,
- xtreamFastSyncEnabled = xtreamFastSyncEnabled
+ xtreamFastSyncEnabled = false
)
val newId = providerDao.insert(newData.toSecureEntity())
newData.copy(id = newId).copy(password = "")
diff --git a/data/src/main/java/com/streamvault/data/repository/SearchRepositoryImpl.kt b/data/src/main/java/com/streamvault/data/repository/SearchRepositoryImpl.kt
new file mode 100644
index 00000000..5ef70e4d
--- /dev/null
+++ b/data/src/main/java/com/streamvault/data/repository/SearchRepositoryImpl.kt
@@ -0,0 +1,320 @@
+package com.streamvault.data.repository
+
+import android.database.sqlite.SQLiteException
+import android.util.Log
+import com.streamvault.data.local.dao.SearchDao
+import com.streamvault.data.local.dao.SearchHitEntity
+import com.streamvault.data.util.toFtsPrefixQuery
+import com.streamvault.domain.model.Channel
+import com.streamvault.domain.model.Movie
+import com.streamvault.domain.model.Series
+import com.streamvault.domain.repository.ChannelRepository
+import com.streamvault.domain.repository.MovieRepository
+import com.streamvault.domain.repository.SearchRepository
+import com.streamvault.domain.repository.SearchRepositoryResult
+import com.streamvault.domain.repository.SeriesRepository
+import javax.inject.Inject
+import javax.inject.Singleton
+import kotlinx.coroutines.ExperimentalCoroutinesApi
+import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.catch
+import kotlinx.coroutines.flow.combine
+import kotlinx.coroutines.flow.flatMapLatest
+import kotlinx.coroutines.flow.flowOf
+import kotlinx.coroutines.flow.map
+import kotlinx.coroutines.flow.onEach
+
+@Singleton
+@OptIn(ExperimentalCoroutinesApi::class)
+class SearchRepositoryImpl @Inject constructor(
+ private val searchDao: SearchDao,
+ private val channelRepository: ChannelRepository,
+ private val movieRepository: MovieRepository,
+ private val seriesRepository: SeriesRepository
+) : SearchRepository {
+ override fun searchContent(
+ providerId: Long,
+ query: String,
+ includeLive: Boolean,
+ includeMovies: Boolean,
+ includeSeries: Boolean,
+ maxResultsPerSection: Int
+ ): Flow<SearchRepositoryResult> {
+ val normalizedQuery = query.trim()
+ val ftsQuery = normalizedQuery.toFtsPrefixQuery()
+ val startedAtNanos = System.nanoTime()
+ val scopeLabel = searchScopeLabel(includeLive, includeMovies, includeSeries)
+ if (ftsQuery.isNullOrBlank() || maxResultsPerSection <= 0) {
+ return flowOf(SearchRepositoryResult())
+ }
+
+ return searchHits(
+ providerId = providerId,
+ ftsQuery = ftsQuery,
+ rawQuery = normalizedQuery,
+ prefixLike = normalizedQuery.toSqlPrefixLikePattern(),
+ includeLive = includeLive,
+ includeMovies = includeMovies,
+ includeSeries = includeSeries,
+ maxResultsPerSection = maxResultsPerSection
+ )
+ .map { hits: List<SearchHitEntity> ->
+ logFtsLookup(
+ providerId = providerId,
+ queryLength = normalizedQuery.length,
+ scopeLabel = scopeLabel,
+ startedAtNanos = startedAtNanos,
+ hits = hits
+ )
+ SearchLookupState.FtsResult(hits) as SearchLookupState
+ }
+ .catch { error ->
+ if (error is SQLiteException) {
+ Log.w(
+ TAG,
+ "Unified FTS search failed; using section search. " +
+ "provider=$providerId scope=$scopeLabel queryLength=${normalizedQuery.length}",
+ error
+ )
+ logFallback(
+ providerId = providerId,
+ queryLength = normalizedQuery.length,
+ scopeLabel = scopeLabel,
+ startedAtNanos = startedAtNanos
+ )
+ emit(SearchLookupState.FtsUnavailable)
+ } else {
+ throw error
+ }
+ }
+ .flatMapLatest { lookupState ->
+ when (lookupState) {
+ SearchLookupState.FtsUnavailable -> legacySearchContent(
+ providerId = providerId,
+ query = normalizedQuery,
+ includeLive = includeLive,
+ includeMovies = includeMovies,
+ includeSeries = includeSeries,
+ maxResultsPerSection = maxResultsPerSection
+ ).onEach { result ->
+ logSearchResult(
+ source = "legacy-fallback",
+ providerId = providerId,
+ queryLength = normalizedQuery.length,
+ scopeLabel = scopeLabel,
+ startedAtNanos = startedAtNanos,
+ result = result
+ )
+ }
+ is SearchLookupState.FtsResult -> {
+ val hits = lookupState.hits
+ if (hits.isEmpty()) {
+ logSearchResult(
+ source = "unified-fts-empty",
+ providerId = providerId,
+ queryLength = normalizedQuery.length,
+ scopeLabel = scopeLabel,
+ startedAtNanos = startedAtNanos,
+ result = SearchRepositoryResult()
+ )
+ flowOf(SearchRepositoryResult())
+ } else {
+ hydrateHits(hits, includeLive, includeMovies, includeSeries)
+ .onEach { result ->
+ logSearchResult(
+ source = "unified-fts",
+ providerId = providerId,
+ queryLength = normalizedQuery.length,
+ scopeLabel = scopeLabel,
+ startedAtNanos = startedAtNanos,
+ result = result
+ )
+ }
+ }
+ }
+ }
+ }
+ }
+
+ override fun searchChannels(providerId: Long, query: String): Flow<List<Channel>> =
+ channelRepository.searchChannels(providerId, query)
+
+ override fun searchMovies(providerId: Long, query: String): Flow<List<Movie>> =
+ movieRepository.searchMovies(providerId, query)
+
+ override fun searchSeries(providerId: Long, query: String): Flow<List<Series>> =
+ seriesRepository.searchSeries(providerId, query)
+
+ private fun searchHits(
+ providerId: Long,
+ ftsQuery: String,
+ rawQuery: String,
+ prefixLike: String,
+ includeLive: Boolean,
+ includeMovies: Boolean,
+ includeSeries: Boolean,
+ maxResultsPerSection: Int
+ ): Flow<List<SearchHitEntity>> =
+ when {
+ includeLive && includeMovies && includeSeries ->
+ searchDao.searchAll(providerId, ftsQuery, rawQuery, prefixLike, maxResultsPerSection)
+ includeLive && !includeMovies && !includeSeries ->
+ searchDao.searchLive(providerId, ftsQuery, rawQuery, prefixLike, maxResultsPerSection)
+ !includeLive && includeMovies && !includeSeries ->
+ searchDao.searchMovies(providerId, ftsQuery, rawQuery, prefixLike, maxResultsPerSection)
+ !includeLive && !includeMovies && includeSeries ->
+ searchDao.searchSeries(providerId, ftsQuery, rawQuery, prefixLike, maxResultsPerSection)
+ includeLive || includeMovies || includeSeries ->
+ searchDao.searchAll(providerId, ftsQuery, rawQuery, prefixLike, maxResultsPerSection)
+ .map { hits ->
+ hits.filter { hit ->
+ (includeLive && hit.contentType == LIVE_TYPE) ||
+ (includeMovies && hit.contentType == MOVIE_TYPE) ||
+ (includeSeries && hit.contentType == SERIES_TYPE)
+ }
+ }
+ else -> flowOf(emptyList())
+ }
+
+ private fun hydrateHits(
+ hits: List<SearchHitEntity>,
+ includeLive: Boolean,
+ includeMovies: Boolean,
+ includeSeries: Boolean
+ ): Flow<SearchRepositoryResult> {
+ val channelIds = hits.orderedIds(LIVE_TYPE).takeIf { includeLive } ?: emptyList()
+ val movieIds = hits.orderedIds(MOVIE_TYPE).takeIf { includeMovies } ?: emptyList()
+ val seriesIds = hits.orderedIds(SERIES_TYPE).takeIf { includeSeries } ?: emptyList()
+
+ return combine(
+ if (channelIds.isEmpty()) flowOf(emptyList()) else channelRepository.getChannelsByIds(channelIds),
+ if (movieIds.isEmpty()) flowOf(emptyList()) else movieRepository.getMoviesByIds(movieIds),
+ if (seriesIds.isEmpty()) flowOf(emptyList()) else seriesRepository.getSeriesByIds(seriesIds)
+ ) { channels, movies, series ->
+ SearchRepositoryResult(
+ channels = channels.reorderByIds(channelIds) { it.id },
+ movies = movies.reorderByIds(movieIds) { it.id },
+ series = series.reorderByIds(seriesIds) { it.id }
+ )
+ }
+ }
+
+ private fun legacySearchContent(
+ providerId: Long,
+ query: String,
+ includeLive: Boolean,
+ includeMovies: Boolean,
+ includeSeries: Boolean,
+ maxResultsPerSection: Int
+ ): Flow<SearchRepositoryResult> =
+ combine(
+ if (includeLive) searchChannels(providerId, query) else flowOf(emptyList()),
+ if (includeMovies) searchMovies(providerId, query) else flowOf(emptyList()),
+ if (includeSeries) searchSeries(providerId, query) else flowOf(emptyList())
+ ) { channels, movies, series ->
+ SearchRepositoryResult(
+ channels = channels.take(maxResultsPerSection),
+ movies = movies.take(maxResultsPerSection),
+ series = series.take(maxResultsPerSection)
+ )
+ }
+
+ private fun List<SearchHitEntity>.orderedIds(contentType: String): List<Long> =
+ filter { it.contentType == contentType }
+ .sortedWith(compareBy<SearchHitEntity> { it.matchRank }.thenBy { it.title })
+ .map { it.contentId }
+ .distinct()
+
+ private fun <T> List<T>.reorderByIds(ids: List<Long>, idSelector: (T) -> Long): List<T> {
+ val byId = associateBy(idSelector)
+ return ids.mapNotNull(byId::get)
+ }
+
+ private fun String.toSqlPrefixLikePattern(): String = buildString {
+ [email protected] { char ->
+ when (char) {
+ '\\', '%', '_' -> append('\\').append(char)
+ else -> append(char)
+ }
+ }
+ append('%')
+ }
+
+ private fun logFtsLookup(
+ providerId: Long,
+ queryLength: Int,
+ scopeLabel: String,
+ startedAtNanos: Long,
+ hits: List<SearchHitEntity>
+ ) {
+ val elapsedMs = elapsedMsSince(startedAtNanos)
+ if (elapsedMs >= SLOW_FTS_LOG_THRESHOLD_MS) {
+ Log.w(
+ TAG,
+ "Slow unified FTS search (${elapsedMs}ms): provider=$providerId " +
+ "scope=$scopeLabel queryLength=$queryLength hits=${hits.size} " +
+ "liveHits=${hits.countType(LIVE_TYPE)} movieHits=${hits.countType(MOVIE_TYPE)} " +
+ "seriesHits=${hits.countType(SERIES_TYPE)}"
+ )
+ }
+ }
+
+ private fun logFallback(
+ providerId: Long,
+ queryLength: Int,
+ scopeLabel: String,
+ startedAtNanos: Long
+ ) {
+ Log.w(
+ TAG,
+ "Search fallback activated after ${elapsedMsSince(startedAtNanos)}ms: " +
+ "provider=$providerId scope=$scopeLabel queryLength=$queryLength"
+ )
+ }
+
+ private fun logSearchResult(
+ source: String,
+ providerId: Long,
+ queryLength: Int,
+ scopeLabel: String,
+ startedAtNanos: Long,
+ result: SearchRepositoryResult
+ ) {
+ val elapsedMs = elapsedMsSince(startedAtNanos)
+ if (elapsedMs >= SLOW_TOTAL_LOG_THRESHOLD_MS || source != "unified-fts") {
+ Log.i(
+ TAG,
+ "Search completed via $source in ${elapsedMs}ms: provider=$providerId " +
+ "scope=$scopeLabel queryLength=$queryLength channels=${result.channels.size} " +
+ "movies=${result.movies.size} series=${result.series.size}"
+ )
+ }
+ }
+
+ private fun elapsedMsSince(startedAtNanos: Long): Long =
+ (System.nanoTime() - startedAtNanos).coerceAtLeast(0L) / 1_000_000L
+
+ private fun List<SearchHitEntity>.countType(contentType: String): Int =
+ count { it.contentType == contentType }
+
+ private fun searchScopeLabel(includeLive: Boolean, includeMovies: Boolean, includeSeries: Boolean): String =
+ buildList {
+ if (includeLive) add(LIVE_TYPE)
+ if (includeMovies) add(MOVIE_TYPE)
+ if (includeSeries) add(SERIES_TYPE)
+ }.joinToString(separator = "+").ifBlank { "NONE" }
+
+ private companion object {
+ const val TAG = "SearchRepository"
+ const val LIVE_TYPE = "LIVE"
+ const val MOVIE_TYPE = "MOVIE"
+ const val SERIES_TYPE = "SERIES"
+ const val SLOW_FTS_LOG_THRESHOLD_MS = 250L
+ const val SLOW_TOTAL_LOG_THRESHOLD_MS = 500L
+ }
+
+ private sealed interface SearchLookupState {
+ data class FtsResult(val hits: List<SearchHitEntity>) : SearchLookupState
+ data object FtsUnavailable : SearchLookupState
+ }
+}
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 e187a460..8a58d024 100644
--- a/data/src/main/java/com/streamvault/data/repository/SeriesRepositoryImpl.kt
+++ b/data/src/main/java/com/streamvault/data/repository/SeriesRepositoryImpl.kt
@@ -12,6 +12,7 @@ import com.streamvault.data.remote.xtream.XtreamProvider
import com.streamvault.data.remote.xtream.XtreamStreamUrlResolver
import com.streamvault.data.security.CredentialCrypto
import com.streamvault.data.sync.ContentCachePolicy
+import com.streamvault.data.sync.SyncManager
import com.streamvault.domain.model.*
import com.streamvault.domain.model.Result.Success
import com.streamvault.domain.repository.PlaybackHistoryRepository
@@ -20,7 +21,6 @@ import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.SupervisorJob
-import kotlinx.coroutines.TimeoutCancellationException
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.channelFlow
import kotlinx.coroutines.flow.combine
@@ -30,13 +30,11 @@ import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOf
+import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.map
-import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.launch
-import kotlinx.coroutines.withTimeout
import com.streamvault.data.util.toFtsPrefixQuery
import com.streamvault.data.util.rankSearchResults
-import java.io.IOException
import java.util.concurrent.ConcurrentHashMap
import javax.inject.Inject
import com.streamvault.data.preferences.PreferencesRepository
@@ -59,6 +57,8 @@ class SeriesRepositoryImpl @Inject constructor(
private val credentialCrypto: CredentialCrypto,
private val preferencesRepository: PreferencesRepository,
private val xtreamStreamUrlResolver: XtreamStreamUrlResolver,
+ private val xtreamContentIndexDao: XtreamContentIndexDao,
+ private val syncManager: SyncManager,
private val seriesCategoryHydrationDao: SeriesCategoryHydrationDao
) : SeriesRepository {
private companion object {
@@ -67,12 +67,14 @@ class SeriesRepositoryImpl @Inject constructor(
const val SEARCH_OVERSAMPLE_LIMIT = 500
const val MIN_SEARCH_QUERY_LENGTH = 2
const val BROWSE_WINDOW_BUFFER = 80
- const val XTREAM_SERIES_CATEGORY_TIMEOUT_MILLIS = 60_000L
const val XTREAM_CATEGORY_HYDRATION_CONCURRENCY = 1
const val XTREAM_EMPTY_CATEGORY_RETRY_COOLDOWN_MILLIS = 30_000L
const val CURSOR_BATCH_SIZE = 40
const val STALKER_PREVIEW_REQUIRED_COUNT_THRESHOLD = 24
const val STALKER_PREVIEW_MAX_REMOTE_PAGES = 2
+ const val DETAIL_REFRESH_TTL_MILLIS = 14L * 24L * 60L * 60L * 1000L
+ const val CACHE_STATE_SUMMARY_ONLY = "SUMMARY_ONLY"
+ const val CACHE_STATE_DETAIL_HYDRATED = "DETAIL_HYDRATED"
}
private data class CachedXtreamProvider(
@@ -277,9 +279,12 @@ class SeriesRepositoryImpl @Inject constructor(
override fun browseSeries(query: LibraryBrowseQuery): Flow<PagedResult<Series>> {
return flow {
- query.categoryId?.let { ensureXtreamCategoryLoaded(query.providerId, it, browseFetchLimit(query)) }
+ val normalizedSearch = query.searchQuery.trim()
+ query.categoryId
+ ?.takeIf { normalizedSearch.length < MIN_SEARCH_QUERY_LENGTH }
+ ?.let { ensureXtreamCategoryLoaded(query.providerId, it, browseFetchLimit(query)) }
emit(fetchSeriesBrowseResult(query))
- }
+ }.flowOn(Dispatchers.IO)
}
override fun searchSeries(providerId: Long, query: String): Flow<List<Series>> =
@@ -288,8 +293,10 @@ class SeriesRepositoryImpl @Inject constructor(
flowOf(emptyList())
} else combine(
safeSeriesSearchFlow(
- source = seriesDao.search(providerId, ftsQuery, SEARCH_OVERSAMPLE_LIMIT),
- fallback = seriesDao.searchFallback(providerId, query.trim().toSqlLikePattern(), SEARCH_OVERSAMPLE_LIMIT),
+ source = seriesDao.search(providerId, ftsQuery, SEARCH_RESULT_LIMIT),
+ fallback = {
+ seriesDao.searchFallback(providerId, query.trim().toSqlLikePattern(), SEARCH_RESULT_LIMIT)
+ },
rawQuery = query.trim()
),
preferencesRepository.parentalControlLevel
@@ -326,6 +333,10 @@ class SeriesRepositoryImpl @Inject constructor(
return Result.success(buildSeriesWithPersistedEpisodes(seriesEntity))
}
+ if (provider.type == ProviderType.XTREAM_CODES && seriesEntity.hasFreshXtreamDetails()) {
+ return Result.success(buildSeriesWithPersistedEpisodes(seriesEntity))
+ }
+
val remoteResult = try {
when (provider.type) {
ProviderType.XTREAM_CODES -> getOrCreateXtreamProvider(providerId, provider).getSeriesInfo(seriesEntity.seriesId)
@@ -335,6 +346,15 @@ class SeriesRepositoryImpl @Inject constructor(
ProviderType.M3U -> return Result.success(buildSeriesWithPersistedEpisodes(seriesEntity))
}
} catch (e: Exception) {
+ if (provider.type == ProviderType.XTREAM_CODES) {
+ xtreamContentIndexDao.markDetailHydrationError(
+ providerId = providerId,
+ contentType = ContentType.SERIES.name,
+ remoteId = seriesEntity.providerSeriesId?.takeIf { it.isNotBlank() } ?: seriesEntity.seriesId.toString(),
+ errorState = "DETAIL_FAILED_RETRYABLE"
+ )
+ return Result.success(buildSeriesWithPersistedEpisodes(seriesEntity))
+ }
return Result.error(e.message ?: "Failed to access provider credentials", e)
}
@@ -358,9 +378,21 @@ class SeriesRepositoryImpl @Inject constructor(
youtubeTrailer = remoteSeries.youtubeTrailer ?: seriesEntity.youtubeTrailer,
episodeRunTime = remoteSeries.episodeRunTime ?: seriesEntity.episodeRunTime,
lastModified = if (remoteSeries.lastModified > 0) remoteSeries.lastModified else seriesEntity.lastModified,
- providerSeriesId = remoteSeries.providerSeriesId?.takeIf { it.isNotBlank() } ?: seriesEntity.providerSeriesId
+ providerSeriesId = remoteSeries.providerSeriesId?.takeIf { it.isNotBlank() } ?: seriesEntity.providerSeriesId,
+ cacheState = CACHE_STATE_DETAIL_HYDRATED,
+ detailHydratedAt = System.currentTimeMillis()
)
seriesDao.update(updatedSeries)
+ if (provider.type == ProviderType.XTREAM_CODES) {
+ xtreamContentIndexDao.markDetailHydrated(
+ providerId = providerId,
+ contentType = ContentType.SERIES.name,
+ remoteId = seriesEntity.providerSeriesId?.takeIf { it.isNotBlank() } ?: seriesEntity.seriesId.toString(),
+ localContentId = seriesEntity.id,
+ imageUrl = updatedSeries.posterUrl,
+ detailHydratedAt = updatedSeries.detailHydratedAt
+ )
+ }
val episodesToPersist = remoteSeries.seasons
.flatMap { season ->
@@ -436,6 +468,14 @@ class SeriesRepositoryImpl @Inject constructor(
)
}
is Result.Error -> {
+ if (provider.type == ProviderType.XTREAM_CODES) {
+ xtreamContentIndexDao.markDetailHydrationError(
+ providerId = providerId,
+ contentType = ContentType.SERIES.name,
+ remoteId = seriesEntity.providerSeriesId?.takeIf { it.isNotBlank() } ?: seriesEntity.seriesId.toString(),
+ errorState = "DETAIL_FAILED_RETRYABLE"
+ )
+ }
val localSeries = buildSeriesWithPersistedEpisodes(seriesEntity)
Result.success(localSeries)
}
@@ -497,12 +537,14 @@ class SeriesRepositoryImpl @Inject constructor(
combine(
safeSeriesSearchFlow(
source = seriesDao.searchByCategory(query.providerId, categoryId, ftsQuery, SEARCH_OVERSAMPLE_LIMIT),
- fallback = seriesDao.searchByCategoryFallback(
- query.providerId,
- categoryId,
- normalizedSearch.toSqlLikePattern(),
- SEARCH_OVERSAMPLE_LIMIT
- ),
+ fallback = {
+ seriesDao.searchByCategoryFallback(
+ query.providerId,
+ categoryId,
+ normalizedSearch.toSqlLikePattern(),
+ SEARCH_OVERSAMPLE_LIMIT
+ )
+ },
rawQuery = normalizedSearch
),
preferencesRepository.parentalControlLevel
@@ -735,6 +777,61 @@ class SeriesRepositoryImpl @Inject constructor(
(query.offset + query.limit + BROWSE_WINDOW_BUFFER).coerceAtMost(SEARCH_RESULT_LIMIT)
private suspend fun fetchSeriesBrowseResult(query: LibraryBrowseQuery): PagedResult<Series> {
+ val normalizedSearch = query.searchQuery.trim()
+ if (normalizedSearch.length >= MIN_SEARCH_QUERY_LENGTH && supportsFastSeriesSearchBrowse(query)) {
+ return fetchFastSeriesSearchBrowseResult(query, normalizedSearch)
+ }
+
+ if (normalizedSearch.length >= MIN_SEARCH_QUERY_LENGTH) {
+ val searchResults = seriesBrowseSource(query).first()
+ val favoriteIds = favoriteDao.getAllByType(query.providerId, ContentType.SERIES.name)
+ .first()
+ .asSequence()
+ .filter { it.groupId == null }
+ .map { it.contentId }
+ .toSet()
+ val history = playbackHistoryDao.getByProvider(query.providerId).first()
+ val inProgressIds = history
+ .asSequence()
+ .filter { it.contentType == ContentType.SERIES || it.contentType == ContentType.SERIES_EPISODE }
+ .filter {
+ it.resumePositionMs > 0L && (
+ it.totalDurationMs <= 0L ||
+ it.resumePositionMs < (it.totalDurationMs * 0.95f).toLong()
+ )
+ }
+ .mapNotNull { it.seriesId ?: it.contentId }
+ .toSet()
+ val completedSeriesIds = history
+ .asSequence()
+ .filter { it.contentType == ContentType.SERIES_EPISODE }
+ .filter { it.totalDurationMs > 0L && it.resumePositionMs >= (it.totalDurationMs * 0.95f).toLong() }
+ .mapNotNull { it.seriesId }
+ .toSet()
+ val watchCounts = history
+ .asSequence()
+ .filter { it.contentType == ContentType.SERIES || it.contentType == ContentType.SERIES_EPISODE }
+ .groupBy { it.seriesId ?: it.contentId }
+ .mapValues { (_, entries) -> entries.maxOf { it.watchCount } }
+ val filteredResults = applySeriesBrowseQuery(
+ series = searchResults,
+ query = query,
+ favoriteIds = favoriteIds,
+ inProgressIds = inProgressIds,
+ completedSeriesIds = completedSeriesIds,
+ watchCounts = watchCounts
+ )
+ val items = filteredResults.drop(query.offset).take(query.limit)
+
+ return PagedResult(
+ items = items,
+ totalCount = filteredResults.size,
+ offset = query.offset,
+ limit = query.limit,
+ hasMoreRemote = false
+ )
+ }
+
val totalCount = seriesBrowseTotalCount(query).first()
val favoriteIds = favoriteDao.getAllByType(query.providerId, ContentType.SERIES.name)
.first()
@@ -799,6 +896,59 @@ class SeriesRepositoryImpl @Inject constructor(
)
}
+ private suspend fun fetchFastSeriesSearchBrowseResult(
+ query: LibraryBrowseQuery,
+ normalizedSearch: String
+ ): PagedResult<Series> {
+ val ftsQuery = normalizedSearch.toFtsPrefixQuery() ?: return PagedResult(
+ items = emptyList(),
+ totalCount = 0,
+ offset = query.offset,
+ limit = query.limit
+ )
+ val includeProtected = if (preferencesRepository.parentalControlLevel.first() >= 3) 0 else 1
+ val pageLimit = query.limit + 1
+ val rows = query.categoryId?.let { categoryId ->
+ seriesDao.searchByCategoryPage(
+ providerId = query.providerId,
+ categoryId = categoryId,
+ query = ftsQuery,
+ rawQuery = normalizedSearch,
+ prefixLike = normalizedSearch.toSqlPrefixLikePattern(),
+ includeProtected = includeProtected,
+ limit = pageLimit,
+ offset = query.offset
+ )
+ } ?: seriesDao.searchPage(
+ providerId = query.providerId,
+ query = ftsQuery,
+ rawQuery = normalizedSearch,
+ prefixLike = normalizedSearch.toSqlPrefixLikePattern(),
+ includeProtected = includeProtected,
+ limit = pageLimit,
+ offset = query.offset
+ )
+ val hasMore = rows.size > query.limit
+ val favoriteIds = favoriteDao.getAllByType(query.providerId, ContentType.SERIES.name)
+ .first()
+ .asSequence()
+ .filter { it.groupId == null }
+ .map { it.contentId }
+ .toSet()
+ val items = rows
+ .take(query.limit)
+ .map { it.toDomain() }
+ .map { series -> if (series.id in favoriteIds) series.copy(isFavorite = true) else series }
+
+ return PagedResult(
+ items = items,
+ totalCount = query.offset + items.size + if (hasMore) 1 else 0,
+ offset = query.offset,
+ limit = query.limit,
+ hasMoreRemote = hasMore
+ )
+ }
+
private suspend fun fetchSeriesCursorWindow(
query: LibraryBrowseQuery,
favoriteIds: Set<Long>
@@ -944,6 +1094,10 @@ class SeriesRepositoryImpl @Inject constructor(
}
}
+ private fun supportsFastSeriesSearchBrowse(query: LibraryBrowseQuery): Boolean =
+ query.filterBy.type == LibraryFilterType.ALL &&
+ query.sortBy in setOf(LibrarySortBy.LIBRARY, LibrarySortBy.TITLE)
+
private fun seriesMatchesFilter(
series: Series,
filterType: LibraryFilterType,
@@ -968,17 +1122,22 @@ class SeriesRepositoryImpl @Inject constructor(
private fun safeSeriesSearchFlow(
source: Flow<List<SeriesBrowseEntity>>,
- fallback: Flow<List<SeriesBrowseEntity>>,
+ fallback: () -> Flow<List<SeriesBrowseEntity>>,
rawQuery: String
- ): Flow<List<SeriesBrowseEntity>> =
- source.catch { error ->
- if (error is SQLiteException) {
- Log.w(TAG, "FTS series search failed for query '$rawQuery'; falling back to LIKE search", error)
- emitAll(fallback)
- } else {
- throw error
+ ): Flow<List<SeriesBrowseEntity>> = flow {
+ try {
+ source.collect { ftsRows ->
+ if (ftsRows.isEmpty()) {
+ emit(emptyList())
+ } else {
+ emit(ftsRows)
+ }
}
+ } catch (error: SQLiteException) {
+ Log.w(TAG, "FTS series search failed for queryLength=${rawQuery.length}; using LIKE-only search", error)
+ emitAll(fallback())
}
+ }
private fun String.toSqlLikePattern(): String {
val escaped = buildString(length) {
@@ -992,6 +1151,18 @@ class SeriesRepositoryImpl @Inject constructor(
return "%$escaped%"
}
+ private fun String.toSqlPrefixLikePattern(): String {
+ val escaped = buildString(length) {
+ [email protected] { char ->
+ when (char) {
+ '%', '_', '\\' -> append('\\')
+ }
+ append(char)
+ }
+ }
+ return "$escaped%"
+ }
+
private suspend fun ensureXtreamCategoryLoaded(
providerId: Long,
categoryId: Long,
@@ -1005,6 +1176,14 @@ class SeriesRepositoryImpl @Inject constructor(
val localCount = seriesDao.getCountByCategory(providerId, categoryId).first()
val hydration = seriesCategoryHydrationDao.get(providerId, categoryId)
+ if (provider.type == ProviderType.XTREAM_CODES) {
+ if (localCount > 0) {
+ loadedXtreamCategories.add(key)
+ } else {
+ syncManager.prioritizeXtreamIndexCategory(providerId, ContentType.SERIES, categoryId)
+ }
+ return
+ }
if (provider.type == ProviderType.STALKER_PORTAL) {
hydrateStalkerSeriesCategoryToCount(
providerId = providerId,
@@ -1017,27 +1196,6 @@ class SeriesRepositoryImpl @Inject constructor(
)
return
}
- val isFresh = hydration?.isFresh() == true && (localCount > 0 || hydration.itemCount == 0)
-
- if (isFresh) {
- loadedXtreamCategories.add(key)
- return
- }
-
- // Stale but has cached data — show immediately, refresh in background
- if (localCount > 0 && refreshStaleInBackground) {
- loadedXtreamCategories.add(key)
- triggerSeriesCategoryHydration(providerId, categoryId, provider, requiredCount)
- return
- }
-
- if (localCount > 0) {
- loadedXtreamCategories.add(key)
- return
- }
-
- // No data — fetch inline so the user sees something right away
- hydrateSeriesCategory(providerId, categoryId, provider)
}
private fun triggerSeriesCategoryHydration(
@@ -1051,6 +1209,9 @@ class SeriesRepositoryImpl @Inject constructor(
if (!backgroundRefreshes.add(key)) return
repositoryScope.launch {
try {
+ if (provider.type == ProviderType.XTREAM_CODES) {
+ return@launch
+ }
val localCount = seriesDao.getCountByCategory(providerId, categoryId).first()
val hydration = seriesCategoryHydrationDao.get(providerId, categoryId)
if (localCount == 0 && hydration?.isEmptyRetryCoolingDown() == true) return@launch
@@ -1064,8 +1225,6 @@ class SeriesRepositoryImpl @Inject constructor(
hydration = hydration,
allowWildcard = allowStalkerWildcard
)
- } else {
- hydrateSeriesCategory(providerId, categoryId, provider)
}
} finally {
backgroundRefreshes.remove(key)
@@ -1073,91 +1232,6 @@ class SeriesRepositoryImpl @Inject constructor(
}
}
- private suspend fun hydrateSeriesCategory(
- providerId: Long,
- categoryId: Long,
- provider: ProviderEntity
- ) {
- val key = "$providerId:$categoryId"
- val lock = xtreamCategoryLoadLocks.getOrPut(key) { Mutex() }
- lock.withLock {
- val localCount = seriesDao.getCountByCategory(providerId, categoryId).first()
- val hydration = seriesCategoryHydrationDao.get(providerId, categoryId)
- if (hydration?.isFresh() == true && (localCount > 0 || hydration.itemCount == 0)) {
- loadedXtreamCategories.add(key)
- return
- }
-
- runCatching {
- val result = withXtreamSeriesCategoryTimeout(categoryId) {
- if (provider.type == ProviderType.XTREAM_CODES) {
- getOrCreateXtreamProvider(providerId, provider).getSeriesList(categoryId)
- } else {
- return@withXtreamSeriesCategoryTimeout Success(emptyList())
- }
- }
- when (result) {
- is Success -> {
- val entities = result.data.map { item -> item.toEntity() }
- val lazyXtreamHydration = shouldUsePersistedCategoryHydration(provider)
- if (lazyXtreamHydration && entities.isEmpty()) {
- seriesCategoryHydrationDao.upsert(
- SeriesCategoryHydrationEntity(
- providerId = providerId,
- categoryId = categoryId,
- lastHydratedAt = System.currentTimeMillis(),
- itemCount = localCount,
- lastStatus = "EMPTY_RETRY",
- lastError = "Xtream category returned an empty result; retry pending.",
- lastLoadedPage = 0,
- totalPages = 0,
- isComplete = false,
- pageSize = 0
- )
- )
- loadedXtreamCategories.remove(key)
- } else {
- seriesDao.replaceCategory(providerId, categoryId, entities)
- episodeDao.deleteOrphans()
- seriesCategoryHydrationDao.upsert(
- SeriesCategoryHydrationEntity(
- providerId = providerId,
- categoryId = categoryId,
- lastHydratedAt = System.currentTimeMillis(),
- itemCount = entities.size,
- lastStatus = "SUCCESS",
- lastError = null,
- lastLoadedPage = 1,
- totalPages = 1,
- isComplete = true,
- pageSize = entities.size
- )
- )
- loadedXtreamCategories.add(key)
- }
- }
- else -> Unit
- }
- }.onFailure { error ->
- val currentCount = seriesDao.getCountByCategory(providerId, categoryId).first()
- seriesCategoryHydrationDao.upsert(
- SeriesCategoryHydrationEntity(
- providerId = providerId,
- categoryId = categoryId,
- lastHydratedAt = hydration?.lastHydratedAt ?: 0L,
- itemCount = currentCount,
- lastStatus = "ERROR",
- lastError = error.message,
- lastLoadedPage = hydration?.lastLoadedPage ?: 0,
- totalPages = hydration?.totalPages ?: 0,
- isComplete = hydration?.isComplete ?: false,
- pageSize = hydration?.pageSize ?: 0
- )
- )
- }
- }
- }
-
private suspend fun hydrateStalkerSeriesCategoryToCount(
providerId: Long,
categoryId: Long,
@@ -1244,21 +1318,12 @@ class SeriesRepositoryImpl @Inject constructor(
return !ContentCachePolicy.shouldRefresh(lastHydratedAt, XTREAM_EMPTY_CATEGORY_RETRY_COOLDOWN_MILLIS, now)
}
- private fun shouldUsePersistedCategoryHydration(provider: ProviderEntity): Boolean {
- return provider.type == ProviderType.XTREAM_CODES && provider.xtreamFastSyncEnabled
- }
-
- private suspend fun <T> withXtreamSeriesCategoryTimeout(
- categoryId: Long,
- block: suspend () -> T
- ): T {
- return try {
- withTimeout(XTREAM_SERIES_CATEGORY_TIMEOUT_MILLIS) {
- block()
- }
- } catch (e: TimeoutCancellationException) {
- throw IOException("Timed out after 60 seconds while loading series category $categoryId", e)
- }
+ private fun SeriesEntity.hasFreshXtreamDetails(now: Long = System.currentTimeMillis()): Boolean {
+ if (cacheState == CACHE_STATE_SUMMARY_ONLY) return false
+ if (detailHydratedAt <= 0L) return false
+ if (remoteStaleAt > 0L) return false
+ if (ContentCachePolicy.shouldRefresh(detailHydratedAt, DETAIL_REFRESH_TTL_MILLIS, now)) return false
+ return true
}
private fun seriesFreshnessScore(series: Series): Long =
diff --git a/data/src/main/java/com/streamvault/data/sync/ProviderSyncStateReaderImpl.kt b/data/src/main/java/com/streamvault/data/sync/ProviderSyncStateReaderImpl.kt
index 5e4cc18a..2b3e4371 100644
--- a/data/src/main/java/com/streamvault/data/sync/ProviderSyncStateReaderImpl.kt
+++ b/data/src/main/java/com/streamvault/data/sync/ProviderSyncStateReaderImpl.kt
@@ -1,13 +1,25 @@
package com.streamvault.data.sync
+import com.streamvault.data.local.dao.XtreamIndexJobDao
import com.streamvault.domain.manager.ProviderSyncStateReader
import com.streamvault.domain.model.SyncState
import javax.inject.Inject
import javax.inject.Singleton
+import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.map
@Singleton
class ProviderSyncStateReaderImpl @Inject constructor(
- private val syncManager: SyncManager
+ private val syncManager: SyncManager,
+ private val xtreamIndexJobDao: XtreamIndexJobDao
) : ProviderSyncStateReader {
override fun currentSyncState(providerId: Long): SyncState = syncManager.currentSyncState(providerId)
-}
\ No newline at end of file
+
+ override fun observeBackgroundIndexingActive(providerId: Long): Flow<Boolean> =
+ xtreamIndexJobDao.observeForProvider(providerId).map { jobs ->
+ jobs.any { job ->
+ job.section in setOf("MOVIE", "SERIES") &&
+ job.state in setOf("QUEUED", "RUNNING", "PARTIAL", "STALE", "FAILED_RETRYABLE")
+ }
+ }
+}
diff --git a/data/src/main/java/com/streamvault/data/sync/ProviderSyncWorker.kt b/data/src/main/java/com/streamvault/data/sync/ProviderSyncWorker.kt
index cf84ec8f..f0cdc102 100644
--- a/data/src/main/java/com/streamvault/data/sync/ProviderSyncWorker.kt
+++ b/data/src/main/java/com/streamvault/data/sync/ProviderSyncWorker.kt
@@ -7,11 +7,19 @@ import androidx.work.BackoffPolicy
import androidx.work.Constraints
import androidx.work.CoroutineWorker
import androidx.work.ExistingPeriodicWorkPolicy
+import androidx.work.ExistingWorkPolicy
import androidx.work.NetworkType
+import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.PeriodicWorkRequestBuilder
import androidx.work.WorkManager
+import androidx.work.WorkRequest
import androidx.work.WorkerParameters
import com.streamvault.data.local.dao.ProviderDao
+import com.streamvault.data.local.dao.XtreamIndexJobDao
+import com.streamvault.domain.model.ContentType
+import com.streamvault.domain.model.ProviderEpgSyncMode
+import com.streamvault.domain.model.ProviderType
+import com.streamvault.domain.repository.SyncMetadataRepository
import dagger.hilt.EntryPoint
import dagger.hilt.InstallIn
import dagger.hilt.android.EntryPointAccessors
@@ -28,6 +36,8 @@ class ProviderSyncWorker(
interface ProviderSyncWorkerEntryPoint {
fun providerDao(): ProviderDao
fun syncManager(): SyncManager
+ fun syncMetadataRepository(): SyncMetadataRepository
+ fun xtreamIndexJobDao(): XtreamIndexJobDao
}
override suspend fun doWork(): Result {
@@ -43,7 +53,12 @@ class ProviderSyncWorker(
var sawRetryableFailure = false
providers.forEach { provider ->
- when (val result = entryPoint.syncManager().sync(provider.id, force = false)) {
+ val result = if (provider.type == ProviderType.XTREAM_CODES) {
+ syncXtreamProviderIfStale(entryPoint, provider)
+ } else {
+ entryPoint.syncManager().sync(provider.id, force = false)
+ }
+ when (result) {
is com.streamvault.domain.model.Result.Error -> {
Log.w(TAG, "Provider sync worker failed for provider ${provider.id}: ${result.message}")
if (shouldRetry(result.exception)) {
@@ -73,6 +88,7 @@ class ProviderSyncWorker(
companion object {
private const val TAG = "ProviderSyncWorker"
private const val UNIQUE_WORK_NAME = "provider-sync-worker"
+ private const val UNIQUE_LAUNCH_STALE_WORK_NAME = "provider-sync-launch-stale-check"
fun enqueuePeriodic(context: Context) {
val request = PeriodicWorkRequestBuilder<ProviderSyncWorker>(6, TimeUnit.HOURS)
@@ -95,5 +111,84 @@ class ProviderSyncWorker(
request
)
}
+
+ fun enqueueLaunchStaleCheck(context: Context) {
+ val request = OneTimeWorkRequestBuilder<ProviderSyncWorker>()
+ .setConstraints(
+ Constraints.Builder()
+ .setRequiredNetworkType(NetworkType.CONNECTED)
+ .setRequiresBatteryNotLow(true)
+ .build()
+ )
+ .setInitialDelay(10, TimeUnit.SECONDS)
+ .setBackoffCriteria(
+ BackoffPolicy.EXPONENTIAL,
+ WorkRequest.MIN_BACKOFF_MILLIS,
+ TimeUnit.MILLISECONDS
+ )
+ .build()
+
+ WorkManager.getInstance(context).enqueueUniqueWork(
+ UNIQUE_LAUNCH_STALE_WORK_NAME,
+ ExistingWorkPolicy.KEEP,
+ request
+ )
+ }
+ }
+
+ private suspend fun syncXtreamProviderIfStale(
+ entryPoint: ProviderSyncWorkerEntryPoint,
+ provider: com.streamvault.data.local.entity.ProviderEntity
+ ): com.streamvault.domain.model.Result<Unit> {
+ val now = System.currentTimeMillis()
+ val metadata = entryPoint.syncMetadataRepository().getMetadata(provider.id)
+ val liveStale = ContentCachePolicy.shouldRefresh(
+ metadata?.lastLiveSuccess ?: 0L,
+ ContentCachePolicy.CATALOG_TTL_MILLIS,
+ now
+ )
+ val epgStale = provider.epgSyncMode != ProviderEpgSyncMode.SKIP &&
+ ContentCachePolicy.shouldRefresh(
+ metadata?.lastEpgSuccess ?: 0L,
+ ContentCachePolicy.EPG_TTL_MILLIS,
+ now
+ )
+ val movieIndexDue = shouldRunIndexJob(entryPoint, provider.id, ContentType.MOVIE, now)
+ val seriesIndexDue = shouldRunIndexJob(entryPoint, provider.id, ContentType.SERIES, now)
+
+ if (!provider.isActive) {
+ return com.streamvault.domain.model.Result.success(Unit)
+ }
+
+ if (liveStale) {
+ when (val liveResult = entryPoint.syncManager().retrySection(provider.id, SyncRepairSection.LIVE)) {
+ is com.streamvault.domain.model.Result.Error -> return liveResult
+ else -> Unit
+ }
+ }
+ if (epgStale) {
+ when (val epgResult = entryPoint.syncManager().syncEpg(provider.id, force = false)) {
+ is com.streamvault.domain.model.Result.Error -> return epgResult
+ else -> Unit
+ }
+ }
+ if (movieIndexDue) {
+ entryPoint.syncManager().scheduleXtreamIndexSync(provider.id, ContentType.MOVIE)
+ }
+ if (seriesIndexDue) {
+ entryPoint.syncManager().scheduleXtreamIndexSync(provider.id, ContentType.SERIES)
+ }
+ return com.streamvault.domain.model.Result.success(Unit)
+ }
+
+ private suspend fun shouldRunIndexJob(
+ entryPoint: ProviderSyncWorkerEntryPoint,
+ providerId: Long,
+ section: ContentType,
+ now: Long
+ ): Boolean {
+ val job = entryPoint.xtreamIndexJobDao().get(providerId, section.name) ?: return true
+ if (job.state in setOf("QUEUED", "PARTIAL", "STALE", "FAILED_RETRYABLE")) return true
+ return ContentCachePolicy.shouldRefresh(job.lastSuccessAt, ContentCachePolicy.CATALOG_TTL_MILLIS, now)
}
}
diff --git a/data/src/main/java/com/streamvault/data/sync/SyncCatalogStore.kt b/data/src/main/java/com/streamvault/data/sync/SyncCatalogStore.kt
index 30b7deba..17e07881 100644
--- a/data/src/main/java/com/streamvault/data/sync/SyncCatalogStore.kt
+++ b/data/src/main/java/com/streamvault/data/sync/SyncCatalogStore.kt
@@ -75,7 +75,7 @@ internal class SyncCatalogStore(
categories?.let { stageCategories(providerId, sessionId, it) }
insertStageRows(limitedChannels, catalogSyncDao::insertChannelStages)
transactionRunner.inTransaction {
- categories?.let { applyCategories(providerId, sessionId, "LIVE") }
+ categories?.let { applyCategories(providerId, sessionId, "LIVE", pruneStale = !overflowed) }
if (overflowed) {
upsertChannels(providerId, sessionId)
} else {
@@ -96,7 +96,7 @@ internal class SyncCatalogStore(
categories?.let { stageCategories(providerId, sessionId, it) }
val stagingResult = stageMovieSequence(providerId, sessionId, movies)
transactionRunner.inTransaction {
- categories?.let { applyCategories(providerId, sessionId, "MOVIE") }
+ categories?.let { applyCategories(providerId, sessionId, "MOVIE", pruneStale = !stagingResult.overflowed) }
if (stagingResult.overflowed) {
upsertMovies(providerId, sessionId)
} else {
@@ -118,7 +118,7 @@ internal class SyncCatalogStore(
categories?.let { stageCategories(providerId, sessionId, it) }
val stagingResult = stageSeriesSequence(providerId, sessionId, series)
transactionRunner.inTransaction {
- categories?.let { applyCategories(providerId, sessionId, "SERIES") }
+ categories?.let { applyCategories(providerId, sessionId, "SERIES", pruneStale = !stagingResult.overflowed) }
if (stagingResult.overflowed) {
upsertSeries(providerId, sessionId)
} else {
@@ -183,7 +183,7 @@ internal class SyncCatalogStore(
try {
transactionRunner.inTransaction {
categories?.let { stageCategories(providerId, sessionId, it) }
- categories?.let { applyCategories(providerId, sessionId, "LIVE") }
+ categories?.let { applyCategories(providerId, sessionId, "LIVE", pruneStale = false) }
upsertChannels(providerId, sessionId)
catalogSyncDao.rebuildChannelFts()
}
@@ -200,7 +200,7 @@ internal class SyncCatalogStore(
try {
transactionRunner.inTransaction {
categories?.let { stageCategories(providerId, sessionId, it) }
- categories?.let { applyCategories(providerId, sessionId, "MOVIE") }
+ categories?.let { applyCategories(providerId, sessionId, "MOVIE", pruneStale = false) }
upsertMovies(providerId, sessionId)
catalogSyncDao.rebuildMovieFts()
}
@@ -218,7 +218,7 @@ internal class SyncCatalogStore(
try {
transactionRunner.inTransaction {
categories?.let { stageCategories(providerId, sessionId, it) }
- categories?.let { applyCategories(providerId, sessionId, "SERIES") }
+ categories?.let { applyCategories(providerId, sessionId, "SERIES", pruneStale = false) }
upsertSeries(providerId, sessionId)
catalogSyncDao.rebuildSeriesFts()
}
@@ -239,7 +239,7 @@ internal class SyncCatalogStore(
categories?.let { stageCategories(providerId, sessionId, it) }
insertStageRows(stagedChannels, catalogSyncDao::insertChannelStages)
transactionRunner.inTransaction {
- categories?.let { applyCategories(providerId, sessionId, "LIVE") }
+ categories?.let { applyCategories(providerId, sessionId, "LIVE", pruneStale = false) }
upsertChannels(providerId, sessionId)
catalogSyncDao.rebuildChannelFts()
}
@@ -260,7 +260,7 @@ internal class SyncCatalogStore(
categories?.let { stageCategories(providerId, sessionId, it) }
val stagingResult = stageMovieSequence(providerId, sessionId, movies)
transactionRunner.inTransaction {
- categories?.let { applyCategories(providerId, sessionId, "MOVIE") }
+ categories?.let { applyCategories(providerId, sessionId, "MOVIE", pruneStale = false) }
upsertMovies(providerId, sessionId)
catalogSyncDao.rebuildMovieFts()
}
@@ -282,7 +282,7 @@ internal class SyncCatalogStore(
categories?.let { stageCategories(providerId, sessionId, it) }
val stagingResult = stageSeriesSequence(providerId, sessionId, series)
transactionRunner.inTransaction {
- categories?.let { applyCategories(providerId, sessionId, "SERIES") }
+ categories?.let { applyCategories(providerId, sessionId, "SERIES", pruneStale = false) }
upsertSeries(providerId, sessionId)
catalogSyncDao.rebuildSeriesFts()
}
@@ -292,6 +292,19 @@ internal class SyncCatalogStore(
}
}
+ suspend fun upsertCategories(providerId: Long, type: String, categories: List<CategoryEntity>) {
+ val sessionId = newSessionId()
+ try {
+ clearProviderStaging(providerId)
+ stageCategories(providerId, sessionId, categories)
+ transactionRunner.inTransaction {
+ applyCategories(providerId, sessionId, type, pruneStale = false)
+ }
+ } finally {
+ clearSession(providerId, sessionId)
+ }
+ }
+
suspend fun replaceCategories(providerId: Long, type: String, categories: List<CategoryEntity>) {
val sessionId = newSessionId()
try {
@@ -373,7 +386,12 @@ internal class SyncCatalogStore(
catalogSyncDao.clearProviderCategoryStages(providerId)
}
- private suspend fun applyCategories(providerId: Long, sessionId: Long, type: String) {
+ private suspend fun applyCategories(
+ providerId: Long,
+ sessionId: Long,
+ type: String,
+ pruneStale: Boolean = true
+ ) {
val stagedByCategoryId = catalogSyncDao.getCategoryStages(providerId, sessionId, type)
.associateBy { it.categoryId }
val changed = categoryDao.getByProviderAndTypeSync(providerId, type)
@@ -396,7 +414,9 @@ internal class SyncCatalogStore(
categoryDao.updateAll(changed)
}
catalogSyncDao.insertMissingCategoriesFromStage(providerId, sessionId, type)
- catalogSyncDao.deleteStaleCategoriesForStage(providerId, sessionId, type)
+ if (pruneStale) {
+ catalogSyncDao.deleteStaleCategoriesForStage(providerId, sessionId, type)
+ }
}
private suspend fun applyChannels(providerId: Long, sessionId: Long) {
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 160551e3..3200d6c0 100644
--- a/data/src/main/java/com/streamvault/data/sync/SyncManager.kt
+++ b/data/src/main/java/com/streamvault/data/sync/SyncManager.kt
@@ -11,14 +11,19 @@ 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.dao.TmdbIdentityDao
+import com.streamvault.data.local.dao.XtreamContentIndexDao
+import com.streamvault.data.local.dao.XtreamIndexJobDao
import com.streamvault.data.local.entity.CategoryEntity
import com.streamvault.data.local.entity.ChannelEntity
import com.streamvault.data.local.entity.ChannelGuideSyncEntity
import com.streamvault.data.local.entity.MovieEntity
import com.streamvault.data.local.entity.SeriesEntity
+import com.streamvault.data.local.entity.XtreamContentIndexEntity
+import com.streamvault.data.local.entity.XtreamIndexJobEntity
import com.streamvault.data.mapper.toDomain
import com.streamvault.data.mapper.toEntity
import com.streamvault.data.parser.M3uParser
+import com.streamvault.data.remote.http.buildAppRequestProfile
import com.streamvault.data.remote.stalker.StalkerApiService
import com.streamvault.data.remote.stalker.StalkerProvider
import com.streamvault.data.remote.stalker.StalkerProviderProfile
@@ -43,6 +48,7 @@ import com.streamvault.domain.model.Movie
import com.streamvault.domain.model.ProviderEpgSyncMode
import com.streamvault.domain.model.Provider
import com.streamvault.domain.model.ProviderType
+import com.streamvault.domain.model.Result
import com.streamvault.domain.model.Series
import com.streamvault.domain.model.SyncMetadata
import com.streamvault.domain.model.SyncState
@@ -53,9 +59,6 @@ import com.streamvault.domain.repository.SyncMetadataRepository
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.CancellationException
-import kotlinx.coroutines.async
-import kotlinx.coroutines.awaitAll
-import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.first
@@ -76,22 +79,11 @@ import java.util.concurrent.ConcurrentHashMap
import java.util.zip.GZIPInputStream
import javax.inject.Inject
import javax.inject.Singleton
-import kotlin.system.measureTimeMillis
private const val TAG = "SyncManager"
-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
@@ -132,6 +124,8 @@ class SyncManager @Inject constructor(
private val categoryDao: CategoryDao,
private val catalogSyncDao: CatalogSyncDao,
private val tmdbIdentityDao: TmdbIdentityDao,
+ private val xtreamContentIndexDao: XtreamContentIndexDao,
+ private val xtreamIndexJobDao: XtreamIndexJobDao,
private val stalkerApiService: StalkerApiService,
private val xtreamJson: Json,
private val m3uParser: M3uParser,
@@ -178,7 +172,11 @@ class SyncManager @Inject constructor(
private val xtreamCatalogHttpService: OkHttpXtreamApiService by lazy {
OkHttpXtreamApiService(
client = okHttpClient,
- json = xtreamJson
+ json = xtreamJson,
+ defaultRequestProfile = buildAppRequestProfile(
+ versionName = null,
+ ownerTag = "sync/xtream"
+ )
)
}
private val xtreamCatalogApiService: XtreamApiService by lazy { xtreamCatalogHttpService }
@@ -186,8 +184,7 @@ class SyncManager @Inject constructor(
SyncManagerXtreamFetcher(
xtreamCatalogApiService = xtreamCatalogApiService,
xtreamSupport = xtreamSupport,
- sanitizeThrowableMessage = ::sanitizeThrowableMessage,
- pageSize = XTREAM_CATALOG_PAGE_SIZE
+ sanitizeThrowableMessage = ::sanitizeThrowableMessage
)
}
private val catalogStrategySupport = SyncManagerCatalogStrategySupport(
@@ -216,52 +213,6 @@ class SyncManager @Inject constructor(
fallbackStageBatchSize = XTREAM_FALLBACK_STAGE_BATCH_SIZE
)
}
- private val xtreamMovieStrategy: SyncManagerXtreamMovieStrategy by lazy {
- SyncManagerXtreamMovieStrategy(
- xtreamCatalogApiService = xtreamCatalogApiService,
- xtreamCatalogHttpService = xtreamCatalogHttpService,
- xtreamAdaptiveSyncPolicy = xtreamAdaptiveSyncPolicy,
- xtreamSupport = xtreamSupport,
- xtreamFetcher = xtreamFetcher,
- catalogStrategySupport = catalogStrategySupport,
- syncCatalogStore = syncCatalogStore,
- progress = ::progress,
- sanitizeThrowableMessage = ::sanitizeThrowableMessage,
- fullCatalogFallbackWarning = ::fullCatalogFallbackWarning,
- categoryFailureWarning = ::categoryFailureWarning,
- pagingFailureWarning = ::pagingFailureWarning,
- stageMovieItems = catalogStager::stageMovieItems,
- stageMovieSequence = catalogStager::stageMovieSequence,
- movieCategorySequentialModeWarning = MOVIE_CATEGORY_SEQUENTIAL_MODE_WARNING,
- moviePagedSequentialModeWarning = MOVIE_PAGED_SEQUENTIAL_MODE_WARNING,
- fallbackStageBatchSize = XTREAM_FALLBACK_STAGE_BATCH_SIZE,
- maxCatalogPages = XTREAM_CATALOG_MAX_PAGES,
- pageSize = XTREAM_CATALOG_PAGE_SIZE
- )
- }
- private val xtreamSeriesStrategy: SyncManagerXtreamSeriesStrategy by lazy {
- SyncManagerXtreamSeriesStrategy(
- xtreamCatalogApiService = xtreamCatalogApiService,
- xtreamCatalogHttpService = xtreamCatalogHttpService,
- xtreamAdaptiveSyncPolicy = xtreamAdaptiveSyncPolicy,
- xtreamSupport = xtreamSupport,
- xtreamFetcher = xtreamFetcher,
- catalogStrategySupport = catalogStrategySupport,
- syncCatalogStore = syncCatalogStore,
- progress = ::progress,
- sanitizeThrowableMessage = ::sanitizeThrowableMessage,
- fullCatalogFallbackWarning = ::fullCatalogFallbackWarning,
- categoryFailureWarning = ::categoryFailureWarning,
- pagingFailureWarning = ::pagingFailureWarning,
- stageSeriesItems = catalogStager::stageSeriesItems,
- stageSeriesSequence = catalogStager::stageSeriesSequence,
- categorySequentialModeWarning = SERIES_CATEGORY_SEQUENTIAL_MODE_WARNING,
- pagedSequentialModeWarning = SERIES_PAGED_SEQUENTIAL_MODE_WARNING,
- fallbackStageBatchSize = XTREAM_FALLBACK_STAGE_BATCH_SIZE,
- maxCatalogPages = XTREAM_CATALOG_MAX_PAGES,
- pageSize = XTREAM_CATALOG_PAGE_SIZE
- )
- }
fun syncStateForProvider(providerId: Long): Flow<SyncState> =
syncStatesByProvider.map { states -> states[providerId] ?: SyncState.Idle }
@@ -308,6 +259,45 @@ class SyncManager @Inject constructor(
BackgroundEpgSyncWorker.enqueue(applicationContext, providerId)
}
+ fun scheduleXtreamIndexSync(providerId: Long, section: ContentType? = null, force: Boolean = false) {
+ runCatching {
+ XtreamIndexWorker.enqueue(
+ context = applicationContext,
+ providerId = providerId,
+ section = section?.name,
+ force = force
+ )
+ }.onFailure { error ->
+ Log.w(TAG, "Failed to schedule Xtream index work for provider $providerId (${section?.name ?: "all"}): ${sanitizeThrowableMessage(error)}")
+ }
+ }
+
+ suspend fun prioritizeXtreamIndexCategory(
+ providerId: Long,
+ section: ContentType,
+ categoryId: Long
+ ) {
+ if (section != ContentType.MOVIE && section != ContentType.SERIES) return
+ val now = System.currentTimeMillis()
+ val updated = xtreamIndexJobDao.requestCategoryPriority(
+ providerId = providerId,
+ section = section.name,
+ categoryId = categoryId,
+ requestedAt = now
+ )
+ if (updated == 0) {
+ upsertXtreamIndexJob(
+ providerId = providerId,
+ section = section.name,
+ state = "QUEUED",
+ now = now,
+ priorityCategoryId = categoryId,
+ priorityRequestedAt = now
+ )
+ }
+ scheduleXtreamIndexSync(providerId, section, force = false)
+ }
+
suspend fun syncEpg(
providerId: Long,
force: Boolean = true,
@@ -320,16 +310,38 @@ class SyncManager @Inject constructor(
.copy(password = credentialCrypto.decryptIfNeeded(providerEntity.password))
.toDomain()
+ val startedAt = System.currentTimeMillis()
+ updateXtreamEpgJobState(
+ provider = provider,
+ state = "RUNNING",
+ now = startedAt,
+ lastAttemptAt = startedAt,
+ lastError = null
+ )
publishSyncState(providerId, SyncState.Syncing("Downloading EPG..."))
try {
val epgResult = syncProviderEpg(
provider = provider,
metadata = syncMetadataRepository.getMetadata(provider.id) ?: SyncMetadata(provider.id),
- now = System.currentTimeMillis(),
+ now = startedAt,
force = force,
onProgress = onProgress
)
+ val finishedAt = System.currentTimeMillis()
+ val epgCount = programDao.countByProvider(providerId)
+ updateXtreamEpgJobState(
+ provider = provider,
+ state = when {
+ epgResult.warnings.isEmpty() -> "SUCCESS"
+ epgResult.hasRetryableFailure -> "FAILED_RETRYABLE"
+ else -> "PARTIAL"
+ },
+ now = finishedAt,
+ indexedRows = epgCount,
+ lastSuccessAt = finishedAt.takeIf { epgResult.warnings.isEmpty() },
+ lastError = epgResult.warnings.takeIf { it.isNotEmpty() }?.joinToString("; ")
+ )
updateSyncStatusMetadata(
providerId = providerId,
status = if (epgResult.warnings.isEmpty()) "SUCCESS" else "PARTIAL"
@@ -353,6 +365,14 @@ class SyncManager @Inject constructor(
} catch (e: Exception) {
val safeMessage = syncErrorSanitizer.userMessage(e, "EPG sync failed")
Log.e(TAG, "EPG sync failed for provider $providerId: ${syncErrorSanitizer.throwableMessage(e)}")
+ val failedAt = System.currentTimeMillis()
+ updateXtreamEpgJobState(
+ provider = provider,
+ state = if (isRetryableEpgException(e)) "FAILED_RETRYABLE" else "FAILED_PERMANENT",
+ now = failedAt,
+ indexedRows = programDao.countByProvider(providerId),
+ lastError = safeMessage
+ )
updateSyncStatusMetadata(providerId = providerId, status = "ERROR")
publishSyncState(providerId, SyncState.Error(safeMessage, e))
com.streamvault.domain.model.Result.error(safeMessage, e)
@@ -362,6 +382,32 @@ class SyncManager @Inject constructor(
private fun shouldSyncEpgUpfront(provider: Provider): Boolean =
provider.epgSyncMode == ProviderEpgSyncMode.UPFRONT
+ private suspend fun updateXtreamEpgJobState(
+ provider: Provider,
+ state: String,
+ now: Long,
+ indexedRows: Int? = null,
+ lastAttemptAt: Long? = null,
+ lastSuccessAt: Long? = null,
+ lastError: String? = null
+ ) {
+ if (provider.type != ProviderType.XTREAM_CODES || provider.epgSyncMode == ProviderEpgSyncMode.SKIP) return
+ upsertXtreamIndexJob(
+ providerId = provider.id,
+ section = "EPG",
+ state = state,
+ now = now,
+ totalCategories = 1,
+ completedCategories = if (state == "SUCCESS") 1 else 0,
+ nextCategoryIndex = if (state == "SUCCESS") 1 else 0,
+ failedCategories = if (state == "FAILED_RETRYABLE" || state == "FAILED_PERMANENT") 1 else 0,
+ indexedRows = indexedRows,
+ lastAttemptAt = lastAttemptAt,
+ lastSuccessAt = lastSuccessAt,
+ lastError = lastError
+ )
+ }
+
suspend fun sync(
providerId: Long,
force: Boolean = false,
@@ -386,7 +432,7 @@ class SyncManager @Inject constructor(
try {
val outcome = withContext(Dispatchers.IO) {
when (provider.type) {
- ProviderType.XTREAM_CODES -> syncXtream(provider, force, onProgress)
+ ProviderType.XTREAM_CODES -> syncXtreamIndexFirst(provider, force, onProgress)
ProviderType.M3U -> syncM3u(provider, force, onProgress)
ProviderType.STALKER_PORTAL -> syncStalker(provider, force, onProgress)
}
@@ -418,6 +464,110 @@ class SyncManager @Inject constructor(
syncStateTracker.reset(providerId)
}
+ suspend fun rebuildXtreamIndex(
+ providerId: Long,
+ 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")
+ if (providerEntity.type != ProviderType.XTREAM_CODES) {
+ return@lock com.streamvault.domain.model.Result.error("Index rebuild is only available for Xtream providers")
+ }
+
+ val provider = providerEntity
+ .copy(password = credentialCrypto.decryptIfNeeded(providerEntity.password))
+ .toDomain()
+
+ publishSyncState(providerId, SyncState.Syncing("Preparing index rebuild..."))
+ val now = System.currentTimeMillis()
+ val warnings = mutableListOf<String>()
+
+ try {
+ withContext(Dispatchers.IO) {
+ progress(providerId, onProgress, "Marking existing index rows stale...")
+ val staleRows = xtreamContentIndexDao.markVodAndSeriesRowsStaleForRebuild(providerId)
+ Log.i(TAG, "Marked $staleRows Xtream VOD/series index rows STALE_REMOTE for provider $providerId rebuild.")
+
+ val useTextClassification = preferencesRepository.useXtreamTextClassification.first()
+ val enableBase64TextCompatibility = preferencesRepository.xtreamBase64TextCompatibility.first()
+ val api = createXtreamSyncProvider(provider, useTextClassification, enableBase64TextCompatibility)
+
+ syncXtreamCategoryShell(
+ provider = provider,
+ api = api,
+ contentType = ContentType.MOVIE,
+ label = "Movies",
+ now = now,
+ onProgress = onProgress
+ ).getOrElse { error ->
+ warnings += "Movies index rebuild could not be queued."
+ upsertXtreamIndexJob(
+ providerId = providerId,
+ section = ContentType.MOVIE.name,
+ state = xtreamIndexFailureState(error),
+ now = now,
+ lastAttemptAt = now,
+ lastError = sanitizeThrowableMessage(error)
+ )
+ 0
+ }
+ scheduleXtreamIndexSync(providerId, ContentType.MOVIE, force = true)
+
+ syncXtreamCategoryShell(
+ provider = provider,
+ api = api,
+ contentType = ContentType.SERIES,
+ label = "Series",
+ now = now,
+ onProgress = onProgress
+ ).getOrElse { error ->
+ warnings += "Series index rebuild could not be queued."
+ upsertXtreamIndexJob(
+ providerId = providerId,
+ section = ContentType.SERIES.name,
+ state = xtreamIndexFailureState(error),
+ now = now,
+ lastAttemptAt = now,
+ lastError = sanitizeThrowableMessage(error)
+ )
+ 0
+ }
+ scheduleXtreamIndexSync(providerId, ContentType.SERIES, force = true)
+
+ val metadata = syncMetadataRepository.getMetadata(providerId) ?: SyncMetadata(providerId)
+ syncMetadataRepository.updateMetadata(
+ metadata.copy(
+ lastMovieAttempt = now,
+ movieCatalogStale = true,
+ movieSyncMode = VodSyncMode.UNKNOWN
+ )
+ )
+ }
+ updateSyncStatusMetadata(
+ providerId = providerId,
+ status = if (warnings.isEmpty()) "SUCCESS" else "PARTIAL"
+ )
+ publishSyncState(
+ providerId,
+ if (warnings.isEmpty()) {
+ SyncState.Success()
+ } else {
+ SyncState.Partial("Index rebuild queued with warnings", warnings)
+ }
+ )
+ com.streamvault.domain.model.Result.success(Unit)
+ } catch (e: CancellationException) {
+ resetState(providerId)
+ throw e
+ } catch (e: Exception) {
+ val safeMessage = syncErrorSanitizer.userMessage(e, "Index rebuild failed")
+ Log.e(TAG, "Xtream index rebuild failed for provider $providerId: ${syncErrorSanitizer.throwableMessage(e)}")
+ updateSyncStatusMetadata(providerId = providerId, status = "ERROR")
+ publishSyncState(providerId, SyncState.Error(safeMessage, e))
+ com.streamvault.domain.model.Result.error(safeMessage, e)
+ }
+ }
+
suspend fun retrySection(
providerId: Long,
section: SyncRepairSection,
@@ -473,7 +623,7 @@ class SyncManager @Inject constructor(
}
}
- private suspend fun syncXtream(
+ private suspend fun syncXtreamIndexFirst(
provider: Provider,
force: Boolean,
onProgress: ((String) -> Unit)?
@@ -482,16 +632,23 @@ class SyncManager @Inject constructor(
UrlSecurityPolicy.validateXtreamServerUrl(provider.serverUrl)?.let { message ->
throw IllegalStateException(message)
}
+
progress(provider.id, onProgress, "Connecting to server...")
val useTextClassification = preferencesRepository.useXtreamTextClassification.first()
val enableBase64TextCompatibility = preferencesRepository.xtreamBase64TextCompatibility.first()
val hiddenLiveCategoryIds = preferencesRepository.getHiddenCategoryIds(provider.id, ContentType.LIVE).first()
val api = createXtreamSyncProvider(provider, useTextClassification, enableBase64TextCompatibility)
-
- var metadata = syncMetadataRepository.getMetadata(provider.id) ?: SyncMetadata(provider.id)
val now = System.currentTimeMillis()
+ var metadata = syncMetadataRepository.getMetadata(provider.id) ?: SyncMetadata(provider.id)
- if (force || ContentCachePolicy.shouldRefresh(metadata.lastLiveSuccess, ContentCachePolicy.CATALOG_TTL_MILLIS, now)) {
+ upsertXtreamIndexJob(
+ providerId = provider.id,
+ section = ContentType.LIVE.name,
+ state = "RUNNING",
+ now = now,
+ lastAttemptAt = now
+ )
+ val liveOutcome = runCatching {
progress(provider.id, onProgress, "Downloading Live TV...")
val liveSyncResult = syncXtreamLiveCatalog(
provider = provider,
@@ -512,9 +669,9 @@ class SyncManager @Inject constructor(
feedback = liveSyncResult.strategyFeedback
)
- when (val liveResult = liveSyncResult.catalogResult) {
+ val acceptedCount = when (val liveResult = liveSyncResult.catalogResult) {
is CatalogStrategyResult.Success -> {
- val acceptedCount = liveSyncResult.stagedSessionId?.let { sessionId ->
+ val accepted = liveSyncResult.stagedSessionId?.let { sessionId ->
if (hiddenLiveCategoryIds.isNotEmpty()) {
mergeHiddenChannelsIntoStaging(provider.id, sessionId, hiddenLiveCategoryIds)
}
@@ -537,320 +694,923 @@ class SyncManager @Inject constructor(
channels = liveCatalog.channels
)
}
- metadata = metadata.copy(
- lastLiveSync = now,
- lastLiveSuccess = now,
- liveCount = acceptedCount,
- liveAvoidFullUntil = liveAvoidFullUntil,
- liveSequentialFailuresRemembered = liveProviderAdaptation.rememberSequential,
- liveHealthySyncStreak = liveProviderAdaptation.healthyStreak
- )
warnings += liveSyncResult.warnings + liveResult.warnings
+ accepted
}
is CatalogStrategyResult.Partial -> {
- // Partial snapshot: upsert only so that channels absent from the subset
- // are not deleted from the existing live catalog.
val liveCatalog = mergeVisibleLiveSyncWithHiddenStoredContent(
providerId = provider.id,
visibleCategories = liveSyncResult.categories,
visibleChannels = liveResult.items.map { it.toEntity() },
hiddenLiveCategoryIds = hiddenLiveCategoryIds
)
- val acceptedCount = syncCatalogStore.upsertLiveCatalog(
+ syncCatalogStore.upsertLiveCatalog(
providerId = provider.id,
categories = liveCatalog.categories,
channels = liveCatalog.channels
- )
- 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.")
+ ).also {
+ warnings += liveSyncResult.warnings + liveResult.warnings + "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
- )
- if (existingChannelCount > 0) {
- warnings += liveSyncResult.warnings + liveResult.warnings +
- listOf("Live TV refresh returned an empty valid catalog; keeping previous channel library.")
+ if (existingChannelCount == 0) {
+ throw IllegalStateException("Live TV catalog was empty.")
}
+ warnings += liveSyncResult.warnings + liveResult.warnings +
+ "Live TV refresh returned an empty valid catalog; keeping previous channel library."
+ existingChannelCount
}
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.")
- } else {
- listOf("Live TV sync failed before any usable channel catalog was available.")
- }
if (existingChannelCount == 0) {
throw IllegalStateException(
"Failed to fetch live streams: ${syncErrorSanitizer.throwableMessage(liveResult.error)}"
)
}
+ warnings += liveSyncResult.warnings + liveResult.warnings +
+ "Live TV sync degraded; keeping previous channel library."
+ existingChannelCount
}
}
- syncMetadataRepository.updateMetadata(metadata)
- }
- if (force || ContentCachePolicy.shouldRefresh(metadata.lastMovieSuccess, ContentCachePolicy.CATALOG_TTL_MILLIS, now)) {
- progress(
- provider.id,
- onProgress,
- "Downloading Movies..."
+ metadata = metadata.copy(
+ lastLiveSync = now,
+ lastLiveSuccess = now,
+ liveCount = acceptedCount,
+ liveAvoidFullUntil = liveAvoidFullUntil,
+ liveSequentialFailuresRemembered = liveProviderAdaptation.rememberSequential,
+ liveHealthySyncStreak = liveProviderAdaptation.healthyStreak
)
- val movieSyncResult = syncXtreamMoviesCatalog(
- provider = provider,
- api = api,
- existingMetadata = metadata,
- onProgress = onProgress
+ syncMetadataRepository.updateMetadata(metadata)
+ acceptedCount
+ }
+ val liveCount = liveOutcome.getOrElse { error ->
+ upsertXtreamIndexJob(
+ providerId = provider.id,
+ section = ContentType.LIVE.name,
+ state = xtreamIndexFailureState(error),
+ now = now,
+ lastAttemptAt = now,
+ lastError = sanitizeThrowableMessage(error)
)
- val sawSequentialStress = movieSyncResult.strategyFeedback.segmentedStressDetected
- val healthyMovieProviderAdaptation = updateSequentialProviderAdaptation(
- previousRemembered = metadata.movieParallelFailuresRemembered,
- previousHealthyStreak = metadata.movieHealthySyncStreak,
- sawSequentialStress = sawSequentialStress
+ throw error
+ }
+ upsertXtreamIndexJob(
+ providerId = provider.id,
+ section = ContentType.LIVE.name,
+ state = "QUEUED",
+ now = now,
+ totalCategories = 1,
+ completedCategories = 0,
+ indexedRows = liveCount,
+ lastAttemptAt = now,
+ lastError = null
+ )
+ scheduleXtreamIndexSync(provider.id, ContentType.LIVE)
+
+ val movieCategoryCount = syncXtreamCategoryShell(
+ provider = provider,
+ api = api,
+ contentType = ContentType.MOVIE,
+ label = "Movies",
+ now = now,
+ onProgress = onProgress
+ ).getOrElse { error ->
+ warnings += "Movies categories could not be loaded; movie indexing will retry later."
+ upsertXtreamIndexJob(
+ providerId = provider.id,
+ section = ContentType.MOVIE.name,
+ state = xtreamIndexFailureState(error),
+ now = now,
+ lastAttemptAt = now,
+ lastError = sanitizeThrowableMessage(error)
)
- val movieAvoidFullUntil = updateAvoidFullUntil(
- previousAvoidFullUntil = metadata.movieAvoidFullUntil,
+ 0
+ }
+ if (movieCategoryCount > 0) {
+ scheduleXtreamIndexSync(provider.id, ContentType.MOVIE)
+ }
+ val seriesCategoryCount = syncXtreamCategoryShell(
+ provider = provider,
+ api = api,
+ contentType = ContentType.SERIES,
+ label = "Series",
+ now = now,
+ onProgress = onProgress
+ ).getOrElse { error ->
+ warnings += "Series categories could not be loaded; series indexing will retry later."
+ upsertXtreamIndexJob(
+ providerId = provider.id,
+ section = ContentType.SERIES.name,
+ state = xtreamIndexFailureState(error),
now = now,
- feedback = movieSyncResult.strategyFeedback
+ lastAttemptAt = now,
+ lastError = sanitizeThrowableMessage(error)
)
+ 0
+ }
+ if (seriesCategoryCount > 0) {
+ scheduleXtreamIndexSync(provider.id, ContentType.SERIES)
+ }
- when (val catalogResult = movieSyncResult.catalogResult) {
- is CatalogStrategyResult.Success -> {
- 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 = acceptedCount,
- movieSyncMode = movieSyncResult.syncMode,
- movieWarningsCount = (movieSyncResult.warnings + catalogResult.warnings).size,
- movieCatalogStale = false,
- movieAvoidFullUntil = movieAvoidFullUntil,
- movieParallelFailuresRemembered = healthyMovieProviderAdaptation.rememberSequential,
- movieHealthySyncStreak = healthyMovieProviderAdaptation.healthyStreak
+ metadata = metadata.copy(
+ lastMovieAttempt = if (movieCategoryCount > 0) now else metadata.lastMovieAttempt,
+ movieCatalogStale = true,
+ movieSyncMode = VodSyncMode.UNKNOWN
+ )
+ syncMetadataRepository.updateMetadata(metadata)
+
+ val epgState = if (provider.epgSyncMode == ProviderEpgSyncMode.SKIP) "IDLE" else "QUEUED"
+ upsertXtreamIndexJob(
+ providerId = provider.id,
+ section = "EPG",
+ state = epgState,
+ now = now,
+ lastAttemptAt = if (epgState == "QUEUED") now else 0L
+ )
+ if (provider.epgSyncMode != ProviderEpgSyncMode.SKIP) {
+ runCatching { scheduleBackgroundEpgSync(provider.id) }
+ .onFailure { error ->
+ Log.w(TAG, "Failed to schedule Xtream background EPG sync for provider ${provider.id}: ${sanitizeThrowableMessage(error)}")
+ warnings += "EPG background sync could not be scheduled; it will retry on the next launch or manual sync."
+ }
+ }
+
+ if (force) {
+ Log.i(TAG, "Xtream index-first sync completed for provider ${provider.id}; VOD and series index jobs are queued.")
+ }
+ return if (warnings.isEmpty()) SyncOutcome() else SyncOutcome(partial = true, warnings = warnings.distinct())
+ }
+
+ private suspend fun syncXtreamCategoryShell(
+ provider: Provider,
+ api: XtreamProvider,
+ contentType: ContentType,
+ label: String,
+ now: Long,
+ onProgress: ((String) -> Unit)?
+ ): kotlin.Result<Int> = runCatching {
+ progress(provider.id, onProgress, "Loading $label categories...")
+ upsertXtreamIndexJob(
+ providerId = provider.id,
+ section = contentType.name,
+ state = "RUNNING",
+ now = now,
+ lastAttemptAt = now
+ )
+ val categories = when (contentType) {
+ ContentType.MOVIE -> requireResult(api.getVodCategories(), "Failed to load VOD categories")
+ ContentType.SERIES -> requireResult(api.getSeriesCategories(), "Failed to load series categories")
+ else -> throw IllegalArgumentException("Unsupported Xtream category shell: $contentType")
+ }
+ syncCatalogStore.upsertCategories(
+ providerId = provider.id,
+ type = contentType.name,
+ categories = categories.map { category -> category.toEntity(provider.id) }
+ )
+ upsertXtreamIndexJob(
+ providerId = provider.id,
+ section = contentType.name,
+ state = "QUEUED",
+ now = now,
+ totalCategories = categories.size,
+ completedCategories = 0,
+ nextCategoryIndex = 0,
+ failedCategories = 0,
+ indexedRows = 0,
+ skippedMalformedRows = 0,
+ lastAttemptAt = now,
+ lastError = null
+ )
+ categories.size
+ }
+
+ suspend fun processQueuedXtreamIndexJobs(
+ providerId: Long,
+ section: ContentType? = null,
+ force: Boolean = false,
+ maxCategoriesPerSection: Int? = null,
+ 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")
+ if (providerEntity.type != ProviderType.XTREAM_CODES) {
+ return@lock com.streamvault.domain.model.Result.success(Unit)
+ }
+
+ val provider = providerEntity
+ .copy(password = credentialCrypto.decryptIfNeeded(providerEntity.password))
+ .toDomain()
+ val useTextClassification = preferencesRepository.useXtreamTextClassification.first()
+ val enableBase64TextCompatibility = preferencesRepository.xtreamBase64TextCompatibility.first()
+ val api = createXtreamSyncProvider(provider, useTextClassification, enableBase64TextCompatibility)
+ val sections = when (section) {
+ ContentType.MOVIE -> listOf(ContentType.MOVIE)
+ ContentType.SERIES -> listOf(ContentType.SERIES)
+ ContentType.LIVE -> listOf(ContentType.LIVE)
+ ContentType.SERIES_EPISODE -> emptyList()
+ null -> listOf(ContentType.LIVE, ContentType.MOVIE, ContentType.SERIES)
+ }
+
+ var sawRetryableFailure = false
+ val warnings = mutableListOf<String>()
+ sections.forEach { contentType ->
+ val job = xtreamIndexJobDao.get(providerId, contentType.name)
+ if (!force && !shouldRunXtreamSummaryIndex(job)) {
+ return@forEach
+ }
+ val failure = runCatching {
+ when (contentType) {
+ ContentType.LIVE -> processXtreamLiveIndexBackfillSection(providerId, onProgress)
+ ContentType.MOVIE,
+ ContentType.SERIES -> processXtreamSummaryIndexSection(provider, api, contentType, maxCategoriesPerSection, onProgress)
+ ContentType.SERIES_EPISODE -> Unit
+ }
+ }.exceptionOrNull()
+ if (failure != null) {
+ val state = xtreamIndexFailureState(failure)
+ val currentJob = xtreamIndexJobDao.get(providerId, contentType.name)
+ if (currentJob?.state != "PARTIAL") {
+ val failureAt = System.currentTimeMillis()
+ upsertXtreamIndexJob(
+ providerId = providerId,
+ section = contentType.name,
+ state = state,
+ now = failureAt,
+ lastAttemptAt = failureAt,
+ lastError = sanitizeThrowableMessage(failure)
)
}
- is CatalogStrategyResult.Partial -> {
- // Partial means the server returned a truncated or mid-interrupted
- // catalog subset. Running full stale deletion would remove titles that
- // simply weren't included in the partial snapshot, so we upsert only.
- val acceptedCount = movieSyncResult.stagedSessionId?.let { sessionId ->
- syncCatalogStore.applyStagedMovieCatalogUpsertOnly(provider.id, sessionId, movieSyncResult.categories)
- movieSyncResult.stagedAcceptedCount
- } ?: syncCatalogStore.upsertMovieCatalog(
- providerId = provider.id,
- categories = movieSyncResult.categories,
- movies = catalogResult.items.asSequence().map { movie -> movie.toEntity() }
+ sawRetryableFailure = sawRetryableFailure || state != "FAILED_PERMANENT"
+ warnings += "${contentType.name.lowercase().replaceFirstChar { it.titlecase() }} indexing failed: ${sanitizeThrowableMessage(failure)}"
+ }
+ }
+
+ if (warnings.isNotEmpty()) {
+ val message = warnings.joinToString("; ")
+ val exception = if (sawRetryableFailure) IOException(message) else IllegalStateException(message)
+ com.streamvault.domain.model.Result.error(warnings.first(), exception)
+ } else {
+ com.streamvault.domain.model.Result.success(Unit)
+ }
+ }
+
+ private fun shouldRunXtreamSummaryIndex(job: XtreamIndexJobEntity?): Boolean {
+ if (job == null) return true
+ if (job.state in setOf("QUEUED", "RUNNING", "PARTIAL", "STALE", "FAILED_RETRYABLE")) return true
+ return ContentCachePolicy.shouldRefresh(job.lastSuccessAt, ContentCachePolicy.CATALOG_TTL_MILLIS)
+ }
+
+ private suspend fun processXtreamSummaryIndexSection(
+ provider: Provider,
+ api: XtreamProvider,
+ contentType: ContentType,
+ maxCategories: Int?,
+ onProgress: ((String) -> Unit)?
+ ) {
+ require(contentType == ContentType.MOVIE || contentType == ContentType.SERIES) {
+ "Unsupported Xtream summary index section: $contentType"
+ }
+ val now = System.currentTimeMillis()
+ val categories = categoryDao.getByProviderAndTypeSync(provider.id, contentType.name)
+ if (categories.isEmpty()) {
+ syncXtreamCategoryShell(
+ provider = provider,
+ api = api,
+ contentType = contentType,
+ label = xtreamIndexSectionLabel(contentType),
+ now = now,
+ onProgress = onProgress
+ ).getOrThrow()
+ }
+ val initialJob = xtreamIndexJobDao.get(provider.id, contentType.name)
+ val priorityCategoryId = initialJob?.priorityCategoryId
+ val indexedCategories = categoryDao.getByProviderAndTypeSync(provider.id, contentType.name)
+ val resumeJob = initialJob?.takeIf { it.state in setOf("QUEUED", "RUNNING", "PARTIAL") }
+ val categoryLimit = maxCategories?.coerceAtLeast(1) ?: Int.MAX_VALUE
+ var nextCategoryIndex = resumeJob?.nextCategoryIndex?.coerceIn(0, indexedCategories.size) ?: 0
+ if (shouldAttemptFullXtreamSummaryStream(resumeJob, priorityCategoryId)) {
+ when (val streamed = streamFullXtreamSummaryIndex(
+ provider = provider,
+ api = api,
+ contentType = contentType,
+ categories = indexedCategories,
+ totalCategories = indexedCategories.size,
+ now = now,
+ onProgress = onProgress
+ )) {
+ is Result.Success -> return
+ is Result.Error -> {
+ Log.w(
+ TAG,
+ "Full ${contentType.name} stream index failed for provider ${provider.id}; falling back to category slices: ${streamed.message}"
)
- metadata = metadata.copy(
- lastMovieSync = now,
- lastMovieAttempt = now,
- lastMoviePartial = now,
- movieCount = acceptedCount,
- movieSyncMode = movieSyncResult.syncMode,
- movieWarningsCount = (movieSyncResult.warnings + catalogResult.warnings).size,
- movieCatalogStale = true,
- movieAvoidFullUntil = movieAvoidFullUntil,
- movieParallelFailuresRemembered = metadata.movieParallelFailuresRemembered || sawSequentialStress,
- movieHealthySyncStreak = 0
+ upsertXtreamIndexJob(
+ providerId = provider.id,
+ section = contentType.name,
+ state = "QUEUED",
+ now = System.currentTimeMillis(),
+ totalCategories = indexedCategories.size,
+ completedCategories = 0,
+ nextCategoryIndex = 0,
+ failedCategories = 0,
+ lastAttemptAt = now,
+ lastError = streamed.message
)
- warnings += movieSyncResult.warnings + catalogResult.warnings
+ nextCategoryIndex = 0
}
- 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,
- movieAvoidFullUntil = movieAvoidFullUntil,
- 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.")
- }
+ Result.Loading -> Unit
+ }
+ }
+ upsertXtreamIndexJob(
+ providerId = provider.id,
+ section = contentType.name,
+ state = "RUNNING",
+ now = now,
+ totalCategories = indexedCategories.size,
+ completedCategories = resumeJob?.completedCategories ?: 0,
+ nextCategoryIndex = nextCategoryIndex,
+ failedCategories = resumeJob?.failedCategories ?: 0,
+ indexedRows = resumeJob?.indexedRows ?: 0,
+ skippedMalformedRows = resumeJob?.skippedMalformedRows ?: 0,
+ lastAttemptAt = now,
+ lastError = null
+ )
+
+ var completedCategories = resumeJob?.completedCategories ?: 0
+ var failedCategories = resumeJob?.failedCategories ?: 0
+ var indexedRows = resumeJob?.indexedRows ?: 0
+ var skippedMalformedRows = resumeJob?.skippedMalformedRows ?: 0
+ var lastError: Throwable? = null
+ var priorityHandled = false
+
+ data class CategoryIndexWork(
+ val category: CategoryEntity,
+ val advancesCursor: Boolean
+ )
+
+ val workItems = buildList {
+ val priorityIndex = priorityCategoryId?.let { id ->
+ indexedCategories.indexOfFirst { it.categoryId == id }.takeIf { index -> index >= 0 }
+ }
+ if (priorityIndex != null && priorityIndex != nextCategoryIndex && size < categoryLimit) {
+ add(CategoryIndexWork(indexedCategories[priorityIndex], advancesCursor = false))
+ }
+ while (nextCategoryIndex < indexedCategories.size && size < categoryLimit) {
+ val category = indexedCategories[nextCategoryIndex]
+ nextCategoryIndex++
+ if (
+ priorityCategoryId != null &&
+ category.categoryId == priorityCategoryId &&
+ any { it.category.categoryId == priorityCategoryId }
+ ) {
+ continue
}
- is CatalogStrategyResult.Failure -> {
- val existingMovieCount = movieDao.getCount(provider.id).first()
- val enteringLazyMode = movieSyncResult.syncMode == VodSyncMode.LAZY_BY_CATEGORY && !movieSyncResult.categories.isNullOrEmpty()
- val finalMode = if (enteringLazyMode) {
- VodSyncMode.LAZY_BY_CATEGORY
- } else {
- metadata.movieSyncMode
+ add(CategoryIndexWork(category, advancesCursor = true))
+ }
+ }
+
+ for (workItem in workItems) {
+ val category = workItem.category
+ progress(provider.id, onProgress, "Indexing ${xtreamIndexSectionLabel(contentType)}: ${category.name}")
+ val outcome = when (contentType) {
+ ContentType.MOVIE -> fetchMovieCategoryOutcome(provider, api, category.toXtreamCategory())
+ ContentType.SERIES -> fetchSeriesCategoryOutcome(provider, api, category.toXtreamCategory())
+ else -> error("Unsupported section")
+ }
+ when (val categoryOutcome = outcome.outcome) {
+ is CategoryFetchOutcome.Success -> {
+ val accepted = when (contentType) {
+ ContentType.MOVIE -> upsertXtreamMovieSummaryBatch(
+ providerId = provider.id,
+ movies = categoryOutcome.items.filterIsInstance<Movie>(),
+ indexedAt = System.currentTimeMillis()
+ )
+ ContentType.SERIES -> upsertXtreamSeriesSummaryBatch(
+ providerId = provider.id,
+ series = categoryOutcome.items.filterIsInstance<Series>(),
+ indexedAt = System.currentTimeMillis()
+ )
+ else -> 0
}
- if (enteringLazyMode) {
- movieSyncResult.categories?.let { syncCatalogStore.replaceCategories(provider.id, "MOVIE", it) }
+ if (workItem.advancesCursor) {
+ indexedRows += accepted
+ skippedMalformedRows += (categoryOutcome.rawCount - categoryOutcome.items.size).coerceAtLeast(0)
+ completedCategories++
}
- 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(
- lastMovieSync = if (enteringLazyMode) now else metadata.lastMovieSync,
- lastMovieAttempt = now,
- 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
- )
- val isFastSyncIntentional = enteringLazyMode || catalogResult.strategyName == "fast_sync_no_categories"
- if (!isFastSyncIntentional) {
- warnings += movieSyncResult.warnings + catalogResult.warnings +
- if (existingMovieCount > 0) {
- listOf("Movies sync degraded; keeping previous movie library.")
- } else {
- listOf("Movies sync failed; continuing with the rest of the provider sync.")
- }
+ if (category.categoryId == priorityCategoryId) {
+ priorityHandled = true
+ upsertXtreamIndexJob(
+ providerId = provider.id,
+ section = contentType.name,
+ state = "RUNNING",
+ now = System.currentTimeMillis(),
+ clearPriority = true
+ )
}
}
+ is CategoryFetchOutcome.Empty -> {
+ if (workItem.advancesCursor) {
+ completedCategories++
+ }
+ if (category.categoryId == priorityCategoryId) {
+ priorityHandled = true
+ upsertXtreamIndexJob(
+ providerId = provider.id,
+ section = contentType.name,
+ state = "RUNNING",
+ now = System.currentTimeMillis(),
+ clearPriority = true
+ )
+ }
+ }
+ is CategoryFetchOutcome.Failure -> {
+ if (workItem.advancesCursor) {
+ failedCategories++
+ }
+ lastError = categoryOutcome.error
+ }
}
- syncMetadataRepository.updateMetadata(metadata)
+ upsertXtreamIndexJob(
+ providerId = provider.id,
+ section = contentType.name,
+ state = if (failedCategories > 0) "PARTIAL" else "RUNNING",
+ now = System.currentTimeMillis(),
+ totalCategories = indexedCategories.size,
+ completedCategories = completedCategories,
+ nextCategoryIndex = nextCategoryIndex,
+ failedCategories = failedCategories,
+ indexedRows = indexedRows,
+ skippedMalformedRows = skippedMalformedRows,
+ lastAttemptAt = now,
+ lastError = lastError?.let(::sanitizeThrowableMessage)
+ )
+ }
+
+ val finishedAt = System.currentTimeMillis()
+ val hasMoreCategories = nextCategoryIndex < indexedCategories.size
+ val finalState = when {
+ hasMoreCategories -> "QUEUED"
+ failedCategories > 0 -> "PARTIAL"
+ else -> "SUCCESS"
+ }
+ val priorityWasNotPresent = priorityCategoryId != null &&
+ indexedCategories.none { it.categoryId == priorityCategoryId }
+ upsertXtreamIndexJob(
+ providerId = provider.id,
+ section = contentType.name,
+ state = finalState,
+ now = finishedAt,
+ totalCategories = indexedCategories.size,
+ completedCategories = completedCategories,
+ nextCategoryIndex = nextCategoryIndex,
+ failedCategories = failedCategories,
+ indexedRows = indexedRows,
+ skippedMalformedRows = skippedMalformedRows,
+ clearPriority = finalState == "SUCCESS" || priorityWasNotPresent || priorityHandled,
+ lastAttemptAt = now,
+ lastSuccessAt = if (finalState == "SUCCESS") finishedAt else null,
+ lastError = lastError?.let(::sanitizeThrowableMessage)
+ )
+ updateXtreamSummaryMetadata(provider.id, contentType, indexedRows, finalState, finishedAt)
+ if (hasMoreCategories) {
+ scheduleXtreamIndexSync(provider.id, contentType, force = false)
+ }
+ if (!hasMoreCategories && failedCategories > 0) {
+ throw IllegalStateException(
+ "${xtreamIndexSectionLabel(contentType)} indexing completed partially.",
+ lastError
+ )
+ }
+ }
+
+ private fun shouldAttemptFullXtreamSummaryStream(
+ resumeJob: XtreamIndexJobEntity?,
+ priorityCategoryId: Long?
+ ): Boolean {
+ if (priorityCategoryId != null && resumeJob?.nextCategoryIndex != 0) return false
+ if (resumeJob == null) return true
+ return resumeJob.nextCategoryIndex == 0 &&
+ resumeJob.completedCategories == 0 &&
+ resumeJob.failedCategories == 0 &&
+ resumeJob.indexedRows == 0
+ }
+
+ private suspend fun streamFullXtreamSummaryIndex(
+ provider: Provider,
+ api: XtreamProvider,
+ contentType: ContentType,
+ categories: List<CategoryEntity>,
+ totalCategories: Int,
+ now: Long,
+ onProgress: ((String) -> Unit)?
+ ): Result<Int> {
+ progress(provider.id, onProgress, "Indexing ${xtreamIndexSectionLabel(contentType)}...")
+ upsertXtreamIndexJob(
+ providerId = provider.id,
+ section = contentType.name,
+ state = "RUNNING",
+ now = now,
+ totalCategories = totalCategories,
+ completedCategories = 0,
+ nextCategoryIndex = 0,
+ failedCategories = 0,
+ indexedRows = 0,
+ skippedMalformedRows = 0,
+ lastAttemptAt = now,
+ lastError = null
+ )
+
+ var indexedRows = 0
+ val categoryNamesById = categories.associate { it.categoryId to it.name }
+ val adultCategoryIds = categories.filter { it.isAdult }.mapTo(mutableSetOf()) { it.categoryId }
+ val streamResult = when (contentType) {
+ ContentType.MOVIE -> api.streamVodSummaries(adultCategoryIds = adultCategoryIds) { batch ->
+ val accepted = upsertXtreamMovieSummaryBatch(
+ providerId = provider.id,
+ movies = batch.withMovieCategoryNames(categoryNamesById),
+ indexedAt = System.currentTimeMillis()
+ )
+ indexedRows += accepted
+ upsertXtreamIndexJob(
+ providerId = provider.id,
+ section = contentType.name,
+ state = "RUNNING",
+ now = System.currentTimeMillis(),
+ totalCategories = totalCategories,
+ completedCategories = 0,
+ nextCategoryIndex = 0,
+ indexedRows = indexedRows,
+ lastAttemptAt = now,
+ lastError = null
+ )
+ }
+ ContentType.SERIES -> api.streamSeriesSummaries(adultCategoryIds = adultCategoryIds) { batch ->
+ val accepted = upsertXtreamSeriesSummaryBatch(
+ providerId = provider.id,
+ series = batch.withSeriesCategoryNames(categoryNamesById),
+ indexedAt = System.currentTimeMillis()
+ )
+ indexedRows += accepted
+ upsertXtreamIndexJob(
+ providerId = provider.id,
+ section = contentType.name,
+ state = "RUNNING",
+ now = System.currentTimeMillis(),
+ totalCategories = totalCategories,
+ completedCategories = 0,
+ nextCategoryIndex = 0,
+ indexedRows = indexedRows,
+ lastAttemptAt = now,
+ lastError = null
+ )
+ }
+ else -> Result.error("Unsupported Xtream summary stream section: $contentType")
+ }
+
+ return when (streamResult) {
+ is Result.Success -> {
+ val finishedAt = System.currentTimeMillis()
+ val acceptedCount = indexedRows.coerceAtLeast(streamResult.data)
+ upsertXtreamIndexJob(
+ providerId = provider.id,
+ section = contentType.name,
+ state = "SUCCESS",
+ now = finishedAt,
+ totalCategories = totalCategories,
+ completedCategories = totalCategories,
+ nextCategoryIndex = totalCategories,
+ failedCategories = 0,
+ indexedRows = acceptedCount,
+ skippedMalformedRows = 0,
+ clearPriority = true,
+ lastAttemptAt = now,
+ lastSuccessAt = finishedAt,
+ lastError = null
+ )
+ updateXtreamSummaryMetadata(provider.id, contentType, acceptedCount, "SUCCESS", finishedAt)
+ Result.success(acceptedCount)
+ }
+ is Result.Error -> streamResult
+ Result.Loading -> Result.error("Xtream summary stream did not complete")
+ }
+ }
+
+ private fun List<Movie>.withMovieCategoryNames(categoryNamesById: Map<Long, String>): List<Movie> =
+ map { movie ->
+ val categoryName = movie.categoryId?.let(categoryNamesById::get)
+ if (categoryName == null || categoryName == movie.categoryName) movie else movie.copy(categoryName = categoryName)
+ }
+
+ private fun List<Series>.withSeriesCategoryNames(categoryNamesById: Map<Long, String>): List<Series> =
+ map { series ->
+ val categoryName = series.categoryId?.let(categoryNamesById::get)
+ if (categoryName == null || categoryName == series.categoryName) series else series.copy(categoryName = categoryName)
+ }
+
+ private suspend fun upsertXtreamMovieSummaryBatch(
+ providerId: Long,
+ movies: List<Movie>,
+ indexedAt: Long
+ ): Int {
+ if (movies.isEmpty()) return 0
+ val incoming = movies.map { movie -> movie.toEntity().copy(cacheState = "SUMMARY_ONLY", detailHydratedAt = 0L, remoteStaleAt = 0L) }
+ val existingByStreamId = movieDao.getByStreamIds(providerId, incoming.map { it.streamId }).associateBy { it.streamId }
+ val merged = incoming.map { summary ->
+ val existing = existingByStreamId[summary.streamId]
+ mergeMovieSummary(existing, summary)
+ }
+ transactionRunner.inTransaction {
+ movieDao.insertAll(merged)
+ val persistedByStreamId = movieDao.getByStreamIds(providerId, merged.map { it.streamId }).associateBy { it.streamId }
+ xtreamContentIndexDao.upsertAll(
+ merged.map { movie ->
+ val persisted = persistedByStreamId[movie.streamId] ?: movie
+ movie.toXtreamIndexRow(providerId, persisted.id, indexedAt)
+ }
+ )
}
+ movieDao.restoreWatchProgress(providerId)
+ return merged.size
+ }
+
+ private suspend fun upsertXtreamSeriesSummaryBatch(
+ providerId: Long,
+ series: List<Series>,
+ indexedAt: Long
+ ): Int {
+ if (series.isEmpty()) return 0
+ val incoming = series.map { item -> item.toEntity().copy(cacheState = "SUMMARY_ONLY", detailHydratedAt = 0L, remoteStaleAt = 0L) }
+ val existingBySeriesId = seriesDao.getBySeriesIds(providerId, incoming.map { it.seriesId }).associateBy { it.seriesId }
+ val merged = incoming.map { summary ->
+ val existing = existingBySeriesId[summary.seriesId]
+ mergeSeriesSummary(existing, summary)
+ }
+ transactionRunner.inTransaction {
+ seriesDao.insertAll(merged)
+ val persistedBySeriesId = seriesDao.getBySeriesIds(providerId, merged.map { it.seriesId }).associateBy { it.seriesId }
+ xtreamContentIndexDao.upsertAll(
+ merged.map { item ->
+ val persisted = persistedBySeriesId[item.seriesId] ?: item
+ item.toXtreamIndexRow(providerId, persisted.id, indexedAt)
+ }
+ )
+ }
+ return merged.size
+ }
+
+ private fun mergeMovieSummary(existing: MovieEntity?, summary: MovieEntity): MovieEntity {
+ if (existing == null) return summary
+ val preserveDetails = existing.cacheState == "DETAIL_HYDRATED" && existing.detailHydratedAt > 0L
+ return summary.copy(
+ id = existing.id,
+ posterUrl = summary.posterUrl ?: existing.posterUrl,
+ backdropUrl = if (preserveDetails) existing.backdropUrl else summary.backdropUrl,
+ plot = if (preserveDetails) existing.plot else summary.plot,
+ cast = if (preserveDetails) existing.cast else summary.cast,
+ director = if (preserveDetails) existing.director else summary.director,
+ genre = summary.genre ?: existing.genre,
+ releaseDate = if (preserveDetails) existing.releaseDate else summary.releaseDate,
+ duration = if (preserveDetails) existing.duration else summary.duration,
+ durationSeconds = if (preserveDetails) existing.durationSeconds else summary.durationSeconds,
+ year = if (preserveDetails) existing.year else summary.year,
+ tmdbId = summary.tmdbId ?: existing.tmdbId,
+ youtubeTrailer = summary.youtubeTrailer ?: existing.youtubeTrailer,
+ watchProgress = existing.watchProgress,
+ watchCount = existing.watchCount,
+ lastWatchedAt = existing.lastWatchedAt,
+ isUserProtected = existing.isUserProtected,
+ cacheState = if (preserveDetails) existing.cacheState else "SUMMARY_ONLY",
+ detailHydratedAt = if (preserveDetails) existing.detailHydratedAt else 0L,
+ remoteStaleAt = 0L
+ )
+ }
+
+ private fun mergeSeriesSummary(existing: SeriesEntity?, summary: SeriesEntity): SeriesEntity {
+ if (existing == null) return summary
+ val preserveDetails = existing.cacheState == "DETAIL_HYDRATED" && existing.detailHydratedAt > 0L
+ return summary.copy(
+ id = existing.id,
+ providerSeriesId = summary.providerSeriesId ?: existing.providerSeriesId,
+ posterUrl = summary.posterUrl ?: existing.posterUrl,
+ backdropUrl = if (preserveDetails) existing.backdropUrl else summary.backdropUrl,
+ plot = if (preserveDetails) existing.plot else summary.plot,
+ cast = if (preserveDetails) existing.cast else summary.cast,
+ director = if (preserveDetails) existing.director else summary.director,
+ genre = summary.genre ?: existing.genre,
+ releaseDate = if (preserveDetails) existing.releaseDate else summary.releaseDate,
+ tmdbId = summary.tmdbId ?: existing.tmdbId,
+ youtubeTrailer = summary.youtubeTrailer ?: existing.youtubeTrailer,
+ episodeRunTime = if (preserveDetails) existing.episodeRunTime else summary.episodeRunTime,
+ isUserProtected = existing.isUserProtected,
+ cacheState = if (preserveDetails) existing.cacheState else "SUMMARY_ONLY",
+ detailHydratedAt = if (preserveDetails) existing.detailHydratedAt else 0L,
+ remoteStaleAt = 0L
+ )
+ }
+
+ private fun MovieEntity.toXtreamIndexRow(
+ providerId: Long,
+ localContentId: Long,
+ indexedAt: Long
+ ): XtreamContentIndexEntity = XtreamContentIndexEntity(
+ providerId = providerId,
+ contentType = ContentType.MOVIE,
+ remoteId = streamId.toString(),
+ localContentId = localContentId.takeIf { it > 0L },
+ name = name,
+ categoryId = categoryId,
+ categoryName = categoryName,
+ imageUrl = posterUrl,
+ containerExtension = containerExtension,
+ rating = rating,
+ addedAt = addedAt,
+ isAdult = isAdult,
+ indexedAt = indexedAt,
+ detailHydratedAt = detailHydratedAt,
+ staleState = "ACTIVE",
+ errorState = null,
+ syncFingerprint = syncFingerprint
+ )
+
+ private fun SeriesEntity.toXtreamIndexRow(
+ providerId: Long,
+ localContentId: Long,
+ indexedAt: Long
+ ): XtreamContentIndexEntity = XtreamContentIndexEntity(
+ providerId = providerId,
+ contentType = ContentType.SERIES,
+ remoteId = providerSeriesId?.takeIf { it.isNotBlank() } ?: seriesId.toString(),
+ localContentId = localContentId.takeIf { it > 0L },
+ name = name,
+ categoryId = categoryId,
+ categoryName = categoryName,
+ imageUrl = posterUrl,
+ rating = rating,
+ remoteUpdatedAt = lastModified,
+ isAdult = isAdult,
+ indexedAt = indexedAt,
+ detailHydratedAt = detailHydratedAt,
+ staleState = "ACTIVE",
+ errorState = null,
+ syncFingerprint = syncFingerprint
+ )
- if (force || ContentCachePolicy.shouldRefresh(metadata.lastSeriesSuccess, ContentCachePolicy.CATALOG_TTL_MILLIS, now)) {
- progress(provider.id, onProgress, "Downloading Series...")
- 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
+ private suspend fun updateXtreamSummaryMetadata(
+ providerId: Long,
+ contentType: ContentType,
+ indexedRows: Int,
+ finalState: String,
+ now: Long
+ ) {
+ val metadata = syncMetadataRepository.getMetadata(providerId) ?: SyncMetadata(providerId)
+ when (contentType) {
+ ContentType.MOVIE -> syncMetadataRepository.updateMetadata(
+ metadata.copy(
+ lastMovieSync = now,
+ lastMovieAttempt = now,
+ lastMovieSuccess = if (finalState == "SUCCESS") now else metadata.lastMovieSuccess,
+ lastMoviePartial = if (finalState != "SUCCESS") now else metadata.lastMoviePartial,
+ movieCount = if (finalState == "SUCCESS") indexedRows else metadata.movieCount.coerceAtLeast(indexedRows),
+ movieCatalogStale = finalState != "SUCCESS",
+ movieSyncMode = VodSyncMode.UNKNOWN
+ )
)
- val seriesAvoidFullUntil = updateAvoidFullUntil(
- previousAvoidFullUntil = metadata.seriesAvoidFullUntil,
- now = now,
- feedback = seriesSyncResult.strategyFeedback
+ ContentType.SERIES -> syncMetadataRepository.updateMetadata(
+ metadata.copy(
+ lastSeriesSync = now,
+ lastSeriesSuccess = if (finalState == "SUCCESS") now else metadata.lastSeriesSuccess,
+ seriesCount = if (finalState == "SUCCESS") indexedRows else metadata.seriesCount.coerceAtLeast(indexedRows)
+ )
)
+ else -> Unit
+ }
+ }
- when (val seriesResult = seriesSyncResult.catalogResult) {
- is CatalogStrategyResult.Success -> {
- 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,
- lastSeriesSuccess = now,
- seriesCount = acceptedCount,
- seriesAvoidFullUntil = seriesAvoidFullUntil,
- seriesSequentialFailuresRemembered = seriesProviderAdaptation.rememberSequential,
- seriesHealthySyncStreak = seriesProviderAdaptation.healthyStreak
- )
- warnings += seriesSyncResult.warnings + seriesResult.warnings
- }
- is CatalogStrategyResult.Partial -> {
- // Partial result: upsert only to avoid deleting titles that weren't
- // included in the truncated snapshot.
- val acceptedCount = seriesSyncResult.stagedSessionId?.let { sessionId ->
- syncCatalogStore.applyStagedSeriesCatalogUpsertOnly(provider.id, sessionId, seriesSyncResult.categories)
- seriesSyncResult.stagedAcceptedCount
- } ?: syncCatalogStore.upsertSeriesCatalog(
- 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.")
- } 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()
- 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
- )
- val isSeriesFastSyncIntentional = enteringLazyMode || seriesResult.strategyName == "fast_sync_no_categories"
- if (!isSeriesFastSyncIntentional) {
- warnings += seriesSyncResult.warnings + seriesResult.warnings +
- if (existingSeriesCount > 0) {
- listOf("Series sync degraded; keeping previous series library.")
- } else {
- listOf("Series sync failed; continuing with the rest of the provider sync.")
- }
- }
- }
- }
- syncMetadataRepository.updateMetadata(metadata)
+ private fun CategoryEntity.toXtreamCategory(): XtreamCategory = XtreamCategory(
+ categoryId = categoryId.toString(),
+ categoryName = name,
+ parentId = parentId?.toInt() ?: 0,
+ isAdult = isAdult
+ )
+
+ private fun xtreamIndexSectionLabel(contentType: ContentType): String = when (contentType) {
+ ContentType.MOVIE -> "Movies"
+ ContentType.SERIES -> "Series"
+ ContentType.LIVE -> "Live TV"
+ ContentType.SERIES_EPISODE -> "Episodes"
+ }
+
+ private suspend fun processXtreamLiveIndexBackfillSection(
+ providerId: Long,
+ onProgress: ((String) -> Unit)?
+ ) {
+ val now = System.currentTimeMillis()
+ progress(providerId, onProgress, "Preparing Live TV index...")
+ upsertXtreamIndexJob(
+ providerId = providerId,
+ section = ContentType.LIVE.name,
+ state = "RUNNING",
+ now = now,
+ lastAttemptAt = now,
+ lastError = null
+ )
+ val categoryCount = categoryDao.getByProviderAndTypeSync(providerId, ContentType.LIVE.name).size
+ val indexedRows = backfillXtreamLiveIndex(providerId, now)
+ upsertXtreamIndexJob(
+ providerId = providerId,
+ section = ContentType.LIVE.name,
+ state = "SUCCESS",
+ now = System.currentTimeMillis(),
+ totalCategories = categoryCount,
+ completedCategories = categoryCount,
+ nextCategoryIndex = categoryCount,
+ failedCategories = 0,
+ indexedRows = indexedRows,
+ skippedMalformedRows = 0,
+ lastAttemptAt = now,
+ lastSuccessAt = System.currentTimeMillis(),
+ lastError = null
+ )
+ }
+
+ private suspend fun backfillXtreamLiveIndex(providerId: Long, indexedAt: Long): Int {
+ val channels = channelDao.getByProviderSync(providerId)
+ if (channels.isEmpty()) return 0
+ val indexRows = channels.map { channel ->
+ XtreamContentIndexEntity(
+ providerId = providerId,
+ contentType = ContentType.LIVE,
+ remoteId = channel.streamId.toString(),
+ localContentId = channel.id.takeIf { it > 0 },
+ name = channel.name,
+ categoryId = channel.categoryId,
+ categoryName = channel.categoryName ?: channel.groupTitle,
+ imageUrl = channel.logoUrl,
+ isAdult = channel.isAdult,
+ indexedAt = indexedAt,
+ detailHydratedAt = indexedAt,
+ syncFingerprint = channel.syncFingerprint
+ )
+ }
+ transactionRunner.inTransaction {
+ xtreamContentIndexDao.deleteByProviderAndType(providerId, ContentType.LIVE.name)
+ xtreamContentIndexDao.upsertAll(indexRows)
}
+ return channels.size
+ }
- if (shouldSyncEpgUpfront(provider)) {
- warnings += syncProviderEpg(
- provider = provider,
- metadata = metadata,
- now = now,
- force = force,
- onProgress = onProgress
- ).warnings
+ private fun xtreamIndexFailureState(error: Throwable): String {
+ val chain = generateSequence(error as Throwable?) { it.cause }.toList()
+ if (chain.any { it is XtreamAuthenticationException }) {
+ return "FAILED_PERMANENT"
+ }
+ val requestFailure = chain.filterIsInstance<XtreamRequestException>().firstOrNull()
+ if (requestFailure?.statusCode == 401 || requestFailure?.statusCode == 403) {
+ return "FAILED_PERMANENT"
}
+ return "FAILED_RETRYABLE"
+ }
- return if (warnings.isEmpty()) SyncOutcome() else SyncOutcome(partial = true, warnings = warnings)
+ private suspend fun upsertXtreamIndexJob(
+ providerId: Long,
+ section: String,
+ state: String,
+ now: Long,
+ totalCategories: Int? = null,
+ completedCategories: Int? = null,
+ nextCategoryIndex: Int? = null,
+ failedCategories: Int? = null,
+ indexedRows: Int? = null,
+ skippedMalformedRows: Int? = null,
+ deletedPrunedRows: Int? = null,
+ priorityCategoryId: Long? = null,
+ priorityRequestedAt: Long? = null,
+ clearPriority: Boolean = false,
+ lastAttemptAt: Long? = null,
+ lastSuccessAt: Long? = null,
+ lastError: String? = null
+ ) {
+ val existing = xtreamIndexJobDao.get(providerId, section)
+ xtreamIndexJobDao.upsert(
+ (existing ?: XtreamIndexJobEntity(providerId = providerId, section = section)).copy(
+ state = state,
+ totalCategories = totalCategories ?: existing?.totalCategories ?: 0,
+ completedCategories = completedCategories ?: existing?.completedCategories ?: 0,
+ nextCategoryIndex = nextCategoryIndex ?: existing?.nextCategoryIndex ?: 0,
+ failedCategories = failedCategories ?: existing?.failedCategories ?: 0,
+ indexedRows = indexedRows ?: existing?.indexedRows ?: 0,
+ skippedMalformedRows = skippedMalformedRows ?: existing?.skippedMalformedRows ?: 0,
+ deletedPrunedRows = deletedPrunedRows ?: existing?.deletedPrunedRows ?: 0,
+ priorityCategoryId = if (clearPriority) null else priorityCategoryId ?: existing?.priorityCategoryId,
+ priorityRequestedAt = if (clearPriority) 0L else priorityRequestedAt ?: existing?.priorityRequestedAt ?: 0L,
+ lastError = lastError,
+ lastAttemptAt = lastAttemptAt ?: existing?.lastAttemptAt ?: 0L,
+ lastSuccessAt = lastSuccessAt ?: existing?.lastSuccessAt ?: 0L,
+ updatedAt = now
+ )
+ )
}
private suspend fun syncM3u(
@@ -1057,7 +1817,9 @@ class SyncManager @Inject constructor(
UrlSecurityPolicy.validateXtreamEpgUrl(xmltvUrl)?.let { message ->
throw IllegalStateException(message)
}
- retryTransient { epgRepository.refreshEpg(provider.id, xmltvUrl) }
+ retryTransient {
+ requireResult(epgRepository.refreshEpg(provider.id, xmltvUrl), "Failed to refresh EPG")
+ }
val epgCount = programDao.countByProvider(provider.id)
updatedMetadata = updatedMetadata.copy(
lastEpgSync = now,
@@ -1087,7 +1849,9 @@ class SyncManager @Inject constructor(
} else {
try {
progress(provider.id, onProgress, "Downloading EPG...")
- retryTransient { epgRepository.refreshEpg(provider.id, currentEpgUrl) }
+ retryTransient {
+ requireResult(epgRepository.refreshEpg(provider.id, currentEpgUrl), "Failed to refresh EPG")
+ }
updatedMetadata = updatedMetadata.copy(
lastEpgSync = now,
lastEpgSuccess = now,
@@ -1123,7 +1887,12 @@ class SyncManager @Inject constructor(
try {
progress(provider.id, onProgress, "Refreshing external EPG sources...")
- epgSourceRepository.refreshAllForProvider(provider.id)
+ retryTransient {
+ requireResult(
+ epgSourceRepository.refreshAllForProvider(provider.id),
+ "External EPG source refresh failed"
+ )
+ }
progress(provider.id, onProgress, "Resolving EPG mappings...")
epgSourceRepository.resolveForProvider(provider.id, hiddenLiveCategoryIds)
} catch (e: CancellationException) {
@@ -1150,7 +1919,12 @@ class SyncManager @Inject constructor(
onProgress = onProgress
)
progress(provider.id, onProgress, "Refreshing external EPG sources...")
- epgSourceRepository.refreshAllForProvider(provider.id)
+ retryTransient {
+ requireResult(
+ epgSourceRepository.refreshAllForProvider(provider.id),
+ "External EPG source refresh failed"
+ )
+ }
progress(provider.id, onProgress, "Resolving EPG mappings...")
epgSourceRepository.resolveForProvider(provider.id, hiddenLiveCategoryIds)
return
@@ -1168,7 +1942,12 @@ class SyncManager @Inject constructor(
if (epgUrl.isBlank()) {
if (provider.type == ProviderType.STALKER_PORTAL) {
progress(provider.id, onProgress, "Refreshing external EPG sources...")
- epgSourceRepository.refreshAllForProvider(provider.id)
+ retryTransient {
+ requireResult(
+ epgSourceRepository.refreshAllForProvider(provider.id),
+ "External EPG source refresh failed"
+ )
+ }
progress(provider.id, onProgress, "Resolving EPG mappings...")
epgSourceRepository.resolveForProvider(provider.id, hiddenLiveCategoryIds)
return
@@ -1183,7 +1962,9 @@ class SyncManager @Inject constructor(
validationError?.let { message ->
throw IllegalStateException(message)
}
- retryTransient { epgRepository.refreshEpg(provider.id, epgUrl) }
+ retryTransient {
+ requireResult(epgRepository.refreshEpg(provider.id, epgUrl), "Failed to refresh EPG")
+ }
val now = System.currentTimeMillis()
val metadata = (syncMetadataRepository.getMetadata(provider.id) ?: SyncMetadata(provider.id))
.copy(
@@ -1195,7 +1976,12 @@ class SyncManager @Inject constructor(
// Also refresh external sources and run resolution
progress(provider.id, onProgress, "Refreshing external EPG sources...")
- epgSourceRepository.refreshAllForProvider(provider.id)
+ retryTransient {
+ requireResult(
+ epgSourceRepository.refreshAllForProvider(provider.id),
+ "External EPG source refresh failed"
+ )
+ }
progress(provider.id, onProgress, "Resolving EPG mappings...")
epgSourceRepository.resolveForProvider(provider.id, hiddenLiveCategoryIds)
}
@@ -1218,7 +2004,9 @@ class SyncManager @Inject constructor(
} else {
try {
progress(provider.id, onProgress, "Downloading EPG...")
- retryTransient { epgRepository.refreshEpg(provider.id, currentEpgUrl) }
+ retryTransient {
+ requireResult(epgRepository.refreshEpg(provider.id, currentEpgUrl), "Failed to refresh EPG")
+ }
val epgCount = programDao.countByProvider(provider.id)
if (epgCount > 0) {
syncMetadataRepository.updateMetadata(
@@ -1614,137 +2402,42 @@ class SyncManager @Inject constructor(
val sectionWarnings = mutableListOf<String>()
when (provider.type) {
ProviderType.XTREAM_CODES -> {
- progress(
- provider.id,
- onProgress,
- "Retrying Movies..."
- )
+ progress(provider.id, onProgress, "Queueing Movies index...")
val useTextClassification = preferencesRepository.useXtreamTextClassification.first()
val enableBase64TextCompatibility = preferencesRepository.xtreamBase64TextCompatibility.first()
val api = createXtreamSyncProvider(provider, useTextClassification, enableBase64TextCompatibility)
val currentMetadata = syncMetadataRepository.getMetadata(provider.id) ?: SyncMetadata(provider.id)
- val movieSyncResult = syncXtreamMoviesCatalog(
+ val categoryCount = syncXtreamCategoryShell(
provider = provider,
api = api,
- existingMetadata = currentMetadata,
- onProgress = onProgress
- )
- 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,
+ contentType = ContentType.MOVIE,
+ label = "Movies",
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 -> {
- val acceptedCount = if (movieSyncResult.syncMode == VodSyncMode.FAST_SYNC) {
- movieSyncResult.categories?.let {
- syncCatalogStore.replaceCategories(provider.id, "MOVIE", it)
- }
- movieDao.getCount(provider.id).first()
- } else {
- 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 = acceptedCount,
- movieCatalogStale = false,
- movieAvoidFullUntil = movieAvoidFullUntil,
- movieParallelFailuresRemembered = healthyMovieProviderAdaptation.rememberSequential,
- movieHealthySyncStreak = healthyMovieProviderAdaptation.healthyStreak
- )
- )
- }
- is CatalogStrategyResult.Partial -> {
- // Partial snapshot: upsert only to avoid deleting titles absent from the subset.
- val acceptedCount = movieSyncResult.stagedSessionId?.let { sessionId ->
- syncCatalogStore.applyStagedMovieCatalogUpsertOnly(provider.id, sessionId, movieSyncResult.categories)
- movieSyncResult.stagedAcceptedCount
- } ?: syncCatalogStore.upsertMovieCatalog(
- providerId = provider.id,
- categories = movieSyncResult.categories,
- movies = catalogResult.items.asSequence().map { movie -> movie.toEntity() }
- )
- syncMetadataRepository.updateMetadata(
- metadata.copy(
- lastMovieSync = now,
- lastMoviePartial = now,
- movieCount = acceptedCount,
- movieCatalogStale = true,
- movieAvoidFullUntil = movieAvoidFullUntil,
- movieParallelFailuresRemembered = currentMetadata.movieParallelFailuresRemembered || sawSequentialStress,
- movieHealthySyncStreak = 0
- )
- )
- sectionWarnings += movieWarnings + listOf("Movies retry completed partially.")
- }
- is CatalogStrategyResult.EmptyValid -> {
- val existingMovieCount = movieDao.getCount(provider.id).first()
- syncMetadataRepository.updateMetadata(
- metadata.copy(
- movieCatalogStale = existingMovieCount > 0 || movieSyncResult.syncMode == VodSyncMode.LAZY_BY_CATEGORY,
- movieAvoidFullUntil = movieAvoidFullUntil,
- 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()
- val enteringLazyMode = movieSyncResult.syncMode == VodSyncMode.LAZY_BY_CATEGORY && !movieSyncResult.categories.isNullOrEmpty()
- if (enteringLazyMode) {
- movieSyncResult.categories?.let { syncCatalogStore.replaceCategories(provider.id, "MOVIE", it) }
- }
- syncMetadataRepository.updateMetadata(
- metadata.copy(
- lastMovieSync = if (enteringLazyMode) now else metadata.lastMovieSync,
- movieCatalogStale = existingMovieCount > 0 || movieSyncResult.syncMode == VodSyncMode.LAZY_BY_CATEGORY,
- movieAvoidFullUntil = movieAvoidFullUntil,
- movieParallelFailuresRemembered = currentMetadata.movieParallelFailuresRemembered || sawSequentialStress || shouldRememberSequentialPreference(catalogResult.error),
- movieHealthySyncStreak = 0
+ onProgress = onProgress
+ ).getOrElse { error ->
+ upsertXtreamIndexJob(
+ providerId = provider.id,
+ section = ContentType.MOVIE.name,
+ state = xtreamIndexFailureState(error),
+ now = now,
+ lastAttemptAt = now,
+ lastError = sanitizeThrowableMessage(error)
)
- )
- if (!enteringLazyMode) {
throw IllegalStateException(
- syncErrorSanitizer.userMessage(catalogResult.error, "Failed to fetch VOD streams"),
- catalogResult.error
+ syncErrorSanitizer.userMessage(error, "Failed to queue movie index"),
+ error
)
}
+ syncMetadataRepository.updateMetadata(
+ currentMetadata.copy(
+ lastMovieAttempt = now,
+ movieCatalogStale = true,
+ movieSyncMode = VodSyncMode.UNKNOWN
+ )
+ )
+ scheduleXtreamIndexSync(provider.id, ContentType.MOVIE)
+ Log.i(TAG, "Queued Xtream movie index for provider ${provider.id}: $categoryCount categories.")
}
- }
- }
ProviderType.M3U -> {
progress(provider.id, onProgress, "Retrying Movies...")
val stats = withContext(Dispatchers.IO) {
@@ -1807,111 +2500,40 @@ class SyncManager @Inject constructor(
val sectionWarnings = mutableListOf<String>()
when (provider.type) {
ProviderType.XTREAM_CODES -> {
- progress(provider.id, onProgress, "Retrying Series...")
+ val now = System.currentTimeMillis()
+ progress(provider.id, onProgress, "Queueing Series index...")
val useTextClassification = preferencesRepository.useXtreamTextClassification.first()
val enableBase64TextCompatibility = preferencesRepository.xtreamBase64TextCompatibility.first()
val api = createXtreamSyncProvider(provider, useTextClassification, enableBase64TextCompatibility)
val currentMetadata = syncMetadataRepository.getMetadata(provider.id) ?: SyncMetadata(provider.id)
- val seriesSyncResult = syncXtreamSeriesCatalog(
+ val categoryCount = syncXtreamCategoryShell(
provider = provider,
api = api,
- existingMetadata = currentMetadata,
- onProgress = onProgress
- )
-
- val now = System.currentTimeMillis()
- val seriesSequentialStress = seriesSyncResult.strategyFeedback.segmentedStressDetected
- val seriesProviderAdaptation = updateSequentialProviderAdaptation(
- previousRemembered = currentMetadata.seriesSequentialFailuresRemembered,
- previousHealthyStreak = currentMetadata.seriesHealthySyncStreak,
- sawSequentialStress = seriesSequentialStress
- )
- val seriesAvoidFullUntil = updateAvoidFullUntil(
- previousAvoidFullUntil = currentMetadata.seriesAvoidFullUntil,
+ contentType = ContentType.SERIES,
+ label = "Series",
now = now,
- feedback = seriesSyncResult.strategyFeedback
- )
- when (val seriesResult = seriesSyncResult.catalogResult) {
- is CatalogStrategyResult.Success -> {
- 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,
- lastSeriesSuccess = now,
- seriesCount = acceptedCount,
- seriesAvoidFullUntil = seriesAvoidFullUntil,
- seriesSequentialFailuresRemembered = seriesProviderAdaptation.rememberSequential,
- seriesHealthySyncStreak = seriesProviderAdaptation.healthyStreak
- )
- )
- }
- is CatalogStrategyResult.Partial -> {
- // Partial snapshot: upsert only to preserve series absent from the subset.
- val acceptedCount = seriesSyncResult.stagedSessionId?.let { sessionId ->
- syncCatalogStore.applyStagedSeriesCatalogUpsertOnly(provider.id, sessionId, seriesSyncResult.categories)
- seriesSyncResult.stagedAcceptedCount
- } ?: syncCatalogStore.upsertSeriesCatalog(
- providerId = provider.id,
- categories = seriesSyncResult.categories,
- series = seriesResult.items.asSequence().map { it.toEntity() }
- )
- syncMetadataRepository.updateMetadata(
- currentMetadata.copy(
- lastSeriesSync = now,
- seriesCount = acceptedCount,
- seriesAvoidFullUntil = seriesAvoidFullUntil,
- seriesSequentialFailuresRemembered = currentMetadata.seriesSequentialFailuresRemembered || seriesSequentialStress,
- seriesHealthySyncStreak = 0
- )
- )
- sectionWarnings += seriesSyncResult.warnings + seriesResult.warnings +
- listOf("Series retry completed partially.")
- }
- 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."
- } else {
- "Series catalog was empty."
- }
- )
- }
- is CatalogStrategyResult.Failure -> {
- 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
- )
- }
- }
+ onProgress = onProgress
+ ).getOrElse { error ->
+ upsertXtreamIndexJob(
+ providerId = provider.id,
+ section = ContentType.SERIES.name,
+ state = xtreamIndexFailureState(error),
+ now = now,
+ lastAttemptAt = now,
+ lastError = sanitizeThrowableMessage(error)
+ )
+ throw IllegalStateException(
+ syncErrorSanitizer.userMessage(error, "Failed to queue series index"),
+ error
+ )
}
+ syncMetadataRepository.updateMetadata(
+ currentMetadata.copy(
+ lastSeriesSync = now
+ )
+ )
+ scheduleXtreamIndexSync(provider.id, ContentType.SERIES)
+ Log.i(TAG, "Queued Xtream series index for provider ${provider.id}: $categoryCount categories.")
}
ProviderType.STALKER_PORTAL -> {
progress(provider.id, onProgress, "Retrying Series...")
@@ -1948,19 +2570,6 @@ class SyncManager @Inject constructor(
return if (sectionWarnings.isEmpty()) SyncOutcome() else SyncOutcome(partial = true, warnings = sectionWarnings)
}
- private suspend fun syncXtreamMoviesCatalog(
- provider: Provider,
- api: XtreamProvider,
- existingMetadata: SyncMetadata,
- onProgress: ((String) -> Unit)?
- ): MovieCatalogSyncResult =
- xtreamMovieStrategy.syncXtreamMoviesCatalog(provider, api, existingMetadata, onProgress)
-
- private suspend fun loadXtreamMoviesFull(
- provider: Provider,
- api: XtreamProvider
- ): CatalogSyncPayload<Movie> = xtreamMovieStrategy.loadXtreamMoviesFull(provider, api)
-
private suspend fun syncXtreamLiveCatalog(
provider: Provider,
api: XtreamProvider,
@@ -1984,81 +2593,12 @@ class SyncManager @Inject constructor(
): CatalogStrategyResult<Channel> =
xtreamLiveStrategy.loadXtreamLiveByCategory(provider, api, rawCategories, onProgress, preferSequential)
- private suspend fun loadXtreamMoviesByCategory(
- provider: Provider,
- api: XtreamProvider,
- rawCategories: List<XtreamCategory>,
- onProgress: ((String) -> Unit)?,
- preferSequential: Boolean
- ): CatalogSyncPayload<Movie> =
- xtreamMovieStrategy.loadXtreamMoviesByCategory(provider, api, rawCategories, onProgress, preferSequential)
-
- private suspend fun loadXtreamMoviesByPage(
- provider: Provider,
- api: XtreamProvider,
- onProgress: ((String) -> Unit)?
- ): CatalogSyncPayload<Movie> = xtreamMovieStrategy.loadXtreamMoviesByPage(provider, api, onProgress)
-
- private suspend fun syncXtreamSeriesCatalog(
- provider: Provider,
- api: XtreamProvider,
- existingMetadata: SyncMetadata,
- onProgress: ((String) -> Unit)?
- ): CatalogSyncPayload<Series> =
- xtreamSeriesStrategy.syncXtreamSeriesCatalog(provider, api, existingMetadata, onProgress)
-
- private suspend fun loadXtreamSeriesFull(
- provider: Provider,
- api: XtreamProvider
- ): CatalogSyncPayload<Series> = xtreamSeriesStrategy.loadXtreamSeriesFull(provider, api)
-
- private suspend fun loadXtreamSeriesByCategory(
- provider: Provider,
- api: XtreamProvider,
- rawCategories: List<XtreamCategory>,
- onProgress: ((String) -> Unit)?,
- preferSequential: Boolean
- ): CatalogSyncPayload<Series> =
- xtreamSeriesStrategy.loadXtreamSeriesByCategory(provider, api, rawCategories, onProgress, preferSequential)
-
- private suspend fun loadXtreamSeriesByPage(
- provider: Provider,
- api: XtreamProvider,
- onProgress: ((String) -> Unit)?
- ): CatalogSyncPayload<Series> = xtreamSeriesStrategy.loadXtreamSeriesByPage(provider, api, onProgress)
-
private suspend fun updateSyncStatusMetadata(providerId: Long, status: String) {
val metadata = (syncMetadataRepository.getMetadata(providerId) ?: SyncMetadata(providerId))
.copy(lastSyncStatus = status)
syncMetadataRepository.updateMetadata(metadata)
}
- private suspend fun fetchXtreamVodCategories(provider: Provider): List<XtreamCategory>? =
- xtreamMovieStrategy.fetchXtreamVodCategories(provider)
-
- private fun strategyWarnings(result: CatalogStrategyResult<*>): List<String> =
- catalogStrategySupport.strategyWarnings(result)
-
- private fun <T> shouldDowngradeCategorySync(
- totalCategories: Int,
- failures: Int,
- fastFailures: Int,
- outcomes: List<CategoryFetchOutcome<T>>
- ): Boolean = catalogStrategySupport.shouldDowngradeCategorySync(totalCategories, failures, fastFailures, outcomes)
-
- private fun <T> shouldRetryFailedCategories(
- totalCategories: Int,
- failures: Int,
- downgradeRecommended: Boolean,
- outcomes: List<CategoryFetchOutcome<T>>
- ): Boolean = catalogStrategySupport.shouldRetryFailedCategories(totalCategories, failures, downgradeRecommended, outcomes)
-
- private fun <T> shouldRetryFailedPages(
- totalPages: Int,
- failures: Int,
- outcomes: List<PageFetchOutcome<T>>
- ): Boolean = catalogStrategySupport.shouldRetryFailedPages(totalPages, failures, outcomes)
-
private fun shouldRememberSequentialPreference(error: Throwable): Boolean {
return xtreamAdaptiveSyncPolicy.isProviderStress(error) ||
error is XtreamAuthenticationException ||
@@ -2219,16 +2759,6 @@ class SyncManager @Inject constructor(
}
}
- 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>,
@@ -2247,20 +2777,6 @@ class SyncManager @Inject constructor(
fetch = fetch
)
- private fun <T> evaluatePageRecoveryPlan(
- provider: Provider,
- sectionLabel: String,
- pageWindow: List<Int>,
- outcomes: List<TimedPageOutcome<T>>,
- sequentialModeWarning: String
- ): PageExecutionPlan<T> = xtreamSupport.evaluatePageRecoveryPlan(
- provider = provider,
- sectionLabel = sectionLabel,
- pageWindow = pageWindow,
- outcomes = outcomes,
- sequentialModeWarning = sequentialModeWarning
- )
-
private suspend fun <T> retryTransient(
maxAttempts: Int = 3,
initialDelayMs: Long = 700L,
@@ -2642,24 +3158,6 @@ class SyncManager @Inject constructor(
category: XtreamCategory
): TimedCategoryOutcome<Series> = xtreamFetcher.fetchSeriesCategoryOutcome(provider, api, category)
- private suspend fun fetchMoviePageOutcome(
- provider: Provider,
- api: XtreamProvider,
- page: Int
- ): TimedPageOutcome<Movie> = xtreamFetcher.fetchMoviePageOutcome(provider, api, page)
-
- private suspend fun fetchSeriesPageOutcome(
- provider: Provider,
- api: XtreamProvider,
- page: Int
- ): TimedPageOutcome<Series> = xtreamFetcher.fetchSeriesPageOutcome(provider, api, page)
-
- private suspend fun <T> continueFailedPageOutcomes(
- provider: Provider,
- timedOutcomes: List<TimedPageOutcome<T>>,
- fetchSequentially: suspend (Int) -> TimedPageOutcome<T>
- ): List<TimedPageOutcome<T>> = xtreamSupport.continueFailedPageOutcomes(provider, timedOutcomes, fetchSequentially)
-
private suspend fun <T> continueFailedCategoryOutcomes(
provider: Provider,
timedOutcomes: List<TimedCategoryOutcome<T>>,
diff --git a/data/src/main/java/com/streamvault/data/sync/SyncManagerCatalogStrategySupport.kt b/data/src/main/java/com/streamvault/data/sync/SyncManagerCatalogStrategySupport.kt
index 1b2d012c..87d622b4 100644
--- a/data/src/main/java/com/streamvault/data/sync/SyncManagerCatalogStrategySupport.kt
+++ b/data/src/main/java/com/streamvault/data/sync/SyncManagerCatalogStrategySupport.kt
@@ -54,20 +54,6 @@ internal class SyncManagerCatalogStrategySupport(
return downgradeRecommended || stressFailures > 0 || failures <= minOf(2, totalCategories)
}
- 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)
- }
-
fun updateAvoidFullUntil(
previousAvoidFullUntil: Long,
now: Long,
diff --git a/data/src/main/java/com/streamvault/data/sync/SyncManagerM3uImporter.kt b/data/src/main/java/com/streamvault/data/sync/SyncManagerM3uImporter.kt
index 3b19aee2..20d51429 100644
--- a/data/src/main/java/com/streamvault/data/sync/SyncManagerM3uImporter.kt
+++ b/data/src/main/java/com/streamvault/data/sync/SyncManagerM3uImporter.kt
@@ -1,8 +1,12 @@
package com.streamvault.data.sync
+import android.util.Log
import com.streamvault.data.local.entity.ChannelEntity
import com.streamvault.data.local.entity.MovieEntity
import com.streamvault.data.parser.M3uParser
+import com.streamvault.data.remote.http.HttpRequestProfile
+import com.streamvault.data.remote.http.safeRequestIdentitySummary
+import com.streamvault.data.remote.http.withRequestProfile
import com.streamvault.data.util.AdultContentClassifier
import com.streamvault.data.util.UrlSecurityPolicy
import com.streamvault.domain.model.ContentType
@@ -17,6 +21,7 @@ import java.net.URI
import java.util.zip.GZIPInputStream
private const val M3U_PROGRESS_INTERVAL = 5_000
+private const val M3U_IMPORTER_TAG = "SyncManagerM3u"
internal class SyncManagerM3uImporter(
private val m3uParser: M3uParser,
@@ -202,9 +207,14 @@ internal class SyncManagerM3uImporter(
return
}
+ val requestProfile = HttpRequestProfile(ownerTag = "provider:${provider.id}/m3u")
retryTransient {
- okHttpClient.newCall(Request.Builder().url(urlStr).build()).execute().use { response ->
- ensureSuccessfulPlaylistResponse(response)
+ val request = Request.Builder()
+ .url(urlStr)
+ .build()
+ .withRequestProfile(requestProfile)
+ okHttpClient.newCall(request).execute().use { response ->
+ ensureSuccessfulPlaylistResponse(response, requestProfile)
val body = response.body ?: throw IllegalStateException("Empty M3U response")
body.byteStream().use { input ->
block(
@@ -219,8 +229,12 @@ internal class SyncManagerM3uImporter(
}
}
- private fun ensureSuccessfulPlaylistResponse(response: Response) {
+ private fun ensureSuccessfulPlaylistResponse(response: Response, requestProfile: HttpRequestProfile) {
if (response.isSuccessful) return
+ Log.w(
+ M3U_IMPORTER_TAG,
+ "Playlist request failed (${response.request.safeRequestIdentitySummary(requestProfile)}): HTTP ${response.code}"
+ )
if (response.code in 500..599 || response.code == 429) {
// Transient — the retry wrapper will attempt again automatically.
throw IOException("Transient HTTP ${response.code}")
diff --git a/data/src/main/java/com/streamvault/data/sync/SyncManagerSupport.kt b/data/src/main/java/com/streamvault/data/sync/SyncManagerSupport.kt
index fee4a8bd..3903b3d9 100644
--- a/data/src/main/java/com/streamvault/data/sync/SyncManagerSupport.kt
+++ b/data/src/main/java/com/streamvault/data/sync/SyncManagerSupport.kt
@@ -6,8 +6,6 @@ import com.streamvault.data.parser.M3uParser
import com.streamvault.data.remote.dto.XtreamCategory
import com.streamvault.data.util.AdultContentClassifier
import com.streamvault.domain.model.ContentType
-import com.streamvault.domain.model.Movie
-import com.streamvault.domain.model.VodSyncMode
import java.io.InputStream
import java.security.MessageDigest
@@ -50,16 +48,6 @@ internal data class XtreamStrategyFeedback(
val segmentedStressDetected: Boolean = false
)
-internal data class MovieCatalogSyncResult(
- val catalogResult: CatalogStrategyResult<Movie>,
- val categories: List<CategoryEntity>?,
- val syncMode: VodSyncMode,
- val warnings: List<String> = emptyList(),
- val strategyFeedback: XtreamStrategyFeedback = XtreamStrategyFeedback(),
- val stagedSessionId: Long? = null,
- val stagedAcceptedCount: Int = 0
-)
-
internal data class CatalogSyncPayload<T>(
val catalogResult: CatalogStrategyResult<T>,
val categories: List<CategoryEntity>?,
@@ -85,7 +73,11 @@ internal sealed interface Attempt<out T> {
}
internal sealed interface CategoryFetchOutcome<out T> {
- data class Success<T>(val categoryName: String, val items: List<T>) : CategoryFetchOutcome<T>
+ data class Success<T>(
+ val categoryName: String,
+ val items: List<T>,
+ val rawCount: Int = items.size
+ ) : CategoryFetchOutcome<T>
data class Empty(val categoryName: String) : CategoryFetchOutcome<Nothing>
data class Failure(val categoryName: String, val error: Throwable) : CategoryFetchOutcome<Nothing>
}
@@ -96,29 +88,11 @@ internal data class TimedCategoryOutcome<T>(
val elapsedMs: Long
)
-internal 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>
-}
-
-internal data class TimedPageOutcome<T>(
- val page: Int,
- val outcome: PageFetchOutcome<T>,
- val elapsedMs: Long
-)
-
internal data class CategoryExecutionPlan<T>(
val outcomes: List<TimedCategoryOutcome<T>>,
val warnings: List<String> = emptyList()
)
-internal data class PageExecutionPlan<T>(
- val outcomes: List<TimedPageOutcome<T>>,
- val warnings: List<String> = emptyList(),
- val stoppedEarly: Boolean = false
-)
-
internal data class M3uImportStats(
val header: M3uParser.M3uHeader,
val liveCount: Int,
diff --git a/data/src/main/java/com/streamvault/data/sync/SyncManagerXtreamFetcher.kt b/data/src/main/java/com/streamvault/data/sync/SyncManagerXtreamFetcher.kt
index 9a28143d..6a0e50d0 100644
--- a/data/src/main/java/com/streamvault/data/sync/SyncManagerXtreamFetcher.kt
+++ b/data/src/main/java/com/streamvault/data/sync/SyncManagerXtreamFetcher.kt
@@ -18,8 +18,7 @@ private const val XTREAM_FETCHER_TAG = "SyncManager"
internal class SyncManagerXtreamFetcher(
private val xtreamCatalogApiService: XtreamApiService,
private val xtreamSupport: SyncManagerXtreamSupport,
- private val sanitizeThrowableMessage: (Throwable?) -> String,
- private val pageSize: Int
+ private val sanitizeThrowableMessage: (Throwable?) -> String
) {
suspend fun fetchLiveCategoryOutcome(
provider: Provider,
@@ -68,7 +67,7 @@ internal class SyncManagerXtreamFetcher(
XTREAM_FETCHER_TAG,
"Xtream live category '${category.categoryName}' completed in ${elapsedMs}ms with ${rawStreams.size} raw items."
)
- CategoryFetchOutcome.Success(category.categoryName, api.mapLiveStreamsResponse(rawStreams))
+ CategoryFetchOutcome.Success(category.categoryName, api.mapLiveStreamsResponse(rawStreams), rawStreams.size)
}
}
return TimedCategoryOutcome(category, outcome, elapsedMs)
@@ -123,7 +122,7 @@ internal class SyncManagerXtreamFetcher(
XTREAM_FETCHER_TAG,
"Xtream movie category '${category.categoryName}' completed in ${elapsedMs}ms with ${rawStreams.size} raw items."
)
- CategoryFetchOutcome.Success(category.categoryName, api.mapVodStreamsResponse(rawStreams))
+ CategoryFetchOutcome.Success(category.categoryName, api.mapVodStreamsResponse(rawStreams), rawStreams.size)
}
}
return TimedCategoryOutcome(category, outcome, elapsedMs)
@@ -178,128 +177,10 @@ internal class SyncManagerXtreamFetcher(
XTREAM_FETCHER_TAG,
"Xtream series category '${category.categoryName}' completed in ${elapsedMs}ms with ${rawSeries.size} raw items."
)
- CategoryFetchOutcome.Success(category.categoryName, api.mapSeriesListResponse(rawSeries))
+ CategoryFetchOutcome.Success(category.categoryName, api.mapSeriesListResponse(rawSeries), rawSeries.size)
}
}
return TimedCategoryOutcome(category, outcome, elapsedMs)
}
- 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 = xtreamSupport.attemptNonCancellation {
- xtreamSupport.withMovieRequestTimeout("movie page $page") {
- xtreamSupport.retryXtreamCatalogTransient(provider.id) {
- xtreamSupport.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(
- XTREAM_FETCHER_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(
- XTREAM_FETCHER_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(
- XTREAM_FETCHER_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)
- }
-
- 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 = xtreamSupport.attemptNonCancellation {
- xtreamSupport.withSeriesRequestTimeout("series page $page") {
- xtreamSupport.retryXtreamCatalogTransient(provider.id) {
- xtreamSupport.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(
- XTREAM_FETCHER_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(
- XTREAM_FETCHER_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(
- XTREAM_FETCHER_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 fun paginationParamsForPage(page: Int): Map<String, String> {
- return mapOf(
- "page" to page.toString(),
- "limit" to pageSize.toString(),
- "offset" to ((page - 1) * pageSize).toString(),
- "items_per_page" to pageSize.toString()
- )
- }
}
diff --git a/data/src/main/java/com/streamvault/data/sync/SyncManagerXtreamMovieStrategy.kt b/data/src/main/java/com/streamvault/data/sync/SyncManagerXtreamMovieStrategy.kt
deleted file mode 100644
index eaf07ba1..00000000
--- a/data/src/main/java/com/streamvault/data/sync/SyncManagerXtreamMovieStrategy.kt
+++ /dev/null
@@ -1,764 +0,0 @@
-package com.streamvault.data.sync
-
-import android.util.Log
-import com.streamvault.data.local.entity.CategoryEntity
-import com.streamvault.data.mapper.toEntity
-import com.streamvault.data.remote.dto.XtreamCategory
-import com.streamvault.data.remote.dto.XtreamStream
-import com.streamvault.data.remote.xtream.OkHttpXtreamApiService
-import com.streamvault.data.remote.xtream.XtreamApiService
-import com.streamvault.data.remote.xtream.XtreamProvider
-import com.streamvault.data.remote.xtream.XtreamUrlFactory
-import com.streamvault.domain.model.ContentType
-import com.streamvault.domain.model.Movie
-import com.streamvault.domain.model.Provider
-import com.streamvault.domain.model.SyncMetadata
-import com.streamvault.domain.model.VodSyncMode
-import kotlinx.coroutines.async
-import kotlinx.coroutines.awaitAll
-import kotlinx.coroutines.coroutineScope
-import kotlin.system.measureTimeMillis
-
-private const val XTREAM_MOVIE_STRATEGY_TAG = "SyncManager"
-
-internal class SyncManagerXtreamMovieStrategy(
- private val xtreamCatalogApiService: XtreamApiService,
- private val xtreamCatalogHttpService: OkHttpXtreamApiService,
- private val xtreamAdaptiveSyncPolicy: XtreamAdaptiveSyncPolicy,
- private val xtreamSupport: SyncManagerXtreamSupport,
- private val xtreamFetcher: SyncManagerXtreamFetcher,
- private val catalogStrategySupport: SyncManagerCatalogStrategySupport,
- private val syncCatalogStore: SyncCatalogStore,
- private val progress: (Long, ((String) -> Unit)?, String) -> Unit,
- private val sanitizeThrowableMessage: (Throwable?) -> String,
- private val fullCatalogFallbackWarning: (String, Throwable?) -> String,
- private val categoryFailureWarning: (String, String, Throwable) -> String,
- private val pagingFailureWarning: (String, Int, Throwable) -> String,
- private val stageMovieItems: suspend (Long, List<Movie>, MutableSet<Long>, FallbackCategoryCollector, Long?) -> StagedCatalogSnapshot,
- private val stageMovieSequence: suspend (Long, Sequence<Movie>, MutableSet<Long>, FallbackCategoryCollector, Long?) -> StagedCatalogSnapshot,
- private val movieCategorySequentialModeWarning: String,
- private val moviePagedSequentialModeWarning: String,
- private val fallbackStageBatchSize: Int,
- private val maxCatalogPages: Int,
- private val pageSize: Int
-) {
- suspend fun syncXtreamMoviesCatalog(
- provider: Provider,
- api: XtreamProvider,
- existingMetadata: SyncMetadata,
- onProgress: ((String) -> Unit)?
- ): MovieCatalogSyncResult {
- Log.i(
- XTREAM_MOVIE_STRATEGY_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() }
-
- 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
- )
-
- if (provider.xtreamFastSyncEnabled) {
- return if (!resolvedCategories.isNullOrEmpty()) {
- Log.i(
- XTREAM_MOVIE_STRATEGY_TAG,
- "Xtream movies fast sync: returning LAZY_BY_CATEGORY for provider ${provider.id} with ${resolvedCategories.size} categories."
- )
- MovieCatalogSyncResult(
- catalogResult = CatalogStrategyResult.Failure(
- strategyName = "fast_sync",
- error = IllegalStateException("Fast sync enabled; movies will hydrate on demand"),
- warnings = emptyList()
- ),
- categories = resolvedCategories,
- syncMode = VodSyncMode.LAZY_BY_CATEGORY,
- warnings = emptyList(),
- strategyFeedback = XtreamStrategyFeedback(preferredSegmentedFirst = false)
- )
- } else {
- Log.w(
- XTREAM_MOVIE_STRATEGY_TAG,
- "Xtream movies fast sync: no categories available for provider ${provider.id}, falling through to standard strategies."
- )
- MovieCatalogSyncResult(
- catalogResult = CatalogStrategyResult.Failure(
- strategyName = "fast_sync_no_categories",
- error = IllegalStateException("Fast sync enabled but no categories available"),
- warnings = listOf("Fast sync enabled but no categories returned from server.")
- ),
- categories = null,
- syncMode = VodSyncMode.UNKNOWN,
- warnings = listOf("Fast sync enabled but no categories returned from server."),
- strategyFeedback = XtreamStrategyFeedback(preferredSegmentedFirst = false)
- )
- }
- }
-
- 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 = catalogStrategySupport.mergePreferredAndFallbackCategories(resolvedCategories, fullPayload.categories),
- syncMode = VodSyncMode.FULL,
- warnings = emptyList(),
- strategyFeedback = XtreamStrategyFeedback(
- preferredSegmentedFirst = false,
- attemptedFullCatalog = true,
- fullCatalogUnsafe = false
- ),
- stagedSessionId = fullPayload.stagedSessionId,
- stagedAcceptedCount = fullPayload.stagedAcceptedCount
- ).also {
- Log.i(
- XTREAM_MOVIE_STRATEGY_TAG,
- "Xtream movies strategy selected FULL for provider ${provider.id} with ${fullPayload.stagedAcceptedCount} items."
- )
- }
- is CatalogStrategyResult.Partial -> return MovieCatalogSyncResult(
- catalogResult = fullResult,
- categories = catalogStrategySupport.mergePreferredAndFallbackCategories(resolvedCategories, fullPayload.categories),
- syncMode = VodSyncMode.FULL,
- warnings = emptyList(),
- strategyFeedback = XtreamStrategyFeedback(
- preferredSegmentedFirst = false,
- attemptedFullCatalog = true,
- fullCatalogUnsafe = false
- ),
- stagedSessionId = fullPayload.stagedSessionId,
- stagedAcceptedCount = fullPayload.stagedAcceptedCount
- ).also {
- Log.w(
- XTREAM_MOVIE_STRATEGY_TAG,
- "Xtream movies strategy selected FULL(partial) for provider ${provider.id} with ${fullPayload.stagedAcceptedCount} items."
- )
- }
- else -> Unit
- }
-
- if (!resolvedCategories.isNullOrEmpty()) {
- progress(provider.id, onProgress, "Preparing Movies category sync...")
- categoryPayload = loadXtreamMoviesByCategory(
- provider = provider,
- api = api,
- rawCategories = rawVodCategories.orEmpty(),
- onProgress = onProgress,
- preferSequential = existingMetadata.movieParallelFailuresRemembered
- )
- }
- when (val categoryResult = categoryPayload.catalogResult) {
- is CatalogStrategyResult.Success -> return buildCategoryResult(
- provider = provider,
- resolvedCategories = resolvedCategories,
- categoryPayload = categoryPayload,
- fullPayload = fullPayload,
- pagedPayload = pagedPayload,
- categoryResult = categoryResult,
- partial = false
- )
- is CatalogStrategyResult.Partial -> return buildCategoryResult(
- provider = provider,
- resolvedCategories = resolvedCategories,
- categoryPayload = categoryPayload,
- fullPayload = fullPayload,
- pagedPayload = pagedPayload,
- categoryResult = categoryResult,
- partial = true
- )
- else -> Unit
- }
-
- 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 buildPagedResult(
- provider = provider,
- pagedPayload = pagedPayload,
- fullPayload = fullPayload,
- categoryPayload = categoryPayload,
- pagedResult = pagedResult,
- partial = false
- )
- is CatalogStrategyResult.Partial -> return buildPagedResult(
- provider = provider,
- pagedPayload = pagedPayload,
- fullPayload = fullPayload,
- categoryPayload = categoryPayload,
- pagedResult = pagedResult,
- partial = true
- )
- else -> Unit
- }
- }
-
- 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 = catalogStrategySupport.mergePreferredAndFallbackCategories(resolvedCategories, fullPayload.categories),
- syncMode = VodSyncMode.FULL,
- warnings = catalogStrategySupport.strategyWarnings(categoryPayload.catalogResult) +
- catalogStrategySupport.strategyWarnings(pagedPayload.catalogResult),
- strategyFeedback = XtreamStrategyFeedback(
- preferredSegmentedFirst = true,
- attemptedFullCatalog = true,
- fullCatalogUnsafe = false
- ),
- stagedSessionId = fullPayload.stagedSessionId,
- stagedAcceptedCount = fullPayload.stagedAcceptedCount
- ).also {
- val itemCount = fullPayload.stagedAcceptedCount.takeIf { it > 0 } ?: fullResult.items.size
- Log.i(XTREAM_MOVIE_STRATEGY_TAG, "Xtream movies strategy selected FULL for provider ${provider.id} with $itemCount items.")
- }
- else -> Unit
- }
-
- val lazyWarnings = buildList {
- addAll(catalogStrategySupport.strategyWarnings(categoryPayload.catalogResult))
- addAll(catalogStrategySupport.strategyWarnings(fullPayload.catalogResult))
- if (!resolvedCategories.isNullOrEmpty()) {
- add("Movies entered lazy category-only mode after category-bulk and full strategies failed.")
- } else {
- addAll(catalogStrategySupport.strategyWarnings(pagedPayload.catalogResult))
- add("Movies entered lazy category-only mode after category-bulk, paged, and full strategies failed.")
- }
- }
- Log.w(
- XTREAM_MOVIE_STRATEGY_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,
- strategyFeedback = XtreamStrategyFeedback(
- preferredSegmentedFirst = true,
- attemptedFullCatalog = true,
- segmentedStressDetected = true
- )
- )
- } 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,
- strategyFeedback = XtreamStrategyFeedback(
- preferredSegmentedFirst = true,
- attemptedFullCatalog = true,
- segmentedStressDetected = true
- )
- )
- }
- }
-
- suspend fun loadXtreamMoviesFull(
- provider: Provider,
- api: XtreamProvider
- ): CatalogSyncPayload<Movie> {
- val fallbackCollector = FallbackCategoryCollector(provider.id, ContentType.MOVIE)
- val seenStreamIds = HashSet<Long>()
- val rawBatch = ArrayList<XtreamStream>(fallbackStageBatchSize)
- var stagedSessionId: Long? = null
- var acceptedCount = 0
- var streamedRawCount = 0
- var fullMoviesFailure: Throwable? = null
-
- suspend fun flushRawBatch() {
- if (rawBatch.isEmpty()) return
- val staged = stageMovieSequence(
- provider.id,
- api.mapVodStreamsSequence(rawBatch.asSequence()),
- seenStreamIds,
- fallbackCollector,
- stagedSessionId
- )
- stagedSessionId = staged.sessionId
- acceptedCount += staged.acceptedCount
- rawBatch.clear()
- }
-
- val fullMoviesElapsedMs = measureTimeMillis {
- when (val attempt = xtreamSupport.attemptNonCancellation {
- xtreamSupport.withMovieRequestTimeout("full movie catalog") {
- xtreamSupport.retryXtreamCatalogTransient(provider.id) {
- xtreamSupport.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 >= fallbackStageBatchSize) {
- flushRawBatch()
- }
- }.also {
- flushRawBatch()
- }
- }
- }
- }
- }) {
- is Attempt.Success -> Unit
- is Attempt.Failure -> {
- fullMoviesFailure = attempt.error
- stagedSessionId?.let { sessionId ->
- syncCatalogStore.discardStagedImport(provider.id, sessionId)
- stagedSessionId = null
- }
- }
- }
- }
- if (streamedRawCount > 0) {
- Log.i(
- XTREAM_MOVIE_STRATEGY_TAG,
- "Xtream movies full catalog succeeded for provider ${provider.id} in ${fullMoviesElapsedMs}ms with $acceptedCount accepted items from $streamedRawCount raw items."
- )
- 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) {
- xtreamSupport.logXtreamCatalogFallback(
- provider = provider,
- section = "movies",
- stage = "full catalog",
- elapsedMs = fullMoviesElapsedMs,
- itemCount = streamedRawCount,
- error = fullMoviesFailure,
- nextStep = "category-bulk"
- )
- CatalogSyncPayload(
- catalogResult = CatalogStrategyResult.Failure(
- strategyName = "full",
- error = fullMoviesFailure!!,
- warnings = listOf(fullCatalogFallbackWarning("Movies", fullMoviesFailure))
- ),
- categories = null
- )
- } else {
- xtreamSupport.logXtreamCatalogFallback(
- provider = provider,
- section = "movies",
- stage = "full catalog",
- elapsedMs = fullMoviesElapsedMs,
- itemCount = streamedRawCount,
- error = null,
- nextStep = "category-bulk"
- )
- CatalogSyncPayload(
- catalogResult = CatalogStrategyResult.EmptyValid(
- strategyName = "full",
- warnings = listOf("Movies full catalog returned an empty valid result.")
- ),
- categories = null
- )
- }
- }
-
- suspend fun loadXtreamMoviesByCategory(
- provider: Provider,
- api: XtreamProvider,
- rawCategories: List<XtreamCategory>,
- onProgress: ((String) -> Unit)?,
- preferSequential: Boolean
- ): CatalogSyncPayload<Movie> {
- val categories = rawCategories.filter { it.categoryId.isNotBlank() }
- if (categories.isEmpty()) {
- 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 = 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 executionPlan = xtreamSupport.executeCategoryRecoveryPlan(
- provider = provider,
- categories = categories,
- initialConcurrency = concurrency,
- sectionLabel = "Movies",
- sequentialModeWarning = movieCategorySequentialModeWarning,
- onProgress = onProgress,
- fetch = { category -> xtreamFetcher.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 }
-
- val downgradeRecommended = catalogStrategySupport.shouldDowngradeCategorySync(
- totalCategories = categories.size,
- failures = failureCount,
- fastFailures = fastFailureCount,
- outcomes = categoryOutcomes
- )
- var fallbackWarnings = executionPlan.warnings
- if (concurrency > 1 && catalogStrategySupport.shouldRetryFailedCategories(
- categories.size,
- failureCount,
- downgradeRecommended,
- categoryOutcomes
- )
- ) {
- Log.w(
- XTREAM_MOVIE_STRATEGY_TAG,
- "Xtream movie category sync is continuing in sequential mode for failed categories on provider ${provider.id}."
- )
- timedOutcomes = xtreamSupport.continueFailedCategoryOutcomes(
- provider = provider,
- timedOutcomes = timedOutcomes,
- fetchSequentially = { category -> xtreamFetcher.fetchMovieCategoryOutcome(provider, api, category) }
- )
- fallbackWarnings = (
- fallbackWarnings +
- if (downgradeRecommended) listOf(movieCategorySequentialModeWarning) else emptyList()
- ).distinct()
- }
-
- 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>>()
- .forEach { success ->
- val staged = stageMovieItems(provider.id, success.items, seenStreamIds, fallbackCollector, 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(
- XTREAM_MOVIE_STRATEGY_TAG,
- "Xtream movie category strategy summary for provider ${provider.id}: successful=$successfulCategories empty=$emptyCategories failed=$failedCategories dedupedMovies=$acceptedCount concurrency=$concurrency"
- )
-
- return when {
- acceptedCount > 0 && failedCategories == 0 -> CatalogSyncPayload(
- catalogResult = CatalogStrategyResult.Success("category_bulk", emptyList(), warnings.toList()),
- categories = fallbackCollector.entities().takeIf { it.isNotEmpty() },
- stagedSessionId = sessionId,
- stagedAcceptedCount = acceptedCount
- )
- 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("Movie category-bulk sync failed for all usable categories"),
- warnings = warnings.toList()
- ),
- categories = null
- )
- else -> CatalogSyncPayload(
- catalogResult = CatalogStrategyResult.EmptyValid(
- strategyName = "category_bulk",
- warnings = listOf("All movie categories returned valid empty results.")
- ),
- categories = null
- )
- }
- }
-
- suspend fun loadXtreamMoviesByPage(
- provider: Provider,
- api: XtreamProvider,
- onProgress: ((String) -> Unit)?
- ): CatalogSyncPayload<Movie> {
- val seenStreamIds = HashSet<Long>()
- val fallbackCollector = FallbackCategoryCollector(provider.id, ContentType.MOVIE)
- val warnings = mutableListOf<String>()
- var sessionId: Long? = null
- var acceptedCount = 0
- var nextPage = 1
- var stopPaging = false
- var forceSequential = false
-
- while (nextPage <= maxCatalogPages && !stopPaging) {
- val remainingPages = maxCatalogPages - 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 <= maxCatalogPages }
- progress(
- provider.id,
- onProgress,
- if (pageWindow.size == 1) {
- "Downloading Movies by page ${pageWindow.first()}..."
- } else {
- "Downloading Movies by page ${pageWindow.first()}-${pageWindow.last()}..."
- }
- )
-
- var timedOutcomes = coroutineScope {
- pageWindow.map { page ->
- async { xtreamFetcher.fetchMoviePageOutcome(provider, api, page) }
- }.awaitAll()
- }
- val failures = timedOutcomes.count { it.outcome is PageFetchOutcome.Failure }
- val recoveryPlan = xtreamSupport.evaluatePageRecoveryPlan(
- provider = provider,
- sectionLabel = "Movies",
- pageWindow = pageWindow,
- outcomes = timedOutcomes,
- sequentialModeWarning = moviePagedSequentialModeWarning
- )
- forceSequential = forceSequential || recoveryPlan.warnings.any { it == moviePagedSequentialModeWarning }
- warnings += recoveryPlan.warnings
- if (recoveryPlan.stoppedEarly) {
- stopPaging = true
- }
- if (!recoveryPlan.stoppedEarly && concurrency > 1 &&
- catalogStrategySupport.shouldRetryFailedPages(pageWindow.size, failures, timedOutcomes.map { it.outcome })
- ) {
- timedOutcomes = xtreamSupport.continueFailedPageOutcomes(
- provider = provider,
- timedOutcomes = timedOutcomes,
- fetchSequentially = { page -> xtreamFetcher.fetchMoviePageOutcome(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 = stageMovieItems(provider.id, outcome.items, seenStreamIds, fallbackCollector, sessionId)
- sessionId = staged.sessionId
- acceptedCount += staged.acceptedCount
- val newItems = staged.acceptedCount
- if (outcome.rawCount < pageSize || 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 (terminalFailure != null) {
- return if (acceptedCount == 0) {
- CatalogSyncPayload(
- catalogResult = CatalogStrategyResult.Failure(
- strategyName = "paged",
- error = terminalFailure!!,
- warnings = listOf(pagingFailureWarning("Movies", terminalFailurePage ?: nextPage, terminalFailure!!))
- ),
- categories = null
- )
- } else {
- CatalogSyncPayload(
- catalogResult = CatalogStrategyResult.Partial(
- strategyName = "paged",
- items = emptyList(),
- warnings = warnings.toList()
- ),
- categories = fallbackCollector.entities().takeIf { it.isNotEmpty() },
- stagedSessionId = sessionId,
- stagedAcceptedCount = acceptedCount
- )
- }
- }
-
- nextPage = pageWindow.last() + 1
- }
-
- return if (acceptedCount > 0) {
- Log.i(
- XTREAM_MOVIE_STRATEGY_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
- )
- }
- }
-
- suspend fun fetchXtreamVodCategories(provider: Provider): List<XtreamCategory>? {
- return when (val attempt = xtreamSupport.attemptNonCancellation {
- xtreamSupport.withMovieRequestTimeout("movie categories") {
- xtreamSupport.retryXtreamCatalogTransient(provider.id) {
- xtreamSupport.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(
- XTREAM_MOVIE_STRATEGY_TAG,
- "Xtream VOD categories request failed for provider ${provider.id}: ${sanitizeThrowableMessage(attempt.error)}"
- )
- null
- }
- }
- }
-
- private fun buildCategoryResult(
- provider: Provider,
- resolvedCategories: List<CategoryEntity>?,
- categoryPayload: CatalogSyncPayload<Movie>,
- fullPayload: CatalogSyncPayload<Movie>,
- pagedPayload: CatalogSyncPayload<Movie>,
- categoryResult: CatalogStrategyResult<Movie>,
- partial: Boolean
- ): MovieCatalogSyncResult {
- val warnings = catalogStrategySupport.strategyWarnings(fullPayload.catalogResult) +
- catalogStrategySupport.strategyWarnings(pagedPayload.catalogResult)
- return MovieCatalogSyncResult(
- catalogResult = categoryResult,
- categories = catalogStrategySupport.mergePreferredAndFallbackCategories(resolvedCategories, categoryPayload.categories),
- syncMode = VodSyncMode.CATEGORY_BULK,
- warnings = warnings,
- strategyFeedback = XtreamStrategyFeedback(
- preferredSegmentedFirst = true,
- segmentedStressDetected = catalogStrategySupport.sawSegmentedStress(
- warnings = warnings,
- result = categoryResult,
- sequentialWarnings = setOf(movieCategorySequentialModeWarning, moviePagedSequentialModeWarning)
- )
- ),
- stagedSessionId = categoryPayload.stagedSessionId,
- stagedAcceptedCount = categoryPayload.stagedAcceptedCount
- ).also {
- Log.println(
- if (partial) Log.WARN else Log.INFO,
- XTREAM_MOVIE_STRATEGY_TAG,
- "Xtream movies strategy selected CATEGORY_BULK${if (partial) "(partial)" else ""} for provider ${provider.id} with ${categoryPayload.stagedAcceptedCount} items."
- )
- }
- }
-
- private fun buildPagedResult(
- provider: Provider,
- pagedPayload: CatalogSyncPayload<Movie>,
- fullPayload: CatalogSyncPayload<Movie>,
- categoryPayload: CatalogSyncPayload<Movie>,
- pagedResult: CatalogStrategyResult<Movie>,
- partial: Boolean
- ): MovieCatalogSyncResult {
- val warnings = catalogStrategySupport.strategyWarnings(fullPayload.catalogResult) +
- catalogStrategySupport.strategyWarnings(categoryPayload.catalogResult)
- return MovieCatalogSyncResult(
- catalogResult = pagedResult,
- categories = pagedPayload.categories,
- syncMode = VodSyncMode.PAGED,
- warnings = warnings,
- strategyFeedback = XtreamStrategyFeedback(
- preferredSegmentedFirst = true,
- segmentedStressDetected = catalogStrategySupport.sawSegmentedStress(
- warnings = warnings,
- result = pagedResult,
- sequentialWarnings = setOf(moviePagedSequentialModeWarning, movieCategorySequentialModeWarning)
- )
- ),
- stagedSessionId = pagedPayload.stagedSessionId,
- stagedAcceptedCount = pagedPayload.stagedAcceptedCount
- ).also {
- Log.println(
- if (partial) Log.WARN else Log.INFO,
- XTREAM_MOVIE_STRATEGY_TAG,
- "Xtream movies strategy selected PAGED${if (partial) "(partial)" else ""} for provider ${provider.id} with ${pagedPayload.stagedAcceptedCount} items."
- )
- }
- }
-}
diff --git a/data/src/main/java/com/streamvault/data/sync/SyncManagerXtreamSeriesStrategy.kt b/data/src/main/java/com/streamvault/data/sync/SyncManagerXtreamSeriesStrategy.kt
deleted file mode 100644
index 1c8d544e..00000000
--- a/data/src/main/java/com/streamvault/data/sync/SyncManagerXtreamSeriesStrategy.kt
+++ /dev/null
@@ -1,536 +0,0 @@
-package com.streamvault.data.sync
-
-import android.util.Log
-import com.streamvault.data.local.entity.CategoryEntity
-import com.streamvault.data.mapper.toEntity
-import com.streamvault.data.remote.dto.XtreamCategory
-import com.streamvault.data.remote.dto.XtreamSeriesItem
-import com.streamvault.data.remote.xtream.OkHttpXtreamApiService
-import com.streamvault.data.remote.xtream.XtreamApiService
-import com.streamvault.data.remote.xtream.XtreamProvider
-import com.streamvault.data.remote.xtream.XtreamUrlFactory
-import com.streamvault.domain.model.ContentType
-import com.streamvault.domain.model.Provider
-import com.streamvault.domain.model.Series
-import com.streamvault.domain.model.SyncMetadata
-import kotlinx.coroutines.async
-import kotlinx.coroutines.awaitAll
-import kotlinx.coroutines.coroutineScope
-import kotlin.system.measureTimeMillis
-
-private const val XTREAM_SERIES_STRATEGY_TAG = "SyncManager"
-
-internal class SyncManagerXtreamSeriesStrategy(
- private val xtreamCatalogApiService: XtreamApiService,
- private val xtreamCatalogHttpService: OkHttpXtreamApiService,
- private val xtreamAdaptiveSyncPolicy: XtreamAdaptiveSyncPolicy,
- private val xtreamSupport: SyncManagerXtreamSupport,
- private val xtreamFetcher: SyncManagerXtreamFetcher,
- private val catalogStrategySupport: SyncManagerCatalogStrategySupport,
- private val syncCatalogStore: SyncCatalogStore,
- private val progress: (Long, ((String) -> Unit)?, String) -> Unit,
- private val sanitizeThrowableMessage: (Throwable?) -> String,
- private val fullCatalogFallbackWarning: (String, Throwable?) -> String,
- private val categoryFailureWarning: (String, String, Throwable) -> String,
- private val pagingFailureWarning: (String, Int, Throwable) -> String,
- private val stageSeriesItems: suspend (Long, List<Series>, MutableSet<Long>, FallbackCategoryCollector, Long?) -> StagedCatalogSnapshot,
- private val stageSeriesSequence: suspend (Long, Sequence<Series>, MutableSet<Long>, FallbackCategoryCollector, Long?) -> StagedCatalogSnapshot,
- private val categorySequentialModeWarning: String,
- private val pagedSequentialModeWarning: String,
- private val fallbackStageBatchSize: Int,
- private val maxCatalogPages: Int,
- private val pageSize: Int
-) {
- suspend fun syncXtreamSeriesCatalog(
- provider: Provider,
- api: XtreamProvider,
- existingMetadata: SyncMetadata,
- onProgress: ((String) -> Unit)?
- ): CatalogSyncPayload<Series> {
- Log.i(XTREAM_SERIES_STRATEGY_TAG, "Xtream series strategy start for provider ${provider.id}.")
- val rawSeriesCategories = when (val attempt = xtreamSupport.attemptNonCancellation {
- xtreamSupport.withSeriesRequestTimeout("series categories") {
- xtreamSupport.retryXtreamCatalogTransient(provider.id) {
- xtreamSupport.executeXtreamRequest(provider.id, XtreamAdaptiveSyncPolicy.Stage.LIGHTWEIGHT) {
- xtreamCatalogApiService.getSeriesCategories(
- XtreamUrlFactory.buildPlayerApiUrl(
- serverUrl = provider.serverUrl,
- username = provider.username,
- password = provider.password,
- action = "get_series_categories"
- )
- )
- }
- }
- }
- }) {
- is Attempt.Success -> attempt.value
- is Attempt.Failure -> {
- Log.w(
- XTREAM_SERIES_STRATEGY_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>(CatalogStrategyResult.EmptyValid("full"), null)
- var pagedPayload = CatalogSyncPayload<Series>(CatalogStrategyResult.EmptyValid("paged"), null)
- var categoryPayload = CatalogSyncPayload<Series>(CatalogStrategyResult.EmptyValid("category_bulk"), null)
-
- if (provider.xtreamFastSyncEnabled) {
- return if (!resolvedCategories.isNullOrEmpty()) {
- Log.i(
- XTREAM_SERIES_STRATEGY_TAG,
- "Xtream series fast sync: returning lazy_by_category for provider ${provider.id} with ${resolvedCategories.size} categories."
- )
- CatalogSyncPayload(
- catalogResult = CatalogStrategyResult.Failure(
- strategyName = "lazy_by_category",
- error = IllegalStateException("Fast sync enabled; series will hydrate on demand"),
- warnings = emptyList()
- ),
- categories = resolvedCategories,
- warnings = emptyList(),
- strategyFeedback = XtreamStrategyFeedback(preferredSegmentedFirst = false)
- )
- } else {
- Log.w(XTREAM_SERIES_STRATEGY_TAG, "Xtream series fast sync: no categories available for provider ${provider.id}.")
- CatalogSyncPayload(
- catalogResult = CatalogStrategyResult.Failure(
- strategyName = "fast_sync_no_categories",
- error = IllegalStateException("Fast sync enabled but no series categories available"),
- warnings = listOf("Fast sync enabled but no series categories returned from server.")
- ),
- categories = null,
- warnings = listOf("Fast sync enabled but no series categories returned from server."),
- strategyFeedback = XtreamStrategyFeedback(preferredSegmentedFirst = false)
- )
- }
- }
-
- 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 = catalogStrategySupport.mergePreferredAndFallbackCategories(resolvedCategories, categoryPayload.categories),
- warnings = catalogStrategySupport.strategyWarnings(fullPayload.catalogResult),
- strategyFeedback = XtreamStrategyFeedback(
- preferredSegmentedFirst = true,
- segmentedStressDetected = catalogStrategySupport.sawSegmentedStress(
- warnings = catalogStrategySupport.strategyWarnings(fullPayload.catalogResult),
- result = categoryResult,
- sequentialWarnings = setOf(categorySequentialModeWarning)
- )
- ),
- stagedSessionId = categoryPayload.stagedSessionId,
- stagedAcceptedCount = categoryPayload.stagedAcceptedCount
- )
- else -> Unit
- }
- }
-
- if (resolvedCategories.isNullOrEmpty()) {
- 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 = pagedResult,
- categories = pagedPayload.categories,
- warnings = catalogStrategySupport.strategyWarnings(fullPayload.catalogResult) +
- catalogStrategySupport.strategyWarnings(categoryPayload.catalogResult),
- strategyFeedback = XtreamStrategyFeedback(
- preferredSegmentedFirst = true,
- segmentedStressDetected = catalogStrategySupport.sawSegmentedStress(
- warnings = catalogStrategySupport.strategyWarnings(fullPayload.catalogResult) +
- catalogStrategySupport.strategyWarnings(categoryPayload.catalogResult),
- result = pagedResult,
- sequentialWarnings = setOf(pagedSequentialModeWarning, categorySequentialModeWarning)
- )
- ),
- stagedSessionId = pagedPayload.stagedSessionId,
- stagedAcceptedCount = pagedPayload.stagedAcceptedCount
- )
- else -> Unit
- }
-
- 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 = categoryPayload.categories,
- warnings = catalogStrategySupport.strategyWarnings(fullPayload.catalogResult) +
- catalogStrategySupport.strategyWarnings(pagedPayload.catalogResult),
- strategyFeedback = XtreamStrategyFeedback(
- preferredSegmentedFirst = true,
- segmentedStressDetected = catalogStrategySupport.sawSegmentedStress(
- warnings = catalogStrategySupport.strategyWarnings(fullPayload.catalogResult) +
- catalogStrategySupport.strategyWarnings(pagedPayload.catalogResult),
- result = categoryResult,
- sequentialWarnings = setOf(categorySequentialModeWarning, pagedSequentialModeWarning)
- )
- ),
- 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 = catalogStrategySupport.strategyWarnings(categoryPayload.catalogResult) +
- catalogStrategySupport.strategyWarnings(pagedPayload.catalogResult),
- strategyFeedback = XtreamStrategyFeedback(
- preferredSegmentedFirst = true,
- attemptedFullCatalog = true,
- fullCatalogUnsafe = false
- ),
- stagedSessionId = fullPayload.stagedSessionId,
- stagedAcceptedCount = fullPayload.stagedAcceptedCount
- )
- else -> Unit
- }
-
- val lazyWarnings = buildList {
- addAll(catalogStrategySupport.strategyWarnings(categoryPayload.catalogResult))
- addAll(catalogStrategySupport.strategyWarnings(fullPayload.catalogResult))
- if (!resolvedCategories.isNullOrEmpty()) {
- add("Series entered lazy category-only mode after category-bulk and full strategies failed.")
- } else {
- addAll(catalogStrategySupport.strategyWarnings(pagedPayload.catalogResult))
- add("Series entered lazy category-only mode after category-bulk, paged, and full strategies failed.")
- }
- }
- Log.w(
- XTREAM_SERIES_STRATEGY_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
- )
- )
- }
- }
-
- suspend fun loadXtreamSeriesFull(provider: Provider, api: XtreamProvider): CatalogSyncPayload<Series> {
- val fallbackCollector = FallbackCategoryCollector(provider.id, ContentType.SERIES)
- val seenSeriesIds = HashSet<Long>()
- val rawBatch = ArrayList<XtreamSeriesItem>(fallbackStageBatchSize)
- var stagedSessionId: Long? = null
- var acceptedCount = 0
- var streamedRawCount = 0
- var fullSeriesFailure: Throwable? = null
-
- suspend fun flushRawBatch() {
- if (rawBatch.isEmpty()) return
- val staged = stageSeriesSequence(provider.id, api.mapSeriesListSequence(rawBatch.asSequence()), seenSeriesIds, fallbackCollector, stagedSessionId)
- stagedSessionId = staged.sessionId
- acceptedCount += staged.acceptedCount
- rawBatch.clear()
- }
-
- val fullSeriesElapsedMs = measureTimeMillis {
- when (val attempt = xtreamSupport.attemptNonCancellation {
- xtreamSupport.withSeriesRequestTimeout("full series catalog") {
- xtreamSupport.retryXtreamCatalogTransient(provider.id) {
- xtreamSupport.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 >= fallbackStageBatchSize) flushRawBatch()
- }.also { flushRawBatch() }
- }
- }
- }
- }) {
- is Attempt.Success -> Unit
- is Attempt.Failure -> {
- fullSeriesFailure = attempt.error
- stagedSessionId?.let { syncCatalogStore.discardStagedImport(provider.id, it) }
- stagedSessionId = null
- }
- }
- }
- if (streamedRawCount > 0) {
- Log.i(
- XTREAM_SERIES_STRATEGY_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) {
- xtreamSupport.logXtreamCatalogFallback(provider, "series", "full catalog", fullSeriesElapsedMs, streamedRawCount, fullSeriesFailure, "category-bulk")
- CatalogSyncPayload(
- catalogResult = CatalogStrategyResult.Failure(
- strategyName = "full",
- error = fullSeriesFailure!!,
- warnings = listOf(fullCatalogFallbackWarning("Series", fullSeriesFailure))
- ),
- categories = null
- )
- } else {
- xtreamSupport.logXtreamCatalogFallback(provider, "series", "full catalog", fullSeriesElapsedMs, streamedRawCount, null, "category-bulk")
- CatalogSyncPayload(
- catalogResult = CatalogStrategyResult.EmptyValid(
- strategyName = "full",
- warnings = listOf("Series full catalog returned an empty valid result.")
- ),
- categories = null
- )
- }
- }
-
- suspend fun loadXtreamSeriesByCategory(
- provider: Provider,
- api: XtreamProvider,
- rawCategories: List<XtreamCategory>,
- onProgress: ((String) -> Unit)?,
- preferSequential: Boolean
- ): CatalogSyncPayload<Series> {
- val categories = rawCategories.filter { it.categoryId.isNotBlank() }
- if (categories.isEmpty()) {
- 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 = xtreamAdaptiveSyncPolicy.concurrencyFor(provider.id, categories.size, preferSequential, XtreamAdaptiveSyncPolicy.Stage.CATEGORY)
- progress(provider.id, onProgress, "Downloading Series by category 0/${categories.size}...")
- val executionPlan = xtreamSupport.executeCategoryRecoveryPlan(
- provider = provider,
- categories = categories,
- initialConcurrency = concurrency,
- sectionLabel = "Series",
- sequentialModeWarning = categorySequentialModeWarning,
- onProgress = onProgress,
- fetch = { category -> xtreamFetcher.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 }
- val downgradeRecommended = catalogStrategySupport.shouldDowngradeCategorySync(categories.size, failureCount, fastFailureCount, categoryOutcomes)
- var fallbackWarnings = executionPlan.warnings
- if (concurrency > 1 && catalogStrategySupport.shouldRetryFailedCategories(categories.size, failureCount, downgradeRecommended, categoryOutcomes)) {
- Log.w(XTREAM_SERIES_STRATEGY_TAG, "Xtream series category sync is continuing in sequential mode for failed categories on provider ${provider.id}.")
- timedOutcomes = xtreamSupport.continueFailedCategoryOutcomes(
- provider = provider,
- timedOutcomes = timedOutcomes,
- fetchSequentially = { category -> xtreamFetcher.fetchSeriesCategoryOutcome(provider, api, category) }
- )
- fallbackWarnings = (fallbackWarnings + if (downgradeRecommended) listOf(categorySequentialModeWarning) else emptyList()).distinct()
- }
- 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>>().forEach { success ->
- val staged = stageSeriesItems(provider.id, success.items, seenSeriesIds, fallbackCollector, 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(
- XTREAM_SERIES_STRATEGY_TAG,
- "Xtream series category strategy summary for provider ${provider.id}: successful=$successfulCategories empty=$emptyCategories failed=$failedCategories dedupedSeries=$acceptedCount concurrency=$concurrency"
- )
- return when {
- acceptedCount > 0 && failedCategories == 0 -> CatalogSyncPayload(
- catalogResult = CatalogStrategyResult.Success("category_bulk", emptyList(), warnings.toList()),
- categories = fallbackCollector.entities().takeIf { it.isNotEmpty() },
- stagedSessionId = sessionId,
- stagedAcceptedCount = acceptedCount
- )
- 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
- )
- }
- }
-
- suspend fun loadXtreamSeriesByPage(
- provider: Provider,
- api: XtreamProvider,
- onProgress: ((String) -> Unit)?
- ): CatalogSyncPayload<Series> {
- val seenSeriesIds = HashSet<Long>()
- val fallbackCollector = FallbackCategoryCollector(provider.id, ContentType.SERIES)
- val warnings = mutableListOf<String>()
- var sessionId: Long? = null
- var acceptedCount = 0
- var nextPage = 1
- var stopPaging = false
- var forceSequential = false
- while (nextPage <= maxCatalogPages && !stopPaging) {
- val remainingPages = maxCatalogPages - nextPage + 1
- val concurrency = xtreamAdaptiveSyncPolicy.concurrencyFor(provider.id, remainingPages, forceSequential, XtreamAdaptiveSyncPolicy.Stage.PAGED)
- val pageWindow = (nextPage until (nextPage + concurrency)).takeWhile { it <= maxCatalogPages }
- 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 { xtreamFetcher.fetchSeriesPageOutcome(provider, api, page) } }.awaitAll() }
- val failures = timedOutcomes.count { it.outcome is PageFetchOutcome.Failure }
- val recoveryPlan = xtreamSupport.evaluatePageRecoveryPlan(provider, "Series", pageWindow, timedOutcomes, pagedSequentialModeWarning)
- forceSequential = forceSequential || recoveryPlan.warnings.any { it == pagedSequentialModeWarning }
- warnings += recoveryPlan.warnings
- if (recoveryPlan.stoppedEarly) stopPaging = true
- if (!recoveryPlan.stoppedEarly && concurrency > 1 && catalogStrategySupport.shouldRetryFailedPages(pageWindow.size, failures, timedOutcomes.map { it.outcome })) {
- timedOutcomes = xtreamSupport.continueFailedPageOutcomes(provider, timedOutcomes) { page ->
- xtreamFetcher.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(provider.id, outcome.items, seenSeriesIds, fallbackCollector, sessionId)
- sessionId = staged.sessionId
- acceptedCount += staged.acceptedCount
- if (outcome.rawCount < pageSize || staged.acceptedCount == 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
- }
- }
- }
- }
- 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 {
- CatalogSyncPayload(
- catalogResult = CatalogStrategyResult.Partial("paged", emptyList(), warnings.toList()),
- categories = fallbackCollector.entities().takeIf { it.isNotEmpty() },
- stagedSessionId = sessionId,
- stagedAcceptedCount = acceptedCount
- )
- }
- }
- nextPage = pageWindow.last() + 1
- }
- 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
- )
- }
- }
-}
diff --git a/data/src/main/java/com/streamvault/data/sync/SyncManagerXtreamSupport.kt b/data/src/main/java/com/streamvault/data/sync/SyncManagerXtreamSupport.kt
index 1e23930a..f7821e2d 100644
--- a/data/src/main/java/com/streamvault/data/sync/SyncManagerXtreamSupport.kt
+++ b/data/src/main/java/com/streamvault/data/sync/SyncManagerXtreamSupport.kt
@@ -97,42 +97,6 @@ internal class SyncManagerXtreamSupport(
return CategoryExecutionPlan(outcomes = outcomes, warnings = warnings.distinct())
}
- 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(
- XTREAM_SUPPORT_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 $recoveryAbortWarningSuffix"
- Log.w(
- XTREAM_SUPPORT_TAG,
- "Xtream $sectionLabel paged sync stopped early for provider ${provider.id} after repeated stress failures in window ${pageWindow.first()}-${pageWindow.last()}."
- )
- }
- return PageExecutionPlan(outcomes = outcomes, warnings = warnings.distinct(), stoppedEarly = stoppedEarly)
- }
-
suspend fun <T> retryTransient(
maxAttempts: Int = 3,
initialDelayMs: Long = 700L,
@@ -254,31 +218,6 @@ internal class SyncManagerXtreamSupport(
)
}
- 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(
- XTREAM_SUPPORT_TAG,
- "Xtream continuation fallback kept ${timedOutcomes.size - failedPages.size} successful page results for provider ${provider.id} and retried only ${failedPages.size} failed pages."
- )
- }
- }
-
suspend fun <T> continueFailedCategoryOutcomes(
provider: Provider,
timedOutcomes: List<TimedCategoryOutcome<T>>,
diff --git a/data/src/main/java/com/streamvault/data/sync/XtreamAdaptiveSyncPolicy.kt b/data/src/main/java/com/streamvault/data/sync/XtreamAdaptiveSyncPolicy.kt
index 0972d40a..dab9c298 100644
--- a/data/src/main/java/com/streamvault/data/sync/XtreamAdaptiveSyncPolicy.kt
+++ b/data/src/main/java/com/streamvault/data/sync/XtreamAdaptiveSyncPolicy.kt
@@ -17,7 +17,6 @@ internal class XtreamAdaptiveSyncPolicy {
enum class Stage(val timeoutMs: Long?) {
LIGHTWEIGHT(15_000L),
CATEGORY(35_000L),
- PAGED(40_000L),
HEAVY(null)
}
@@ -79,13 +78,6 @@ internal class XtreamAdaptiveSyncPolicy {
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 {
@@ -208,13 +200,12 @@ internal class XtreamAdaptiveSyncPolicy {
}
private fun segmentedRequestSpacingFor(providerId: Long, stage: Stage): Long {
- if (stage != Stage.CATEGORY && stage != Stage.PAGED) {
+ if (stage != Stage.CATEGORY) {
return 0L
}
val health = providerHealth[providerId] ?: ProviderHealth()
val baseSpacingMs = when (stage) {
Stage.CATEGORY -> 250L
- Stage.PAGED -> 180L
else -> 0L
}
val stressSpacingMs = when {
diff --git a/data/src/main/java/com/streamvault/data/sync/XtreamIndexWorker.kt b/data/src/main/java/com/streamvault/data/sync/XtreamIndexWorker.kt
new file mode 100644
index 00000000..e1f91572
--- /dev/null
+++ b/data/src/main/java/com/streamvault/data/sync/XtreamIndexWorker.kt
@@ -0,0 +1,199 @@
+package com.streamvault.data.sync
+
+import android.app.ActivityManager
+import android.content.Context
+import android.database.sqlite.SQLiteException
+import android.util.Log
+import androidx.work.BackoffPolicy
+import androidx.work.Constraints
+import androidx.work.CoroutineWorker
+import androidx.work.Data
+import androidx.work.ExistingPeriodicWorkPolicy
+import androidx.work.ExistingWorkPolicy
+import androidx.work.NetworkType
+import androidx.work.OneTimeWorkRequestBuilder
+import androidx.work.PeriodicWorkRequestBuilder
+import androidx.work.WorkManager
+import androidx.work.WorkRequest
+import androidx.work.WorkerParameters
+import com.streamvault.data.local.dao.ProviderDao
+import com.streamvault.domain.model.ContentType
+import com.streamvault.domain.model.ProviderType
+import dagger.hilt.EntryPoint
+import dagger.hilt.InstallIn
+import dagger.hilt.android.EntryPointAccessors
+import dagger.hilt.components.SingletonComponent
+import java.io.IOException
+import java.util.concurrent.TimeUnit
+
+class XtreamIndexWorker(
+ appContext: Context,
+ workerParams: WorkerParameters
+) : CoroutineWorker(appContext, workerParams) {
+
+ @EntryPoint
+ @InstallIn(SingletonComponent::class)
+ interface XtreamIndexWorkerEntryPoint {
+ fun providerDao(): ProviderDao
+ fun syncManager(): SyncManager
+ }
+
+ override suspend fun doWork(): Result {
+ if (isDeviceLowOnMemory()) {
+ Log.w(TAG, "Deferring Xtream index work: device low on memory")
+ return Result.retry()
+ }
+
+ val force = inputData.getBoolean(KEY_FORCE, false)
+ val requestedProviderId = inputData.getLong(KEY_PROVIDER_ID, INVALID_PROVIDER_ID)
+ val requestedSection = inputData.getString(KEY_SECTION)?.toContentTypeOrNull()
+
+ return try {
+ val entryPoint = EntryPointAccessors.fromApplication(
+ applicationContext,
+ XtreamIndexWorkerEntryPoint::class.java
+ )
+ val providers = if (requestedProviderId > 0L) {
+ entryPoint.providerDao().getById(requestedProviderId)?.let(::listOf).orEmpty()
+ } else {
+ entryPoint.providerDao().getAllSync()
+ .filter { provider -> provider.isActive && provider.type == ProviderType.XTREAM_CODES }
+ }
+
+ var sawRetryableFailure = false
+ providers
+ .filter { provider -> provider.type == ProviderType.XTREAM_CODES }
+ .forEach { provider ->
+ when (val result = entryPoint.syncManager().processQueuedXtreamIndexJobs(
+ providerId = provider.id,
+ section = requestedSection,
+ force = force,
+ maxCategoriesPerSection = CATEGORY_SLICE_SIZE
+ )) {
+ is com.streamvault.domain.model.Result.Error -> {
+ Log.w(TAG, "Xtream index worker failed for provider ${provider.id}: ${result.message}")
+ if (shouldRetry(result.exception)) {
+ sawRetryableFailure = true
+ }
+ }
+ else -> Unit
+ }
+ }
+
+ if (sawRetryableFailure) Result.retry() else Result.success()
+ } catch (error: Exception) {
+ Log.e(TAG, "Xtream index worker failed", error)
+ if (shouldRetry(error)) Result.retry() else Result.failure()
+ }
+ }
+
+ private fun isDeviceLowOnMemory(): Boolean {
+ val activityManager = applicationContext.getSystemService(Context.ACTIVITY_SERVICE)
+ as? ActivityManager ?: return false
+ val info = ActivityManager.MemoryInfo()
+ return runCatching {
+ activityManager.getMemoryInfo(info)
+ info.lowMemory
+ }.getOrDefault(false)
+ }
+
+ private fun shouldRetry(error: Throwable?): Boolean {
+ return when (error) {
+ is IOException -> true
+ is SQLiteException -> error.message.orEmpty().contains("locked", ignoreCase = true) ||
+ error.message.orEmpty().contains("busy", ignoreCase = true)
+ else -> false
+ }
+ }
+
+ companion object {
+ private const val TAG = "XtreamIndexWorker"
+ private const val KEY_PROVIDER_ID = "provider_id"
+ private const val KEY_SECTION = "section"
+ private const val KEY_FORCE = "force"
+ private const val INVALID_PROVIDER_ID = -1L
+ private const val CATEGORY_SLICE_SIZE = 2
+ private const val UNIQUE_WORK_PREFIX = "xtream-index-worker-"
+ private const val UNIQUE_PERIODIC_WORK_NAME = "xtream-index-periodic-worker"
+
+ fun enqueue(
+ context: Context,
+ providerId: Long,
+ section: String? = null,
+ force: Boolean = false,
+ initialDelaySeconds: Long = 0L
+ ) {
+ if (providerId <= 0L) return
+ val request = OneTimeWorkRequestBuilder<XtreamIndexWorker>()
+ .setInputData(
+ Data.Builder()
+ .putLong(KEY_PROVIDER_ID, providerId)
+ .putBoolean(KEY_FORCE, force)
+ .also { builder ->
+ section?.let { builder.putString(KEY_SECTION, it) }
+ }
+ .build()
+ )
+ .setConstraints(defaultConstraints())
+ .setInitialDelay(initialDelaySeconds.coerceAtLeast(0L), TimeUnit.SECONDS)
+ .setBackoffCriteria(
+ BackoffPolicy.EXPONENTIAL,
+ WorkRequest.MIN_BACKOFF_MILLIS,
+ TimeUnit.MILLISECONDS
+ )
+ .build()
+
+ WorkManager.getInstance(context).enqueueUniqueWork(
+ uniqueWorkName(providerId, section),
+ if (force) ExistingWorkPolicy.REPLACE else ExistingWorkPolicy.APPEND_OR_REPLACE,
+ request
+ )
+ }
+
+ fun enqueueLaunchStaleCheck(context: Context) {
+ val request = OneTimeWorkRequestBuilder<XtreamIndexWorker>()
+ .setConstraints(defaultConstraints())
+ .setInitialDelay(20, TimeUnit.SECONDS)
+ .setBackoffCriteria(
+ BackoffPolicy.EXPONENTIAL,
+ WorkRequest.MIN_BACKOFF_MILLIS,
+ TimeUnit.MILLISECONDS
+ )
+ .build()
+
+ WorkManager.getInstance(context).enqueueUniqueWork(
+ "$UNIQUE_WORK_PREFIX-launch-stale-check",
+ ExistingWorkPolicy.KEEP,
+ request
+ )
+ }
+
+ fun enqueuePeriodic(context: Context) {
+ val request = PeriodicWorkRequestBuilder<XtreamIndexWorker>(6, TimeUnit.HOURS)
+ .setConstraints(defaultConstraints())
+ .setBackoffCriteria(
+ BackoffPolicy.EXPONENTIAL,
+ WorkRequest.MIN_BACKOFF_MILLIS,
+ TimeUnit.MILLISECONDS
+ )
+ .build()
+
+ WorkManager.getInstance(context).enqueueUniquePeriodicWork(
+ UNIQUE_PERIODIC_WORK_NAME,
+ ExistingPeriodicWorkPolicy.KEEP,
+ request
+ )
+ }
+
+ private fun defaultConstraints(): Constraints = Constraints.Builder()
+ .setRequiredNetworkType(NetworkType.CONNECTED)
+ .setRequiresBatteryNotLow(true)
+ .build()
+
+ private fun uniqueWorkName(providerId: Long, section: String?): String =
+ "$UNIQUE_WORK_PREFIX$providerId-${section.orEmpty()}"
+
+ private fun String.toContentTypeOrNull(): ContentType? =
+ runCatching { ContentType.valueOf(this) }.getOrNull()
+ }
+}
diff --git a/data/src/test/java/com/streamvault/data/manager/BackupManagerImplTest.kt b/data/src/test/java/com/streamvault/data/manager/BackupManagerImplTest.kt
index 0190a45c..3c07bbb4 100644
--- a/data/src/test/java/com/streamvault/data/manager/BackupManagerImplTest.kt
+++ b/data/src/test/java/com/streamvault/data/manager/BackupManagerImplTest.kt
@@ -341,6 +341,63 @@ class BackupManagerImplTest {
verify(preferencesRepository, never()).setParentalControlLevel(any())
}
+ @Test
+ fun `importConfig restores audio video sync enabled preference`() = runBlocking {
+ val context: Context = mock()
+ val contentResolver: ContentResolver = mock()
+ whenever(context.contentResolver).thenReturn(contentResolver)
+
+ val providerDao: ProviderDao = mock()
+ val preferencesRepository: PreferencesRepository = mock()
+ val gson = Gson()
+ val backupData = BackupData(
+ preferences = mapOf(
+ "playerAudioVideoSyncEnabled" to "true",
+ "playerAudioVideoOffsetMs" to "150"
+ )
+ )
+ whenever(contentResolver.openInputStream(Uri.parse("content://backup-av-sync-preferences"))).thenReturn(
+ ByteArrayInputStream(gson.toJson(backupData).toByteArray())
+ )
+ whenever(providerDao.getAllSync()).thenReturn(emptyList())
+
+ val manager = BackupManagerImpl(
+ context = context,
+ preferencesRepository = preferencesRepository,
+ credentialCrypto = mock<CredentialCrypto>(),
+ providerDao = providerDao,
+ favoriteDao = mock<FavoriteDao>(),
+ virtualGroupDao = mock<VirtualGroupDao>(),
+ playbackHistoryDao = mock<PlaybackHistoryDao>(),
+ movieDao = mock<MovieDao>(),
+ episodeDao = mock<EpisodeDao>(),
+ categoryRepository = mock<CategoryRepository>(),
+ recordingScheduleDao = mock<RecordingScheduleDao>(),
+ recordingManager = mock<RecordingManager>(),
+ transactionRunner = object : DatabaseTransactionRunner {
+ override suspend fun <T> inTransaction(block: suspend () -> T): T = block()
+ },
+ gson = gson
+ )
+
+ val result = manager.importConfig(
+ uriString = "content://backup-av-sync-preferences",
+ plan = BackupImportPlan(
+ importPreferences = true,
+ importProviders = false,
+ importSavedLibrary = false,
+ importPlaybackHistory = false,
+ importMultiViewPresets = false,
+ importRecordingSchedules = false,
+ conflictStrategy = BackupConflictStrategy.KEEP_EXISTING
+ )
+ )
+
+ assertThat(result).isInstanceOf(Result.Success::class.java)
+ verify(preferencesRepository).setPlayerAudioVideoSyncEnabled(true)
+ verify(preferencesRepository).setPlayerAudioVideoOffsetMs(150)
+ }
+
@Test
fun `toScheduledRecordingBackup stores requested window and padding separately`() {
val provider = Provider(
@@ -643,4 +700,4 @@ class BackupManagerImplTest {
}
}
}
-}
\ No newline at end of file
+}
diff --git a/data/src/test/java/com/streamvault/data/remote/http/RequestIdentityTest.kt b/data/src/test/java/com/streamvault/data/remote/http/RequestIdentityTest.kt
new file mode 100644
index 00000000..037c70d3
--- /dev/null
+++ b/data/src/test/java/com/streamvault/data/remote/http/RequestIdentityTest.kt
@@ -0,0 +1,41 @@
+package com.streamvault.data.remote.http
+
+import com.google.common.truth.Truth.assertThat
+import okhttp3.Request
+import org.junit.Test
+
+class RequestIdentityTest {
+
+ @Test
+ fun `withRequestProfile does not overwrite explicit user agent`() {
+ val request = Request.Builder()
+ .url("https://example.test/playlist.m3u")
+ .header(USER_AGENT_HEADER, "ExplicitAgent/1.0")
+ .build()
+ .withRequestProfile(HttpRequestProfile(userAgent = "FallbackAgent/1.0"))
+
+ assertThat(request.header(USER_AGENT_HEADER)).isEqualTo("ExplicitAgent/1.0")
+ }
+
+ @Test
+ fun `safeRequestIdentitySummary redacts sensitive headers`() {
+ val request = Request.Builder()
+ .url("https://example.test/epg.xml")
+ .header(USER_AGENT_HEADER, "StreamVault/1.0")
+ .header("Authorization", "Bearer secret")
+ .header("Cookie", "session=secret")
+ .header("Referer", "https://portal.example.test")
+ .build()
+
+ val summary = request.safeRequestIdentitySummary(
+ HttpRequestProfile(ownerTag = "provider:7/epg")
+ )
+
+ assertThat(summary).contains("owner=provider:7/epg")
+ assertThat(summary).contains("userAgent=StreamVault/1.0")
+ assertThat(summary).contains("Referer")
+ assertThat(summary).doesNotContain("Authorization")
+ assertThat(summary).doesNotContain("Cookie")
+ assertThat(summary).doesNotContain("secret")
+ }
+}
\ No newline at end of file
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 b3993012..ae6d71ed 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.http.HttpRequestProfile
import com.streamvault.data.remote.dto.XtreamSeriesInfoResponse
import java.net.SocketTimeoutException
import kotlinx.coroutines.test.runTest
@@ -93,6 +94,33 @@ class OkHttpXtreamApiServiceTest {
assertThat(seenIds).containsExactly(101L, 102L).inOrder()
}
+ @Test
+ fun `get applies request profile user agent`() = runTest {
+ var seenUserAgent: String? = null
+ val service = OkHttpXtreamApiService(
+ client = OkHttpClient.Builder()
+ .addInterceptor { chain ->
+ seenUserAgent = chain.request().header("User-Agent")
+ Response.Builder()
+ .request(Request.Builder().url(chain.request().url).build())
+ .protocol(Protocol.HTTP_1_1)
+ .code(200)
+ .message("test")
+ .body("[]".toResponseBody("application/json".toMediaType()))
+ .build()
+ }
+ .build(),
+ json = json
+ )
+
+ service.getLiveCategories(
+ endpoint = "https://example.test/player_api.php",
+ requestProfile = HttpRequestProfile(userAgent = "StreamVaultTest/1.0", ownerTag = "provider:7/xtream")
+ )
+
+ assertThat(seenUserAgent).isEqualTo("StreamVaultTest/1.0")
+ }
+
@Test
fun `series info parser tolerates flattened info and nested episode objects`() {
val payload = """
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 21efcc53..5bb36082 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
@@ -1,6 +1,7 @@
package com.streamvault.data.remote.xtream
import com.google.common.truth.Truth.assertThat
+import com.streamvault.data.remote.http.HttpRequestProfile
import com.streamvault.data.remote.dto.XtreamAuthResponse
import com.streamvault.data.remote.dto.XtreamCategory
import com.streamvault.data.remote.dto.XtreamEpgListing
@@ -282,18 +283,18 @@ class XtreamProviderTest {
val provider = XtreamProvider(
providerId = 42,
api = object : XtreamApiService {
- override suspend fun authenticate(endpoint: String): XtreamAuthResponse =
+ override suspend fun authenticate(endpoint: String, requestProfile: HttpRequestProfile): XtreamAuthResponse =
XtreamAuthResponse(XtreamUserInfo(auth = 1), XtreamServerInfo())
- override suspend fun getLiveCategories(endpoint: String): List<XtreamCategory> = emptyList()
+ override suspend fun getLiveCategories(endpoint: String, requestProfile: HttpRequestProfile): List<XtreamCategory> = emptyList()
- override suspend fun getLiveStreams(endpoint: String): List<XtreamStream> = emptyList()
+ override suspend fun getLiveStreams(endpoint: String, requestProfile: HttpRequestProfile): List<XtreamStream> = emptyList()
- override suspend fun getVodCategories(endpoint: String): List<XtreamCategory> {
+ override suspend fun getVodCategories(endpoint: String, requestProfile: HttpRequestProfile): List<XtreamCategory> {
throw XtreamNetworkException("category prefetch failed")
}
- override suspend fun getVodStreams(endpoint: String): List<XtreamStream> = listOf(
+ override suspend fun getVodStreams(endpoint: String, requestProfile: HttpRequestProfile): List<XtreamStream> = listOf(
XtreamStream(
name = "Action Movie",
streamId = 321,
@@ -303,17 +304,17 @@ class XtreamProviderTest {
)
)
- override suspend fun getVodInfo(endpoint: String): XtreamVodInfoResponse = XtreamVodInfoResponse()
+ override suspend fun getVodInfo(endpoint: String, requestProfile: HttpRequestProfile): XtreamVodInfoResponse = XtreamVodInfoResponse()
- override suspend fun getSeriesCategories(endpoint: String): List<XtreamCategory> = emptyList()
+ override suspend fun getSeriesCategories(endpoint: String, requestProfile: HttpRequestProfile): List<XtreamCategory> = emptyList()
- override suspend fun getSeriesList(endpoint: String): List<XtreamSeriesItem> = emptyList()
+ override suspend fun getSeriesList(endpoint: String, requestProfile: HttpRequestProfile): List<XtreamSeriesItem> = emptyList()
- override suspend fun getSeriesInfo(endpoint: String): XtreamSeriesInfoResponse = XtreamSeriesInfoResponse()
+ override suspend fun getSeriesInfo(endpoint: String, requestProfile: HttpRequestProfile): XtreamSeriesInfoResponse = XtreamSeriesInfoResponse()
- override suspend fun getShortEpg(endpoint: String): XtreamEpgResponse = XtreamEpgResponse()
+ override suspend fun getShortEpg(endpoint: String, requestProfile: HttpRequestProfile): XtreamEpgResponse = XtreamEpgResponse()
- override suspend fun getFullEpg(endpoint: String): XtreamEpgResponse = XtreamEpgResponse()
+ override suspend fun getFullEpg(endpoint: String, requestProfile: HttpRequestProfile): XtreamEpgResponse = XtreamEpgResponse()
},
serverUrl = "https://example.com",
username = "user",
@@ -499,24 +500,24 @@ class XtreamProviderTest {
val provider = XtreamProvider(
providerId = 42,
api = object : XtreamApiService {
- override suspend fun authenticate(endpoint: String): XtreamAuthResponse =
+ override suspend fun authenticate(endpoint: String, requestProfile: HttpRequestProfile): XtreamAuthResponse =
XtreamAuthResponse(XtreamUserInfo(auth = 1), XtreamServerInfo())
- override suspend fun getLiveCategories(endpoint: String): List<XtreamCategory> = emptyList()
+ override suspend fun getLiveCategories(endpoint: String, requestProfile: HttpRequestProfile): List<XtreamCategory> = emptyList()
- override suspend fun getLiveStreams(endpoint: String): List<XtreamStream> = emptyList()
+ override suspend fun getLiveStreams(endpoint: String, requestProfile: HttpRequestProfile): List<XtreamStream> = emptyList()
- override suspend fun getVodCategories(endpoint: String): List<XtreamCategory> = emptyList()
+ override suspend fun getVodCategories(endpoint: String, requestProfile: HttpRequestProfile): List<XtreamCategory> = emptyList()
- override suspend fun getVodStreams(endpoint: String): List<XtreamStream> = emptyList()
+ override suspend fun getVodStreams(endpoint: String, requestProfile: HttpRequestProfile): List<XtreamStream> = emptyList()
- override suspend fun getVodInfo(endpoint: String): XtreamVodInfoResponse = XtreamVodInfoResponse()
+ override suspend fun getVodInfo(endpoint: String, requestProfile: HttpRequestProfile): XtreamVodInfoResponse = XtreamVodInfoResponse()
- override suspend fun getSeriesCategories(endpoint: String): List<XtreamCategory> = emptyList()
+ override suspend fun getSeriesCategories(endpoint: String, requestProfile: HttpRequestProfile): List<XtreamCategory> = emptyList()
- override suspend fun getSeriesList(endpoint: String): List<XtreamSeriesItem> = emptyList()
+ override suspend fun getSeriesList(endpoint: String, requestProfile: HttpRequestProfile): List<XtreamSeriesItem> = emptyList()
- override suspend fun getSeriesInfo(endpoint: String): XtreamSeriesInfoResponse {
+ override suspend fun getSeriesInfo(endpoint: String, requestProfile: HttpRequestProfile): XtreamSeriesInfoResponse {
requestedEndpoints += endpoint
return if (endpoint.contains("series_id=77")) {
XtreamSeriesInfoResponse()
@@ -538,9 +539,9 @@ class XtreamProviderTest {
}
}
- override suspend fun getShortEpg(endpoint: String): XtreamEpgResponse = XtreamEpgResponse()
+ override suspend fun getShortEpg(endpoint: String, requestProfile: HttpRequestProfile): XtreamEpgResponse = XtreamEpgResponse()
- override suspend fun getFullEpg(endpoint: String): XtreamEpgResponse = XtreamEpgResponse()
+ override suspend fun getFullEpg(endpoint: String, requestProfile: HttpRequestProfile): XtreamEpgResponse = XtreamEpgResponse()
},
serverUrl = "https://example.com",
username = "user",
@@ -602,28 +603,28 @@ class XtreamProviderTest {
private val shortEpg: XtreamEpgResponse = XtreamEpgResponse(),
private val fullEpg: XtreamEpgResponse = XtreamEpgResponse()
) : XtreamApiService {
- override suspend fun authenticate(endpoint: String): XtreamAuthResponse {
+ override suspend fun authenticate(endpoint: String, requestProfile: HttpRequestProfile): XtreamAuthResponse {
return authResponse
}
- override suspend fun getLiveCategories(endpoint: String): List<XtreamCategory> = liveCategories
+ override suspend fun getLiveCategories(endpoint: String, requestProfile: HttpRequestProfile): List<XtreamCategory> = liveCategories
- override suspend fun getLiveStreams(endpoint: String): List<XtreamStream> = liveStreams
+ override suspend fun getLiveStreams(endpoint: String, requestProfile: HttpRequestProfile): List<XtreamStream> = liveStreams
- override suspend fun getVodCategories(endpoint: String): List<XtreamCategory> = vodCategories
+ override suspend fun getVodCategories(endpoint: String, requestProfile: HttpRequestProfile): List<XtreamCategory> = vodCategories
- override suspend fun getVodStreams(endpoint: String): List<XtreamStream> = vodStreams
+ override suspend fun getVodStreams(endpoint: String, requestProfile: HttpRequestProfile): List<XtreamStream> = vodStreams
- override suspend fun getVodInfo(endpoint: String): XtreamVodInfoResponse = vodInfo
+ override suspend fun getVodInfo(endpoint: String, requestProfile: HttpRequestProfile): XtreamVodInfoResponse = vodInfo
- override suspend fun getSeriesCategories(endpoint: String): List<XtreamCategory> = seriesCategories
+ override suspend fun getSeriesCategories(endpoint: String, requestProfile: HttpRequestProfile): List<XtreamCategory> = seriesCategories
- override suspend fun getSeriesList(endpoint: String): List<XtreamSeriesItem> = seriesList
+ override suspend fun getSeriesList(endpoint: String, requestProfile: HttpRequestProfile): List<XtreamSeriesItem> = seriesList
- override suspend fun getSeriesInfo(endpoint: String): XtreamSeriesInfoResponse = seriesInfo
+ override suspend fun getSeriesInfo(endpoint: String, requestProfile: HttpRequestProfile): XtreamSeriesInfoResponse = seriesInfo
- override suspend fun getShortEpg(endpoint: String): XtreamEpgResponse = shortEpg
+ override suspend fun getShortEpg(endpoint: String, requestProfile: HttpRequestProfile): XtreamEpgResponse = shortEpg
- override suspend fun getFullEpg(endpoint: String): XtreamEpgResponse = fullEpg
+ override suspend fun getFullEpg(endpoint: String, requestProfile: HttpRequestProfile): XtreamEpgResponse = fullEpg
}
}
diff --git a/data/src/test/java/com/streamvault/data/repository/ChannelRepositoryImplTest.kt b/data/src/test/java/com/streamvault/data/repository/ChannelRepositoryImplTest.kt
index e4589736..16988c71 100644
--- a/data/src/test/java/com/streamvault/data/repository/ChannelRepositoryImplTest.kt
+++ b/data/src/test/java/com/streamvault/data/repository/ChannelRepositoryImplTest.kt
@@ -211,6 +211,33 @@ class ChannelRepositoryImplTest {
assertThat(result.map { it.name }).containsExactly("News One")
}
+ @Test
+ fun `searchChannels does not run like fallback when fts returns rows`() = runTest {
+ whenever(channelDao.search(eq(7L), any(), any())).thenReturn(
+ flowOf(
+ listOf(
+ ChannelBrowseEntity(
+ id = 100L,
+ streamId = 200L,
+ name = "News Fast",
+ streamUrl = "https://stream/news-fast",
+ number = 10,
+ providerId = 7L
+ )
+ )
+ )
+ )
+ whenever(parentalControlManager.unlockedCategoriesForProvider(7L)).thenReturn(flowOf(emptySet()))
+ whenever(favoriteDao.getAllByType(7L, ContentType.LIVE.name)).thenReturn(flowOf(emptyList()))
+
+ val repository = createRepository()
+
+ val result = repository.searchChannels(7L, "news").first()
+
+ assertThat(result.map { it.name }).containsExactly("News Fast")
+ verify(channelDao, never()).searchFallback(eq(7L), any(), any())
+ }
+
private fun createRepository() = ChannelRepositoryImpl(
channelDao = channelDao,
categoryDao = categoryDao,
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 9157192f..3c641027 100644
--- a/data/src/test/java/com/streamvault/data/repository/MovieRepositoryImplTest.kt
+++ b/data/src/test/java/com/streamvault/data/repository/MovieRepositoryImplTest.kt
@@ -8,6 +8,7 @@ import com.streamvault.data.local.dao.MovieCategoryHydrationDao
import com.streamvault.data.local.dao.MovieDao
import com.streamvault.data.local.dao.PlaybackHistoryDao
import com.streamvault.data.local.dao.ProviderDao
+import com.streamvault.data.local.dao.XtreamContentIndexDao
import com.streamvault.data.local.DatabaseTransactionRunner
import com.streamvault.data.local.entity.FavoriteEntity
import com.streamvault.data.local.entity.MovieBrowseEntity
@@ -27,6 +28,7 @@ import com.streamvault.data.remote.stalker.StalkerApiService
import com.streamvault.data.remote.xtream.XtreamApiService
import com.streamvault.data.remote.xtream.XtreamStreamUrlResolver
import com.streamvault.data.security.CredentialCrypto
+import com.streamvault.data.sync.SyncManager
import com.streamvault.domain.model.ContentType
import com.streamvault.domain.model.LibraryBrowseQuery
import com.streamvault.domain.model.LibraryFilterBy
@@ -52,6 +54,7 @@ import org.mockito.kotlin.argumentCaptor
import org.mockito.kotlin.eq
import org.mockito.kotlin.mock
import org.mockito.kotlin.never
+import org.mockito.kotlin.times
import org.mockito.kotlin.verify
import org.mockito.kotlin.whenever
@@ -69,6 +72,8 @@ class MovieRepositoryImplTest {
private val xtreamStreamUrlResolver: XtreamStreamUrlResolver = mock()
private val movieCategoryHydrationDao: MovieCategoryHydrationDao = mock()
private val syncMetadataRepository: SyncMetadataRepository = mock()
+ private val xtreamContentIndexDao: XtreamContentIndexDao = mock()
+ private val syncManager: SyncManager = mock()
private val credentialCrypto = object : CredentialCrypto {
override fun encryptIfNeeded(value: String): String = value
override fun decryptIfNeeded(value: String): String = value
@@ -176,7 +181,7 @@ class MovieRepositoryImplTest {
}
@Test
- fun `getMoviesByCategory lazily hydrates xtream category when local cache is empty`() = runTest {
+ fun `getMoviesByCategory does not hydrate xtream category when local cache is empty`() = runTest {
whenever(preferencesRepository.parentalControlLevel).thenReturn(flowOf(0))
whenever(preferencesRepository.xtreamBase64TextCompatibility).thenReturn(flowOf(false))
whenever(movieDao.getCountByCategory(7L, 42L)).thenReturn(flowOf(0))
@@ -193,30 +198,18 @@ class MovieRepositoryImplTest {
status = ProviderStatus.ACTIVE
)
)
- whenever(xtreamApiService.getVodCategories(any())).thenReturn(
- listOf(XtreamCategory(categoryId = "42", categoryName = "Action"))
- )
- whenever(xtreamApiService.getVodStreams(any())).thenReturn(
- listOf(
- XtreamStream(
- streamId = 101L,
- name = "Movie",
- categoryId = "42",
- streamIcon = null,
- containerExtension = "mp4"
- )
- )
- )
-
val repository = createRepository()
- repository.getMoviesByCategory(7L, 42L).first()
+ val result = repository.getMoviesByCategory(7L, 42L).first()
- verify(movieDao).replaceCategory(eq(7L), eq(42L), any())
+ assertThat(result).isEmpty()
+ verify(syncManager).prioritizeXtreamIndexCategory(7L, ContentType.MOVIE, 42L)
+ verify(movieDao, never()).replaceCategory(eq(7L), eq(42L), any())
+ verify(xtreamApiService, never()).getVodStreams(any())
}
@Test
- fun `getMoviesByCategory marks empty xtream fast sync hydration for retry`() = runTest {
+ fun `getMoviesByCategory skips legacy xtream empty retry hydration`() = runTest {
whenever(preferencesRepository.parentalControlLevel).thenReturn(flowOf(0))
whenever(preferencesRepository.xtreamBase64TextCompatibility).thenReturn(flowOf(false))
whenever(movieDao.getCountByCategory(7L, 42L)).thenReturn(flowOf(0))
@@ -236,20 +229,48 @@ class MovieRepositoryImplTest {
status = ProviderStatus.ACTIVE
)
)
- whenever(xtreamApiService.getVodCategories(any())).thenReturn(
- listOf(XtreamCategory(categoryId = "42", categoryName = "Action"))
- )
- whenever(xtreamApiService.getVodStreams(any())).thenReturn(emptyList())
-
val repository = createRepository()
repository.getMoviesByCategory(7L, 42L).first()
+ verify(syncManager).prioritizeXtreamIndexCategory(7L, ContentType.MOVIE, 42L)
verify(movieDao, never()).replaceCategory(eq(7L), eq(42L), any())
- val hydrationCaptor = argumentCaptor<com.streamvault.data.local.entity.MovieCategoryHydrationEntity>()
- verify(movieCategoryHydrationDao).upsert(hydrationCaptor.capture())
- assertThat(hydrationCaptor.firstValue.lastStatus).isEqualTo("EMPTY_RETRY")
- assertThat(hydrationCaptor.firstValue.itemCount).isEqualTo(0)
+ verify(movieCategoryHydrationDao, never()).upsert(any())
+ verify(xtreamApiService, never()).getVodStreams(any())
+ }
+
+ @Test
+ fun `getMovieDetails uses fresh xtream hydrated cache without refetching`() = runTest {
+ val hydratedAt = System.currentTimeMillis()
+ whenever(movieDao.getById(99L)).thenReturn(
+ movieRecord(
+ id = 99L,
+ name = "Cached Movie",
+ genre = "Drama",
+ categoryId = 42L,
+ rating = 7.1f
+ ).copy(
+ cacheState = "DETAIL_HYDRATED",
+ detailHydratedAt = hydratedAt
+ )
+ )
+ 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
+ )
+ )
+
+ val result = createRepository().getMovieDetails(7L, 99L)
+
+ assertThat(result.getOrNull()?.name).isEqualTo("Cached Movie")
+ verify(xtreamApiService, never()).getVodInfo(any())
+ verify(xtreamContentIndexDao, never()).markDetailHydrated(any(), any(), any(), any(), anyOrNull(), any())
}
@Test
@@ -418,6 +439,73 @@ class MovieRepositoryImplTest {
assertThat(result.map { it.name }).containsExactly("Matrix Reloaded")
}
+ @Test
+ fun `searchMovies returns empty without like fallback when fts has no rows`() = runTest {
+ whenever(preferencesRepository.parentalControlLevel).thenReturn(flowOf(0))
+ whenever(movieDao.search(eq(7L), any(), any())).thenReturn(flowOf(emptyList()))
+ whenever(favoriteDao.getAllByType(7L, ContentType.MOVIE.name)).thenReturn(flowOf(emptyList()))
+
+ val repository = createRepository()
+
+ val result = repository.searchMovies(7L, "matrix").first()
+
+ assertThat(result).isEmpty()
+ verify(movieDao, never()).searchFallback(eq(7L), any(), any())
+ }
+
+ @Test
+ fun `searchMovies does not run like fallback when fts returns rows`() = runTest {
+ whenever(preferencesRepository.parentalControlLevel).thenReturn(flowOf(0))
+ whenever(movieDao.search(eq(7L), any(), any())).thenReturn(
+ flowOf(
+ listOf(
+ movieEntity(
+ id = 103L,
+ name = "Matrix",
+ genre = "Action",
+ categoryId = 42L,
+ rating = 9.0f
+ )
+ )
+ )
+ )
+ whenever(favoriteDao.getAllByType(7L, ContentType.MOVIE.name)).thenReturn(flowOf(emptyList()))
+
+ val repository = createRepository()
+
+ val result = repository.searchMovies(7L, "matrix").first()
+
+ assertThat(result.map { it.name }).containsExactly("Matrix")
+ verify(movieDao, never()).searchFallback(eq(7L), any(), any())
+ }
+
+ @Test
+ fun `browseMovies search uses bounded page query`() = runTest {
+ whenever(preferencesRepository.parentalControlLevel).thenReturn(flowOf(0))
+ whenever(movieDao.searchPage(eq(7L), any(), any(), any(), any(), any(), any())).thenReturn(
+ listOf(
+ movieEntity(id = 101L, name = "Matrix", genre = "Action", categoryId = 42L, rating = 9.0f),
+ movieEntity(id = 102L, name = "Matrix Reloaded", genre = "Action", categoryId = 42L, rating = 7.5f)
+ )
+ )
+ whenever(favoriteDao.getAllByType(7L, ContentType.MOVIE.name)).thenReturn(flowOf(emptyList()))
+
+ val result = createRepository().browseMovies(
+ LibraryBrowseQuery(
+ providerId = 7L,
+ searchQuery = "matrix",
+ offset = 0,
+ limit = 1
+ )
+ ).first()
+
+ assertThat(result.totalCount).isEqualTo(2)
+ assertThat(result.items.map { it.name }).containsExactly("Matrix")
+ verify(movieDao, times(1)).searchPage(eq(7L), any(), any(), any(), any(), eq(2), eq(0))
+ verify(movieDao, never()).search(eq(7L), any(), any())
+ verify(movieDao, never()).searchFallback(eq(7L), any(), any())
+ }
+
@Test
fun `browseMovies top rated excludes unrated entries and uses filtered total count`() = runTest {
whenever(preferencesRepository.parentalControlLevel).thenReturn(flowOf(0))
@@ -464,6 +552,8 @@ class MovieRepositoryImplTest {
xtreamStreamUrlResolver = xtreamStreamUrlResolver,
movieCategoryHydrationDao = movieCategoryHydrationDao,
syncMetadataRepository = syncMetadataRepository,
+ xtreamContentIndexDao = xtreamContentIndexDao,
+ syncManager = syncManager,
transactionRunner = transactionRunner
)
diff --git a/data/src/test/java/com/streamvault/data/repository/SearchRepositoryImplTest.kt b/data/src/test/java/com/streamvault/data/repository/SearchRepositoryImplTest.kt
new file mode 100644
index 00000000..56e70b3a
--- /dev/null
+++ b/data/src/test/java/com/streamvault/data/repository/SearchRepositoryImplTest.kt
@@ -0,0 +1,140 @@
+package com.streamvault.data.repository
+
+import android.database.sqlite.SQLiteException
+import com.google.common.truth.Truth.assertThat
+import com.streamvault.data.local.dao.SearchDao
+import com.streamvault.data.local.dao.SearchHitEntity
+import com.streamvault.domain.model.Channel
+import com.streamvault.domain.model.Movie
+import com.streamvault.domain.model.Series
+import com.streamvault.domain.repository.ChannelRepository
+import com.streamvault.domain.repository.MovieRepository
+import com.streamvault.domain.repository.SeriesRepository
+import kotlinx.coroutines.flow.first
+import kotlinx.coroutines.flow.flow
+import kotlinx.coroutines.flow.flowOf
+import kotlinx.coroutines.test.runTest
+import org.junit.Test
+import org.mockito.kotlin.any
+import org.mockito.kotlin.eq
+import org.mockito.kotlin.mock
+import org.mockito.kotlin.never
+import org.mockito.kotlin.verify
+import org.mockito.kotlin.whenever
+
+class SearchRepositoryImplTest {
+ private val searchDao: SearchDao = mock()
+ private val channelRepository: ChannelRepository = mock()
+ private val movieRepository: MovieRepository = mock()
+ private val seriesRepository: SeriesRepository = mock()
+
+ private val repository = SearchRepositoryImpl(
+ searchDao = searchDao,
+ channelRepository = channelRepository,
+ movieRepository = movieRepository,
+ seriesRepository = seriesRepository
+ )
+
+ @Test
+ fun `empty unified FTS result does not trigger legacy LIKE fallback`() = runTest {
+ whenever(searchDao.searchAll(eq(PROVIDER_ID), any(), any(), any(), eq(LIMIT)))
+ .thenReturn(flowOf(emptyList()))
+
+ val result = repository.searchContent(
+ providerId = PROVIDER_ID,
+ query = "missing",
+ includeLive = true,
+ includeMovies = true,
+ includeSeries = true,
+ maxResultsPerSection = LIMIT
+ ).first()
+
+ assertThat(result.channels).isEmpty()
+ assertThat(result.movies).isEmpty()
+ assertThat(result.series).isEmpty()
+ verify(channelRepository, never()).searchChannels(any(), any())
+ verify(movieRepository, never()).searchMovies(any(), any())
+ verify(seriesRepository, never()).searchSeries(any(), any())
+ }
+
+ @Test
+ fun `unified FTS failure falls back to legacy section search`() = runTest {
+ whenever(searchDao.searchAll(eq(PROVIDER_ID), any(), any(), any(), eq(LIMIT)))
+ .thenReturn(flow { throw SQLiteException("fts unavailable") })
+ whenever(channelRepository.searchChannels(PROVIDER_ID, "star"))
+ .thenReturn(flowOf(listOf(Channel(id = 1L, name = "Star News"))))
+ whenever(movieRepository.searchMovies(PROVIDER_ID, "star"))
+ .thenReturn(flowOf(listOf(Movie(id = 2L, name = "Star Movie"))))
+ whenever(seriesRepository.searchSeries(PROVIDER_ID, "star"))
+ .thenReturn(flowOf(listOf(Series(id = 3L, name = "Star Series"))))
+
+ val result = repository.searchContent(
+ providerId = PROVIDER_ID,
+ query = "star",
+ includeLive = true,
+ includeMovies = true,
+ includeSeries = true,
+ maxResultsPerSection = LIMIT
+ ).first()
+
+ assertThat(result.channels.map { it.id }).containsExactly(1L)
+ assertThat(result.movies.map { it.id }).containsExactly(2L)
+ assertThat(result.series.map { it.id }).containsExactly(3L)
+ }
+
+ @Test
+ fun `unified FTS hits hydrate only matching ids and preserve ranking order`() = runTest {
+ whenever(searchDao.searchAll(eq(PROVIDER_ID), any(), any(), any(), eq(LIMIT)))
+ .thenReturn(
+ flowOf(
+ listOf(
+ hit(contentType = "MOVIE", contentId = 20L, title = "Star B", matchRank = 1),
+ hit(contentType = "MOVIE", contentId = 10L, title = "Star A", matchRank = 0)
+ )
+ )
+ )
+ whenever(movieRepository.getMoviesByIds(listOf(10L, 20L)))
+ .thenReturn(
+ flowOf(
+ listOf(
+ Movie(id = 20L, name = "Star B"),
+ Movie(id = 10L, name = "Star A")
+ )
+ )
+ )
+
+ val result = repository.searchContent(
+ providerId = PROVIDER_ID,
+ query = "star",
+ includeLive = true,
+ includeMovies = true,
+ includeSeries = true,
+ maxResultsPerSection = LIMIT
+ ).first()
+
+ assertThat(result.channels).isEmpty()
+ assertThat(result.movies.map { it.id }).containsExactly(10L, 20L).inOrder()
+ assertThat(result.series).isEmpty()
+ verify(channelRepository, never()).getChannelsByIds(any())
+ verify(seriesRepository, never()).getSeriesByIds(any())
+ }
+
+ private fun hit(
+ contentType: String,
+ contentId: Long,
+ title: String,
+ matchRank: Int
+ ): SearchHitEntity =
+ SearchHitEntity(
+ contentType = contentType,
+ contentId = contentId,
+ title = title,
+ sectionRank = 0,
+ matchRank = matchRank
+ )
+
+ private companion object {
+ const val PROVIDER_ID = 99L
+ const val LIMIT = 120
+ }
+}
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 a4f0dd43..b266d54c 100644
--- a/data/src/test/java/com/streamvault/data/repository/SeriesRepositoryImplTest.kt
+++ b/data/src/test/java/com/streamvault/data/repository/SeriesRepositoryImplTest.kt
@@ -9,6 +9,7 @@ import com.streamvault.data.local.dao.PlaybackHistoryDao
import com.streamvault.data.local.dao.ProviderDao
import com.streamvault.data.local.dao.SeriesDao
import com.streamvault.data.local.dao.SeriesCategoryHydrationDao
+import com.streamvault.data.local.dao.XtreamContentIndexDao
import com.streamvault.data.local.entity.EpisodeEntity
import com.streamvault.data.local.entity.SeriesEntity
import com.streamvault.data.local.entity.SeriesBrowseEntity
@@ -29,6 +30,7 @@ import com.streamvault.data.remote.xtream.XtreamParsingException
import com.streamvault.data.remote.xtream.XtreamApiService
import com.streamvault.data.remote.xtream.XtreamStreamUrlResolver
import com.streamvault.data.security.CredentialCrypto
+import com.streamvault.data.sync.SyncManager
import com.streamvault.domain.model.ContentType
import com.streamvault.domain.model.LibraryBrowseQuery
import com.streamvault.domain.model.LibraryFilterBy
@@ -50,6 +52,7 @@ import org.mockito.kotlin.argumentCaptor
import org.mockito.kotlin.eq
import org.mockito.kotlin.mock
import org.mockito.kotlin.never
+import org.mockito.kotlin.times
import org.mockito.kotlin.verify
import org.mockito.kotlin.verifyNoInteractions
import org.mockito.kotlin.whenever
@@ -68,13 +71,15 @@ class SeriesRepositoryImplTest {
private val preferencesRepository: PreferencesRepository = mock()
private val xtreamStreamUrlResolver: XtreamStreamUrlResolver = mock()
private val seriesCategoryHydrationDao: SeriesCategoryHydrationDao = mock()
+ private val xtreamContentIndexDao: XtreamContentIndexDao = mock()
+ private val syncManager: SyncManager = mock()
private val credentialCrypto = object : CredentialCrypto {
override fun encryptIfNeeded(value: String): String = value
override fun decryptIfNeeded(value: String): String = value
}
@Test
- fun `getSeriesByCategory lazily hydrates xtream category when local cache is empty`() = runTest {
+ fun `getSeriesByCategory does not hydrate xtream category when local cache is empty`() = runTest {
whenever(preferencesRepository.parentalControlLevel).thenReturn(flowOf(0))
whenever(preferencesRepository.xtreamBase64TextCompatibility).thenReturn(flowOf(false))
whenever(seriesDao.getCountByCategory(7L, 77L)).thenReturn(flowOf(0))
@@ -90,29 +95,49 @@ class SeriesRepositoryImplTest {
status = ProviderStatus.ACTIVE
)
)
- whenever(xtreamApiService.getSeriesCategories(any())).thenReturn(
- listOf(XtreamCategory(categoryId = "77", categoryName = "Drama"))
- )
- whenever(xtreamApiService.getSeriesList(any())).thenReturn(
- listOf(
- XtreamSeriesItem(
- seriesId = 301L,
- name = "Series",
- categoryId = "77",
- cover = null
- )
- )
- )
whenever(seriesCategoryHydrationDao.get(7L, 77L)).thenReturn(null)
- whenever(episodeDao.deleteOrphans()).thenReturn(0)
val repository = createRepository()
val result = repository.getSeriesByCategory(7L, 77L).first()
assertThat(result).isEmpty()
- verify(seriesDao).replaceCategory(eq(7L), eq(77L), any())
- verify(episodeDao).deleteOrphans()
+ verify(syncManager).prioritizeXtreamIndexCategory(7L, ContentType.SERIES, 77L)
+ verify(seriesDao, never()).replaceCategory(eq(7L), eq(77L), any())
+ verify(xtreamApiService, never()).getSeriesList(any())
+ verify(episodeDao, never()).deleteOrphans()
+ }
+
+ @Test
+ fun `getSeriesDetails uses fresh xtream hydrated cache without refetching`() = runTest {
+ val hydratedAt = System.currentTimeMillis()
+ val seriesEntity = SeriesEntity(
+ id = 99L,
+ seriesId = 301L,
+ name = "Cached Series",
+ providerId = 7L,
+ cacheState = "DETAIL_HYDRATED",
+ detailHydratedAt = hydratedAt
+ )
+ whenever(seriesDao.getById(99L)).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(99L)).thenReturn(emptyList())
+
+ val result = createRepository().getSeriesDetails(7L, 99L)
+
+ assertThat(result.getOrNull()?.name).isEqualTo("Cached Series")
+ verify(xtreamApiService, never()).getSeriesInfo(any())
+ verify(xtreamContentIndexDao, never()).markDetailHydrated(any(), any(), any(), any(), anyOrNull(), any())
}
@Test
@@ -257,7 +282,7 @@ class SeriesRepositoryImplTest {
}
@Test
- fun `getSeriesByCategory marks empty xtream fast sync hydration for retry`() = runTest {
+ fun `getSeriesByCategory skips legacy xtream empty retry hydration`() = runTest {
whenever(preferencesRepository.parentalControlLevel).thenReturn(flowOf(0))
whenever(preferencesRepository.xtreamBase64TextCompatibility).thenReturn(flowOf(false))
whenever(seriesDao.getCountByCategory(7L, 77L)).thenReturn(flowOf(0))
@@ -275,20 +300,14 @@ class SeriesRepositoryImplTest {
status = ProviderStatus.ACTIVE
)
)
- whenever(xtreamApiService.getSeriesCategories(any())).thenReturn(
- listOf(XtreamCategory(categoryId = "77", categoryName = "Drama"))
- )
- whenever(xtreamApiService.getSeriesList(any())).thenReturn(emptyList())
-
val repository = createRepository()
repository.getSeriesByCategory(7L, 77L).first()
+ verify(syncManager).prioritizeXtreamIndexCategory(7L, ContentType.SERIES, 77L)
verify(seriesDao, never()).replaceCategory(eq(7L), eq(77L), any())
- val hydrationCaptor = argumentCaptor<com.streamvault.data.local.entity.SeriesCategoryHydrationEntity>()
- verify(seriesCategoryHydrationDao).upsert(hydrationCaptor.capture())
- assertThat(hydrationCaptor.firstValue.lastStatus).isEqualTo("EMPTY_RETRY")
- assertThat(hydrationCaptor.firstValue.itemCount).isEqualTo(0)
+ verify(seriesCategoryHydrationDao, never()).upsert(any())
+ verify(xtreamApiService, never()).getSeriesList(any())
}
@Test
@@ -424,6 +443,7 @@ class SeriesRepositoryImplTest {
assertThat(series.name).isEqualTo("Stored Series")
verify(stalkerApiService).getSeriesDetails(any(), any(), eq("55000:55000"))
verifyNoInteractions(xtreamApiService)
+ verify(xtreamContentIndexDao, never()).markDetailHydrated(any(), any(), any(), any(), anyOrNull(), any())
}
@Test
@@ -453,6 +473,72 @@ class SeriesRepositoryImplTest {
assertThat(result.map { it.name }).containsExactly("Drama House")
}
+ @Test
+ fun `searchSeries returns empty without like fallback when fts has no rows`() = runTest {
+ whenever(preferencesRepository.parentalControlLevel).thenReturn(flowOf(0))
+ whenever(seriesDao.search(eq(7L), any(), any())).thenReturn(flowOf(emptyList()))
+ whenever(favoriteDao.getAllByType(7L, ContentType.SERIES.name)).thenReturn(flowOf(emptyList()))
+
+ val repository = createRepository()
+
+ val result = repository.searchSeries(7L, "drama").first()
+
+ assertThat(result).isEmpty()
+ verify(seriesDao, never()).searchFallback(eq(7L), any(), any())
+ }
+
+ @Test
+ fun `searchSeries does not run like fallback when fts returns rows`() = runTest {
+ whenever(preferencesRepository.parentalControlLevel).thenReturn(flowOf(0))
+ whenever(seriesDao.search(eq(7L), any(), any())).thenReturn(
+ flowOf(
+ listOf(
+ SeriesBrowseEntity(
+ id = 17L,
+ seriesId = 1700L,
+ name = "Drama",
+ providerId = 7L
+ )
+ )
+ )
+ )
+ whenever(favoriteDao.getAllByType(7L, ContentType.SERIES.name)).thenReturn(flowOf(emptyList()))
+
+ val repository = createRepository()
+
+ val result = repository.searchSeries(7L, "drama").first()
+
+ assertThat(result.map { it.name }).containsExactly("Drama")
+ verify(seriesDao, never()).searchFallback(eq(7L), any(), any())
+ }
+
+ @Test
+ fun `browseSeries search uses bounded page query`() = runTest {
+ whenever(preferencesRepository.parentalControlLevel).thenReturn(flowOf(0))
+ whenever(seriesDao.searchPage(eq(7L), any(), any(), any(), any(), any(), any())).thenReturn(
+ listOf(
+ SeriesBrowseEntity(id = 17L, seriesId = 1700L, name = "Drama", providerId = 7L),
+ SeriesBrowseEntity(id = 18L, seriesId = 1800L, name = "Drama Island", providerId = 7L)
+ )
+ )
+ whenever(favoriteDao.getAllByType(7L, ContentType.SERIES.name)).thenReturn(flowOf(emptyList()))
+
+ val result = createRepository().browseSeries(
+ LibraryBrowseQuery(
+ providerId = 7L,
+ searchQuery = "drama",
+ offset = 0,
+ limit = 1
+ )
+ ).first()
+
+ assertThat(result.totalCount).isEqualTo(2)
+ assertThat(result.items.map { it.name }).containsExactly("Drama")
+ verify(seriesDao, times(1)).searchPage(eq(7L), any(), any(), any(), any(), eq(2), eq(0))
+ verify(seriesDao, never()).search(eq(7L), any(), any())
+ verify(seriesDao, never()).searchFallback(eq(7L), any(), any())
+ }
+
private fun createRepository() = SeriesRepositoryImpl(
seriesDao = seriesDao,
episodeDao = episodeDao,
@@ -466,6 +552,8 @@ class SeriesRepositoryImplTest {
credentialCrypto = credentialCrypto,
preferencesRepository = preferencesRepository,
xtreamStreamUrlResolver = xtreamStreamUrlResolver,
+ xtreamContentIndexDao = xtreamContentIndexDao,
+ syncManager = syncManager,
seriesCategoryHydrationDao = seriesCategoryHydrationDao
)
}
diff --git a/data/src/test/java/com/streamvault/data/sync/SyncCatalogStoreTest.kt b/data/src/test/java/com/streamvault/data/sync/SyncCatalogStoreTest.kt
index 9be4b349..f9730d7d 100644
--- a/data/src/test/java/com/streamvault/data/sync/SyncCatalogStoreTest.kt
+++ b/data/src/test/java/com/streamvault/data/sync/SyncCatalogStoreTest.kt
@@ -303,7 +303,7 @@ class SyncCatalogStoreTest {
}
@Test
- fun `replaceCategories clears inherited protection when a protected category is remapped`() = runTest {
+ fun `replaceCategories preserves user protection when provider renames category`() = runTest {
val providerId = 7L
val currentCategory = CategoryEntity(
id = 51L,
@@ -339,15 +339,70 @@ class SyncCatalogStoreTest {
assertThat(updatedCategories.firstValue.single()).isEqualTo(
currentCategory.copy(
name = "Documentaries",
- isUserProtected = false,
+ isUserProtected = true,
syncFingerprint = "new-category"
)
)
- verify(movieDao).clearProtectionForCategories(providerId, listOf(909L))
+ verify(movieDao, never()).clearProtectionForCategories(any(), any())
verify(channelDao, never()).clearProtectionForCategories(any(), any())
verify(seriesDao, never()).clearProtectionForCategories(any(), any())
}
+ @Test
+ fun `upsertCategories preserves unstaged categories for index-first setup`() = runTest {
+ val providerId = 7L
+ whenever(categoryDao.getByProviderAndTypeSync(providerId, ContentType.MOVIE.name)).thenReturn(
+ listOf(
+ CategoryEntity(
+ id = 51L,
+ categoryId = 909L,
+ name = "Existing",
+ type = ContentType.MOVIE,
+ providerId = providerId,
+ isUserProtected = true,
+ syncFingerprint = "existing"
+ ),
+ CategoryEntity(
+ id = 52L,
+ categoryId = 910L,
+ name = "Still Remote",
+ type = ContentType.MOVIE,
+ providerId = providerId,
+ syncFingerprint = "still-remote"
+ )
+ )
+ )
+ whenever(catalogSyncDao.getCategoryStages(eq(providerId), any(), eq(ContentType.MOVIE.name))).thenReturn(
+ listOf(
+ CategoryImportStageEntity(
+ sessionId = 1L,
+ providerId = providerId,
+ categoryId = 909L,
+ name = "Existing Renamed",
+ type = ContentType.MOVIE,
+ syncFingerprint = "existing-renamed"
+ )
+ )
+ )
+
+ store().upsertCategories(
+ providerId = providerId,
+ type = ContentType.MOVIE.name,
+ categories = listOf(
+ CategoryEntity(
+ categoryId = 909L,
+ name = "Existing Renamed",
+ type = ContentType.MOVIE,
+ providerId = providerId
+ )
+ )
+ )
+
+ verify(catalogSyncDao).insertMissingCategoriesFromStage(eq(providerId), any(), eq(ContentType.MOVIE.name))
+ verify(catalogSyncDao, never()).deleteStaleCategoriesForStage(any(), any(), any())
+ verify(movieDao, never()).clearProtectionForCategories(any(), any())
+ }
+
@Test
fun `replaceLiveCatalog keeps lowest numbered channels within configured budget`() = runTest {
val providerId = 9L
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 990f8a3f..65eae352 100644
--- a/data/src/test/java/com/streamvault/data/sync/SyncManagerTest.kt
+++ b/data/src/test/java/com/streamvault/data/sync/SyncManagerTest.kt
@@ -11,9 +11,13 @@ 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.dao.TmdbIdentityDao
+import com.streamvault.data.local.dao.XtreamContentIndexDao
+import com.streamvault.data.local.dao.XtreamIndexJobDao
+import com.streamvault.data.local.entity.CategoryEntity
import com.streamvault.data.local.entity.ChannelEntity
import com.streamvault.data.local.entity.ChannelGuideSyncEntity
import com.streamvault.data.local.entity.ProviderEntity
+import com.streamvault.data.local.entity.XtreamIndexJobEntity
import com.streamvault.data.parser.M3uParser
import com.streamvault.data.security.CredentialCrypto
import com.streamvault.domain.model.SyncState
@@ -30,6 +34,7 @@ import com.streamvault.data.remote.stalker.StalkerProviderProfile
import com.streamvault.data.remote.stalker.StalkerSession
import com.streamvault.data.remote.stalker.StalkerApiService
import com.streamvault.data.preferences.PreferencesRepository
+import com.streamvault.domain.model.ContentType
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.async
@@ -184,6 +189,8 @@ class SyncManagerTest {
private val categoryDao: CategoryDao = mock()
private val catalogSyncDao: CatalogSyncDao = mock()
private val tmdbIdentityDao: TmdbIdentityDao = mock()
+ private val xtreamContentIndexDao: XtreamContentIndexDao = mock()
+ private val xtreamIndexJobDao: XtreamIndexJobDao = mock()
private val epgRepo: EpgRepository = mock()
private val epgSourceRepo: EpgSourceRepository = mock()
private val preferencesRepo: PreferencesRepository = mock()
@@ -214,6 +221,8 @@ class SyncManagerTest {
categoryDao,
catalogSyncDao,
tmdbIdentityDao,
+ xtreamContentIndexDao,
+ xtreamIndexJobDao,
epgRepo,
epgSourceRepo,
preferencesRepo,
@@ -245,6 +254,9 @@ class SyncManagerTest {
org.mockito.kotlin.whenever(
stalkerApiService.streamEpg(any(), any(), any(), any(), any())
).thenReturn(Result.success(0))
+ org.mockito.kotlin.whenever(epgSourceRepo.refreshAllForProvider(any())).thenReturn(Result.success(Unit))
+ org.mockito.kotlin.whenever(epgSourceRepo.resolveForProvider(any(), any()))
+ .thenReturn(com.streamvault.domain.model.EpgResolutionSummary())
}
}
@@ -268,6 +280,8 @@ class SyncManagerTest {
categoryDao = categoryDao,
catalogSyncDao = catalogSyncDao,
tmdbIdentityDao = tmdbIdentityDao,
+ xtreamContentIndexDao = xtreamContentIndexDao,
+ xtreamIndexJobDao = xtreamIndexJobDao,
stalkerApiService = stalkerApiService,
xtreamJson = xtreamJson,
m3uParser = M3uParser(),
@@ -282,6 +296,30 @@ class SyncManagerTest {
// ── Initial state ───────────────────────────────────────────────
+ private fun stubXtreamLiveCatalog() {
+ xtreamBackend.respond(action = "get_live_categories", body = """[{"category_id":"1","category_name":"News"}]""")
+ xtreamBackend.respond(
+ action = "get_live_streams",
+ body = """
+ [
+ {
+ "name": "Channel One",
+ "stream_id": 1001,
+ "category_id": "1",
+ "stream_icon": "https://example.com/ch1.png",
+ "tv_archive": 0,
+ "num": 1
+ }
+ ]
+ """.trimIndent()
+ )
+ }
+
+ private fun stubXtreamEmptyVodAndSeriesCategories() {
+ xtreamBackend.respond(action = "get_vod_categories", body = "[]")
+ xtreamBackend.respond(action = "get_series_categories", body = "[]")
+ }
+
@Test
fun `initialState_isIdle`() = runTest {
val mgr = buildManager()
@@ -341,9 +379,11 @@ class SyncManagerTest {
}
@Test
- fun `sync_xtream_withFreshCache_andForceFalse_skipsRemoteCalls`() = runTest {
+ fun `sync_xtream_withFreshCache_andForceFalse_runs_index_first_shell`() = runTest {
val mgr = buildManager(providerType = ProviderType.XTREAM_CODES)
val now = System.currentTimeMillis()
+ stubXtreamLiveCatalog()
+ stubXtreamEmptyVodAndSeriesCategories()
syncMetadataRepo.updateMetadata(
SyncMetadata(
providerId = 1L,
@@ -362,7 +402,54 @@ class SyncManagerTest {
advanceUntilIdle()
assertThat(result.isSuccess).isTrue()
- assertThat(xtreamBackend.requestCount()).isEqualTo(0)
+ assertThat(xtreamBackend.requestedActions).contains("get_live_categories")
+ assertThat(xtreamBackend.requestedActions).contains("get_live_streams")
+ assertThat(xtreamBackend.requestedActions).contains("get_vod_categories")
+ assertThat(xtreamBackend.requestedActions).contains("get_series_categories")
+ }
+
+ @Test
+ fun `syncEpg_xtream_success_marks_epg_job_success`() = runTest {
+ val mgr = buildManager(providerType = ProviderType.XTREAM_CODES)
+ org.mockito.kotlin.whenever(epgRepo.refreshEpg(eq(1L), any())).thenReturn(Result.success(Unit))
+ org.mockito.kotlin.whenever(epgSourceRepo.refreshAllForProvider(1L)).thenReturn(Result.success(Unit))
+ org.mockito.kotlin.whenever(epgSourceRepo.resolveForProvider(eq(1L), any()))
+ .thenReturn(com.streamvault.domain.model.EpgResolutionSummary())
+ org.mockito.kotlin.whenever(programDao.countByProvider(1L)).thenReturn(7)
+
+ val result = mgr.syncEpg(1L, force = true)
+ advanceUntilIdle()
+
+ val jobs = argumentCaptor<XtreamIndexJobEntity>()
+ verify(xtreamIndexJobDao, atLeastOnce()).upsert(jobs.capture())
+ assertThat(result.isSuccess).isTrue()
+ assertThat(jobs.allValues.any { it.section == "EPG" && it.state == "RUNNING" }).isTrue()
+ assertThat(jobs.allValues.last { it.section == "EPG" }.state).isEqualTo("SUCCESS")
+ assertThat(jobs.allValues.last { it.section == "EPG" }.indexedRows).isEqualTo(7)
+ assertThat(mgr.currentSyncState(1L)).isInstanceOf(SyncState.Success::class.java)
+ }
+
+ @Test
+ fun `syncEpg_xtream_refresh_error_marks_epg_job_retryable_instead_of_success`() = runTest {
+ val mgr = buildManager(providerType = ProviderType.XTREAM_CODES)
+ org.mockito.kotlin.whenever(epgRepo.refreshEpg(eq(1L), any()))
+ .thenReturn(Result.error("network down", java.io.IOException("network down")))
+ org.mockito.kotlin.whenever(epgSourceRepo.refreshAllForProvider(1L)).thenReturn(Result.success(Unit))
+ org.mockito.kotlin.whenever(epgSourceRepo.resolveForProvider(eq(1L), any()))
+ .thenReturn(com.streamvault.domain.model.EpgResolutionSummary())
+ org.mockito.kotlin.whenever(programDao.countByProvider(1L)).thenReturn(0)
+
+ val result = mgr.syncEpg(1L, force = true)
+ advanceUntilIdle()
+
+ val jobs = argumentCaptor<XtreamIndexJobEntity>()
+ verify(xtreamIndexJobDao, atLeastOnce()).upsert(jobs.capture())
+ val finalEpgJob = jobs.allValues.last { it.section == "EPG" }
+ val state = mgr.currentSyncState(1L) as SyncState.Partial
+ assertThat(result.isSuccess).isTrue()
+ assertThat(finalEpgJob.state).isEqualTo("FAILED_RETRYABLE")
+ assertThat(finalEpgJob.lastError).contains("EPG XMLTV sync failed")
+ assertThat(state.hasRetryableEpgFailure).isTrue()
}
@Test
@@ -398,6 +485,7 @@ class SyncManagerTest {
]
""".trimIndent()
)
+ stubXtreamEmptyVodAndSeriesCategories()
val result = mgr.sync(1L, force = false)
advanceUntilIdle()
@@ -409,9 +497,10 @@ class SyncManagerTest {
}
@Test
- fun `sync_xtream_falls_back_to_movie_categories_from_streams`() = runTest {
+ fun `sync_xtream_vod_category_failure_does_not_fetch_movie_streams`() = runTest {
val mgr = buildManager(providerType = ProviderType.XTREAM_CODES)
val now = System.currentTimeMillis()
+ stubXtreamLiveCatalog()
syncMetadataRepo.updateMetadata(
SyncMetadata(
providerId = 1L,
@@ -424,37 +513,26 @@ class SyncManagerTest {
)
)
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()
- )
+ xtreamBackend.respond(action = "get_series_categories", body = "[]")
val result = mgr.sync(1L, force = false)
advanceUntilIdle()
assertThat(result.isSuccess).isTrue()
- 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")
+ assertThat(xtreamBackend.requestedActions).contains("get_vod_categories")
+ assertThat(xtreamBackend.requestedActions).doesNotContain("get_vod_streams")
+ assertThat(mgr.currentSyncState(1L)).isInstanceOf(SyncState.Partial::class.java)
+ val jobs = argumentCaptor<XtreamIndexJobEntity>()
+ verify(xtreamIndexJobDao, atLeastOnce()).upsert(jobs.capture())
+ assertThat(jobs.allValues.last { it.section == "MOVIE" }.state).isEqualTo("FAILED_RETRYABLE")
}
@Test
- fun `sync_xtream_fast_sync_only_fetches_movie_categories`() = runTest {
+ fun `sync_xtream_ignores_legacy_fast_sync_and_queues_movie_categories`() = runTest {
val provider = sampleProvider(ProviderType.XTREAM_CODES).copy(xtreamFastSyncEnabled = true)
val mgr = buildManager(providerType = ProviderType.XTREAM_CODES, providerEntity = provider)
val now = System.currentTimeMillis()
+ stubXtreamLiveCatalog()
syncMetadataRepo.updateMetadata(
SyncMetadata(
providerId = 1L,
@@ -474,6 +552,7 @@ class SyncManagerTest {
]
""".trimIndent()
)
+ xtreamBackend.respond(action = "get_series_categories", body = "[]")
org.mockito.kotlin.whenever(movieDao.getCount(1L)).thenReturn(flowOf(0))
val result = mgr.sync(1L, force = false)
@@ -483,10 +562,20 @@ class SyncManagerTest {
assertThat(xtreamBackend.requestedActions).contains("get_vod_categories")
assertThat(xtreamBackend.requestedActions).doesNotContain("get_vod_streams")
verify(catalogSyncDao, atLeastOnce()).insertCategoryStages(any())
+ val jobs = argumentCaptor<XtreamIndexJobEntity>()
+ verify(xtreamIndexJobDao, atLeastOnce()).upsert(jobs.capture())
+ assertThat(
+ jobs.allValues.any { job ->
+ job.section == "MOVIE" &&
+ job.state == "QUEUED" &&
+ job.totalCategories == 1 &&
+ job.indexedRows == 0
+ }
+ ).isTrue()
}
@Test
- fun `retrySection_movies_fast_sync_succeeds_with_categories_only`() = runTest {
+ fun `retrySection_movies_queues_xtream_index_categories_only`() = runTest {
val mgr = buildManager(providerType = ProviderType.XTREAM_CODES)
xtreamBackend.respond(
action = "get_vod_categories",
@@ -500,17 +589,163 @@ class SyncManagerTest {
val result = mgr.retrySection(
providerId = 1L,
- section = SyncRepairSection.MOVIES,
- movieFastSyncOverride = true
+ section = SyncRepairSection.MOVIES
)
advanceUntilIdle()
assertThat(result.isSuccess).isTrue()
val metadata = syncMetadataRepo.getMetadata(1L)
- assertThat(metadata?.lastMovieSync ?: 0L).isGreaterThan(0L)
- assertThat(metadata?.movieSyncMode).isEqualTo(com.streamvault.domain.model.VodSyncMode.LAZY_BY_CATEGORY)
+ assertThat(metadata?.lastMovieAttempt ?: 0L).isGreaterThan(0L)
+ assertThat(metadata?.movieCatalogStale).isTrue()
+ assertThat(metadata?.movieSyncMode).isEqualTo(com.streamvault.domain.model.VodSyncMode.UNKNOWN)
+ assertThat(xtreamBackend.requestedActions).contains("get_vod_categories")
+ assertThat(xtreamBackend.requestedActions).doesNotContain("get_vod_streams")
+ val jobs = argumentCaptor<XtreamIndexJobEntity>()
+ verify(xtreamIndexJobDao, atLeastOnce()).upsert(jobs.capture())
+ assertThat(
+ jobs.allValues.any { job ->
+ job.section == "MOVIE" &&
+ job.state == "QUEUED" &&
+ job.totalCategories == 1 &&
+ job.indexedRows == 0
+ }
+ ).isTrue()
+ }
+
+ @Test
+ fun `retrySection_series_queues_xtream_index_categories_only`() = runTest {
+ val mgr = buildManager(providerType = ProviderType.XTREAM_CODES)
+ xtreamBackend.respond(
+ action = "get_series_categories",
+ body = """
+ [
+ {"category_id":"77","category_name":"Drama"}
+ ]
+ """.trimIndent()
+ )
+
+ val result = mgr.retrySection(
+ providerId = 1L,
+ section = SyncRepairSection.SERIES
+ )
+ advanceUntilIdle()
+
+ assertThat(result.isSuccess).isTrue()
+ val metadata = syncMetadataRepo.getMetadata(1L)
+ assertThat(metadata?.lastSeriesSync ?: 0L).isGreaterThan(0L)
+ assertThat(xtreamBackend.requestedActions).contains("get_series_categories")
+ assertThat(xtreamBackend.requestedActions).doesNotContain("get_series")
+ val jobs = argumentCaptor<XtreamIndexJobEntity>()
+ verify(xtreamIndexJobDao, atLeastOnce()).upsert(jobs.capture())
+ assertThat(
+ jobs.allValues.any { job ->
+ job.section == "SERIES" &&
+ job.state == "QUEUED" &&
+ job.totalCategories == 1 &&
+ job.indexedRows == 0
+ }
+ ).isTrue()
+ }
+
+ @Test
+ fun `rebuildXtreamIndex marks_existing_rows_stale_and_queues_movie_and_series_indexes`() = runTest {
+ val mgr = buildManager(providerType = ProviderType.XTREAM_CODES)
+ org.mockito.kotlin.whenever(xtreamContentIndexDao.markVodAndSeriesRowsStaleForRebuild(1L)).thenReturn(12)
+ xtreamBackend.respond(
+ action = "get_vod_categories",
+ body = """
+ [
+ {"category_id":"42","category_name":"Action"}
+ ]
+ """.trimIndent()
+ )
+ xtreamBackend.respond(
+ action = "get_series_categories",
+ body = """
+ [
+ {"category_id":"77","category_name":"Drama"}
+ ]
+ """.trimIndent()
+ )
+
+ val result = mgr.rebuildXtreamIndex(1L)
+ advanceUntilIdle()
+
+ assertThat(result.isSuccess).isTrue()
+ verify(xtreamContentIndexDao).markVodAndSeriesRowsStaleForRebuild(1L)
assertThat(xtreamBackend.requestedActions).contains("get_vod_categories")
+ assertThat(xtreamBackend.requestedActions).contains("get_series_categories")
assertThat(xtreamBackend.requestedActions).doesNotContain("get_vod_streams")
+ assertThat(xtreamBackend.requestedActions).doesNotContain("get_series")
+ val jobs = argumentCaptor<XtreamIndexJobEntity>()
+ verify(xtreamIndexJobDao, atLeastOnce()).upsert(jobs.capture())
+ assertThat(
+ jobs.allValues.any { job ->
+ job.section == "MOVIE" &&
+ job.state == "QUEUED" &&
+ job.totalCategories == 1
+ }
+ ).isTrue()
+ assertThat(
+ jobs.allValues.any { job ->
+ job.section == "SERIES" &&
+ job.state == "QUEUED" &&
+ job.totalCategories == 1
+ }
+ ).isTrue()
+ }
+
+ @Test
+ fun `processQueuedXtreamIndexJobs streams full movie index before category fallback`() = runTest {
+ val mgr = buildManager(providerType = ProviderType.XTREAM_CODES)
+ org.mockito.kotlin.whenever(
+ categoryDao.getByProviderAndTypeSync(1L, ContentType.MOVIE.name)
+ ).thenReturn(
+ listOf(
+ CategoryEntity(
+ categoryId = 42L,
+ name = "Action",
+ type = ContentType.MOVIE,
+ providerId = 1L
+ )
+ )
+ )
+ org.mockito.kotlin.whenever(xtreamIndexJobDao.get(1L, ContentType.MOVIE.name)).thenReturn(
+ XtreamIndexJobEntity(
+ providerId = 1L,
+ section = ContentType.MOVIE.name,
+ state = "QUEUED",
+ totalCategories = 1
+ )
+ )
+ org.mockito.kotlin.whenever(movieDao.getByStreamIds(eq(1L), any())).thenReturn(emptyList())
+ xtreamBackend.respond(
+ action = "get_vod_streams",
+ body = """
+ [
+ {"stream_id":100,"name":"Streamed One","category_id":"42","container_extension":"mp4"},
+ {"stream_id":101,"name":"Streamed Two","category_id":"42","container_extension":"mkv"}
+ ]
+ """.trimIndent()
+ )
+
+ val result = mgr.processQueuedXtreamIndexJobs(
+ providerId = 1L,
+ section = ContentType.MOVIE,
+ maxCategoriesPerSection = 2
+ )
+ advanceUntilIdle()
+
+ assertThat(result.isSuccess).isTrue()
+ assertThat(xtreamBackend.requestedActions).contains("get_vod_streams")
+ verify(movieDao, atLeastOnce()).insertAll(any())
+ verify(xtreamContentIndexDao, atLeastOnce()).upsertAll(any())
+ val jobs = argumentCaptor<XtreamIndexJobEntity>()
+ verify(xtreamIndexJobDao, atLeastOnce()).upsert(jobs.capture())
+ val finalMovieJob = jobs.allValues.last { it.section == ContentType.MOVIE.name }
+ assertThat(finalMovieJob.state).isEqualTo("SUCCESS")
+ assertThat(finalMovieJob.indexedRows).isEqualTo(2)
+ assertThat(finalMovieJob.nextCategoryIndex).isEqualTo(1)
}
@Test
@@ -1031,6 +1266,7 @@ class SyncManagerTest {
fun `sync_xtream_movie_failure_does_not_block_series_sync`() = runTest {
val mgr = buildManager(providerType = ProviderType.XTREAM_CODES)
val now = System.currentTimeMillis()
+ stubXtreamLiveCatalog()
syncMetadataRepo.updateMetadata(
SyncMetadata(
providerId = 1L,
@@ -1041,26 +1277,15 @@ class SyncManagerTest {
)
)
org.mockito.kotlin.whenever(movieDao.getCount(1L)).thenReturn(flowOf(0))
+ xtreamBackend.respond(action = "get_vod_categories", body = """{"error":"categories unavailable"}""", code = 500)
xtreamBackend.respond(action = "get_series_categories", body = """[{"category_id":"9","category_name":"Drama"}]""")
- xtreamBackend.respond(
- action = "get_series",
- body = """
- [
- {
- "series_id": 301,
- "name": "Series One",
- "category_id": "9",
- "cover": "https://example.com/cover.jpg"
- }
- ]
- """.trimIndent()
- )
val result = mgr.sync(1L, force = false)
advanceUntilIdle()
assertThat(result.isSuccess).isTrue()
assertThat(xtreamBackend.requestedActions).contains("get_series_categories")
+ assertThat(xtreamBackend.requestedActions).doesNotContain("get_series")
}
@Test
diff --git a/docs/xtream-index-sync-plan.md b/docs/xtream-index-sync-plan.md
new file mode 100644
index 00000000..5202d9c8
--- /dev/null
+++ b/docs/xtream-index-sync-plan.md
@@ -0,0 +1,259 @@
+# Xtream Index-First Sync Plan
+
+## Table Of Contents
+
+- [Summary](#summary)
+- [Phases](#phases)
+ - [Phase 0: Plan Document](#phase-0-plan-document)
+ - [Phase 1: Data Model And Migration](#phase-1-data-model-and-migration)
+ - [Phase 1.5: Compatibility Semantics](#phase-15-compatibility-semantics)
+ - [Phase 2: New Xtream Setup Flow](#phase-2-new-xtream-setup-flow)
+ - [Phase 3: Browse, Search, And Detail Hydration](#phase-3-browse-search-and-detail-hydration)
+ - [Phase 4: Settings Sync Redesign](#phase-4-settings-sync-redesign)
+ - [Phase 5: Background Sync And Staleness](#phase-5-background-sync-and-staleness)
+ - [Phase 6: Cleanup And Compatibility](#phase-6-cleanup-and-compatibility)
+- [Acceptance Criteria](#acceptance-criteria)
+- [Public API / Type Changes](#public-api--type-changes)
+- [Test Plan](#test-plan)
+- [Assumptions And Defaults](#assumptions-and-defaults)
+
+## Summary
+
+Replace the current Xtream full-sync and fast/on-demand category-sync model with an index-first architecture.
+
+Provider setup becomes usable after:
+
+- Xtream authentication succeeds.
+- Live TV categories and the full live channel catalog are loaded.
+- VOD and series categories are loaded.
+- Background jobs are queued for VOD/series summary indexing and EPG.
+
+VOD/series search and browse will use thin summary rows first. Rich movie details, series seasons, and episodes hydrate only when the user opens or plays an item. Existing Xtream providers and already-synced data are preserved and backfilled into the new index model.
+
+Xtream endpoint assumptions are based on the common Player API shape: `get_live_streams`, `get_vod_streams`, `get_series`, category endpoints, `get_vod_info`, `get_series_info`, `get_short_epg`, and XMLTV.
+
+Reference docs:
+
+- https://servextex.github.io/xtream-ui-ubuntu/player_api_documentacion.html
+- https://xtream-masters.com/api-doc/player_api.php
+- https://ottpanel.tv/player_api.html
+
+## Phases
+
+### Phase 0: Plan Document
+
+- Create `docs/xtream-index-sync-plan.md` with this phased plan.
+- Treat this document as the source of truth for later edits before implementation starts.
+- Scope this redesign to Xtream only. Do not redesign M3U or Stalker behavior in this project.
+
+### Phase 1: Data Model And Migration
+
+- Add a dedicated Xtream content index table for `LIVE`, `MOVIE`, and `SERIES` summaries.
+- Store, at minimum: provider id, content type, remote id, optional local content id, name, category id/name, image URL, rating, added/modified timestamp, adult flag, indexed timestamp, detail hydrated timestamp, stale/error state, and sync fingerprint.
+- Store image URLs only, not poster/logo bytes. Poster/logo files remain lazy-loaded by the app image loader/cache when rows are displayed.
+- Track index job state per provider and section (`LIVE`, `MOVIE`, `SERIES`, `EPG`) with states: `IDLE`, `QUEUED`, `RUNNING`, `PARTIAL`, `SUCCESS`, `FAILED_RETRYABLE`, `FAILED_PERMANENT`, and `STALE`.
+- Store progress counters where applicable: total categories, completed categories, failed categories, indexed rows, skipped malformed rows, deleted/pruned rows, last error, last attempt time, and last success time.
+- Keep existing `channels`, `movies`, `series`, and `episodes` tables as the cached playable/detail tables.
+- For VOD/series, also upsert summary rows into existing `movies`/`series` tables so current navigation, favorites, playback history, and repository APIs keep stable local ids.
+- The separate index table is the source for cross-content search, section freshness, and indexing status. The existing content tables remain the source for current screen APIs, stable local ids, favorites, playback history, and detail/playback caching.
+- Add row state fields to VOD/series cached rows: `SUMMARY_ONLY`, `DETAIL_HYDRATED`, `STALE`.
+- Backfill the new index from existing Xtream `channels`, `movies`, and `series` rows during migration.
+- Preserve existing provider rows, favorites, playback history, watch progress, hidden categories, protected categories, and EPG mappings.
+- Batch DB writes during migration/backfill to avoid long UI-blocking transactions and reduce WAL growth.
+- Add maintenance support for pruning orphan index rows whose provider/local content rows were deleted outside normal sync.
+
+### Phase 1.5: Compatibility Semantics
+
+- Preserve old Xtream provider records and translate old sync settings into the new model.
+- Treat `xtreamFastSyncEnabled` as migration-only compatibility state. Existing `true` and `false` values should both map to the new index-first behavior.
+- Alias old `VodSyncMode` values into new section/index status:
+ - `FULL`, `CATEGORY_BULK`, and `PAGED` become "indexed/hydrated from legacy catalog" when local rows exist.
+ - `LAZY_BY_CATEGORY` becomes "categories available, index pending/stale".
+ - `UNKNOWN` becomes "index pending" unless local rows can be backfilled.
+- Existing cached VOD/series rows should be kept and marked `DETAIL_HYDRATED` when they contain rich fields, otherwise `SUMMARY_ONLY`.
+- Existing category hydration metadata should not be trusted as the new indexing source of truth, but it may be used to seed freshness hints.
+- Do not force users to re-add providers or manually rebuild libraries after migration.
+- Never clear existing VOD/series data at the start of migration or indexing.
+- During incremental sync and migration, remote-missing rows should be marked stale first, not deleted immediately.
+- Do not prune rows referenced by active playback history, favorites, custom groups, or in-progress playback unless the user explicitly deletes/clears data.
+- When a remote id reappears, revive the existing local row and preserve local id, favorites, history, and watch progress.
+
+### Phase 2: New Xtream Setup Flow
+
+- Remove the setup-time Fast Sync toggle for Xtream.
+- Replace `xtreamFastSyncEnabled` behavior with the new default index-first flow.
+- Xtream add-provider should block only on:
+ - authentication,
+ - live categories,
+ - full live channel catalog,
+ - VOD categories,
+ - series categories.
+- After that, mark the provider active or partial and return to the app.
+- Queue background work for:
+ - VOD summary index from `get_vod_streams`,
+ - series summary index from `get_series`,
+ - EPG sync according to provider EPG mode.
+- VOD/series index jobs should stream/parse large Xtream list responses where possible and commit summary rows in batches. Do not wait for the entire response to finish before making rows visible.
+- If unfiltered VOD/series list endpoints fail, are too large, or time out, fall back to background category-by-category indexing without blocking setup.
+- Live TV remains fully loaded upfront because `get_live_streams` already returns the usable live catalog needed for playback, search, EPG mapping, catch-up flags, and Android TV input sync.
+- Failure policy during setup:
+ - Auth failure marks provider setup failed/permanent and does not queue indexing.
+ - Response-too-large on VOD/series full-list indexing marks that strategy unavailable and queues category fallback.
+ - Network/timeouts mark queued background work retryable and preserve any setup data already saved.
+- Setup must not delete existing catalog/index rows for an edited existing provider unless the user explicitly deletes the provider.
+- Setup should publish queued/running section state so Settings/Search/VOD can immediately show that VOD/series indexing is in progress.
+
+### Phase 3: Browse, Search, And Detail Hydration
+
+- Search should return live, movie, and series results from the summary index / summary-backed local rows.
+- Search must run against all indexed rows for the provider/scope, not only rows visible in the currently loaded UI page or preview batch.
+- Search result pagination should page the ranked indexed result set. Loading more search results must not require opening categories.
+- If indexing is still in progress, search should return all currently indexed matches and expose an indexing/partial state so the UI can distinguish "still indexing" from "no results".
+- If a provider falls back to category-by-category indexing, matching items become searchable as their categories are indexed. The global search surface should update incrementally.
+- VOD and series category screens should show indexed summary rows immediately when available.
+- Category click should not trigger full rich hydration. It may trigger a background freshness check for that category.
+- Category pagination should page summary rows from the index/local summary rows first.
+- If a category has not been indexed yet, clicking it should enqueue/prioritize that category's index job and show a loading/partial state, not an empty "no content" state.
+- If global VOD/series indexing is already running, user-selected categories should be moved to the front of the remaining index queue without cancelling successfully indexed work.
+- Search cards and category cards should show poster/logo images when the summary row has an image URL. If the URL is blank or fails, show the existing placeholder. Later detail hydration may replace the image URL and refresh the UI.
+- Movie detail open should call `get_vod_info`, merge richer fields into the cached movie row, and mark it `DETAIL_HYDRATED`.
+- Series detail open should call `get_series_info`, merge richer series fields, persist seasons/episodes, and mark it `DETAIL_HYDRATED`.
+- Movie playback may use the indexed stream id and container extension to build the internal playback URL. If required playback fields are missing, hydrate details first.
+- Series playback should require series detail hydration because episodes come from `get_series_info`.
+- Existing continue watching, favorites, related content, and recommendations should continue using local cached rows, now backed by summary-first data.
+- Detail freshness rules:
+ - Movie details and series details hydrate on open/play.
+ - Details should not be refreshed on every open.
+ - Default detail refresh TTL: 14 days, unless the user manually refreshes, the item is stale/missing required playback fields, or the provider reports a newer modified timestamp.
+- Detail hydration failures should keep summary rows usable and mark only the detail state failed/retryable.
+- Empty search while indexing is active should say the library is still indexing rather than implying no content exists.
+- Category browse should expose retry affordance if that category failed to index.
+- Search/category screens should not trigger destructive pruning. They may only enqueue/prioritize index or detail work.
+
+### Phase 4: Settings Sync Redesign
+
+- Replace Xtream Full/Fast sync options with:
+ - `Sync Now`: incremental sync for stale live, categories, VOD index, series index, and EPG.
+ - `Rebuild Index`: rebuild VOD/series summary indexes from Xtream, preserving hydrated detail rows where remote ids still exist.
+ - `Live TV`: refresh live categories and full live channel catalog.
+ - `Movies`: refresh movie categories and movie summary index.
+ - `Series`: refresh series categories and series summary index.
+ - `EPG`: enqueue or run EPG sync.
+- Remove foreground full VOD import and fast lazy category-only as user-facing Xtream modes.
+- Keep internal recovery strategies only as background indexing fallbacks, not as separate product modes.
+- Settings progress should report background-safe states: queued, indexing, indexed count, stale, partial, failed, retrying.
+- Manual section syncs should use the same index-first pipeline as setup and background sync.
+- Manual `Rebuild Index` should mark rows missing from the latest successful section scan as `STALE_REMOTE`, but prune only after a complete successful rebuild confirms absence.
+- Rebuild Index must preserve hydrated details for unchanged remote ids and preserve stable local ids whenever possible.
+- Section sync failures from Settings should preserve previous visible content and update section status/error metadata.
+- Settings must show enough state to distinguish queued, running, partial, stale, retryable failed, and permanent failed work.
+
+### Phase 5: Background Sync And Staleness
+
+- Reuse WorkManager as the scheduling backbone.
+- Add or refactor workers so Xtream catalog sync can run by section: live, movie index, series index, EPG.
+- On app launch, enqueue a non-blocking stale check for active Xtream providers.
+- Periodic provider sync should:
+ - refresh stale live catalog,
+ - refresh stale VOD/series indexes,
+ - refresh EPG when due,
+ - avoid blocking UI startup.
+- Default TTLs:
+ - live catalog: 24 hours,
+ - VOD summary index: 24 hours,
+ - series summary index: 24 hours,
+ - EPG: 6 hours,
+ - detail hydration: refresh only on explicit open if stale or missing.
+- Use network-connected constraints, exponential backoff, retryable failure classification, and low-memory deferral where relevant.
+- Partial failures should preserve previous indexed data and mark the failed section stale/error instead of clearing user-visible libraries.
+- Index workers should publish progress after each committed batch: indexed count, current section, optional current category, and whether results are complete or partial.
+- Index workers should use batch commits so search/category UI can observe newly indexed rows while long VOD/series indexing continues.
+- Index freshness:
+ - Live catalog TTL: 24 hours.
+ - Movie summary index TTL: 24 hours.
+ - Series summary index TTL: 24 hours.
+ - EPG TTL: 6 hours.
+- Failure policy:
+ - HTTP 401/403 on auth/root catalog requests is permanent until credentials/settings change.
+ - HTTP 408/409/429/5xx, network loss, DNS failure, connection reset, and timeout are retryable.
+ - Malformed whole-response JSON marks the section partial/failed and keeps old data.
+ - Malformed individual streamed items are skipped, counted, and do not stop the whole job.
+ - Empty valid results do not delete old rows unless a complete successful rebuild confirms true absence.
+- Deletion policy:
+ - Incremental sync may mark missing rows `STALE_REMOTE`.
+ - Only complete successful rebuilds may prune remote-missing rows.
+ - Partial/category indexing may only update stale status for categories that completed successfully.
+- Concurrency policy:
+ - Default to one heavy Xtream indexing request per provider at a time.
+ - Do not run VOD and series full-list heavy indexing in parallel for the same provider by default.
+ - Use adaptive concurrency only for category fallback, starting conservatively and reducing to sequential after rate limits, timeouts, response-too-large, or repeated provider stress.
+ - Do not let background indexing compete with active playback for network/CPU. If needed, pause/defer non-urgent indexing during playback.
+
+### Phase 6: Cleanup And Compatibility
+
+- Deprecate/remove Xtream full/category-bulk/paged foreground sync branches once the new index pipeline is stable.
+- Remove `LAZY_BY_CATEGORY` as a user-facing Xtream outcome.
+- Keep compatibility aliases in metadata migrations so old providers do not break.
+- Update setup and settings strings to remove old Fast Sync language.
+- Keep M3U and Stalker sync behavior unchanged.
+- After implementation, run `graphify update .` because code files will have changed.
+
+## Acceptance Criteria
+
+- Adding an Xtream provider completes after auth, live catalog, VOD categories, and series categories, without waiting for full VOD/series indexing.
+- Live TV is playable and searchable immediately after setup succeeds.
+- VOD/series categories appear immediately after setup succeeds.
+- VOD search finds items from unvisited categories after the summary index completes.
+- If indexing is still running, search and category screens clearly show partial/indexing state.
+- Opening a movie hydrates rich details once, persists them, and does not refetch on every open.
+- Opening a series hydrates seasons/episodes, persists them, and preserves local ids on refresh.
+- Existing Xtream providers migrate without re-adding credentials and preserve favorites, history, watch progress, protected/hidden categories, and EPG mappings.
+- Background sync never blocks app launch.
+- Failed refreshes preserve previous visible content.
+- Rebuild Index can repair stale/bad index state without wiping user data on partial failure.
+
+## Public API / Type Changes
+
+- Add index status models for summary indexing and detail hydration.
+- Replace Xtream setup command usage of `xtreamFastSyncEnabled` with an index-first default; keep the stored field only as migration compatibility until later cleanup.
+- Extend sync metadata with last-success/attempt fields for live index, movie index, series index, and per-section stale/error state.
+- Add sync commands for `SYNC_NOW`, `REBUILD_INDEX`, `LIVE`, `MOVIES`, `SERIES`, and `EPG`.
+- Add repository behavior for summary-backed VOD/series rows and detail hydration on open/play.
+
+## Test Plan
+
+- Migration tests:
+ - Existing Xtream movie/series/channel rows backfill index rows.
+ - Favorites, history, watched progress, and protected categories survive migration.
+- Setup tests:
+ - Xtream add-provider completes after live + categories and queues background VOD/series/EPG work.
+ - VOD list endpoint failure falls back to queued category indexing without failing provider setup.
+- Indexing tests:
+ - `get_vod_streams` summaries upsert movie summary rows and searchable index rows.
+ - `get_series` summaries upsert series summary rows and searchable index rows.
+ - Rebuild index preserves hydrated details for unchanged remote ids.
+- Browse/search tests:
+ - Search finds unvisited VOD/series categories after summary indexing.
+ - Category screens show summary rows without rich detail hydration.
+ - Live search remains available after live catalog sync.
+- Detail tests:
+ - Opening movie detail calls `get_vod_info` once when missing/stale and persists enriched fields.
+ - Opening series detail calls `get_series_info`, persists episodes, and marks detail hydrated.
+ - Playback hydrates first only when required playback fields are missing.
+- Background tests:
+ - Launch stale check enqueues work without blocking UI.
+ - Periodic sync refreshes only stale sections.
+ - Retryable failures use WorkManager retry; permanent auth/config failures mark section error.
+- UI tests:
+ - Setup no longer shows Xtream Fast Sync.
+ - Settings shows Sync Now, Rebuild Index, Live TV, Movies, Series, and EPG.
+ - Sync progress/status reflects queued/indexing/partial states.
+
+## Assumptions And Defaults
+
+- Xtream-only redesign; do not alter M3U or Stalker sync architecture.
+- Existing local content is preserved and indexed, not wiped.
+- Live TV loads full usable channel rows upfront.
+- Live TV still participates in the shared content index for search/status, but the live channel table remains the usable playback catalog.
+- VOD/series rich details hydrate on open/play, not for the entire library in background.
+- Background category-by-category indexing is a fallback for providers whose full VOD/series list endpoints fail.
diff --git a/docs/xtream-live-onboarding-plan.md b/docs/xtream-live-onboarding-plan.md
new file mode 100644
index 00000000..bbfe908c
--- /dev/null
+++ b/docs/xtream-live-onboarding-plan.md
@@ -0,0 +1,194 @@
+# Xtream Live Onboarding Reliability Plan
+
+## Table Of Contents
+
+- [Summary](#summary)
+- [Plan](#plan)
+- [Implementation Order](#implementation-order)
+- [What Improves Weak-Device Reliability](#what-improves-weak-device-reliability)
+- [What Improves Add-Provider Speed](#what-improves-add-provider-speed)
+- [Xtream Live Thin-Row Follow-Up](#xtream-live-thin-row-follow-up)
+- [Validation Criteria](#validation-criteria)
+- [Open Questions](#open-questions)
+
+## Summary
+
+This document captures the planned Xtream Live onboarding redesign focused on correctness first, with explicit attention to weak-device behavior and large Live catalogs.
+
+The current risk areas are:
+
+- provider add can depend on a long Live import completing in one uninterrupted run,
+- Xtream Live finalization logic is split across multiple paths,
+- slow or interrupted devices can be exposed to broken partial outcomes,
+- provider setup can look complete even when Live import is not yet safely usable.
+
+The main goal is to make provider add finish in a correct and durable state, especially for large Xtream Live catalogs. A secondary goal is to enable a later usable-first onboarding flow that can improve perceived setup speed.
+
+## Plan
+
+1. Stabilize the validation baseline first.
+Resolve the current app compile failure so every refactor can be checked quickly with `SyncManager.kt`, `ProviderRepositoryImpl.kt`, and related tests. This is not part of the provider-add fix itself, but without a clean compile loop the rest will be slower and riskier.
+
+2. Define the Live onboarding invariants in the sync layer.
+Write down and enforce the rules the code must satisfy before provider add is considered complete:
+- Xtream Live onboarding must not finish in a state where Live categories are committed but usable Live channels are not.
+- A staged full-catalog success must commit staged rows, not depend on any empty in-memory fallback list.
+- Category-fallback success, partial success, and full success must all flow through one commit contract.
+This work belongs around `SyncManager.kt`, `SyncManagerXtreamLiveStrategy.kt`, and `SyncCatalogStore.kt`.
+
+3. Extract one shared Xtream Live commit pipeline.
+Create a single internal helper that owns all Xtream Live finalization behavior:
+- interpret `stagedSessionId`
+- merge visible and hidden categories
+- choose replace versus upsert semantics
+- apply staged imports or direct imports
+- return accepted count and final sync warnings
+Both the initial onboarding path and the Live-only retry path should call this same helper instead of having separate success logic in `SyncManager.kt`.
+
+4. Refactor the initial add-provider flow to use the shared Live commit pipeline.
+Keep the current Xtream strategy selection and staging logic, but route onboarding completion through the same commit helper as retries. The immediate goal is that a slow device, fallback path, or staged full import cannot end in a categories-only Live state during provider add.
+
+5. Make initial Live import resumable instead of fragile.
+Treat provider add as a resumable onboarding import job:
+- persist enough onboarding state to know whether initial Live import is still in progress
+- retain staged Live import data until committed or explicitly discarded
+- resume interrupted onboarding after process death or app restart
+Only this step materially improves weak-device reliability, because it removes the assumption that provider add must finish in one uninterrupted foreground run.
+
+6. Separate provider persistence from provider usability.
+Keep saving provider credentials and metadata, but do not expose the provider as fully active/ready until the initial Live import reaches the invariant from step 2. This means changing behavior in `ProviderRepositoryImpl.kt` so “saved” and “usable” are not treated as the same thing.
+
+7. Adjust onboarding UI only after the backend flow is correct.
+Once the sync path is reliable, update `app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupViewModel.kt` so the screen reflects real import state:
+- initial import in progress
+- initial import resumable
+- provider ready
+- provider saved but still completing import
+This is not the core fix, but it needs to align with the backend once the backend semantics change.
+
+8. Add hard regression tests around the real failure modes.
+Cover these cases:
+- initial Xtream onboarding full staged success commits staged Live rows
+- initial Xtream onboarding category fallback commits usable Live rows
+- provider add cannot finish ready with Live categories and zero committed Live channels unless the source is explicitly empty
+- interrupted onboarding resumes safely
+- retry and onboarding both use the same Live commit path
+Target files are `SyncManagerTest.kt`, `ProviderSetupViewModelTest.kt`, and any focused new sync tests if the current file gets too large.
+
+9. Add diagnostic logging around provider-add Live import.
+Log only what is needed to diagnose real-device failures:
+- full versus category fallback chosen
+- category count
+- accepted Live row count
+- staged session created, applied, discarded
+- elapsed time for each major phase
+- resume versus fresh onboarding
+This is not a workaround. It is necessary to verify whether the final design actually fixes Chromecast-class failures.
+
+10. Validate on both strong and weak environments.
+Run validation in this order:
+- local focused sync tests
+- targeted compile checks
+- emulator onboarding with a very large Xtream provider
+- real Chromecast or comparable low-resource TV device onboarding with the same provider
+The success criterion is not just “no error shown.” It is:
+- provider add completes
+- Live categories appear
+- Live counts are non-zero when provider data is non-empty
+- app survives slow import or resumes cleanly if interrupted
+
+## Implementation Order
+
+1. Fix compile baseline.
+2. Extract shared Xtream Live commit helper.
+3. Switch onboarding and retry paths to the shared helper.
+4. Introduce resumable initial Live onboarding state.
+5. Separate saved versus ready provider semantics.
+6. Update onboarding UI contract.
+7. Add regression tests.
+8. Validate on emulator and real weak device.
+
+## What Improves Weak-Device Reliability
+
+These are the parts of the plan that directly help weaker or interruption-prone devices:
+
+1. Resumable initial Live import.
+This is the largest reliability improvement. Slow devices are more likely to be interrupted, paused, backgrounded, or reclaimed during a long provider-add run.
+
+2. Shared, correct Xtream Live commit logic.
+Weak devices are more likely to exercise fallback and staged paths. A single commit pipeline reduces the chance of invalid final state under stress.
+
+3. Finalize provider readiness only after a valid Live state.
+This prevents slow devices from exposing categories-with-zero-channels as if setup completed successfully.
+
+4. Proper use of staged import for onboarding.
+This reduces the damage caused by long-running work, interruptions, and alternate strategy paths.
+
+## What Improves Add-Provider Speed
+
+The main plan above is reliability-first. These additions are the ones that would make add-provider feel faster for Live TV:
+
+1. Make onboarding usable-first instead of full-library-first.
+Authenticate, import Live categories, import an initial usable Live slice, then let the user into Live TV while the rest continues in background.
+
+2. Separate provider-added from full Live hydration.
+Provider setup should complete when the provider is usable, not only when every Live row is imported.
+
+3. Commit the first usable staged slice early.
+Do not wait for the full Live catalog when a meaningful first batch can make browsing possible.
+
+4. Defer noncritical work out of the setup critical path.
+Anything not required for initial Live browse should not block add-provider completion.
+
+5. Keep resumability even in the faster flow.
+Usable-first onboarding still needs resumable import so weak devices do not restart large work from zero.
+
+## Xtream Live Thin-Row Follow-Up
+
+Xtream Live row thinning is a valid follow-up optimization, but it is not the first fix for the current onboarding failure mode.
+
+The sequencing decision is:
+
+1. First fix correctness and durability.
+Shared commit logic, resumable onboarding, and correct ready-state semantics matter more than row width for the reported provider-add failure.
+
+2. Then optimize Xtream Live storage for the hot path.
+If add-provider speed is still not good enough after the reliability work, Xtream Live can move toward a thinner persisted row shape.
+
+3. Prefer a compatibility-preserving implementation first.
+The safest first version is to keep the current `channels` table schema and have Xtream fast sync populate only the core columns during onboarding, while deferring noncritical fields until later hydration.
+
+The practical thin-row guidance for Xtream Live is:
+
+- keep as core: `providerId`, `streamId`, `name`, `categoryId`, `epgChannelId`, `logoUrl`, `number`, `isAdult`, minimal catch-up flags, compact `syncFingerprint`
+- prefer to derive or defer: `categoryName`, full playable `streamUrl`, quality metadata, playback/runtime error stats
+- keep M3U-oriented fields such as `groupTitle` out of the Xtream fast-sync hot path unless a shared schema requires them
+
+Compatibility guidance:
+
+1. App-update compatibility can be preserved.
+If the thinning work is done with normal Room migration support, users updating from older versions can be migrated safely.
+
+2. Old-app downgrade compatibility should not be assumed.
+Once a newer version changes the database schema, an older app version usually will not be able to reopen that upgraded database unless explicit downgrade support is built.
+
+3. Deferred-population on the existing schema is the lowest-risk path.
+This approach improves Xtream add-provider performance without forcing an immediate schema split across Xtream, M3U, Stalker, player, and preference code.
+
+## Validation Criteria
+
+The final design should satisfy all of the following:
+
+- adding a provider cannot finish in a categories-only Live state when the source has usable Live channels,
+- staged full Live success and category fallback both produce valid committed Live rows,
+- interrupted onboarding either resumes or stays clearly incomplete instead of silently breaking the provider,
+- weak devices do not require special-case logic to avoid invalid final state,
+- if a usable-first onboarding path is added, time-to-first-usable-Live improves without sacrificing catalog correctness.
+
+## Open Questions
+
+1. Should provider add remain blocked on full Live hydration, or should the product explicitly move to a usable-first Live onboarding model?
+2. What minimum Live threshold should count as “usable” if setup is allowed to complete before full hydration?
+3. Should interrupted onboarding auto-resume on next launch, or require an explicit user confirmation when the provider is saved but incomplete?
+4. How much telemetry is acceptable in release builds for diagnosing slow-device onboarding failures without creating noisy logs?
+5. If add-provider speed becomes a product priority, should category priority be based on provider ordering, first visible categories, or a fixed bootstrap slice such as All Channels plus the first N categories?
\ No newline at end of file
diff --git a/domain/src/main/java/com/streamvault/domain/manager/ProviderSyncStateReader.kt b/domain/src/main/java/com/streamvault/domain/manager/ProviderSyncStateReader.kt
index ed4ccc55..6bf19208 100644
--- a/domain/src/main/java/com/streamvault/domain/manager/ProviderSyncStateReader.kt
+++ b/domain/src/main/java/com/streamvault/domain/manager/ProviderSyncStateReader.kt
@@ -1,7 +1,9 @@
package com.streamvault.domain.manager
import com.streamvault.domain.model.SyncState
+import kotlinx.coroutines.flow.Flow
interface ProviderSyncStateReader {
fun currentSyncState(providerId: Long): SyncState
-}
\ No newline at end of file
+ fun observeBackgroundIndexingActive(providerId: Long): Flow<Boolean>
+}
diff --git a/domain/src/main/java/com/streamvault/domain/repository/SearchRepository.kt b/domain/src/main/java/com/streamvault/domain/repository/SearchRepository.kt
new file mode 100644
index 00000000..5f624a82
--- /dev/null
+++ b/domain/src/main/java/com/streamvault/domain/repository/SearchRepository.kt
@@ -0,0 +1,29 @@
+package com.streamvault.domain.repository
+
+import com.streamvault.domain.model.Channel
+import com.streamvault.domain.model.Movie
+import com.streamvault.domain.model.Series
+import kotlinx.coroutines.flow.Flow
+
+data class SearchRepositoryResult(
+ val channels: List<Channel> = emptyList(),
+ val movies: List<Movie> = emptyList(),
+ val series: List<Series> = emptyList()
+)
+
+interface SearchRepository {
+ fun searchContent(
+ providerId: Long,
+ query: String,
+ includeLive: Boolean,
+ includeMovies: Boolean,
+ includeSeries: Boolean,
+ maxResultsPerSection: Int
+ ): Flow<SearchRepositoryResult>
+
+ fun searchChannels(providerId: Long, query: String): Flow<List<Channel>>
+
+ fun searchMovies(providerId: Long, query: String): Flow<List<Movie>>
+
+ fun searchSeries(providerId: Long, query: String): Flow<List<Series>>
+}
diff --git a/domain/src/main/java/com/streamvault/domain/usecase/SearchContent.kt b/domain/src/main/java/com/streamvault/domain/usecase/SearchContent.kt
index f9a8a30c..113826fc 100644
--- a/domain/src/main/java/com/streamvault/domain/usecase/SearchContent.kt
+++ b/domain/src/main/java/com/streamvault/domain/usecase/SearchContent.kt
@@ -1,11 +1,12 @@
package com.streamvault.domain.usecase
+import com.streamvault.domain.manager.ProviderSyncStateReader
import com.streamvault.domain.model.Channel
import com.streamvault.domain.model.Movie
import com.streamvault.domain.model.Series
-import com.streamvault.domain.repository.ChannelRepository
-import com.streamvault.domain.repository.MovieRepository
-import com.streamvault.domain.repository.SeriesRepository
+import com.streamvault.domain.model.SyncState
+import com.streamvault.domain.repository.SearchRepository
+import com.streamvault.domain.repository.SearchRepositoryResult
import com.streamvault.domain.util.shouldRethrowDomainFlowFailure
import java.util.logging.Level
import java.util.logging.Logger
@@ -13,8 +14,10 @@ import javax.inject.Inject
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.combine
+import kotlinx.coroutines.flow.first
+import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOf
-import kotlinx.coroutines.flow.map
+import kotlinx.coroutines.withTimeoutOrNull
enum class SearchContentScope {
ALL,
@@ -31,10 +34,13 @@ data class SearchContentResult(
)
class SearchContent @Inject constructor(
- private val channelRepository: ChannelRepository,
- private val movieRepository: MovieRepository,
- private val seriesRepository: SeriesRepository
+ private val searchRepository: SearchRepository,
+ private val providerSyncStateReader: ProviderSyncStateReader
) {
+ private companion object {
+ const val SEARCH_RESPONSE_TIMEOUT_MS = 2_500L
+ }
+
private val logger = Logger.getLogger("SearchContent")
operator fun invoke(
@@ -49,46 +55,52 @@ class SearchContent @Inject constructor(
}
return combine(
- if (scope == SearchContentScope.ALL || scope == SearchContentScope.LIVE) {
- channelRepository.searchChannels(providerId, normalizedQuery)
- .map { it to false }
- .catch { error ->
- if (error.shouldRethrowDomainFlowFailure()) throw error
- logger.log(Level.WARNING, "Channel search section failed", error)
- emit(emptyList<Channel>() to true)
- }
- } else {
- flowOf(emptyList<Channel>() to false)
- },
- if (scope == SearchContentScope.ALL || scope == SearchContentScope.MOVIES) {
- movieRepository.searchMovies(providerId, normalizedQuery)
- .map { it to false }
- .catch { error ->
- if (error.shouldRethrowDomainFlowFailure()) throw error
- logger.log(Level.WARNING, "Movie search section failed", error)
- emit(emptyList<Movie>() to true)
- }
- } else {
- flowOf(emptyList<Movie>() to false)
- },
- if (scope == SearchContentScope.ALL || scope == SearchContentScope.SERIES) {
- seriesRepository.searchSeries(providerId, normalizedQuery)
- .map { it to false }
- .catch { error ->
- if (error.shouldRethrowDomainFlowFailure()) throw error
- logger.log(Level.WARNING, "Series search section failed", error)
- emit(emptyList<Series>() to true)
- }
- } else {
- flowOf(emptyList<Series>() to false)
+ contentSearchFlow(providerId, normalizedQuery, scope, maxResultsPerSection),
+ providerSyncStateReader.observeBackgroundIndexingActive(providerId)
+ ) { searchResult, indexWorkActive ->
+ val (result, searchDegraded) = searchResult
+ val indexingActive = when (providerSyncStateReader.currentSyncState(providerId)) {
+ is SyncState.Syncing,
+ is SyncState.Partial -> true
+ else -> false
}
- ) { (channels, channelsDegraded), (movies, moviesDegraded), (series, seriesDegraded) ->
SearchContentResult(
- channels = channels.take(maxResultsPerSection),
- movies = movies.take(maxResultsPerSection),
- series = series.take(maxResultsPerSection),
- isPartialResult = channelsDegraded || moviesDegraded || seriesDegraded
+ channels = result.channels,
+ movies = result.movies,
+ series = result.series,
+ isPartialResult = searchDegraded || indexingActive || indexWorkActive
)
}
}
-}
\ No newline at end of file
+
+ private fun contentSearchFlow(
+ providerId: Long,
+ query: String,
+ scope: SearchContentScope,
+ maxResultsPerSection: Int
+ ): Flow<Pair<SearchRepositoryResult, Boolean>> =
+ flow {
+ val result = withTimeoutOrNull(SEARCH_RESPONSE_TIMEOUT_MS) {
+ searchRepository.searchContent(
+ providerId = providerId,
+ query = query,
+ includeLive = scope == SearchContentScope.ALL || scope == SearchContentScope.LIVE,
+ includeMovies = scope == SearchContentScope.ALL || scope == SearchContentScope.MOVIES,
+ includeSeries = scope == SearchContentScope.ALL || scope == SearchContentScope.SERIES,
+ maxResultsPerSection = maxResultsPerSection
+ ).first()
+ }
+
+ if (result == null) {
+ logger.warning("Search timed out for provider $providerId and query '$query'")
+ emit(SearchRepositoryResult() to true)
+ } else {
+ emit(result to false)
+ }
+ }
+ .catch { error ->
+ if (error.shouldRethrowDomainFlowFailure()) throw error
+ logger.log(Level.WARNING, "Unified content search failed", error)
+ emit(SearchRepositoryResult() to true)
+ }
+}
diff --git a/domain/src/main/java/com/streamvault/domain/usecase/ValidateAndAddProvider.kt b/domain/src/main/java/com/streamvault/domain/usecase/ValidateAndAddProvider.kt
index eae33f56..1868ece1 100644
--- a/domain/src/main/java/com/streamvault/domain/usecase/ValidateAndAddProvider.kt
+++ b/domain/src/main/java/com/streamvault/domain/usecase/ValidateAndAddProvider.kt
@@ -16,7 +16,7 @@ data class XtreamProviderSetupCommand(
val username: String,
val password: String,
val name: String,
- val xtreamFastSyncEnabled: Boolean = true,
+ val xtreamFastSyncEnabled: Boolean = false,
val epgSyncMode: ProviderEpgSyncMode = ProviderEpgSyncMode.BACKGROUND,
val existingProviderId: Long? = null
)
@@ -165,7 +165,7 @@ class ValidateAndAddProvider @Inject constructor(
username = parsedXtream.username,
password = parsedXtream.password,
name = validatedInput.name,
- xtreamFastSyncEnabled = true,
+ xtreamFastSyncEnabled = false,
epgSyncMode = command.epgSyncMode,
onProgress = onProgress,
id = command.existingProviderId
diff --git a/domain/src/test/java/com/streamvault/domain/usecase/GetContinueWatchingTest.kt b/domain/src/test/java/com/streamvault/domain/usecase/GetContinueWatchingTest.kt
index b92ba205..c8d81965 100644
--- a/domain/src/test/java/com/streamvault/domain/usecase/GetContinueWatchingTest.kt
+++ b/domain/src/test/java/com/streamvault/domain/usecase/GetContinueWatchingTest.kt
@@ -182,7 +182,14 @@ class GetContinueWatchingTest {
return historyFlow ?: flowOf(multiProviderHistory.filter { it.providerId in providerIds }.take(limit))
}
override fun getUnwatchedCount(providerId: Long, seriesId: Long): Flow<Int> = flowOf(0)
- override suspend fun getPlaybackHistory(contentId: Long, contentType: ContentType, providerId: Long): PlaybackHistory? = null
+ override suspend fun getPlaybackHistory(
+ contentId: Long,
+ contentType: ContentType,
+ providerId: Long,
+ seriesId: Long?,
+ seasonNumber: Int?,
+ episodeNumber: Int?
+ ): PlaybackHistory? = null
override suspend fun markAsWatched(history: PlaybackHistory) = com.streamvault.domain.model.Result.success(Unit)
override suspend fun recordPlayback(history: PlaybackHistory) = com.streamvault.domain.model.Result.success(Unit)
override suspend fun updateResumePosition(history: PlaybackHistory) = com.streamvault.domain.model.Result.success(Unit)
diff --git a/domain/src/test/java/com/streamvault/domain/usecase/MarkAsWatchedTest.kt b/domain/src/test/java/com/streamvault/domain/usecase/MarkAsWatchedTest.kt
index 2614f744..44c72e1f 100644
--- a/domain/src/test/java/com/streamvault/domain/usecase/MarkAsWatchedTest.kt
+++ b/domain/src/test/java/com/streamvault/domain/usecase/MarkAsWatchedTest.kt
@@ -52,7 +52,14 @@ class MarkAsWatchedTest {
override fun getRecentlyWatchedByProvider(providerId: Long, limit: Int): Flow<List<PlaybackHistory>> = flowOf(emptyList())
override fun getRecentlyWatchedByProviders(providerIds: Set<Long>, limit: Int): Flow<List<PlaybackHistory>> = flowOf(emptyList())
override fun getUnwatchedCount(providerId: Long, seriesId: Long): Flow<Int> = flowOf(0)
- override suspend fun getPlaybackHistory(contentId: Long, contentType: ContentType, providerId: Long): PlaybackHistory? = null
+ override suspend fun getPlaybackHistory(
+ contentId: Long,
+ contentType: ContentType,
+ providerId: Long,
+ seriesId: Long?,
+ seasonNumber: Int?,
+ episodeNumber: Int?
+ ): PlaybackHistory? = null
override suspend fun markAsWatched(history: PlaybackHistory): com.streamvault.domain.model.Result<Unit> {
lastMarkedHistory = history
return com.streamvault.domain.model.Result.success(Unit)
diff --git a/domain/src/test/java/com/streamvault/domain/usecase/SearchContentTest.kt b/domain/src/test/java/com/streamvault/domain/usecase/SearchContentTest.kt
index 0645eefb..07e3c182 100644
--- a/domain/src/test/java/com/streamvault/domain/usecase/SearchContentTest.kt
+++ b/domain/src/test/java/com/streamvault/domain/usecase/SearchContentTest.kt
@@ -1,21 +1,19 @@
package com.streamvault.domain.usecase
import com.google.common.truth.Truth.assertThat
-import com.streamvault.domain.model.Category
+import com.streamvault.domain.manager.ProviderSyncStateReader
import com.streamvault.domain.model.Channel
-import com.streamvault.domain.model.LibraryBrowseQuery
import com.streamvault.domain.model.Movie
-import com.streamvault.domain.model.PagedResult
-import com.streamvault.domain.model.Result
import com.streamvault.domain.model.Series
-import com.streamvault.domain.model.StreamInfo
-import com.streamvault.domain.repository.ChannelRepository
-import com.streamvault.domain.repository.MovieRepository
-import com.streamvault.domain.repository.SeriesRepository
+import com.streamvault.domain.model.SyncState
+import com.streamvault.domain.repository.SearchRepository
+import com.streamvault.domain.repository.SearchRepositoryResult
+import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOf
+import kotlinx.coroutines.flow.map
import kotlinx.coroutines.test.runTest
import org.junit.Test
@@ -24,15 +22,12 @@ class SearchContentTest {
@Test
fun returnsCombinedResultsAcrossAllSections() = runTest {
val useCase = SearchContent(
- channelRepository = FakeChannelRepository(
- searchResults = listOf(Channel(id = 1L, name = "News 1"))
+ searchRepository = FakeSearchRepository(
+ channelResults = listOf(Channel(id = 1L, name = "News 1")),
+ movieResults = listOf(Movie(id = 2L, name = "Movie 1")),
+ seriesResults = listOf(Series(id = 3L, name = "Series 1"))
),
- movieRepository = FakeMovieRepository(
- searchResults = listOf(Movie(id = 2L, name = "Movie 1"))
- ),
- seriesRepository = FakeSeriesRepository(
- searchResults = listOf(Series(id = 3L, name = "Series 1"))
- )
+ providerSyncStateReader = FakeProviderSyncStateReader()
)
val result = useCase(providerId = 99L, query = "star").first()
@@ -45,15 +40,12 @@ class SearchContentTest {
@Test
fun restrictsResultsToRequestedScope() = runTest {
val useCase = SearchContent(
- channelRepository = FakeChannelRepository(
- searchResults = listOf(Channel(id = 1L, name = "News 1"))
- ),
- movieRepository = FakeMovieRepository(
- searchResults = listOf(Movie(id = 2L, name = "Movie 1"))
+ searchRepository = FakeSearchRepository(
+ channelResults = listOf(Channel(id = 1L, name = "News 1")),
+ movieResults = listOf(Movie(id = 2L, name = "Movie 1")),
+ seriesResults = listOf(Series(id = 3L, name = "Series 1"))
),
- seriesRepository = FakeSeriesRepository(
- searchResults = listOf(Series(id = 3L, name = "Series 1"))
- )
+ providerSyncStateReader = FakeProviderSyncStateReader()
)
val result = useCase(
@@ -70,15 +62,12 @@ class SearchContentTest {
@Test
fun shortQueriesReturnEmptyResults() = runTest {
val useCase = SearchContent(
- channelRepository = FakeChannelRepository(
- searchResults = listOf(Channel(id = 1L, name = "News 1"))
- ),
- movieRepository = FakeMovieRepository(
- searchResults = listOf(Movie(id = 2L, name = "Movie 1"))
+ searchRepository = FakeSearchRepository(
+ channelResults = listOf(Channel(id = 1L, name = "News 1")),
+ movieResults = listOf(Movie(id = 2L, name = "Movie 1")),
+ seriesResults = listOf(Series(id = 3L, name = "Series 1"))
),
- seriesRepository = FakeSeriesRepository(
- searchResults = listOf(Series(id = 3L, name = "Series 1"))
- )
+ providerSyncStateReader = FakeProviderSyncStateReader()
)
val result = useCase(providerId = 99L, query = "a").first()
@@ -88,16 +77,40 @@ class SearchContentTest {
assertThat(result.series).isEmpty()
}
+ @Test
+ fun marksSearchPartialWhileProviderSyncIsActive() = runTest {
+ val useCase = SearchContent(
+ searchRepository = FakeSearchRepository(movieResults = listOf(Movie(id = 2L, name = "Movie 1"))),
+ providerSyncStateReader = FakeProviderSyncStateReader(SyncState.Syncing("Indexing movies"))
+ )
+
+ val result = useCase(providerId = 99L, query = "movie", scope = SearchContentScope.MOVIES).first()
+
+ assertThat(result.movies).hasSize(1)
+ assertThat(result.isPartialResult).isTrue()
+ }
+
+ @Test
+ fun marksSearchPartialWhileBackgroundIndexJobIsActive() = runTest {
+ val useCase = SearchContent(
+ searchRepository = FakeSearchRepository(movieResults = listOf(Movie(id = 2L, name = "Movie 1"))),
+ providerSyncStateReader = FakeProviderSyncStateReader(backgroundIndexingActive = true)
+ )
+
+ val result = useCase(providerId = 99L, query = "movie", scope = SearchContentScope.MOVIES).first()
+
+ assertThat(result.movies).hasSize(1)
+ assertThat(result.isPartialResult).isTrue()
+ }
+
@Test
fun rethrows_non_io_upstream_failures() = runTest {
val expected = IllegalStateException("channel search failed")
val useCase = SearchContent(
- channelRepository = FakeChannelRepository(
- searchResults = emptyList(),
- searchFlow = flow { throw expected }
+ searchRepository = FakeSearchRepository(
+ channelFlow = flow { throw expected }
),
- movieRepository = FakeMovieRepository(searchResults = emptyList()),
- seriesRepository = FakeSeriesRepository(searchResults = emptyList())
+ providerSyncStateReader = FakeProviderSyncStateReader()
)
val thrown = try {
@@ -110,79 +123,71 @@ class SearchContentTest {
assertThat(thrown).isNotNull()
assertThat(thrown?.message).isEqualTo(expected.message)
}
-}
-private class FakeChannelRepository(
- private val searchResults: List<Channel>,
- private val searchFlow: Flow<List<Channel>>? = null
-) : ChannelRepository {
- override fun searchChannels(providerId: Long, query: String): Flow<List<Channel>> = searchFlow ?: flowOf(searchResults)
- override fun getChannels(providerId: Long): Flow<List<Channel>> = unsupported()
- override fun getChannelCount(providerId: Long): Flow<Int> = unsupported()
- override fun getChannelsByCategory(providerId: Long, categoryId: Long): Flow<List<Channel>> = unsupported()
- override fun getChannelsByCategoryPage(providerId: Long, categoryId: Long, limit: Int): Flow<List<Channel>> = unsupported()
- override fun getChannelsByNumber(providerId: Long, categoryId: Long): Flow<List<Channel>> = unsupported()
- override fun getChannelsWithoutErrors(providerId: Long, categoryId: Long): Flow<List<Channel>> = unsupported()
- override fun getChannelsWithoutErrorsPage(providerId: Long, categoryId: Long, limit: Int): Flow<List<Channel>> = unsupported()
- override suspend fun getChannelsByCategoryPageOffset(providerId: Long, categoryId: Long, limit: Int, offset: Int): List<Channel> = error("Not used in test")
- override suspend fun getChannelsWithoutErrorsPageOffset(providerId: Long, categoryId: Long, limit: Int, offset: Int): List<Channel> = error("Not used in test")
- override fun searchChannelsByCategory(providerId: Long, categoryId: Long, query: String): Flow<List<Channel>> = unsupported()
- override fun searchChannelsByCategoryPaged(providerId: Long, categoryId: Long, query: String, limit: Int): Flow<List<Channel>> = unsupported()
- override fun getCategories(providerId: Long): Flow<List<Category>> = unsupported()
- override suspend fun getChannel(channelId: Long): Channel? = error("Not used in test")
- override suspend fun getStreamInfo(channel: Channel, preferStableUrl: Boolean): Result<StreamInfo> = error("Not used in test")
- override suspend fun refreshChannels(providerId: Long): Result<Unit> = error("Not used in test")
- override fun getChannelsByIds(ids: List<Long>): Flow<List<Channel>> = unsupported()
- override suspend fun incrementChannelErrorCount(channelId: Long): Result<Unit> = error("Not used in test")
- override suspend fun resetChannelErrorCount(channelId: Long): Result<Unit> = error("Not used in test")
-}
+ @Test
+ fun marksSearchPartialWhenRepositoryDoesNotEmitWithinBudget() = runTest {
+ val useCase = SearchContent(
+ searchRepository = FakeSearchRepository(
+ searchContentFlow = flow {
+ delay(3_000L)
+ emit(SearchRepositoryResult(movies = listOf(Movie(id = 2L, name = "Late Movie"))))
+ }
+ ),
+ providerSyncStateReader = FakeProviderSyncStateReader()
+ )
+
+ val result = useCase(providerId = 99L, query = "movie", scope = SearchContentScope.MOVIES).first()
-private class FakeMovieRepository(
- private val searchResults: List<Movie>,
- private val searchFlow: Flow<List<Movie>>? = null
-) : MovieRepository {
- override fun searchMovies(providerId: Long, query: String): Flow<List<Movie>> = searchFlow ?: flowOf(searchResults)
- override fun getMovies(providerId: Long): Flow<List<Movie>> = unsupported()
- override fun getMoviesByCategory(providerId: Long, categoryId: Long): Flow<List<Movie>> = unsupported()
- override fun getMoviesByCategoryPage(providerId: Long, categoryId: Long, limit: Int, offset: Int): Flow<List<Movie>> = unsupported()
- override fun getMoviesByCategoryPreview(providerId: Long, categoryId: Long, limit: Int): Flow<List<Movie>> = unsupported()
- override fun getCategoryPreviewRows(providerId: Long, categoryIds: List<Long>, limitPerCategory: Int): Flow<Map<Long?, List<Movie>>> = unsupported()
- override fun getTopRatedPreview(providerId: Long, limit: Int): Flow<List<Movie>> = unsupported()
- override fun getFreshPreview(providerId: Long, limit: Int): Flow<List<Movie>> = unsupported()
- override fun getRecommendations(providerId: Long, limit: Int): Flow<List<Movie>> = unsupported()
- override fun getRelatedContent(providerId: Long, movieId: Long, limit: Int): Flow<List<Movie>> = unsupported()
- override fun getMoviesByIds(ids: List<Long>): Flow<List<Movie>> = unsupported()
- override fun getCategories(providerId: Long): Flow<List<Category>> = unsupported()
- override fun getCategoryItemCounts(providerId: Long): Flow<Map<Long, Int>> = unsupported()
- override fun getLibraryCount(providerId: Long): Flow<Int> = unsupported()
- override fun browseMovies(query: LibraryBrowseQuery): Flow<PagedResult<Movie>> = unsupported()
- override suspend fun getMovie(movieId: Long): Movie? = error("Not used in test")
- override suspend fun getMovieDetails(providerId: Long, movieId: Long): Result<Movie> = error("Not used in test")
- override suspend fun getStreamInfo(movie: Movie): Result<StreamInfo> = error("Not used in test")
- override suspend fun refreshMovies(providerId: Long): Result<Unit> = error("Not used in test")
+ assertThat(result.movies).isEmpty()
+ assertThat(result.isPartialResult).isTrue()
+ }
}
-private class FakeSeriesRepository(
- private val searchResults: List<Series>,
- private val searchFlow: Flow<List<Series>>? = null
-) : SeriesRepository {
- override fun searchSeries(providerId: Long, query: String): Flow<List<Series>> = searchFlow ?: flowOf(searchResults)
- override fun getSeries(providerId: Long): Flow<List<Series>> = unsupported()
- override fun getSeriesByCategory(providerId: Long, categoryId: Long): Flow<List<Series>> = unsupported()
- override fun getSeriesByCategoryPage(providerId: Long, categoryId: Long, limit: Int, offset: Int): Flow<List<Series>> = unsupported()
- override fun getSeriesByCategoryPreview(providerId: Long, categoryId: Long, limit: Int): Flow<List<Series>> = unsupported()
- override fun getCategoryPreviewRows(providerId: Long, categoryIds: List<Long>, limitPerCategory: Int): Flow<Map<Long?, List<Series>>> = unsupported()
- override fun getTopRatedPreview(providerId: Long, limit: Int): Flow<List<Series>> = unsupported()
- override fun getFreshPreview(providerId: Long, limit: Int): Flow<List<Series>> = unsupported()
- override fun getSeriesByIds(ids: List<Long>): Flow<List<Series>> = unsupported()
- override fun getCategories(providerId: Long): Flow<List<Category>> = unsupported()
- override fun getCategoryItemCounts(providerId: Long): Flow<Map<Long, Int>> = unsupported()
- override fun getLibraryCount(providerId: Long): Flow<Int> = unsupported()
- override fun browseSeries(query: LibraryBrowseQuery): Flow<PagedResult<Series>> = unsupported()
- override suspend fun getSeriesById(seriesId: Long): Series? = error("Not used in test")
- override suspend fun getSeriesDetails(providerId: Long, seriesId: Long): Result<Series> = error("Not used in test")
- override suspend fun getEpisodeStreamInfo(episode: com.streamvault.domain.model.Episode): Result<StreamInfo> = error("Not used in test")
- override suspend fun refreshSeries(providerId: Long): Result<Unit> = error("Not used in test")
+private class FakeProviderSyncStateReader(
+ private val state: SyncState = SyncState.Idle,
+ private val backgroundIndexingActive: Boolean = false
+) : ProviderSyncStateReader {
+ override fun currentSyncState(providerId: Long): SyncState = state
+ override fun observeBackgroundIndexingActive(providerId: Long): Flow<Boolean> = flowOf(backgroundIndexingActive)
}
-private fun <T> unsupported(): Flow<T> = error("Not used in test")
+private class FakeSearchRepository(
+ private val channelResults: List<Channel> = emptyList(),
+ private val movieResults: List<Movie> = emptyList(),
+ private val seriesResults: List<Series> = emptyList(),
+ private val channelFlow: Flow<List<Channel>>? = null,
+ private val movieFlow: Flow<List<Movie>>? = null,
+ private val seriesFlow: Flow<List<Series>>? = null,
+ private val searchContentFlow: Flow<SearchRepositoryResult>? = null
+) : SearchRepository {
+ override fun searchContent(
+ providerId: Long,
+ query: String,
+ includeLive: Boolean,
+ includeMovies: Boolean,
+ includeSeries: Boolean,
+ maxResultsPerSection: Int
+ ): Flow<SearchRepositoryResult> {
+ searchContentFlow?.let { return it }
+ channelFlow?.let { if (includeLive) return it.map { channels -> SearchRepositoryResult(channels = channels) } }
+ movieFlow?.let { if (includeMovies) return it.map { movies -> SearchRepositoryResult(movies = movies) } }
+ seriesFlow?.let { if (includeSeries) return it.map { series -> SearchRepositoryResult(series = series) } }
+
+ return flowOf(
+ SearchRepositoryResult(
+ channels = if (includeLive) channelResults.take(maxResultsPerSection) else emptyList(),
+ movies = if (includeMovies) movieResults.take(maxResultsPerSection) else emptyList(),
+ series = if (includeSeries) seriesResults.take(maxResultsPerSection) else emptyList()
+ )
+ )
+ }
+
+ override fun searchChannels(providerId: Long, query: String): Flow<List<Channel>> =
+ channelFlow ?: flowOf(channelResults)
+
+ override fun searchMovies(providerId: Long, query: String): Flow<List<Movie>> =
+ movieFlow ?: flowOf(movieResults)
+
+ override fun searchSeries(providerId: Long, query: String): Flow<List<Series>> =
+ seriesFlow ?: flowOf(seriesResults)
+}
diff --git a/domain/src/test/java/com/streamvault/domain/usecase/SyncProviderTest.kt b/domain/src/test/java/com/streamvault/domain/usecase/SyncProviderTest.kt
index a4744759..d89c41ca 100644
--- a/domain/src/test/java/com/streamvault/domain/usecase/SyncProviderTest.kt
+++ b/domain/src/test/java/com/streamvault/domain/usecase/SyncProviderTest.kt
@@ -80,6 +80,7 @@ private class FakeSyncStateReader(
private val syncState: SyncState = SyncState.Success()
) : ProviderSyncStateReader {
override fun currentSyncState(providerId: Long): SyncState = syncState
+ override fun observeBackgroundIndexingActive(providerId: Long): Flow<Boolean> = flowOf(false)
}
private class FakeSyncProviderRepository(
diff --git a/player/src/main/java/com/streamvault/player/Media3PlayerEngine.kt b/player/src/main/java/com/streamvault/player/Media3PlayerEngine.kt
index ce49183d..34c1b70a 100644
--- a/player/src/main/java/com/streamvault/player/Media3PlayerEngine.kt
+++ b/player/src/main/java/com/streamvault/player/Media3PlayerEngine.kt
@@ -54,6 +54,7 @@ import com.streamvault.player.playback.PreloadCoordinator
import com.streamvault.player.playback.ResolvedStreamType
import com.streamvault.player.playback.StreamTypeResolver
import com.streamvault.player.playback.VideoStallDetector
+import com.streamvault.player.playback.shouldUseManagedCodecSelector
import com.streamvault.player.stats.PlayerStatsCollector
import com.streamvault.player.timeshift.DefaultLiveTimeshiftManager
import com.streamvault.player.timeshift.LiveTimeshiftBackend
@@ -92,6 +93,8 @@ class Media3PlayerEngine @Inject constructor(
companion object {
private const val TAG = "Media3PlayerEngine"
private const val AUDIO_RENDERER_RECOVERY_COOLDOWN_MS = 15_000L
+ private const val TEXTURE_VIEW_STARTUP_TIMEOUT_MS = 9_000L
+ private const val TEXTURE_VIEW_BUFFERED_STARTUP_THRESHOLD_MS = 4_000L
private const val MEDIA_SESSION_ID_PREFIX = "streamvault"
private val nextMediaSessionInstanceId = AtomicLong(1L)
}
@@ -135,12 +138,18 @@ class Media3PlayerEngine @Inject constructor(
private var requestedDecoderMode: DecoderMode = DecoderMode.AUTO
private var activeDecoderMode: DecoderMode = DecoderMode.HARDWARE
private var requestedSurfaceMode: PlayerSurfaceMode = PlayerSurfaceMode.AUTO
+ private var sessionSurfaceModeOverride: PlayerSurfaceMode? = null
private var activeDecoderPolicy: ActiveDecoderPolicy = ActiveDecoderPolicy.AUTO
private var recoveryDecoderPolicyOverride: ActiveDecoderPolicy? = null
private var knownBadDecoderNames: Set<String> = emptySet()
+ private var knownBadSurfaceTypes: Set<String> = emptySet()
private var selectedVideoDecoderName: String = "Unknown"
private var videoStallCount = 0
private var videoStallRecoveryAttempt = 0
+ private var videoStallNoticeIssued = false
+ private var videoStallSafeRecoveryPerformed = false
+ private var textureViewSessionFallbackAttempted = false
+ private var audioVideoSyncSinkActive = false
private var lastStreamInfo: StreamInfo? = null
private var lastMediaId: String? = null
private var currentResolvedStreamType: ResolvedStreamType = ResolvedStreamType.UNKNOWN
@@ -182,6 +191,8 @@ class Media3PlayerEngine @Inject constructor(
private val audioVideoOffsetUs = AtomicLong(0L)
private val _audioVideoOffsetMs = MutableStateFlow(0)
override val audioVideoOffsetMs: StateFlow<Int> = _audioVideoOffsetMs.asStateFlow()
+ private val _audioVideoSyncEnabled = MutableStateFlow(false)
+ override val audioVideoSyncEnabled: StateFlow<Boolean> = _audioVideoSyncEnabled.asStateFlow()
private val _renderSurfaceType = MutableStateFlow(PlayerRenderSurfaceType.SURFACE_VIEW)
override val renderSurfaceType: StateFlow<PlayerRenderSurfaceType> = _renderSurfaceType.asStateFlow()
@@ -259,6 +270,7 @@ class Media3PlayerEngine @Inject constructor(
val stalled = videoStallDetector.shouldReportStall(
playbackState = _playbackState.value,
isPlaying = _isPlaying.value,
+ playbackStarted = playbackStarted,
currentPositionMs = _currentPosition.value,
bufferedDurationMs = stats.bufferedDurationMs
)
@@ -267,8 +279,14 @@ class Media3PlayerEngine @Inject constructor(
videoStallCount = videoStallCount,
videoDecoderName = selectedVideoDecoderName,
activeDecoderPolicy = activeDecoderPolicy.name,
- renderSurfaceType = _renderSurfaceType.value.name
+ renderSurfaceType = _renderSurfaceType.value.name,
+ audioVideoSyncEnabled = _audioVideoSyncEnabled.value,
+ audioVideoSyncSinkActive = audioVideoSyncSinkActive
)
+ if (shouldFallbackTextureViewBeforeFirstFrame(stats)) {
+ fallbackTextureViewSurface("NO_FIRST_FRAME")
+ continue
+ }
if (stalled) handleVideoStall()
}
}
@@ -395,6 +413,8 @@ class Media3PlayerEngine @Inject constructor(
override fun setSurfaceMode(mode: PlayerSurfaceMode) {
if (requestedSurfaceMode == mode) return
requestedSurfaceMode = mode
+ sessionSurfaceModeOverride = null
+ textureViewSessionFallbackAttempted = false
updateRenderSurfaceForMode()
lastStreamInfo?.let { streamInfo ->
val wasPlaying = exoPlayer?.playWhenReady == true
@@ -421,10 +441,25 @@ class Media3PlayerEngine @Inject constructor(
exoPlayer?.playbackParameters = PlaybackParameters(clamped)
}
+ override fun setAudioVideoSyncEnabled(enabled: Boolean) {
+ if (_audioVideoSyncEnabled.value == enabled) return
+ _audioVideoSyncEnabled.value = enabled
+ if (!enabled) {
+ _audioVideoOffsetMs.value = 0
+ audioVideoOffsetUs.set(0L)
+ }
+ val streamInfo = lastStreamInfo ?: return
+ val player = exoPlayer ?: return
+ val wasPlaying = player.playWhenReady
+ val position = player.currentPosition.takeIf { it > 0L }
+ prepareInternal(streamInfo, preserveRetryState = true, seekPositionMs = position, autoPlay = wasPlaying)
+ }
+
override fun setAudioVideoOffsetMs(offsetMs: Int) {
val clamped = offsetMs.coerceIn(AUDIO_VIDEO_OFFSET_MIN_MS, AUDIO_VIDEO_OFFSET_MAX_MS)
- _audioVideoOffsetMs.value = clamped
- audioVideoOffsetUs.set(clamped * 1_000L)
+ val effectiveOffset = if (_audioVideoSyncEnabled.value) clamped else 0
+ _audioVideoOffsetMs.value = effectiveOffset
+ audioVideoOffsetUs.set(effectiveOffset * 1_000L)
}
@MainThread
@@ -651,6 +686,10 @@ class Media3PlayerEngine @Inject constructor(
videoStallRecoveryAttempt = 0
recoveryDecoderPolicyOverride = null
knownBadDecoderNames = emptySet()
+ knownBadSurfaceTypes = emptySet()
+ sessionSurfaceModeOverride = null
+ textureViewSessionFallbackAttempted = false
+ audioVideoSyncSinkActive = false
activeLiveTimeshiftStreamInfo = null
activeLiveTimeshiftChannelKey = null
isPlayingTimeshiftSnapshot = false
@@ -687,6 +726,8 @@ class Media3PlayerEngine @Inject constructor(
}
if (lastMediaId != mediaId) {
decoderPreferencePolicy.resetForMedia(mediaId)
+ sessionSurfaceModeOverride = null
+ textureViewSessionFallbackAttempted = false
}
lastMediaId = mediaId
playbackStarted = false
@@ -699,6 +740,8 @@ class Media3PlayerEngine @Inject constructor(
videoStallDetector.reset()
if (!preserveRetryState) {
videoStallRecoveryAttempt = 0
+ videoStallNoticeIssued = false
+ videoStallSafeRecoveryPerformed = false
}
selectedVideoDecoderName = "Unknown"
@@ -858,7 +901,7 @@ class Media3PlayerEngine @Inject constructor(
videoScalingMode = C.VIDEO_SCALING_MODE_SCALE_TO_FIT
playbackParameters = PlaybackParameters(_playbackSpeed.value)
setVideoFrameMetadataListener(VideoFrameMetadataListener { _, _, _, _ ->
- videoStallDetector.onVideoFrameRendered()
+ videoStallDetector.onVideoFrameRendered(_currentPosition.value)
})
addAnalyticsListener(createAnalyticsListener())
addListener(createPlayerListener())
@@ -868,6 +911,8 @@ class Media3PlayerEngine @Inject constructor(
private fun buildRenderersFactory(): DefaultRenderersFactory {
val decoderPolicy = activeDecoderPolicy
val badDecoderNames = knownBadDecoderNames
+ val requestedMode = requestedDecoderMode
+ val useAudioVideoSyncSink = _audioVideoSyncEnabled.value
return object : DefaultRenderersFactory(context) {
override fun buildAudioSink(
context: Context,
@@ -879,6 +924,11 @@ class Media3PlayerEngine @Inject constructor(
) {
"DefaultRenderersFactory did not provide an AudioSink."
}
+ if (!useAudioVideoSyncSink) {
+ audioVideoSyncSinkActive = false
+ return audioSink
+ }
+ audioVideoSyncSinkActive = true
return AudioVideoOffsetAudioSink(
delegate = audioSink,
offsetUsProvider = { audioVideoOffsetUs.get() }
@@ -935,7 +985,7 @@ class Media3PlayerEngine @Inject constructor(
}
}.apply {
setEnableDecoderFallback(true)
- if (decoderPolicy != ActiveDecoderPolicy.AUTO || badDecoderNames.isNotEmpty()) {
+ if (shouldUseManagedCodecSelector(requestedMode, decoderPolicy)) {
setMediaCodecSelector(
PlaybackCodecSelector(
policyProvider = { decoderPolicy },
@@ -1206,7 +1256,7 @@ class Media3PlayerEngine @Inject constructor(
}
private fun resolveActiveDecoderPolicy(mode: DecoderMode): ActiveDecoderPolicy = when (mode) {
- DecoderMode.AUTO -> ActiveDecoderPolicy.HARDWARE_PREFERRED
+ DecoderMode.AUTO -> ActiveDecoderPolicy.AUTO
DecoderMode.HARDWARE -> ActiveDecoderPolicy.HARDWARE_PREFERRED
DecoderMode.SOFTWARE -> ActiveDecoderPolicy.SOFTWARE_PREFERRED
DecoderMode.COMPATIBILITY -> ActiveDecoderPolicy.COMPATIBILITY
@@ -1219,7 +1269,15 @@ class Media3PlayerEngine @Inject constructor(
}
private fun updateRenderSurfaceForMode() {
- _renderSurfaceType.value = when (requestedSurfaceMode) {
+ val surfaceMode = sessionSurfaceModeOverride
+ ?: when {
+ requestedSurfaceMode == PlayerSurfaceMode.TEXTURE_VIEW &&
+ knownBadSurfaceTypes.contains(PlayerRenderSurfaceType.TEXTURE_VIEW.name) -> {
+ PlayerSurfaceMode.SURFACE_VIEW
+ }
+ else -> requestedSurfaceMode
+ }
+ _renderSurfaceType.value = when (surfaceMode) {
PlayerSurfaceMode.SURFACE_VIEW -> PlayerRenderSurfaceType.SURFACE_VIEW
PlayerSurfaceMode.TEXTURE_VIEW -> PlayerRenderSurfaceType.TEXTURE_VIEW
PlayerSurfaceMode.AUTO -> if (activeDecoderPolicy == ActiveDecoderPolicy.COMPATIBILITY) {
@@ -1242,14 +1300,24 @@ class Media3PlayerEngine @Inject constructor(
resolutionBucket = bucket
)
val names = PlaybackCodecSelector.knownBadDecoderNames(records)
- scope.launch { knownBadDecoderNames = names }
+ val surfaces = records.map { it.key.surfaceType }.toSet()
+ scope.launch {
+ knownBadDecoderNames = names
+ knownBadSurfaceTypes = surfaces
+ if (
+ _renderSurfaceType.value == PlayerRenderSurfaceType.TEXTURE_VIEW &&
+ sessionSurfaceModeOverride == null &&
+ surfaces.contains(PlayerRenderSurfaceType.TEXTURE_VIEW.name)
+ ) {
+ fallbackTextureViewSurface("KNOWN_BAD_SURFACE")
+ }
+ }
}
}
private fun handleVideoStall() {
val streamInfo = lastStreamInfo ?: return
videoStallCount++
- videoStallRecoveryAttempt++
recordCompatibilityFailure("VIDEO_STALL")
_playerStats.value = _playerStats.value.copy(videoStallCount = videoStallCount)
@@ -1257,40 +1325,46 @@ class Media3PlayerEngine @Inject constructor(
val seekPosition = exoPlayer?.currentPosition?.takeIf { it > 0L }
Log.w(
TAG,
- "video-stall attempt=$videoStallRecoveryAttempt decoder=$selectedVideoDecoderName policy=$activeDecoderPolicy surface=${_renderSurfaceType.value} target=${PlaybackLogSanitizer.sanitizeUrl(streamInfo.url)}"
+ "video-stall count=$videoStallCount recovered=$videoStallSafeRecoveryPerformed decoder=$selectedVideoDecoderName policy=$activeDecoderPolicy surface=${_renderSurfaceType.value} target=${PlaybackLogSanitizer.sanitizeUrl(streamInfo.url)}"
)
- when (videoStallRecoveryAttempt) {
- 1 -> {
- viewBinder.attachPlayer(null)
- viewBinder.attachPlayer(exoPlayer)
- prepareInternal(streamInfo, preserveRetryState = true, seekPositionMs = seekPosition, autoPlay = wasPlaying)
- }
- 2 -> {
- activeDecoderPolicy = when (activeDecoderPolicy) {
- ActiveDecoderPolicy.SOFTWARE_PREFERRED -> ActiveDecoderPolicy.HARDWARE_PREFERRED
- else -> ActiveDecoderPolicy.SOFTWARE_PREFERRED
- }
- recoveryDecoderPolicyOverride = activeDecoderPolicy
- recreatePlayer()
- prepareInternal(streamInfo, preserveRetryState = true, seekPositionMs = seekPosition, autoPlay = wasPlaying)
- }
- 3 -> {
- requestedDecoderMode = DecoderMode.COMPATIBILITY
- activeDecoderPolicy = ActiveDecoderPolicy.COMPATIBILITY
- recoveryDecoderPolicyOverride = activeDecoderPolicy
- updateRenderSurfaceForMode()
- recreatePlayer()
- prepareInternal(streamInfo, preserveRetryState = true, seekPositionMs = seekPosition, autoPlay = wasPlaying)
- }
- else -> {
- _error.tryEmit(
- PlayerError.DecoderError(
- "Video decoder stalled on this device. Try Compatibility Mode, TextureView, or a lower-quality stream."
- )
+ if (!playbackStarted) {
+ Log.w(TAG, "video-stall ignored because playback has not started yet")
+ return
+ }
+
+ // Treat the first stall signal after startup as diagnostics only. Some devices
+ // report delayed frames or clock drift immediately after start, and recreating
+ // the player at that point can make startup crashes worse.
+ if (!videoStallNoticeIssued) {
+ videoStallNoticeIssued = true
+ Log.w(TAG, "video-stall recorded without automatic recovery")
+ return
+ }
+
+ if (videoStallSafeRecoveryPerformed) {
+ _error.tryEmit(
+ PlayerError.DecoderError(
+ "Video playback stalled on this device. Try another stream or open diagnostics."
)
- }
+ )
+ return
}
+
+ if (_renderSurfaceType.value == PlayerRenderSurfaceType.TEXTURE_VIEW && !textureViewSessionFallbackAttempted) {
+ fallbackTextureViewSurface("VIDEO_STALL")
+ return
+ }
+
+ videoStallSafeRecoveryPerformed = true
+ videoStallRecoveryAttempt++
+ Log.w(TAG, "video-stall performing one safe reprepare attempt=$videoStallRecoveryAttempt")
+ prepareInternal(
+ streamInfo = streamInfo,
+ preserveRetryState = true,
+ seekPositionMs = seekPosition,
+ autoPlay = wasPlaying
+ )
}
private fun recordCompatibilityFailure(failureType: String) {
@@ -1332,6 +1406,57 @@ class Media3PlayerEngine @Inject constructor(
else -> "UNKNOWN"
}
+ private fun shouldFallbackTextureViewBeforeFirstFrame(stats: PlayerStats): Boolean {
+ if (_renderSurfaceType.value != PlayerRenderSurfaceType.TEXTURE_VIEW) return false
+ if (sessionSurfaceModeOverride == PlayerSurfaceMode.SURFACE_VIEW) return false
+ if (textureViewSessionFallbackAttempted) return false
+ if (lastStreamInfo == null) return false
+ if (playbackStarted) return false
+ if (!isCurrentStreamLive()) return false
+ val state = _playbackState.value
+ if (state != PlaybackState.READY && state != PlaybackState.BUFFERING) return false
+ if (System.currentTimeMillis() - prepareStartMs < TEXTURE_VIEW_STARTUP_TIMEOUT_MS) return false
+ if (state == PlaybackState.BUFFERING && stats.bufferedDurationMs < TEXTURE_VIEW_BUFFERED_STARTUP_THRESHOLD_MS) {
+ return false
+ }
+ if (selectedVideoDecoderName == "Unknown" && state != PlaybackState.READY) return false
+ return true
+ }
+
+ private fun fallbackTextureViewSurface(reason: String) {
+ val streamInfo = lastStreamInfo ?: return
+ if (_renderSurfaceType.value != PlayerRenderSurfaceType.TEXTURE_VIEW) return
+ if (textureViewSessionFallbackAttempted) return
+
+ textureViewSessionFallbackAttempted = true
+ sessionSurfaceModeOverride = PlayerSurfaceMode.SURFACE_VIEW
+ updateRenderSurfaceForMode()
+ recordCompatibilityFailure("TEXTURE_VIEW_$reason")
+
+ val wasPlaying = exoPlayer?.playWhenReady ?: true
+ val seekPosition = exoPlayer?.currentPosition?.takeIf {
+ currentResolvedStreamType == ResolvedStreamType.PROGRESSIVE && it > 0L
+ }
+ Log.w(
+ TAG,
+ "texture-view fallback reason=$reason decoder=$selectedVideoDecoderName policy=$activeDecoderPolicy target=${PlaybackLogSanitizer.sanitizeUrl(streamInfo.url)}"
+ )
+
+ viewBinder.attachPlayer(null)
+ prepareInternal(
+ streamInfo = streamInfo,
+ preserveRetryState = true,
+ seekPositionMs = seekPosition,
+ autoPlay = wasPlaying
+ )
+ }
+
+ private fun isCurrentStreamLive(): Boolean = currentResolvedStreamType in setOf(
+ ResolvedStreamType.HLS,
+ ResolvedStreamType.MPEG_TS_LIVE,
+ ResolvedStreamType.RTSP
+ )
+
private fun handleAudioRendererIssue(error: Exception, source: String) {
val streamInfo = lastStreamInfo
if (streamInfo == null) {
diff --git a/player/src/main/java/com/streamvault/player/PlayerEngine.kt b/player/src/main/java/com/streamvault/player/PlayerEngine.kt
index d5aa9f7a..6052660b 100644
--- a/player/src/main/java/com/streamvault/player/PlayerEngine.kt
+++ b/player/src/main/java/com/streamvault/player/PlayerEngine.kt
@@ -51,6 +51,7 @@ interface PlayerEngine {
val availableVideoTracks: StateFlow<List<PlayerTrack>>
val playbackSpeed: StateFlow<Float>
val audioVideoOffsetMs: StateFlow<Int>
+ val audioVideoSyncEnabled: StateFlow<Boolean>
val timeshiftState: StateFlow<LiveTimeshiftState>
val renderSurfaceType: StateFlow<PlayerRenderSurfaceType>
@@ -71,6 +72,7 @@ interface PlayerEngine {
fun setVolume(volume: Float)
fun setMuted(muted: Boolean)
fun setPlaybackSpeed(speed: Float)
+ fun setAudioVideoSyncEnabled(enabled: Boolean)
fun setAudioVideoOffsetMs(offsetMs: Int)
fun startLiveTimeshift(streamInfo: StreamInfo, channelKey: String, config: TimeshiftConfig)
fun stopLiveTimeshift()
@@ -144,6 +146,8 @@ data class PlayerStats(
val videoDecoderName: String = "Unknown",
val activeDecoderPolicy: String = "AUTO",
val renderSurfaceType: String = "SURFACE_VIEW",
+ val audioVideoSyncEnabled: Boolean = false,
+ val audioVideoSyncSinkActive: Boolean = false,
val videoStallCount: Int = 0,
val lastVideoFrameAgoMs: Long = 0,
val videoBitrate: Int = 0,
diff --git a/player/src/main/java/com/streamvault/player/playback/CodecPreference.kt b/player/src/main/java/com/streamvault/player/playback/CodecPreference.kt
index 40cbe9f7..40c1359d 100644
--- a/player/src/main/java/com/streamvault/player/playback/CodecPreference.kt
+++ b/player/src/main/java/com/streamvault/player/playback/CodecPreference.kt
@@ -14,6 +14,11 @@ enum class ActiveDecoderPolicy {
COMPATIBILITY
}
+internal fun shouldUseManagedCodecSelector(
+ requestedMode: DecoderMode,
+ decoderPolicy: ActiveDecoderPolicy
+): Boolean = requestedMode != DecoderMode.AUTO && decoderPolicy != ActiveDecoderPolicy.AUTO
+
@UnstableApi
class PlaybackCodecSelector(
private val delegate: MediaCodecSelector = MediaCodecSelector.DEFAULT,
diff --git a/player/src/main/java/com/streamvault/player/playback/VideoStallDetector.kt b/player/src/main/java/com/streamvault/player/playback/VideoStallDetector.kt
index 3c0bfbfc..1c184ba1 100644
--- a/player/src/main/java/com/streamvault/player/playback/VideoStallDetector.kt
+++ b/player/src/main/java/com/streamvault/player/playback/VideoStallDetector.kt
@@ -10,6 +10,7 @@ class VideoStallDetector(
) {
private var startedAtMs: Long = 0L
private var lastFrameAtMs: Long = 0L
+ private var firstFramePositionMs: Long = 0L
private var lastPositionMs: Long = 0L
private var lastPositionCheckMs: Long = 0L
private var stalled = false
@@ -18,12 +19,16 @@ class VideoStallDetector(
val now = nowMs()
startedAtMs = now
lastFrameAtMs = 0L
+ firstFramePositionMs = 0L
lastPositionMs = 0L
lastPositionCheckMs = now
stalled = false
}
- fun onVideoFrameRendered() {
+ fun onVideoFrameRendered(currentPositionMs: Long = 0L) {
+ if (lastFrameAtMs <= 0L) {
+ firstFramePositionMs = currentPositionMs.coerceAtLeast(0L)
+ }
lastFrameAtMs = nowMs()
stalled = false
}
@@ -36,17 +41,19 @@ class VideoStallDetector(
fun shouldReportStall(
playbackState: PlaybackState,
isPlaying: Boolean,
+ playbackStarted: Boolean,
currentPositionMs: Long,
bufferedDurationMs: Long
): Boolean {
val now = nowMs()
- if (playbackState != PlaybackState.READY || !isPlaying || bufferedDurationMs <= 1_000L) {
+ if (playbackState != PlaybackState.READY || !isPlaying || !playbackStarted || bufferedDurationMs <= 1_000L) {
lastPositionMs = currentPositionMs
lastPositionCheckMs = now
stalled = false
return false
}
if (now - startedAtMs < initialGraceMs || lastFrameAtMs <= 0L) return false
+ if (currentPositionMs - firstFramePositionMs < minPositionAdvanceMs) return false
val positionAdvanced = currentPositionMs - lastPositionMs >= minPositionAdvanceMs
val checkWindowElapsed = now - lastPositionCheckMs >= minPositionAdvanceMs
diff --git a/player/src/test/java/com/streamvault/player/playback/PlaybackCodecSelectorTest.kt b/player/src/test/java/com/streamvault/player/playback/PlaybackCodecSelectorTest.kt
index aa333650..df1c34a8 100644
--- a/player/src/test/java/com/streamvault/player/playback/PlaybackCodecSelectorTest.kt
+++ b/player/src/test/java/com/streamvault/player/playback/PlaybackCodecSelectorTest.kt
@@ -2,6 +2,7 @@ package com.streamvault.player.playback
import androidx.media3.common.util.UnstableApi
import com.google.common.truth.Truth.assertThat
+import com.streamvault.domain.model.DecoderMode
import org.junit.Test
@UnstableApi
@@ -33,6 +34,15 @@ class PlaybackCodecSelectorTest {
.containsExactly("OMX.bad.decoder")
}
+ @Test
+ fun `managed codec selector is reserved for explicit decoder modes`() {
+ assertThat(shouldUseManagedCodecSelector(DecoderMode.AUTO, ActiveDecoderPolicy.AUTO)).isFalse()
+ assertThat(shouldUseManagedCodecSelector(DecoderMode.AUTO, ActiveDecoderPolicy.SOFTWARE_PREFERRED)).isFalse()
+ assertThat(shouldUseManagedCodecSelector(DecoderMode.HARDWARE, ActiveDecoderPolicy.HARDWARE_PREFERRED)).isTrue()
+ assertThat(shouldUseManagedCodecSelector(DecoderMode.SOFTWARE, ActiveDecoderPolicy.SOFTWARE_PREFERRED)).isTrue()
+ assertThat(shouldUseManagedCodecSelector(DecoderMode.COMPATIBILITY, ActiveDecoderPolicy.COMPATIBILITY)).isTrue()
+ }
+
private fun compatibilityRecord(
decoderName: String,
failures: Int,
diff --git a/player/src/test/java/com/streamvault/player/playback/VideoStallDetectorTest.kt b/player/src/test/java/com/streamvault/player/playback/VideoStallDetectorTest.kt
index 8e7573c4..c4770883 100644
--- a/player/src/test/java/com/streamvault/player/playback/VideoStallDetectorTest.kt
+++ b/player/src/test/java/com/streamvault/player/playback/VideoStallDetectorTest.kt
@@ -18,6 +18,7 @@ class VideoStallDetectorTest {
detector.shouldReportStall(
playbackState = PlaybackState.READY,
isPlaying = true,
+ playbackStarted = true,
currentPositionMs = 3_000L,
bufferedDurationMs = 5_000L
)
@@ -29,13 +30,14 @@ class VideoStallDetectorTest {
val detector = detector()
detector.reset()
nowMs = 1_000L
- detector.onVideoFrameRendered()
+ detector.onVideoFrameRendered(currentPositionMs = 500L)
nowMs = 9_000L
assertThat(
detector.shouldReportStall(
playbackState = PlaybackState.READY,
isPlaying = true,
+ playbackStarted = true,
currentPositionMs = 3_000L,
bufferedDurationMs = 5_000L
)
@@ -44,6 +46,7 @@ class VideoStallDetectorTest {
detector.shouldReportStall(
playbackState = PlaybackState.READY,
isPlaying = true,
+ playbackStarted = true,
currentPositionMs = 5_000L,
bufferedDurationMs = 5_000L
)
@@ -55,12 +58,13 @@ class VideoStallDetectorTest {
val detector = detector()
detector.reset()
nowMs = 1_000L
- detector.onVideoFrameRendered()
+ detector.onVideoFrameRendered(currentPositionMs = 500L)
nowMs = 9_000L
- assertThat(detector.shouldReportStall(PlaybackState.BUFFERING, true, 4_000L, 5_000L)).isFalse()
- assertThat(detector.shouldReportStall(PlaybackState.READY, false, 4_000L, 5_000L)).isFalse()
- assertThat(detector.shouldReportStall(PlaybackState.READY, true, 4_000L, 0L)).isFalse()
+ assertThat(detector.shouldReportStall(PlaybackState.BUFFERING, true, true, 4_000L, 5_000L)).isFalse()
+ assertThat(detector.shouldReportStall(PlaybackState.READY, false, true, 4_000L, 5_000L)).isFalse()
+ assertThat(detector.shouldReportStall(PlaybackState.READY, true, false, 4_000L, 5_000L)).isFalse()
+ assertThat(detector.shouldReportStall(PlaybackState.READY, true, true, 4_000L, 0L)).isFalse()
}
@Test
@@ -68,14 +72,33 @@ class VideoStallDetectorTest {
val detector = detector()
detector.reset()
nowMs = 1_000L
- detector.onVideoFrameRendered()
+ detector.onVideoFrameRendered(currentPositionMs = 500L)
nowMs = 9_000L
- assertThat(detector.shouldReportStall(PlaybackState.READY, true, 3_000L, 5_000L)).isTrue()
+ assertThat(detector.shouldReportStall(PlaybackState.READY, true, true, 3_000L, 5_000L)).isTrue()
nowMs = 9_100L
- detector.onVideoFrameRendered()
+ detector.onVideoFrameRendered(currentPositionMs = 3_000L)
nowMs = 15_000L
- assertThat(detector.shouldReportStall(PlaybackState.READY, true, 6_000L, 5_000L)).isTrue()
+ assertThat(detector.shouldReportStall(PlaybackState.READY, true, true, 6_000L, 5_000L)).isTrue()
+ }
+
+ @Test
+ fun `does not report before playback advances beyond first frame`() {
+ val detector = detector()
+ detector.reset()
+ nowMs = 1_000L
+ detector.onVideoFrameRendered(currentPositionMs = 2_500L)
+ nowMs = 9_000L
+
+ assertThat(
+ detector.shouldReportStall(
+ playbackState = PlaybackState.READY,
+ isPlaying = true,
+ playbackStarted = true,
+ currentPositionMs = 3_000L,
+ bufferedDurationMs = 5_000L
+ )
+ ).isFalse()
}
private fun detector() = VideoStallDetector(