Skip to content

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

Add localization for sync index progress and enhance tests

David Nashash470d49d706d4
diff --git a/app/src/androidTest/java/com/streamvault/app/benchmark/AutomaticProviderSyncRuntimeTest.kt b/app/src/androidTest/java/com/streamvault/app/benchmark/AutomaticProviderSyncRuntimeTest.kt
index 7a671f84..0e600cd8 100644
--- a/app/src/androidTest/java/com/streamvault/app/benchmark/AutomaticProviderSyncRuntimeTest.kt
+++ b/app/src/androidTest/java/com/streamvault/app/benchmark/AutomaticProviderSyncRuntimeTest.kt
@@ -70,7 +70,8 @@ class AutomaticProviderSyncRuntimeTest {
try {
graph.preferences().setAutomaticSyncSettings(null, original.defaults.copy(enabled = true))
val added = graph.providers().addProvider(LegacyProvider(name = "Automatic sync fixture", type = ProviderType.M3U,
- serverUrl = "$base/playlist.m3u", m3uUrl = "$base/playlist.m3u", isActive = false, epgSyncMode = ProviderEpgSyncMode.SKIP))
+ serverUrl = "$base/playlist.m3u", m3uUrl = "$base/playlist.m3u", isActive = false, epgSyncMode = ProviderEpgSyncMode.SKIP,
+ m3uVodClassificationEnabled = true))
check(added is Result.Success)
val id = added.data
providerId = id
@@ -114,6 +115,18 @@ class AutomaticProviderSyncRuntimeTest {
assertThat(requests.get()).isEqualTo(disabledRequests)
assertThat(graph.sync().syncSection(id, SyncRepairSection.LIVE)).isInstanceOf(Result.Success::class.java)
assertThat(requests.get()).isGreaterThan(disabledRequests)
+
+ // Explicit complete-playlist refresh remains available with automatic sync
+ // disabled, downloads once, and reconciles an emptied opposite section.
+ playlist.set("#EXTM3U\n" + entry("a", "Updated") +
+ "#EXTINF:-1 group-title=\"Movies\",New Movie\n$base/movie/new.mp4\n")
+ val beforeManual = requests.get()
+ assertThat(graph.sync().refreshPlaylistCatalog(id)).isInstanceOf(Result.Success::class.java)
+ assertThat(requests.get()).isEqualTo(beforeManual + 1)
+ assertThat(graph.database().movieDao().getByProvider(id).first().map { it.name }).containsExactly("New Movie")
+ playlist.set("#EXTM3U\n" + entry("a", "Updated"))
+ assertThat(graph.sync().refreshPlaylistCatalog(id)).isInstanceOf(Result.Success::class.java)
+ assertThat(graph.database().movieDao().getByProvider(id).first()).isEmpty()
} finally {
providerId?.let { id -> graph.providers().deleteProvider(id); graph.preferences().setAutomaticSyncSettings(id, null) }
graph.preferences().setAutomaticSyncSettings(null, original.defaults)
diff --git a/app/src/androidTest/java/com/streamvault/app/benchmark/XtreamMovieRefreshRuntimeTest.kt b/app/src/androidTest/java/com/streamvault/app/benchmark/XtreamMovieRefreshRuntimeTest.kt
new file mode 100644
index 00000000..935d92e1
--- /dev/null
+++ b/app/src/androidTest/java/com/streamvault/app/benchmark/XtreamMovieRefreshRuntimeTest.kt
@@ -0,0 +1,117 @@
+package com.streamvault.app.benchmark
+
+import android.app.Application
+import android.net.Uri
+import androidx.test.core.app.ApplicationProvider
+import androidx.test.ext.junit.runners.AndroidJUnit4
+import androidx.test.platform.app.InstrumentationRegistry
+import com.google.common.truth.Truth.assertThat
+import com.streamvault.data.sync.SyncRepairSection
+import com.streamvault.domain.model.LegacyProvider
+import com.streamvault.domain.model.ProviderEpgSyncMode
+import com.streamvault.domain.model.ProviderType
+import com.streamvault.domain.model.Result
+import com.streamvault.domain.sync.AutomaticSyncSettings
+import dagger.hilt.android.EntryPointAccessors
+import java.net.ServerSocket
+import java.util.concurrent.atomic.AtomicInteger
+import kotlin.concurrent.thread
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.flow.first
+import kotlinx.coroutines.runBlocking
+import kotlinx.coroutines.withContext
+import kotlinx.coroutines.withTimeout
+import org.junit.Assume.assumeTrue
+import org.junit.Test
+import org.junit.runner.RunWith
+
+/** Opt-in local HTTP fixture; no real provider credentials or playback are used. */
+@RunWith(AndroidJUnit4::class)
+class XtreamMovieRefreshRuntimeTest {
+ @Test fun manualAndUpgradeCatchupDiscoverNewMovies() = runBlocking<Unit> {
+ assumeTrue(InstrumentationRegistry.getArguments().getString("automaticSyncProbe") == "true")
+ val app = ApplicationProvider.getApplicationContext<Application>()
+ check(app.packageName.endsWith(".debug"))
+ val graph = EntryPointAccessors.fromApplication(app, XtreamSyncBenchmarkEntryPoint::class.java)
+ val original = graph.preferences().automaticSyncConfiguration.first()
+ val socket = ServerSocket(0)
+ val base = "http://127.0.0.1:${socket.localPort}"
+ val movieCount = AtomicInteger(1)
+ val movieRequests = AtomicInteger()
+ val server = thread(isDaemon = true, name = "xtream-movie-refresh-fixture") {
+ while (!socket.isClosed) {
+ try {
+ socket.accept().use { client ->
+ client.soTimeout = 5000
+ val reader = client.getInputStream().bufferedReader()
+ val path = reader.readLine().split(' ').getOrNull(1).orEmpty()
+ while (!reader.readLine().isNullOrEmpty()) { }
+ val action = Uri.parse(base + path).getQueryParameter("action")
+ val body = when (action) {
+ "get_vod_categories" -> """[{"category_id":"42","category_name":"Fixture Movies"}]"""
+ "get_vod_streams" -> {
+ movieRequests.incrementAndGet()
+ (1..movieCount.get()).joinToString(prefix = "[", postfix = "]") { id ->
+ """{"stream_id":$id,"name":"Fixture Movie $id","category_id":"42","container_extension":"mp4","added":"1700000000"}"""
+ }
+ }
+ "get_series_categories", "get_series", "get_live_categories", "get_live_streams" -> "[]"
+ else -> """{"user_info":{"auth":1,"status":"Active","max_connections":"2"},"server_info":{"url":"127.0.0.1"}}"""
+ }.toByteArray()
+ client.getOutputStream().apply {
+ write("HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: ${body.size}\r\nConnection: close\r\n\r\n".toByteArray())
+ write(body); flush()
+ }
+ }
+ } catch (error: Exception) { if (!socket.isClosed) throw error }
+ }
+ }
+ var providerId: Long? = null
+ try {
+ graph.preferences().setAutomaticSyncSettings(null, original.defaults.copy(enabled = false))
+ val added = graph.providers().addProvider(LegacyProvider(name = "Xtream Movie refresh fixture",
+ type = ProviderType.XTREAM_CODES, serverUrl = base, username = "fixture", password = "fixture",
+ isActive = false, epgSyncMode = ProviderEpgSyncMode.SKIP))
+ check(added is Result.Success)
+ val id = added.data
+ providerId = id
+ suspend fun awaitMovies(count: Int) = withTimeout(90_000L) {
+ while (true) {
+ val movies = graph.database().movieDao().getByProvider(id).first()
+ val job = graph.database().xtreamIndexJobDao().get(id, "MOVIE")
+ if (movies.size == count && job?.state == "SUCCESS") return@withTimeout movies
+ check(job?.state != "FAILED_PERMANENT") { "Fixture Movie index failed permanently" }
+ delay(200L)
+ }
+ @Suppress("UNREACHABLE_CODE") error("unreachable")
+ }
+ assertThat(graph.sync().syncSection(id, SyncRepairSection.MOVIES)).isInstanceOf(Result.Success::class.java)
+ val first = awaitMovies(1)
+ val firstId = first.single().id
+ movieCount.set(2)
+ assertThat(graph.sync().syncSection(id, SyncRepairSection.MOVIES)).isInstanceOf(Result.Success::class.java)
+ val manual = awaitMovies(2)
+ assertThat(manual.single { it.name == "Fixture Movie 1" }.id).isEqualTo(firstId)
+
+ // The existing Movie success is fresh. A new sync-engine checkpoint must
+ // still request catch-up instead of carrying the old freshness across it.
+ movieCount.set(3)
+ graph.preferences().setAutomaticSyncSettings(id, AutomaticSyncSettings(
+ live = false, movies = true, series = false, epg = false, deferWhileBusy = false))
+ graph.preferences().setAutomaticSyncSettings(null, original.defaults.copy(enabled = true))
+ val automatic = awaitMovies(3)
+ assertThat(automatic.map { it.name }).containsExactly("Fixture Movie 1", "Fixture Movie 2", "Fixture Movie 3")
+ assertThat(movieRequests.get()).isAtLeast(3)
+ assertThat(graph.providers().getProvider(id)?.isActive).isFalse()
+ } finally {
+ providerId?.let { id ->
+ graph.providers().deleteProvider(id)
+ graph.preferences().setAutomaticSyncSettings(id, null)
+ }
+ graph.preferences().setAutomaticSyncSettings(null, original.defaults)
+ socket.close()
+ withContext(Dispatchers.IO) { server.join(5000L) }
+ }
+ }
+}
diff --git a/app/src/main/java/com/streamvault/app/AppStartupCoordinator.kt b/app/src/main/java/com/streamvault/app/AppStartupCoordinator.kt
index 65dc2444..6002b6eb 100644
--- a/app/src/main/java/com/streamvault/app/AppStartupCoordinator.kt
+++ b/app/src/main/java/com/streamvault/app/AppStartupCoordinator.kt
@@ -49,7 +49,9 @@ internal class AppStartupCoordinator internal constructor(
private val tvTasks: List<AppStartupTask>,
private val scope: CoroutineScope,
private val traceSection: TraceSection = ::runWithoutAndroidTrace,
- private val onTaskFailure: (String, Throwable) -> Unit = { _, _ -> }
+ private val onTaskFailure: (String, Throwable) -> Unit = { _, _ -> },
+ private val foregroundCheck: () -> Unit = {},
+ private val monotonicTimeMillis: () -> Long = { System.nanoTime() / 1_000_000L }
) {
@Inject
@@ -98,11 +100,27 @@ internal class AppStartupCoordinator internal constructor(
),
scope = CoroutineScope(SupervisorJob() + Dispatchers.IO),
traceSection = ::runWithAndroidTrace,
- onTaskFailure = ::logTaskFailure
+ onTaskFailure = ::logTaskFailure,
+ foregroundCheck = { com.streamvault.data.sync.ProviderSyncWorker.enqueueForegroundCheck(context) }
)
private val processMaintenanceStarted = AtomicBoolean(false)
private val firstUiFrameHandled = AtomicBoolean(false)
+ private var lastForegroundCheckAt: Long? = null
+
+ /** Returning to a retained process must also check for newly stale catalogs. */
+ @Synchronized
+ fun onAppForegrounded() {
+ val now = monotonicTimeMillis()
+ val last = lastForegroundCheckAt
+ if (last != null && now >= last && now - last < 30_000L) return
+ try {
+ foregroundCheck()
+ lastForegroundCheckAt = now
+ } catch (error: Exception) {
+ onTaskFailure("foreground-sync-check", error)
+ }
+ }
/** Starts process maintenance once, even when no Activity is created. */
fun startProcessMaintenance() {
diff --git a/app/src/main/java/com/streamvault/app/MainActivity.kt b/app/src/main/java/com/streamvault/app/MainActivity.kt
index 97fe2d67..a051e699 100644
--- a/app/src/main/java/com/streamvault/app/MainActivity.kt
+++ b/app/src/main/java/com/streamvault/app/MainActivity.kt
@@ -277,6 +277,7 @@ class MainActivity : ComponentActivity(), CatalogPlatformHost {
override fun onResume() {
super.onResume()
applyImmersiveSystemUi()
+ appStartupCoordinator.onAppForegrounded()
}
private fun closeApp() {
diff --git a/app/src/main/java/com/streamvault/app/diagnostics/CrashReportStore.kt b/app/src/main/java/com/streamvault/app/diagnostics/CrashReportStore.kt
index 8199da71..a59176cd 100644
--- a/app/src/main/java/com/streamvault/app/diagnostics/CrashReportStore.kt
+++ b/app/src/main/java/com/streamvault/app/diagnostics/CrashReportStore.kt
@@ -26,10 +26,16 @@ object CrashReportStore {
const val MIME_TYPE_TEXT = "text/plain"
private const val CRASH_DIR = "diagnostics/crash"
private const val LATEST_FILE_NAME = "latest-crash.txt"
+ private const val TEMP_FILE_NAME = "$LATEST_FILE_NAME.tmp"
+ private const val ARCHIVED_FILE_PREFIX = "crash-"
+ private const val ARCHIVED_FILE_SUFFIX = ".txt"
+ private const val MAX_STORED_REPORTS = 5
+ private const val MAX_ARCHIVED_REPORTS = MAX_STORED_REPORTS - 1
private const val PLAYBACK_SUPPORT_FILE_NAME = "latest-playback-support.txt"
private const val MAX_REPORT_CHARS = 64_000
private val installed = AtomicBoolean(false)
private val writingCrash = AtomicBoolean(false)
+ private val reportLock = Any()
private val formatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME
private val urlPattern = Regex("""https?://[^\s"'<>]+""", RegexOption.IGNORE_CASE)
private val sensitiveParamPattern = Regex(
@@ -42,10 +48,7 @@ object CrashReportStore {
Thread.setDefaultUncaughtExceptionHandler { thread, throwable ->
if (writingCrash.compareAndSet(false, true)) {
runCatching {
- latestReportFile(application).writeText(
- buildReport(application, thread, throwable),
- Charsets.UTF_8
- )
+ saveReport(application, buildReport(application, thread, throwable))
}
writingCrash.set(false)
}
@@ -75,16 +78,28 @@ object CrashReportStore {
file.parentFile?.mkdirs()
}
- fun deleteLatestReport(context: Context): Boolean =
- latestReportFile(context).delete()
+ fun deleteLatestReport(context: Context): Boolean = synchronized(reportLock) {
+ val latest = latestReportFile(context)
+ val directory = latest.parentFile ?: return@synchronized false
+ val reports = archivedReports(directory) + latest + File(directory, TEMP_FILE_NAME)
+ var foundReport = false
+ var allDeleted = true
+ reports.distinct().forEach { file ->
+ if (file.exists()) {
+ foundReport = true
+ if (!file.delete()) allDeleted = false
+ }
+ }
+ foundReport && allDeleted
+ }
fun recordHandledFailure(context: Context, operation: String, throwable: Throwable) {
runCatching {
- latestReportFile(context).writeText(
+ saveReport(
+ context,
buildReport(context, Thread.currentThread(), throwable)
.replaceFirst("StreamVault Crash Report", "StreamVault Failure Report")
- .plus("\nOperation: ${sanitize(operation)}\n"),
- Charsets.UTF_8
+ .plus("\nOperation: ${sanitize(operation)}\n")
)
}
}
@@ -135,6 +150,62 @@ object CrashReportStore {
}.take(MAX_REPORT_CHARS)
}
+ private fun saveReport(context: Context, content: String) = synchronized(reportLock) {
+ val latest = latestReportFile(context)
+ val directory = latest.parentFile ?: return@synchronized
+ val temporary = File(directory, TEMP_FILE_NAME)
+
+ // Write the new report before rotating so a failed write preserves the current report.
+ temporary.writeText(content, Charsets.UTF_8)
+
+ if (latest.isFile && latest.length() > 0L) {
+ archiveLatestReport(latest)
+ } else {
+ latest.delete()
+ }
+ trimArchivedReports(directory)
+
+ if (!temporary.renameTo(latest)) {
+ temporary.copyTo(latest, overwrite = true)
+ temporary.delete()
+ }
+ }
+
+ private fun archiveLatestReport(latest: File) {
+ val directory = latest.parentFile ?: return
+ val timestamp = latest.lastModified().takeIf { it > 0L } ?: System.currentTimeMillis()
+ var suffix = 0
+ var archived: File
+ do {
+ archived = File(directory, "$ARCHIVED_FILE_PREFIX$timestamp-$suffix$ARCHIVED_FILE_SUFFIX")
+ suffix++
+ } while (archived.exists())
+
+ if (!latest.renameTo(archived)) {
+ runCatching { latest.copyTo(archived, overwrite = false) }
+ .onSuccess { latest.delete() }
+ }
+ }
+
+ private fun trimArchivedReports(directory: File) {
+ val reports = archivedReports(directory)
+ .sortedWith(compareBy<File> { archiveTimestamp(it) }.thenBy { it.name })
+ reports.take((reports.size - MAX_ARCHIVED_REPORTS).coerceAtLeast(0))
+ .forEach(File::delete)
+ }
+
+ private fun archiveTimestamp(file: File): Long =
+ file.name.removePrefix(ARCHIVED_FILE_PREFIX)
+ .substringBefore('-')
+ .toLongOrNull()
+ ?: file.lastModified()
+
+ private fun archivedReports(directory: File): List<File> =
+ directory.listFiles { file ->
+ file.isFile && file.name.startsWith(ARCHIVED_FILE_PREFIX) &&
+ file.name.endsWith(ARCHIVED_FILE_SUFFIX)
+ }?.toList().orEmpty()
+
private fun latestPlaybackSupport(context: Context): String? {
val file = File(context.filesDir, "$CRASH_DIR/$PLAYBACK_SUPPORT_FILE_NAME")
if (!file.isFile || file.length() <= 0L) return null
diff --git a/app/src/test/java/com/streamvault/app/AppStartupCoordinatorTest.kt b/app/src/test/java/com/streamvault/app/AppStartupCoordinatorTest.kt
index 275d7b88..3a39b1ef 100644
--- a/app/src/test/java/com/streamvault/app/AppStartupCoordinatorTest.kt
+++ b/app/src/test/java/com/streamvault/app/AppStartupCoordinatorTest.kt
@@ -16,6 +16,35 @@ import com.google.common.truth.Truth.assertThat
@OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)
class AppStartupCoordinatorTest {
+ @Test
+ fun foregroundChecksRepeatForRetainedProcessesButThrottleQuickResumes() = runTest {
+ var now = 0L
+ var checks = 0
+ val coordinator = AppStartupCoordinator(emptyList(), emptyList(), this,
+ foregroundCheck = { checks++ }, monotonicTimeMillis = { now })
+ coordinator.onAppForegrounded()
+ coordinator.onAppForegrounded()
+ now = 29_999L
+ coordinator.onAppForegrounded()
+ assertThat(checks).isEqualTo(1)
+ now = 86_400_000L
+ coordinator.onAppForegrounded()
+ assertThat(checks).isEqualTo(2)
+ }
+
+ @Test
+ fun foregroundSchedulingFailureDoesNotCrashOrThrottleTheNextAttempt() = runTest {
+ var attempts = 0
+ val failures = mutableListOf<String>()
+ val coordinator = AppStartupCoordinator(emptyList(), emptyList(), this,
+ foregroundCheck = { if (++attempts == 1) error("unavailable") },
+ onTaskFailure = { name, _ -> failures += name })
+ coordinator.onAppForegrounded()
+ coordinator.onAppForegrounded()
+ assertThat(attempts).isEqualTo(2)
+ assertThat(failures).containsExactly("foreground-sync-check")
+ }
+
@Test
fun processMaintenanceStartsOnceWithoutAnActivity() = runTest {
val dispatcher = StandardTestDispatcher(testScheduler)
diff --git a/data/build.gradle.kts b/data/build.gradle.kts
index 91f63234..d04f4d59 100644
--- a/data/build.gradle.kts
+++ b/data/build.gradle.kts
@@ -27,6 +27,7 @@ android {
// Library instrumentation runs as its own APK on current Android.
targetSdk = 36
unitTests.isReturnDefaultValues = true
+ unitTests.isIncludeAndroidResources = true
}
lint {
diff --git a/data/src/main/java/com/streamvault/data/manager/PreferenceBackupRegistry.kt b/data/src/main/java/com/streamvault/data/manager/PreferenceBackupRegistry.kt
index af590703..a151ae0c 100644
--- a/data/src/main/java/com/streamvault/data/manager/PreferenceBackupRegistry.kt
+++ b/data/src/main/java/com/streamvault/data/manager/PreferenceBackupRegistry.kt
@@ -86,7 +86,7 @@ internal object PreferenceBackupRegistry {
private val runtimeStoragePrefixes = setOf(
"xtream_text_import_applied_generation_", "last_live_category_id_",
"last_split_catalog_type_", "aspect_ratio_", "guide_empty_keys_v1_", "automatic_sync_status_",
- "sports_event_channel_pick_"
+ "sports_event_channel_pick_", "catalog_sync_engine_", "catalog_sync_upgrade_started_"
)
private val providerKeys = setOf(
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 f3f76de2..318a7fe4 100644
--- a/data/src/main/java/com/streamvault/data/preferences/PreferencesRepository.kt
+++ b/data/src/main/java/com/streamvault/data/preferences/PreferencesRepository.kt
@@ -384,7 +384,27 @@ class PreferencesRepository @Inject constructor(
}
// Update durable work immediately; the worker re-reads policy before each section.
com.streamvault.data.sync.ProviderSyncWorker.enqueuePeriodic(context)
- com.streamvault.data.sync.ProviderSyncWorker.enqueueLaunchStaleCheck(context)
+ com.streamvault.data.sync.ProviderSyncWorker.enqueueForegroundCheck(context)
+ }
+
+ /** Runtime-only upgrade catch-up; completion is recorded only after successful sections. */
+ suspend fun catalogSyncUpgradeStartedAt(providerId: Long): Long? {
+ val applied = intPreferencesKey("catalog_sync_engine_$providerId")
+ val started = longPreferencesKey("catalog_sync_upgrade_started_$providerId")
+ val values = preferencesDataStore.edit { values ->
+ val now = System.currentTimeMillis()
+ if ((values[applied] ?: 0) < 1 && ((values[started] ?: 0L) <= 0L || (values[started] ?: 0L) > now)) {
+ values[started] = now
+ }
+ }
+ return if ((values[applied] ?: 0) >= 1) null else values[started]
+ }
+
+ suspend fun completeCatalogSyncUpgrade(providerId: Long) {
+ preferencesDataStore.edit { values ->
+ values[intPreferencesKey("catalog_sync_engine_$providerId")] = 1
+ values.remove(longPreferencesKey("catalog_sync_upgrade_started_$providerId"))
+ }
}
suspend fun recordAutomaticSyncStatus(providerId: Long, status: com.streamvault.domain.sync.AutomaticSyncStatus) {
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 34562774..309e962d 100644
--- a/data/src/main/java/com/streamvault/data/repository/MovieRepositoryImpl.kt
+++ b/data/src/main/java/com/streamvault/data/repository/MovieRepositoryImpl.kt
@@ -1748,6 +1748,10 @@ class MovieRepositoryImpl @Inject constructor(
)
return@launch
}
+ } catch (cancelled: kotlinx.coroutines.CancellationException) {
+ throw cancelled
+ } catch (error: Exception) {
+ Log.w("MovieRepositoryImpl", "Background Movie refresh failed for provider $providerId: ${error.javaClass.simpleName}")
} finally {
backgroundRefreshes.remove(key)
}
@@ -1764,6 +1768,7 @@ class MovieRepositoryImpl @Inject constructor(
val hasEmptySuccessfulCheckpoint = localCount == 0 &&
(hydration?.lastSuccessfulPage ?: hydration?.lastLoadedPage ?: 0) > 0
if (hasEmptySuccessfulCheckpoint) return true
+ if (hydration == null || (hydration.isComplete && ContentCachePolicy.shouldRefresh(hydration.lastHydratedAt, ContentCachePolicy.CATALOG_TTL_MILLIS, now))) return true
if (hydration?.isComplete == true) return false
if (loadCompletely) return true
if (localCount >= requiredCount) return false
@@ -1791,9 +1796,13 @@ class MovieRepositoryImpl @Inject constructor(
if (!allowWildcard && stalkerProvider.isWildcardCategory(ContentType.MOVIE, categoryId)) return@withLock
var currentCount = localCount ?: movieDao.getCountByCategory(providerId, categoryId).first()
var currentHydration = persistedHydration ?: hydration
- if ((currentHydration?.isComplete == true && currentCount > 0) ||
+ val refreshExpired = currentHydration == null || (currentHydration.isComplete && ContentCachePolicy.shouldRefresh(
+ currentHydration.lastHydratedAt, ContentCachePolicy.CATALOG_TTL_MILLIS
+ ))
+ if (refreshExpired) currentHydration = null
+ if (!refreshExpired && ((currentHydration?.isComplete == true && currentCount > 0) ||
(!loadCompletely && currentCount >= requiredCount)
- ) return@withLock
+ )) return@withLock
if (currentCount == 0 && currentHydration?.isEmptyRetryCoolingDown() == true) return@withLock
val isPreviewLoad = requiredCount <= STALKER_PREVIEW_REQUIRED_COUNT_THRESHOLD
@@ -1824,7 +1833,7 @@ class MovieRepositoryImpl @Inject constructor(
var firstIteration = true
var remotePagesRequested = 0
val seenPageFingerprints = mutableSetOf<String>()
- while (currentCount < targetCount) {
+ while (currentCount < targetCount || (refreshExpired && firstIteration)) {
val attemptStartedAt = System.currentTimeMillis()
if (isPreviewLoad && nextPage > STALKER_PREVIEW_MAX_REMOTE_PAGES) break
if (remotePagesRequested >= maxRemotePages) break
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 ea8eb745..c0def532 100644
--- a/data/src/main/java/com/streamvault/data/repository/SeriesRepositoryImpl.kt
+++ b/data/src/main/java/com/streamvault/data/repository/SeriesRepositoryImpl.kt
@@ -1699,6 +1699,10 @@ class SeriesRepositoryImpl @Inject constructor(
}
} catch (_: CredentialDecryptionException) {
logUnreadableProviderCredentials(providerId)
+ } catch (cancelled: kotlinx.coroutines.CancellationException) {
+ throw cancelled
+ } catch (error: Exception) {
+ Log.w("SeriesRepositoryImpl", "Background Series refresh failed for provider $providerId: ${error.javaClass.simpleName}")
} finally {
backgroundRefreshes.remove(key)
}
@@ -1715,6 +1719,7 @@ class SeriesRepositoryImpl @Inject constructor(
val hasEmptySuccessfulCheckpoint = localCount == 0 &&
(hydration?.lastSuccessfulPage ?: hydration?.lastLoadedPage ?: 0) > 0
if (hasEmptySuccessfulCheckpoint) return true
+ if (hydration == null || (hydration.isComplete && ContentCachePolicy.shouldRefresh(hydration.lastHydratedAt, ContentCachePolicy.CATALOG_TTL_MILLIS, now))) return true
if (hydration?.isComplete == true) return false
if (loadCompletely) return true
if (localCount >= requiredCount) return false
@@ -1742,9 +1747,13 @@ class SeriesRepositoryImpl @Inject constructor(
if (!allowWildcard && stalkerProvider.isWildcardCategory(ContentType.SERIES, categoryId)) return@withLock
var currentCount = localCount ?: seriesDao.getCountByCategory(providerId, categoryId).first()
var currentHydration = persistedHydration ?: hydration
- if ((currentHydration?.isComplete == true && currentCount > 0) ||
+ val refreshExpired = currentHydration == null || (currentHydration.isComplete && ContentCachePolicy.shouldRefresh(
+ currentHydration.lastHydratedAt, ContentCachePolicy.CATALOG_TTL_MILLIS
+ ))
+ if (refreshExpired) currentHydration = null
+ if (!refreshExpired && ((currentHydration?.isComplete == true && currentCount > 0) ||
(!loadCompletely && currentCount >= requiredCount)
- ) return@withLock
+ )) return@withLock
if (currentCount == 0 && currentHydration?.isEmptyRetryCoolingDown() == true) return@withLock
val isPreviewLoad = requiredCount <= STALKER_PREVIEW_REQUIRED_COUNT_THRESHOLD
@@ -1775,7 +1784,7 @@ class SeriesRepositoryImpl @Inject constructor(
var firstIteration = true
var remotePagesRequested = 0
val seenPageFingerprints = mutableSetOf<String>()
- while (currentCount < targetCount) {
+ while (currentCount < targetCount || (refreshExpired && firstIteration)) {
val attemptStartedAt = System.currentTimeMillis()
if (isPreviewLoad && nextPage > STALKER_PREVIEW_MAX_REMOTE_PAGES) break
if (remotePagesRequested >= maxRemotePages) break
diff --git a/data/src/main/java/com/streamvault/data/security/CredentialCrypto.kt b/data/src/main/java/com/streamvault/data/security/CredentialCrypto.kt
index ad336798..b50d83c6 100644
--- a/data/src/main/java/com/streamvault/data/security/CredentialCrypto.kt
+++ b/data/src/main/java/com/streamvault/data/security/CredentialCrypto.kt
@@ -43,22 +43,51 @@ class AndroidKeystoreCredentialCrypto @Inject constructor(
private val SOFTWARE_KEY_FILE_NAME = "streamvault_credential_software.key"
private val SOFTWARE_KEY_ALGORITHM = "AES"
private val SOFTWARE_KEY_SIZE_BITS = 256
- private val secretKeyProvider = CachingSecretKeyProvider(::loadOrCreateSecretKey)
+ private val softwareKeyFile: File
+ get() = File(context.filesDir, SOFTWARE_KEY_FILE_NAME)
+ private val hardwareSecretKeyProvider = CachingSecretKeyProvider(::loadOrCreateHardwareSecretKey)
+ private val softwareSecretKeyProvider = CachingSecretKeyProvider(::loadOrCreateSoftwareSecretKey)
+
+ @Volatile
+ private var preferSoftwareKey = false
+
+ private enum class KeySource {
+ HARDWARE,
+ SOFTWARE
+ }
+
+ private data class SelectedKey(
+ val secretKey: SecretKey,
+ val source: KeySource
+ )
override fun encryptIfNeeded(value: String): String {
if (value.isBlank() || value.startsWith(PREFIX)) return value
+ val selectedKey = try {
+ selectPreferredKey()
+ } catch (e: Exception) {
+ throw encryptionFailure(e)
+ }
+
return try {
- val cipher = Cipher.getInstance(TRANSFORMATION)
- cipher.init(Cipher.ENCRYPT_MODE, secretKeyProvider.get())
- val iv = cipher.iv
- val encrypted = cipher.doFinal(value.toByteArray(Charsets.UTF_8))
- val packed = iv + encrypted
- PREFIX + java.util.Base64.getEncoder().encodeToString(packed)
+ encryptWithKey(value, selectedKey.secretKey)
} catch (e: Exception) {
- // Do NOT fall back to plaintext — rethrow so the caller can surface the failure.
- Log.e(TAG, "Keystore encryption failed. Credential will NOT be stored.", e)
- throw SecurityException("Failed to encrypt credential: ${e.message}", e)
+ if (selectedKey.source == KeySource.SOFTWARE) {
+ throw encryptionFailure(e)
+ }
+
+ // A hardware key can be returned successfully while failing during cipher.init or
+ // doFinal. Pin the app to the software key after the first successful fallback.
+ Log.w(TAG, "Hardware-backed credential encryption failed; retrying with a software key.", e)
+ try {
+ val softwareKey = softwareSecretKeyProvider.get()
+ preferSoftwareKey = true
+ encryptWithKey(value, softwareKey)
+ } catch (fallbackException: Exception) {
+ if (fallbackException !== e) e.addSuppressed(fallbackException)
+ throw encryptionFailure(e)
+ }
}
}
@@ -75,31 +104,99 @@ class AndroidKeystoreCredentialCrypto @Inject constructor(
val iv = bytes.copyOfRange(0, IV_SIZE_BYTES)
val ciphertext = bytes.copyOfRange(IV_SIZE_BYTES, bytes.size)
- val cipher = Cipher.getInstance(TRANSFORMATION)
- cipher.init(
- Cipher.DECRYPT_MODE,
- secretKeyProvider.get(),
- GCMParameterSpec(AUTH_TAG_BITS, iv)
- )
- String(cipher.doFinal(ciphertext), Charsets.UTF_8)
+ val selectedKey = selectPreferredKey()
+ try {
+ decryptWithKey(selectedKey.secretKey, iv, ciphertext)
+ } catch (primaryException: Exception) {
+ val alternateKey = try {
+ when (selectedKey.source) {
+ KeySource.HARDWARE -> softwareKeyFile
+ .takeIf(File::exists)
+ ?.let { softwareSecretKeyProvider.get() }
+
+ KeySource.SOFTWARE -> loadExistingHardwareSecretKey()
+ }
+ } catch (alternateKeyException: Exception) {
+ if (alternateKeyException !== primaryException) {
+ primaryException.addSuppressed(alternateKeyException)
+ }
+ null
+ }
+
+ if (alternateKey == null || alternateKey === selectedKey.secretKey) {
+ throw primaryException
+ }
+
+ try {
+ decryptWithKey(alternateKey, iv, ciphertext)
+ } catch (alternateException: Exception) {
+ if (alternateException !== primaryException) {
+ primaryException.addSuppressed(alternateException)
+ }
+ throw primaryException
+ }
+ }
} catch (e: Exception) {
Log.e(TAG, "Keystore decryption failed. Stored credential is unreadable.", e)
throw CredentialDecryptionException(cause = e)
}
}
- private fun loadOrCreateSecretKey(): SecretKey {
+ @Synchronized
+ private fun selectPreferredKey(): SelectedKey {
+ if (preferSoftwareKey || softwareKeyFile.exists()) {
+ preferSoftwareKey = true
+ return SelectedKey(softwareSecretKeyProvider.get(), KeySource.SOFTWARE)
+ }
+
return try {
- loadOrCreateHardwareSecretKey()
+ val hardwareKey = hardwareSecretKeyProvider.get()
+ if (preferSoftwareKey || softwareKeyFile.exists()) {
+ preferSoftwareKey = true
+ SelectedKey(softwareSecretKeyProvider.get(), KeySource.SOFTWARE)
+ } else {
+ SelectedKey(hardwareKey, KeySource.HARDWARE)
+ }
} catch (e: Exception) {
- // Some devices (notably budget Android TV boxes) ship a broken Keymaster/TEE whose
- // hardware-backed Keystore cannot generate keys. Fall back to a software key so
- // credential persistence keeps working instead of crashing on those devices.
+ // Some devices ship a broken Keystore that cannot load or generate hardware keys.
+ // Keep using the app-private key if one is needed; its file also records that this
+ // installation may already have credentials encrypted with that key.
Log.w(TAG, "Hardware-backed Keystore unavailable; falling back to a software key.", e)
- loadOrCreateSoftwareSecretKey()
+ preferSoftwareKey = true
+ SelectedKey(softwareSecretKeyProvider.get(), KeySource.SOFTWARE)
}
}
+ private fun encryptWithKey(value: String, secretKey: SecretKey): String {
+ val cipher = Cipher.getInstance(TRANSFORMATION)
+ cipher.init(Cipher.ENCRYPT_MODE, secretKey)
+ val iv = cipher.iv
+ val encrypted = cipher.doFinal(value.toByteArray(Charsets.UTF_8))
+ val packed = iv + encrypted
+ return PREFIX + java.util.Base64.getEncoder().encodeToString(packed)
+ }
+
+ private fun decryptWithKey(secretKey: SecretKey, iv: ByteArray, ciphertext: ByteArray): String {
+ val cipher = Cipher.getInstance(TRANSFORMATION)
+ cipher.init(
+ Cipher.DECRYPT_MODE,
+ secretKey,
+ GCMParameterSpec(AUTH_TAG_BITS, iv)
+ )
+ return String(cipher.doFinal(ciphertext), Charsets.UTF_8)
+ }
+
+ private fun encryptionFailure(cause: Exception): SecurityException {
+ // Do NOT fall back to plaintext — surface the failure so the credential is never stored unencrypted.
+ Log.e(TAG, "Credential encryption failed. Credential will NOT be stored.", cause)
+ return SecurityException("Failed to encrypt credential: ${cause.message}", cause)
+ }
+
+ private fun loadExistingHardwareSecretKey(): SecretKey? {
+ val keyStore = KeyStore.getInstance(KEYSTORE_TYPE).apply { load(null) }
+ return keyStore.getKey(KEY_ALIAS, null) as? SecretKey
+ }
+
private fun loadOrCreateHardwareSecretKey(): SecretKey {
val keyStore = KeyStore.getInstance(KEYSTORE_TYPE).apply { load(null) }
val existing = keyStore.getKey(KEY_ALIAS, null) as? SecretKey
@@ -121,21 +218,20 @@ class AndroidKeystoreCredentialCrypto @Inject constructor(
}
/**
- * Best-effort software AES key persisted in app-private storage. This is only reached when the
- * hardware-backed Keystore is unusable, where a hardware-protected key is impossible by
- * definition. The key material lives in the app sandbox (invisible to other apps) and keeps
- * credentials encrypted at rest rather than storing them as plaintext.
+ * Best-effort software AES key persisted in app-private storage. This is used when hardware key
+ * creation or a hardware-backed cipher operation fails. Keeping the same file-backed key across
+ * app updates lets the app continue reading credentials written while this fallback was active.
+ * The key material stays in the app sandbox and credentials remain encrypted at rest.
*/
private fun loadOrCreateSoftwareSecretKey(): SecretKey {
- val keyFile = File(context.filesDir, SOFTWARE_KEY_FILE_NAME)
- if (keyFile.exists()) {
- return SecretKeySpec(keyFile.readBytes(), SOFTWARE_KEY_ALGORITHM)
+ if (softwareKeyFile.exists()) {
+ return SecretKeySpec(softwareKeyFile.readBytes(), SOFTWARE_KEY_ALGORITHM)
}
val keyGenerator = KeyGenerator.getInstance(SOFTWARE_KEY_ALGORITHM)
keyGenerator.init(SOFTWARE_KEY_SIZE_BITS)
val key = keyGenerator.generateKey()
- keyFile.writeBytes(key.encoded)
+ softwareKeyFile.writeBytes(key.encoded)
return key
}
}
diff --git a/data/src/main/java/com/streamvault/data/settings/SettingsOperationsImpl.kt b/data/src/main/java/com/streamvault/data/settings/SettingsOperationsImpl.kt
index 8072e946..805de01d 100644
--- a/data/src/main/java/com/streamvault/data/settings/SettingsOperationsImpl.kt
+++ b/data/src/main/java/com/streamvault/data/settings/SettingsOperationsImpl.kt
@@ -52,6 +52,9 @@ class SettingsOperationsImpl @Inject constructor(
providerId, section.toSyncRepairSection(), onProgress
)
+ override suspend fun syncPlaylistCatalog(providerId: Long, onProgress: ((String) -> Unit)?): Result<ProviderSectionSyncResult> =
+ syncCommands.refreshPlaylistCatalog(providerId, onProgress)
+
override suspend fun retryProviderSection(
providerId: Long,
section: SettingsSyncSection,
@@ -68,7 +71,7 @@ class SettingsOperationsImpl @Inject constructor(
): Result<ProviderSectionSyncResult> = syncCommands.rebuildIndex(providerId, onProgress)
override fun scheduleBackgroundEpgSync(providerId: Long) {
- syncCommands.scheduleBackgroundEpgSync(providerId)
+ syncCommands.scheduleManualEpgSync(providerId)
}
private fun XtreamIndexJobEntity.toSettingsSnapshot() = SettingsXtreamIndexJob(
diff --git a/data/src/main/java/com/streamvault/data/sync/AutomaticSyncRunner.kt b/data/src/main/java/com/streamvault/data/sync/AutomaticSyncRunner.kt
index 5b443f90..17c76ccb 100644
--- a/data/src/main/java/com/streamvault/data/sync/AutomaticSyncRunner.kt
+++ b/data/src/main/java/com/streamvault/data/sync/AutomaticSyncRunner.kt
@@ -58,9 +58,11 @@ class AutomaticSyncRunner @Inject constructor(
suspend fun indexEnabled(providerId: Long, section: ContentType?): Boolean {
val policy = preferences.automaticSyncConfiguration.first().forProvider(providerId)
return policy.enabled && when (section) {
+ ContentType.LIVE -> policy.live
ContentType.MOVIE -> policy.movies
ContentType.SERIES -> policy.series
- else -> policy.movies || policy.series
+ null -> policy.live || policy.movies || policy.series
+ else -> false
}
}
@@ -73,11 +75,11 @@ class AutomaticSyncRunner @Inject constructor(
val previous = preferences.automaticSyncStatuses.first()[providerId] ?: AutomaticSyncStatus()
val snapshot = snapshots.getSnapshot(providerId) ?: return
val policy = settings(providerId)
- val pending = listOf(ContentType.MOVIE, ContentType.SERIES).filter {
- if (it == ContentType.MOVIE) policy.movies else policy.series
+ val pending = listOf(ContentType.LIVE, ContentType.MOVIE, ContentType.SERIES).filter {
+ when (it) { ContentType.LIVE -> policy.live; ContentType.MOVIE -> policy.movies; else -> policy.series }
}.any { section ->
if (snapshot.provider.type == ProviderType.STALKER_PORTAL) {
- stalkerJobs.get(providerId, section)?.state in setOf(StalkerIndexState.QUEUED, StalkerIndexState.RUNNING, StalkerIndexState.RETRY_WAIT, StalkerIndexState.PARTIAL)
+ section != ContentType.LIVE && stalkerJobs.get(providerId, section)?.state in setOf(StalkerIndexState.QUEUED, StalkerIndexState.RUNNING, StalkerIndexState.RETRY_WAIT, StalkerIndexState.PARTIAL)
} else {
xtreamJobs.get(providerId, section.name)?.state in setOf("QUEUED", "RUNNING", "PARTIAL", "FAILED_RETRYABLE")
}
@@ -102,19 +104,8 @@ class AutomaticSyncRunner @Inject constructor(
is M3uConfig -> config.epgSyncMode
is JellyfinConfig -> ProviderEpgSyncMode.SKIP
}
- var metadata = metadataRepository.getMetadata(providerId)
- // Index completion is authoritative; catalog-shell setup is not a completed index.
- if (snapshot.provider.type == ProviderType.XTREAM_CODES) {
- metadata = (metadata ?: SyncMetadata(providerId)).copy(
- lastMovieSuccess = xtreamJobs.get(providerId, ContentType.MOVIE.name)?.lastSuccessAt ?: metadata?.lastMovieSuccess ?: 0,
- lastSeriesSuccess = xtreamJobs.get(providerId, ContentType.SERIES.name)?.lastSuccessAt ?: metadata?.lastSeriesSuccess ?: 0
- )
- } else if ((snapshot.configuration as? StalkerConfig)?.catalogMode == StalkerCatalogMode.BACKGROUND_INDEX) {
- metadata = (metadata ?: SyncMetadata(providerId)).copy(
- lastMovieSuccess = stalkerJobs.get(providerId, ContentType.MOVIE)?.lastSuccessAt ?: metadata?.lastMovieSuccess ?: 0,
- lastSeriesSuccess = stalkerJobs.get(providerId, ContentType.SERIES)?.lastSuccessAt ?: metadata?.lastSeriesSuccess ?: 0
- )
- }
+ val upgradeStartedAt = if (policy.enabled) preferences.catalogSyncUpgradeStartedAt(providerId) else null
+ val metadata = planningMetadata(snapshot, upgradeStartedAt)
val plan = ProviderRefreshPlanner.plan(snapshot.provider.type, metadata, policy, now,
epgAvailable = epgMode != ProviderEpgSyncMode.SKIP,
unifiedVod = snapshot.accountRuntime.catalogLayout == CatalogLayout.UNIFIED_VOD)
@@ -127,16 +118,29 @@ class AutomaticSyncRunner @Inject constructor(
ProviderSyncWorker.enqueueAutomaticCheck(context, providerId, policy)
return@withContext Result.success(Unit)
}
- if (plan.sections.isEmpty()) { report(AutomaticSyncOutcome.UP_TO_DATE); return@withContext Result.success(Unit) }
+ // A queued Live search backfill is independent of catalog freshness.
+ val liveBackfillPending = snapshot.provider.type == ProviderType.XTREAM_CODES && policy.live &&
+ xtreamJobs.get(providerId, ContentType.LIVE.name)?.state in setOf("QUEUED", "RUNNING", "PARTIAL", "STALE", "FAILED_RETRYABLE")
+ if (liveBackfillPending) {
+ withContext(AutomaticSyncExecution.policy.asContextElement(policy)) {
+ commands.scheduleXtreamIndexSync(providerId, ContentType.LIVE, force = false)
+ }
+ }
+ if (plan.sections.isEmpty()) {
+ if (upgradeStartedAt != null && !liveBackfillPending) preferences.completeCatalogSyncUpgrade(providerId)
+ report(if (liveBackfillPending) AutomaticSyncOutcome.QUEUED else AutomaticSyncOutcome.UP_TO_DATE)
+ return@withContext Result.success(Unit)
+ }
report(AutomaticSyncOutcome.RUNNING)
- var queued = false
+ var queued = liveBackfillPending
var partial = false
var failure: Result.Error? = null
suspend fun permanentlyRejected(section: RefreshSection): Boolean {
val content = when (section) { RefreshSection.MOVIES -> ContentType.MOVIE; RefreshSection.SERIES -> ContentType.SERIES; else -> return false }
return when (snapshot.provider.type) {
ProviderType.XTREAM_CODES -> xtreamJobs.get(providerId, content.name)?.state == "FAILED_PERMANENT"
- ProviderType.STALKER_PORTAL -> stalkerJobs.get(providerId, content)?.state == StalkerIndexState.FAILED
+ ProviderType.STALKER_PORTAL -> snapshot.accountRuntime.catalogLayout != CatalogLayout.UNIFIED_VOD &&
+ stalkerJobs.get(providerId, content)?.state == StalkerIndexState.FAILED
else -> false
}
}
@@ -149,15 +153,16 @@ class AutomaticSyncRunner @Inject constructor(
when (val result = commands.refreshScheduledPlaylist(providerId,
RefreshSection.LIVE in catalogSections, RefreshSection.MOVIES in catalogSections)) {
is Result.Error -> failure = result
- is Result.Success -> partial = result.data.partial
+ is Result.Success -> partial = partial || result.data.partial
Result.Loading -> failure = Result.error("Playlist refresh did not complete")
}
runnableSections.filter { it == RefreshSection.EPG }
- } else runnableSections
+ } else runnableSections.sortedBy {
+ when (it) { RefreshSection.MOVIES -> 0; RefreshSection.SERIES -> 1; RefreshSection.LIVE -> 2; RefreshSection.EPG -> 3 }
+ }
for (section in sections) {
val blocked = waitingReason(providerId)
if (blocked != null) { report(blocked); return@withContext failure ?: Result.success(Unit) }
- // A switched-off section must also stop an already queued automatic check.
val latest = preferences.automaticSyncConfiguration.first().forProvider(providerId)
val enabled = when (section) { RefreshSection.LIVE -> latest.live; RefreshSection.MOVIES -> latest.movies; RefreshSection.SERIES -> latest.series; RefreshSection.EPG -> latest.epg }
if (!enabled) continue
@@ -170,12 +175,49 @@ class AutomaticSyncRunner @Inject constructor(
Result.Loading -> failure = Result.error("Scheduled refresh did not complete")
}
}
- val latestMetadata = metadataRepository.getMetadata(providerId)
- val nextPlan = ProviderRefreshPlanner.plan(snapshot.provider.type, latestMetadata, policy, System.currentTimeMillis(),
+ val latestPolicy = settings(providerId)
+ val nextPlan = ProviderRefreshPlanner.plan(snapshot.provider.type, planningMetadata(snapshot, upgradeStartedAt), latestPolicy, System.currentTimeMillis(),
epgAvailable = epgMode != ProviderEpgSyncMode.SKIP, unifiedVod = snapshot.accountRuntime.catalogLayout == CatalogLayout.UNIFIED_VOD)
+ if (upgradeStartedAt != null && latestPolicy.enabled && nextPlan.sections.isEmpty() && failure == null && !partial && !queued) {
+ preferences.completeCatalogSyncUpgrade(providerId)
+ }
preferences.recordAutomaticSyncStatus(providerId, AutomaticSyncStatus(System.currentTimeMillis(),
- when { failure != null -> AutomaticSyncOutcome.FAILED; partial -> AutomaticSyncOutcome.PARTIAL; queued -> AutomaticSyncOutcome.QUEUED; else -> AutomaticSyncOutcome.REFRESHED },
+ when { !latestPolicy.enabled -> AutomaticSyncOutcome.DISABLED; failure != null -> AutomaticSyncOutcome.FAILED; partial -> AutomaticSyncOutcome.PARTIAL; queued -> AutomaticSyncOutcome.QUEUED; else -> AutomaticSyncOutcome.REFRESHED },
nextPlan.nextDueAt, plan.sections))
failure ?: Result.success(Unit)
}
+
+ private suspend fun planningMetadata(snapshot: ProviderSnapshot, upgradeStartedAt: Long?): SyncMetadata? {
+ val providerId = snapshot.provider.id
+ var metadata = metadataRepository.getMetadata(providerId)
+ // Index completion is authoritative; catalog-shell setup is not a completed index.
+ if (snapshot.provider.type == ProviderType.XTREAM_CODES) {
+ metadata = (metadata ?: SyncMetadata(providerId)).copy(
+ lastMovieSuccess = indexSuccess(xtreamJobs.get(providerId, ContentType.MOVIE.name), metadata?.lastMovieSuccess ?: 0L),
+ lastSeriesSuccess = indexSuccess(xtreamJobs.get(providerId, ContentType.SERIES.name), metadata?.lastSeriesSuccess ?: 0L)
+ )
+ } else if ((snapshot.configuration as? StalkerConfig)?.catalogMode == StalkerCatalogMode.BACKGROUND_INDEX &&
+ snapshot.accountRuntime.catalogLayout != CatalogLayout.UNIFIED_VOD) {
+ suspend fun success(section: ContentType, fallback: Long): Long {
+ val job = stalkerJobs.get(providerId, section)
+ return if (job?.state in setOf(StalkerIndexState.QUEUED, StalkerIndexState.RUNNING, StalkerIndexState.RETRY_WAIT, StalkerIndexState.PARTIAL)) 0L
+ else job?.lastSuccessAt ?: fallback
+ }
+ metadata = (metadata ?: SyncMetadata(providerId)).copy(
+ lastMovieSuccess = success(ContentType.MOVIE, metadata?.lastMovieSuccess ?: 0L),
+ lastSeriesSuccess = success(ContentType.SERIES, metadata?.lastSeriesSuccess ?: 0L)
+ )
+ }
+ return metadata?.let { current ->
+ fun freshness(success: Long) = if (upgradeStartedAt != null && success < upgradeStartedAt) 0L else success
+ current.copy(lastLiveSuccess = freshness(current.lastLiveSuccess),
+ lastMovieSuccess = freshness(current.lastMovieSuccess), lastSeriesSuccess = freshness(current.lastSeriesSuccess),
+ lastEpgSuccess = freshness(current.lastEpgSuccess))
+ }
+ }
+
+ private fun indexSuccess(job: com.streamvault.data.local.entity.XtreamIndexJobEntity?, fallback: Long): Long =
+ if (job?.state in setOf("QUEUED", "RUNNING", "PARTIAL", "STALE", "FAILED_RETRYABLE")) 0L
+ else job?.lastSuccessAt ?: fallback
+
}
diff --git a/data/src/main/java/com/streamvault/data/sync/BackgroundEpgSyncWorker.kt b/data/src/main/java/com/streamvault/data/sync/BackgroundEpgSyncWorker.kt
index b3b780ed..9b9fffb2 100644
--- a/data/src/main/java/com/streamvault/data/sync/BackgroundEpgSyncWorker.kt
+++ b/data/src/main/java/com/streamvault/data/sync/BackgroundEpgSyncWorker.kt
@@ -61,7 +61,7 @@ class BackgroundEpgSyncWorker(
BackgroundEpgSyncWorkerEntryPoint::class.java
)
val provider = entryPoint.providerDao().getById(providerId)
- if (provider?.type == ProviderType.XTREAM_CODES &&
+ if (!force && provider?.type == ProviderType.XTREAM_CODES &&
entryPoint.xtreamIndexJobDao().hasPendingCatalogWork(providerId)
) {
Log.i(TAG, "Deferring guide work for provider $providerId until queued catalog indexing completes")
@@ -173,7 +173,7 @@ class BackgroundEpgSyncWorker(
WorkManager.getInstance(context).enqueueUniqueWork(
providerEpgWorkUniqueName(providerId),
- ExistingWorkPolicy.KEEP,
+ if (force) ExistingWorkPolicy.REPLACE else ExistingWorkPolicy.KEEP,
request
)
}
diff --git a/data/src/main/java/com/streamvault/data/sync/M3uCatalogSyncExecutor.kt b/data/src/main/java/com/streamvault/data/sync/M3uCatalogSyncExecutor.kt
index d8bb7e68..b8a2917c 100644
--- a/data/src/main/java/com/streamvault/data/sync/M3uCatalogSyncExecutor.kt
+++ b/data/src/main/java/com/streamvault/data/sync/M3uCatalogSyncExecutor.kt
@@ -44,8 +44,9 @@ internal class M3uCatalogSyncExecutor(
private val progress: (Long, ((String) -> Unit)?, String) -> Unit,
private val sanitizeThrowableMessage: (Throwable) -> String
) {
- suspend fun refreshCatalog(provider: Provider, live: Boolean, movies: Boolean): SyncOutcome {
- val stats = withContext(Dispatchers.IO) { importer.importPlaylist(provider, null, includeLive = live, includeMovies = movies) }
+ suspend fun refreshCatalog(provider: Provider, live: Boolean, movies: Boolean, onProgress: ((String) -> Unit)? = null): SyncOutcome {
+ require(live || movies)
+ val stats = withContext(Dispatchers.IO) { importer.importPlaylist(provider, onProgress, includeLive = live, includeMovies = movies) }
if (stats.liveCount == 0 && stats.movieCount == 0) throw IllegalStateException("Playlist contains no supported entries for the selected sections")
val now = System.currentTimeMillis()
val metadata = syncMetadataRepository.getMetadata(provider.id) ?: SyncMetadata(provider.id)
@@ -57,8 +58,9 @@ internal class M3uCatalogSyncExecutor(
lastMovieSuccess = if (movies) now else metadata.lastMovieSuccess,
movieCount = if (movies) stats.movieCount else metadata.movieCount
))
- if (provider.epgUrl.isBlank()) assignPlaylistEpgSources(provider, stats, mutableListOf())
- return SyncOutcome(partial = stats.warnings.isNotEmpty(), warnings = stats.warnings,
+ val warnings = stats.warnings.toMutableList()
+ if (provider.epgUrl.isBlank()) assignPlaylistEpgSources(provider, stats, warnings)
+ return SyncOutcome(partial = warnings.isNotEmpty(), warnings = warnings.distinct(),
activation = SyncActivation.ACTIVATED_CATALOG)
}
diff --git a/data/src/main/java/com/streamvault/data/sync/ProviderEpgSyncExecutor.kt b/data/src/main/java/com/streamvault/data/sync/ProviderEpgSyncExecutor.kt
index ffb14049..e3e3a989 100644
--- a/data/src/main/java/com/streamvault/data/sync/ProviderEpgSyncExecutor.kt
+++ b/data/src/main/java/com/streamvault/data/sync/ProviderEpgSyncExecutor.kt
@@ -564,6 +564,12 @@ internal class ProviderEpgSyncExecutor(
epgSourceRepository.resolveForProvider(provider.id, hiddenLiveCategoryIds)
}
}
+ if (provider.guideSourcePolicy == GuideSourcePolicy.EXTERNAL_ONLY && warnings.isEmpty() && !hasRetryableFailure) {
+ val current = syncMetadataRepository.getMetadata(provider.id) ?: metadata
+ syncMetadataRepository.updateMetadata(current.copy(
+ lastEpgSync = now, lastEpgSuccess = now, epgCount = programDao.countByProvider(provider.id)
+ ))
+ }
return ProviderGuideSyncResult(warnings, hasRetryableFailure)
}
diff --git a/data/src/main/java/com/streamvault/data/sync/ProviderSyncPorts.kt b/data/src/main/java/com/streamvault/data/sync/ProviderSyncPorts.kt
index b0b3a299..86b05ec5 100644
--- a/data/src/main/java/com/streamvault/data/sync/ProviderSyncPorts.kt
+++ b/data/src/main/java/com/streamvault/data/sync/ProviderSyncPorts.kt
@@ -96,6 +96,11 @@ interface ProviderSyncCommands {
suspend fun refreshScheduledPlaylist(providerId: Long, live: Boolean, movies: Boolean): Result<ProviderSectionSyncResult> =
syncSection(providerId, if (live) SyncRepairSection.LIVE else SyncRepairSection.MOVIES)
+ suspend fun refreshPlaylistCatalog(providerId: Long, onProgress: ((String) -> Unit)? = null): Result<ProviderSectionSyncResult> =
+ refreshScheduledPlaylist(providerId, live = true, movies = true)
+
+ fun scheduleManualEpgSync(providerId: Long) { scheduleBackgroundEpgSync(providerId) }
+
suspend fun refreshScheduledSection(providerId: Long, section: SyncRepairSection): Result<ProviderSectionSyncResult> =
syncSection(providerId, section)
diff --git a/data/src/main/java/com/streamvault/data/sync/ProviderSyncWorkScheduler.kt b/data/src/main/java/com/streamvault/data/sync/ProviderSyncWorkScheduler.kt
index 70a8ad43..a4d75915 100644
--- a/data/src/main/java/com/streamvault/data/sync/ProviderSyncWorkScheduler.kt
+++ b/data/src/main/java/com/streamvault/data/sync/ProviderSyncWorkScheduler.kt
@@ -29,8 +29,9 @@ class ProviderSyncWorkScheduler @Inject constructor(
StalkerIndexWorker.cancel(applicationContext, providerId)
}
- fun scheduleBackgroundEpg(providerId: Long) {
- BackgroundEpgSyncWorker.enqueue(applicationContext, providerId)
+ fun scheduleBackgroundEpg(providerId: Long, force: Boolean = false) {
+ BackgroundEpgSyncWorker.enqueue(applicationContext, providerId, force = force,
+ initialDelaySeconds = if (force) 0L else 30L)
}
fun scheduleProviderResume(providerId: Long, configurationGeneration: Long? = null) {
@@ -52,8 +53,21 @@ class ProviderSyncWorkScheduler @Inject constructor(
automatic: Boolean = (AutomaticSyncExecution.automatic.get() == true)
) {
val origins = applicationContext.getSharedPreferences("automatic_sync_work", Context.MODE_PRIVATE)
- val replaceAutomatic = !automatic && origins.getBoolean("xtream_$providerId", false)
- origins.edit { putBoolean("xtream_$providerId", automatic) }
+ val manager = androidx.work.WorkManager.getInstance(applicationContext)
+ val policy = AutomaticSyncExecution.policy.get() ?: com.streamvault.domain.sync.AutomaticSyncSettings()
+ val wasAutomatic = origins.getBoolean("xtream_$providerId", false)
+ // Migrate an old mixed-origin chain once. New automatic chains have their own
+ // identity, so policy edits cannot cancel a manual sibling or block it.
+ if (!origins.getBoolean("xtream_split_queue_$providerId", false) && wasAutomatic) {
+ manager.cancelUniqueWork(providerWorkUniqueName(providerId))
+ }
+ if (!automatic) manager.cancelUniqueWork(providerAutomaticIndexWorkUniqueName(providerId))
+ val replaceAutomatic = automatic && wasAutomatic && origins.getString("xtream_policy_$providerId", null) != policy.toString()
+ origins.edit {
+ putBoolean("xtream_split_queue_$providerId", true)
+ putBoolean("xtream_$providerId", automatic)
+ putString("xtream_policy_$providerId", if (automatic) policy.toString() else null)
+ }
XtreamIndexWorker.enqueue(
context = applicationContext,
providerId = providerId,
@@ -72,8 +86,19 @@ class ProviderSyncWorkScheduler @Inject constructor(
appendSuccessor: Boolean = false
) {
val origins = applicationContext.getSharedPreferences("automatic_sync_work", Context.MODE_PRIVATE)
- val replaceAutomatic = !automatic && origins.getBoolean("stalker_$providerId", false)
- origins.edit { putBoolean("stalker_$providerId", automatic) }
+ val manager = androidx.work.WorkManager.getInstance(applicationContext)
+ val policy = AutomaticSyncExecution.policy.get() ?: com.streamvault.domain.sync.AutomaticSyncSettings()
+ val wasAutomatic = origins.getBoolean("stalker_$providerId", false)
+ if (!origins.getBoolean("stalker_split_queue_$providerId", false) && wasAutomatic) {
+ manager.cancelUniqueWork(providerWorkUniqueName(providerId))
+ }
+ if (!automatic) manager.cancelUniqueWork(providerAutomaticIndexWorkUniqueName(providerId))
+ val replaceAutomatic = automatic && wasAutomatic && origins.getString("stalker_policy_$providerId", null) != policy.toString()
+ origins.edit {
+ putBoolean("stalker_split_queue_$providerId", true)
+ putBoolean("stalker_$providerId", automatic)
+ putString("stalker_policy_$providerId", if (automatic) policy.toString() else null)
+ }
// Stalker section requests are intentionally coalesced into the durable
// provider job. This preserves the existing worker contract: the worker
// selects the next pending section from its persisted job state.
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 749a48d9..407dc549 100644
--- a/data/src/main/java/com/streamvault/data/sync/ProviderSyncWorker.kt
+++ b/data/src/main/java/com/streamvault/data/sync/ProviderSyncWorker.kt
@@ -222,11 +222,11 @@ class ProviderSyncWorker(
else entryPoint.providerDao().getAllSync()
}
if (providers.isEmpty()) {
- return if (sawRetryableFailure) Result.retry() else Result.success()
+ return if (sawRetryableFailure && !inputData.getBoolean("foreground_check", false)) Result.retry() else Result.success()
}
var sawPermanentFailure = false
- providers.filterNot { it.id in providerIdsWithPendingEdits }.forEach { provider ->
+ providers.filterNot { it.id in providerIdsWithPendingEdits }.sortedByDescending { it.isActive }.forEach { provider ->
val disposition = entryPoint.providerWorkflowRunner().execute(
providerId = provider.id,
phase = ProviderWorkflowPhase.PRIMARY_CATALOG,
@@ -289,16 +289,12 @@ class ProviderSyncWorker(
}
}
- when {
- sawRetryableFailure -> Result.retry()
- sawPermanentFailure -> Result.failure()
- else -> Result.success()
- }
+ providerCheckWorkResult(inputData.getBoolean("foreground_check", false), sawRetryableFailure, sawPermanentFailure)
} catch (cancelled: kotlinx.coroutines.CancellationException) {
throw cancelled
} catch (e: Exception) {
Log.e(TAG, "Provider sync worker failed", e)
- if (shouldRetry(e)) Result.retry() else Result.failure()
+ providerCheckWorkResult(inputData.getBoolean("foreground_check", false), shouldRetry(e), !shouldRetry(e))
}
}
@@ -578,6 +574,18 @@ class ProviderSyncWorker(
WorkManager.getInstance(context).enqueueUniqueWork("provider-sync-idle-check", ExistingWorkPolicy.KEEP, request)
}
+ fun enqueueForegroundCheck(context: Context) {
+ val request = OneTimeWorkRequestBuilder<ProviderSyncWorker>()
+ .setInputData(workDataOf("foreground_check" to true))
+ .setConstraints(automaticSyncConstraints(com.streamvault.domain.sync.AutomaticSyncSettings()))
+ .build()
+ WorkManager.getInstance(context).enqueueUniqueWork(
+ // Keep an in-flight check, but do not lose a policy edit that arrives
+ // after that check read its policy. Foreground checks never back off.
+ "provider-sync-foreground-check", ExistingWorkPolicy.APPEND_OR_REPLACE, request
+ )
+ }
+
fun enqueueLaunchStaleCheck(context: Context) {
val request = OneTimeWorkRequestBuilder<ProviderSyncWorker>()
.setConstraints(
@@ -687,3 +695,15 @@ class ProviderSyncWorker(
)
}
}
+
+/** Provider outcomes are durable; a foreground event must not poison its appended successor. */
+internal fun providerCheckWorkResult(
+ foreground: Boolean,
+ retryableFailure: Boolean,
+ permanentFailure: Boolean
+): androidx.work.ListenableWorker.Result = when {
+ foreground -> androidx.work.ListenableWorker.Result.success()
+ retryableFailure -> androidx.work.ListenableWorker.Result.retry()
+ permanentFailure -> androidx.work.ListenableWorker.Result.failure()
+ else -> androidx.work.ListenableWorker.Result.success()
+}
diff --git a/data/src/main/java/com/streamvault/data/sync/ProviderWorkScheduling.kt b/data/src/main/java/com/streamvault/data/sync/ProviderWorkScheduling.kt
index ef173797..4f571801 100644
--- a/data/src/main/java/com/streamvault/data/sync/ProviderWorkScheduling.kt
+++ b/data/src/main/java/com/streamvault/data/sync/ProviderWorkScheduling.kt
@@ -15,6 +15,12 @@ internal fun providerEpgWorkUniqueName(providerId: Long): String {
return PROVIDER_EPG_WORK_UNIQUE_PREFIX + providerId
}
+/** Automatic constraints must never become prerequisites of an explicit refresh. */
+internal fun providerAutomaticIndexWorkUniqueName(providerId: Long): String {
+ require(providerId > 0L)
+ return "provider-automatic-index-$providerId"
+}
+
internal fun providerWorkExistingPolicy(supersede: Boolean): ExistingWorkPolicy =
if (supersede) {
ExistingWorkPolicy.REPLACE
diff --git a/data/src/main/java/com/streamvault/data/sync/StalkerCatalogSectionExecutor.kt b/data/src/main/java/com/streamvault/data/sync/StalkerCatalogSectionExecutor.kt
index e4461486..dfa96c26 100644
--- a/data/src/main/java/com/streamvault/data/sync/StalkerCatalogSectionExecutor.kt
+++ b/data/src/main/java/com/streamvault/data/sync/StalkerCatalogSectionExecutor.kt
@@ -29,7 +29,8 @@ internal class StalkerCatalogSectionExecutor(
private val updateIndexJob: suspend (Long, ContentType, Int, Long) -> Unit,
private val emitSectionProgress: (Long, Section, Int, Int) -> Unit,
private val progress: (Long, ((String) -> Unit)?, String) -> Unit,
- private val hasPendingIndex: suspend (Long, ContentType) -> Boolean = { _, _ -> false }
+ private val hasPendingIndex: suspend (Long, ContentType) -> Boolean = { _, _ -> false },
+ private val invalidateUnifiedVod: suspend (Long) -> Unit = {}
) {
suspend fun queueIndexSection(
providerId: Long,
@@ -86,6 +87,9 @@ internal class StalkerCatalogSectionExecutor(
}
)
if (!indexCatalog || unified) {
+ // Refresh category contents lazily, retaining cached rows until replacement.
+ movieCategoryHydrationDao.deleteByProvider(provider.id)
+ if (unified) invalidateUnifiedVod(provider.id)
val current = syncMetadataRepository.getMetadata(provider.id) ?: SyncMetadata(provider.id)
syncMetadataRepository.updateMetadata(current.copy(lastMovieSync = now, lastMovieSuccess = now))
return SyncOutcome(activation = SyncActivation.ACTIVATED_CATALOG)
@@ -147,6 +151,7 @@ internal class StalkerCatalogSectionExecutor(
)
val now = System.currentTimeMillis()
if (!indexCatalog) {
+ seriesCategoryHydrationDao.deleteByProvider(provider.id)
val current = syncMetadataRepository.getMetadata(provider.id) ?: SyncMetadata(provider.id)
syncMetadataRepository.updateMetadata(current.copy(lastSeriesSync = now, lastSeriesSuccess = now))
return SyncOutcome(activation = SyncActivation.ACTIVATED_CATALOG)
diff --git a/data/src/main/java/com/streamvault/data/sync/StalkerIndexWorker.kt b/data/src/main/java/com/streamvault/data/sync/StalkerIndexWorker.kt
index 5f6d043f..674655f5 100644
--- a/data/src/main/java/com/streamvault/data/sync/StalkerIndexWorker.kt
+++ b/data/src/main/java/com/streamvault/data/sync/StalkerIndexWorker.kt
@@ -210,7 +210,7 @@ class StalkerIndexWorker(
.build()
WorkManager.getInstance(context).enqueueUniqueWork(
- providerWorkUniqueName(providerId),
+ if (automatic) providerAutomaticIndexWorkUniqueName(providerId) else providerWorkUniqueName(providerId),
stalkerIndexExistingWorkPolicy(force || replaceAutomatic, appendSuccessor),
request
)
@@ -219,6 +219,7 @@ class StalkerIndexWorker(
fun cancel(context: Context, providerId: Long) {
if (providerId > 0L) {
WorkManager.getInstance(context).cancelUniqueWork(providerWorkUniqueName(providerId))
+ WorkManager.getInstance(context).cancelUniqueWork(providerAutomaticIndexWorkUniqueName(providerId))
}
}
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 a9ade211..af3264fb 100644
--- a/data/src/main/java/com/streamvault/data/sync/SyncManager.kt
+++ b/data/src/main/java/com/streamvault/data/sync/SyncManager.kt
@@ -614,7 +614,8 @@ class SyncManager @Inject constructor(
com.streamvault.domain.model.StalkerIndexState.RUNNING,
com.streamvault.domain.model.StalkerIndexState.RETRY_WAIT
)
- }
+ },
+ invalidateUnifiedVod = { providerId -> vodCategoryHydrationDao.deleteByProvider(providerId) }
)
}
private val xtreamCatalogExecutor by lazy {
@@ -896,7 +897,11 @@ class SyncManager @Inject constructor(
StalkerProvider.clearCachesForProvider(providerId)
}
- override fun scheduleAutomaticSyncCheck() { ProviderSyncWorker.enqueueLaunchStaleCheck(applicationContext) }
+ override fun scheduleAutomaticSyncCheck() { ProviderSyncWorker.enqueueForegroundCheck(applicationContext) }
+
+ override fun scheduleManualEpgSync(providerId: Long) {
+ providerSyncWorkScheduler.scheduleBackgroundEpg(providerId, force = true)
+ }
override fun scheduleBackgroundEpgSync(providerId: Long) {
runCatching {
@@ -1414,7 +1419,6 @@ class SyncManager @Inject constructor(
)
0
}
- scheduleXtreamIndexSync(providerId, ContentType.MOVIE, force = true)
xtreamCatalogSectionExecutor.syncCategoryShell(
provider = provider,
@@ -1435,7 +1439,9 @@ class SyncManager @Inject constructor(
)
0
}
- scheduleXtreamIndexSync(providerId, ContentType.SERIES, force = true)
+ // Replace the previous chain once. A provider-wide worker handles both
+ // rebuilt sections without the Series request cancelling Movies.
+ scheduleXtreamIndexSync(providerId, section = null, force = true)
syncStatusPublicationCoordinator.markMovieIndexRebuildAttempt(providerId, now)
}
@@ -1491,10 +1497,16 @@ class SyncManager @Inject constructor(
retryFailedCategoriesOnly = false
)
- override suspend fun refreshScheduledPlaylist(providerId: Long, live: Boolean, movies: Boolean): Result<com.streamvault.domain.sync.ProviderSectionSyncResult> = withProviderLock(providerId) {
+ override suspend fun refreshPlaylistCatalog(providerId: Long, onProgress: ((String) -> Unit)?): Result<com.streamvault.domain.sync.ProviderSectionSyncResult> =
+ refreshPlaylist(providerId, live = true, movies = true, onProgress = onProgress)
+
+ override suspend fun refreshScheduledPlaylist(providerId: Long, live: Boolean, movies: Boolean): Result<com.streamvault.domain.sync.ProviderSectionSyncResult> =
+ refreshPlaylist(providerId, live, movies, null)
+
+ private suspend fun refreshPlaylist(providerId: Long, live: Boolean, movies: Boolean, onProgress: ((String) -> Unit)?): Result<com.streamvault.domain.sync.ProviderSectionSyncResult> = withProviderLock(providerId) {
val provider = loadCompatibilityProvider(providerId) ?: return@withProviderLock Result.error("Provider configuration is unavailable")
try {
- val outcome = m3uCatalogExecutor.refreshCatalog(provider, live, movies)
+ val outcome = m3uCatalogExecutor.refreshCatalog(provider, live, movies, onProgress)
Result.success(com.streamvault.domain.sync.ProviderSectionSyncResult(partial = outcome.partial, warnings = outcome.warnings, catalogChanged = true))
} catch (cancelled: CancellationException) { throw cancelled }
catch (error: Exception) { Result.error(syncErrorSanitizer.userMessage(error, "Playlist refresh failed"), error) }
diff --git a/data/src/main/java/com/streamvault/data/sync/VodCategoryHydrationCoordinator.kt b/data/src/main/java/com/streamvault/data/sync/VodCategoryHydrationCoordinator.kt
index d2b06bfe..54517a4a 100644
--- a/data/src/main/java/com/streamvault/data/sync/VodCategoryHydrationCoordinator.kt
+++ b/data/src/main/java/com/streamvault/data/sync/VodCategoryHydrationCoordinator.kt
@@ -68,7 +68,9 @@ internal class VodCategoryHydrationCoordinator(
if (provider.type != ProviderType.STALKER_PORTAL) {
return@withVodCategoryLock Result.success(Unit)
}
- val current = vodCategoryHydrationDao.get(providerId, categoryId)
+ val current = vodCategoryHydrationDao.get(providerId, categoryId)?.takeUnless {
+ it.isComplete && ContentCachePolicy.shouldRefresh(it.lastHydratedAt, ContentCachePolicy.CATALOG_TTL_MILLIS)
+ }
if (current?.isComplete == true ||
(requestedPage != null && current != null && current.lastSuccessfulPage >= requestedPage) ||
(request == VodCategoryHydrationRequest.OPEN && (current?.lastSuccessfulPage ?: 0) > 0)
@@ -268,7 +270,9 @@ internal class VodCategoryHydrationCoordinator(
if (provider.type != ProviderType.STALKER_PORTAL || provider.catalogLayout != CatalogLayout.SPLIT) {
return@withVodCategoryLock Result.success(Unit)
}
- var hydration = movieCategoryHydrationDao.get(providerId, movieCategoryId)
+ var hydration = movieCategoryHydrationDao.get(providerId, movieCategoryId)?.takeUnless {
+ it.isComplete && ContentCachePolicy.shouldRefresh(it.lastHydratedAt, ContentCachePolicy.CATALOG_TTL_MILLIS)
+ }
var movieCount = movieDao.getCountByCategory(providerId, movieCategoryId).first()
if (hydration?.isComplete == true ||
(requestedPage != null && hydration != null && hydration.lastSuccessfulPage >= requestedPage) ||
diff --git a/data/src/main/java/com/streamvault/data/sync/XtreamIndexWorker.kt b/data/src/main/java/com/streamvault/data/sync/XtreamIndexWorker.kt
index b20868c8..337774d7 100644
--- a/data/src/main/java/com/streamvault/data/sync/XtreamIndexWorker.kt
+++ b/data/src/main/java/com/streamvault/data/sync/XtreamIndexWorker.kt
@@ -212,7 +212,7 @@ class XtreamIndexWorker(
.build()
WorkManager.getInstance(context).enqueueUniqueWork(
- providerWorkUniqueName(providerId),
+ if (automatic) providerAutomaticIndexWorkUniqueName(providerId) else providerWorkUniqueName(providerId),
providerWorkExistingPolicy(supersede = force || replaceAutomatic),
request
)
diff --git a/data/src/test/java/com/streamvault/data/preferences/CatalogSyncUpgradePreferencesTest.kt b/data/src/test/java/com/streamvault/data/preferences/CatalogSyncUpgradePreferencesTest.kt
new file mode 100644
index 00000000..d409d596
--- /dev/null
+++ b/data/src/test/java/com/streamvault/data/preferences/CatalogSyncUpgradePreferencesTest.kt
@@ -0,0 +1,26 @@
+package com.streamvault.data.preferences
+
+import androidx.datastore.preferences.preferencesDataStoreFile
+import com.google.common.truth.Truth.assertThat
+import kotlinx.coroutines.runBlocking
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.mockito.kotlin.mock
+import org.robolectric.RobolectricTestRunner
+import org.robolectric.RuntimeEnvironment
+
+@RunWith(RobolectricTestRunner::class)
+class CatalogSyncUpgradePreferencesTest {
+ @Test fun `catchup checkpoint persists until explicitly completed and is provider scoped`() = runBlocking<Unit> {
+ val context = RuntimeEnvironment.getApplication()
+ context.preferencesDataStoreFile("user_preferences").delete()
+ val preferences = PreferencesRepository(context, mock(), mock(), mock(), mock())
+ val first = preferences.catalogSyncUpgradeStartedAt(9021L)
+ assertThat(first).isGreaterThan(0L)
+ assertThat(preferences.catalogSyncUpgradeStartedAt(9021L)).isEqualTo(first)
+ preferences.completeCatalogSyncUpgrade(9021L)
+ assertThat(preferences.catalogSyncUpgradeStartedAt(9021L)).isNull()
+ assertThat(preferences.catalogSyncUpgradeStartedAt(9022L)).isGreaterThan(0L)
+ context.preferencesDataStoreFile("user_preferences").delete()
+ }
+}
diff --git a/data/src/test/java/com/streamvault/data/settings/SettingsOperationsImplTest.kt b/data/src/test/java/com/streamvault/data/settings/SettingsOperationsImplTest.kt
index b35cac66..2a7c2875 100644
--- a/data/src/test/java/com/streamvault/data/settings/SettingsOperationsImplTest.kt
+++ b/data/src/test/java/com/streamvault/data/settings/SettingsOperationsImplTest.kt
@@ -170,6 +170,6 @@ class SettingsOperationsImplTest {
fun `schedule background epg forwards provider id`() {
operations.scheduleBackgroundEpgSync(7L)
- verify(syncCommands).scheduleBackgroundEpgSync(7L)
+ verify(syncCommands).scheduleManualEpgSync(7L)
}
}
diff --git a/data/src/test/java/com/streamvault/data/sync/AutomaticSyncRegressionTest.kt b/data/src/test/java/com/streamvault/data/sync/AutomaticSyncRegressionTest.kt
new file mode 100644
index 00000000..bcc19587
--- /dev/null
+++ b/data/src/test/java/com/streamvault/data/sync/AutomaticSyncRegressionTest.kt
@@ -0,0 +1,111 @@
+package com.streamvault.data.sync
+
+import android.content.Context
+import android.net.ConnectivityManager
+import android.net.Network
+import com.google.common.truth.Truth.assertThat
+import com.streamvault.data.local.dao.RecordingRunDao
+import com.streamvault.data.local.dao.XtreamIndexJobDao
+import com.streamvault.data.local.entity.XtreamIndexJobEntity
+import com.streamvault.data.preferences.PreferencesRepository
+import com.streamvault.domain.model.*
+import com.streamvault.domain.model.Result
+import com.streamvault.domain.repository.EpgSourceRepository
+import com.streamvault.domain.repository.ProviderSnapshotRepository
+import com.streamvault.domain.repository.SyncMetadataRepository
+import com.streamvault.domain.sync.*
+import kotlinx.coroutines.flow.flowOf
+import kotlinx.coroutines.test.runTest
+import org.junit.Before
+import org.junit.Test
+import org.mockito.kotlin.*
+
+/** Regression coverage for automatic section admission, completion, and guide freshness. */
+class AutomaticSyncRegressionTest {
+ private val context: Context = mock()
+ private val network: ConnectivityManager = mock()
+ private val preferences: PreferencesRepository = mock()
+ private val snapshots: ProviderSnapshotRepository = mock()
+ private val metadata: SyncMetadataRepository = mock()
+ private val commands: ProviderSyncCommands = mock()
+ private val xtream: XtreamIndexJobDao = mock()
+ private val stalker: StalkerIndexJobStore = mock()
+ private val recordings: RecordingRunDao = mock()
+ private val runner = AutomaticSyncRunner(context, preferences, snapshots, metadata, commands, xtream, stalker, recordings)
+
+ @Before fun setup() = runTest {
+ whenever(context.getSystemService(ConnectivityManager::class.java)).thenReturn(network)
+ whenever(network.activeNetwork).thenReturn(mock<Network>())
+ whenever(preferences.automaticSyncConfiguration).thenReturn(flowOf(AutomaticSyncConfiguration()))
+ whenever(preferences.automaticSyncStatuses).thenReturn(flowOf(emptyMap()))
+ whenever(recordings.getByStatus(RecordingStatus.RECORDING)).thenReturn(emptyList())
+ }
+
+ @Test fun `Live-only automatic policy admits its Live search-index continuation`() = runTest {
+ whenever(preferences.automaticSyncConfiguration).thenReturn(flowOf(AutomaticSyncConfiguration(
+ AutomaticSyncSettings(live = true, movies = false, series = false, epg = false)
+ )))
+ assertThat(runner.indexEnabled(7L, ContentType.LIVE)).isTrue()
+ }
+
+ @Test fun `disabled Live section rejects its automatic index continuation`() = runTest {
+ whenever(preferences.automaticSyncConfiguration).thenReturn(flowOf(AutomaticSyncConfiguration(
+ AutomaticSyncSettings(live = false, movies = true, series = false, epg = false)
+ )))
+ assertThat(runner.indexEnabled(7L, ContentType.LIVE)).isFalse()
+ }
+
+ @Test fun `automatic completion status accounts for queued Live backfill`() = runTest {
+ whenever(snapshots.getSnapshot(7L)).thenReturn(ProviderSnapshot(
+ Provider(7L, "Xtream", ProviderType.XTREAM_CODES),
+ XtreamConfig("https://example.test", "user", "password"), 1L
+ ))
+ whenever(xtream.get(7L, ContentType.LIVE.name)).thenReturn(
+ XtreamIndexJobEntity(providerId = 7L, section = "LIVE", state = "QUEUED")
+ )
+ runner.reportIndexProgress(7L, failed = false)
+ verify(preferences).recordAutomaticSyncStatus(eq(7L), argThat {
+ outcome == AutomaticSyncOutcome.QUEUED
+ })
+ }
+
+ @Test fun `successful external-only guide refresh advances EPG freshness`() = runTest {
+ val sources: EpgSourceRepository = mock()
+ val programs: com.streamvault.data.local.dao.ProgramDao = mock()
+ whenever(programs.countByProvider(7L)).thenReturn(0)
+ whenever(preferences.getHiddenCategoryIds(7L, ContentType.LIVE)).thenReturn(flowOf(emptySet()))
+ whenever(sources.refreshAllForProvider(7L)).thenReturn(Result.success(Unit))
+ val executor = ProviderEpgSyncExecutor(
+ preferencesRepository = preferences,
+ epgRepository = mock(),
+ epgSourceRepository = sources,
+ channelDao = mock(),
+ programDao = programs,
+ transactionRunner = mock(),
+ syncMetadataRepository = metadata,
+ stalkerPortalStateStore = mock(),
+ stalkerRequestCoordinator = mock(),
+ createStalkerProvider = { error("Unexpected Stalker client") },
+ xtreamSupport = SyncManagerXtreamSupport(
+ adaptiveSyncPolicy = mock(),
+ shouldRememberSequentialPreference = { false },
+ sanitizeThrowableMessage = { it?.message.orEmpty() },
+ progress = { _, _, _ -> },
+ movieRequestTimeoutMillis = 1000L,
+ seriesRequestTimeoutMillis = 1000L,
+ recoveryAbortWarningSuffix = "Review probe"
+ ),
+ progress = { _, _, _ -> },
+ sanitizeThrowableMessage = { it?.message.orEmpty() }
+ )
+ val provider = LegacyProvider(
+ id = 7L, name = "Playlist", type = ProviderType.M3U,
+ serverUrl = "https://example.test/list.m3u",
+ guideSourcePolicy = GuideSourcePolicy.EXTERNAL_ONLY
+ )
+ val result = executor.syncM3uProviderEpg(provider, SyncMetadata(7L), 1000L, true, null)
+ assertThat(result.warnings).isEmpty()
+ verify(sources).refreshAllForProvider(7L)
+ verify(metadata).updateMetadata(argThat { lastEpgSuccess > 0L })
+ }
+}
diff --git a/data/src/test/java/com/streamvault/data/sync/AutomaticSyncRunnerTest.kt b/data/src/test/java/com/streamvault/data/sync/AutomaticSyncRunnerTest.kt
index 75bdc62b..c9ddb809 100644
--- a/data/src/test/java/com/streamvault/data/sync/AutomaticSyncRunnerTest.kt
+++ b/data/src/test/java/com/streamvault/data/sync/AutomaticSyncRunnerTest.kt
@@ -62,6 +62,35 @@ class AutomaticSyncRunnerTest {
verify(preferences).recordAutomaticSyncStatus(eq(7L), argThat { outcome == AutomaticSyncOutcome.UP_TO_DATE })
}
+ @Test fun `pending Xtream movies resume even when their last success is recent`() = runTest {
+ snapshot(XtreamConfig("https://example.test", "user", "password"))
+ whenever(xtream.get(7L, ContentType.MOVIE.name)).thenReturn(
+ com.streamvault.data.local.entity.XtreamIndexJobEntity(7L, "MOVIE", "QUEUED", lastSuccessAt = now)
+ )
+ runner.check(7L)
+ verify(commands).refreshScheduledSection(7L, SyncRepairSection.MOVIES)
+ }
+
+ @Test fun `upgrade catchup refreshes inherited fresh catalogs and records completion only after success`() = runTest {
+ snapshot(M3uConfig("https://example.test/list"))
+ whenever(preferences.catalogSyncUpgradeStartedAt(7L)).thenReturn(now)
+ whenever(metadata.getMetadata(7L)).thenReturn(
+ fresh.copy(lastLiveSuccess = now - 1, lastMovieSuccess = now - 1), fresh
+ )
+ runner.check(7L)
+ verify(commands).refreshScheduledPlaylist(7L, true, true)
+ verify(preferences).completeCatalogSyncUpgrade(7L)
+ }
+
+ @Test fun `failed upgrade catchup stays pending for recovery`() = runTest {
+ snapshot(M3uConfig("https://example.test/list"))
+ whenever(preferences.catalogSyncUpgradeStartedAt(7L)).thenReturn(now)
+ whenever(metadata.getMetadata(7L)).thenReturn(fresh.copy(lastLiveSuccess = now - 1, lastMovieSuccess = now - 1))
+ whenever(commands.refreshScheduledPlaylist(any(), any(), any())).thenReturn(Result.error("offline", java.io.IOException()))
+ runner.check(7L)
+ verify(preferences, never()).completeCatalogSyncUpgrade(any())
+ }
+
@Test fun `Stalker freshness reads Stalker jobs rather than Xtream jobs`() = runTest {
snapshot(StalkerConfig(portalUrl = "https://example.test", device = StalkerDeviceIdentity(macAddress = "00:11:22:33:44:55"), catalogMode = StalkerCatalogMode.BACKGROUND_INDEX))
whenever(metadata.getMetadata(7L)).thenReturn(fresh.copy(lastMovieSuccess = 0, lastSeriesSuccess = 0))
diff --git a/data/src/test/java/com/streamvault/data/sync/ProviderSyncWorkSchedulerIntegrationTest.kt b/data/src/test/java/com/streamvault/data/sync/ProviderSyncWorkSchedulerIntegrationTest.kt
new file mode 100644
index 00000000..79003c42
--- /dev/null
+++ b/data/src/test/java/com/streamvault/data/sync/ProviderSyncWorkSchedulerIntegrationTest.kt
@@ -0,0 +1,86 @@
+package com.streamvault.data.sync
+
+import androidx.work.Configuration
+import androidx.work.WorkManager
+import com.google.common.truth.Truth.assertThat
+import com.streamvault.domain.sync.AutomaticSyncSettings
+import kotlinx.coroutines.asContextElement
+import kotlinx.coroutines.test.runTest
+import kotlinx.coroutines.withContext
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.robolectric.RobolectricTestRunner
+import org.robolectric.RuntimeEnvironment
+import org.robolectric.annotation.Config
+
+@RunWith(RobolectricTestRunner::class)
+@Config(sdk = [28], manifest = Config.NONE)
+class ProviderSyncWorkSchedulerIntegrationTest {
+ private fun workManager(): WorkManager {
+ val context = RuntimeEnvironment.getApplication()
+ return runCatching { WorkManager.getInstance(context) }.getOrElse {
+ WorkManager.initialize(context, Configuration.Builder().build())
+ WorkManager.getInstance(context)
+ }
+ }
+
+ @Test fun `manual work bypasses automatic constraints and survives subsequent policy changes`() = runTest {
+ val context = RuntimeEnvironment.getApplication()
+ val manager = workManager()
+ val scheduler = ProviderSyncWorkScheduler(context)
+ withContext(AutomaticSyncExecution.policy.asContextElement(AutomaticSyncSettings(chargingOnly = true))) {
+ scheduler.scheduleStalkerIndex(987956L, automatic = true, initialDelaySeconds = 3600L)
+ }
+ scheduler.scheduleStalkerIndex(987956L, automatic = false, initialDelaySeconds = 3600L)
+ val manual = manager.getWorkInfosForUniqueWork(providerWorkUniqueName(987956L)).get().single { !it.state.isFinished }
+ assertThat(manual.constraints.requiresCharging()).isFalse()
+ assertThat(manager.getWorkInfosForUniqueWork(providerAutomaticIndexWorkUniqueName(987956L)).get().all { it.state.isFinished }).isTrue()
+ withContext(AutomaticSyncExecution.policy.asContextElement(AutomaticSyncSettings(chargingOnly = true))) {
+ scheduler.scheduleStalkerIndex(987956L, automatic = true, initialDelaySeconds = 3600L)
+ }
+ withContext(AutomaticSyncExecution.policy.asContextElement(AutomaticSyncSettings(chargingOnly = false))) {
+ scheduler.scheduleStalkerIndex(987956L, automatic = true, initialDelaySeconds = 3600L)
+ }
+ val retained = manager.getWorkInfosForUniqueWork(providerWorkUniqueName(987956L)).get().single { !it.state.isFinished }
+ assertThat(retained.id).isEqualTo(manual.id)
+ }
+
+ @Test fun `manual guide request supersedes an unforced guide request`() {
+ val context = RuntimeEnvironment.getApplication()
+ val manager = workManager()
+ BackgroundEpgSyncWorker.enqueue(context, 987957L, force = false, initialDelaySeconds = 3600L)
+ val original = manager.getWorkInfosForUniqueWork(providerEpgWorkUniqueName(987957L)).get().single { !it.state.isFinished }
+ BackgroundEpgSyncWorker.enqueue(context, 987957L, force = true, initialDelaySeconds = 3600L)
+ val replacement = manager.getWorkInfosForUniqueWork(providerEpgWorkUniqueName(987957L)).get().single { !it.state.isFinished }
+ assertThat(replacement.id).isNotEqualTo(original.id)
+ }
+
+ @Test fun `a policy edit retains a successor check when a foreground check is already pending`() {
+ val context = RuntimeEnvironment.getApplication()
+ val manager = workManager()
+ val old = androidx.work.OneTimeWorkRequestBuilder<ProviderSyncWorker>()
+ .setInitialDelay(3600L, java.util.concurrent.TimeUnit.SECONDS).build()
+ manager.enqueueUniqueWork("provider-sync-foreground-check", androidx.work.ExistingWorkPolicy.KEEP, old).result.get()
+ ProviderSyncWorker.enqueueForegroundCheck(context)
+ val checks = manager.getWorkInfosForUniqueWork("provider-sync-foreground-check").get()
+ assertThat(checks.count { !it.state.isFinished }).isEqualTo(2)
+ }
+
+ @Test fun `relaxing charging replaces the pending automatic Stalker request`() = runTest {
+ val context = RuntimeEnvironment.getApplication()
+ val manager = runCatching { WorkManager.getInstance(context) }.getOrElse {
+ WorkManager.initialize(context, Configuration.Builder().build())
+ WorkManager.getInstance(context)
+ }
+ val scheduler = ProviderSyncWorkScheduler(context)
+ withContext(AutomaticSyncExecution.policy.asContextElement(AutomaticSyncSettings(chargingOnly = true))) {
+ scheduler.scheduleStalkerIndex(987955L, automatic = true, initialDelaySeconds = 3600L)
+ }
+ withContext(AutomaticSyncExecution.policy.asContextElement(AutomaticSyncSettings(chargingOnly = false))) {
+ scheduler.scheduleStalkerIndex(987955L, automatic = true, initialDelaySeconds = 3600L)
+ }
+ val jobs = manager.getWorkInfosForUniqueWork(providerAutomaticIndexWorkUniqueName(987955L)).get()
+ val pending = jobs.single { !it.state.isFinished }
+ assertThat(pending.constraints.requiresCharging()).isFalse()
+ }
+}
diff --git a/data/src/test/java/com/streamvault/data/sync/ProviderSyncWorkerTest.kt b/data/src/test/java/com/streamvault/data/sync/ProviderSyncWorkerTest.kt
index 770e4929..3a76a578 100644
--- a/data/src/test/java/com/streamvault/data/sync/ProviderSyncWorkerTest.kt
+++ b/data/src/test/java/com/streamvault/data/sync/ProviderSyncWorkerTest.kt
@@ -30,6 +30,14 @@ import org.mockito.kotlin.verify
import org.mockito.kotlin.whenever
class ProviderSyncWorkerTest {
+ @Test fun foregroundFailuresDoNotPoisonTheNextQueuedCheck() {
+ for (retryable in listOf(false, true)) for (permanent in listOf(false, true)) {
+ assertThat(providerCheckWorkResult(true, retryable, permanent))
+ .isEqualTo(androidx.work.ListenableWorker.Result.success())
+ }
+ assertThat(providerCheckWorkResult(false, true, false)).isEqualTo(androidx.work.ListenableWorker.Result.retry())
+ assertThat(providerCheckWorkResult(false, false, true)).isEqualTo(androidx.work.ListenableWorker.Result.failure())
+ }
@Test
fun `permanent index rejection is not retried merely because success timestamp is absent`() {
assertThat(shouldRunPersistedIndexJob(
diff --git a/data/src/test/java/com/streamvault/data/sync/StalkerMovieRefreshRegressionTest.kt b/data/src/test/java/com/streamvault/data/sync/StalkerMovieRefreshRegressionTest.kt
new file mode 100644
index 00000000..b086d218
--- /dev/null
+++ b/data/src/test/java/com/streamvault/data/sync/StalkerMovieRefreshRegressionTest.kt
@@ -0,0 +1,63 @@
+package com.streamvault.data.sync
+
+import com.google.common.truth.Truth.assertThat
+import com.streamvault.data.local.dao.MovieCategoryHydrationDao
+import com.streamvault.data.local.dao.MovieDao
+import com.streamvault.data.local.entity.MovieCategoryHydrationEntity
+import com.streamvault.data.remote.stalker.StalkerProvider
+import com.streamvault.data.repository.MovieRepositoryImpl
+import com.streamvault.domain.model.Category
+import com.streamvault.domain.model.ContentType
+import com.streamvault.domain.model.LegacyProvider
+import com.streamvault.domain.model.ProviderType
+import com.streamvault.domain.model.Result
+import com.streamvault.domain.repository.SyncMetadataRepository
+import kotlinx.coroutines.flow.flowOf
+import kotlinx.coroutines.test.runTest
+import org.junit.Test
+import org.mockito.Answers
+import org.mockito.kotlin.*
+
+/** Refreshing categories must allow previously completed contents to be fetched again. */
+class StalkerMovieRefreshRegressionTest {
+ @Test fun `scheduled on-demand refresh invalidates category checkpoints without deleting cached content`() = runTest {
+ val hydrationDao: MovieCategoryHydrationDao = mock()
+ val movieDao: MovieDao = mock()
+ val metadata: SyncMetadataRepository = mock()
+ val api: StalkerProvider = mock()
+ whenever(api.getVodCategories()).thenReturn(Result.success(listOf(Category(10L, name = "Movies", type = ContentType.MOVIE))))
+ whenever(movieDao.getCount(7L)).thenReturn(flowOf(100))
+ val executor = StalkerCatalogSectionExecutor(
+ movieCategoryHydrationDao = hydrationDao,
+ seriesCategoryHydrationDao = mock(),
+ xtreamContentIndexDao = mock(),
+ syncCatalogStore = mock(),
+ movieDao = movieDao,
+ seriesDao = mock(),
+ syncMetadataRepository = metadata,
+ createProvider = { api },
+ updateIndexJob = { _, _, _, _ -> error("Unexpected index queue") },
+ emitSectionProgress = { _, _, _, _ -> },
+ progress = { _, _, _ -> }
+ )
+ val provider = LegacyProvider(7L, "Portal", ProviderType.STALKER_PORTAL, serverUrl = "https://example.test")
+ val outcome = executor.syncMovies(provider, null, indexCatalog = false)
+ assertThat(outcome.partial).isFalse()
+ assertThat(outcome.continuationWork).isEmpty()
+ verify(metadata).updateMetadata(argThat { lastMovieSuccess > 0L })
+ verify(hydrationDao).deleteByProvider(7L)
+
+ // This private predicate is pure: no repository fields or network are involved.
+ val repository: MovieRepositoryImpl = mock(defaultAnswer = Answers.CALLS_REAL_METHODS)
+ val predicate = MovieRepositoryImpl::class.java.getDeclaredMethod(
+ "shouldUseStalkerLazyFallback", MovieCategoryHydrationEntity::class.java,
+ Int::class.javaPrimitiveType, Int::class.javaPrimitiveType, Boolean::class.javaPrimitiveType
+ ).apply { isAccessible = true }
+ val oldComplete = MovieCategoryHydrationEntity(
+ providerId = 7L, categoryId = 10L, lastHydratedAt = 1L,
+ itemCount = 100, lastSuccessfulPage = 1, isComplete = true
+ )
+ val willFetch = predicate.invoke(repository, oldComplete, 100, 200, false) as Boolean
+ assertThat(willFetch).isTrue()
+ }
+}
diff --git a/data/src/test/java/com/streamvault/data/sync/SyncManagerM3uImporterTest.kt b/data/src/test/java/com/streamvault/data/sync/SyncManagerM3uImporterTest.kt
index daa9d844..2b5e7717 100644
--- a/data/src/test/java/com/streamvault/data/sync/SyncManagerM3uImporterTest.kt
+++ b/data/src/test/java/com/streamvault/data/sync/SyncManagerM3uImporterTest.kt
@@ -29,6 +29,15 @@ import java.util.zip.GZIPOutputStream
class SyncManagerM3uImporterTest {
+ @Test fun `complete Live-only playlist commits an empty Movie section for reconciliation`() = runTest {
+ val fixture = fixture(
+ body = playlistEntry("News", "https://stream.example.com/news.ts").toByteArray(),
+ limits = CatalogSizeLimits(maxM3uDecompressedBytes = 4096, maxM3uLineBytes = 1024)
+ )
+ fixture.importer.importPlaylist(provider(), onProgress = null, includeLive = true, includeMovies = true)
+ verify(fixture.store).finalizeStagedImport(eq(PROVIDER_ID), eq(SESSION_ID), anyOrNull(), anyOrNull(), eq(true), eq(true), any())
+ }
+
@Test
fun `unknown length input accepts the exact decompressed byte limit`() = runTest {
val playlist = playlistEntry("News", "https://stream.example.com/news.ts").toByteArray()
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 4318b7a8..ce630350 100644
--- a/data/src/test/java/com/streamvault/data/sync/SyncManagerTest.kt
+++ b/data/src/test/java/com/streamvault/data/sync/SyncManagerTest.kt
@@ -1892,6 +1892,9 @@ class SyncManagerTest {
assertThat(result.isSuccess).isTrue()
verify(xtreamContentIndexDao).markVodAndSeriesRowsStaleForRebuild(1L)
+ verify(workScheduler).scheduleXtreamIndex(1L, null, true)
+ verify(workScheduler, org.mockito.kotlin.never()).scheduleXtreamIndex(1L, ContentType.MOVIE, true)
+ verify(workScheduler, org.mockito.kotlin.never()).scheduleXtreamIndex(1L, ContentType.SERIES, true)
assertThat(xtreamBackend.requestedActions).contains("get_vod_categories")
assertThat(xtreamBackend.requestedActions).contains("get_series_categories")
assertThat(xtreamBackend.requestedActions).doesNotContain("get_vod_streams")
diff --git a/data/src/test/resources/robolectric.properties b/data/src/test/resources/robolectric.properties
new file mode 100644
index 00000000..b790e231
--- /dev/null
+++ b/data/src/test/resources/robolectric.properties
@@ -0,0 +1,3 @@
+# Preserve the former JVM-test default while loading WorkManager resources.
+# Individual platform tests can still override this with @Config.
+sdk=28
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index 57b1e8b5..96afc31f 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -6,10 +6,17 @@ All notable product changes are recorded in this document.
### Changed
- Removed Trakt badge from player when not logged in.
+- Crash diagnostics now retain the five most recent reports, removing the oldest as new reports are saved.
### Fixed
- QR pairing now routes Xtream `get.php` URLs with embedded credentials through the same URL setup flow as manual entry.
- QR pairing now reports provider-specific setup errors in the web flow and handles Stalker TV review prompts through the native setup dialogs.
+- Fixed aspect ratio button causing crash in VOD.
+- Fixed Settings Sync Now for Xtream providers so movie and series indexing is not cancelled by a competing section request, and progress remains visible until indexing finishes.
+- Fixed automatic sync for existing providers after upgrade: catalogs that predate the updated sync engine are caught up, and overdue checks are requested when the app opens or returns to the foreground.
+- Fixed scheduled index work when sync policies change, pending Live sections, and rebuilding an index for all provider sections.
+- Fixed complete M3U refreshes and manual guide sync so they reconcile the selected catalog sections and fetch fresh guide data.
+- Fixed Stalker VOD refreshes to invalidate completed category caches so newly added movies and series can be fetched.
## [1.2.0]
@@ -51,6 +58,7 @@ All notable product changes are recorded in this document.
- Fixed the VOD playback settings sheet remaining visible over picture-in-picture playback.
- Fixed live channels in custom groups showing **Add** instead of **Remove** in the channel options dialog.
- Fixed provider observation crashes on devices where saved credentials cannot be decrypted by skipping unnecessary credential decryption in public provider projections.
+- Fixed credential encryption fallback changing key sources after an update: an existing software key remains preferred, legacy credentials can be decrypted with either available key, and failed hardware cipher operations retry with the software key.
- Fixed successful new-provider setup staying on Add Provider; new providers now navigate to Home, while edits return to the previous screen.
- Fixed repeated stream restarts during network outages and unnecessary recovery from nonfatal audio errors.
- Fixed stalled live playback recovery to refresh the live window without interrupting active network retries.
diff --git a/docs/automatic-provider-sync.md b/docs/automatic-provider-sync.md
index 21fe9bfb..98035f57 100644
--- a/docs/automatic-provider-sync.md
+++ b/docs/automatic-provider-sync.md
@@ -9,19 +9,25 @@ Default behavior:
- Connected network and battery not low; charging, unmetered networking and device idle are optional.
- Automatic work waits while local playback (including paused/buffering players) or recording is active. An idle transition requests a catch-up check.
- No preferred time window by default. Windows can cross midnight and use device-local time.
-- A durable hourly check plans due work; process startup and provider selection also request checks. Android decides actual execution times.
+- A durable hourly check plans due work; process startup, provider selection and policy edits also request checks. Returning to an existing app process requests an immediate check, throttled to once per 30 seconds. Android decides actual execution times.
The shared ProviderRefreshPlanner selects supported sections using successful refresh timestamps. Attempt timestamps do not make failed work fresh. Explicit Settings refreshes share capability selection and the current catalog executors while ignoring automatic enablement and freshness. Interrupted provider setup/configuration recovery remains independent of automatic refresh settings.
+On the first automatic check with the corrected sync engine, each provider gets a persisted catch-up checkpoint. Selected sections last refreshed before that checkpoint are due even if their inherited timestamps are otherwise recent. The checkpoint completes only after those sections succeed; failed and queued work remain recoverable. Global/provider disablement and automatic constraints still apply. These runtime checkpoints are not included in portable backups.
+
Provider behavior:
- Xtream: current Live strategy plus resumable Movies/Series index jobs.
-- Stalker: current Live executor and its own index-job store. On-demand VOD refreshes category shells; background-index mode queues resumable item indexing. Unified VOD does not request split Series.
+- Stalker: current Live executor and its own index-job store. On-demand VOD refreshes category shells and invalidates completed content checkpoints while retaining cached rows; revisiting a category can fetch new entries. Background-index mode queues resumable item indexing. Unified VOD does not request split Series.
- M3U: one playlist download applies the selected Live/Movie sections. Complete snapshots add, update and prune entries using existing import safety rules.
- Jellyfin: Movies and Series refresh only when due, including for inactive saved providers; there are no Live/guide requests.
Automatic index continuations retain their policy/provenance, recheck restrictions and section selections, and preserve pending progress. Explicit manual index work can replace pending automatic work with restrictive constraints. Permanent index failures require explicit retry. Scheduled refreshes do not change the selected provider or deactivate it after a refresh failure.
+Automatic index requests use a separate WorkManager identity from manual/configuration work. A changed automatic policy replaces its old constrained request without cancelling manual work; manual requests cancel automatic index work and reuse durable checkpoints. Old mixed-origin automatic chains are reconciled when first rescheduled. Pending index checkpoints are resumed independently of the previous successful refresh's age.
+
+Settings keeps manual Movie/Series and index-rebuild progress visible through durable indexing, including localized section labels and item counts. Cancel stops the foreground wait; admitted library work continues. Rebuild Index replaces the prior chain once with one provider-wide index request. A complete M3U selection downloads and reconciles both catalog sections together, including an emptied opposite section and playlist guide-source discovery. Manual guide refreshes force the provider download, supersede unforced pending requests, and do not wait for unrelated queued catalog indexing. Successful external-only guide refreshes advance provider-level guide freshness.
+
Settings displays per-section last successful timestamps, the next due time, and the last automatic-check result, distinguishing fresh data, queued indexing, running work, deferral, warnings and failure. Automatic policy defaults and overrides are included in backup/restore through portable provider identities; runtime status is not backed up.
## Validation
@@ -45,3 +51,13 @@ Final validation:
Local evidence is retained in `tmp/automatic-sync/`: build logs, final instrumentation result, UI hierarchy captures and the interval-picker screenshot. Build artifacts are `app/build/outputs/apk/debug/app-debug.apk` and `app/build/outputs/apk/androidTest/debug/app-debug-androidTest.apk`.
This validation exercises scheduled catalog synchronization. It does not claim live playback, real-provider availability, or exact wall-clock background execution timing.
+
+## Sync correction validation (2026-10-19)
+
+- Full domain, data and Settings unit suites plus the targeted app startup suite passed: **1,973 tests** (249 domain, 1,628 data, 89 Settings and seven startup tests), zero failures or skips.
+- WorkManager integration tests cover changed automatic constraints, manual/automatic queue isolation, forced guide replacement, appended foreground checks and failure handling. Regression tests cover upgrade catch-up, pending jobs, Live admission, complete M3U reconciliation, Stalker cache refresh and durable Settings progress.
+- Debug application and instrumentation APKs assembled successfully after the final production change.
+- Both opt-in runtime tests passed on a disposable read-only Android emulator against the final APK: `XtreamMovieRefreshRuntimeTest` and `AutomaticProviderSyncRuntimeTest` (**two tests, 62.545 seconds**). Local HTTP fixtures exercise newly added Xtream movies, inherited fresh timestamps requiring upgrade catch-up, stable existing row IDs, inactive providers, complete M3U refresh/pruning and automatic disablement.
+- Localization checks found no missing affected keys across all 38 advertised locales; the new progress formatter preserves its argument contract in every locale. `git diff --check` passed.
+
+Evidence is retained locally under `tmp/sync-review/`: `fixed-unit-results.json`, `final-data-suite.log`, `final-settings-tests.log`, `queue-final-validation.log`, `fixed-runtime-final.txt`, `fix-localization.txt` and `fix-format-contracts.txt`. The disposable emulator was shut down after validation. These checks use synthetic providers; the reporting user's account and live playback were not exercised.
diff --git a/domain/src/main/java/com/streamvault/domain/settings/SettingsOperations.kt b/domain/src/main/java/com/streamvault/domain/settings/SettingsOperations.kt
index 63755f45..705f0020 100644
--- a/domain/src/main/java/com/streamvault/domain/settings/SettingsOperations.kt
+++ b/domain/src/main/java/com/streamvault/domain/settings/SettingsOperations.kt
@@ -16,6 +16,8 @@ interface SettingsOperations {
section: SettingsSyncSection,
onProgress: ((String) -> Unit)? = null
): Result<ProviderSectionSyncResult>
+ suspend fun syncPlaylistCatalog(providerId: Long, onProgress: ((String) -> Unit)? = null): Result<ProviderSectionSyncResult> =
+ syncProviderSection(providerId, SettingsSyncSection.LIVE, onProgress)
suspend fun retryProviderSection(
providerId: Long,
section: SettingsSyncSection,
diff --git a/feature/provider/src/main/res/values-da/strings.xml b/feature/provider/src/main/res/values-da/strings.xml
index b647e99b..2951d788 100644
--- a/feature/provider/src/main/res/values-da/strings.xml
+++ b/feature/provider/src/main/res/values-da/strings.xml
@@ -105,8 +105,8 @@
<string name="setup_phone_pairing_security_warning">Sikkerhed: Parring sender loginoplysninger uden kryptering via dit lokale netværk. Brug kun et privat Wi-Fi-netværk, du har tillid til.</string>
<string name="setup_phone_pairing_error_help">Parringen kunne ikke gennemføres. Kontrollér udbyderoplysningerne, og prøv igen. Hvis QR-sessionen er udløbet, skal du starte en ny på tv’et.</string>
<string name="setup_phone_pairing_mac_label">MAC-adresse</string>
- <string name="setup_phone_pairing_continue_on_tv">Fortsæt på tv'et for at gennemgå og fuldføre dette trin.</string>
- <string name="setup_phone_pairing_stalker_certificate_error">Certifikatet kunne ikke kontrolleres sikkert. Gennemgå denne forbindelse på tv'et.</string>
+ <string name="setup_phone_pairing_continue_on_tv">Fortsæt på tv\'et for at gennemgå og fuldføre dette trin.</string>
+ <string name="setup_phone_pairing_stalker_certificate_error">Certifikatet kunne ikke kontrolleres sikkert. Gennemgå denne forbindelse på tv\'et.</string>
<string name="stalker_transport_invalid_tls_title">Denne udbyders sikkerhedscertifikat kan ikke bekræftes</string>
<string name="stalker_transport_invalid_tls_body">Forbindelsen til %1$s kan stadig være krypteret, men appen kan ikke bekræfte, at den faktisk tilhører denne udbyder. En person på netværket kan muligvis læse dine login- eller streamoplysninger.</string>
<string name="stalker_transport_http_title">Denne udbyder bruger en ukrypteret forbindelse</string>
diff --git a/feature/provider/src/main/res/values-tr/strings.xml b/feature/provider/src/main/res/values-tr/strings.xml
index 6d9735b4..896364e1 100644
--- a/feature/provider/src/main/res/values-tr/strings.xml
+++ b/feature/provider/src/main/res/values-tr/strings.xml
@@ -105,8 +105,8 @@
<string name="setup_phone_pairing_security_warning">Güvenlik: Eşleştirme, oturum açma bilgilerini yerel ağınız üzerinden şifrelemeden gönderir. Yalnızca güvendiğiniz özel bir Wi-Fi ağı kullanın.</string>
<string name="setup_phone_pairing_error_help">Eşleştirme tamamlanamadı. Sağlayıcı bilgilerini kontrol edip yeniden deneyin. QR oturumunun süresi dolduysa TV’de yeni bir oturum başlatın.</string>
<string name="setup_phone_pairing_mac_label">MAC adresi</string>
- <string name="setup_phone_pairing_continue_on_tv">Bu adımı inceleyip tamamlamak için TV'de devam edin.</string>
- <string name="setup_phone_pairing_stalker_certificate_error">Sertifika güvenli şekilde denetlenemedi. Bu bağlantıyı TV'de inceleyin.</string>
+ <string name="setup_phone_pairing_continue_on_tv">Bu adımı inceleyip tamamlamak için TV\'de devam edin.</string>
+ <string name="setup_phone_pairing_stalker_certificate_error">Sertifika güvenli şekilde denetlenemedi. Bu bağlantıyı TV\'de inceleyin.</string>
<string name="stalker_transport_invalid_tls_title">Bu sağlayıcının güvenlik sertifikası doğrulanamıyor</string>
<string name="stalker_transport_invalid_tls_body">%1$s bağlantısı hâlâ şifreli olabilir ancak uygulama bunun gerçekten bu sağlayıcıya ait olduğunu doğrulayamıyor. Ağdaki biri oturum açma veya yayın ayrıntılarınızı okuyabilir.</string>
<string name="stalker_transport_http_title">Bu sağlayıcı şifrelenmemiş bağlantı kullanıyor</string>
@@ -114,7 +114,7 @@
<string name="stalker_transport_origin_changed_title">Bu sağlayıcı farklı bir adres kullanmak istiyor</string>
<string name="stalker_transport_origin_changed_body">Sağlayıcı bağlantıyı %1$s adresine yönlendirdi. Yalnızca bu adresi tanıyorsanız devam edin.</string>
<string name="stalker_verification_inconclusive_title">Canlı TV doğrulanamadı</string>
- <string name="stalker_verification_inconclusive_body">Sağlayıcı oturum açmanızı kabul etti ancak Canlı TV denetimi tamamlanmadı. Doğrulama beklemedeyken kaydedebilirsiniz; eşitleme Canlı TV'nin oynatılabildiğini doğrulayana kadar etkin olmayacaktır.</string>
+ <string name="stalker_verification_inconclusive_body">Sağlayıcı oturum açmanızı kabul etti ancak Canlı TV denetimi tamamlanmadı. Doğrulama beklemedeyken kaydedebilirsiniz; eşitleme Canlı TV\'nin oynatılabildiğini doğrulayana kadar etkin olmayacaktır.</string>
<string name="stalker_transport_go_back">Geri dön</string>
<string name="stalker_transport_connect_anyway">Yine de bağlan</string>
<string name="stalker_save_without_verification">Doğrulamadan kaydet</string>
diff --git a/feature/settings/src/main/java/com/streamvault/feature/settings/presentation/SettingsProviderActions.kt b/feature/settings/src/main/java/com/streamvault/feature/settings/presentation/SettingsProviderActions.kt
index c3d4c2e5..1b773f3f 100644
--- a/feature/settings/src/main/java/com/streamvault/feature/settings/presentation/SettingsProviderActions.kt
+++ b/feature/settings/src/main/java/com/streamvault/feature/settings/presentation/SettingsProviderActions.kt
@@ -1,5 +1,8 @@
package com.streamvault.feature.settings.presentation
+import android.content.Context
+import com.streamvault.feature.settings.R
+
import com.streamvault.feature.settings.api.SettingsSurfaceRefreshPort
import com.streamvault.domain.model.ActiveLiveSource
import com.streamvault.domain.model.ChannelLogoSourcePolicy
@@ -33,6 +36,7 @@ internal fun shouldAutoSyncProvider(
): Boolean = !PersistedTimestampPolicy.isFresh(lastSyncedAt, now, staleAfterMillis)
internal class SettingsProviderActions(
+ private val appContext: Context,
private val providerRepository: ProviderRepository,
private val combinedM3uRepository: CombinedM3uRepository,
private val preferencesRepository: SettingsPreferences,
@@ -269,9 +273,9 @@ internal class SettingsProviderActions(
it.copy(
isSyncing = true,
syncingProviderName = providerName,
- syncProgress = "Queueing index rebuild...",
+ syncProgress = appContext.getString(R.string.settings_syncing_preparing),
syncStartedAt = System.currentTimeMillis(),
- syncSectionLabel = "Rebuild index",
+ syncSectionLabel = appContext.getString(R.string.settings_sync_option_rebuild_index),
syncCanCancel = true
)
}
@@ -286,7 +290,7 @@ internal class SettingsProviderActions(
syncStartedAt = 0L,
syncSectionLabel = null,
syncCanCancel = false,
- userMessage = "Refresh stopped. Already queued library work will continue."
+ userMessage = appContext.getString(R.string.settings_sync_stopped_queued)
)
}
throw e
@@ -299,7 +303,7 @@ internal class SettingsProviderActions(
syncStartedAt = 0L,
syncSectionLabel = null,
syncCanCancel = false,
- userMessage = "Sync failed: ${e.message}"
+ userMessage = appContext.getString(R.string.settings_sync_failed, appContext.getString(R.string.settings_sync_incomplete))
)
}
}
@@ -308,14 +312,14 @@ internal class SettingsProviderActions(
suspend fun prepareProviderRefresh(providerId: Long): Result<ProviderSectionSyncResult> {
val provider = providerRepository.getProvider(providerId)
- ?: return Result.error("Provider is no longer available")
+ ?: return Result.error(appContext.getString(R.string.settings_sync_provider_missing))
if (provider.type != ProviderType.XTREAM_CODES) return Result.success(ProviderSectionSyncResult())
val generation = preferencesRepository.getXtreamTextImportGeneration()
if (generation <= preferencesRepository.getXtreamTextImportAppliedGeneration(providerId)) {
return Result.success(ProviderSectionSyncResult())
}
val result = settingsOperations.rebuildXtreamIndex(providerId) { message ->
- uiState.update { it.copy(syncProgress = message) }
+ uiState.update { it.copy(syncProgress = appContext.getString(R.string.settings_syncing_preparing)) }
}
if (result is Result.Success && !result.data.partial) {
preferencesRepository.markXtreamTextImportApplied(providerId, generation)
@@ -335,7 +339,7 @@ internal class SettingsProviderActions(
val result = if (provider?.type == ProviderType.XTREAM_CODES) {
settingsOperations.rebuildXtreamIndex(providerId) { message ->
uiState.update { state ->
- state.copy(syncProgress = message, syncingProviderName = providerName)
+ state.copy(syncProgress = appContext.getString(R.string.settings_syncing_preparing), syncingProviderName = providerName)
}
}
} else {
@@ -348,7 +352,7 @@ internal class SettingsProviderActions(
),
onProgress = { message ->
uiState.update { state ->
- state.copy(syncProgress = message, syncingProviderName = providerName)
+ state.copy(syncProgress = appContext.getString(R.string.settings_syncing_preparing), syncingProviderName = providerName)
}
}
)
@@ -364,6 +368,17 @@ internal class SettingsProviderActions(
preferencesRepository.markXtreamTextImportApplied(providerId, generation)
}
}
+ val finalResult = if (provider?.type == ProviderType.XTREAM_CODES && result is Result.Success && result.data.queued) {
+ val jobs = awaitSettingsCatalogIndex(settingsOperations, providerId, setOf("MOVIE", "SERIES")) { job ->
+ val label = appContext.getString(if (job.section == "MOVIE") R.string.settings_sync_option_movies else R.string.settings_sync_option_series)
+ 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 = label, syncProgress = appContext.getString(
+ R.string.settings_sync_index_progress, appContext.getString(stage, label),
+ java.text.NumberFormat.getIntegerInstance().format(job.indexedRows))) }
+ }
+ Result.success(ProviderSectionSyncResult(partial = result.data.partial || jobs.size != 2 || jobs.any { it.state !in setOf("SUCCESS", "COMPLETE") }))
+ } else result
uiState.update { state ->
state.copy(
isSyncing = false,
@@ -373,12 +388,11 @@ internal class SettingsProviderActions(
syncSectionLabel = null,
syncCanCancel = false,
userMessage = when {
- result is Result.Error -> "Rebuild index failed: ${result.message}"
- result is Result.Success && result.data.partial ->
- "Index rebuild queued with warnings: ${result.data.warnings.joinToString()}"
- result is Result.Success && !result.data.queued -> "Index rebuild completed"
- result is Result.Loading -> "Index rebuild did not complete"
- else -> "Index rebuild queued"
+ finalResult is Result.Error -> appContext.getString(R.string.settings_sync_failed, appContext.getString(R.string.settings_sync_incomplete))
+ finalResult is Result.Success && finalResult.data.partial -> appContext.getString(R.string.settings_sync_incomplete)
+ finalResult is Result.Success && !finalResult.data.queued -> appContext.getString(R.string.settings_sync_sections_success, appContext.getString(R.string.settings_sync_option_rebuild_index))
+ finalResult is Result.Loading -> appContext.getString(R.string.settings_sync_no_result)
+ else -> appContext.getString(R.string.settings_sync_section_queued, appContext.getString(R.string.settings_sync_option_rebuild_index))
},
syncWarningsByProvider = state.syncWarningsByProvider
)
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 2a77b64a..6215eb30 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
@@ -6,6 +6,8 @@ import com.streamvault.feature.settings.api.SettingsSurfaceRefreshPort
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
@@ -14,6 +16,7 @@ import kotlinx.coroutines.Job
import kotlinx.coroutines.CancellationException
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
@@ -125,20 +128,24 @@ 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) {
// A changed text-decoding preference intentionally rebuilds Xtream indexes;
// ordinary refreshes retain their existing checkpoints.
when (val preparation = prepareRefresh(providerId)) {
is Result.Success -> {
hasQueuedWork = preparation.data.queued
- failures += preparation.data.warnings
+ if (preparation.data.partial || preparation.data.warnings.isNotEmpty()) failures += appContext.getString(R.string.settings_sync_incomplete)
}
- is Result.Error -> failures += preparation.message
+ is Result.Error -> failures += appContext.getString(R.string.settings_sync_incomplete)
Result.Loading -> failures += appContext.getString(R.string.settings_sync_no_result)
}
}
selections.forEach { selection ->
currentCoroutineContext().ensureActive()
+ if (combinedPlaylist && selection == ProviderSyncSelection.MOVIES) return@forEach
val sectionLabel = selection.label(appContext)
val section = when (selection) {
ProviderSyncSelection.TV -> SettingsSyncSection.LIVE
@@ -159,25 +166,35 @@ internal class SettingsSyncActions(
completed += appContext.getString(R.string.settings_sync_section_queued, sectionLabel)
return@forEach
}
- when (val result = settingsOperations.syncProviderSection(providerId, section) { progress ->
- uiState.update { it.copy(syncProgress = progress) }
- }) {
- is Result.Error -> failures += "$sectionLabel: ${result.message}"
+ val onProgress: (String) -> Unit = {
+ uiState.update { it.copy(syncProgress = appContext.getString(R.string.settings_syncing_section, sectionLabel)) }
+ }
+ val result = if (combinedPlaylist && section == SettingsSyncSection.LIVE) {
+ settingsOperations.syncPlaylistCatalog(providerId, onProgress)
+ } else settingsOperations.syncProviderSection(providerId, section, onProgress)
+ when (result) {
+ is Result.Error -> failures += appContext.getString(R.string.settings_sync_incomplete)
Result.Loading -> failures += "$sectionLabel: ${appContext.getString(R.string.settings_sync_no_result)}"
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()
}
- val warnings = receipt.warnings.ifEmpty {
- if (receipt.partial) listOf(appContext.getString(R.string.settings_sync_incomplete)) else emptyList()
- }.map { "$sectionLabel: $it" }
+ // Provider diagnostics retain technical details. Product messages
+ // are rendered from this module's localized resources.
+ val warnings = if (receipt.partial || receipt.warnings.isNotEmpty()) {
+ listOf(appContext.getString(R.string.settings_sync_index_progress,
+ sectionLabel, appContext.getString(R.string.settings_sync_incomplete)))
+ } else emptyList()
uiState.update { state ->
val previous = state.syncWarningsByProvider[providerId].orEmpty()
val updated = if (receipt.queued) previous + warnings else {
- previous.filterNot { it.startsWith("$sectionLabel:") } + warnings
+ previous.filterNot { it.startsWith("$sectionLabel:") || it.startsWith("$sectionLabel ·") } + warnings
}.distinct()
state.copy(syncWarningsByProvider = if (updated.isEmpty()) {
state.syncWarningsByProvider - providerId
@@ -188,10 +205,42 @@ internal class SettingsSyncActions(
completed += if (receipt.queued) {
appContext.getString(R.string.settings_sync_section_queued, sectionLabel)
} else sectionLabel
+ if (combinedPlaylist && section == SettingsSyncSection.LIVE) {
+ completed += ProviderSyncSelection.MOVIES.label(appContext)
+ }
}
}
}
}
+ 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(
@@ -213,7 +262,7 @@ internal class SettingsSyncActions(
}
throw e
} catch (e: Exception) {
- uiState.update { it.copy(userMessage = appContext.getString(R.string.settings_sync_failed, e.message.orEmpty())) }
+ uiState.update { it.copy(userMessage = appContext.getString(R.string.settings_sync_failed, appContext.getString(R.string.settings_sync_incomplete))) }
} finally {
uiState.update {
it.copy(
@@ -224,3 +273,18 @@ internal class SettingsSyncActions(
}
}
}
+
+/** Foreground ownership lasts until durable indexing terminates; cancelling only stops waiting. */
+internal suspend fun awaitSettingsCatalogIndex(
+ operations: SettingsOperations,
+ providerId: Long,
+ sections: Set<String>,
+ onProgress: (SettingsXtreamIndexJob) -> Unit
+): List<SettingsXtreamIndexJob> {
+ val terminal = setOf("SUCCESS", "COMPLETE", "PARTIAL", "TRUNCATED", "FAILED", "FAILED_RETRYABLE", "FAILED_PERMANENT")
+ return operations.observeXtreamIndexJobs().first { all ->
+ val jobs = all.filter { it.providerId == providerId && it.section in sections }
+ jobs.firstOrNull { it.state !in terminal }?.let(onProgress)
+ jobs.size < sections.size || jobs.all { it.state in terminal }
+ }.filter { it.providerId == providerId && it.section in sections }
+}
diff --git a/feature/settings/src/main/java/com/streamvault/feature/settings/presentation/SettingsViewModel.kt b/feature/settings/src/main/java/com/streamvault/feature/settings/presentation/SettingsViewModel.kt
index 1aa073df..d3a7b3d7 100644
--- a/feature/settings/src/main/java/com/streamvault/feature/settings/presentation/SettingsViewModel.kt
+++ b/feature/settings/src/main/java/com/streamvault/feature/settings/presentation/SettingsViewModel.kt
@@ -93,7 +93,6 @@ import kotlinx.coroutines.launch
import kotlin.math.max
import javax.inject.Inject
-private const val BACKGROUND_INDEX_STATUS_PREFIX = "Background index:"
@HiltViewModel
@OptIn(ExperimentalCoroutinesApi::class)
@@ -174,6 +173,7 @@ class SettingsViewModel @Inject constructor(
uiState = _uiState
)
private val providerActions: SettingsProviderActions = SettingsProviderActions(
+ appContext = application,
providerRepository = providerRepository,
combinedM3uRepository = combinedM3uRepository,
preferencesRepository = preferencesRepository,
@@ -326,6 +326,8 @@ class SettingsViewModel @Inject constructor(
}
}
+ private var previousIndexWarnings = emptySet<String>()
+
private fun registerXtreamIndexJobObserver() {
viewModelScope.launch {
settingsOperations.observeXtreamIndexJobs().collect { jobs ->
@@ -335,6 +337,8 @@ class SettingsViewModel @Inject constructor(
providerJobs.mapNotNull { job -> job.toSettingsWarningMessage() }
}
.filterValues { it.isNotEmpty() }
+ val outdatedWarnings = previousIndexWarnings
+ previousIndexWarnings = jobWarningsByProvider.values.flatten().toSet()
_uiState.update { state ->
val providerIds = state.providers.map { it.id }.toSet()
@@ -353,7 +357,7 @@ class SettingsViewModel @Inject constructor(
.filterKeys { it in providerIds }
.mapValues { (providerId, warnings) ->
warnings.filterNot { warning ->
- warning.startsWith(BACKGROUND_INDEX_STATUS_PREFIX) ||
+ warning in outdatedWarnings ||
completedLabelsByProvider[providerId].orEmpty().any { warning.startsWith("$it:") }
}
}
@@ -416,20 +420,18 @@ class SettingsViewModel @Inject constructor(
private fun SettingsXtreamIndexJob.toSettingsWarningMessage(): String? {
val label = when (section) {
- "LIVE" -> "Live TV"
- "MOVIE" -> "Movies"
- "SERIES" -> "Series"
- "EPG" -> "EPG"
- else -> section.lowercase().replaceFirstChar { it.titlecase() }
- }
- return when (state) {
- "PARTIAL" -> "$BACKGROUND_INDEX_STATUS_PREFIX $label partial: ${indexedRows} indexed"
- "TRUNCATED" -> "$BACKGROUND_INDEX_STATUS_PREFIX $label truncated: ${indexedRows} indexed"
- "FAILED" -> "$BACKGROUND_INDEX_STATUS_PREFIX $label failed${lastError?.let { ": $it" }.orEmpty()}"
- "FAILED_RETRYABLE" -> "$BACKGROUND_INDEX_STATUS_PREFIX $label retryable failed${lastError?.let { ": $it" }.orEmpty()}"
- "FAILED_PERMANENT" -> "$BACKGROUND_INDEX_STATUS_PREFIX $label permanently failed${lastError?.let { ": $it" }.orEmpty()}"
+ "LIVE" -> appContext.getString(R.string.settings_sync_option_tv)
+ "MOVIE" -> appContext.getString(R.string.settings_sync_option_movies)
+ "SERIES" -> appContext.getString(R.string.settings_sync_option_series)
+ "EPG" -> appContext.getString(R.string.settings_sync_option_epg)
+ else -> return null
+ }
+ val message = when (state) {
+ "PARTIAL", "TRUNCATED" -> appContext.getString(R.string.settings_sync_incomplete)
+ "FAILED", "FAILED_RETRYABLE", "FAILED_PERMANENT" -> appContext.getString(R.string.settings_auto_sync_status_failed)
else -> null
}
+ return message?.let { appContext.getString(R.string.settings_sync_index_progress, label, it) }
}
fun setActiveProvider(providerId: Long) {
diff --git a/feature/settings/src/main/res/values-ar/strings.xml b/feature/settings/src/main/res/values-ar/strings.xml
index 06174f7f..d39d7d44 100644
--- a/feature/settings/src/main/res/values-ar/strings.xml
+++ b/feature/settings/src/main/res/values-ar/strings.xml
@@ -952,4 +952,5 @@
<string name="settings_sports_custom_definition_file_too_large">ملف JSON أكبر من الحد الأقصى البالغ 32 كيلوبايت</string>
<string name="settings_sports_custom_definition_file_error">تعذّر تحميل ملف JSON هذا</string>
<string name="settings_experimental_badge">تجريبي</string>
+ <string name="settings_sync_index_progress">%1$s · %2$s</string>
</resources>
diff --git a/feature/settings/src/main/res/values-bg/strings.xml b/feature/settings/src/main/res/values-bg/strings.xml
index 7a060976..9f4ea553 100644
--- a/feature/settings/src/main/res/values-bg/strings.xml
+++ b/feature/settings/src/main/res/values-bg/strings.xml
@@ -938,4 +938,5 @@
<string name="settings_sports_custom_definition_file_too_large">JSON файлът надвишава ограничението от 32 KB</string>
<string name="settings_sports_custom_definition_file_error">Този JSON файл не може да бъде зареден</string>
<string name="settings_experimental_badge">Експериментално</string>
+ <string name="settings_sync_index_progress">%1$s · %2$s</string>
</resources>
diff --git a/feature/settings/src/main/res/values-cs/strings.xml b/feature/settings/src/main/res/values-cs/strings.xml
index c8e3111d..326454c6 100644
--- a/feature/settings/src/main/res/values-cs/strings.xml
+++ b/feature/settings/src/main/res/values-cs/strings.xml
@@ -946,4 +946,5 @@
<string name="settings_sports_custom_definition_file_too_large">Soubor JSON překračuje limit 32 kB</string>
<string name="settings_sports_custom_definition_file_error">Tento soubor JSON nelze načíst</string>
<string name="settings_experimental_badge">Experimentální</string>
+ <string name="settings_sync_index_progress">%1$s · %2$s</string>
</resources>
diff --git a/feature/settings/src/main/res/values-da/strings.xml b/feature/settings/src/main/res/values-da/strings.xml
index 890802e4..b13d29d1 100644
--- a/feature/settings/src/main/res/values-da/strings.xml
+++ b/feature/settings/src/main/res/values-da/strings.xml
@@ -940,4 +940,5 @@
<string name="settings_sports_custom_definition_file_too_large">JSON-filen overskrider grænsen på 32 kB</string>
<string name="settings_sports_custom_definition_file_error">Denne JSON-fil kunne ikke indlæses</string>
<string name="settings_experimental_badge">Eksperimentel</string>
+ <string name="settings_sync_index_progress">%1$s · %2$s</string>
</resources>
diff --git a/feature/settings/src/main/res/values-de/strings.xml b/feature/settings/src/main/res/values-de/strings.xml
index 2ee23001..fbfa7bc3 100644
--- a/feature/settings/src/main/res/values-de/strings.xml
+++ b/feature/settings/src/main/res/values-de/strings.xml
@@ -936,4 +936,5 @@
<string name="settings_sports_custom_definition_file_too_large">Die JSON-Datei überschreitet das Limit von 32 KB</string>
<string name="settings_sports_custom_definition_file_error">Diese JSON-Datei konnte nicht geladen werden</string>
<string name="settings_experimental_badge">Experimentell</string>
+ <string name="settings_sync_index_progress">%1$s · %2$s</string>
</resources>
diff --git a/feature/settings/src/main/res/values-el/strings.xml b/feature/settings/src/main/res/values-el/strings.xml
index a20b1c7c..0a85f1a5 100644
--- a/feature/settings/src/main/res/values-el/strings.xml
+++ b/feature/settings/src/main/res/values-el/strings.xml
@@ -940,4 +940,5 @@
<string name="settings_sports_custom_definition_file_too_large">Το αρχείο JSON υπερβαίνει το όριο των 32 KB</string>
<string name="settings_sports_custom_definition_file_error">Δεν ήταν δυνατή η φόρτωση αυτού του αρχείου JSON</string>
<string name="settings_experimental_badge">Πειραματικό</string>
+ <string name="settings_sync_index_progress">%1$s · %2$s</string>
</resources>
diff --git a/feature/settings/src/main/res/values-es/strings.xml b/feature/settings/src/main/res/values-es/strings.xml
index 9bdce996..ccdedeed 100644
--- a/feature/settings/src/main/res/values-es/strings.xml
+++ b/feature/settings/src/main/res/values-es/strings.xml
@@ -936,4 +936,5 @@
<string name="settings_sports_custom_definition_file_too_large">El archivo JSON supera el límite de 32 KB</string>
<string name="settings_sports_custom_definition_file_error">No se pudo cargar este archivo JSON</string>
<string name="settings_experimental_badge">Experimental</string>
+ <string name="settings_sync_index_progress">%1$s · %2$s</string>
</resources>
diff --git a/feature/settings/src/main/res/values-fa/strings.xml b/feature/settings/src/main/res/values-fa/strings.xml
index b17741b1..ab1c24a9 100644
--- a/feature/settings/src/main/res/values-fa/strings.xml
+++ b/feature/settings/src/main/res/values-fa/strings.xml
@@ -938,4 +938,5 @@
<string name="settings_sports_custom_definition_file_too_large">اندازه فایل JSON از حد ۳۲ کیلوبایت بیشتر است</string>
<string name="settings_sports_custom_definition_file_error">بارگذاری این فایل JSON ممکن نبود</string>
<string name="settings_experimental_badge">آزمایشی</string>
+ <string name="settings_sync_index_progress">%1$s · %2$s</string>
</resources>
diff --git a/feature/settings/src/main/res/values-fi/strings.xml b/feature/settings/src/main/res/values-fi/strings.xml
index bd8599cd..aed34bbe 100644
--- a/feature/settings/src/main/res/values-fi/strings.xml
+++ b/feature/settings/src/main/res/values-fi/strings.xml
@@ -940,4 +940,5 @@
<string name="settings_sports_custom_definition_file_too_large">JSON-tiedosto ylittää 32 kt:n rajan</string>
<string name="settings_sports_custom_definition_file_error">Tätä JSON-tiedostoa ei voitu ladata</string>
<string name="settings_experimental_badge">Kokeellinen</string>
+ <string name="settings_sync_index_progress">%1$s · %2$s</string>
</resources>
diff --git a/feature/settings/src/main/res/values-fil/strings.xml b/feature/settings/src/main/res/values-fil/strings.xml
index 1a5cb4af..27a46b71 100644
--- a/feature/settings/src/main/res/values-fil/strings.xml
+++ b/feature/settings/src/main/res/values-fil/strings.xml
@@ -938,4 +938,5 @@
<string name="settings_sports_custom_definition_file_too_large">Lumampas ang JSON file sa limit na 32 KB</string>
<string name="settings_sports_custom_definition_file_error">Hindi ma-load ang JSON file na ito</string>
<string name="settings_experimental_badge">Eksperimental</string>
+ <string name="settings_sync_index_progress">%1$s · %2$s</string>
</resources>
diff --git a/feature/settings/src/main/res/values-fr/strings.xml b/feature/settings/src/main/res/values-fr/strings.xml
index d3d8a0a9..b4d6e191 100644
--- a/feature/settings/src/main/res/values-fr/strings.xml
+++ b/feature/settings/src/main/res/values-fr/strings.xml
@@ -940,4 +940,5 @@
<string name="settings_sports_custom_definition_file_too_large">Le fichier JSON dépasse la limite de 32 Ko</string>
<string name="settings_sports_custom_definition_file_error">Impossible de charger ce fichier JSON</string>
<string name="settings_experimental_badge">Expérimental</string>
+ <string name="settings_sync_index_progress">%1$s · %2$s</string>
</resources>
diff --git a/feature/settings/src/main/res/values-hi/strings.xml b/feature/settings/src/main/res/values-hi/strings.xml
index 7a88054a..f788961f 100644
--- a/feature/settings/src/main/res/values-hi/strings.xml
+++ b/feature/settings/src/main/res/values-hi/strings.xml
@@ -938,4 +938,5 @@
<string name="settings_sports_custom_definition_file_too_large">JSON फ़ाइल 32 KB की सीमा से बड़ी है</string>
<string name="settings_sports_custom_definition_file_error">यह JSON फ़ाइल लोड नहीं की जा सकी</string>
<string name="settings_experimental_badge">प्रायोगिक</string>
+ <string name="settings_sync_index_progress">%1$s · %2$s</string>
</resources>
diff --git a/feature/settings/src/main/res/values-hr/strings.xml b/feature/settings/src/main/res/values-hr/strings.xml
index 36249b67..7941b164 100644
--- a/feature/settings/src/main/res/values-hr/strings.xml
+++ b/feature/settings/src/main/res/values-hr/strings.xml
@@ -941,4 +941,5 @@
<string name="settings_sports_custom_definition_file_too_large">JSON datoteka premašuje ograničenje od 32 KB</string>
<string name="settings_sports_custom_definition_file_error">Nije moguće učitati ovu JSON datoteku</string>
<string name="settings_experimental_badge">Eksperimentalno</string>
+ <string name="settings_sync_index_progress">%1$s · %2$s</string>
</resources>
diff --git a/feature/settings/src/main/res/values-hu/strings.xml b/feature/settings/src/main/res/values-hu/strings.xml
index 19d52557..2ed8ac78 100644
--- a/feature/settings/src/main/res/values-hu/strings.xml
+++ b/feature/settings/src/main/res/values-hu/strings.xml
@@ -940,4 +940,5 @@
<string name="settings_sports_custom_definition_file_too_large">A JSON-fájl meghaladja a 32 KB-os korlátot</string>
<string name="settings_sports_custom_definition_file_error">Ez a JSON-fájl nem tölthető be</string>
<string name="settings_experimental_badge">Kísérleti</string>
+ <string name="settings_sync_index_progress">%1$s · %2$s</string>
</resources>
diff --git a/feature/settings/src/main/res/values-in/strings.xml b/feature/settings/src/main/res/values-in/strings.xml
index aa18da60..c779e189 100644
--- a/feature/settings/src/main/res/values-in/strings.xml
+++ b/feature/settings/src/main/res/values-in/strings.xml
@@ -940,4 +940,5 @@
<string name="settings_sports_custom_definition_file_too_large">File JSON melebihi batas 32 KB</string>
<string name="settings_sports_custom_definition_file_error">File JSON ini tidak dapat dimuat</string>
<string name="settings_experimental_badge">Eksperimental</string>
+ <string name="settings_sync_index_progress">%1$s · %2$s</string>
</resources>
diff --git a/feature/settings/src/main/res/values-it/strings.xml b/feature/settings/src/main/res/values-it/strings.xml
index fcaff4d5..6a9a448a 100644
--- a/feature/settings/src/main/res/values-it/strings.xml
+++ b/feature/settings/src/main/res/values-it/strings.xml
@@ -936,4 +936,5 @@
<string name="settings_sports_custom_definition_file_too_large">Il file JSON supera il limite di 32 KB</string>
<string name="settings_sports_custom_definition_file_error">Impossibile caricare questo file JSON</string>
<string name="settings_experimental_badge">Sperimentale</string>
+ <string name="settings_sync_index_progress">%1$s · %2$s</string>
</resources>
diff --git a/feature/settings/src/main/res/values-iw/strings.xml b/feature/settings/src/main/res/values-iw/strings.xml
index 357cfd9b..15eeb416 100644
--- a/feature/settings/src/main/res/values-iw/strings.xml
+++ b/feature/settings/src/main/res/values-iw/strings.xml
@@ -943,4 +943,5 @@
<string name="settings_sports_custom_definition_file_too_large">קובץ JSON חורג מהמגבלה של 32 KB</string>
<string name="settings_sports_custom_definition_file_error">לא ניתן לטעון את קובץ ה-JSON הזה</string>
<string name="settings_experimental_badge">ניסיוני</string>
+ <string name="settings_sync_index_progress">%1$s · %2$s</string>
</resources>
diff --git a/feature/settings/src/main/res/values-ja/strings.xml b/feature/settings/src/main/res/values-ja/strings.xml
index 064dc1ba..728f83b4 100644
--- a/feature/settings/src/main/res/values-ja/strings.xml
+++ b/feature/settings/src/main/res/values-ja/strings.xml
@@ -938,4 +938,5 @@
<string name="settings_sports_custom_definition_file_too_large">JSON ファイルが 32 KB の上限を超えています</string>
<string name="settings_sports_custom_definition_file_error">この JSON ファイルを読み込めませんでした</string>
<string name="settings_experimental_badge">試験運用</string>
+ <string name="settings_sync_index_progress">%1$s · %2$s</string>
</resources>
diff --git a/feature/settings/src/main/res/values-ko/strings.xml b/feature/settings/src/main/res/values-ko/strings.xml
index c7f70447..73657bfe 100644
--- a/feature/settings/src/main/res/values-ko/strings.xml
+++ b/feature/settings/src/main/res/values-ko/strings.xml
@@ -936,4 +936,5 @@
<string name="settings_sports_custom_definition_file_too_large">JSON 파일이 32KB 제한을 초과합니다</string>
<string name="settings_sports_custom_definition_file_error">이 JSON 파일을 불러오지 못했습니다</string>
<string name="settings_experimental_badge">실험적 기능</string>
+ <string name="settings_sync_index_progress">%1$s · %2$s</string>
</resources>
diff --git a/feature/settings/src/main/res/values-mk/strings.xml b/feature/settings/src/main/res/values-mk/strings.xml
index b4f5bef6..4590bce0 100644
--- a/feature/settings/src/main/res/values-mk/strings.xml
+++ b/feature/settings/src/main/res/values-mk/strings.xml
@@ -938,4 +938,5 @@
<string name="settings_sports_custom_definition_file_too_large">JSON-датотеката ја надминува границата од 32 KB</string>
<string name="settings_sports_custom_definition_file_error">Оваа JSON-датотека не може да се вчита</string>
<string name="settings_experimental_badge">Експериментално</string>
+ <string name="settings_sync_index_progress">%1$s · %2$s</string>
</resources>
diff --git a/feature/settings/src/main/res/values-ms/strings.xml b/feature/settings/src/main/res/values-ms/strings.xml
index d9d02273..ddb68fb8 100644
--- a/feature/settings/src/main/res/values-ms/strings.xml
+++ b/feature/settings/src/main/res/values-ms/strings.xml
@@ -935,4 +935,5 @@
<string name="settings_sports_custom_definition_file_too_large">Fail JSON melebihi had 32 KB</string>
<string name="settings_sports_custom_definition_file_error">Fail JSON ini tidak dapat dimuatkan</string>
<string name="settings_experimental_badge">Eksperimen</string>
+ <string name="settings_sync_index_progress">%1$s · %2$s</string>
</resources>
diff --git a/feature/settings/src/main/res/values-nb/strings.xml b/feature/settings/src/main/res/values-nb/strings.xml
index f1ab2ccc..91ac52f8 100644
--- a/feature/settings/src/main/res/values-nb/strings.xml
+++ b/feature/settings/src/main/res/values-nb/strings.xml
@@ -940,4 +940,5 @@
<string name="settings_sports_custom_definition_file_too_large">JSON-filen overskrider grensen på 32 kB</string>
<string name="settings_sports_custom_definition_file_error">Denne JSON-filen kunne ikke lastes inn</string>
<string name="settings_experimental_badge">Eksperimentell</string>
+ <string name="settings_sync_index_progress">%1$s · %2$s</string>
</resources>
diff --git a/feature/settings/src/main/res/values-nl/strings.xml b/feature/settings/src/main/res/values-nl/strings.xml
index ab79881a..99a91d61 100644
--- a/feature/settings/src/main/res/values-nl/strings.xml
+++ b/feature/settings/src/main/res/values-nl/strings.xml
@@ -940,4 +940,5 @@
<string name="settings_sports_custom_definition_file_too_large">Het JSON-bestand is groter dan de limiet van 32 KB</string>
<string name="settings_sports_custom_definition_file_error">Dit JSON-bestand kon niet worden geladen</string>
<string name="settings_experimental_badge">Experimenteel</string>
+ <string name="settings_sync_index_progress">%1$s · %2$s</string>
</resources>
diff --git a/feature/settings/src/main/res/values-pl/strings.xml b/feature/settings/src/main/res/values-pl/strings.xml
index 8868bd38..5efaba2f 100644
--- a/feature/settings/src/main/res/values-pl/strings.xml
+++ b/feature/settings/src/main/res/values-pl/strings.xml
@@ -946,4 +946,5 @@
<string name="settings_sports_custom_definition_file_too_large">Plik JSON przekracza limit 32 KB</string>
<string name="settings_sports_custom_definition_file_error">Nie można wczytać tego pliku JSON</string>
<string name="settings_experimental_badge">Eksperymentalne</string>
+ <string name="settings_sync_index_progress">%1$s · %2$s</string>
</resources>
diff --git a/feature/settings/src/main/res/values-pt/strings.xml b/feature/settings/src/main/res/values-pt/strings.xml
index fb942e40..42ca860a 100644
--- a/feature/settings/src/main/res/values-pt/strings.xml
+++ b/feature/settings/src/main/res/values-pt/strings.xml
@@ -936,4 +936,5 @@
<string name="settings_sports_custom_definition_file_too_large">O arquivo JSON excede o limite de 32 KB</string>
<string name="settings_sports_custom_definition_file_error">Não foi possível carregar este arquivo JSON</string>
<string name="settings_experimental_badge">Experimental</string>
+ <string name="settings_sync_index_progress">%1$s · %2$s</string>
</resources>
diff --git a/feature/settings/src/main/res/values-ro/strings.xml b/feature/settings/src/main/res/values-ro/strings.xml
index f0b32d25..007d28f2 100644
--- a/feature/settings/src/main/res/values-ro/strings.xml
+++ b/feature/settings/src/main/res/values-ro/strings.xml
@@ -943,4 +943,5 @@
<string name="settings_sports_custom_definition_file_too_large">Fișierul JSON depășește limita de 32 KB</string>
<string name="settings_sports_custom_definition_file_error">Acest fișier JSON nu a putut fi încărcat</string>
<string name="settings_experimental_badge">Experimental</string>
+ <string name="settings_sync_index_progress">%1$s · %2$s</string>
</resources>
diff --git a/feature/settings/src/main/res/values-ru/strings.xml b/feature/settings/src/main/res/values-ru/strings.xml
index 0b2c3d3c..ba0a5e49 100644
--- a/feature/settings/src/main/res/values-ru/strings.xml
+++ b/feature/settings/src/main/res/values-ru/strings.xml
@@ -946,4 +946,5 @@
<string name="settings_sports_custom_definition_file_too_large">Файл JSON превышает ограничение 32 КБ</string>
<string name="settings_sports_custom_definition_file_error">Не удалось загрузить этот файл JSON</string>
<string name="settings_experimental_badge">Экспериментально</string>
+ <string name="settings_sync_index_progress">%1$s · %2$s</string>
</resources>
diff --git a/feature/settings/src/main/res/values-sk/strings.xml b/feature/settings/src/main/res/values-sk/strings.xml
index 6177d736..f338784f 100644
--- a/feature/settings/src/main/res/values-sk/strings.xml
+++ b/feature/settings/src/main/res/values-sk/strings.xml
@@ -944,4 +944,5 @@
<string name="settings_sports_custom_definition_file_too_large">Súbor JSON prekračuje limit 32 kB</string>
<string name="settings_sports_custom_definition_file_error">Tento súbor JSON sa nepodarilo načítať</string>
<string name="settings_experimental_badge">Experimentálne</string>
+ <string name="settings_sync_index_progress">%1$s · %2$s</string>
</resources>
diff --git a/feature/settings/src/main/res/values-sq/strings.xml b/feature/settings/src/main/res/values-sq/strings.xml
index ee4e9bc1..4e46d76a 100644
--- a/feature/settings/src/main/res/values-sq/strings.xml
+++ b/feature/settings/src/main/res/values-sq/strings.xml
@@ -938,4 +938,5 @@
<string name="settings_sports_custom_definition_file_too_large">Skedari JSON tejkalon kufirin prej 32 KB</string>
<string name="settings_sports_custom_definition_file_error">Ky skedar JSON nuk mund të ngarkohej</string>
<string name="settings_experimental_badge">Eksperimentale</string>
+ <string name="settings_sync_index_progress">%1$s · %2$s</string>
</resources>
diff --git a/feature/settings/src/main/res/values-sr/strings.xml b/feature/settings/src/main/res/values-sr/strings.xml
index 9a769ccf..20969205 100644
--- a/feature/settings/src/main/res/values-sr/strings.xml
+++ b/feature/settings/src/main/res/values-sr/strings.xml
@@ -941,4 +941,5 @@
<string name="settings_sports_custom_definition_file_too_large">JSON датотека премашује ограничење од 32 KB</string>
<string name="settings_sports_custom_definition_file_error">Није могуће учитати ову JSON датотеку</string>
<string name="settings_experimental_badge">Експериментално</string>
+ <string name="settings_sync_index_progress">%1$s · %2$s</string>
</resources>
diff --git a/feature/settings/src/main/res/values-sv/strings.xml b/feature/settings/src/main/res/values-sv/strings.xml
index 98a75ae5..28bb1f77 100644
--- a/feature/settings/src/main/res/values-sv/strings.xml
+++ b/feature/settings/src/main/res/values-sv/strings.xml
@@ -940,4 +940,5 @@
<string name="settings_sports_custom_definition_file_too_large">JSON-filen överskrider gränsen på 32 kB</string>
<string name="settings_sports_custom_definition_file_error">Det gick inte att läsa in den här JSON-filen</string>
<string name="settings_experimental_badge">Experimentell</string>
+ <string name="settings_sync_index_progress">%1$s · %2$s</string>
</resources>
diff --git a/feature/settings/src/main/res/values-th/strings.xml b/feature/settings/src/main/res/values-th/strings.xml
index 08e63aae..9cfa991a 100644
--- a/feature/settings/src/main/res/values-th/strings.xml
+++ b/feature/settings/src/main/res/values-th/strings.xml
@@ -935,4 +935,5 @@
<string name="settings_sports_custom_definition_file_too_large">ไฟล์ JSON มีขนาดเกินขีดจำกัด 32 KB</string>
<string name="settings_sports_custom_definition_file_error">ไม่สามารถโหลดไฟล์ JSON นี้ได้</string>
<string name="settings_experimental_badge">ฟีเจอร์ทดลอง</string>
+ <string name="settings_sync_index_progress">%1$s · %2$s</string>
</resources>
diff --git a/feature/settings/src/main/res/values-tr/strings.xml b/feature/settings/src/main/res/values-tr/strings.xml
index 7f992051..5aee988a 100644
--- a/feature/settings/src/main/res/values-tr/strings.xml
+++ b/feature/settings/src/main/res/values-tr/strings.xml
@@ -940,4 +940,5 @@
<string name="settings_sports_custom_definition_file_too_large">JSON dosyası 32 KB sınırını aşıyor</string>
<string name="settings_sports_custom_definition_file_error">Bu JSON dosyası yüklenemedi</string>
<string name="settings_experimental_badge">Deneysel</string>
+ <string name="settings_sync_index_progress">%1$s · %2$s</string>
</resources>
diff --git a/feature/settings/src/main/res/values-uk/strings.xml b/feature/settings/src/main/res/values-uk/strings.xml
index e1f87470..0f4070ea 100644
--- a/feature/settings/src/main/res/values-uk/strings.xml
+++ b/feature/settings/src/main/res/values-uk/strings.xml
@@ -946,4 +946,5 @@
<string name="settings_sports_custom_definition_file_too_large">Файл JSON перевищує обмеження 32 КБ</string>
<string name="settings_sports_custom_definition_file_error">Не вдалося завантажити цей файл JSON</string>
<string name="settings_experimental_badge">Експериментально</string>
+ <string name="settings_sync_index_progress">%1$s · %2$s</string>
</resources>
diff --git a/feature/settings/src/main/res/values-vi/strings.xml b/feature/settings/src/main/res/values-vi/strings.xml
index 2a456554..6cbc8f7d 100644
--- a/feature/settings/src/main/res/values-vi/strings.xml
+++ b/feature/settings/src/main/res/values-vi/strings.xml
@@ -937,4 +937,5 @@
<string name="settings_sports_custom_definition_file_too_large">Tệp JSON vượt quá giới hạn 32 KB</string>
<string name="settings_sports_custom_definition_file_error">Không thể tải tệp JSON này</string>
<string name="settings_experimental_badge">Thử nghiệm</string>
+ <string name="settings_sync_index_progress">%1$s · %2$s</string>
</resources>
diff --git a/feature/settings/src/main/res/values-zh-rTW/strings.xml b/feature/settings/src/main/res/values-zh-rTW/strings.xml
index b6eb6098..5b1b61b6 100644
--- a/feature/settings/src/main/res/values-zh-rTW/strings.xml
+++ b/feature/settings/src/main/res/values-zh-rTW/strings.xml
@@ -935,4 +935,5 @@
<string name="settings_sports_custom_definition_file_too_large">JSON 檔案超過 32 KB 上限</string>
<string name="settings_sports_custom_definition_file_error">無法載入此 JSON 檔案</string>
<string name="settings_experimental_badge">實驗性</string>
+ <string name="settings_sync_index_progress">%1$s · %2$s</string>
</resources>
diff --git a/feature/settings/src/main/res/values-zh/strings.xml b/feature/settings/src/main/res/values-zh/strings.xml
index 1290799a..2078082e 100644
--- a/feature/settings/src/main/res/values-zh/strings.xml
+++ b/feature/settings/src/main/res/values-zh/strings.xml
@@ -936,4 +936,5 @@
<string name="settings_sports_custom_definition_file_too_large">JSON 文件超过 32 KB 限制</string>
<string name="settings_sports_custom_definition_file_error">无法加载此 JSON 文件</string>
<string name="settings_experimental_badge">实验性</string>
+ <string name="settings_sync_index_progress">%1$s · %2$s</string>
</resources>
diff --git a/feature/settings/src/main/res/values/strings.xml b/feature/settings/src/main/res/values/strings.xml
index 764ed0cb..4394597a 100644
--- a/feature/settings/src/main/res/values/strings.xml
+++ b/feature/settings/src/main/res/values/strings.xml
@@ -1015,4 +1015,5 @@
<string name="settings_sports_custom_definition_file_too_large">The JSON file is larger than the 32 KB limit</string>
<string name="settings_sports_custom_definition_file_error">Could not load this JSON file</string>
<string name="settings_experimental_badge">Experimental</string>
+ <string name="settings_sync_index_progress">%1$s · %2$s</string>
</resources>
diff --git a/feature/settings/src/test/java/com/streamvault/feature/settings/presentation/SettingsProviderActionsTest.kt b/feature/settings/src/test/java/com/streamvault/feature/settings/presentation/SettingsProviderActionsTest.kt
index bcea4cf8..ea515cb3 100644
--- a/feature/settings/src/test/java/com/streamvault/feature/settings/presentation/SettingsProviderActionsTest.kt
+++ b/feature/settings/src/test/java/com/streamvault/feature/settings/presentation/SettingsProviderActionsTest.kt
@@ -18,6 +18,7 @@ import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.advanceUntilIdle
import kotlinx.coroutines.test.runTest
+import kotlinx.coroutines.test.runCurrent
import org.junit.Test
import org.mockito.kotlin.any
import org.mockito.kotlin.doThrow
@@ -41,6 +42,9 @@ class SettingsProviderActionsTest {
private val requestedSyncs = mutableListOf<Long>()
private val actions = SettingsProviderActions(
+ appContext = mock<android.content.Context>(defaultAnswer = org.mockito.stubbing.Answer { call ->
+ if (call.method.name == "getString") "Localized" else org.mockito.Answers.RETURNS_DEFAULTS.answer(call)
+ }),
providerRepository = providerRepository,
combinedM3uRepository = combinedM3uRepository,
preferencesRepository = preferencesRepository,
@@ -52,6 +56,28 @@ class SettingsProviderActionsTest {
onSyncRequested = { _, provider -> requestedSyncs += provider.id }
)
+ @Test fun rebuildRemainsVisibleUntilBothDurableSectionsComplete() = runTest {
+ whenever(providerRepository.getProvider(7L)).thenReturn(Provider(
+ id = 7L, name = "Xtream", type = ProviderType.XTREAM_CODES, serverUrl = "https://example.test"
+ ))
+ whenever(preferencesRepository.getXtreamTextImportGeneration()).thenReturn(0L)
+ whenever(preferencesRepository.getXtreamTextImportAppliedGeneration(7L)).thenReturn(0L)
+ whenever(settingsOperations.rebuildXtreamIndex(eq(7L), any())).thenReturn(
+ Result.success(ProviderSectionSyncResult(queued = true))
+ )
+ val jobs = MutableStateFlow(listOf(
+ com.streamvault.domain.settings.SettingsXtreamIndexJob(7L, "MOVIE", "QUEUED", 0, null),
+ com.streamvault.domain.settings.SettingsXtreamIndexJob(7L, "SERIES", "QUEUED", 0, null)
+ ))
+ whenever(settingsOperations.observeXtreamIndexJobs()).thenReturn(jobs)
+ actions.rebuildProviderIndex(this, 7L).start()
+ runCurrent()
+ assertThat(uiState.value.isSyncing).isTrue()
+ jobs.value = jobs.value.map { it.copy(state = "SUCCESS", indexedRows = 20) }
+ advanceUntilIdle()
+ assertThat(uiState.value.isSyncing).isFalse()
+ }
+
@Test
fun successfulManualLiveRefreshPreventsRepeatedSyncOnProviderSwitch() = runTest {
whenever(providerRepository.getProvider(7L)).thenReturn(Provider(
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 cdf0d2b6..0f4a3cec 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
@@ -7,16 +7,19 @@ import com.streamvault.domain.model.ProviderType
import com.streamvault.domain.model.Result
import com.streamvault.domain.settings.SettingsOperations
import com.streamvault.domain.settings.SettingsSyncSection
+import com.streamvault.domain.settings.SettingsXtreamIndexJob
import com.streamvault.domain.sync.ProviderSectionSyncResult
import com.streamvault.feature.settings.R
import com.streamvault.feature.settings.api.SettingsSurfaceRefreshPort
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.test.advanceUntilIdle
import kotlinx.coroutines.test.runCurrent
import kotlinx.coroutines.test.runTest
import org.junit.Test
+import org.junit.Before
import org.mockito.Answers
import org.mockito.kotlin.any
import org.mockito.kotlin.doSuspendableAnswer
@@ -45,6 +48,8 @@ class SettingsSyncActionsTest {
R.string.settings_sync_cancelled -> "Sync cancelled."
R.string.settings_sync_stopped_queued -> "Refresh stopped. Already queued work will continue."
R.string.settings_syncing_section -> "Refreshing %1\$s"
+ R.string.settings_sync_index_progress -> "%1\$s · %2\$s"
+ R.string.settings_sync_incomplete -> "Refresh is incomplete; cached content was preserved."
else -> "Preparing"
}
String.format(format, *invocation.arguments.drop(1).toTypedArray())
@@ -60,6 +65,13 @@ class SettingsSyncActionsTest {
error("A section refresh must not rebuild the index")
}
+ @Before fun completedIndexes() {
+ whenever(operations.observeXtreamIndexJobs()).thenReturn(flowOf(listOf(
+ SettingsXtreamIndexJob(7L, "MOVIE", "SUCCESS", 30, null),
+ SettingsXtreamIndexJob(7L, "SERIES", "SUCCESS", 20, null)
+ )))
+ }
+
@Test
fun `sync now includes Stalker series and queues EPG without waiting for it`() = runTest {
whenever(operations.syncProviderSection(eq(7L), any(), any())).thenAnswer { invocation ->
@@ -74,7 +86,8 @@ class SettingsSyncActionsTest {
verify(operations).syncProviderSection(eq(7L), eq(SettingsSyncSection.SERIES), any())
verify(operations, never()).syncProviderSection(eq(7L), eq(SettingsSyncSection.EPG), any())
verify(operations).scheduleBackgroundEpgSync(7L)
- assertThat(state.value.userMessage).contains("Series refresh queued")
+ assertThat(state.value.userMessage).contains("Series")
+ assertThat(state.value.userMessage).doesNotContain("Series refresh queued")
assertThat(state.value.userMessage).contains("EPG refresh queued")
assertThat(state.value.isSyncing).isFalse()
}
@@ -90,7 +103,8 @@ class SettingsSyncActionsTest {
advanceUntilIdle()
assertThat(state.value.userMessage).contains("Incomplete")
- assertThat(state.value.syncWarningsByProvider[7L]).containsExactly("TV: Sports unavailable")
+ assertThat(state.value.syncWarningsByProvider[7L].orEmpty().single()).contains("Refresh is incomplete")
+ assertThat(state.value.userMessage).doesNotContain("Sports unavailable")
verify(surfaces).enqueueTvInputCatalogRefresh()
}
@@ -103,8 +117,9 @@ class SettingsSyncActionsTest {
actions.retryWarningAction(this, 7L, ProviderWarningAction.MOVIES)
advanceUntilIdle()
- assertThat(state.value.syncWarningsByProvider[7L]).containsExactly("Movies: Missing rows")
- assertThat(state.value.userMessage).contains("Movies refresh queued")
+ assertThat(state.value.syncWarningsByProvider[7L]).isNull()
+ assertThat(state.value.userMessage).contains("Movies")
+ assertThat(state.value.userMessage).doesNotContain("Movies refresh queued")
}
@Test
@@ -115,8 +130,8 @@ class SettingsSyncActionsTest {
)
actions.retryWarningAction(this, 7L, ProviderWarningAction.EPG)
advanceUntilIdle()
- assertThat(state.value.userMessage).contains("XMLTV unavailable")
- assertThat(state.value.syncWarningsByProvider[7L]).contains("EPG: XMLTV unavailable")
+ assertThat(state.value.userMessage).contains("Refresh is incomplete")
+ assertThat(state.value.userMessage).doesNotContain("XMLTV unavailable")
whenever(operations.syncProviderSection(eq(7L), eq(SettingsSyncSection.EPG), any())).thenReturn(
Result.success(ProviderSectionSyncResult())
@@ -137,7 +152,7 @@ class SettingsSyncActionsTest {
assertThat(state.value.isSyncing).isFalse()
assertThat(state.value.syncCanCancel).isFalse()
assertThat(state.value.syncProgress).isNull()
- assertThat(state.value.userMessage).contains("Guide unavailable")
+ assertThat(state.value.userMessage).contains("Refresh is incomplete")
}
@Test
@@ -186,4 +201,47 @@ class SettingsSyncActionsTest {
ProviderSyncSelection.SERIES, ProviderSyncSelection.EPG
).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 {
+ 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")
+ }
+
+ @Test fun `M3U combined refresh uses one complete playlist operation`() = runTest {
+ state.value = state.value.copy(providers = listOf(provider.copy(type = ProviderType.M3U)))
+ whenever(operations.syncPlaylistCatalog(eq(7L), any())).thenReturn(Result.success(ProviderSectionSyncResult(catalogChanged = true)))
+ actions.syncProviderCustom(this, 7L, setOf(ProviderSyncSelection.TV, ProviderSyncSelection.MOVIES))
+ advanceUntilIdle()
+ verify(operations).syncPlaylistCatalog(eq(7L), any())
+ verify(operations, never()).syncProviderSection(any(), any(), any())
+ assertThat(state.value.userMessage).contains("Movies")
+ verify(surfaces).enqueueTvInputCatalogRefresh()
+ }
}