Skip to content

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

Fix Xtream provider refresh recovery

David Nashashf1bf7e92f033
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
index fdaa63fe..6592a873 100644
--- a/data/src/main/java/com/streamvault/data/local/dao/XtreamIndexDaos.kt
+++ b/data/src/main/java/com/streamvault/data/local/dao/XtreamIndexDaos.kt
@@ -250,6 +250,33 @@ abstract class XtreamContentIndexDao {
open suspend fun pruneOrphanLocalContentRows(): Int =
pruneOrphanLiveRows() + pruneOrphanMovieRows() + pruneOrphanSeriesRows()
+ // Coverage uses indexed_at rather than stale_state so cached search results remain usable.
+ @Query("UPDATE xtream_content_index SET indexed_at = 0 WHERE provider_id = :providerId AND content_type = :contentType")
+ abstract suspend fun beginSnapshot(providerId: Long, contentType: String): Int
+
+ @Query("DELETE FROM xtream_content_index WHERE provider_id = :providerId AND content_type = :contentType AND indexed_at = 0")
+ protected abstract suspend fun deleteUnseenIndexRows(providerId: Long, contentType: String): Int
+
+ @Query("""DELETE FROM movies WHERE provider_id = :providerId AND CAST(stream_id AS TEXT) IN
+ (SELECT remote_id FROM xtream_content_index WHERE provider_id = :providerId AND content_type = 'MOVIE' AND indexed_at = 0)""")
+ protected abstract suspend fun deleteUnseenMovies(providerId: Long): Int
+
+ @Query("""DELETE FROM series WHERE provider_id = :providerId AND COALESCE(NULLIF(provider_series_id, ''), CAST(series_id AS TEXT)) IN
+ (SELECT remote_id FROM xtream_content_index WHERE provider_id = :providerId AND content_type = 'SERIES' AND indexed_at = 0)""")
+ protected abstract suspend fun deleteUnseenSeries(providerId: Long): Int
+
+ /** Only a complete successful snapshot may remove remotely deleted content. */
+ @Transaction
+ open suspend fun pruneCompletedSnapshot(providerId: Long, contentType: String): Int {
+ val deleted = when (contentType) {
+ "MOVIE" -> deleteUnseenMovies(providerId)
+ "SERIES" -> deleteUnseenSeries(providerId)
+ else -> error("Unsupported snapshot type")
+ }
+ deleteUnseenIndexRows(providerId, contentType)
+ return deleted
+ }
+
@Transaction
open suspend fun pruneStaleLocalContentRows(providerId: Long, contentType: String): Int {
val deleted = when (contentType) {
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 cf10da10..6e902f7f 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
@@ -243,6 +243,7 @@ class XtreamProvider(
val resolvedAdultCategoryIds = adultCategoryIds ?: loadAdultCategoryIds(ContentType.MOVIE)
val buffer = mutableListOf<Movie>()
var acceptedCount = 0
+ var malformedRows = false
api.streamVodStreams(
XtreamUrlFactory.buildPlayerApiUrl(
serverUrl = serverUrl,
@@ -253,7 +254,7 @@ class XtreamProvider(
),
requestProfile
) { stream ->
- mapVodStream(stream, resolvedAdultCategoryIds)?.let { movie ->
+ mapVodStream(stream, resolvedAdultCategoryIds).also { if (it == null) malformedRows = true }?.let { movie ->
buffer += movie
acceptedCount++
if (buffer.size >= batchSize) {
@@ -265,6 +266,7 @@ class XtreamProvider(
if (buffer.isNotEmpty()) {
onBatch(buffer.toList())
}
+ if (malformedRows) throw XtreamParsingException("Malformed VOD summary coverage")
Result.success(acceptedCount)
} catch (e: CancellationException) {
throw e
@@ -393,6 +395,7 @@ class XtreamProvider(
val resolvedAdultCategoryIds = adultCategoryIds ?: loadAdultCategoryIds(ContentType.SERIES)
val buffer = mutableListOf<Series>()
var acceptedCount = 0
+ var malformedRows = false
api.streamSeriesList(
XtreamUrlFactory.buildPlayerApiUrl(
serverUrl = serverUrl,
@@ -403,7 +406,7 @@ class XtreamProvider(
),
requestProfile
) { item ->
- mapSeriesItem(item, resolvedAdultCategoryIds)?.let { series ->
+ mapSeriesItem(item, resolvedAdultCategoryIds).also { if (it == null) malformedRows = true }?.let { series ->
buffer += series
acceptedCount++
if (buffer.size >= batchSize) {
@@ -415,6 +418,7 @@ class XtreamProvider(
if (buffer.isNotEmpty()) {
onBatch(buffer.toList())
}
+ if (malformedRows) throw XtreamParsingException("Malformed series summary coverage")
Result.success(acceptedCount)
} catch (e: CancellationException) {
throw e
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 b20d7f74..b982f43a 100644
--- a/data/src/main/java/com/streamvault/data/sync/SyncManager.kt
+++ b/data/src/main/java/com/streamvault/data/sync/SyncManager.kt
@@ -411,6 +411,18 @@ class SyncManager @Inject constructor(
XtreamIncrementalIndexExecutor(
operations = CallbackXtreamIncrementalIndexOperations(
XtreamIncrementalIndexCallbacks(
+ beginSnapshot = { providerId, type ->
+ transactionRunner.inTransaction {
+ providerWorkflowCommitFence.assertCanCommit(providerId)
+ xtreamContentIndexDao.beginSnapshot(providerId, type.name)
+ }
+ },
+ finishSnapshot = { providerId, type ->
+ transactionRunner.inTransaction {
+ providerWorkflowCommitFence.assertCanCommit(providerId)
+ xtreamContentIndexDao.pruneCompletedSnapshot(providerId, type.name)
+ }
+ },
getCategories = { providerId, contentType ->
categoryDao.getByProviderAndTypeSync(providerId, contentType.name)
},
@@ -2164,7 +2176,7 @@ class SyncManager @Inject constructor(
val localId = existingByStreamId[movie.streamId]?.id ?: movie.id
val row = movie.toXtreamIndexRow(providerId, localId, indexedAt)
val existing = indexRowsBefore[row.remoteId]
- existing == null || existing.copy(indexedAt = row.indexedAt) != row
+ existing == null || existing.indexedAt == 0L || existing.copy(indexedAt = row.indexedAt) != row
}
if (updatedMovies.isNotEmpty() || movieIndexChanged) {
transactionRunner.inTransaction {
@@ -2186,7 +2198,7 @@ class SyncManager @Inject constructor(
}
val indexUpdates = indexRows.filter { row ->
val existing = indexRowsBefore[row.remoteId]
- existing == null || existing.copy(indexedAt = row.indexedAt) != row
+ existing == null || existing.indexedAt == 0L || existing.copy(indexedAt = row.indexedAt) != row
}
if (indexUpdates.isNotEmpty()) xtreamContentIndexDao.upsertAll(indexUpdates)
}
@@ -2225,7 +2237,7 @@ class SyncManager @Inject constructor(
val localId = existingBySeriesId[item.seriesId]?.id ?: item.id
val row = item.toXtreamIndexRow(providerId, localId, indexedAt)
val existing = indexRowsBefore[row.remoteId]
- existing == null || existing.copy(indexedAt = row.indexedAt) != row
+ existing == null || existing.indexedAt == 0L || existing.copy(indexedAt = row.indexedAt) != row
}
if (updatedSeries.isNotEmpty() || seriesIndexChanged) {
transactionRunner.inTransaction {
@@ -2247,7 +2259,7 @@ class SyncManager @Inject constructor(
}
val indexUpdates = indexRows.filter { row ->
val existing = indexRowsBefore[row.remoteId]
- existing == null || existing.copy(indexedAt = row.indexedAt) != row
+ existing == null || existing.indexedAt == 0L || existing.copy(indexedAt = row.indexedAt) != row
}
if (indexUpdates.isNotEmpty()) xtreamContentIndexDao.upsertAll(indexUpdates)
}
diff --git a/data/src/main/java/com/streamvault/data/sync/XtreamCatalogSectionExecutor.kt b/data/src/main/java/com/streamvault/data/sync/XtreamCatalogSectionExecutor.kt
index 284ea8ce..4a225627 100644
--- a/data/src/main/java/com/streamvault/data/sync/XtreamCatalogSectionExecutor.kt
+++ b/data/src/main/java/com/streamvault/data/sync/XtreamCatalogSectionExecutor.kt
@@ -1,6 +1,7 @@
package com.streamvault.data.sync
import android.util.Log
+import com.streamvault.data.util.runSuspendCatching
import com.streamvault.data.mapper.toEntity
import com.streamvault.data.preferences.PreferencesRepository
import com.streamvault.data.remote.xtream.XtreamProvider
@@ -33,7 +34,7 @@ internal class XtreamCatalogSectionExecutor(
label: String,
now: Long,
onProgress: ((String) -> Unit)?
- ): kotlin.Result<Int> = runCatching {
+ ): kotlin.Result<Int> = runSuspendCatching {
progress(provider.id, onProgress, "Loading $label categories...")
markIndexRunning(provider.id, contentType, now)
val categories = when (contentType) {
@@ -41,7 +42,7 @@ internal class XtreamCatalogSectionExecutor(
ContentType.SERIES -> requireResult(api.getSeriesCategories(), "Failed to load series categories")
else -> throw IllegalArgumentException("Unsupported Xtream category shell: $contentType")
}
- syncCatalogStore.upsertCategories(
+ syncCatalogStore.replaceCategories(
providerId = provider.id,
type = contentType.name,
categories = categories.map { category -> category.toEntity(provider.id) }
diff --git a/data/src/main/java/com/streamvault/data/sync/XtreamIncrementalIndexExecutor.kt b/data/src/main/java/com/streamvault/data/sync/XtreamIncrementalIndexExecutor.kt
index 3b9f3bd9..90ab84c7 100644
--- a/data/src/main/java/com/streamvault/data/sync/XtreamIncrementalIndexExecutor.kt
+++ b/data/src/main/java/com/streamvault/data/sync/XtreamIncrementalIndexExecutor.kt
@@ -17,6 +17,9 @@ import com.streamvault.domain.model.Series
* supplied through one narrow operations port so the coordinator does not regain those seams.
*/
internal interface XtreamIncrementalIndexOperations {
+ suspend fun beginSnapshot(providerId: Long, contentType: ContentType)
+ suspend fun finishSnapshot(providerId: Long, contentType: ContentType)
+
fun monotonicTimeMillis(): Long = System.nanoTime() / 1_000_000L
suspend fun getCategories(providerId: Long, contentType: ContentType): List<CategoryEntity>
@@ -115,7 +118,7 @@ internal class XtreamIncrementalIndexExecutor(
val initialJob = operations.getJob(provider.id, contentType)
val priorityCategoryId = initialJob?.priorityCategoryId
val indexedCategories = operations.getCategories(provider.id, contentType)
- val resumeJob = initialJob?.takeIf { it.state in setOf("QUEUED", "RUNNING", "PARTIAL") }
+ val resumeJob = initialJob?.takeIf { it.state in setOf("QUEUED", "RUNNING", "PARTIAL", "FAILED_RETRYABLE") }
val categoryLimit = maxCategories?.coerceAtLeast(1) ?: Int.MAX_VALUE
val restartIncompleteFailedSweep = resumeJob?.let { job ->
job.state == "PARTIAL" &&
@@ -130,6 +133,7 @@ internal class XtreamIncrementalIndexExecutor(
var restoreMovieWatchProgressPending = false
try {
if (shouldAttemptFullStream(resumeJob, priorityCategoryId)) {
+ operations.beginSnapshot(provider.id, contentType)
when (val streamed = streamFullSummary(
provider = provider,
api = api,
@@ -146,6 +150,11 @@ internal class XtreamIncrementalIndexExecutor(
throw error
}
}
+ if (indexedCategories.isEmpty()) {
+ throw streamed.exception ?: java.io.IOException(streamed.message)
+ }
+ // Discard coverage from the incomplete bulk response before fallback.
+ operations.beginSnapshot(provider.id, contentType)
operations.log(
"Full ${contentType.name} stream index failed for provider ${provider.id}; falling back to category slices: ${streamed.message}"
)
@@ -328,10 +337,12 @@ internal class XtreamIncrementalIndexExecutor(
val finishedAt = System.currentTimeMillis()
val hasMoreCategories = nextCategoryIndex < indexedCategories.size
val finalState = when {
- hasMoreCategories -> "QUEUED"
failedCategories > 0 -> "PARTIAL"
+ hasMoreCategories -> "QUEUED"
+ skippedMalformedRows > 0 -> "PARTIAL"
else -> "SUCCESS"
}
+ if (finalState == "SUCCESS") operations.finishSnapshot(provider.id, contentType)
val priorityWasNotPresent = priorityCategoryId != null &&
indexedCategories.none { it.categoryId == priorityCategoryId }
upsertJob(
@@ -351,7 +362,7 @@ internal class XtreamIncrementalIndexExecutor(
lastError = lastError?.let(operations::sanitize)
)
operations.updateSummaryMetadata(provider.id, contentType, indexedRows, finalState, finishedAt)
- if (hasMoreCategories) {
+ if (hasMoreCategories && failedCategories == 0) {
operations.scheduleIndex(provider.id, contentType)
}
if (!hasMoreCategories && failedCategories > 0) {
@@ -440,6 +451,7 @@ internal class XtreamIncrementalIndexExecutor(
is Result.Success -> {
val finishedAt = System.currentTimeMillis()
val acceptedCount = indexedRows.coerceAtLeast(streamResult.data)
+ operations.finishSnapshot(provider.id, contentType)
upsertJob(
providerId = provider.id,
section = contentType.name,
diff --git a/data/src/main/java/com/streamvault/data/sync/XtreamIncrementalIndexOperationsAdapter.kt b/data/src/main/java/com/streamvault/data/sync/XtreamIncrementalIndexOperationsAdapter.kt
index df92ea50..3ce785b8 100644
--- a/data/src/main/java/com/streamvault/data/sync/XtreamIncrementalIndexOperationsAdapter.kt
+++ b/data/src/main/java/com/streamvault/data/sync/XtreamIncrementalIndexOperationsAdapter.kt
@@ -10,6 +10,8 @@ import com.streamvault.domain.model.Result
import com.streamvault.domain.model.Series
internal data class XtreamIncrementalIndexCallbacks(
+ val beginSnapshot: suspend (Long, ContentType) -> Unit,
+ val finishSnapshot: suspend (Long, ContentType) -> Unit,
val getCategories: suspend (Long, ContentType) -> List<CategoryEntity>,
val ensureCategoryShell: suspend (Provider, XtreamProvider, ContentType, Long, ((String) -> Unit)?) -> Unit,
val getJob: suspend (Long, ContentType) -> XtreamIndexJobEntity?,
@@ -32,6 +34,9 @@ internal data class XtreamIncrementalIndexCallbacks(
internal class CallbackXtreamIncrementalIndexOperations(
private val callbacks: XtreamIncrementalIndexCallbacks
) : XtreamIncrementalIndexOperations {
+ override suspend fun beginSnapshot(providerId: Long, contentType: ContentType) = callbacks.beginSnapshot(providerId, contentType)
+ override suspend fun finishSnapshot(providerId: Long, contentType: ContentType) = callbacks.finishSnapshot(providerId, contentType)
+
override suspend fun getCategories(providerId: Long, contentType: ContentType): List<CategoryEntity> =
callbacks.getCategories(providerId, contentType)
diff --git a/data/src/test/java/com/streamvault/data/local/XtreamSnapshotReconciliationTest.kt b/data/src/test/java/com/streamvault/data/local/XtreamSnapshotReconciliationTest.kt
new file mode 100644
index 00000000..601ba2f1
--- /dev/null
+++ b/data/src/test/java/com/streamvault/data/local/XtreamSnapshotReconciliationTest.kt
@@ -0,0 +1,52 @@
+package com.streamvault.data.local
+
+import androidx.room.Room
+import com.google.common.truth.Truth.assertThat
+import com.streamvault.data.local.entity.MovieEntity
+import com.streamvault.data.local.entity.SeriesEntity
+import com.streamvault.data.local.entity.ProviderEntity
+import com.streamvault.data.local.entity.XtreamContentIndexEntity
+import com.streamvault.domain.model.ContentType
+import com.streamvault.domain.model.ProviderType
+import kotlinx.coroutines.test.runTest
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.robolectric.RobolectricTestRunner
+import org.robolectric.RuntimeEnvironment
+
+@RunWith(RobolectricTestRunner::class)
+class XtreamSnapshotReconciliationTest {
+ @Test fun `successful snapshot removes missing movies and series but retains active indexes and other providers`() = runTest {
+ val db = Room.inMemoryDatabaseBuilder(RuntimeEnvironment.getApplication(), StreamVaultDatabase::class.java)
+ .allowMainThreadQueries().build()
+ try {
+ for (providerId in listOf(1L, 2L)) {
+ db.providerDao().insert(ProviderEntity(id = providerId, name = "Fixture", type = ProviderType.XTREAM_CODES))
+ db.movieDao().insertAll(listOf(MovieEntity(providerId = providerId, streamId = 10, name = "Gone"),
+ MovieEntity(providerId = providerId, streamId = 20, name = "Retained")))
+ db.seriesDao().insertAll(listOf(SeriesEntity(providerId = providerId, seriesId = 10, name = "Gone"),
+ SeriesEntity(providerId = providerId, seriesId = 20, name = "Retained")))
+ for (type in listOf(ContentType.MOVIE, ContentType.SERIES)) {
+ db.xtreamContentIndexDao().upsertAll(listOf(
+ XtreamContentIndexEntity(providerId, type, "10", name = "Gone"),
+ XtreamContentIndexEntity(providerId, type, "20", name = "Retained", indexedAt = 100)))
+ }
+ }
+ val index = db.xtreamContentIndexDao()
+ assertThat(db.movieDao().getByStreamId(1, 10)).isNotNull()
+ for (type in listOf(ContentType.MOVIE, ContentType.SERIES)) {
+ index.beginSnapshot(1, type.name)
+ assertThat(index.countActiveRows(1, type.name)).isEqualTo(2)
+ // An incomplete import has not removed any cached content.
+ index.upsert(XtreamContentIndexEntity(1, type, "20", name = "Retained", indexedAt = 100))
+ assertThat(index.pruneCompletedSnapshot(1, type.name)).isEqualTo(1)
+ assertThat(index.getByRemoteId(1, type.name, "10")).isNull()
+ assertThat(index.getByRemoteId(1, type.name, "20")).isNotNull()
+ assertThat(index.getByRemoteId(2, type.name, "10")).isNotNull()
+ }
+ assertThat(db.movieDao().getByStreamId(1, 10)).isNull()
+ assertThat(db.movieDao().getByStreamId(1, 20)).isNotNull()
+ assertThat(db.movieDao().getByStreamId(2, 10)).isNotNull()
+ } finally { db.close() }
+ }
+}
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 cd32598f..ea1af138 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
@@ -36,6 +36,17 @@ import org.junit.Test
@OptIn(ExperimentalCoroutinesApi::class)
class XtreamProviderTest {
+ @Test fun `malformed summaries cannot certify complete snapshot coverage`() = runTest {
+ val provider = XtreamProvider(providerId = 42,
+ api = FakeXtreamApiService(
+ vodStreams = listOf(vodStream("1"), vodStream("1").copy(streamId = 0)),
+ seriesList = listOf(XtreamSeriesItem(seriesId = 1, name = "Valid"),
+ XtreamSeriesItem(seriesId = 0, name = "Invalid"))),
+ serverUrl = "https://example.com", username = "user", password = "pass")
+ assertThat(provider.streamVodSummaries(adultCategoryIds = emptySet()) { }).isInstanceOf(Result.Error::class.java)
+ assertThat(provider.streamSeriesSummaries(adultCategoryIds = emptySet()) { }).isInstanceOf(Result.Error::class.java)
+ }
+
@Test
fun `series compatibility fallback preserves cancellation and does not issue legacy request`() = runTest {
val requestedEndpoints = mutableListOf<String>()
diff --git a/data/src/test/java/com/streamvault/data/sync/XtreamIncrementalIndexExecutorTest.kt b/data/src/test/java/com/streamvault/data/sync/XtreamIncrementalIndexExecutorTest.kt
index 7f289b31..3270970f 100644
--- a/data/src/test/java/com/streamvault/data/sync/XtreamIncrementalIndexExecutorTest.kt
+++ b/data/src/test/java/com/streamvault/data/sync/XtreamIncrementalIndexExecutorTest.kt
@@ -122,8 +122,8 @@ class XtreamIncrementalIndexExecutorTest {
assertThat(operations.fetchedCategoryIds).containsExactly(1L, 2L).inOrder()
assertThat(operations.updates.last().nextCategoryIndex).isEqualTo(1)
- assertThat(operations.updates.last().state).isEqualTo("QUEUED")
- assertThat(operations.scheduled).containsExactly(ContentType.MOVIE)
+ assertThat(operations.updates.last().state).isEqualTo("PARTIAL")
+ assertThat(operations.scheduled).isEmpty()
}
@Test
@@ -246,6 +246,43 @@ class XtreamIncrementalIndexExecutorTest {
assertThat(operations.scheduled).containsExactly(ContentType.MOVIE)
}
+ @Test fun `retryable checkpoint resumes category cursor instead of restarting bulk`() = runTest {
+ val operations = FakeOperations(listOf(category(1L), category(2L), category(3L)),
+ job = XtreamIndexJobEntity(providerId = 1L, section = "MOVIE", state = "FAILED_RETRYABLE",
+ nextCategoryIndex = 2, completedCategories = 2, indexedRows = 20))
+ XtreamIncrementalIndexExecutor(operations).processSummary(provider(), mock(), ContentType.MOVIE, 4, onProgress = null)
+ assertThat(operations.fetchedCategoryIds).containsExactly(3L)
+ assertThat(operations.updates.last().indexedRows).isEqualTo(20)
+ }
+
+ @Test fun `failed bulk without categories cannot publish success or prune cached rows`() = runTest {
+ val failure = IOException("timeout")
+ val operations = FakeOperations(emptyList(), streamMovieResult = Result.error("timeout", failure))
+ try {
+ XtreamIncrementalIndexExecutor(operations).processSummary(provider(), mock(), ContentType.MOVIE, 4, onProgress = null)
+ error("Expected failure")
+ } catch (error: IOException) { assertThat(error).isSameInstanceAs(failure) }
+ assertThat(operations.updates.none { it.state == "SUCCESS" }).isTrue()
+ assertThat(operations.snapshots).doesNotContain("finish")
+ }
+
+ @Test fun `failed category preserves cache and does not schedule another failing pass`() = runTest {
+ val operations = FakeOperations(listOf(category(1L), category(2L)),
+ streamMovieResult = Result.error("unavailable"), failureCategoryId = 1L)
+ XtreamIncrementalIndexExecutor(operations).processSummary(provider(), mock(), ContentType.MOVIE, 4, onProgress = null)
+ assertThat(operations.updates.last().state).isEqualTo("PARTIAL")
+ assertThat(operations.updates.last().nextCategoryIndex).isEqualTo(0)
+ assertThat(operations.scheduled).isEmpty()
+ assertThat(operations.snapshots).doesNotContain("finish")
+ }
+
+ @Test fun `successful bulk reconciles deleted rows before publishing success`() = runTest {
+ val operations = FakeOperations(listOf(category(1L)), streamMovieResult = Result.success(7))
+ XtreamIncrementalIndexExecutor(operations).processSummary(provider(), mock(), ContentType.MOVIE, 4, onProgress = null)
+ assertThat(operations.snapshots).containsExactly("begin", "finish").inOrder()
+ assertThat(operations.updates.last().state).isEqualTo("SUCCESS")
+ }
+
private class FakeOperations(
private val categories: List<CategoryEntity>,
private val job: XtreamIndexJobEntity? = null,
@@ -260,6 +297,9 @@ class XtreamIncrementalIndexExecutorTest {
val fetchedCategoryIds = mutableListOf<Long>()
val metadataUpdates = mutableListOf<Any>()
val scheduled = mutableListOf<ContentType>()
+ val snapshots = mutableListOf<String>()
+ override suspend fun beginSnapshot(providerId: Long, contentType: ContentType) { snapshots += "begin" }
+ override suspend fun finishSnapshot(providerId: Long, contentType: ContentType) { snapshots += "finish" }
private var elapsedRealtimeMillis = 0L
override fun monotonicTimeMillis() = elapsedRealtimeMillis
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index a25a67fc..8820d064 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -18,6 +18,7 @@ All notable product changes are recorded in this document.
- Stremio live TV catalogs and programme guides are available under Extensions; they do not become IPTV provider channels in the main Live TV tab.
### Fixed
+- Fixed Xtream movie and series refresh recovery: failed categories no longer loop without progress, retries resume from saved checkpoints, Settings returns control after work is queued, and deleted VOD items are reconciled only after a complete successful refresh.
- Fixed archive seeks through Stremio Service by preventing an extra response byte from corrupting later requests on a reused connection.
- Fixed VOD player controls disappearing while navigating with the remote; the idle timer now restarts after each key press.
- Raised XMLTV ingestion limits for very large feeds to 2 GiB downloaded and 4 GiB decompressed while keeping parsing streamed.
diff --git a/feature/settings/src/main/java/com/streamvault/feature/settings/presentation/SettingsSyncActions.kt b/feature/settings/src/main/java/com/streamvault/feature/settings/presentation/SettingsSyncActions.kt
index 6215eb30..430ea67c 100644
--- a/feature/settings/src/main/java/com/streamvault/feature/settings/presentation/SettingsSyncActions.kt
+++ b/feature/settings/src/main/java/com/streamvault/feature/settings/presentation/SettingsSyncActions.kt
@@ -7,16 +7,16 @@ import com.streamvault.domain.settings.SettingsOperations
import com.streamvault.domain.settings.SettingsSyncSection
import com.streamvault.domain.model.Result
import com.streamvault.domain.model.ProviderType
-import com.streamvault.domain.settings.SettingsXtreamIndexJob
import com.streamvault.domain.model.LegacyProvider as Provider
import com.streamvault.domain.sync.ProviderSectionSyncResult
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.CoroutineStart
import kotlinx.coroutines.Job
import kotlinx.coroutines.CancellationException
+import com.streamvault.domain.settings.SettingsXtreamIndexJob
+import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.update
-import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.ensureActive
@@ -128,7 +128,6 @@ internal class SettingsSyncActions(
try {
val failures = mutableListOf<String>()
val completed = mutableListOf<String>()
- val queuedCatalogSections = mutableSetOf<ProviderSyncSelection>()
val combinedPlaylist = uiState.value.providers.firstOrNull { it.id == providerId }?.type == ProviderType.M3U &&
ProviderSyncSelection.TV in selections && ProviderSyncSelection.MOVIES in selections
if (queueEpg) {
@@ -178,9 +177,6 @@ internal class SettingsSyncActions(
is Result.Success -> {
val receipt = result.data
hasQueuedWork = hasQueuedWork || receipt.queued
- if (receipt.queued && selection in setOf(ProviderSyncSelection.MOVIES, ProviderSyncSelection.SERIES)) {
- queuedCatalogSections += selection
- }
if (section == SettingsSyncSection.LIVE && receipt.catalogChanged) {
// Refresh TV integration immediately, even if a later section is cancelled.
surfaceRefreshPort.enqueueTvInputCatalogRefresh()
@@ -212,35 +208,6 @@ internal class SettingsSyncActions(
}
}
}
- if (queuedCatalogSections.isNotEmpty()) {
- val sections = queuedCatalogSections.associateBy {
- if (it == ProviderSyncSelection.MOVIES) "MOVIE" else "SERIES"
- }
- val jobs = awaitSettingsCatalogIndex(settingsOperations, providerId, sections.keys) { job ->
- val selection = sections.getValue(job.section)
- val stage = if (job.state in setOf("QUEUED", "STALE", "RETRY_WAIT")) R.string.settings_sync_section_queued
- else R.string.settings_syncing_section
- uiState.update { it.copy(
- syncSectionLabel = selection.label(appContext),
- syncProgress = appContext.getString(R.string.settings_sync_index_progress,
- appContext.getString(stage, selection.label(appContext)),
- java.text.NumberFormat.getIntegerInstance().format(job.indexedRows))
- ) }
- }
- sections.forEach { (key, selection) ->
- completed.remove(appContext.getString(R.string.settings_sync_section_queued, selection.label(appContext)))
- if (jobs.any { it.section == key && it.state in setOf("SUCCESS", "COMPLETE") }) {
- completed += selection.label(appContext)
- uiState.update { state ->
- val warnings = state.syncWarningsByProvider[providerId].orEmpty().filterNot {
- it.startsWith("${selection.label(appContext)}:") || it.startsWith("${selection.label(appContext)} ·")
- }
- state.copy(syncWarningsByProvider = if (warnings.isEmpty()) state.syncWarningsByProvider - providerId
- else state.syncWarningsByProvider + (providerId to warnings))
- }
- } else failures += appContext.getString(R.string.settings_sync_incomplete)
- }
- }
uiState.update {
it.copy(userMessage = when {
failures.isEmpty() -> appContext.getString(
@@ -274,6 +241,7 @@ internal class SettingsSyncActions(
}
}
+
/** Foreground ownership lasts until durable indexing terminates; cancelling only stops waiting. */
internal suspend fun awaitSettingsCatalogIndex(
operations: SettingsOperations,
diff --git a/feature/settings/src/test/java/com/streamvault/feature/settings/presentation/SettingsSyncActionsTest.kt b/feature/settings/src/test/java/com/streamvault/feature/settings/presentation/SettingsSyncActionsTest.kt
index 0f4a3cec..20bbf7ae 100644
--- a/feature/settings/src/test/java/com/streamvault/feature/settings/presentation/SettingsSyncActionsTest.kt
+++ b/feature/settings/src/test/java/com/streamvault/feature/settings/presentation/SettingsSyncActionsTest.kt
@@ -87,7 +87,7 @@ class SettingsSyncActionsTest {
verify(operations, never()).syncProviderSection(eq(7L), eq(SettingsSyncSection.EPG), any())
verify(operations).scheduleBackgroundEpgSync(7L)
assertThat(state.value.userMessage).contains("Series")
- assertThat(state.value.userMessage).doesNotContain("Series refresh queued")
+ assertThat(state.value.userMessage).contains("Series refresh queued")
assertThat(state.value.userMessage).contains("EPG refresh queued")
assertThat(state.value.isSyncing).isFalse()
}
@@ -117,9 +117,9 @@ class SettingsSyncActionsTest {
actions.retryWarningAction(this, 7L, ProviderWarningAction.MOVIES)
advanceUntilIdle()
- assertThat(state.value.syncWarningsByProvider[7L]).isNull()
+ assertThat(state.value.syncWarningsByProvider[7L]).containsExactly("Movies: Missing rows")
assertThat(state.value.userMessage).contains("Movies")
- assertThat(state.value.userMessage).doesNotContain("Movies refresh queued")
+ assertThat(state.value.userMessage).contains("Movies refresh queued")
}
@Test
@@ -202,36 +202,17 @@ class SettingsSyncActionsTest {
).inOrder()
}
- @Test fun `manual catalog loading stays visible through queued running and completed states`() = runTest {
- val jobs = MutableStateFlow(listOf(SettingsXtreamIndexJob(7L, "MOVIE", "QUEUED", 0, null)))
- whenever(operations.observeXtreamIndexJobs()).thenReturn(jobs)
- whenever(operations.syncProviderSection(eq(7L), eq(SettingsSyncSection.MOVIES), any()))
- .thenReturn(Result.success(ProviderSectionSyncResult(queued = true)))
- actions.syncProviderSection(this, 7L, ProviderSyncSelection.MOVIES)
- runCurrent()
- assertThat(state.value.isSyncing).isTrue()
- jobs.value = listOf(SettingsXtreamIndexJob(7L, "MOVIE", "RUNNING", 25, null))
- runCurrent()
- assertThat(state.value.syncProgress).contains("25")
- jobs.value = listOf(SettingsXtreamIndexJob(7L, "MOVIE", "SUCCESS", 50, null))
- advanceUntilIdle()
- assertThat(state.value.isSyncing).isFalse()
- assertThat(state.value.userMessage).contains("Movies")
- assertThat(state.value.userMessage).doesNotContain("queued")
- }
-
- @Test fun `cancel while awaiting durable indexing explains that the work continues`() = runTest {
+ @Test fun `queued movie refresh releases overlay even when worker never starts`() = runTest {
whenever(operations.observeXtreamIndexJobs()).thenReturn(MutableStateFlow(listOf(
SettingsXtreamIndexJob(7L, "MOVIE", "QUEUED", 0, null)
)))
whenever(operations.syncProviderSection(eq(7L), eq(SettingsSyncSection.MOVIES), any()))
.thenReturn(Result.success(ProviderSectionSyncResult(queued = true)))
actions.syncProviderSection(this, 7L, ProviderSyncSelection.MOVIES)
- runCurrent()
- actions.cancelSync()
advanceUntilIdle()
assertThat(state.value.isSyncing).isFalse()
- assertThat(state.value.userMessage).contains("queued work will continue")
+ assertThat(state.value.userMessage).contains("Movies refresh queued")
+ verify(operations, never()).observeXtreamIndexJobs()
}
@Test fun `M3U combined refresh uses one complete playlist operation`() = runTest {