StreamVault is a TV-first free IPTV player for Android TV built with Kotlin, Jetpack Compose, Room, Hilt, and Media3.
Kotlin iptv-player
feat(epg): adapt PR236 Stalker guide fallback
David Nashashccd6a87c4561
diff --git a/data/src/main/java/com/streamvault/data/preferences/EmptyGuideKeyCache.kt b/data/src/main/java/com/streamvault/data/preferences/EmptyGuideKeyCache.ktnew file mode 100644index 00000000..b2274276--- /dev/null+++ b/data/src/main/java/com/streamvault/data/preferences/EmptyGuideKeyCache.kt@@ -0,0 +1,33 @@+package com.streamvault.data.preferences++internal object EmptyGuideKeyCache {+ const val TTL_MILLIS = 24L * 60L * 60L * 1000L+ const val MAX_ENTRIES = 512+}++internal fun decodeEmptyGuideKeys(encoded: String?, now: Long): Map<String, Long> =+ encoded+ .orEmpty()+ .lineSequence()+ .mapNotNull { line ->+ val separator = line.indexOf('\t')+ if (separator <= 0) return@mapNotNull null+ val key = line.substring(0, separator).trim()+ val timestamp = line.substring(separator + 1).trim().toLongOrNull() ?: return@mapNotNull null+ if (key.isBlank() || timestamp <= 0L || now - timestamp >= EmptyGuideKeyCache.TTL_MILLIS) {+ return@mapNotNull null+ }+ key to timestamp+ }+ .toList()+ .sortedByDescending { it.second }+ .take(EmptyGuideKeyCache.MAX_ENTRIES)+ .toMap()++internal fun encodeEmptyGuideKeys(values: Map<String, Long>): String =+ values+ .filter { (key, timestamp) -> key.isNotBlank() && timestamp > 0L }+ .entries+ .sortedByDescending { it.value }+ .take(EmptyGuideKeyCache.MAX_ENTRIES)+ .joinToString("\n") { (key, timestamp) -> "$key\t$timestamp" }diff --git a/data/src/main/java/com/streamvault/data/preferences/PreferencesRepository.kt b/data/src/main/java/com/streamvault/data/preferences/PreferencesRepository.ktindex c744b953..22b5cf26 100644--- a/data/src/main/java/com/streamvault/data/preferences/PreferencesRepository.kt+++ b/data/src/main/java/com/streamvault/data/preferences/PreferencesRepository.kt@@ -314,6 +314,9 @@ class PreferencesRepository @Inject constructor(val LAST_MAINTENANCE_EPG_PROGRAMME_ROWS = longPreferencesKey("last_maintenance_epg_programme_rows")val LAST_MAINTENANCE_PLAYBACK_HISTORY_ROWS = longPreferencesKey("last_maintenance_playback_history_rows")val LAST_MAINTENANCE_FAVORITE_ROWS = longPreferencesKey("last_maintenance_favorite_rows")++ fun emptyGuideKeys(providerId: Long) =+ stringPreferencesKey("guide_empty_keys_v1_$providerId")}private object ParentalSessionKeys {@@ -368,6 +371,61 @@ class PreferencesRepository @Inject constructor(}}+ suspend fun getEmptyGuideKeys(providerId: Long): Map<String, Long> {+ if (providerId <= 0L) return emptyMap()+ val key = PreferencesKeys.emptyGuideKeys(providerId)+ val now = System.currentTimeMillis()+ val preferences = context.dataStore.data.first()+ val raw = preferences[key]+ val decoded = decodeEmptyGuideKeys(raw, now)+ val normalized = encodeEmptyGuideKeys(decoded)+ if (raw != normalized) {+ context.dataStore.edit { mutablePreferences ->+ if (normalized.isBlank()) {+ mutablePreferences.remove(key)+ } else {+ mutablePreferences[key] = normalized+ }+ }+ }+ return decoded+ }++ suspend fun addEmptyGuideKeys(providerId: Long, lookupKeys: Set<String>) {+ if (providerId <= 0L || lookupKeys.isEmpty()) return+ val key = PreferencesKeys.emptyGuideKeys(providerId)+ val now = System.currentTimeMillis()+ context.dataStore.edit { preferences ->+ val merged = decodeEmptyGuideKeys(preferences[key], now).toMutableMap()+ lookupKeys+ .map(String::trim)+ .filter(String::isNotBlank)+ .forEach { lookupKey -> merged[lookupKey] = now }+ val encoded = encodeEmptyGuideKeys(merged)+ if (encoded.isBlank()) {+ preferences.remove(key)+ } else {+ preferences[key] = encoded+ }+ }+ }++ suspend fun removeEmptyGuideKeys(providerId: Long, lookupKeys: Set<String>) {+ if (providerId <= 0L) return+ val key = PreferencesKeys.emptyGuideKeys(providerId)+ val now = System.currentTimeMillis()+ context.dataStore.edit { preferences ->+ val remaining = decodeEmptyGuideKeys(preferences[key], now)+ .filterKeys { it !in lookupKeys }+ val encoded = encodeEmptyGuideKeys(remaining)+ if (encoded.isBlank()) {+ preferences.remove(key)+ } else {+ preferences[key] = encoded+ }+ }+ }+val defaultViewMode: Flow<String?> = context.dataStore.data.map { preferences ->preferences[PreferencesKeys.DEFAULT_VIEW_MODE]}diff --git a/data/src/main/java/com/streamvault/data/remote/stalker/OkHttpStalkerApiService.kt b/data/src/main/java/com/streamvault/data/remote/stalker/OkHttpStalkerApiService.ktindex 35645562..ad0839b0 100644--- a/data/src/main/java/com/streamvault/data/remote/stalker/OkHttpStalkerApiService.kt+++ b/data/src/main/java/com/streamvault/data/remote/stalker/OkHttpStalkerApiService.kt@@ -2653,6 +2653,8 @@ class OkHttpStalkerApiService @Inject constructor(val requestPriority = when {request.url.queryParameter("action").equals("create_link", ignoreCase = true) ->StalkerNetworkPriority.INTERACTIVE+ request.url.queryParameter("action").equals("get_short_epg", ignoreCase = true) ->+ StalkerNetworkPriority.PREFETCHcurrentCoroutineContext()[StalkerRequestPriorityContext]?.priority in setOf(com.streamvault.domain.model.StalkerRequestPriority.EPG,com.streamvault.domain.model.StalkerRequestPriority.BACKGROUND_INDEXdiff --git a/data/src/main/java/com/streamvault/data/remote/stalker/StalkerProvider.kt b/data/src/main/java/com/streamvault/data/remote/stalker/StalkerProvider.ktindex 9d386397..31a85629 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@@ -738,6 +738,12 @@ internal companion object {}}+ override suspend fun getEpg(request: GuideRequest): Result<List<Program>> {+ val numericKey = request.streamId.takeIf { it > 0L }?.toString()+ ?: return Result.error("EPG lookup needs numeric portal channel id")+ return getEpg(numericKey)+ }+suspend fun getBulkEpg(periodHours: Int = 6): Result<List<Program>> {return runWithAuthorizedSession { session, _ ->when (val epgResult = api.getBulkEpg(session, currentDeviceProfile(), periodHours)) {@@ -789,6 +795,27 @@ internal companion object {}}+ override suspend fun getShortEpg(request: GuideRequest): Result<List<Program>> {+ val numericKey = request.streamId.takeIf { it > 0L }?.toString()+ val numericResult = numericKey?.let { getShortEpg(it, request.limit) }+ if (numericResult is Result.Success && numericResult.data.isNotEmpty()) {+ return numericResult+ }++ val xmlKey = request.epgChannelId+ ?.trim()+ ?.takeIf(String::isNotBlank)+ ?.takeUnless { it == numericKey }+ val xmlResult = xmlKey?.let { getShortEpg(it, request.limit) }+ return when {+ xmlResult is Result.Success -> xmlResult+ numericResult is Result.Success -> numericResult+ numericResult is Result.Error -> numericResult+ xmlResult is Result.Error -> xmlResult+ else -> Result.error("Short EPG lookup returned no programs")+ }+ }+suspend fun resolvePlaybackInfo(kind: StalkerStreamKind,cmd: String,diff --git a/data/src/main/java/com/streamvault/data/repository/ProviderRepositoryImpl.kt b/data/src/main/java/com/streamvault/data/repository/ProviderRepositoryImpl.ktindex 2f60f6c0..a5a3cc20 100644--- a/data/src/main/java/com/streamvault/data/repository/ProviderRepositoryImpl.kt+++ b/data/src/main/java/com/streamvault/data/repository/ProviderRepositoryImpl.kt@@ -1840,7 +1840,8 @@ class ProviderRepositoryImpl @Inject constructor(streamId = streamId,epgChannelId = epgChannelId,limit = limit,- guide = guide+ guide = guide,+ shortEpgOnly = providerEntity.type == ProviderType.STALKER_PORTAL)if (result is Result.Success && result.data.isNotEmpty()) {cacheProgramsForChannel(providerId, result.data)@@ -1885,7 +1886,8 @@ class ProviderRepositoryImpl @Inject constructor(streamId = request.streamId,epgChannelId = request.epgChannelId,limit = limit,- guide = guide+ guide = guide,+ shortEpgOnly = providerEntity.type == ProviderType.STALKER_PORTAL)}}@@ -2090,7 +2092,8 @@ class ProviderRepositoryImpl @Inject constructor(streamId: Long,epgChannelId: String?,limit: Int,- guide: GuideSource+ guide: GuideSource,+ shortEpgOnly: Boolean = false): Result<List<Program>> {if (providerId <= 0L || streamId <= 0L) {return Result.error("Live stream context is unavailable.")@@ -2109,6 +2112,13 @@ class ProviderRepositoryImpl @Inject constructor(normalizeXtreamPrograms(providerId, epgChannelId ?: streamId.toString(), shortPrograms))}+ if (shortEpgOnly) {+ return when (shortResult) {+ is Result.Success -> Result.success(emptyList())+ is Result.Error -> Result.error(shortResult.message, shortResult.exception)+ is Result.Loading -> Result.error("Unexpected loading state")+ }+ }return when (val fullResult = guide.getEpg(request)) {is Result.Success -> Result.success(normalizeXtreamPrograms(diff --git a/data/src/main/java/com/streamvault/data/sync/ProviderEpgSyncExecutor.kt b/data/src/main/java/com/streamvault/data/sync/ProviderEpgSyncExecutor.ktindex 150494f9..7158c4d6 100644--- a/data/src/main/java/com/streamvault/data/sync/ProviderEpgSyncExecutor.kt+++ b/data/src/main/java/com/streamvault/data/sync/ProviderEpgSyncExecutor.kt@@ -231,6 +231,7 @@ internal class ProviderEpgSyncExecutor(val bulkCoveredChannelKeys = linkedSetOf<String>()var importedProgramCount = 0var providerRateLimited = false+ var bulkEpgReturnedEmpty = falsesuspend fun flushPrograms() {if (insertBuffer.isEmpty()) return@@ -273,6 +274,9 @@ internal class ProviderEpgSyncExecutor(if (result is Result.Error) {throw result.exception ?: IllegalStateException(result.message)}+ if (result is Result.Success && result.data == 0) {+ bulkEpgReturnedEmpty = true+ }}}.onFailure { error ->providerRateLimited = error.hasStalkerRateLimit()@@ -327,6 +331,14 @@ internal class ProviderEpgSyncExecutor(if (streamResult is Result.Error) {throw streamResult.exception ?: IllegalStateException(streamResult.message)}+ if (bulkEpgReturnedEmpty && perChannelRecordCount == 0) {+ ignorePerChannelGuide = true+ Log.w(+ TAG,+ "Stalker portal returned empty bulk and per-channel EPG; " ++ "skipping remaining per-channel guide calls."+ )+ }}.onFailure { error ->if (error.hasStalkerRateLimit()) {providerRateLimited = truediff --git a/data/src/test/java/com/streamvault/data/preferences/EmptyGuideKeyCacheTest.kt b/data/src/test/java/com/streamvault/data/preferences/EmptyGuideKeyCacheTest.ktnew file mode 100644index 00000000..c0f20290--- /dev/null+++ b/data/src/test/java/com/streamvault/data/preferences/EmptyGuideKeyCacheTest.kt@@ -0,0 +1,35 @@+package com.streamvault.data.preferences++import com.google.common.truth.Truth.assertThat+import org.junit.Test++class EmptyGuideKeyCacheTest {+ @Test+ fun decodePrunesExpiredEntriesAndBoundsNewestEntries() {+ val encoded = buildString {+ append("expired\t100\n")+ repeat(EmptyGuideKeyCache.MAX_ENTRIES + 3) { index ->+ append("key-$index\t${1_000L + index}\n")+ }+ }++ val decoded = decodeEmptyGuideKeys(+ encoded = encoded,+ now = 1_000L + EmptyGuideKeyCache.TTL_MILLIS+ )++ assertThat(decoded).doesNotContainKey("expired")+ assertThat(decoded).hasSize(EmptyGuideKeyCache.MAX_ENTRIES)+ assertThat(decoded).containsKey("key-${EmptyGuideKeyCache.MAX_ENTRIES + 2}")+ assertThat(decoded).doesNotContainKey("key-0")+ }++ @Test+ fun encodeUsesStableNewestFirstRepresentation() {+ val encoded = encodeEmptyGuideKeys(+ mapOf("older" to 10L, "newer" to 20L)+ )++ assertThat(encoded).isEqualTo("newer\t20\nolder\t10")+ }+}diff --git a/data/src/test/java/com/streamvault/data/remote/stalker/StalkerProviderTest.kt b/data/src/test/java/com/streamvault/data/remote/stalker/StalkerProviderTest.ktindex a9cee49d..07a767e7 100644--- a/data/src/test/java/com/streamvault/data/remote/stalker/StalkerProviderTest.kt+++ b/data/src/test/java/com/streamvault/data/remote/stalker/StalkerProviderTest.kt@@ -12,6 +12,7 @@ import com.streamvault.domain.model.CatalogLayoutimport com.streamvault.domain.model.ProviderStatusimport com.streamvault.domain.model.PlaybackTransportModeimport com.streamvault.domain.model.Result+import com.streamvault.domain.provider.GuideRequestimport com.streamvault.domain.model.StalkerBootstrapRecipeimport com.streamvault.domain.model.StalkerTransportGrantimport com.streamvault.domain.model.StalkerTransportMode@@ -45,6 +46,116 @@ class StalkerProviderTest {assertThat(page.isComplete).isFalse()}+ @Test+ fun shortEpgRequest_triesXmlKeyWhenNumericPortalKeyIsEmpty() = runTest {+ val api = FakeStalkerApiService(+ profile = StalkerProviderProfile(accountName = "Room"),+ shortEpgByChannel = mapOf(+ "42" to emptyList(),+ "xml.channel" to listOf(+ StalkerProgramRecord(+ id = "1",+ channelId = "xml.channel",+ title = "Guide entry",+ description = "",+ startTimeMillis = 1_000L,+ endTimeMillis = 2_000L+ )+ )+ )+ )+ val provider = StalkerProvider(+ providerId = 7,+ api = api,+ portalUrl = "https://portal.example.com/c/",+ macAddress = "00:1A:79:12:34:56",+ deviceProfile = "MAG250",+ timezone = "UTC",+ locale = "en"+ )++ val result = provider.getShortEpg(GuideRequest(streamId = 42L, epgChannelId = "xml.channel"))++ assertThat(result).isInstanceOf(Result.Success::class.java)+ assertThat((result as Result.Success).data.single().title).isEqualTo("Guide entry")+ }++ @Test+ fun shortEpgRequest_prefersNumericPortalKeyWhenItHasPrograms() = runTest {+ val api = FakeStalkerApiService(+ profile = StalkerProviderProfile(accountName = "Room"),+ shortEpgByChannel = mapOf(+ "42" to listOf(+ StalkerProgramRecord(+ id = "1",+ channelId = "42",+ title = "Numeric guide entry",+ description = "",+ startTimeMillis = 1_000L,+ endTimeMillis = 2_000L+ )+ ),+ "xml.channel" to listOf(+ StalkerProgramRecord(+ id = "2",+ channelId = "xml.channel",+ title = "XML guide entry",+ description = "",+ startTimeMillis = 1_000L,+ endTimeMillis = 2_000L+ )+ )+ )+ )+ val provider = StalkerProvider(+ providerId = 7,+ api = api,+ portalUrl = "https://portal.example.com/c/",+ macAddress = "00:1A:79:12:34:56",+ deviceProfile = "MAG250",+ timezone = "UTC",+ locale = "en"+ )++ val result = provider.getShortEpg(GuideRequest(streamId = 42L, epgChannelId = "xml.channel"))++ assertThat((result as Result.Success).data.single().title).isEqualTo("Numeric guide entry")+ assertThat(api.shortEpgCalls).containsExactly("42")+ }++ @Test+ fun fullEpgRequest_usesNumericPortalKey() = runTest {+ val api = FakeStalkerApiService(+ profile = StalkerProviderProfile(accountName = "Room"),+ epgByChannel = mapOf(+ "42" to listOf(+ StalkerProgramRecord(+ id = "1",+ channelId = "42",+ title = "Full guide entry",+ description = "",+ startTimeMillis = 1_000L,+ endTimeMillis = 2_000L+ )+ )+ )+ )+ val provider = StalkerProvider(+ providerId = 7,+ api = api,+ portalUrl = "https://portal.example.com/c/",+ macAddress = "00:1A:79:12:34:56",+ deviceProfile = "MAG250",+ timezone = "UTC",+ locale = "en"+ )++ val result = provider.getEpg(GuideRequest(streamId = 42L, epgChannelId = "xml.channel"))++ assertThat((result as Result.Success).data.single().title).isEqualTo("Full guide entry")+ assertThat(api.epgCalls).containsExactly("42")+ }+@Testfun authenticate_treats_status_zero_as_partial_not_expired() = runTest {val provider = StalkerProvider(@@ -1236,6 +1347,8 @@ class StalkerProviderTest {private val seriesCategoriesResult: Result<List<StalkerCategoryRecord>>? = null,private val vodPageItems: List<StalkerItemRecord> = emptyList(),private val seriesPageItems: List<StalkerItemRecord> = emptyList(),+ private val shortEpgByChannel: Map<String, List<StalkerProgramRecord>> = emptyMap(),+ private val epgByChannel: Map<String, List<StalkerProgramRecord>> = emptyMap(),private var authenticationFailuresBeforeSuccess: Int = 0,private val authenticationError: Throwable? = null) : StalkerApiService {@@ -1247,6 +1360,8 @@ class StalkerProviderTest {private setvar lastAuthenticateProfile: StalkerDeviceProfile? = nullprivate set+ val shortEpgCalls: MutableList<String> = mutableListOf()+ val epgCalls: MutableList<String> = mutableListOf()override suspend fun authenticate(profile: StalkerDeviceProfile): Result<Pair<StalkerSession, StalkerProviderProfile>> {authenticateCalls += 1@@ -1339,13 +1454,19 @@ class StalkerProviderTest {profile: StalkerDeviceProfile,channelId: String,limit: Int- ) = Result.success(emptyList<StalkerProgramRecord>())+ ): Result<List<StalkerProgramRecord>> {+ shortEpgCalls += channelId+ return Result.success(shortEpgByChannel[channelId].orEmpty())+ }override suspend fun getEpg(session: StalkerSession,profile: StalkerDeviceProfile,channelId: String- ) = Result.success(emptyList<StalkerProgramRecord>())+ ): Result<List<StalkerProgramRecord>> {+ epgCalls += channelId+ return Result.success(epgByChannel[channelId].orEmpty())+ }override suspend fun getBulkEpg(session: StalkerSession,diff --git a/data/src/test/java/com/streamvault/data/sync/SyncManagerTest.kt b/data/src/test/java/com/streamvault/data/sync/SyncManagerTest.ktindex 289f71f4..6a20a7a5 100644--- a/data/src/test/java/com/streamvault/data/sync/SyncManagerTest.kt+++ b/data/src/test/java/com/streamvault/data/sync/SyncManagerTest.kt@@ -3629,6 +3629,49 @@ class SyncManagerTest {assertThat(metadata?.epgCount).isEqualTo(1)}+ @Test+ fun retrySection_epg_stalker_skips_dead_epg_info_after_first_empty_channel() = runTest {+ val providerEntity = sampleProvider(ProviderType.STALKER_PORTAL).copy(+ serverUrl = "http://example.com",+ username = "",+ password = "",+ stalkerMacAddress = "00:11:22:33:44:55",+ epgSyncMode = ProviderEpgSyncMode.BACKGROUND,+ epgUrl = ""+ )+ 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(channelDao.getGuideSyncEntriesByProvider(1L)).thenReturn(+ (1..5).map { index ->+ ChannelGuideSyncEntity(+ streamId = 100L + index,+ name = "Channel $index",+ epgChannelId = "guide-$index"+ )+ }+ )+ stalkerApiService.stubStreamBulkEpg(programs = emptyList())+ (1..5).forEach { index ->+ stalkerApiService.stubStreamEpg(channelId = "guide-$index", programs = emptyList())+ }+ org.mockito.kotlin.whenever(programDao.countByProvider(1L)).thenReturn(0)++ val result = manager.retrySection(providerId = 1L, section = SyncRepairSection.EPG)++ assertThat(result).isInstanceOf(Result.Success::class.java)+ org.mockito.kotlin.verify(stalkerApiService, org.mockito.kotlin.times(1))+ .streamEpg(any(), any(), any(), any(), any())+ }+@Testfun retrySection_epg_stalker_dedupes_same_guide_key_within_one_run() = runTest {val providerEntity = sampleProvider(ProviderType.STALKER_PORTAL).copy(diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.mdindex bdf7a4fc..ba5859d5 100644--- a/docs/CHANGELOG.md+++ b/docs/CHANGELOG.md@@ -23,6 +23,9 @@ All notable product changes are recorded in this document.- Improved Stalker authentication resilience by stopping repeated handshakes after explicit soft-throttle signals, reusing short-lived encrypted sessions across provider instances and process restarts, and restoring session cookies for resumed API requests.- Fixed Stalker compatibility discovery treating every tokenless HTTP 200 response as a rate limit; generic endpoint or recipe responses now continue through fallback discovery.- Fixed Stalker VOD category layout drift by retargeting stale stored category types before synchronization instead of forcing an unnecessary catalog re-download.+- Improved Stalker on-demand guide loading by preferring numeric short-EPG lookups, pacing prefetch requests, and publishing guide results in bounded chunks.+- Reduced repeated empty Stalker guide requests by sharing provider-scoped, expiring empty-key cache state between the Guide and Home now-playing fallbacks.+- Fixed Stalker guide synchronization continuing through dead per-channel EPG endpoints after both bulk and first per-channel responses are confirmed empty.## [1.0.17]diff --git a/feature/live/src/main/java/com/streamvault/feature/live/epg/EpgViewModel.kt b/feature/live/src/main/java/com/streamvault/feature/live/epg/EpgViewModel.ktindex 1eec9d9f..b6ffc96b 100644--- a/feature/live/src/main/java/com/streamvault/feature/live/epg/EpgViewModel.kt+++ b/feature/live/src/main/java/com/streamvault/feature/live/epg/EpgViewModel.kt@@ -83,6 +83,8 @@ import com.streamvault.feature.live.presentation.epg.resolveLiveGuideCategorySelimport com.streamvault.feature.live.presentation.epg.countMissingLiveGuideEntriesimport com.streamvault.feature.live.presentation.epg.countLiveGuideChannelsWithScheduleimport com.streamvault.feature.live.presentation.epg.hasUpcomingLiveGuideData+import com.streamvault.feature.live.presentation.model.GuideCacheKey+import com.streamvault.feature.live.presentation.model.GuideCachePolicyimport javax.inject.Provider as InjectProviderdata class RecordingConflictInfo(@@ -279,7 +281,8 @@ class EpgViewModel @Inject constructor(companion object {const val MAX_CHANNELS = 60- private const val MAX_XTREAM_GUIDE_FALLBACK_CHANNELS = 10+ private const val MAX_XTREAM_GUIDE_FALLBACK_CHANNELS = 60+ private const val XTREAM_GUIDE_FALLBACK_CHUNK_SIZE = 12private const val MAX_XTREAM_GUIDE_FALLBACK_PROGRAMS = 6const val LOOKBACK_MS = 60 * 60 * 1000Lconst val LOOKAHEAD_MS = 6 * 60 * 60 * 1000L@@ -310,6 +313,9 @@ class EpgViewModel @Inject constructor(val programReminderUiState: StateFlow<ProgramReminderUiState> = _programReminderUiState.asStateFlow()private var overrideSearchJob: Job? = nullprivate var guideFallbackJob: Job? = null+ private var guideFallbackContext: GuideFallbackContext? = null+ private val sessionEmptyGuideKeys = mutableSetOf<GuideCacheKey>()+ private val persistedEmptyGuideKeys = mutableMapOf<Long, Map<String, Long>>()private var prefetchJob: Deferred<GuidePrefetchedPage?>? = nullprivate var loadMoreJob: Job? = nullprivate var combinedCategoriesById: Map<Long, CombinedCategory> = emptyMap()@@ -1682,12 +1688,22 @@ class EpgViewModel @Inject constructor(// 1. Try the multi-source resolved path first.val channelIds = channels.map { it.id }+ val sentinelLookupKeys = channels+ .filter(GuideCachePolicy::isSentinelChannel)+ .flatMap { channel ->+ listOfNotNull(+ GuideCachePolicy.cacheKey(providerId, channel)?.lookupKey,+ channel.epgChannelId?.trim()?.takeIf(String::isNotBlank)+ )+ }+ .toSet()val resolvedPrograms: Map<String, List<Program>> = runCatching {epgRepository.getResolvedProgramsForChannels(providerId, channelIds, windowStart, windowEnd)}.getOrElse { emptyMap() }+ .filterKeys { it !in sentinelLookupKeys }// 2. For channels not covered by resolution, fall back to legacy provider-native query.- val unresolvedChannels = channels.filter { channel ->+ val unresolvedChannels = channels.filterNot(GuideCachePolicy::isSentinelChannel).filter { channel ->val key = channel.guideLookupKey()key == null || resolvedPrograms[key].isNullOrEmpty()}@@ -1755,48 +1771,60 @@ class EpgViewModel @Inject constructor(channels: List<Channel>,existingProgramsByChannel: Map<String, List<Program>>) {+ if (guideFallbackJob?.isActive == true && guideFallbackContext == snapshotContext) {+ return+ }guideFallbackJob?.cancel()if (channels.isEmpty()) {+ guideFallbackContext = nullreturn}+ guideFallbackContext = snapshotContextguideFallbackJob = viewModelScope.launch {- val fallbackProgramsByChannel = buildMap {- channels.groupBy(Channel::providerId).forEach { (providerId, providerChannels) ->- val provider = providerRepository.getProvider(providerId) ?: return@forEach- val providerPrograms = fetchXtreamGuideFallback(- provider = provider,- providerId = providerId,- channels = providerChannels,- existingProgramsByChannel = existingProgramsByChannel + this,- windowStart = snapshotContext.guideWindowStart,- windowEnd = snapshotContext.guideWindowEnd- )- putAll(providerPrograms)- }- }- if (fallbackProgramsByChannel.isEmpty()) {- return@launch+ val fallbackProgramsByChannel = linkedMapOf<String, List<Program>>()+ channels.groupBy(Channel::providerId).forEach { (providerId, providerChannels) ->+ val provider = providerRepository.getProvider(providerId) ?: return@forEach+ val providerPrograms = fetchXtreamGuideFallback(+ provider = provider,+ providerId = providerId,+ channels = providerChannels,+ existingProgramsByChannel = existingProgramsByChannel + fallbackProgramsByChannel,+ windowStart = snapshotContext.guideWindowStart,+ windowEnd = snapshotContext.guideWindowEnd,+ onPartial = { partial ->+ fallbackProgramsByChannel.putAll(partial)+ publishGuideFallbackUpdate(snapshotContext, fallbackProgramsByChannel)+ }+ )+ fallbackProgramsByChannel.putAll(providerPrograms)}+ publishGuideFallbackUpdate(snapshotContext, fallbackProgramsByChannel)+ }+ }- baseGuideSnapshot.update { currentSnapshot ->- if (currentSnapshot == null || !currentSnapshot.matches(snapshotContext)) {- return@update currentSnapshot- }-- val mergedProgramsByChannel = currentSnapshot.baseProgramsByChannel + fallbackProgramsByChannel- val visibleChannels = currentSnapshot.visibleChannels- val channelsWithSchedule = countLiveGuideChannelsWithSchedule(visibleChannels, mergedProgramsByChannel)- val hasUpcomingData = hasUpcomingLiveGuideData(mergedProgramsByChannel, currentSnapshot.guideWindowStart)-- currentSnapshot.copy(- baseProgramsByChannel = mergedProgramsByChannel,- failedScheduleCount = countMissingLiveGuideEntries(visibleChannels, mergedProgramsByChannel),- lastUpdatedAt = System.currentTimeMillis(),- baseChannelsWithSchedule = channelsWithSchedule,- baseGuideStale = visibleChannels.isNotEmpty() && (channelsWithSchedule == 0 || !hasUpcomingData)- )+ private fun publishGuideFallbackUpdate(+ snapshotContext: GuideFallbackContext,+ fallbackProgramsByChannel: Map<String, List<Program>>+ ) {+ if (fallbackProgramsByChannel.isEmpty()) return+ baseGuideSnapshot.update { currentSnapshot ->+ if (currentSnapshot == null || !currentSnapshot.matches(snapshotContext)) {+ return@update currentSnapshot}++ val mergedProgramsByChannel = currentSnapshot.baseProgramsByChannel + fallbackProgramsByChannel+ val visibleChannels = currentSnapshot.visibleChannels+ val channelsWithSchedule = countLiveGuideChannelsWithSchedule(visibleChannels, mergedProgramsByChannel)+ val hasUpcomingData = hasUpcomingLiveGuideData(mergedProgramsByChannel, currentSnapshot.guideWindowStart)++ currentSnapshot.copy(+ baseProgramsByChannel = mergedProgramsByChannel,+ failedScheduleCount = countMissingLiveGuideEntries(visibleChannels, mergedProgramsByChannel),+ lastUpdatedAt = System.currentTimeMillis(),+ baseChannelsWithSchedule = channelsWithSchedule,+ baseGuideStale = visibleChannels.isNotEmpty() && (channelsWithSchedule == 0 || !hasUpcomingData)+ )}}@@ -1806,7 +1834,8 @@ class EpgViewModel @Inject constructor(channels: List<Channel>,existingProgramsByChannel: Map<String, List<Program>>,windowStart: Long,- windowEnd: Long+ windowEnd: Long,+ onPartial: suspend (Map<String, List<Program>>) -> Unit): Map<String, List<Program>> {if (provider.guideSourcePolicy == GuideSourcePolicy.EXTERNAL_ONLY ||provider.guideSourcePolicy == GuideSourcePolicy.DISABLED@@ -1820,41 +1849,92 @@ class EpgViewModel @Inject constructor(return emptyMap()}- val missingChannels = channels.filter { channel ->- val lookupKey = channel.guideLookupKey()- lookupKey != null &&- channel.streamId > 0L &&- existingProgramsByChannel[lookupKey].isNullOrEmpty()- }- if (missingChannels.isEmpty()) {+ ensurePersistedEmptyGuideKeys(providerId)+ val sentinelKeys = channels+ .filter(GuideCachePolicy::isSentinelChannel)+ .mapNotNull { channel -> GuideCachePolicy.cacheKey(providerId, channel)?.lookupKey }+ .toSet()+ markEmptyGuideKeys(providerId, sentinelKeys)++ val fallbackChannels = GuideCachePolicy.requestableChannels(+ providerId = providerId,+ channels = channels,+ sessionEmptyKeys = sessionEmptyGuideKeys,+ persistedEmptyAt = persistedEmptyGuideKeys[providerId].orEmpty(),+ existingProgramsByChannel = existingProgramsByChannel,+ now = System.currentTimeMillis()+ ).take(MAX_XTREAM_GUIDE_FALLBACK_CHANNELS)+ if (fallbackChannels.isEmpty()) {return emptyMap()}- val fallbackChannels = missingChannels.take(MAX_XTREAM_GUIDE_FALLBACK_CHANNELS)- val programsByRequest = providerRepository.getProgramsForLiveStreams(- providerId = providerId,- requests = fallbackChannels.map { channel ->+ val resolvedPrograms = linkedMapOf<String, List<Program>>()+ fallbackChannels.chunked(XTREAM_GUIDE_FALLBACK_CHUNK_SIZE).forEach { chunk ->+ val requests = chunk.map { channel ->LiveStreamProgramRequest(streamId = channel.streamId,epgChannelId = channel.epgChannelId)- },- limit = MAX_XTREAM_GUIDE_FALLBACK_PROGRAMS- )-- return fallbackChannels.mapNotNull { channel ->- val programs = (programsByRequest[- LiveStreamProgramRequest(+ }+ val programsByRequest = providerRepository.getProgramsForLiveStreams(+ providerId = providerId,+ requests = requests,+ limit = MAX_XTREAM_GUIDE_FALLBACK_PROGRAMS+ )+ val partial = linkedMapOf<String, List<Program>>()+ chunk.forEach { channel ->+ val request = LiveStreamProgramRequest(streamId = channel.streamId,epgChannelId = channel.epgChannelId)- ] as? com.streamvault.domain.model.Result.Success)?.data- .orEmpty()- .filter { program -> program.endTime > windowStart && program.startTime < windowEnd }- .sortedBy { program -> program.startTime }- val lookupKey = channel.guideLookupKey() ?: return@mapNotNull null- if (programs.isEmpty()) null else lookupKey to programs- }.toMap()+ val result = programsByRequest[request]+ val returnedPrograms = (result as? Result.Success)?.data.orEmpty()+ val programs = returnedPrograms+ .filter { program -> program.endTime > windowStart && program.startTime < windowEnd }+ .sortedBy(Program::startTime)+ val cacheKey = GuideCachePolicy.cacheKey(providerId, channel) ?: return@forEach+ if (result is Result.Success) {+ if (returnedPrograms.isEmpty()) {+ markEmptyGuideKeys(providerId, setOf(cacheKey.lookupKey))+ } else {+ clearEmptyGuideKeys(providerId, setOf(cacheKey.lookupKey))+ }+ }+ if (programs.isNotEmpty()) {+ partial[cacheKey.lookupKey] = programs+ }+ }+ resolvedPrograms.putAll(partial)+ onPartial(resolvedPrograms.toMap())+ }+ return resolvedPrograms+ }++ private suspend fun ensurePersistedEmptyGuideKeys(providerId: Long) {+ if (providerId !in persistedEmptyGuideKeys) {+ persistedEmptyGuideKeys[providerId] = preferencesRepository.getEmptyGuideKeys(providerId)+ }+ }++ private suspend fun markEmptyGuideKeys(providerId: Long, lookupKeys: Set<String>) {+ if (lookupKeys.isEmpty()) return+ val now = System.currentTimeMillis()+ lookupKeys.forEach { lookupKey ->+ sessionEmptyGuideKeys += GuideCacheKey(providerId, lookupKey)+ }+ persistedEmptyGuideKeys[providerId] = persistedEmptyGuideKeys[providerId].orEmpty() ++ lookupKeys.associateWith { now }+ preferencesRepository.addEmptyGuideKeys(providerId, lookupKeys)+ }++ private suspend fun clearEmptyGuideKeys(providerId: Long, lookupKeys: Set<String>) {+ if (lookupKeys.isEmpty()) return+ lookupKeys.forEach { lookupKey ->+ sessionEmptyGuideKeys.remove(GuideCacheKey(providerId, lookupKey))+ }+ persistedEmptyGuideKeys[providerId] = persistedEmptyGuideKeys[providerId].orEmpty()+ .filterKeys { it !in lookupKeys }+ preferencesRepository.removeEmptyGuideKeys(providerId, lookupKeys)}private fun GuideBaseSnapshot.matches(context: GuideFallbackContext): Boolean =diff --git a/feature/live/src/main/java/com/streamvault/feature/live/home/HomeViewModel.kt b/feature/live/src/main/java/com/streamvault/feature/live/home/HomeViewModel.ktindex 4e71d057..c5053187 100644--- a/feature/live/src/main/java/com/streamvault/feature/live/home/HomeViewModel.kt+++ b/feature/live/src/main/java/com/streamvault/feature/live/home/HomeViewModel.kt@@ -11,6 +11,8 @@ import com.streamvault.feature.live.api.LiveSurfaceRefreshPortimport com.streamvault.domain.policy.applyProviderCategoryDisplayPreferencesimport com.streamvault.domain.playback.orderedByRequestedRawIdsimport com.streamvault.feature.live.presentation.model.guideLookupKey+import com.streamvault.feature.live.presentation.model.GuideCacheKey+import com.streamvault.feature.live.presentation.model.GuideCachePolicyimport com.streamvault.domain.model.LiveTvChannelModeimport com.streamvault.domain.model.LiveTvQuickFilterVisibilityModeimport com.streamvault.data.preferences.PreferencesRepository@@ -127,6 +129,8 @@ class HomeViewModel @Inject constructor(private var previewPlayerEngine: PlayerEngine? = nullprivate var previewSessionVersion: Long = 0Lprivate var combinedCategoriesById: Map<Long, CombinedCategory> = emptyMap()+ private val sessionEmptyGuideKeys = mutableSetOf<GuideCacheKey>()+ private val persistedEmptyGuideKeys = mutableMapOf<Long, Map<String, Long>>()init {loadAllProviders()@@ -1288,7 +1292,7 @@ class HomeViewModel @Inject constructor(channels: List<Channel>,existingPrograms: Map<String, Program>): Map<String, Program> {- val providerType = _uiState.value.provider?.type+ val providerType = providerRepository.getProvider(providerId)?.typeif (providerType != com.streamvault.domain.model.ProviderType.XTREAM_CODES &&providerType != com.streamvault.domain.model.ProviderType.STALKER_PORTAL@@ -1296,18 +1300,26 @@ class HomeViewModel @Inject constructor(return emptyMap()}- val missingChannels = channels.filter { channel ->- val lookupKey = channel.guideLookupKey()- lookupKey != null &&- channel.streamId > 0L &&- !existingPrograms.containsKey(lookupKey)- }- if (missingChannels.isEmpty()) {+ ensurePersistedEmptyGuideKeys(providerId)+ val sentinelKeys = channels+ .filter(GuideCachePolicy::isSentinelChannel)+ .mapNotNull { channel -> GuideCachePolicy.cacheKey(providerId, channel)?.lookupKey }+ .toSet()+ markEmptyGuideKeys(providerId, sentinelKeys)++ val fallbackChannels = GuideCachePolicy.requestableChannels(+ providerId = providerId,+ channels = channels,+ sessionEmptyKeys = sessionEmptyGuideKeys,+ persistedEmptyAt = persistedEmptyGuideKeys[providerId].orEmpty(),+ existingProgramsByChannel = existingPrograms.mapValues { (_, program) -> listOf(program) },+ now = System.currentTimeMillis()+ ).take(10)+ if (fallbackChannels.isEmpty()) {return emptyMap()}val now = System.currentTimeMillis()- val fallbackChannels = missingChannels.take(10)val programsByRequest = providerRepository.getProgramsForLiveStreams(providerId = providerId,requests = fallbackChannels.map { channel ->@@ -1320,19 +1332,54 @@ class HomeViewModel @Inject constructor()return fallbackChannels.mapNotNull { channel ->- val programs = (programsByRequest[+ val result = programsByRequest[LiveStreamProgramRequest(streamId = channel.streamId,epgChannelId = channel.epgChannelId)- ] as? Result.Success)?.data.orEmpty()+ ]+ val programs = (result as? Result.Success)?.data.orEmpty()+ val cacheKey = GuideCachePolicy.cacheKey(providerId, channel) ?: return@mapNotNull null+ if (result is Result.Success) {+ if (programs.isEmpty()) {+ markEmptyGuideKeys(providerId, setOf(cacheKey.lookupKey))+ } else {+ clearEmptyGuideKeys(providerId, setOf(cacheKey.lookupKey))+ }+ }val currentProgram = programs.firstOrNull { it.startTime <= now && it.endTime > now }?: programs.firstOrNull()- val lookupKey = channel.guideLookupKey() ?: return@mapNotNull null- currentProgram?.let { lookupKey to it }+ currentProgram?.let { cacheKey.lookupKey to it }}.toMap()}+ private suspend fun ensurePersistedEmptyGuideKeys(providerId: Long) {+ if (providerId !in persistedEmptyGuideKeys) {+ persistedEmptyGuideKeys[providerId] = preferencesRepository.getEmptyGuideKeys(providerId)+ }+ }++ private suspend fun markEmptyGuideKeys(providerId: Long, lookupKeys: Set<String>) {+ if (lookupKeys.isEmpty()) return+ val now = System.currentTimeMillis()+ lookupKeys.forEach { lookupKey ->+ sessionEmptyGuideKeys += GuideCacheKey(providerId, lookupKey)+ }+ persistedEmptyGuideKeys[providerId] = persistedEmptyGuideKeys[providerId].orEmpty() ++ lookupKeys.associateWith { now }+ preferencesRepository.addEmptyGuideKeys(providerId, lookupKeys)+ }++ private suspend fun clearEmptyGuideKeys(providerId: Long, lookupKeys: Set<String>) {+ if (lookupKeys.isEmpty()) return+ lookupKeys.forEach { lookupKey ->+ sessionEmptyGuideKeys.remove(GuideCacheKey(providerId, lookupKey))+ }+ persistedEmptyGuideKeys[providerId] = persistedEmptyGuideKeys[providerId].orEmpty()+ .filterKeys { it !in lookupKeys }+ preferencesRepository.removeEmptyGuideKeys(providerId, lookupKeys)+ }+fun updateVisibleChannelWindow(channelIds: List<Long>, focusedChannelId: Long? = null) {val combinedIds = buildSet {addAll(channelIds)diff --git a/feature/live/src/main/java/com/streamvault/feature/live/presentation/model/GuideCachePolicy.kt b/feature/live/src/main/java/com/streamvault/feature/live/presentation/model/GuideCachePolicy.ktnew file mode 100644index 00000000..393a7e03--- /dev/null+++ b/feature/live/src/main/java/com/streamvault/feature/live/presentation/model/GuideCachePolicy.kt@@ -0,0 +1,48 @@+package com.streamvault.feature.live.presentation.model++import com.streamvault.domain.model.Channel++data class GuideCacheKey(+ val providerId: Long,+ val lookupKey: String+)++object GuideCachePolicy {+ const val GUIDE_EMPTY_KEY_TTL_MILLIS = 24L * 60L * 60L * 1000L+ private const val SENTINEL_GLOTV = "glotv"++ fun cacheKey(providerId: Long, channel: Channel): GuideCacheKey? =+ channel.guideLookupKey()?.let { lookupKey ->+ GuideCacheKey(providerId = providerId, lookupKey = lookupKey)+ }++ fun isSentinelChannel(channel: Channel): Boolean =+ channel.epgChannelId+ ?.trim()+ ?.equals(SENTINEL_GLOTV, ignoreCase = true) == true++ fun isEmptyKeyFresh(+ persistedEmptyAt: Map<String, Long>,+ lookupKey: String,+ now: Long+ ): Boolean = persistedEmptyAt[lookupKey]?.let { timestamp ->+ timestamp > 0L && now - timestamp < GUIDE_EMPTY_KEY_TTL_MILLIS+ } == true++ fun requestableChannels(+ providerId: Long,+ channels: List<Channel>,+ sessionEmptyKeys: Set<GuideCacheKey>,+ persistedEmptyAt: Map<String, Long>,+ existingProgramsByChannel: Map<String, List<*>>,+ now: Long+ ): List<Channel> = channels.filter { channel ->+ val cacheKey = cacheKey(providerId, channel)+ cacheKey != null &&+ !isSentinelChannel(channel) &&+ channel.streamId > 0L &&+ cacheKey !in sessionEmptyKeys &&+ !isEmptyKeyFresh(persistedEmptyAt, cacheKey.lookupKey, now) &&+ existingProgramsByChannel[cacheKey.lookupKey].isNullOrEmpty()+ }+}diff --git a/feature/live/src/test/java/com/streamvault/feature/live/presentation/model/GuideCachePolicyTest.kt b/feature/live/src/test/java/com/streamvault/feature/live/presentation/model/GuideCachePolicyTest.ktnew file mode 100644index 00000000..1e6d13a1--- /dev/null+++ b/feature/live/src/test/java/com/streamvault/feature/live/presentation/model/GuideCachePolicyTest.kt@@ -0,0 +1,86 @@+package com.streamvault.feature.live.presentation.model++import com.google.common.truth.Truth.assertThat+import com.streamvault.domain.model.Channel+import org.junit.Test++class GuideCachePolicyTest {+ @Test+ fun emptyKeyFromAnotherProviderDoesNotSuppressRequest() {+ val channel = Channel(+ id = 2L,+ name = "Provider two",+ providerId = 2L,+ streamId = 42L+ )++ val requestable = GuideCachePolicy.requestableChannels(+ providerId = 2L,+ channels = listOf(channel),+ sessionEmptyKeys = setOf(GuideCacheKey(providerId = 1L, lookupKey = "42")),+ persistedEmptyAt = emptyMap(),+ existingProgramsByChannel = emptyMap(),+ now = 1_000L+ )++ assertThat(requestable).containsExactly(channel)+ }++ @Test+ fun sentinelUsesRawEpgIdEvenWhenStreamIdIsTheLookupKey() {+ val channel = Channel(+ id = 1L,+ name = "Sentinel",+ epgChannelId = " GLOTV ",+ providerId = 1L,+ streamId = 42L+ )++ assertThat(GuideCachePolicy.isSentinelChannel(channel)).isTrue()+ assertThat(GuideCachePolicy.cacheKey(1L, channel))+ .isEqualTo(GuideCacheKey(providerId = 1L, lookupKey = "42"))+ }++ @Test+ fun expiredPersistedEmptyKeyDoesNotSuppressRequest() {+ val channel = Channel(+ id = 1L,+ name = "Expired",+ providerId = 1L,+ streamId = 42L+ )++ val requestable = GuideCachePolicy.requestableChannels(+ providerId = 1L,+ channels = listOf(channel),+ sessionEmptyKeys = emptySet(),+ persistedEmptyAt = mapOf("42" to 1_000L),+ existingProgramsByChannel = emptyMap(),+ now = 1_000L + GuideCachePolicy.GUIDE_EMPTY_KEY_TTL_MILLIS+ )++ assertThat(requestable).containsExactly(channel)+ }++ @Test+ fun sentinelChannelIsNeverRequestable() {+ val channel = Channel(+ id = 1L,+ name = "Sentinel",+ epgChannelId = "glotv",+ providerId = 1L,+ streamId = 42L+ )++ val requestable = GuideCachePolicy.requestableChannels(+ providerId = 1L,+ channels = listOf(channel),+ sessionEmptyKeys = emptySet(),+ persistedEmptyAt = emptyMap(),+ existingProgramsByChannel = emptyMap(),+ now = 1_000L+ )++ assertThat(requestable).isEmpty()+ }+}