Skip to content

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

playback and stalker improvement

David Nashash81b9c31cbe34
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerLifecycleActions.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerLifecycleActions.kt
index 4f7e57e4..78242761 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerLifecycleActions.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerLifecycleActions.kt
@@ -66,43 +66,6 @@ internal fun PlayerViewModel.startTokenRenewalMonitoring(expirationTime: Long?)
}
}
-internal suspend fun PlayerViewModel.synchronizeStalkerPlaybackFetchDeferral(isPlaying: Boolean) {
- if (!isPlaying) {
- stopActiveStalkerPlaybackFetchDeferral()
- return
- }
-
- val providerId = currentProviderId.takeIf { it > 0L } ?: run {
- stopActiveStalkerPlaybackFetchDeferral()
- return
- }
- val provider = providerRepository.getProvider(providerId)
- if (provider?.type != ProviderType.STALKER_PORTAL) {
- stopActiveStalkerPlaybackFetchDeferral()
- return
- }
- val previousProviderId = activeStalkerPlaybackProviderId
- if (previousProviderId != null && previousProviderId != providerId) {
- syncManager.noteStalkerPlaybackStopped(previousProviderId)
- }
- if (previousProviderId != providerId) {
- syncManager.noteStalkerPlaybackStarted(providerId)
- activeStalkerPlaybackProviderId = providerId
- }
-}
-
-internal fun PlayerViewModel.reconcileStalkerPlaybackFetchDeferral() {
- viewModelScope.launch {
- synchronizeStalkerPlaybackFetchDeferral(playerEngine.isPlaying.value)
- }
-}
-
-internal fun PlayerViewModel.stopActiveStalkerPlaybackFetchDeferral() {
- val providerId = activeStalkerPlaybackProviderId ?: return
- activeStalkerPlaybackProviderId = null
- syncManager.noteStalkerPlaybackStopped(providerId)
-}
-
fun PlayerViewModel.onAppBackgrounded() {
if (!isAppInForeground) return
isAppInForeground = false
@@ -128,7 +91,6 @@ fun PlayerViewModel.onAppForegrounded() {
}
fun PlayerViewModel.onPlayerScreenDisposed() {
- stopActiveStalkerPlaybackFetchDeferral()
if (currentContentType != ContentType.LIVE) {
viewModelScope.launch {
persistPlaybackProgress()
@@ -136,6 +98,7 @@ fun PlayerViewModel.onPlayerScreenDisposed() {
}
}
playerEngine.stopLiveTimeshift()
+ stopActiveStalkerPlaybackFetchDeferral()
clearPlaybackTimers()
}
@@ -151,11 +114,42 @@ internal fun PlayerViewModel.clearPlaybackTimers() {
_sleepTimerUiState.value = SleepTimerUiState()
}
+internal fun PlayerViewModel.stopActiveStalkerPlaybackFetchDeferral() {
+ val providerId = activeStalkerPlaybackProviderId ?: return
+ activeStalkerPlaybackProviderId = null
+ viewModelScope.launch {
+ syncManager.noteStalkerPlaybackStopped(providerId)
+ }
+}
+
+internal suspend fun PlayerViewModel.synchronizeStalkerPlaybackFetchDeferral(isPlaying: Boolean) {
+ if (!isPlaying) {
+ stopActiveStalkerPlaybackFetchDeferral()
+ return
+ }
+
+ val providerId = currentProviderId.takeIf { it > 0L } ?: run {
+ stopActiveStalkerPlaybackFetchDeferral()
+ return
+ }
+ val provider = providerRepository.getProvider(providerId)
+ if (provider?.type != ProviderType.STALKER_PORTAL) {
+ stopActiveStalkerPlaybackFetchDeferral()
+ return
+ }
+ if (activeStalkerPlaybackProviderId == providerId) return
+
+ stopActiveStalkerPlaybackFetchDeferral()
+ activeStalkerPlaybackProviderId = providerId
+ syncManager.noteStalkerPlaybackStarted(providerId)
+}
+
fun PlayerViewModel.handOffPlaybackToMultiView() {
if (currentContentType != ContentType.LIVE) {
viewModelScope.launch { persistPlaybackProgress() }
}
playerEngine.stopLiveTimeshift()
+ stopActiveStalkerPlaybackFetchDeferral()
livePreviewHandoffManager.clear(playerEngine)
}
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerPreparationSetupActions.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerPreparationSetupActions.kt
index f8df32e4..5a6dac0a 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerPreparationSetupActions.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerPreparationSetupActions.kt
@@ -65,6 +65,7 @@ internal fun PlayerViewModel.applyPrepareSessionState(
val previousCategoryId = currentCategoryId
val previousCombinedProfileId = currentCombinedProfileId
val previousCombinedSourceFilterProviderId = currentCombinedSourceFilterProviderId
+ stopActiveStalkerPlaybackFetchDeferral()
val shouldReloadPlaylist = categoryId != -1L &&
(
categoryId != previousCategoryId ||
@@ -115,7 +116,6 @@ internal fun PlayerViewModel.applyPrepareSessionState(
if (currentContentType != ContentType.SERIES_EPISODE || providerId <= 0 || currentSeriesId == null) {
clearSeriesEpisodeContext()
}
- reconcileStalkerPlaybackFetchDeferral()
if (currentContentType != ContentType.LIVE) {
lastRecordedLivePlaybackKey = null
recentChannelsJob?.cancel()
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModel.kt
index e686218f..e4a1dd61 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModel.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModel.kt
@@ -15,9 +15,9 @@ import com.streamvault.app.util.isPlaybackComplete
import com.streamvault.app.tv.LauncherRecommendationsManager
import com.streamvault.app.tv.WatchNextManager
import com.streamvault.data.remote.stalker.StalkerUrlFactory
-import com.streamvault.data.sync.SyncManager
import com.streamvault.data.remote.xtream.XtreamStreamUrlResolver
import com.streamvault.data.security.CredentialDecryptionException
+import com.streamvault.data.sync.SyncManager
import com.streamvault.domain.manager.RecordingManager
import com.streamvault.domain.model.Category
import com.streamvault.domain.model.ChannelNumberingMode
@@ -307,7 +307,6 @@ class PlayerViewModel @Inject constructor(
internal var currentCombinedProfileMembers: List<CombinedM3uProfileMember> = emptyList()
internal var combinedCategoriesById: Map<Long, CombinedCategory> = emptyMap()
private var lastObservedPlaybackState: PlaybackState = PlaybackState.IDLE
- internal var activeStalkerPlaybackProviderId: Long? = null
internal var epgJob: Job? = null
internal var playlistJob: Job? = null
@@ -339,6 +338,7 @@ class PlayerViewModel @Inject constructor(
private var defaultIdleStandbyTimerMinutes: Int = 0
internal var playbackTimerDefaultsApplied = false
internal var sleepTimerExitEmitted = false
+ internal var activeStalkerPlaybackProviderId: Long? = null
val castConnectionState: StateFlow<CastConnectionState> = castManager.connectionState
diff --git a/data/src/main/java/com/streamvault/data/remote/stalker/StalkerProvider.kt b/data/src/main/java/com/streamvault/data/remote/stalker/StalkerProvider.kt
index 9bcd0612..3d9171f8 100644
--- a/data/src/main/java/com/streamvault/data/remote/stalker/StalkerProvider.kt
+++ b/data/src/main/java/com/streamvault/data/remote/stalker/StalkerProvider.kt
@@ -696,7 +696,14 @@ class StalkerProvider(
val (session, _) = authResult.data
when (val result = loader(session, currentDeviceProfile())) {
is Result.Success -> {
- val categories = result.data.map { record ->
+ val categoryRecords = result.data.ifEmpty {
+ when (type) {
+ ContentType.MOVIE -> listOf(StalkerCategoryRecord(id = "*", name = "All Movies"))
+ ContentType.SERIES -> listOf(StalkerCategoryRecord(id = "*", name = "All Series"))
+ else -> emptyList()
+ }
+ }
+ val categories = categoryRecords.map { record ->
val id = syntheticCategoryId(type, record.id.ifBlank { record.name })
CategorySeed(
id = id,
diff --git a/data/src/main/java/com/streamvault/data/remote/stalker/StalkerTrafficCoordinator.kt b/data/src/main/java/com/streamvault/data/remote/stalker/StalkerTrafficCoordinator.kt
index 571db0b6..e7ee9cb4 100644
--- a/data/src/main/java/com/streamvault/data/remote/stalker/StalkerTrafficCoordinator.kt
+++ b/data/src/main/java/com/streamvault/data/remote/stalker/StalkerTrafficCoordinator.kt
@@ -3,36 +3,24 @@ package com.streamvault.data.remote.stalker
import java.util.concurrent.ConcurrentHashMap
internal object StalkerTrafficCoordinator {
- private const val PLAYBACK_PROTECTION_WINDOW_MILLIS = 90_000L
- private const val ACTIVE_PLAYBACK_RECHECK_MILLIS = 5_000L
- private val recentPlaybackByProvider = ConcurrentHashMap<Long, Long>()
- private val activePlaybackCountByProvider = ConcurrentHashMap<Long, Int>()
+ private const val ACTIVE_PLAYBACK_RECHECK_MILLIS = 3_000L
+ private val activePlaybackCountsByProvider = ConcurrentHashMap<Long, Int>()
- fun notePlaybackActivity(providerId: Long, now: Long = System.currentTimeMillis()) {
+ fun notePlaybackStarted(providerId: Long) {
if (providerId <= 0L) return
- recentPlaybackByProvider[providerId] = now
- }
-
- fun notePlaybackStarted(providerId: Long, now: Long = System.currentTimeMillis()) {
- if (providerId <= 0L) return
- recentPlaybackByProvider[providerId] = now
- activePlaybackCountByProvider.compute(providerId) { _, existing ->
- (existing ?: 0) + 1
+ activePlaybackCountsByProvider.compute(providerId) { _, current ->
+ (current ?: 0) + 1
}
}
fun notePlaybackStopped(providerId: Long) {
if (providerId <= 0L) return
- activePlaybackCountByProvider.compute(providerId) { _, existing ->
+ activePlaybackCountsByProvider.compute(providerId) { _, current ->
when {
- existing == null || existing <= 1 -> null
- else -> existing - 1
+ current == null || current <= 1 -> null
+ else -> current - 1
}
}
- if ((activePlaybackCountByProvider[providerId] ?: 0) <= 0) {
- activePlaybackCountByProvider.remove(providerId)
- recentPlaybackByProvider.remove(providerId)
- }
}
fun shouldDeferCatalogFetch(providerId: Long, now: Long = System.currentTimeMillis()): Boolean =
@@ -40,20 +28,11 @@ internal object StalkerTrafficCoordinator {
fun deferCatalogFetchMillis(providerId: Long, now: Long = System.currentTimeMillis()): Long {
if (providerId <= 0L) return 0L
- if ((activePlaybackCountByProvider[providerId] ?: 0) > 0) {
- return ACTIVE_PLAYBACK_RECHECK_MILLIS
- }
- val lastPlaybackAt = recentPlaybackByProvider[providerId] ?: return 0L
- val remaining = (lastPlaybackAt + PLAYBACK_PROTECTION_WINDOW_MILLIS) - now
- if (remaining <= 0L) {
- recentPlaybackByProvider.remove(providerId, lastPlaybackAt)
- return 0L
- }
- return remaining
+ if ((activePlaybackCountsByProvider[providerId] ?: 0) <= 0) return 0L
+ return ACTIVE_PLAYBACK_RECHECK_MILLIS
}
internal fun resetForTests() {
- recentPlaybackByProvider.clear()
- activePlaybackCountByProvider.clear()
+ activePlaybackCountsByProvider.clear()
}
}
\ No newline at end of file
diff --git a/data/src/main/java/com/streamvault/data/remote/xtream/XtreamStreamUrlResolver.kt b/data/src/main/java/com/streamvault/data/remote/xtream/XtreamStreamUrlResolver.kt
index f0091b0e..efe76e5f 100644
--- a/data/src/main/java/com/streamvault/data/remote/xtream/XtreamStreamUrlResolver.kt
+++ b/data/src/main/java/com/streamvault/data/remote/xtream/XtreamStreamUrlResolver.kt
@@ -157,7 +157,6 @@ class XtreamStreamUrlResolver @Inject constructor(
expirationTime = extractStreamExpirationTime(passthroughUrl)
)
}
- StalkerTrafficCoordinator.notePlaybackActivity(resolvedProvider.id)
val playbackInfo = when (
val resolvedResult = getOrCreateStalkerProvider(resolvedProvider)
.resolvePlaybackInfo(
@@ -213,7 +212,6 @@ class XtreamStreamUrlResolver @Inject constructor(
fallbackContentType: ContentType?,
fallbackContainerExtension: String?
): ResolvedStreamUrl? {
- StalkerTrafficCoordinator.notePlaybackActivity(provider.id)
val kind = when (fallbackContentType) {
ContentType.LIVE -> StalkerStreamKind.LIVE
ContentType.MOVIE -> StalkerStreamKind.MOVIE
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 29cb3262..9bb07cb5 100644
--- a/data/src/main/java/com/streamvault/data/sync/StalkerIndexWorker.kt
+++ b/data/src/main/java/com/streamvault/data/sync/StalkerIndexWorker.kt
@@ -99,7 +99,7 @@ class StalkerIndexWorker(
private const val KEY_SECTION = "section"
private const val KEY_FORCE = "force"
private const val INVALID_PROVIDER_ID = -1L
- private const val CATEGORY_SLICE_SIZE = 12
+ private const val CATEGORY_SLICE_SIZE = 32
private const val UNIQUE_WORK_PREFIX = "stalker-index-worker-"
fun enqueue(
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 4c57efa5..9a02cb6f 100644
--- a/data/src/main/java/com/streamvault/data/sync/SyncManager.kt
+++ b/data/src/main/java/com/streamvault/data/sync/SyncManager.kt
@@ -97,10 +97,10 @@ import javax.inject.Singleton
private const val TAG = "SyncManager"
private const val XTREAM_FALLBACK_STAGE_BATCH_SIZE = 500
-private const val STALKER_INDEX_CATEGORY_SLICE_SIZE = 12
-private const val STALKER_WILDCARD_PAGE_SLICE_SIZE = 48
+private const val STALKER_INDEX_CATEGORY_SLICE_SIZE = 32
+private const val STALKER_WILDCARD_PAGE_SLICE_SIZE = 192
private const val STALKER_MAX_PARALLEL_CATEGORY_FETCHES = 6
-private const val STALKER_MAX_SECTION_RUN_MILLIS = 90_000L
+private const val STALKER_MAX_SECTION_RUN_MILLIS = 240_000L
private const val STALKER_CATEGORY_RETRY_BUDGET = 3
private const val STALKER_CATEGORY_RETRY_COOLDOWN_MILLIS = 5 * 60 * 1000L
private const val STALKER_RUNNING_JOB_STALE_MILLIS = 15 * 60 * 1000L
@@ -352,11 +352,7 @@ class SyncManager @Inject constructor(
block: suspend () -> T
): T = when (section) {
ContentType.MOVIE,
- ContentType.SERIES -> if (providerMaxConnections > 1) {
- withStalkerIndexSectionLock(providerId, section, block)
- } else {
- withStalkerSummaryProviderLock(providerId, block)
- }
+ ContentType.SERIES -> withStalkerSummaryProviderLock(providerId, block)
else -> withProviderLock(providerId, block)
}
@@ -430,29 +426,27 @@ class SyncManager @Inject constructor(
force: Boolean = false,
initialDelaySeconds: Long = 0L
) {
+ val effectiveSection: ContentType? = null
runCatching {
StalkerIndexWorker.enqueue(
context = applicationContext,
providerId = providerId,
- section = section?.name,
+ section = effectiveSection?.name,
force = force,
initialDelaySeconds = initialDelaySeconds
)
}.onFailure { error ->
- Log.w(TAG, "Failed to schedule Stalker index work for provider $providerId (${section?.name ?: "all"}): ${sanitizeThrowableMessage(error)}")
+ Log.w(TAG, "Failed to schedule Stalker index work for provider $providerId (${effectiveSection?.name ?: "all"}): ${sanitizeThrowableMessage(error)}")
}
}
fun noteStalkerPlaybackStarted(providerId: Long) {
- if (providerId <= 0L) return
StalkerTrafficCoordinator.notePlaybackStarted(providerId)
}
fun noteStalkerPlaybackStopped(providerId: Long) {
- if (providerId <= 0L) return
StalkerTrafficCoordinator.notePlaybackStopped(providerId)
- scheduleStalkerIndexSync(providerId, ContentType.MOVIE, force = false)
- scheduleStalkerIndexSync(providerId, ContentType.SERIES, force = false)
+ scheduleStalkerIndexSync(providerId = providerId)
}
suspend fun prioritizeXtreamIndexCategory(
@@ -504,7 +498,12 @@ class SyncManager @Inject constructor(
priorityRequestedAt = now
)
}
- scheduleStalkerIndexSync(providerId, section, force = false)
+ val provider = providerDao.getById(providerId)?.toDomain()
+ if (provider != null) {
+ scheduleStalkerIndexContinuation(provider, section, force = false)
+ } else {
+ scheduleStalkerIndexSync(providerId, section, force = false)
+ }
}
suspend fun syncEpg(
@@ -538,6 +537,16 @@ class SyncManager @Inject constructor(
.toDomain()
val providerId = provider.id
+ if (!force && provider.type == ProviderType.STALKER_PORTAL && hasPendingStalkerCatalogIndex(provider.id)) {
+ updateXtreamEpgJobState(
+ provider = provider,
+ state = "QUEUED",
+ now = System.currentTimeMillis(),
+ lastError = null
+ )
+ return com.streamvault.domain.model.Result.success(Unit)
+ }
+
val startedAt = System.currentTimeMillis()
updateXtreamEpgJobState(
provider = provider,
@@ -1514,9 +1523,6 @@ class SyncManager @Inject constructor(
private fun shouldRunXtreamSummaryIndex(job: XtreamIndexJobEntity?): Boolean {
if (job == null) return true
- if (job.state == "RUNNING" && System.currentTimeMillis() - job.updatedAt < STALKER_RUNNING_JOB_STALE_MILLIS) {
- return false
- }
if (job.state in setOf("QUEUED", "RUNNING", "PARTIAL", "STALE", "FAILED_RETRYABLE")) return true
return ContentCachePolicy.shouldRefresh(job.lastSuccessAt, ContentCachePolicy.CATALOG_TTL_MILLIS)
}
@@ -1532,9 +1538,10 @@ class SyncManager @Inject constructor(
return withStalkerSummaryLock(providerId, section, providerMaxConnections) lock@{
val playbackDelayMillis = StalkerTrafficCoordinator.deferCatalogFetchMillis(providerId)
if (playbackDelayMillis > 0L) {
+ Log.i(TAG, "Deferring Stalker catalog work for provider $providerId because playback is active.")
scheduleStalkerIndexSync(
providerId = providerId,
- section = section,
+ section = null,
force = force,
initialDelaySeconds = ((playbackDelayMillis + 999L) / 1000L).coerceAtLeast(1L)
)
@@ -1551,48 +1558,57 @@ class SyncManager @Inject constructor(
.copy(password = credentialCrypto.decryptIfNeeded(providerEntity.password))
.toDomain()
val api = createStalkerSyncProvider(provider)
- val sections = when (section) {
- ContentType.MOVIE -> listOf(ContentType.MOVIE)
- ContentType.SERIES -> listOf(ContentType.SERIES)
- else -> listOf(ContentType.MOVIE, ContentType.SERIES)
+ val decision = chooseNextStalkerCatalogSection(
+ provider = provider,
+ api = api,
+ requestedSection = section,
+ force = force,
+ now = System.currentTimeMillis()
+ )
+ val contentType = decision.contentType
+ if (contentType == null) {
+ Log.i(TAG, "Stalker catalog worker skipped provider $providerId: ${decision.reason}")
+ if (decision.retryDelaySeconds > 0L) {
+ scheduleStalkerIndexSync(
+ providerId = providerId,
+ section = null,
+ force = false,
+ initialDelaySeconds = decision.retryDelaySeconds
+ )
+ } else {
+ scheduleStalkerEpgIfCatalogIdle(provider)
+ }
+ return@lock com.streamvault.domain.model.Result.success(Unit)
}
+ Log.i(TAG, "Stalker catalog worker selected ${contentType.name} for provider $providerId: ${decision.reason}")
val warnings = mutableListOf<String>()
val failures = mutableListOf<Throwable>()
var sawRetryableFailure = false
val categoryLimit = maxCategoriesPerSection?.coerceAtLeast(1) ?: STALKER_INDEX_CATEGORY_SLICE_SIZE
- sections.forEach { contentType ->
- val job = xtreamIndexJobDao.get(providerId, contentType.name)
- if (!force && !shouldRunXtreamSummaryIndex(job)) {
- return@forEach
- }
- if (job?.state == "RUNNING" && System.currentTimeMillis() - job.updatedAt < STALKER_RUNNING_JOB_STALE_MILLIS) {
- return@forEach
- }
- val failure = runCatching {
- processStalkerSummaryIndexSection(
- provider = provider,
- api = api,
- contentType = contentType,
- maxCategories = categoryLimit,
- onProgress = onProgress
- )
- }.exceptionOrNull()
- if (failure != null) {
- val failedAt = System.currentTimeMillis()
- val state = stalkerIndexFailureState(failure)
- upsertXtreamIndexJob(
- providerId = providerId,
- section = contentType.name,
- state = state,
- now = failedAt,
- lastAttemptAt = failedAt,
- lastError = sanitizeThrowableMessage(failure)
- )
- failures += failure
- sawRetryableFailure = sawRetryableFailure || state != "FAILED_PERMANENT"
- warnings += "${contentType.name.lowercase().replaceFirstChar { it.titlecase() }} indexing failed: ${sanitizeThrowableMessage(failure)}"
- }
+ val failure = runCatching {
+ processStalkerSummaryIndexSection(
+ provider = provider,
+ api = api,
+ contentType = contentType,
+ maxCategories = categoryLimit,
+ onProgress = onProgress
+ )
+ }.exceptionOrNull()
+ if (failure != null) {
+ val failedAt = System.currentTimeMillis()
+ val state = stalkerIndexFailureState(failure)
+ upsertXtreamIndexJob(
+ providerId = providerId,
+ section = contentType.name,
+ state = state,
+ now = failedAt,
+ lastAttemptAt = failedAt,
+ lastError = sanitizeThrowableMessage(failure)
+ )
+ failures += failure
+ sawRetryableFailure = sawRetryableFailure || state != "FAILED_PERMANENT"
+ warnings += "${contentType.name.lowercase().replaceFirstChar { it.titlecase() }} indexing failed: ${sanitizeThrowableMessage(failure)}"
}
if (warnings.isNotEmpty()) {
@@ -1601,11 +1617,213 @@ class SyncManager @Inject constructor(
val exception = if (sawRetryableFailure) IOException(message, cause) else IllegalStateException(message, cause)
com.streamvault.domain.model.Result.error(warnings.first(), exception)
} else {
+ scheduleNextStalkerCatalogStep(provider, api)
+ scheduleStalkerEpgIfCatalogIdle(provider)
com.streamvault.domain.model.Result.success(Unit)
}
}
}
+ private data class StalkerCatalogDecision(
+ val contentType: ContentType?,
+ val retryDelaySeconds: Long = 0L,
+ val reason: String
+ )
+
+ private data class StalkerCatalogSectionState(
+ val contentType: ContentType,
+ val runnable: Boolean,
+ val retryDelaySeconds: Long,
+ val pending: Boolean,
+ val jobState: String?
+ )
+
+ private suspend fun chooseNextStalkerCatalogSection(
+ provider: Provider,
+ api: StalkerProvider,
+ requestedSection: ContentType?,
+ force: Boolean,
+ now: Long
+ ): StalkerCatalogDecision {
+ val movie = stalkerCatalogSectionState(provider, api, ContentType.MOVIE, force, now)
+ if (movie.runnable) {
+ return StalkerCatalogDecision(ContentType.MOVIE, reason = "movies are runnable (${movie.jobState ?: "no job"})")
+ }
+
+ val series = stalkerCatalogSectionState(provider, api, ContentType.SERIES, force, now)
+ if (series.runnable) {
+ val reason = if (movie.pending && movie.retryDelaySeconds > 0L) {
+ "movies are waiting ${movie.retryDelaySeconds}s for retry; series is runnable"
+ } else {
+ "movies are complete or terminal; series is runnable (${series.jobState ?: "no job"})"
+ }
+ return StalkerCatalogDecision(ContentType.SERIES, reason = reason)
+ }
+
+ val retryDelaySeconds = listOf(movie.retryDelaySeconds, series.retryDelaySeconds)
+ .filter { it > 0L }
+ .minOrNull()
+ ?: 0L
+ return StalkerCatalogDecision(
+ contentType = null,
+ retryDelaySeconds = retryDelaySeconds,
+ reason = when {
+ retryDelaySeconds > 0L -> "catalog is waiting ${retryDelaySeconds}s for retry"
+ movie.pending || series.pending -> "catalog has no attemptable work"
+ requestedSection == ContentType.MOVIE -> "requested movie section is not pending"
+ requestedSection == ContentType.SERIES -> "requested series section is not pending"
+ else -> "catalog is idle"
+ }
+ )
+ }
+
+ private suspend fun stalkerCatalogSectionState(
+ provider: Provider,
+ api: StalkerProvider,
+ contentType: ContentType,
+ force: Boolean,
+ now: Long
+ ): StalkerCatalogSectionState {
+ val job = xtreamIndexJobDao.get(provider.id, contentType.name)
+ if (!force && !shouldRunXtreamSummaryIndex(job)) {
+ return StalkerCatalogSectionState(
+ contentType = contentType,
+ runnable = false,
+ retryDelaySeconds = 0L,
+ pending = false,
+ jobState = job?.state
+ )
+ }
+
+ val categories = categoryDao.getByProviderAndTypeSync(provider.id, contentType.name)
+ val visibleCategories = visibleStalkerIndexCategories(
+ contentType,
+ allVisibleStalkerIndexCategories(provider.id, contentType, categories),
+ api
+ )
+ if (visibleCategories.isEmpty()) {
+ return StalkerCatalogSectionState(
+ contentType = contentType,
+ runnable = true,
+ retryDelaySeconds = 0L,
+ pending = true,
+ jobState = job?.state
+ )
+ }
+
+ val hydrations = visibleCategories.map { category ->
+ getStalkerHydrationSnapshot(provider.id, contentType, category.categoryId)
+ }
+ val hasAttemptableWork = hydrations.any { hydration -> canAttemptStalkerCategory(hydration, now) }
+ val retryDelaySeconds = nextRetryDelaySeconds(hydrations, now)
+ val hasUnresolvedWork = hydrations.any { hydration ->
+ hydration == null ||
+ (!hydration.isComplete && !hydration.isTerminalFailure && hydration.retryBudgetRemaining > 0)
+ }
+ val needsStateReconciliation = job?.state in setOf("QUEUED", "RUNNING", "STALE", "FAILED_RETRYABLE") &&
+ !hasUnresolvedWork
+ return StalkerCatalogSectionState(
+ contentType = contentType,
+ runnable = hasAttemptableWork || needsStateReconciliation,
+ retryDelaySeconds = retryDelaySeconds,
+ pending = hasUnresolvedWork || needsStateReconciliation,
+ jobState = job?.state
+ )
+ }
+
+ private suspend fun scheduleNextStalkerCatalogStep(provider: Provider, api: StalkerProvider) {
+ val decision = chooseNextStalkerCatalogSection(
+ provider = provider,
+ api = api,
+ requestedSection = null,
+ force = false,
+ now = System.currentTimeMillis()
+ )
+ when {
+ decision.contentType != null -> {
+ Log.i(TAG, "Scheduling next Stalker catalog step for provider ${provider.id}: ${decision.contentType.name}")
+ scheduleStalkerIndexSync(provider.id, section = null, force = false)
+ }
+ decision.retryDelaySeconds > 0L -> {
+ Log.i(TAG, "Scheduling Stalker catalog retry for provider ${provider.id} in ${decision.retryDelaySeconds}s")
+ scheduleStalkerIndexSync(
+ providerId = provider.id,
+ section = null,
+ force = false,
+ initialDelaySeconds = decision.retryDelaySeconds
+ )
+ }
+ }
+ }
+
+ private suspend fun scheduleStalkerEpgIfCatalogIdle(provider: Provider) {
+ if (provider.type != ProviderType.STALKER_PORTAL || provider.epgSyncMode == ProviderEpgSyncMode.SKIP) return
+ if (!hasPendingStalkerCatalogIndex(provider.id)) {
+ Log.i(TAG, "Scheduling Stalker EPG for provider ${provider.id}: catalog is idle.")
+ scheduleBackgroundEpgSync(provider.id)
+ } else {
+ Log.i(TAG, "Deferring Stalker EPG for provider ${provider.id}: catalog indexing is still pending.")
+ }
+ }
+
+ private suspend fun hasPendingStalkerCatalogIndex(providerId: Long): Boolean {
+ val now = System.currentTimeMillis()
+ return listOf(ContentType.MOVIE, ContentType.SERIES).any { contentType ->
+ when (xtreamIndexJobDao.get(providerId, contentType.name)?.state) {
+ "QUEUED",
+ "RUNNING",
+ "STALE",
+ "FAILED_RETRYABLE" -> true
+ "PARTIAL" -> hasRetryableStalkerCategoryWork(providerId, contentType, now)
+ else -> false
+ }
+ }
+ }
+
+ private suspend fun hasRetryableStalkerCategoryWork(
+ providerId: Long,
+ contentType: ContentType,
+ now: Long
+ ): Boolean =
+ categoryDao.getByProviderAndTypeSync(providerId, contentType.name).any { category ->
+ val hydration = getStalkerHydrationSnapshot(providerId, contentType, category.categoryId)
+ hydration == null ||
+ (!hydration.isComplete &&
+ !hydration.isTerminalFailure &&
+ hydration.retryBudgetRemaining > 0)
+ }
+
+ private fun scheduleStalkerIndexContinuation(
+ provider: Provider,
+ section: ContentType,
+ force: Boolean = false,
+ initialDelaySeconds: Long = 0L
+ ) {
+ scheduleStalkerIndexSync(
+ providerId = provider.id,
+ section = null,
+ force = force,
+ initialDelaySeconds = initialDelaySeconds
+ )
+ }
+
+ private fun nextRetryDelaySeconds(
+ hydrations: Iterable<StalkerHydrationSnapshot?>,
+ now: Long
+ ): Long {
+ val retryAt = hydrations
+ .filterNotNull()
+ .filter { hydration ->
+ !hydration.isComplete &&
+ !hydration.isTerminalFailure &&
+ hydration.retryBudgetRemaining > 0 &&
+ hydration.retryAfterMs > now
+ }
+ .minOfOrNull { it.retryAfterMs }
+ ?: return 0L
+ return ((retryAt - now + 999L) / 1000L).coerceAtLeast(1L)
+ }
+
private suspend fun processStalkerSummaryIndexSection(
provider: Provider,
api: StalkerProvider,
@@ -1618,7 +1836,11 @@ class SyncManager @Inject constructor(
}
val now = System.currentTimeMillis()
val categories = categoryDao.getByProviderAndTypeSync(provider.id, contentType.name)
- val visibleCategories = visibleStalkerIndexCategories(provider.id, contentType, categories, api)
+ val allVisibleCategories = allVisibleStalkerIndexCategories(provider.id, contentType, categories)
+ val visibleCategories = visibleStalkerIndexCategories(contentType, allVisibleCategories, api)
+ val wildcardCategory = allVisibleCategories.firstOrNull { category ->
+ api.isWildcardCategory(contentType, category.categoryId)
+ }
if (visibleCategories.isEmpty()) {
val deletedRows = xtreamContentIndexDao.pruneStaleLocalContentRows(provider.id, contentType.name)
val indexedRows = currentStalkerIndexedRowCount(provider.id, contentType)
@@ -1644,6 +1866,21 @@ class SyncManager @Inject constructor(
val initialJob = xtreamIndexJobDao.get(provider.id, contentType.name)
+ if (wildcardCategory != null && visibleCategories.size == 1 && visibleCategories.first().categoryId == wildcardCategory.categoryId) {
+ if (processStalkerWildcardIndexSection(
+ provider = provider,
+ api = api,
+ contentType = contentType,
+ wildcardCategory = wildcardCategory,
+ visibleCategories = allVisibleCategories,
+ maxPages = STALKER_WILDCARD_PAGE_SLICE_SIZE,
+ initialJob = initialJob,
+ onProgress = onProgress
+ )) {
+ return
+ }
+ }
+
val priorityCategoryId = initialJob?.priorityCategoryId
val hydrationByCategory = visibleCategories.associate { category ->
category.categoryId to getStalkerHydrationSnapshot(provider.id, contentType, category.categoryId)
@@ -1709,6 +1946,9 @@ class SyncManager @Inject constructor(
var clearPriority = false
var skippedMalformedRows = initialJob?.skippedMalformedRows ?: 0
+ var pagesCommitted = 0
+ var rowsCommitted = 0
+ val sectionStartedAt = System.currentTimeMillis()
val runtimeProfile = CatalogSyncRuntimeProfile.from(applicationContext)
val parallelFetchLimit = stalkerCategoryFetchConcurrencyLimit(
provider = provider,
@@ -1718,6 +1958,7 @@ class SyncManager @Inject constructor(
val runDeadlineAt = System.currentTimeMillis() + STALKER_MAX_SECTION_RUN_MILLIS
val pendingQueue = ArrayDeque(pending)
var forceSequential = parallelFetchLimit <= 1
+ val retriedImmediately = mutableSetOf<Long>()
while (pendingQueue.isNotEmpty() && System.currentTimeMillis() < runDeadlineAt) {
if (StalkerTrafficCoordinator.shouldDeferCatalogFetch(provider.id)) {
break
@@ -1795,6 +2036,8 @@ class SyncManager @Inject constructor(
if (anomaly != null) {
val indexedAt = System.currentTimeMillis()
skippedMalformedRows += result.data.items.size
+ val shouldRetryImmediately = category.categoryId !in retriedImmediately &&
+ ((hydration?.failureCount ?: 0) == 0)
markStalkerAttemptFailed(
providerId = provider.id,
contentType = contentType,
@@ -1806,6 +2049,10 @@ class SyncManager @Inject constructor(
retryable = true,
pageFingerprint = pageFingerprint
)
+ if (shouldRetryImmediately) {
+ retriedImmediately += category.categoryId
+ pendingQueue.addLast(category)
+ }
upsertXtreamIndexJob(
providerId = provider.id,
section = contentType.name,
@@ -1836,6 +2083,9 @@ class SyncManager @Inject constructor(
if (retryable) {
windowRetryableFailures += 1
}
+ val shouldRetryImmediately = retryable &&
+ category.categoryId !in retriedImmediately &&
+ ((hydration?.failureCount ?: 0) == 0)
markStalkerAttemptFailed(
providerId = provider.id,
contentType = contentType,
@@ -1847,6 +2097,10 @@ class SyncManager @Inject constructor(
retryable = retryable,
pageFingerprint = hydration?.lastPageFingerprint
)
+ if (shouldRetryImmediately) {
+ retriedImmediately += category.categoryId
+ pendingQueue.addLast(category)
+ }
if (!retryable) {
throw IllegalStateException(result.message, result.exception)
}
@@ -1886,9 +2140,11 @@ class SyncManager @Inject constructor(
restoreMovieWatchProgressPending = true
}
for (page in successfulPages) {
+ pagesCommitted += 1
+ rowsCommitted += page.items.size
val pageComplete = page.isComplete ||
(page.items.isEmpty() && page.totalPages in 1..page.requestedPage)
- val categoryCount = currentStalkerCategoryCount(provider.id, contentType, page.category.categoryId)
+ val categoryCount = (page.hydration?.itemCount ?: 0) + page.items.size
markStalkerAttemptSucceeded(
providerId = provider.id,
contentType = contentType,
@@ -1925,6 +2181,7 @@ class SyncManager @Inject constructor(
val hasMoreCategories = refreshedHydration.values.any { hydration ->
canAttemptStalkerCategory(hydration, finishedAt)
}
+ val retryDelaySeconds = nextRetryDelaySeconds(refreshedHydration.values, finishedAt)
val indexedRows = currentStalkerIndexedRowCount(provider.id, contentType)
val pruneSuppressed = refreshedHydration.values.any { hydration ->
hydration?.hasPruneSuppressionRisk == true
@@ -1958,8 +2215,22 @@ class SyncManager @Inject constructor(
lastError = refreshedHydration.values.firstOrNull { it?.lastStatus == "ERROR" }?.lastError
)
updateStalkerSummaryMetadata(provider.id, contentType, indexedRows, finalState, finishedAt)
- if (hasMoreCategories) {
- scheduleStalkerIndexSync(provider.id, contentType, force = false)
+ Log.i(
+ TAG,
+ "Stalker ${contentType.name} indexing finished for provider ${provider.id}: state=$finalState completed=$completedCategories failed=$failedCategories rows=$indexedRows committedPages=$pagesCommitted committedRows=$rowsCommitted throughput=${stalkerThroughputSummary(sectionStartedAt, pagesCommitted, rowsCommitted)} retryDelay=${retryDelaySeconds}s"
+ )
+ when {
+ hasMoreCategories -> scheduleStalkerIndexContinuation(provider, contentType, force = false)
+ finalState == "PARTIAL" -> {
+ if (retryDelaySeconds > 0L) {
+ scheduleStalkerIndexContinuation(
+ provider = provider,
+ section = contentType,
+ force = false,
+ initialDelaySeconds = retryDelaySeconds
+ )
+ }
+ }
}
} finally {
if (contentType == ContentType.MOVIE && restoreMovieWatchProgressPending) {
@@ -1975,7 +2246,7 @@ class SyncManager @Inject constructor(
): Int {
val runtimeLimit = runtimeProfile.maxCategoryConcurrency.coerceAtLeast(1)
val providerLimit = provider.maxConnections.coerceAtLeast(1)
- val effectiveLimit = maxOf(runtimeLimit, providerLimit)
+ val effectiveLimit = minOf(runtimeLimit, providerLimit)
return minOf(
maxCategories.coerceAtLeast(1),
effectiveLimit,
@@ -1983,6 +2254,17 @@ class SyncManager @Inject constructor(
).coerceAtLeast(1)
}
+ private fun stalkerThroughputSummary(
+ startedAt: Long,
+ pages: Int,
+ rows: Int
+ ): String {
+ val elapsedSeconds = ((System.currentTimeMillis() - startedAt).coerceAtLeast(1L)) / 1000.0
+ val pagesPerSecond = pages / elapsedSeconds
+ val rowsPerSecond = rows / elapsedSeconds
+ return "%.2f pages/s, %.2f rows/s".format(java.util.Locale.US, pagesPerSecond, rowsPerSecond)
+ }
+
private suspend fun processStalkerWildcardIndexSection(
provider: Provider,
api: StalkerProvider,
@@ -2020,8 +2302,11 @@ class SyncManager @Inject constructor(
var skippedMalformedRows = initialJob?.skippedMalformedRows ?: 0
val seenPageFingerprints = mutableSetOf<String>()
var pagesProcessed = 0
+ var rowsCommitted = 0
var lastError: String? = null
var restoreMovieWatchProgressPending = false
+ var indexedRowsEstimate = currentStalkerIndexedRowCount(provider.id, contentType)
+ val sectionStartedAt = System.currentTimeMillis()
try {
while (pagesProcessed < maxPages) {
@@ -2105,6 +2390,8 @@ class SyncManager @Inject constructor(
if (contentType == ContentType.MOVIE && visibleItems.isNotEmpty()) {
restoreMovieWatchProgressPending = true
}
+ indexedRowsEstimate += visibleItems.size
+ rowsCommitted += visibleItems.size
val pageComplete = result.data.isComplete ||
(result.data.items.isEmpty() && result.data.totalPages in 1..nextPage)
@@ -2115,7 +2402,7 @@ class SyncManager @Inject constructor(
hydration = currentHydration,
attemptedPage = nextPage,
now = indexedAt,
- itemCount = currentStalkerIndexedRowCount(provider.id, contentType),
+ itemCount = indexedRowsEstimate,
totalPages = result.data.totalPages,
pageSize = result.data.pageSize,
pageComplete = pageComplete,
@@ -2178,8 +2465,23 @@ class SyncManager @Inject constructor(
lastError = lastError ?: refreshedHydration?.lastError
)
updateStalkerSummaryMetadata(provider.id, contentType, indexedRows, finalState, finishedAt)
- if (hasMorePages) {
- scheduleStalkerIndexSync(provider.id, contentType, force = false)
+ Log.i(
+ TAG,
+ "Stalker wildcard ${contentType.name} indexing finished for provider ${provider.id}: state=$finalState pages=$pagesProcessed rows=$rowsCommitted totalRows=$indexedRows throughput=${stalkerThroughputSummary(sectionStartedAt, pagesProcessed, rowsCommitted)}"
+ )
+ when {
+ hasMorePages -> scheduleStalkerIndexContinuation(provider, contentType, force = false)
+ finalState == "PARTIAL" -> {
+ val delaySeconds = nextRetryDelaySeconds(listOf(refreshedHydration), finishedAt)
+ if (delaySeconds > 0L) {
+ scheduleStalkerIndexContinuation(
+ provider = provider,
+ section = contentType,
+ force = false,
+ initialDelaySeconds = delaySeconds
+ )
+ }
+ }
}
return true
} finally {
@@ -2409,7 +2711,7 @@ class SyncManager @Inject constructor(
remainingBudget <= 0 -> "FAILED_BUDGET_EXHAUSTED"
else -> "FAILED_RETRYABLE"
}
- val retryAfterMs = if (nextStatus == "FAILED_RETRYABLE") {
+ val retryAfterMs = if (nextStatus == "FAILED_RETRYABLE" && priorFailures > 0) {
now + STALKER_CATEGORY_RETRY_COOLDOWN_MILLIS * (priorFailures + 1).coerceAtLeast(1)
} else {
0L
@@ -2663,14 +2965,21 @@ class SyncManager @Inject constructor(
else -> Result.error("Unsupported Stalker wildcard summary page section: $contentType")
}
- private suspend fun visibleStalkerIndexCategories(
+ private suspend fun allVisibleStalkerIndexCategories(
providerId: Long,
+ contentType: ContentType,
+ categories: List<CategoryEntity>
+ ): List<CategoryEntity> {
+ val hiddenCategoryIds = preferencesRepository.getHiddenCategoryIds(providerId, contentType).first()
+ return categories.filterNot { category -> category.categoryId in hiddenCategoryIds }
+ }
+
+ private suspend fun visibleStalkerIndexCategories(
contentType: ContentType,
categories: List<CategoryEntity>,
api: StalkerProvider
): List<CategoryEntity> {
- val hiddenCategoryIds = preferencesRepository.getHiddenCategoryIds(providerId, contentType).first()
- val visible = categories.filterNot { category -> category.categoryId in hiddenCategoryIds }
+ val visible = categories
if (visible.isEmpty()) return emptyList()
val normalCategories = visible.filterNot { category -> api.isWildcardCategory(contentType, category.categoryId) }
return if (normalCategories.isNotEmpty()) normalCategories else visible
@@ -3555,6 +3864,8 @@ class SyncManager @Inject constructor(
var metadata = syncMetadataRepository.getMetadata(provider.id) ?: SyncMetadata(provider.id)
val now = System.currentTimeMillis()
+ var queuedMovieIndex = false
+ var queuedSeriesIndex = false
if (force || ContentCachePolicy.shouldRefresh(metadata.lastLiveSuccess, ContentCachePolicy.CATALOG_TTL_MILLIS, now)) {
upsertXtreamIndexJob(
@@ -3638,7 +3949,7 @@ class SyncManager @Inject constructor(
movieCatalogStale = true
)
syncMetadataRepository.updateMetadata(metadata)
- scheduleStalkerIndexSync(provider.id, ContentType.MOVIE, force = force)
+ queuedMovieIndex = true
}
if (force || ContentCachePolicy.shouldRefresh(metadata.lastSeriesSuccess, ContentCachePolicy.CATALOG_TTL_MILLIS, now)) {
@@ -3676,17 +3987,29 @@ class SyncManager @Inject constructor(
seriesCount = seriesDao.getCount(provider.id).first()
)
syncMetadataRepository.updateMetadata(metadata)
- scheduleStalkerIndexSync(provider.id, ContentType.SERIES, force = force)
+ queuedSeriesIndex = true
}
- if (shouldSyncEpgUpfront(provider)) {
- warnings += syncProviderEpg(
- provider = provider,
- metadata = metadata,
+ if (provider.epgSyncMode != ProviderEpgSyncMode.SKIP) {
+ upsertXtreamIndexJob(
+ providerId = provider.id,
+ section = "EPG",
+ state = "QUEUED",
now = now,
- force = force,
- onProgress = onProgress
- ).warnings
+ totalCategories = 1,
+ completedCategories = 0,
+ nextCategoryIndex = 0,
+ failedCategories = 0,
+ lastAttemptAt = now,
+ lastError = null
+ )
+ }
+
+ when {
+ queuedMovieIndex && queuedSeriesIndex -> scheduleStalkerIndexSync(provider.id, force = force)
+ queuedMovieIndex -> scheduleStalkerIndexContinuation(provider, ContentType.MOVIE, force = force)
+ queuedSeriesIndex -> scheduleStalkerIndexContinuation(provider, ContentType.SERIES, force = force)
+ else -> scheduleStalkerEpgIfCatalogIdle(provider)
}
return if (warnings.isEmpty()) SyncOutcome() else SyncOutcome(partial = true, warnings = warnings)
@@ -4459,7 +4782,7 @@ class SyncManager @Inject constructor(
movieCatalogStale = true
)
syncMetadataRepository.updateMetadata(metadata)
- scheduleStalkerIndexSync(provider.id, ContentType.MOVIE, force = true)
+ scheduleStalkerIndexContinuation(provider, ContentType.MOVIE, force = true)
}
}
return if (sectionWarnings.isEmpty()) SyncOutcome() else SyncOutcome(partial = true, warnings = sectionWarnings)
@@ -4543,7 +4866,7 @@ class SyncManager @Inject constructor(
seriesCount = seriesDao.getCount(provider.id).first()
)
syncMetadataRepository.updateMetadata(metadata)
- scheduleStalkerIndexSync(provider.id, ContentType.SERIES, force = true)
+ scheduleStalkerIndexContinuation(provider, ContentType.SERIES, force = true)
}
ProviderType.M3U -> {
throw IllegalStateException("Series retry is unavailable for this provider")
diff --git a/data/src/test/java/com/streamvault/data/remote/stalker/StalkerTrafficCoordinatorTest.kt b/data/src/test/java/com/streamvault/data/remote/stalker/StalkerTrafficCoordinatorTest.kt
index 7e95be88..1dddc4d6 100644
--- a/data/src/test/java/com/streamvault/data/remote/stalker/StalkerTrafficCoordinatorTest.kt
+++ b/data/src/test/java/com/streamvault/data/remote/stalker/StalkerTrafficCoordinatorTest.kt
@@ -17,24 +17,32 @@ class StalkerTrafficCoordinatorTest {
}
@Test
- fun `deferCatalogFetchMillis stays deferred while playback is active beyond legacy window`() {
- StalkerTrafficCoordinator.notePlaybackStarted(providerId = 7L, now = 1_000L)
+ fun `deferCatalogFetchMillis stays deferred while playback is active`() {
+ StalkerTrafficCoordinator.notePlaybackStarted(providerId = 7L)
- val deferredAtTwoMinutes = StalkerTrafficCoordinator.deferCatalogFetchMillis(
- providerId = 7L,
- now = 121_000L
- )
+ val deferred = StalkerTrafficCoordinator.deferCatalogFetchMillis(providerId = 7L)
- assertThat(deferredAtTwoMinutes).isGreaterThan(0L)
+ assertThat(deferred).isGreaterThan(0L)
}
@Test
fun `deferCatalogFetchMillis clears immediately when playback stops`() {
- StalkerTrafficCoordinator.notePlaybackActivity(providerId = 7L, now = 1_000L)
- StalkerTrafficCoordinator.notePlaybackStarted(providerId = 7L, now = 2_000L)
+ StalkerTrafficCoordinator.notePlaybackStarted(providerId = 7L)
+ StalkerTrafficCoordinator.notePlaybackStopped(providerId = 7L)
- StalkerTrafficCoordinator.notePlaybackStopped(7L)
+ val deferred = StalkerTrafficCoordinator.deferCatalogFetchMillis(providerId = 7L)
- assertThat(StalkerTrafficCoordinator.deferCatalogFetchMillis(providerId = 7L, now = 2_001L)).isEqualTo(0L)
+ assertThat(deferred).isEqualTo(0L)
+ }
+
+ @Test
+ fun `deferCatalogFetchMillis tracks nested playback sessions for same provider`() {
+ StalkerTrafficCoordinator.notePlaybackStarted(providerId = 7L)
+ StalkerTrafficCoordinator.notePlaybackStarted(providerId = 7L)
+ StalkerTrafficCoordinator.notePlaybackStopped(providerId = 7L)
+
+ val deferred = StalkerTrafficCoordinator.deferCatalogFetchMillis(providerId = 7L)
+
+ assertThat(deferred).isGreaterThan(0L)
}
}
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 bce11b15..5474ca68 100644
--- a/data/src/test/java/com/streamvault/data/sync/SyncManagerTest.kt
+++ b/data/src/test/java/com/streamvault/data/sync/SyncManagerTest.kt
@@ -1429,7 +1429,7 @@ class SyncManagerTest {
}
@Test
- fun `processQueuedStalkerIndexJobs allows movie and series sections to overlap for same provider`() = runTest {
+ fun `processQueuedStalkerIndexJobs runs movies before series for same provider`() = runTest {
val providerEntity = sampleProvider(ProviderType.STALKER_PORTAL).copy(
serverUrl = "http://example.com",
username = "",
@@ -1477,22 +1477,28 @@ class SyncManagerTest {
)
)
)
- org.mockito.kotlin.whenever(xtreamIndexJobDao.get(1L, ContentType.MOVIE.name)).thenReturn(
- XtreamIndexJobEntity(
+ val indexJobs = mutableMapOf(
+ ContentType.MOVIE.name to XtreamIndexJobEntity(
providerId = 1L,
section = ContentType.MOVIE.name,
state = "QUEUED",
totalCategories = 1
- )
- )
- org.mockito.kotlin.whenever(xtreamIndexJobDao.get(1L, ContentType.SERIES.name)).thenReturn(
- XtreamIndexJobEntity(
+ ),
+ ContentType.SERIES.name to XtreamIndexJobEntity(
providerId = 1L,
section = ContentType.SERIES.name,
state = "QUEUED",
totalCategories = 1
)
)
+ org.mockito.kotlin.whenever(xtreamIndexJobDao.get(eq(1L), any())).thenAnswer { invocation ->
+ indexJobs[invocation.getArgument<String>(1)]
+ }
+ org.mockito.kotlin.whenever(xtreamIndexJobDao.upsert(any())).thenAnswer { invocation ->
+ val entity = invocation.getArgument<XtreamIndexJobEntity>(0)
+ indexJobs[entity.section] = entity
+ Unit
+ }
val movieHydrationByCategory = mutableMapOf<Long, MovieCategoryHydrationEntity>()
org.mockito.kotlin.whenever(movieCategoryHydrationDao.get(eq(1L), any())).thenAnswer { invocation ->
movieHydrationByCategory[invocation.getArgument<Long>(1)]
@@ -1573,13 +1579,15 @@ class SyncManagerTest {
)
}
+ advanceUntilIdle()
+ assertThat(seriesFetchStarted.isCompleted).isFalse()
+ releaseMovieFetch.complete(Unit)
+
+ val movieResult = movieJob.await()
withTimeout(1_000) {
seriesFetchStarted.await()
}
- releaseMovieFetch.complete(Unit)
-
val seriesResult = seriesJob.await()
- val movieResult = movieJob.await()
if (seriesResult is Result.Error) fail(seriesResult.exception?.stackTraceToString() ?: seriesResult.message)
if (movieResult is Result.Error) fail(movieResult.exception?.stackTraceToString() ?: movieResult.message)
@@ -1590,7 +1598,7 @@ class SyncManagerTest {
}
@Test
- fun `processQueuedStalkerIndexJobs serializes movie and series sections for one connection provider`() = runTest {
+ fun `processQueuedStalkerIndexJobs retries failed movie category before moving to series`() = runTest {
val providerEntity = sampleProvider(ProviderType.STALKER_PORTAL).copy(
serverUrl = "http://example.com",
username = "",
@@ -1638,22 +1646,395 @@ class SyncManagerTest {
)
)
)
+ val indexJobs = mutableMapOf(
+ ContentType.MOVIE.name to XtreamIndexJobEntity(
+ providerId = 1L,
+ section = ContentType.MOVIE.name,
+ state = "QUEUED",
+ totalCategories = 1
+ ),
+ ContentType.SERIES.name to XtreamIndexJobEntity(
+ providerId = 1L,
+ section = ContentType.SERIES.name,
+ state = "QUEUED",
+ totalCategories = 1
+ )
+ )
+ org.mockito.kotlin.whenever(xtreamIndexJobDao.get(eq(1L), any())).thenAnswer { invocation ->
+ indexJobs[invocation.getArgument<String>(1)]
+ }
+ org.mockito.kotlin.whenever(xtreamIndexJobDao.upsert(any())).thenAnswer { invocation ->
+ val entity = invocation.getArgument<XtreamIndexJobEntity>(0)
+ indexJobs[entity.section] = entity
+ Unit
+ }
+ val movieHydrationByCategory = mutableMapOf<Long, MovieCategoryHydrationEntity>()
+ org.mockito.kotlin.whenever(movieCategoryHydrationDao.get(eq(1L), any())).thenAnswer { invocation ->
+ movieHydrationByCategory[invocation.getArgument<Long>(1)]
+ }
+ org.mockito.kotlin.whenever(movieCategoryHydrationDao.upsert(any())).thenAnswer { invocation ->
+ val entity = invocation.getArgument<MovieCategoryHydrationEntity>(0)
+ movieHydrationByCategory[entity.categoryId] = entity
+ Unit
+ }
+ val seriesHydrationByCategory = mutableMapOf<Long, SeriesCategoryHydrationEntity>()
+ org.mockito.kotlin.whenever(seriesCategoryHydrationDao.get(eq(1L), any())).thenAnswer { invocation ->
+ seriesHydrationByCategory[invocation.getArgument<Long>(1)]
+ }
+ org.mockito.kotlin.whenever(seriesCategoryHydrationDao.upsert(any())).thenAnswer { invocation ->
+ val entity = invocation.getArgument<SeriesCategoryHydrationEntity>(0)
+ seriesHydrationByCategory[entity.categoryId] = entity
+ Unit
+ }
+ org.mockito.kotlin.whenever(movieDao.getByStreamIds(eq(1L), any())).thenReturn(emptyList())
+ org.mockito.kotlin.whenever(seriesDao.getBySeriesIds(eq(1L), any())).thenReturn(emptyList())
+
+ var movieAttempts = 0
+ org.mockito.kotlin.whenever(stalkerApiService.getVodStreamsPage(any(), any(), eq("5"), eq(1))).thenAnswer {
+ movieAttempts += 1
+ if (movieAttempts == 1) {
+ Result.error("temporary movie failure", java.io.IOException("temporary movie failure"))
+ } else {
+ Result.success(
+ StalkerPagedItems(
+ items = listOf(
+ StalkerItemRecord(
+ id = "100",
+ name = "Movie 100",
+ categoryId = "5",
+ cmd = "ffmpeg http://example.com/100.ts"
+ )
+ ),
+ page = 1,
+ totalPages = 1,
+ pageSize = 14
+ )
+ )
+ }
+ }
+ org.mockito.kotlin.whenever(stalkerApiService.getSeriesPage(any(), any(), eq("9"), eq(1))).thenReturn(
+ Result.success(
+ StalkerPagedItems(
+ items = listOf(
+ StalkerItemRecord(
+ id = "200",
+ name = "Series 200",
+ categoryId = "9",
+ cmd = "ffmpeg http://example.com/200.ts",
+ isSeries = true
+ )
+ ),
+ page = 1,
+ totalPages = 1,
+ pageSize = 14
+ )
+ )
+ )
+
+ val movieResult = manager.processQueuedStalkerIndexJobs(providerId = 1L, maxCategoriesPerSection = 1)
+ val seriesResult = manager.processQueuedStalkerIndexJobs(providerId = 1L, maxCategoriesPerSection = 1)
+
+ if (movieResult is Result.Error) fail(movieResult.exception?.stackTraceToString() ?: movieResult.message)
+ if (seriesResult is Result.Error) fail(seriesResult.exception?.stackTraceToString() ?: seriesResult.message)
+ assertThat(movieAttempts).isEqualTo(2)
+ verify(stalkerApiService).getSeriesPage(any(), any(), eq("9"), eq(1))
+ assertThat(indexJobs[ContentType.MOVIE.name]?.state).isEqualTo("SUCCESS")
+ assertThat(indexJobs[ContentType.SERIES.name]?.state).isEqualTo("SUCCESS")
+ }
+
+ @Test
+ fun `processQueuedStalkerIndexJobs commits first movie category before fetching next category for one connection provider`() = runTest {
+ val providerEntity = sampleProvider(ProviderType.STALKER_PORTAL).copy(
+ serverUrl = "http://example.com",
+ username = "",
+ password = "",
+ stalkerMacAddress = "00:11:22:33:44:55",
+ epgSyncMode = ProviderEpgSyncMode.SKIP,
+ maxConnections = 1
+ )
+ val actionCategoryId = stalkerSyntheticCategoryId(providerEntity.id, ContentType.MOVIE, "5")
+ val dramaCategoryId = stalkerSyntheticCategoryId(providerEntity.id, ContentType.MOVIE, "6")
+ val manager = buildManager(providerType = ProviderType.STALKER_PORTAL, providerEntity = providerEntity)
+
+ org.mockito.kotlin.whenever(stalkerApiService.authenticate(any())).thenReturn(
+ Result.success(
+ StalkerSession(
+ loadUrl = "http://example.com/stalker_portal/server/load.php",
+ portalReferer = "http://example.com/stalker_portal/c/",
+ token = "token"
+ ) to StalkerProviderProfile(accountName = "Stalker")
+ )
+ )
+ org.mockito.kotlin.whenever(stalkerApiService.getVodCategories(any(), any())).thenReturn(
+ Result.success(
+ listOf(
+ StalkerCategoryRecord(id = "5", name = "Action"),
+ StalkerCategoryRecord(id = "6", name = "Drama")
+ )
+ )
+ )
+ org.mockito.kotlin.whenever(categoryDao.getByProviderAndTypeSync(1L, ContentType.MOVIE.name)).thenReturn(
+ listOf(
+ CategoryEntity(
+ categoryId = actionCategoryId,
+ name = "Action",
+ type = ContentType.MOVIE,
+ providerId = 1L
+ ),
+ CategoryEntity(
+ categoryId = dramaCategoryId,
+ name = "Drama",
+ type = ContentType.MOVIE,
+ providerId = 1L
+ )
+ )
+ )
org.mockito.kotlin.whenever(xtreamIndexJobDao.get(1L, ContentType.MOVIE.name)).thenReturn(
XtreamIndexJobEntity(
providerId = 1L,
section = ContentType.MOVIE.name,
state = "QUEUED",
- totalCategories = 1
+ totalCategories = 2
)
)
- org.mockito.kotlin.whenever(xtreamIndexJobDao.get(1L, ContentType.SERIES.name)).thenReturn(
+ val hydrationByCategory = mutableMapOf<Long, MovieCategoryHydrationEntity>()
+ org.mockito.kotlin.whenever(movieCategoryHydrationDao.get(eq(1L), any())).thenAnswer { invocation ->
+ hydrationByCategory[invocation.getArgument<Long>(1)]
+ }
+ org.mockito.kotlin.whenever(movieCategoryHydrationDao.upsert(any())).thenAnswer { invocation ->
+ val entity = invocation.getArgument<MovieCategoryHydrationEntity>(0)
+ hydrationByCategory[entity.categoryId] = entity
+ Unit
+ }
+ org.mockito.kotlin.whenever(movieDao.getByStreamIds(eq(1L), any())).thenReturn(emptyList())
+
+ val firstCategoryCommitted = CompletableDeferred<Unit>()
+ org.mockito.kotlin.whenever(movieDao.insertAll(any())).doSuspendableAnswer {
+ firstCategoryCommitted.complete(Unit)
+ Unit
+ }
+ org.mockito.kotlin.whenever(stalkerApiService.getVodStreamsPage(any(), any(), eq("5"), eq(1))).thenReturn(
+ Result.success(
+ StalkerPagedItems(
+ items = listOf(
+ StalkerItemRecord(
+ id = "100",
+ name = "Movie 100",
+ categoryId = "5",
+ cmd = "ffmpeg http://example.com/100.ts"
+ )
+ ),
+ page = 1,
+ totalPages = 1,
+ pageSize = 14
+ )
+ )
+ )
+ org.mockito.kotlin.whenever(stalkerApiService.getVodStreamsPage(any(), any(), eq("6"), eq(1))).thenAnswer {
+ assertThat(firstCategoryCommitted.isCompleted).isTrue()
+ Result.success(
+ StalkerPagedItems(
+ items = listOf(
+ StalkerItemRecord(
+ id = "101",
+ name = "Movie 101",
+ categoryId = "6",
+ cmd = "ffmpeg http://example.com/101.ts"
+ )
+ ),
+ page = 1,
+ totalPages = 1,
+ pageSize = 14
+ )
+ )
+ }
+
+ val result = manager.processQueuedStalkerIndexJobs(
+ providerId = 1L,
+ section = ContentType.MOVIE,
+ maxCategoriesPerSection = 2
+ )
+
+ if (result is Result.Error) fail(result.exception?.stackTraceToString() ?: result.message)
+ assertThat(result.isSuccess).isTrue()
+ verify(stalkerApiService).getVodStreamsPage(any(), any(), eq("5"), eq(1))
+ verify(stalkerApiService).getVodStreamsPage(any(), any(), eq("6"), eq(1))
+ }
+
+ @Test
+ fun `processQueuedStalkerIndexJobs resumes fresh running Stalker movie job`() = runTest {
+ val providerEntity = sampleProvider(ProviderType.STALKER_PORTAL).copy(
+ serverUrl = "http://example.com",
+ username = "",
+ password = "",
+ stalkerMacAddress = "00:11:22:33:44:55",
+ epgSyncMode = ProviderEpgSyncMode.SKIP,
+ maxConnections = 1
+ )
+ val actionCategoryId = stalkerSyntheticCategoryId(providerEntity.id, ContentType.MOVIE, "5")
+ val manager = buildManager(providerType = ProviderType.STALKER_PORTAL, providerEntity = providerEntity)
+
+ org.mockito.kotlin.whenever(stalkerApiService.authenticate(any())).thenReturn(
+ Result.success(
+ StalkerSession(
+ loadUrl = "http://example.com/stalker_portal/server/load.php",
+ portalReferer = "http://example.com/stalker_portal/c/",
+ token = "token"
+ ) to StalkerProviderProfile(accountName = "Stalker")
+ )
+ )
+ org.mockito.kotlin.whenever(stalkerApiService.getVodCategories(any(), any())).thenReturn(
+ Result.success(listOf(StalkerCategoryRecord(id = "5", name = "Action")))
+ )
+ org.mockito.kotlin.whenever(categoryDao.getByProviderAndTypeSync(1L, ContentType.MOVIE.name)).thenReturn(
+ listOf(
+ CategoryEntity(
+ categoryId = actionCategoryId,
+ name = "Action",
+ type = ContentType.MOVIE,
+ providerId = 1L
+ )
+ )
+ )
+ org.mockito.kotlin.whenever(xtreamIndexJobDao.get(1L, ContentType.MOVIE.name)).thenReturn(
XtreamIndexJobEntity(
+ providerId = 1L,
+ section = ContentType.MOVIE.name,
+ state = "RUNNING",
+ totalCategories = 1,
+ updatedAt = System.currentTimeMillis()
+ )
+ )
+ val hydrationByCategory = mutableMapOf(
+ actionCategoryId to MovieCategoryHydrationEntity(
+ providerId = 1L,
+ categoryId = actionCategoryId,
+ lastHydratedAt = System.currentTimeMillis(),
+ itemCount = 56,
+ lastStatus = "RUNNING",
+ lastLoadedPage = 4,
+ lastAttemptedPage = 5,
+ lastSuccessfulPage = 4,
+ totalPages = 13,
+ isComplete = false,
+ pageSize = 14,
+ retryAfterMs = 0L,
+ failureCount = 0,
+ retryBudgetRemaining = 3
+ )
+ )
+ org.mockito.kotlin.whenever(movieCategoryHydrationDao.get(eq(1L), any())).thenAnswer { invocation ->
+ hydrationByCategory[invocation.getArgument<Long>(1)]
+ }
+ org.mockito.kotlin.whenever(movieCategoryHydrationDao.upsert(any())).thenAnswer { invocation ->
+ val entity = invocation.getArgument<MovieCategoryHydrationEntity>(0)
+ hydrationByCategory[entity.categoryId] = entity
+ Unit
+ }
+ org.mockito.kotlin.whenever(movieDao.getByStreamIds(eq(1L), any())).thenReturn(emptyList())
+ val requestedPages = mutableListOf<Int>()
+ org.mockito.kotlin.whenever(stalkerApiService.getVodStreamsPage(any(), any(), anyOrNull(), any())).thenAnswer { invocation ->
+ val requestedPage = invocation.getArgument<Int>(3)
+ requestedPages += requestedPage
+ Result.success(
+ StalkerPagedItems(
+ items = listOf(
+ StalkerItemRecord(
+ id = "105",
+ name = "Movie 105",
+ categoryId = "5",
+ cmd = "ffmpeg http://example.com/105.ts"
+ )
+ ),
+ page = requestedPage,
+ totalPages = 13,
+ pageSize = 14
+ )
+ )
+ }
+
+ val result = manager.processQueuedStalkerIndexJobs(
+ providerId = 1L,
+ section = ContentType.MOVIE,
+ maxCategoriesPerSection = 1
+ )
+
+ if (result is Result.Error) fail(result.exception?.stackTraceToString() ?: result.message)
+ assertThat(result.isSuccess).isTrue()
+ assertThat(requestedPages).contains(5)
+ }
+
+ @Test
+ fun `processQueuedStalkerIndexJobs serializes movie and series sections for one connection provider`() = runTest {
+ val providerEntity = sampleProvider(ProviderType.STALKER_PORTAL).copy(
+ serverUrl = "http://example.com",
+ username = "",
+ password = "",
+ stalkerMacAddress = "00:11:22:33:44:55",
+ epgSyncMode = ProviderEpgSyncMode.SKIP,
+ maxConnections = 1
+ )
+ val movieCategoryId = stalkerSyntheticCategoryId(providerEntity.id, ContentType.MOVIE, "5")
+ val seriesCategoryId = stalkerSyntheticCategoryId(providerEntity.id, ContentType.SERIES, "9")
+ val manager = buildManager(providerType = ProviderType.STALKER_PORTAL, providerEntity = providerEntity)
+
+ org.mockito.kotlin.whenever(stalkerApiService.authenticate(any())).thenReturn(
+ Result.success(
+ StalkerSession(
+ loadUrl = "http://example.com/stalker_portal/server/load.php",
+ portalReferer = "http://example.com/stalker_portal/c/",
+ token = "token"
+ ) to StalkerProviderProfile(accountName = "Stalker")
+ )
+ )
+ org.mockito.kotlin.whenever(stalkerApiService.getVodCategories(any(), any())).thenReturn(
+ Result.success(listOf(StalkerCategoryRecord(id = "5", name = "Action")))
+ )
+ org.mockito.kotlin.whenever(stalkerApiService.getSeriesCategories(any(), any())).thenReturn(
+ Result.success(listOf(StalkerCategoryRecord(id = "9", name = "Drama")))
+ )
+ org.mockito.kotlin.whenever(categoryDao.getByProviderAndTypeSync(1L, ContentType.MOVIE.name)).thenReturn(
+ listOf(
+ CategoryEntity(
+ categoryId = movieCategoryId,
+ name = "Action",
+ type = ContentType.MOVIE,
+ providerId = 1L
+ )
+ )
+ )
+ org.mockito.kotlin.whenever(categoryDao.getByProviderAndTypeSync(1L, ContentType.SERIES.name)).thenReturn(
+ listOf(
+ CategoryEntity(
+ categoryId = seriesCategoryId,
+ name = "Drama",
+ type = ContentType.SERIES,
+ providerId = 1L
+ )
+ )
+ )
+ val indexJobs = mutableMapOf(
+ ContentType.MOVIE.name to XtreamIndexJobEntity(
+ providerId = 1L,
+ section = ContentType.MOVIE.name,
+ state = "QUEUED",
+ totalCategories = 1
+ ),
+ ContentType.SERIES.name to XtreamIndexJobEntity(
providerId = 1L,
section = ContentType.SERIES.name,
state = "QUEUED",
totalCategories = 1
)
)
+ org.mockito.kotlin.whenever(xtreamIndexJobDao.get(eq(1L), any())).thenAnswer { invocation ->
+ indexJobs[invocation.getArgument<String>(1)]
+ }
+ org.mockito.kotlin.whenever(xtreamIndexJobDao.upsert(any())).thenAnswer { invocation ->
+ val entity = invocation.getArgument<XtreamIndexJobEntity>(0)
+ indexJobs[entity.section] = entity
+ Unit
+ }
val movieHydrationByCategory = mutableMapOf<Long, MovieCategoryHydrationEntity>()
org.mockito.kotlin.whenever(movieCategoryHydrationDao.get(eq(1L), any())).thenAnswer { invocation ->
movieHydrationByCategory[invocation.getArgument<Long>(1)]
@@ -1732,29 +2113,126 @@ class SyncManagerTest {
section = ContentType.SERIES,
maxCategoriesPerSection = 1
)
- }
-
- advanceUntilIdle()
- assertThat(seriesFetchStarted.isCompleted).isFalse()
-
- releaseMovieFetch.complete(Unit)
- withTimeout(1_000) {
- seriesFetchStarted.await()
- }
+ }
+
+ advanceUntilIdle()
+ assertThat(seriesFetchStarted.isCompleted).isFalse()
+
+ releaseMovieFetch.complete(Unit)
+ withTimeout(1_000) {
+ seriesFetchStarted.await()
+ }
+
+ val movieResult = movieJob.await()
+ val seriesResult = seriesJob.await()
+
+ if (movieResult is Result.Error) fail(movieResult.exception?.stackTraceToString() ?: movieResult.message)
+ if (seriesResult is Result.Error) fail(seriesResult.exception?.stackTraceToString() ?: seriesResult.message)
+ assertThat(movieResult.isSuccess).isTrue()
+ assertThat(seriesResult.isSuccess).isTrue()
+ verify(stalkerApiService).getVodStreamsPage(any(), any(), eq("5"), eq(1))
+ verify(stalkerApiService).getSeriesPage(any(), any(), eq("9"), eq(1))
+ }
+
+ @Test
+ fun `processQueuedStalkerIndexJobs falls back to non paged movie fetch when first page is empty`() = runTest {
+ val providerEntity = sampleProvider(ProviderType.STALKER_PORTAL).copy(
+ serverUrl = "http://example.com",
+ username = "",
+ password = "",
+ stalkerMacAddress = "00:11:22:33:44:55",
+ epgSyncMode = ProviderEpgSyncMode.SKIP,
+ maxConnections = 1
+ )
+ val movieCategoryId = stalkerSyntheticCategoryId(providerEntity.id, ContentType.MOVIE, "5")
+ val manager = buildManager(providerType = ProviderType.STALKER_PORTAL, providerEntity = providerEntity)
+
+ org.mockito.kotlin.whenever(stalkerApiService.authenticate(any())).thenReturn(
+ Result.success(
+ StalkerSession(
+ loadUrl = "http://example.com/stalker_portal/server/load.php",
+ portalReferer = "http://example.com/stalker_portal/c/",
+ token = "token"
+ ) to StalkerProviderProfile(accountName = "Stalker")
+ )
+ )
+ org.mockito.kotlin.whenever(stalkerApiService.getVodCategories(any(), any())).thenReturn(
+ Result.success(listOf(StalkerCategoryRecord(id = "5", name = "Action")))
+ )
+ org.mockito.kotlin.whenever(categoryDao.getByProviderAndTypeSync(1L, ContentType.MOVIE.name)).thenReturn(
+ listOf(
+ CategoryEntity(
+ categoryId = movieCategoryId,
+ name = "Action",
+ type = ContentType.MOVIE,
+ providerId = 1L
+ )
+ )
+ )
+ org.mockito.kotlin.whenever(xtreamIndexJobDao.get(1L, ContentType.MOVIE.name)).thenReturn(
+ XtreamIndexJobEntity(
+ providerId = 1L,
+ section = ContentType.MOVIE.name,
+ state = "QUEUED",
+ totalCategories = 1
+ )
+ )
+ val movieHydrationByCategory = mutableMapOf<Long, MovieCategoryHydrationEntity>()
+ org.mockito.kotlin.whenever(movieCategoryHydrationDao.get(eq(1L), any())).thenAnswer { invocation ->
+ movieHydrationByCategory[invocation.getArgument<Long>(1)]
+ }
+ org.mockito.kotlin.whenever(movieCategoryHydrationDao.upsert(any())).thenAnswer { invocation ->
+ val entity = invocation.getArgument<MovieCategoryHydrationEntity>(0)
+ movieHydrationByCategory[entity.categoryId] = entity
+ Unit
+ }
+ org.mockito.kotlin.whenever(movieDao.getByStreamIds(eq(1L), any())).thenReturn(emptyList())
+ org.mockito.kotlin.whenever(movieDao.getCount(1L)).thenReturn(flowOf(0), flowOf(1), flowOf(1))
+ org.mockito.kotlin.whenever(movieDao.getCountByCategory(1L, movieCategoryId)).thenReturn(flowOf(1))
+ org.mockito.kotlin.whenever(xtreamContentIndexDao.pruneStaleLocalContentRows(1L, ContentType.MOVIE.name)).thenReturn(0)
+
+ org.mockito.kotlin.whenever(stalkerApiService.getVodStreamsPage(any(), any(), eq("5"), eq(1))).thenReturn(
+ Result.success(
+ StalkerPagedItems(
+ items = emptyList(),
+ page = 1,
+ totalPages = 1,
+ pageSize = 14
+ )
+ )
+ )
+ org.mockito.kotlin.whenever(stalkerApiService.getVodStreams(any(), any(), eq("5"))).thenReturn(
+ Result.success(
+ listOf(
+ StalkerItemRecord(
+ id = "100",
+ name = "Movie 100",
+ categoryId = "5",
+ cmd = "ffmpeg http://example.com/100.ts"
+ )
+ )
+ )
+ )
- val movieResult = movieJob.await()
- val seriesResult = seriesJob.await()
+ val result = manager.processQueuedStalkerIndexJobs(
+ providerId = 1L,
+ section = ContentType.MOVIE,
+ maxCategoriesPerSection = 1
+ )
- if (movieResult is Result.Error) fail(movieResult.exception?.stackTraceToString() ?: movieResult.message)
- if (seriesResult is Result.Error) fail(seriesResult.exception?.stackTraceToString() ?: seriesResult.message)
- assertThat(movieResult.isSuccess).isTrue()
- assertThat(seriesResult.isSuccess).isTrue()
+ if (result is Result.Error) fail(result.exception?.stackTraceToString() ?: result.message)
+ assertThat(result.isSuccess).isTrue()
verify(stalkerApiService).getVodStreamsPage(any(), any(), eq("5"), eq(1))
- verify(stalkerApiService).getSeriesPage(any(), any(), eq("9"), eq(1))
+ verify(stalkerApiService).getVodStreams(any(), any(), eq("5"))
+ verify(movieDao).insertAll(check { movies ->
+ assertThat(movies).hasSize(1)
+ assertThat(movies.first().providerId).isEqualTo(1L)
+ assertThat(movies.first().streamId).isEqualTo(100L)
+ })
}
@Test
- fun `processQueuedStalkerIndexJobs falls back to non paged movie fetch when first page is empty`() = runTest {
+ fun `processQueuedStalkerIndexJobs uses wildcard movie indexing when wildcard category is the only visible category`() = runTest {
val providerEntity = sampleProvider(ProviderType.STALKER_PORTAL).copy(
serverUrl = "http://example.com",
username = "",
@@ -1763,7 +2241,7 @@ class SyncManagerTest {
epgSyncMode = ProviderEpgSyncMode.SKIP,
maxConnections = 1
)
- val movieCategoryId = stalkerSyntheticCategoryId(providerEntity.id, ContentType.MOVIE, "5")
+ val wildcardCategoryId = stalkerSyntheticCategoryId(providerEntity.id, ContentType.MOVIE, "*")
val manager = buildManager(providerType = ProviderType.STALKER_PORTAL, providerEntity = providerEntity)
org.mockito.kotlin.whenever(stalkerApiService.authenticate(any())).thenReturn(
@@ -1776,13 +2254,13 @@ class SyncManagerTest {
)
)
org.mockito.kotlin.whenever(stalkerApiService.getVodCategories(any(), any())).thenReturn(
- Result.success(listOf(StalkerCategoryRecord(id = "5", name = "Action")))
+ Result.success(listOf(StalkerCategoryRecord(id = "*", name = "All Movies")))
)
org.mockito.kotlin.whenever(categoryDao.getByProviderAndTypeSync(1L, ContentType.MOVIE.name)).thenReturn(
listOf(
CategoryEntity(
- categoryId = movieCategoryId,
- name = "Action",
+ categoryId = wildcardCategoryId,
+ name = "All Movies",
type = ContentType.MOVIE,
providerId = 1L
)
@@ -1807,31 +2285,24 @@ class SyncManagerTest {
}
org.mockito.kotlin.whenever(movieDao.getByStreamIds(eq(1L), any())).thenReturn(emptyList())
org.mockito.kotlin.whenever(movieDao.getCount(1L)).thenReturn(flowOf(0), flowOf(1), flowOf(1))
- org.mockito.kotlin.whenever(movieDao.getCountByCategory(1L, movieCategoryId)).thenReturn(flowOf(1))
org.mockito.kotlin.whenever(xtreamContentIndexDao.pruneStaleLocalContentRows(1L, ContentType.MOVIE.name)).thenReturn(0)
-
- org.mockito.kotlin.whenever(stalkerApiService.getVodStreamsPage(any(), any(), eq("5"), eq(1))).thenReturn(
+ org.mockito.kotlin.whenever(stalkerApiService.getVodStreamsPage(any(), any(), eq("*"), eq(1))).thenReturn(
Result.success(
StalkerPagedItems(
- items = emptyList(),
+ items = listOf(
+ StalkerItemRecord(
+ id = "100",
+ name = "Movie 100",
+ categoryId = "5",
+ cmd = "ffmpeg http://example.com/100.ts"
+ )
+ ),
page = 1,
totalPages = 1,
pageSize = 14
)
)
)
- org.mockito.kotlin.whenever(stalkerApiService.getVodStreams(any(), any(), eq("5"))).thenReturn(
- Result.success(
- listOf(
- StalkerItemRecord(
- id = "100",
- name = "Movie 100",
- categoryId = "5",
- cmd = "ffmpeg http://example.com/100.ts"
- )
- )
- )
- )
val result = manager.processQueuedStalkerIndexJobs(
providerId = 1L,
@@ -1841,8 +2312,7 @@ class SyncManagerTest {
if (result is Result.Error) fail(result.exception?.stackTraceToString() ?: result.message)
assertThat(result.isSuccess).isTrue()
- verify(stalkerApiService).getVodStreamsPage(any(), any(), eq("5"), eq(1))
- verify(stalkerApiService).getVodStreams(any(), any(), eq("5"))
+ verify(stalkerApiService).getVodStreamsPage(any(), any(), eq("*"), eq(1))
verify(movieDao).insertAll(check { movies ->
assertThat(movies).hasSize(1)
assertThat(movies.first().providerId).isEqualTo(1L)
@@ -1938,6 +2408,228 @@ class SyncManagerTest {
verify(stalkerApiService, org.mockito.kotlin.times(0)).getSeries(any(), any(), anyOrNull())
}
+ @Test
+ fun sync_stalker_persists_wildcard_vod_and_series_categories_when_portal_category_lists_are_empty() = runTest {
+ val providerEntity = sampleProvider(ProviderType.STALKER_PORTAL).copy(
+ serverUrl = "http://example.com",
+ username = "",
+ password = "",
+ stalkerMacAddress = "00:11:22:33:44:55",
+ epgSyncMode = ProviderEpgSyncMode.SKIP
+ )
+ val manager = buildManager(providerType = ProviderType.STALKER_PORTAL, providerEntity = providerEntity)
+
+ org.mockito.kotlin.whenever(stalkerApiService.authenticate(any())).thenReturn(
+ Result.success(
+ StalkerSession(
+ loadUrl = "http://example.com/stalker_portal/server/load.php",
+ portalReferer = "http://example.com/stalker_portal/c/",
+ token = "token"
+ ) to StalkerProviderProfile(accountName = "Stalker")
+ )
+ )
+ org.mockito.kotlin.whenever(stalkerApiService.getLiveCategories(any(), any())).thenReturn(
+ Result.success(listOf(StalkerCategoryRecord(id = "10", name = "News")))
+ )
+ stalkerApiService.stubStreamLiveStreams(
+ listOf(
+ StalkerItemRecord(
+ id = "100",
+ name = "News",
+ categoryId = "10",
+ cmd = "ffmpeg http://example.com/live.ts"
+ )
+ )
+ )
+ org.mockito.kotlin.whenever(stalkerApiService.getVodCategories(any(), any())).thenReturn(Result.success(emptyList()))
+ org.mockito.kotlin.whenever(stalkerApiService.getSeriesCategories(any(), any())).thenReturn(Result.success(emptyList()))
+
+ val result = manager.sync(providerId = 1L, force = false)
+
+ assertThat(result).isInstanceOf(Result.Success::class.java)
+ val categoryStagesCaptor = argumentCaptor<List<com.streamvault.data.local.entity.CategoryImportStageEntity>>()
+ verify(catalogSyncDao, atLeastOnce()).insertCategoryStages(categoryStagesCaptor.capture())
+ val stagedCategories = categoryStagesCaptor.allValues.flatten()
+ assertThat(stagedCategories.any {
+ it.type == ContentType.MOVIE && it.name == "All Movies" &&
+ it.categoryId == stalkerSyntheticCategoryId(1L, ContentType.MOVIE, "*")
+ }).isTrue()
+ assertThat(stagedCategories.any {
+ it.type == ContentType.SERIES && it.name == "All Series" &&
+ it.categoryId == stalkerSyntheticCategoryId(1L, ContentType.SERIES, "*")
+ }).isTrue()
+ val queuedJobCaptor = argumentCaptor<XtreamIndexJobEntity>()
+ verify(xtreamIndexJobDao, atLeastOnce()).upsert(queuedJobCaptor.capture())
+ assertThat(queuedJobCaptor.allValues.any {
+ it.section == ContentType.MOVIE.name && it.state == "QUEUED" && it.totalCategories == 1
+ }).isTrue()
+ assertThat(queuedJobCaptor.allValues.any {
+ it.section == ContentType.SERIES.name && it.state == "QUEUED" && it.totalCategories == 1
+ }).isTrue()
+ verify(stalkerApiService, org.mockito.kotlin.times(0)).getVodStreamsPage(any(), any(), anyOrNull(), any())
+ verify(stalkerApiService, org.mockito.kotlin.times(0)).getSeriesPage(any(), any(), anyOrNull(), any())
+ }
+
+ @Test
+ fun sync_stalker_queues_epg_until_after_background_catalog_indexing() = runTest {
+ val providerEntity = sampleProvider(ProviderType.STALKER_PORTAL).copy(
+ serverUrl = "http://example.com",
+ username = "",
+ password = "",
+ stalkerMacAddress = "00:11:22:33:44:55",
+ epgSyncMode = ProviderEpgSyncMode.UPFRONT
+ )
+ val manager = buildManager(providerType = ProviderType.STALKER_PORTAL, providerEntity = providerEntity)
+
+ org.mockito.kotlin.whenever(stalkerApiService.authenticate(any())).thenReturn(
+ Result.success(
+ StalkerSession(
+ loadUrl = "http://example.com/stalker_portal/server/load.php",
+ portalReferer = "http://example.com/stalker_portal/c/",
+ token = "token"
+ ) to StalkerProviderProfile(accountName = "Stalker")
+ )
+ )
+ org.mockito.kotlin.whenever(stalkerApiService.getLiveCategories(any(), any())).thenReturn(
+ Result.success(listOf(StalkerCategoryRecord(id = "10", name = "News")))
+ )
+ stalkerApiService.stubStreamLiveStreams(
+ listOf(
+ StalkerItemRecord(
+ id = "100",
+ name = "News",
+ categoryId = "10",
+ cmd = "ffmpeg http://example.com/live.ts"
+ )
+ )
+ )
+ org.mockito.kotlin.whenever(stalkerApiService.getVodCategories(any(), any())).thenReturn(
+ Result.success(listOf(StalkerCategoryRecord(id = "42", name = "Action")))
+ )
+ org.mockito.kotlin.whenever(stalkerApiService.getSeriesCategories(any(), any())).thenReturn(
+ Result.success(listOf(StalkerCategoryRecord(id = "77", name = "Drama")))
+ )
+
+ val result = manager.sync(providerId = 1L, force = false)
+
+ assertThat(result).isInstanceOf(Result.Success::class.java)
+ val queuedJobCaptor = argumentCaptor<XtreamIndexJobEntity>()
+ verify(xtreamIndexJobDao, atLeastOnce()).upsert(queuedJobCaptor.capture())
+ assertThat(queuedJobCaptor.allValues.any { job ->
+ job.providerId == 1L &&
+ job.section == "EPG" &&
+ job.state == "QUEUED"
+ }).isTrue()
+ verify(stalkerApiService, org.mockito.kotlin.times(0)).streamBulkEpg(any(), any(), any(), any())
+ verify(stalkerApiService, org.mockito.kotlin.times(0)).streamEpg(any(), any(), any(), any(), any())
+ verify(epgRepo, org.mockito.kotlin.times(0)).refreshEpg(any(), any())
+ }
+
+ @Test
+ fun syncEpg_stalker_defers_while_catalog_index_jobs_are_pending() = runTest {
+ val providerEntity = sampleProvider(ProviderType.STALKER_PORTAL).copy(
+ serverUrl = "http://example.com",
+ username = "",
+ password = "",
+ stalkerMacAddress = "00:11:22:33:44:55",
+ epgSyncMode = ProviderEpgSyncMode.UPFRONT
+ )
+ val manager = buildManager(providerType = ProviderType.STALKER_PORTAL, providerEntity = providerEntity)
+ val movieCategoryId = stalkerSyntheticCategoryId(providerEntity.id, ContentType.MOVIE, "5")
+
+ org.mockito.kotlin.whenever(xtreamIndexJobDao.get(1L, ContentType.MOVIE.name)).thenReturn(
+ XtreamIndexJobEntity(
+ providerId = 1L,
+ section = ContentType.MOVIE.name,
+ state = "RUNNING"
+ )
+ )
+ org.mockito.kotlin.whenever(xtreamIndexJobDao.get(1L, ContentType.SERIES.name)).thenReturn(
+ XtreamIndexJobEntity(
+ providerId = 1L,
+ section = ContentType.SERIES.name,
+ state = "QUEUED"
+ )
+ )
+
+ val result = manager.syncEpg(providerId = 1L, force = false)
+
+ assertThat(result).isInstanceOf(Result.Success::class.java)
+ val queuedJobCaptor = argumentCaptor<XtreamIndexJobEntity>()
+ verify(xtreamIndexJobDao, atLeastOnce()).upsert(queuedJobCaptor.capture())
+ assertThat(queuedJobCaptor.allValues.any { job ->
+ job.providerId == 1L &&
+ job.section == "EPG" &&
+ job.state == "QUEUED"
+ }).isTrue()
+ verify(stalkerApiService, org.mockito.kotlin.times(0)).streamBulkEpg(any(), any(), any(), any())
+ verify(stalkerApiService, org.mockito.kotlin.times(0)).streamEpg(any(), any(), any(), any(), any())
+ verify(epgRepo, org.mockito.kotlin.times(0)).refreshEpg(any(), any())
+ }
+
+ @Test
+ fun syncEpg_stalker_defers_while_catalog_index_job_is_partial() = runTest {
+ val providerEntity = sampleProvider(ProviderType.STALKER_PORTAL).copy(
+ serverUrl = "http://example.com",
+ username = "",
+ password = "",
+ stalkerMacAddress = "00:11:22:33:44:55",
+ epgSyncMode = ProviderEpgSyncMode.UPFRONT
+ )
+ val manager = buildManager(providerType = ProviderType.STALKER_PORTAL, providerEntity = providerEntity)
+ val movieCategoryId = stalkerSyntheticCategoryId(providerEntity.id, ContentType.MOVIE, "5")
+
+ org.mockito.kotlin.whenever(xtreamIndexJobDao.get(1L, ContentType.MOVIE.name)).thenReturn(
+ XtreamIndexJobEntity(
+ providerId = 1L,
+ section = ContentType.MOVIE.name,
+ state = "PARTIAL"
+ )
+ )
+ org.mockito.kotlin.whenever(xtreamIndexJobDao.get(1L, ContentType.SERIES.name)).thenReturn(
+ XtreamIndexJobEntity(
+ providerId = 1L,
+ section = ContentType.SERIES.name,
+ state = "SUCCESS"
+ )
+ )
+ org.mockito.kotlin.whenever(categoryDao.getByProviderAndTypeSync(1L, ContentType.MOVIE.name)).thenReturn(
+ listOf(
+ CategoryEntity(
+ categoryId = movieCategoryId,
+ name = "Action",
+ type = ContentType.MOVIE,
+ providerId = 1L
+ )
+ )
+ )
+ org.mockito.kotlin.whenever(movieCategoryHydrationDao.get(1L, movieCategoryId)).thenReturn(
+ MovieCategoryHydrationEntity(
+ providerId = 1L,
+ categoryId = movieCategoryId,
+ lastStatus = "FAILED_RETRYABLE",
+ lastAttemptedPage = 1,
+ retryAfterMs = System.currentTimeMillis() + 60_000L,
+ failureCount = 1,
+ retryBudgetRemaining = 2
+ )
+ )
+
+ val result = manager.syncEpg(providerId = 1L, force = false)
+
+ assertThat(result).isInstanceOf(Result.Success::class.java)
+ val queuedJobCaptor = argumentCaptor<XtreamIndexJobEntity>()
+ verify(xtreamIndexJobDao, atLeastOnce()).upsert(queuedJobCaptor.capture())
+ assertThat(queuedJobCaptor.allValues.any { job ->
+ job.providerId == 1L &&
+ job.section == "EPG" &&
+ job.state == "QUEUED"
+ }).isTrue()
+ verify(stalkerApiService, org.mockito.kotlin.times(0)).streamBulkEpg(any(), any(), any(), any())
+ verify(stalkerApiService, org.mockito.kotlin.times(0)).streamEpg(any(), any(), any(), any(), any())
+ verify(epgRepo, org.mockito.kotlin.times(0)).refreshEpg(any(), any())
+ }
+
@Test
fun sync_stalker_recovers_when_live_categories_fail_but_bulk_channels_work() = runTest {
val providerEntity = sampleProvider(ProviderType.STALKER_PORTAL).copy(
@@ -2091,7 +2783,7 @@ class SyncManagerTest {
}
@Test
- fun sync_stalker_upfront_epg_without_xmltv_imports_native_portal_guide() = runTest {
+ fun sync_stalker_upfront_epg_queues_native_portal_guide_until_catalog_is_idle() = runTest {
val providerEntity = sampleProvider(ProviderType.STALKER_PORTAL).copy(
serverUrl = "http://example.com",
username = "",
@@ -2153,20 +2845,21 @@ class SyncManagerTest {
val result = manager.sync(providerId = 1L, force = true)
assertThat(result).isInstanceOf(Result.Success::class.java)
- val insertedProgramsCaptor = argumentCaptor<List<com.streamvault.data.local.entity.ProgramEntity>>()
- verify(programDao).insertAll(insertedProgramsCaptor.capture())
- assertThat(insertedProgramsCaptor.firstValue).hasSize(1)
- assertThat(insertedProgramsCaptor.firstValue.first().channelId).isEqualTo("100")
- assertThat(insertedProgramsCaptor.firstValue.first().providerId).isEqualTo(1L)
- val metadata = syncMetadataRepo.getMetadata(1L)
- assertThat(metadata?.epgCount).isEqualTo(1)
+ val queuedJobCaptor = argumentCaptor<XtreamIndexJobEntity>()
+ verify(xtreamIndexJobDao, atLeastOnce()).upsert(queuedJobCaptor.capture())
+ assertThat(queuedJobCaptor.allValues.any { job ->
+ job.providerId == 1L &&
+ job.section == "EPG" &&
+ job.state == "QUEUED"
+ }).isTrue()
verify(stalkerApiService).streamLiveStreams(any(), any(), any())
verify(stalkerApiService, org.mockito.kotlin.times(0)).getLiveStreams(any(), any(), eq("10"))
- verify(stalkerApiService).streamEpg(any(), any(), eq("100"), any(), any())
+ verify(stalkerApiService, org.mockito.kotlin.times(0)).streamEpg(any(), any(), eq("100"), any(), any())
+ verify(programDao, org.mockito.kotlin.times(0)).insertAll(any())
}
@Test
- fun sync_stalker_upfront_epg_batches_native_portal_guide_writes() = runTest {
+ fun sync_stalker_upfront_epg_defers_batched_native_portal_guide_until_catalog_is_idle() = runTest {
val providerEntity = sampleProvider(ProviderType.STALKER_PORTAL).copy(
serverUrl = "http://example.com",
username = "",
@@ -2228,9 +2921,14 @@ class SyncManagerTest {
val result = manager.sync(providerId = 1L, force = true)
assertThat(result).isInstanceOf(Result.Success::class.java)
- val insertedProgramsCaptor = argumentCaptor<List<com.streamvault.data.local.entity.ProgramEntity>>()
- verify(programDao, atLeast(2)).insertAll(insertedProgramsCaptor.capture())
- assertThat(insertedProgramsCaptor.allValues.flatten()).hasSize(505)
+ val queuedJobCaptor = argumentCaptor<XtreamIndexJobEntity>()
+ verify(xtreamIndexJobDao, atLeastOnce()).upsert(queuedJobCaptor.capture())
+ assertThat(queuedJobCaptor.allValues.any { job ->
+ job.providerId == 1L &&
+ job.section == "EPG" &&
+ job.state == "QUEUED"
+ }).isTrue()
+ verify(programDao, org.mockito.kotlin.times(0)).insertAll(any())
}
@Test
diff --git a/docs/deep-research-report.md b/docs/deep-research-report.md
deleted file mode 100644
index 92eec6be..00000000
--- a/docs/deep-research-report.md
+++ /dev/null
@@ -1,248 +0,0 @@
-# Executive Summary
-
-Stalker-based IPTV clients perform an initial multi-step sync when new portal credentials are entered. First, the client “handshakes” with the portal (type=`stb&action=handshake`), obtaining a bearer token and device profile【84†L89-L97】【84†L109-L114】. Using this token, the client fetches channel categories (e.g. `type=itv&action=get_genres`) and then paged channel lists, as well as VOD (video-on-demand) categories (e.g. `type=vod&action=get_categories`) and their items (via `type=vod&action=get_ordered_list`)【90†L3333-L3341】【96†L1969-L1978】. These API calls typically return JSON objects with keys like `"total_items"`, `"max_page_items"`, and a `"data"` array of item records. For example, a `get_ordered_list` response contains a top-level `"js"` object with `total_items` and `data` arrays【96†L1969-L1978】. Payload sizes vary by provider; one page may carry tens to hundreds of items (each item often hundreds of bytes), so VOD libraries in the thousands can yield many kilobytes or even megabytes of JSON. In practice, clients employ numerous strategies (partial loading, caching, parallel fetches, compression, etc.) to make the initial load feel fast despite large data. Server-side, portal middlewares use indexing, pagination, gzip compression, CDN-backed assets, and possibly pre-generated manifests to speed responses. Popular clients (including open-source Stalker plugins and custom sync tools) typically page through categories in parallel and cache results. Real-world reports note first-time syncs taking on the order of ~10–60 seconds for very large catalogs, whereas optimized incremental loading and local caching greatly improve perceived responsiveness【85†L328-L336】【75†L193-L200】. Key security points: all calls use an access token (Bearer scheme) bound to the device MAC, and clients must refresh that token or re-handshake if it expires. Rate limits are not well-documented; providers may throttle excessive requests.
-
-**Sources:** Official Stalker middleware/API discussions and code【84†L89-L97】【90†L3333-L3341】【96†L1969-L1978】, IPTV client implementations and forum reports【85†L328-L336】【75†L193-L200】.
-
-## Stalker Portal API & Initial Sync Endpoints
-
-On first sync the client typically executes these steps (see flowchart below):
-
-```mermaid
-flowchart LR
- A[Enter Portal Credentials] --> B[STB Handshake<br/>(type=stb&action=handshake)]
- B -->|returns token| C[Get Profile (type=stb&action=get_profile)]
- C -->|device settings| D[Get IPTV Categories<br/>(type=itv&action=get_genres)]
- D --> E[Get IPTV Lists<br/>(type=itv&action=get_ordered_list…p=1,2,…)]
- C --> F[Get VOD Categories<br/>(type=vod&action=get_categories)]
- F --> G[Get VOD Movies<br/>(type=vod&action=get_ordered_list…p=1,2,…)]
- G --> H[Get VOD Series/Seasons (if needed)]
- E & G --> I[Load EPG (type=itv&action=get_short_epg&...)]
-```
-
-1. **Handshake/Auth (STB):** The client calls `/portal.php?type=stb&action=handshake` (with required HTTP headers including the device MAC, user-agent, etc.)【84†L86-L94】. The portal returns a JSON with an access token: e.g. `{"js":{"token":"C00F7332ED272F00D5FD3E82F567A282"}}`【84†L89-L97】. This token must be included as `Authorization: Bearer <token>` in subsequent calls.
-
-2. **Get STB Profile:** Next, the client calls `/portal.php?type=stb&action=get_profile` using the token【84†L109-L114】. The JSON profile includes device settings and user info (e.g. `parent_password`, `client_type`, etc.) which some clients may cache.
-
-3. **Load Channel Categories (Genres):** With the token, call `/portal.php?type=itv&action=get_genres`【85†L328-L336】. This returns an array of “genres” (live-TV categories), e.g.
- ```json
- {"js":[{"id":"*","title":"All","alias":"All",...},{"id":"173","title":"TR|TURKIYE",...}, ...]}
- ```
- (Note: the example above from【85†L333-L341】 shows an `"id":"*" All` plus numbered categories.) Each genre has an internal ID used to fetch its channels.
-
-4. **Load Channel Lists:** For each genre or all-channels, the client pages through `/portal.php?type=itv&action=get_ordered_list&genre=<id>&p=1` etc【85†L406-L415】. The response JSON contains `"total_items"`, `"max_page_items"`, and a `"data"` array of channel objects. (The client typically loops `p=1,2,...` until all pages are fetched【85†L416-L424】.) Channel objects include fields like `id`, `name`, `cmd` (stream command), `logo`, and others. For example, one returned channel entry might be:
- ```json
- {"id":"3031","name":"NEDERLAND 4K+","number":"462","cmd":"ffmpeg http://localhost/ch/3031_","hd":"0",...}
- ```
- (See【85†L421-L428】 for a truncated example.)
-
-5. **Load VOD Categories:** Parallel to channels, the client fetches VOD categories. Stalker portals use `/server/load.php?type=vod&action=get_categories` (or equivalently `portal.php?...`) to obtain VOD category lists【90†L3333-L3341】. Each category has fields like `"id"` and `"title"`. These are analogous to “movie genres.”
-
-6. **Load VOD Lists:** For each VOD category (or all categories), the client calls `/server/load.php?type=vod&action=get_ordered_list&category=<id>&p=1` etc【90†L3333-L3341】【96†L1969-L1978】. The code examples show parameters like `'sortby':'added'`, `'not_ended':'0'`, `'p':page`, etc.【96†L1969-L1978】. The response JSON structure is similar: it contains `"js": {"total_items": <N>, "max_page_items": <M>, "data": [ {...}, {...}, ... ] }`. Each item in `"data"` is a VOD item with fields like `"id"`, `"name"`, `"category_id"`, and usually a `"cmd"` or `"url"` field for streaming, plus a `"screenshot_uri"` or thumbnail URL, `"modified"`, etc. For series, there may be `is_series` flags and separate APIs to list episodes or seasons. The open-source code shows clients iterating pages until all items are retrieved【96†L1969-L1978】.
-
-7. **Get Episode/Series Details (if any):** If the provider supports TV shows/series, the client might next call `type=vod&action=get_seasons` or similar to fetch seasons and episodes (as seen in open-source clients)【70†L3925-L3933】.
-
-8. **Catch-up/EPG:** Finally, clients fetch any electronic program guide (EPG) or TV-archive data via `type=itv&action=get_short_epg` or similar calls (not shown above). These can be large (whole EPG) but are often paged or limited by time window.
-
-**Typical JSON Payloads:** All portal responses are JSON (the examples above show JSON under `"js": {...}`). Exact sizes depend on provider. For instance, one channel list page in Quassi’s example had ~14 items【85†L421-L429】. If a VOD category has 2000 movies and 50 per page, that’s 40 pages; if each item is ~300–500 bytes, total JSON could be ~200 KB per category. Clients usually do *not* fetch all VOD data at once unless caching for offline use.
-
-## Client-Side Loading Strategies
-
-To keep the UI responsive, clients use tactics like:
-
-- **Incremental/Paged Loading:** Don’t fetch all items in one shot. Fetch the first page of each list immediately (e.g. first ITV and first VOD pages), display those, and load further pages in background. The example plugin code above explicitly loops pages 1..max in a background loop【96†L1969-L1978】.
-
-- **Lazy Loading:** Delay loading of large sections until needed. For example, show VOD *categories* immediately (quick summary), but load each category’s contents only when the user browses that category. This avoids long waits for seldom-used categories.
-
-- **Parallel Fetches:** Issue multiple API calls concurrently (e.g. fetch channel list and first page of movies at the same time). Multi-threaded or async fetching can fill multiple list views quickly. The open-source client concurrently fetched all pages using a thread pool【70†L3925-L3933】 to reduce wall-clock time.
-
-- **Metadata-Only Sync:** At first login, clients may only download item metadata (title, ID, thumbnail URL), deferring heavy data (e.g. full description, or actual video manifest) until playback. That way the initial JSON is smaller. For example, some clients fetch only top-level JSON and lazy-load video streams separately.
-
-- **Background Prefetch:** Once initial data is shown, quietly fetch more in the background (e.g. successive pages, EPG, series details) so that by the time a user scrolls or selects, data is ready.
-
-- **Thumbnail-First:** Load small thumbnail images early, while larger cover images or detailed info load later. Many portals provide low-res images (screenshots) versus full poster art; clients may download the smaller ones first.
-
-- **Caching:** Store results locally (e.g. on device cache or database). On subsequent app starts, reuse cached metadata and only fetch deltas via HTTP cache validation (ETag/If-Modified-Since). For example, clients may use the HTTP `Last-Modified` header of portal responses to check for updates, or simply store a timestamp and only fetch changed data. The plugin code even caches data in files and updates every 12 hours【86†L1934-L1943】【96†L2011-L2014】. This dramatically improves perceived load time after the first sync.
-
-- **Compression & Delta Sync:** Ensure requests use gzip (portals typically compress JSON). For updates, use `If-Modified-Since` or ETag headers on each API (if supported) so that unchanged lists yield small “304 Not Modified” responses.
-
-Below is a **timeline flow** of an initial sync showing parallel steps:
-
-```mermaid
-sequenceDiagram
- participant Client
- participant Portal
- Client->>Portal: GET /portal.php?type=stb&action=handshake (with MAC)
- Portal-->>Client: JSON { "js":{"token":"ABC123..."} }
- Client->>Portal: GET /portal.php?type=stb&action=get_profile (Bearer token)
- Portal-->>Client: JSON profile {...}
- par Parallel fetching
- Client->>Portal: GET type=itv&action=get_genres (page 1)
- Portal-->>Client: JSON { "js":[{...}, ...] } (genres list)
- Client->>Portal: GET type=vod&action=get_categories
- Portal-->>Client: JSON { "js":[{...}, ...] } (VOD categories)
- end
- par Load first content pages
- Client->>Portal: GET type=itv&action=get_ordered_list&genre=<firstID>&p=1
- Portal-->>Client: JSON { "js":{"total_items":N,"data":[...20 items...]}}
- Client->>Portal: GET type=vod&action=get_ordered_list&category=<firstCat>&p=1
- Portal-->>Client: JSON { "js":{"total_items":M,"data":[...20 items...]}}
- end
- Note over Client,Portal: Show UI lists (channels, movies) as they arrive
-```
-
-**Trade-Offs:** Loading everything upfront (“eager load”) gives completeness but may delay the first screen. Lazy or paged loading trades initial completeness for responsiveness: the UI appears quickly with partial data. Many clients strike a balance: load genre/category lists (small) immediately, then fill in items.
-
-**Table – Strategy Comparison:**
-
-| Strategy | Pros | Cons | Impact on First-Load Time |
-|-----------------------|---------------------------------|-----------------------------------|-----------------------------------|
-| **Full upfront** | All data available at once | Very slow initial sync, heavy load| Very long delay (seconds to minutes) for large catalogs |
-| **Paged/Incremental** | Faster UI start, avoids freezing| Requires more complex code (looping) | Moderate: first page quick (few sec), rest gradually |
-| **Lazy (on-demand)** | Only fetch needed data | First access to new section delayed | Very fast startup; slight lag when opening each new category |
-| **Parallel fetch** | Better CPU/network usage | Possible rate-limit or sync complexity | Reduces wall-clock time (fetching multiple lists at once) |
-| **Cache (client)** | Instant reload after first sync | Stale data if not updated | Negligible (loads from local cache) |
-| **Compression/gzip** | Reduces bytes over wire | None (adds CPU for decompress) | Reduces bandwidth impact, speeds transfer if large JSON |
-
-_Source:_ Portal API observations and client implementations【90†L3333-L3341】【96†L1969-L1978】.
-
-## Server-Side Optimizations
-
-Middleware providers and portal servers can aid speed by:
-
-- **Indexing & Pre-aggregation:** The portal’s database is typically indexed on category and alphabetical fields, making queries for each `get_ordered_list` fast. Some systems precompute popular lists or maintain cached JSON.
-
-- **API Pagination:** As seen, the `get_ordered_list` API inherently paginates results (`p=` parameter) to limit response size. Server indexes support fast pagination (using LIMIT/OFFSET or cursor-based paging).
-
-- **Compressed Responses:** Stalker middleware supports gzip/deflate. Clients should set `Accept-Encoding: gzip` and expect compressed JSON. This cuts payload size significantly for large JSON arrays.
-
-- **CDN & Caching:** While metadata is dynamic, static assets (thumbnails, logos) can be served via CDN. Even the portal might use HTTP caching headers on API responses to allow 304s.
-
-- **Thumbnails vs Full Manifests:** Portals often provide two sets of URLs: one for small preview images (e.g. “screenshot_uri”) and one for full resolution art. Using smaller images in listings reduces transfer. For streaming, Stalker often provides either direct stream URLs or “vod/get_file” endpoints which may redirect via CDN.
-
-- **Manifest Generation:** For on-demand video, portals might not generate HLS/DASH on the fly. Instead, streams can be direct file URLs or pre-encoded HLS. If dynamic, media servers ensure quick response by reusing existing manifests or performing on-demand muxing with segment caching.
-
-- **Content Delivery:** For catch-up (TV archive), servers often use a separate domain or server. Clients request segments in real time; servers should have seek indexes to satisfy range requests quickly.
-
-If payload sizes are unknown from documentation, we note that “portal payload sizes are unspecified per provider” – providers control how much metadata is returned (some include synopsis or actors, others minimal). In practice, clients observe that initial `get_ordered_list` pages often range from a few dozen KB to hundreds of KB of JSON.
-
-## Real-World Examples
-
-- **Open-Source Clients:** The [stalker.py](https://github.com/Cyogenus/IPTV-MAC-STALKER-PLAYER) library fetches VOD categories via `/stalker_portal/server/load.php?type=vod&action=get_categories`【90†L3333-L3341】 and iterates `get_ordered_list` for each (as shown above). The [plugin.video.stalker](https://github.com/esxbr/plugin.video.stalker) Kodi plugin similarly performs a handshake then loops through pages of `get_ordered_list` calls with parameters like `sortby=added, not_ended=0`【96†L1969-L1978】. These code examples illustrate the typical access patterns.
-
-- **Commercial Apps:** Proprietary apps (e.g. TiviMate, Stalker-based STB apps) follow the same API pattern. A technical overview notes that TiviMate “fetches load.php (handshake), then get.php (content lists), then epg.php”【20†L55-L60】. (In effect, `load.php` is the same as `portal.php?type=stb&action=handshake` on MAG portals.) These clients often preload the first page of all lists. Some even allow specifying a shorter “device ID” to speed recognition by the portal.
-
-- **Forum Reports:** Users report initial VOD sync times of tens of seconds. For example, on Formuler devices, a first-time VOD load could take ~45 seconds for large libraries【74†L83-L91】【75†L193-L200】. Once data is cached, subsequent access is nearly instantaneous. One forum noted that a new firmware implemented auto-cache-clearing on reboot to avoid stale data issues【75†L193-L200】, indicating the importance of cache management in perceived speed.
-
-- **GitHub Implementations:** Some repos generate M3U playlists from Stalker portals. For instance, [santhosh101066/stalker-m3u-server](https://github.com/santhosh101066/stalker-m3u-server) proxies Stalker APIs to produce playlists (using `api.php` to fetch content【45†L243-L249】). Others, like [generator scripts](https://github.com/Cyogenus/IPTV-MAC-STALKER-PLAYER), parse portal JSON directly. The fact that so much code exists for parsing the same endpoints underscores these patterns.
-
-## Network Traffic Patterns & Performance
-
-Analyzing traffic, we see:
-
-- **Handshake (~100–300 bytes):** The `handshake` request is small (no query data except type/action), response ~50–100 bytes (token).
-- **Profile (~1–2 KB):** The profile JSON (all the fields in【84†L119-L127】) is ~1–2 KB.
-- **Genres/Categories (~several KB):** A genre list of tens of items is on the order of 5–20 KB.
-- **List Pages (~10–100 KB+):** Each page of channels or movies varies. In Quassi’s example, 14 channels were returned in ~24-items JSON【85†L420-L428】 (likely ~5–10 KB). If hundreds of movies per page, the JSON can be tens of KB. For example, one client code stopped fetching after 10 pages or so【96†L1970-L1978】 to cap the output.
-- **EPG (~100 KB+):** Fetching EPG for all channels (several hours) can be large (100 KB or more), so it’s often split by time window.
-- **Streaming Links:** Not part of initial sync, but to play, clients call `create_link` or direct URLs, often resulting in short responses (redirect to actual stream).
-
-**Timing:** In practice, a well-optimized portal can reply to a `get_ordered_list` page request in a few hundred milliseconds, but when doing dozens of pages across multiple categories, total time adds up. Client-side parallelism helps hide this. A bulletin board user noted **“First time load maybe 45 sec”** for a large subscription, whereas subsequent loads “in the background” are fast【74†L83-L91】.
-
-## Security and Rate Limiting
-
-- **Authentication:** Stalker portal uses a bearer token (OAuth2-style) bound to the device (MAC). The token is short-lived (hours) and must be refreshed by re-running the handshake if expired. Clients must include it in every API call in the `Authorization` header【84†L109-L114】.
-
-- **Device Verification:** The portal compares the provided MAC and token to ensure the same device. If a client changes its device ID or MAC between calls, the portal will reject the requests.
-
-- **Rate Limits:** Official limits aren’t documented, but providers often throttle abusive patterns. In practice, clients avoid hammering the portal (e.g. pause between calls, use caching). Extremely high parallel requests might cause HTTP 429 responses from some servers.
-
-- **Data Privacy:** All video streams still require credentials; knowing an item’s metadata doesn’t give the stream URL without a valid session token. Some portals watermark URLs with play tokens to prevent link sharing.
-
-## Recommendations and Trade-offs
-
-For best UX on first load, clients should:
-
-- **Show progress:** Inform the user that sync is happening, e.g. “Loading movies 1/10…”. This sets expectations for longer waits (minutes) if needed.
-
-- **Prioritize UI readiness:** Always fetch category lists before item lists, so the UI can show “(Loading…)” instead of a blank screen.
-
-- **Use caching:** Persist data locally. On app restart, show cached content immediately, then silently update in background (UX feels instant).
-
-- **Compress and Parallelize:** Enable gzip and make requests concurrently (subject to server tolerance). Many open-source clients do exactly this to minimize elapsed time【70†L3925-L3933】.
-
-- **Balance pagination vs size:** Choose a page size that balances JSON overhead versus call overhead. Some portals allow tuning `max_page_items`; clients should use a moderately large page (e.g. 50 items) to reduce number of requests but avoid giant JSON dumps.
-
-- **Table of Pros/Cons (excerpt):**
-
-```markdown
-| Approach | Pros | Cons |
-|--------------------|-------------------------------------------|---------------------------------------|
-| Full download | No more sync needed (complete library) | Very slow initial load, heavy memory |
-| Page-by-page | Fast initial pages, lower memory use | Need to handle multiple requests |
-| Lazy per-category | Quick start, fetch only viewed sections | Each new category load has delay |
-| Cache & Refresh | Instant reload after first sync | Risk of stale info if not updated |
-| Parallel fetching | Reduces wait by overlapping requests | Server may throttle many simultaneous |
-```
-
-## Diagrams of Initial Sync
-
-Below is a high-level **flowchart** of an example initial sync data flow:
-
-```mermaid
-flowchart TB
- subgraph Client Device
- A(Credentials Entry) --> B(Handshake: GET type=stb&action=handshake)
- B -->|token| C(Get Profile)
- C --> D(Get ITV Genres)
- C --> E(Get VOD Categories)
- D --> F{Channels by genre}
- F -->|GET for genre i| G(ITV List Page 1)
- G --> H(UI list gets channels)
- E --> I{Movies by category}
- I -->|GET for category j| J(VOD List Page 1)
- J --> K(UI list gets movies)
- %% Parallel arrow style
- C -->|concurrent| D
- C -->|concurrent| E
- F -->|pages| G
- I -->|pages| J
- end
- subgraph Server (Portal API)
- B[Portal.php: handshake] -- returns token --> B
- C[Portal.php: get_profile] -- returns settings --> C
- D[Portal.php: get_genres] -- returns genre list --> D
- E[Portal.php: get_categories] -- returns VOD cats --> E
- G[Portal.php: get_ordered_list (itv)] -- returns channels --> G
- J[Portal.php: get_ordered_list (vod)] -- returns movies --> J
- end
-```
-
-This flow highlights that after the handshake (`B`) and profile (`C`), the client can load live-TV and VOD data in parallel.
-
-Below is a **sequence timeline** of typical API calls (latency not to scale):
-
-```mermaid
-sequenceDiagram
- participant U as User/Client
- participant S as Portal Server
- U->>S: GET /portal.php?type=stb&action=handshake
- S-->>U: {"js":{"token":"XYZ","..."}}
- U->>S: GET /portal.php?type=stb&action=get_profile (Bearer token)
- S-->>U: {"js":{...profile data...}}
- par
- U->>S: GET /portal.php?type=itv&action=get_genres
- S-->>U: {"js":[...genre list...]}
- U->>S: GET /portal.php?type=vod&action=get_categories
- S-->>U: {"js":[...VOD cat list...]}
- end
- U->>S: GET /portal.php?type=itv&action=get_ordered_list&genre=ID&p=1
- S-->>U: {"js":{"total_items":N,"data":[...channels...]}}
- U->>S: GET /portal.php?type=vod&action=get_ordered_list&category=ID&p=1
- S-->>U: {"js":{"total_items":M,"data":[...movies...]}}
- Note over U: UI displays first pages; app continues fetching more pages...
-```
-
-These diagrams illustrate that initial sync is multi-step and often involves overlapping requests for best performance.
-
-**Sources:** Based on Infomir/Stalker portal documentation and source code【84†L89-L97】【90†L3333-L3341】, client implementations【96†L1969-L1978】, and user reports【85†L328-L336】【75†L193-L200】. Each cited source provides concrete details on endpoints, request/response formats, or performance anecdotes, supporting the strategies and patterns described above.
\ No newline at end of file
diff --git a/player/src/main/java/com/streamvault/player/Media3PlayerEngine.kt b/player/src/main/java/com/streamvault/player/Media3PlayerEngine.kt
index 37e94e67..ddc9d3dd 100644
--- a/player/src/main/java/com/streamvault/player/Media3PlayerEngine.kt
+++ b/player/src/main/java/com/streamvault/player/Media3PlayerEngine.kt
@@ -39,6 +39,7 @@ import com.streamvault.domain.model.VideoFormat
import com.streamvault.domain.repository.PlaybackCompatibilityRepository
import com.streamvault.player.audio.PlayerAudioFocusController
import com.streamvault.player.playback.ActiveDecoderPolicy
+import com.streamvault.player.playback.AutomaticRecoveryAction
import com.streamvault.player.playback.DefaultDecoderPreferencePolicy
import com.streamvault.player.playback.DefaultPlaybackCompatibilityProfile
import com.streamvault.player.playback.AudioVideoOffsetAudioSink
@@ -62,6 +63,7 @@ import com.streamvault.player.playback.buildPlaybackRendererPlan
import com.streamvault.player.playback.resolveRetryAttemptAfterPlaybackStarted
import com.streamvault.player.playback.resolveRetryAttemptAfterReady
import com.streamvault.player.playback.resolveRetrySeekPositionMs
+import com.streamvault.player.playback.shouldAttemptAutomaticRecovery
import com.streamvault.player.playback.StreamTypeResolver
import com.streamvault.player.playback.VideoStallDetector
import com.streamvault.player.stats.PlayerStatsCollector
@@ -1499,6 +1501,23 @@ class Media3PlayerEngine @Inject constructor(
videoStallRecoveryAttempt++
if (!videoStallSafeRecoveryPerformed) {
videoStallSafeRecoveryPerformed = true
+ if (!shouldAttemptAutomaticRecovery(
+ action = AutomaticRecoveryAction.FULL_REPREPARE,
+ resolvedStreamType = currentResolvedStreamType,
+ playbackStarted = playbackStarted
+ )
+ ) {
+ Log.w(
+ TAG,
+ "video-stall reprepare suppressed after playback start for provider streamType=$currentResolvedStreamType"
+ )
+ _error.tryEmit(
+ PlayerError.DecoderError(
+ "Video playback stalled. Automatic recovery was not attempted to avoid opening another provider connection."
+ )
+ )
+ return
+ }
Log.w(TAG, "video-stall safe reprepare attempt=$videoStallRecoveryAttempt")
prepareInternal(
streamInfo = streamInfo,
@@ -1533,6 +1552,18 @@ class Media3PlayerEngine @Inject constructor(
val mediaId = lastMediaId ?: return false
val fallbackMode = decoderPreferencePolicy.onDecoderInitFailure(requestedDecoderMode, mediaId) ?: return false
val fallbackPolicy = resolveActiveDecoderPolicy(policyModeFor(requestedDecoderMode, fallbackMode))
+ if (!shouldAttemptAutomaticRecovery(
+ action = AutomaticRecoveryAction.DECODER_FALLBACK,
+ resolvedStreamType = currentResolvedStreamType,
+ playbackStarted = playbackStarted
+ )
+ ) {
+ Log.w(
+ TAG,
+ "video-stall decoder fallback suppressed after playback start fallback=$fallbackMode streamType=$currentResolvedStreamType mediaId=$mediaId"
+ )
+ return false
+ }
recoveryDecoderPolicyOverride = fallbackPolicy
Log.w(
TAG,
@@ -1697,6 +1728,25 @@ class Media3PlayerEngine @Inject constructor(
val seekPosition = exoPlayer?.currentPosition
?.takeIf { currentResolvedStreamType == ResolvedStreamType.PROGRESSIVE && it > 0L }
+ if (!shouldAttemptAutomaticRecovery(
+ action = AutomaticRecoveryAction.FULL_REPREPARE,
+ resolvedStreamType = currentResolvedStreamType,
+ playbackStarted = playbackStarted
+ )
+ ) {
+ Log.e(
+ TAG,
+ "audio-renderer-recover suppressed after playback start source=$source streamType=$currentResolvedStreamType target=${PlaybackLogSanitizer.sanitizeUrl(streamInfo.url)} message=${PlaybackLogSanitizer.sanitizeMessage(error.message)}"
+ )
+ lastSupportErrorMessage = error.message ?: "Audio playback failed for this stream."
+ _error.tryEmit(
+ PlayerError.DecoderError(
+ error.message ?: "Audio playback failed for this stream."
+ )
+ )
+ return
+ }
+
Log.w(
TAG,
"audio-renderer-recover source=$source target=${PlaybackLogSanitizer.sanitizeUrl(streamInfo.url)} message=${PlaybackLogSanitizer.sanitizeMessage(error.message)}"
@@ -1846,6 +1896,22 @@ class Media3PlayerEngine @Inject constructor(
if (category == PlaybackErrorCategory.DECODER || category == PlaybackErrorCategory.FORMAT_UNSUPPORTED) {
val fallbackMode = decoderPreferencePolicy.onDecoderInitFailure(requestedDecoderMode, mediaId)
if (fallbackMode != null) {
+ if (!shouldAttemptAutomaticRecovery(
+ action = AutomaticRecoveryAction.DECODER_FALLBACK,
+ resolvedStreamType = currentResolvedStreamType,
+ playbackStarted = playbackStarted
+ )
+ ) {
+ Log.w(
+ TAG,
+ "decoder-preference fallback suppressed after playback start fallback=$fallbackMode streamType=$currentResolvedStreamType mediaId=$mediaId"
+ )
+ _retryStatus.value = null
+ lastSupportErrorMessage = error.message
+ _error.tryEmit(PlayerError.fromException(error))
+ _playbackState.value = PlaybackState.ERROR
+ return
+ }
Log.w(
TAG,
"decoder-preference fallback=$fallbackMode mediaId=$mediaId target=${PlaybackLogSanitizer.sanitizeUrl(streamInfo.url)}"
@@ -1857,6 +1923,22 @@ class Media3PlayerEngine @Inject constructor(
}
val nextAttempt = retryAttempt + 1
+ if (!shouldAttemptAutomaticRecovery(
+ action = AutomaticRecoveryAction.FULL_REPREPARE,
+ resolvedStreamType = currentResolvedStreamType,
+ playbackStarted = playbackStarted
+ )
+ ) {
+ _retryStatus.value = null
+ Log.e(
+ TAG,
+ "retry suppressed after playback start category=$category streamType=$currentResolvedStreamType target=${PlaybackLogSanitizer.sanitizeUrl(streamInfo.url)} message=${PlaybackLogSanitizer.sanitizeMessage(error.message)}"
+ )
+ lastSupportErrorMessage = error.message
+ _error.tryEmit(PlayerError.fromException(error))
+ _playbackState.value = PlaybackState.ERROR
+ return
+ }
if (retryPolicy.shouldRetry(error, retryContext, playbackStarted, nextAttempt)) {
val delayMs = retryPolicy.retryDelayMs(error, nextAttempt)
val player = exoPlayer
diff --git a/player/src/main/java/com/streamvault/player/playback/PlaybackRecoveryPolicy.kt b/player/src/main/java/com/streamvault/player/playback/PlaybackRecoveryPolicy.kt
new file mode 100644
index 00000000..4ebb5dab
--- /dev/null
+++ b/player/src/main/java/com/streamvault/player/playback/PlaybackRecoveryPolicy.kt
@@ -0,0 +1,24 @@
+package com.streamvault.player.playback
+
+internal enum class AutomaticRecoveryAction {
+ FULL_REPREPARE,
+ SURFACE_FALLBACK,
+ DECODER_FALLBACK
+}
+
+internal fun shouldAttemptAutomaticRecovery(
+ action: AutomaticRecoveryAction,
+ resolvedStreamType: ResolvedStreamType,
+ playbackStarted: Boolean
+): Boolean {
+ if (!playbackStarted) return true
+ if (!resolvedStreamType.isLiveProviderSession()) return true
+ return action == AutomaticRecoveryAction.SURFACE_FALLBACK
+}
+
+private fun ResolvedStreamType.isLiveProviderSession(): Boolean {
+ return this == ResolvedStreamType.HLS ||
+ this == ResolvedStreamType.SMOOTH_STREAMING ||
+ this == ResolvedStreamType.MPEG_TS_LIVE ||
+ this == ResolvedStreamType.RTSP
+}
diff --git a/player/src/test/java/com/streamvault/player/playback/PlaybackRecoveryPolicyTest.kt b/player/src/test/java/com/streamvault/player/playback/PlaybackRecoveryPolicyTest.kt
new file mode 100644
index 00000000..3bf55c50
--- /dev/null
+++ b/player/src/test/java/com/streamvault/player/playback/PlaybackRecoveryPolicyTest.kt
@@ -0,0 +1,62 @@
+package com.streamvault.player.playback
+
+import com.google.common.truth.Truth.assertThat
+import org.junit.Test
+
+class PlaybackRecoveryPolicyTest {
+
+ @Test
+ fun `live provider stream after playback start blocks full reprepare`() {
+ assertThat(
+ shouldAttemptAutomaticRecovery(
+ action = AutomaticRecoveryAction.FULL_REPREPARE,
+ resolvedStreamType = ResolvedStreamType.MPEG_TS_LIVE,
+ playbackStarted = true
+ )
+ ).isFalse()
+ }
+
+ @Test
+ fun `live provider stream after playback start blocks decoder fallback`() {
+ assertThat(
+ shouldAttemptAutomaticRecovery(
+ action = AutomaticRecoveryAction.DECODER_FALLBACK,
+ resolvedStreamType = ResolvedStreamType.HLS,
+ playbackStarted = true
+ )
+ ).isFalse()
+ }
+
+ @Test
+ fun `startup recovery may still open provider stream`() {
+ assertThat(
+ shouldAttemptAutomaticRecovery(
+ action = AutomaticRecoveryAction.FULL_REPREPARE,
+ resolvedStreamType = ResolvedStreamType.MPEG_TS_LIVE,
+ playbackStarted = false
+ )
+ ).isTrue()
+ }
+
+ @Test
+ fun `progressive streams keep automatic recovery after playback start`() {
+ assertThat(
+ shouldAttemptAutomaticRecovery(
+ action = AutomaticRecoveryAction.FULL_REPREPARE,
+ resolvedStreamType = ResolvedStreamType.PROGRESSIVE,
+ playbackStarted = true
+ )
+ ).isTrue()
+ }
+
+ @Test
+ fun `surface fallback remains allowed because it does not force a provider reopen by policy`() {
+ assertThat(
+ shouldAttemptAutomaticRecovery(
+ action = AutomaticRecoveryAction.SURFACE_FALLBACK,
+ resolvedStreamType = ResolvedStreamType.MPEG_TS_LIVE,
+ playbackStarted = true
+ )
+ ).isTrue()
+ }
+}