package tv.tivilux.nativeplayer import android.app.Application import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.mutableStateMapOf import androidx.compose.runtime.setValue import androidx.compose.runtime.snapshots.Snapshot import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.viewModelScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.async import kotlinx.coroutines.awaitAll import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import kotlinx.coroutines.sync.Semaphore import kotlinx.coroutines.sync.withPermit import tv.tivilux.nativeplayer.data.AppUpdateInfo import tv.tivilux.nativeplayer.data.AppUpdateManager import tv.tivilux.nativeplayer.data.CredentialStore import tv.tivilux.nativeplayer.data.LibraryStore import tv.tivilux.nativeplayer.data.ProfileStore import tv.tivilux.nativeplayer.data.PlaybackStore import tv.tivilux.nativeplayer.data.SettingsStore import tv.tivilux.nativeplayer.data.StartupCacheStore import tv.tivilux.nativeplayer.data.FastCacheMeta import tv.tivilux.nativeplayer.data.FastLiveCache import tv.tivilux.nativeplayer.data.FastLibraryCache import tv.tivilux.nativeplayer.data.FastEpgCache import tv.tivilux.nativeplayer.data.StartupSnapshot import tv.tivilux.nativeplayer.data.SportsScheduleRepository import tv.tivilux.nativeplayer.data.XtreamRepository import tv.tivilux.nativeplayer.model.AppSettings import tv.tivilux.nativeplayer.model.Category import tv.tivilux.nativeplayer.model.ContentType import tv.tivilux.nativeplayer.model.Credentials import tv.tivilux.nativeplayer.model.EpgProgram import tv.tivilux.nativeplayer.model.MediaEntry import tv.tivilux.nativeplayer.model.HouseholdProfile import tv.tivilux.nativeplayer.model.PlaybackProgress import tv.tivilux.nativeplayer.model.MovieDetail import tv.tivilux.nativeplayer.model.SeriesDetail import tv.tivilux.nativeplayer.model.SportLeague import tv.tivilux.nativeplayer.model.SportsEvent import tv.tivilux.nativeplayer.model.SportsLeagueSummary import tv.tivilux.nativeplayer.model.SessionInfo import java.util.Locale import java.util.Calendar class TiviLuxViewModel(application: Application) : AndroidViewModel(application) { private val repository = XtreamRepository() private val sportsScheduleRepository = SportsScheduleRepository() private val credentialStore = CredentialStore(application) private val profileStore = ProfileStore(application) private val playbackStore = PlaybackStore(application) private val libraryStore = LibraryStore(application).apply { setActiveProfile(profileStore.activeProfile().id) } private val settingsStore = SettingsStore(application) private val startupCacheStore = StartupCacheStore(application) private val updateManager = AppUpdateManager(application) private val maintenancePrefs = application.getSharedPreferences("tivilux_maintenance", android.content.Context.MODE_PRIVATE) // Only a channel ID is persisted, scoped to the signed-in provider account. // No playback URL or credentials are written to these preferences. private val startupChannelPrefs = application.getSharedPreferences("tivilux_last_live", android.content.Context.MODE_PRIVATE) private fun lastChannelKey(creds: Credentials): String = "channel_" + (creds.serverUrl.trimEnd('/') + "|" + creds.username).hashCode().toString() private fun rememberedLiveChannel(creds: Credentials, channels: List): MediaEntry? { val id = startupChannelPrefs.getString(lastChannelKey(creds), null) ?: return null return channels.firstOrNull { it.id.toString() == id && isVisibleContent(it) } } private fun resumeLastLiveAfterAuth(creds: Credentials) { if (session == null) return // Never autoplay from cache before provider authorization. val channels = allLiveChannels val last = rememberedLiveChannel(creds, channels) if (last != null) play(last, AppScreen.LIVE) else currentScreen = AppScreen.LIVE // Deleted/unavailable channel: show guide, not black video. } private val epgLoadingIds = mutableSetOf() // Limit background guide fetches so rapid D-pad scrolling never creates a wall of // simultaneous HTTP work on lower-power Android TV hardware. private val epgFetchGate = Semaphore(2) // Provider-wide VOD catalogs can be enormous. Some XUI panels return only a tiny // sample for get_vod_streams/get_series unless a category_id is supplied. A shared // gate lets Movies + Series repair in parallel without flooding the provider. private val catalogFetchGate = Semaphore(4) private val catalogRepairRunning = mutableSetOf() // Sports owns its own lightweight revision counter so unrelated TV-guide updates // do not force the entire Sports Hub to rebuild on every EPG row that arrives. private var sportsEpgRevision = 0L // Official schedule changes are tracked separately from provider/EPG changes. v0.4.40 // used the EPG revision for both, which could trigger repeated full Sports rebuilds while // six official leagues were warming in the background and starve video/input on TV boxes. private var sportsOfficialRevision = 0L private var sportsEventsCacheRevision = -1L private var sportsEventsCache by mutableStateOf>(emptyList()) private var sportsSummariesCacheRevision = -1L private var sportsSummariesCache by mutableStateOf>(emptyList()) private var sportsDerivedBuildJob: Job? = null private var sportsPrefetchJob: Job? = null // Lightweight score-only polling while Game Center is visible. This never rescans Xtream, // EPG, feed matches, or playback sources; it only patches official score/status metadata. private var sportsLiveScoreJob: Job? = null private var sportsChannelIndex: Map = emptyMap() private var sportsChannelsByLeague: Map> = emptyMap() private var allSportsChannels: List = emptyList() private val sportsLastLeagueScanEpoch = mutableMapOf() private var officialSportsSchedule by mutableStateOf>(emptyList()) private var sportsOfficialScheduleLastFetchEpoch = 0L private var sportsOfficialScheduleLoading = false var sportsBackgroundLoading by mutableStateOf(false) private set var sportsBackgroundCategory by mutableStateOf("") private set var sportsBackgroundReady by mutableStateOf(false) private set private val catalogCache = mutableMapOf, List>() private val visibleCatalogCache = mutableMapOf>() private data class OrderedCategorySnapshot( val source: List, val revision: Long, val ordered: List, ) private val orderedCategoryCache = mutableMapOf() private val visibleCategoryCache = mutableMapOf>() private val movieDetailCache = mutableMapOf() private val seriesDetailCache = mutableMapOf() private val favoritesCategoryId = "__tivilux_favorites__" private var hiddenCategoryCache: Map> = mapOf( ContentType.LIVE to libraryStore.hiddenCategoryIds(ContentType.LIVE), ContentType.MOVIE to libraryStore.hiddenCategoryIds(ContentType.MOVIE), ContentType.SERIES to libraryStore.hiddenCategoryIds(ContentType.SERIES), ) private var hiddenLiveChannelCache: Set = libraryStore.hiddenLiveChannelIds() private fun refreshContentVisibilityCache() { visibleCatalogCache.clear() orderedCategoryCache.clear() visibleCategoryCache.clear() hiddenCategoryCache = mapOf( ContentType.LIVE to libraryStore.hiddenCategoryIds(ContentType.LIVE), ContentType.MOVIE to libraryStore.hiddenCategoryIds(ContentType.MOVIE), ContentType.SERIES to libraryStore.hiddenCategoryIds(ContentType.SERIES), ) hiddenLiveChannelCache = libraryStore.hiddenLiveChannelIds() } // Search is deliberately indexed separately from Compose state. The old path flattened, // de-duplicated and lower-cased the entire loaded library every time the query changed. // On 30k+ Movies / 9k+ Series that can turn text entry into visible remote lag. private data class SearchIndexEntry(val item: MediaEntry, val normalizedName: String) private data class SearchIndexStamp( val liveIdentity: Int, val liveSize: Int, val movieIdentity: Int, val movieSize: Int, val seriesIdentity: Int, val seriesSize: Int, val visibilityRevision: Long, ) private var searchIndexStamp: SearchIndexStamp? = null private var searchIndex: List = emptyList() private var searchJob: Job? = null var credentials by mutableStateOf(credentialStore.load()) private set var session by mutableStateOf(null) private set var settings by mutableStateOf(settingsStore.load()) private set var profiles by mutableStateOf(profileStore.profiles()) private set var activeProfile by mutableStateOf(profileStore.activeProfile()) private set var favoriteKeysState by mutableStateOf(libraryStore.favoriteKeys()) private set var playbackRevision by mutableStateOf(0L) private set var guideOrderRevision by mutableStateOf(0L) private set var contentVisibilityRevision by mutableStateOf(0L) private set private var playbackNextItem: MediaEntry? = null // Do not render Home/Guide during returning-viewer last-channel restoration. var restoringLastLive by mutableStateOf(credentials != null) private set var currentScreen by mutableStateOf(AppScreen.HOME) private set var previousScreen by mutableStateOf(AppScreen.HOME) private set private var detailReturnScreen by mutableStateOf(AppScreen.HOME) var loading by mutableStateOf(false) private set var error by mutableStateOf(null) private set var availableUpdate by mutableStateOf(null) private set var updateDownloading by mutableStateOf(false) private set var updateProgress by mutableStateOf(0) private set var updateStatus by mutableStateOf(null) private set var updateError by mutableStateOf(null) private set private var pendingUpdateAfterPermission: AppUpdateInfo? = null var startupLoading by mutableStateOf(false) private set var startupStage by mutableStateOf(StartupStage.LIVE) private set var startupProgress by mutableStateOf(0f) private set var startupDetail by mutableStateOf("Preparing your television") private set var startupLiveCount by mutableStateOf(0) private set var startupEpgCompleted by mutableStateOf(0) private set var startupEpgFound by mutableStateOf(0) private set var startupEpgTotal by mutableStateOf(0) private set var startupMovieCount by mutableStateOf(0) private set var startupSeriesCount by mutableStateOf(0) private set var categories by mutableStateOf>>(emptyMap()) private set var catalogs by mutableStateOf>>(emptyMap()) private set // Preserve the provider's complete Live TV lineup even when the guide is filtered // to a single category. Sports Hub always searches the full active playlist. var allLiveChannels by mutableStateOf>(emptyList()) private set var selectedCategories by mutableStateOf>(emptyMap()) private set var selectedSportsLeague by mutableStateOf(SportLeague.ALL) private set var sportsScanning by mutableStateOf(false) private set var sportsScanCompleted by mutableStateOf(0) private set var sportsScanTotal by mutableStateOf(0) private set var sportsLastScanEpoch by mutableStateOf(0L) private set var sportsPreparing by mutableStateOf(false) private set var sportsLoadingStage by mutableStateOf("Loading TiviLux Game Center…") private set var sportsReadyNoticeToken by mutableStateOf(0L) private set var sportsReadyNoticePending by mutableStateOf(false) private set private var sportsLoadCycle = 0L private var sportsReadyCycle = -1L private var sportsLoadCycleInProgress = false var selectedChannel by mutableStateOf(null) private set // One-shot guide entry anchor. Normal Live TV navigation leaves this null so the // alphabetically/provider-sorted guide opens at row 1. Returning from fullscreen or // Sports sets the actual playing channel so the guide returns to that exact stream. var guideOpenAnchorChannelId by mutableStateOf(null) private set // True only while the TV focus/list is actively moving. Heavy guide/network/cache work // yields to this flag so a held D-pad can never build a background-work backlog. private var guideInteractionBusy: Boolean = false // The channel that is actually playing in the Live TV preview. This is // intentionally separate from D-pad focus so browsing the guide never retunes video. var tunedChannel by mutableStateOf(null) private set var previousTunedChannel by mutableStateOf(null) private set var recentLiveChannels by mutableStateOf>(emptyList()) private set // SnapshotStateMap updates one guide entry in-place instead of copying the entire // EPG map every time a channel finishes loading. This is a major TV-guide smoothness win. val epgByChannel = mutableStateMapOf>() var playingItem by mutableStateOf(null) private set var playingUrl by mutableStateOf(null) private set var playingUrlCandidates by mutableStateOf>(emptyList()) private set // Session-only MultiView state. Keeping the four selections in the ViewModel means a // viewer can long-OK one tile to fullscreen and return without losing the other feeds. var multiViewSlots by mutableStateOf>(List(4) { null }) private set private var multiViewReturnScreen: AppScreen = AppScreen.LIVE var selectedMovieDetail by mutableStateOf(null) private set var selectedSeriesDetail by mutableStateOf(null) private set var searchQuery by mutableStateOf("") private set var searchResultsState by mutableStateOf>(emptyList()) private set init { credentials?.let { reconnect(it) } } fun clearError() { error = null } fun login(server: String, username: String, password: String) { val creds = Credentials(server.trim(), username.trim(), password) if (creds.serverUrl.isBlank() || creds.username.isBlank() || creds.password.isBlank()) { error = "Server, username and password are required." return } restoringLastLive = false reconnect(creds, save = true) } private fun reconnect(creds: Credentials, save: Boolean = false) { viewModelScope.launch { loading = true error = null // Classic startup: show the existing percentage screen on every launch. // Never start a remembered stream until the viewer explicitly selects it. startupLoading = true restoringLastLive = false startupStage = StartupStage.LIVE startupProgress = 0f startupDetail = "Loading Live TV channels" try { val authenticated = withContext(Dispatchers.IO) { repository.authenticate(creds) } credentials = creds session = authenticated if (save) credentialStore.save(creds) runStartupLoad(creds) currentScreen = when { profiles.size > 1 -> AppScreen.PROFILES else -> AppScreen.HOME } viewModelScope.launch { val updateJitterMs = 2_000L + ((creds.username.hashCode().toLong() and 0x7fffffffL) % 18_000L) delay(updateJitterMs) checkForUpdates(silent = true) } } catch (t: Throwable) { if (save) { credentialStore.clear() error = t.message ?: "Unable to connect to provider." } else { credentials = creds error = t.message ?: "Connection temporarily unavailable — retrying." // Keep existing cached/offline fallback and retry behavior, but never autoplay. runCatching { runStartupLoad(creds) } currentScreen = AppScreen.HOME scheduleReconnect(creds) } } finally { restoringLastLive = false startupLoading = false loading = false scheduleSportsWarmupAfterStartup() } } } private fun scheduleReconnect(creds: Credentials) { viewModelScope.launch { var waitMs = 2_000L repeat(8) { delay(waitMs) if (credentials != creds || session != null) return@launch val authenticated = runCatching { repository.authenticate(creds) }.getOrNull() if (authenticated != null) { session = authenticated error = null if (allLiveChannels.isEmpty()) { runCatching { runStartupLoad(creds) } } // Classic startup: reconnect must not autoplay the last-watched channel. return@launch } waitMs = (waitMs * 2).coerceAtMost(30_000L) } } } private suspend fun runStartupLoad(creds: Credentials) { startupStage = StartupStage.LIVE startupProgress = 0f startupDetail = "Loading complete Live TV lineup" startupLiveCount = 0 startupEpgCompleted = 0 startupEpgFound = 0 startupEpgTotal = 0 startupMovieCount = 0 startupSeriesCount = 0 // 0.4.x ultra-fast cached launch. The cache is segmented so Home only waits for // the lightweight Live TV segment. The huge EPG/Movie/Series segments hydrate // in parallel after Home is already responsive. val fastMeta = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) { startupCacheStore.loadMeta(creds) } if (fastMeta != null) { val fastLive = withContext(Dispatchers.IO) { startupCacheStore.loadLive(creds) } if (fastLive != null && fastLive.channels.isNotEmpty()) { applyFastLiveCache(fastLive, fastMeta) startupStage = StartupStage.LIVE startupLiveCount = fastLive.channels.size startupProgress = 1f startupDetail = "${fastLive.channels.size} Live TV channels loaded" // Build 122: a returning viewer has a valid local Live TV snapshot. // Do not block Home on inflating the large EPG and VOD gzip files. // Keep the classic progress screen for first-time library creation. startupStage = StartupStage.EPG startupProgress = 1f startupDetail = "Restoring saved TV guide" startupStage = StartupStage.LIBRARY startupProgress = 1f startupDetail = "Restoring saved Movies & Series" startupStage = StartupStage.READY startupDetail = "TiviLux ready • saved library restoring" viewModelScope.launch { // Allow the caller to switch to Home before heavy cache inflation. // A cancellation (logout/account change) cancels this job as usual. kotlinx.coroutines.yield() if (credentials != creds) return@launch val cachedEpg = withContext(Dispatchers.IO) { startupCacheStore.loadEpg(creds) } if (credentials != creds) return@launch if (cachedEpg != null && cachedEpg.guide.isNotEmpty()) { applyEpgGuideSmoothly(cachedEpg.guide, clearExisting = false) startupEpgTotal = fastLive.channels.size startupEpgCompleted = fastLive.channels.size startupEpgFound = fastLive.channels.count { cachedEpg.guide[it.id].orEmpty().isNotEmpty() } } val cachedMovies = withContext(Dispatchers.IO) { startupCacheStore.loadMovies(creds) } if (credentials != creds) return@launch cachedMovies?.let { part -> if (part.categories.isNotEmpty()) categories = categories + (ContentType.MOVIE to part.categories) val movies = mergeCatalogWithoutShrinking(catalogCache[ContentType.MOVIE to null].orEmpty(), part.entries) catalogCache[ContentType.MOVIE to null] = movies catalogs = catalogs + (ContentType.MOVIE to filterMaster(movies, selectedCategories[ContentType.MOVIE])) startupMovieCount = movies.size } val cachedSeries = withContext(Dispatchers.IO) { startupCacheStore.loadSeries(creds) } if (credentials != creds) return@launch cachedSeries?.let { part -> if (part.categories.isNotEmpty()) categories = categories + (ContentType.SERIES to part.categories) val series = mergeCatalogWithoutShrinking(catalogCache[ContentType.SERIES to null].orEmpty(), part.entries) catalogCache[ContentType.SERIES to null] = series catalogs = catalogs + (ContentType.SERIES to filterMaster(series, selectedCategories[ContentType.SERIES])) startupSeriesCount = series.size } } // Preserve deferred refreshes without holding the startup screen open. viewModelScope.launch { val cacheAgeMs = System.currentTimeMillis() - fastMeta.savedAtMillis if (cacheAgeMs < 20L * 60L * 1000L) return@launch val staggerMs = 45_000L + ((creds.username.hashCode().toLong() and 0x7fffffffL) % 75_000L) delay(staggerMs) refreshStartupCacheInBackground(creds) } scheduleCompletenessSweep(creds) return } } // Upgrade compatibility: 0.3.x stored one large cache file. Use it once, then // persistStartupSnapshot() converts it to the segmented 0.4.x format. val cachedSnapshot = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) { startupCacheStore.load(creds) } cachedSnapshot?.let { cached -> applyStartupSnapshot(cached) // One-time migration to the segmented v0.4 cache happens directly from the // legacy object so we do not have to push its entire EPG through Compose first. viewModelScope.launch(kotlinx.coroutines.Dispatchers.IO) { startupCacheStore.save(creds, cached.copy(savedAtMillis = System.currentTimeMillis())) } startupStage = StartupStage.READY startupDetail = "Local library ready • optimizing cache" delay(25) viewModelScope.launch { // Hydrate the cached guide in small UI-friendly chunks after Home is shown. applyEpgGuideSmoothly(cached.epgByChannel, clearExisting = true) val staggerMs = 30_000L + ((creds.username.hashCode().toLong() and 0x7fffffffL) % 60_000L) delay(staggerMs) refreshStartupCacheInBackground(creds) } scheduleCompletenessSweep(creds) return } // Kick off the complete Movies + Series catalogs immediately. They now download // at the same time as Live TV instead of waiting for the Live lineup first. val libraryPrefetch = viewModelScope.async { coroutineScope { val movieCategoriesJob = async { runCatching { categories[ContentType.MOVIE].orEmpty().ifEmpty { repository.categories(creds, ContentType.MOVIE) } }.getOrDefault(emptyList()) } val seriesCategoriesJob = async { runCatching { categories[ContentType.SERIES].orEmpty().ifEmpty { repository.categories(creds, ContentType.SERIES) } }.getOrDefault(emptyList()) } val moviesJob = async { runCatching { catalogCache[ContentType.MOVIE to null] ?: repository.catalog(creds, ContentType.MOVIE, null) } .getOrDefault(emptyList()) } val seriesJob = async { runCatching { catalogCache[ContentType.SERIES to null] ?: repository.catalog(creds, ContentType.SERIES, null) } .getOrDefault(emptyList()) } Pair( Pair(movieCategoriesJob.await(), moviesJob.await()), Pair(seriesCategoriesJob.await(), seriesJob.await()), ) } } // 1) Pull the complete Live TV catalog and its groups in parallel. val liveData = coroutineScope { val categoriesJob = async { categories[ContentType.LIVE].orEmpty().ifEmpty { repository.categories(creds, ContentType.LIVE) } } val channelsJob = async { catalogCache[ContentType.LIVE to null] ?: repository.catalog(creds, ContentType.LIVE, null) } categoriesJob.await() to channelsJob.await() } val liveCategories = liveData.first val liveList = liveData.second categories = categories + (ContentType.LIVE to liveCategories) catalogCache[ContentType.LIVE to null] = liveList liveList.groupBy { it.categoryId }.forEach { (categoryId, entries) -> if (categoryId.isNotBlank()) catalogCache[ContentType.LIVE to categoryId] = entries } catalogs = catalogs + (ContentType.LIVE to liveList) allLiveChannels = liveList rebuildSportsChannelIndex() selectedCategories = selectedCategories + (ContentType.LIVE to null) selectedChannel = rememberedLiveChannel(creds, liveList) ?: liveList.firstOrNull() if (tunedChannel == null) tunedChannel = selectedChannel startupLiveCount = liveList.size startupDetail = "${liveList.size} Live TV channels loaded" startupProgress = 1f // 2) Prime the guide without making first launch wait for a full-account XMLTV // parse. Large providers can expose tens of thousands of programmes and forcing // that entire file to finish before Home makes the APK feel hung. Give the bulk // XMLTV path a short startup budget; if it does not complete quickly, open Home // with on-demand EPG and finish the exact full-account count in the background. startupStage = StartupStage.EPG startupProgress = 0.12f startupEpgTotal = liveList.size startupDetail = "Starting EPG / TV guide" val quickGuide = runCatching { repository.fullEpg( credentials = creds, channels = liveList, // Build 82: never strand a cold/first launch on "Preparing TV Guide". // If the provider XMLTV cannot be indexed inside this startup budget, // Home opens and the complete guide finishes via the background path below. maxWorkMillis = 2_000L, ) }.getOrNull() if (!quickGuide.isNullOrEmpty()) { applyEpgGuideSmoothly(quickGuide, clearExisting = true) startupEpgCompleted = liveList.size startupEpgFound = liveList.count { epgByChannel[it.id].orEmpty().isNotEmpty() } startupProgress = 1f startupDetail = "$startupEpgFound of ${liveList.size} channels have EPG data" } else { // Do not perform thousands of get_short_epg calls on the blocking startup // screen. The guide already knows how to fetch visible/focused channels on // demand, while the complete XMLTV index continues after Home is usable. startupEpgCompleted = epgByChannel.size startupEpgFound = liveList.count { epgByChannel[it.id].orEmpty().isNotEmpty() } startupProgress = 1f startupDetail = "TV guide ready • complete EPG indexing continues in background" } // 3) Pull the ENTIRE VOD + Series catalogs (not just one category) and their // category lists in parallel. Category switching later filters these local // master lists, which gives an exact total and removes repeat provider calls. startupStage = StartupStage.LIBRARY startupProgress = .08f startupDetail = "Scanning complete Movies & Series libraries" val libraryData = libraryPrefetch.await() val movieCategories = libraryData.first.first val movies = libraryData.first.second val seriesCategories = libraryData.second.first val series = libraryData.second.second categories = categories + mapOf( ContentType.MOVIE to movieCategories, ContentType.SERIES to seriesCategories, ) catalogCache[ContentType.MOVIE to null] = movies catalogCache[ContentType.SERIES to null] = series // Keep cold startup light: category lists are derived lazily from the master // catalogs on first open instead of building two huge indexes on the launch path. catalogs = catalogs + mapOf( ContentType.MOVIE to movies, ContentType.SERIES to series, ) selectedCategories = selectedCategories + mapOf( ContentType.MOVIE to null, ContentType.SERIES to null, ) startupMovieCount = movies.size startupSeriesCount = series.size startupProgress = 1f startupDetail = "${movies.size} movies • ${series.size} series • complete catalogs ready" persistStartupSnapshot(creds) startupStage = StartupStage.READY // If the full XMLTV guide did not fit inside the short startup budget, finish it // after Home opens. When complete we update the exact EPG count and replace the // on-device snapshot so the next launch is instant. if (quickGuide.isNullOrEmpty() && liveList.isNotEmpty()) { viewModelScope.launch { // Give the viewer the first interaction window before the CPU-heavy full // XMLTV parse begins. Visible guide rows still fetch instantly on demand. delay(30_000) refreshFullEpgInBackground(creds, liveList) } } scheduleCompletenessSweep(creds) delay(50) } private suspend fun awaitBackgroundMaintenanceWindow() { // XMLTV parsing is CPU-heavy, so keep it away from content browsing and playback. while (currentScreen !in setOf(AppScreen.HOME, AppScreen.SETTINGS) || guideInteractionBusy) { delay(1_000) } } private suspend fun awaitBackgroundCatalogWindow(type: ContentType) { // Catalog HTTP/JSON work happens on Dispatchers.IO and is safe to continue while // the viewer browses the matching library. Pausing it on MOVIES/SERIES was the // reason a provider that returned only ~20 global items could stay stuck there. val allowed = when (type) { ContentType.MOVIE -> setOf(AppScreen.HOME, AppScreen.SETTINGS, AppScreen.MOVIES, AppScreen.MOVIE_DETAIL) ContentType.SERIES -> setOf(AppScreen.HOME, AppScreen.SETTINGS, AppScreen.SERIES, AppScreen.SERIES_DETAIL) else -> setOf(AppScreen.HOME, AppScreen.SETTINGS) } while (currentScreen !in allowed || guideInteractionBusy) delay(500) } private fun catalogLooksSuspicious(type: ContentType): Boolean { if (type !in setOf(ContentType.MOVIE, ContentType.SERIES)) return false val master = catalogCache[type to null].orEmpty() // An empty master catalog is always suspicious, even before category metadata has // hydrated. This is the exact state that previously let "All Movies" stay blank. if (master.isEmpty()) return true val groups = categories[type].orEmpty().count { it.id.isNotBlank() } if (groups <= 1) return false // If a provider exposes many categories but its "all" endpoint returns only a // handful of rows, treat it as a preview/paginated response rather than a library. val expectedFloor = maxOf(40, groups * 3) return master.size < expectedFloor } private fun scheduleCompletenessSweep(creds: Credentials) { launchCatalogRepair(creds, ContentType.MOVIE, delayMs = if (catalogLooksSuspicious(ContentType.MOVIE)) 350L else 4_000L) launchCatalogRepair(creds, ContentType.SERIES, delayMs = if (catalogLooksSuspicious(ContentType.SERIES)) 700L else 6_000L) } private fun launchCatalogRepair(creds: Credentials, type: ContentType, delayMs: Long = 0L, force: Boolean = false) { if (type !in setOf(ContentType.MOVIE, ContentType.SERIES)) return if (!catalogRepairRunning.add(type)) return val key = "catalog_complete_v0416_${type.name.lowercase()}_${creds.serverUrl.hashCode()}_${creds.username.hashCode()}" val lastSweep = maintenancePrefs.getLong(key, 0L) val suspicious = catalogLooksSuspicious(type) if (!force && !suspicious && System.currentTimeMillis() - lastSweep < 24L * 60L * 60L * 1000L) { catalogRepairRunning.remove(type) return } viewModelScope.launch { try { if (delayMs > 0L) delay(delayMs) awaitBackgroundCatalogWindow(type) val groups = categories[type].orEmpty().ifEmpty { runCatching { repository.categories(creds, type) }.getOrDefault(emptyList()).also { loaded -> if (loaded.isNotEmpty()) categories = categories + (type to loaded) } } if (groups.isEmpty()) return@launch val complete = sweepCatalogCompleteness(creds, type, groups) if (complete) { maintenancePrefs.edit().putLong(key, System.currentTimeMillis()).apply() } } finally { catalogRepairRunning.remove(type) } } } private suspend fun sweepCatalogCompleteness(creds: Credentials, type: ContentType, groups: List): Boolean { if (type !in setOf(ContentType.MOVIE, ContentType.SERIES) || groups.isEmpty()) return false awaitBackgroundCatalogWindow(type) val masterKey = type to null val original = catalogCache[masterKey].orEmpty() val merged = LinkedHashMap(maxOf(original.size + 1024, 4096)) original.forEach { merged[it.id] = it } var successfulGroups = 0 var failedGroups = 0 var lastPublishedSize = original.size groups.filter { it.id.isNotBlank() }.chunked(12).forEach { batch -> awaitBackgroundCatalogWindow(type) val results = coroutineScope { batch.map { category -> async { category to catalogFetchGate.withPermit { runCatching { repository.catalog(creds, type, category.id) } } } }.awaitAll() } results.forEach { (category, result) -> result.onSuccess { entries -> successfulGroups++ // Keep a trustworthy category cache even when the provider omitted // category_id fields in the rows themselves. catalogCache[type to category.id] = entries entries.forEach { entry -> merged[entry.id] = entry } if (selectedCategories[type] == category.id) { catalogs = catalogs + (type to entries) } }.onFailure { failedGroups++ } } // Publish progressive growth while "All" is open instead of making the user // stare at a 20-title sample until every category has finished. if (selectedCategories[type] == null && merged.size > lastPublishedSize) { val progressive = merged.values.toList() catalogCache[masterKey] = progressive catalogs = catalogs + (type to progressive) if (type == ContentType.MOVIE) startupMovieCount = progressive.size else startupSeriesCount = progressive.size lastPublishedSize = progressive.size } kotlinx.coroutines.yield() } val complete = merged.values.toList() if (complete.size >= original.size) { catalogCache[masterKey] = complete val selected = selectedCategories[type] catalogs = catalogs + (type to if (selected == null) complete else { catalogCache[type to selected] ?: complete.filter { it.categoryId == selected } }) if (type == ContentType.MOVIE) startupMovieCount = complete.size else startupSeriesCount = complete.size persistStartupSnapshot(creds) } // Do not lock out retries for 24 hours when a suspicious tiny global catalog // failed to grow. This lets transient panel/network failures self-heal next launch. val improvedTinyCatalog = !catalogLooksSuspicious(type) return successfulGroups > 0 && failedGroups == 0 && improvedTinyCatalog } private suspend fun refreshFullEpgInBackground(creds: Credentials, liveList: List) { awaitBackgroundMaintenanceWindow() val result = runCatching { repository.fullEpg(creds, liveList) } .onSuccess { guide -> if (guide.isEmpty()) return@onSuccess applyEpgGuideSmoothly(guide, clearExisting = true) startupEpgTotal = liveList.size startupEpgCompleted = liveList.size startupEpgFound = liveList.count { epgByChannel[it.id].orEmpty().isNotEmpty() } persistStartupSnapshot(creds) } } /** * Applying a provider-wide guide can touch thousands of channel entries. Doing that * in one main-thread burst causes visible D-pad hitching even though the XML parsing * itself happened on IO. Apply only channels that actually have programmes and yield * between small chunks so Compose gets a frame between batches. */ private suspend fun applyEpgGuideSmoothly( guide: Map>, clearExisting: Boolean, ) { // Never clear thousands of observable guide entries in one frame. New provider data // overwrites matching channel IDs; stale IDs naturally disappear on the next process // launch/cache rebuild. This avoids a full-guide invalidation while video is playing. val entries = guide.entries.filter { it.value.isNotEmpty() } if (entries.isEmpty()) return // The full cached/XMLTV guide is allowed to hydrate while Live TV is open. The old // behavior deferred all bulk EPG until the user left Live, which is why programme // cells appeared blank during a long scroll and suddenly returned after stopping. // We only pause observable updates during an active D-pad burst, then apply tiny // batches between frames so the guide stays populated without fighting navigation. while (guideInteractionBusy) delay(80) entries.chunked(8).forEach { chunk -> while (guideInteractionBusy) delay(50) Snapshot.withMutableSnapshot { chunk.forEach { (channelId, programs) -> epgByChannel[channelId] = programs } } delay(8) } if (entries.any { sportsChannelIndex.containsKey(it.key) }) markSportsEpgChanged() } private fun applyFastLiveCache(cache: FastLiveCache, meta: FastCacheMeta) { val liveList = cache.channels categories = categories + (ContentType.LIVE to cache.categories) catalogCache[ContentType.LIVE to null] = liveList liveList.groupBy { it.categoryId }.forEach { (categoryId, entries) -> if (categoryId.isNotBlank()) catalogCache[ContentType.LIVE to categoryId] = entries } selectedCategories = selectedCategories + mapOf( ContentType.LIVE to selectedCategories[ContentType.LIVE], ContentType.MOVIE to selectedCategories[ContentType.MOVIE], ContentType.SERIES to selectedCategories[ContentType.SERIES], ) catalogs = catalogs + (ContentType.LIVE to filterMaster(liveList, selectedCategories[ContentType.LIVE])) allLiveChannels = liveList rebuildSportsChannelIndex() val tunedId = tunedChannel?.id tunedChannel = tunedId?.let { id -> liveList.firstOrNull { it.id == id } } ?: credentials?.let { rememberedLiveChannel(it, liveList) } ?: liveList.firstOrNull() selectedChannel = tunedChannel startupLiveCount = meta.liveCount startupEpgTotal = meta.liveCount startupEpgCompleted = 0 startupEpgFound = meta.epgChannelCount startupMovieCount = meta.movieCount startupSeriesCount = meta.seriesCount } /** * Hydrates the heavyweight cached pieces after Home is already visible. Each file is * deserialized on IO threads in parallel, then applied once. This keeps the first * remote press responsive even with 30k+ VOD titles and a large XMLTV guide. */ private suspend fun hydrateSegmentedCache(creds: Credentials) { // 0.4.4 ULTRA: never deserialize EPG + 30k movies + series simultaneously. That // creates a CPU/GC spike on TV hardware exactly when the user starts pressing keys. // Hydrate one segment at a time, only while Home/Settings is calm. delay(1_250) awaitBackgroundMaintenanceWindow() val cachedEpg = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) { startupCacheStore.loadEpg(creds) } cachedEpg?.let { part -> if (part.guide.isNotEmpty()) { applyEpgGuideSmoothly(part.guide, clearExisting = false) startupEpgCompleted = allLiveChannels.size startupEpgFound = allLiveChannels.count { part.guide[it.id].orEmpty().isNotEmpty() } } } delay(350) awaitBackgroundMaintenanceWindow() val cachedMovies = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) { startupCacheStore.loadMovies(creds) } cachedMovies?.let { part -> if (part.categories.isNotEmpty()) categories = categories + (ContentType.MOVIE to part.categories) val safeMovies = mergeCatalogWithoutShrinking(catalogCache[ContentType.MOVIE to null].orEmpty(), part.entries) catalogCache[ContentType.MOVIE to null] = safeMovies catalogs = catalogs + (ContentType.MOVIE to filterMaster(safeMovies, selectedCategories[ContentType.MOVIE])) startupMovieCount = safeMovies.size } delay(350) awaitBackgroundMaintenanceWindow() val cachedSeries = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) { startupCacheStore.loadSeries(creds) } cachedSeries?.let { part -> if (part.categories.isNotEmpty()) categories = categories + (ContentType.SERIES to part.categories) val safeSeries = mergeCatalogWithoutShrinking(catalogCache[ContentType.SERIES to null].orEmpty(), part.entries) catalogCache[ContentType.SERIES to null] = safeSeries catalogs = catalogs + (ContentType.SERIES to filterMaster(safeSeries, selectedCategories[ContentType.SERIES])) startupSeriesCount = safeSeries.size } } private fun applyStartupSnapshot(snapshot: StartupSnapshot) { val liveList = snapshot.liveChannels categories = categories + mapOf( ContentType.LIVE to snapshot.liveCategories, ContentType.MOVIE to snapshot.movieCategories, ContentType.SERIES to snapshot.seriesCategories, ) catalogCache.clear() catalogCache[ContentType.LIVE to null] = liveList catalogCache[ContentType.MOVIE to null] = snapshot.movies catalogCache[ContentType.SERIES to null] = snapshot.series // Do not build tens of thousands of category-index entries on the launch frame. // loadCategory() will create each category cache on first use; the segmented v3 // cache path builds indexes after Home is already interactive. selectedCategories = selectedCategories + mapOf( ContentType.LIVE to selectedCategories[ContentType.LIVE], ContentType.MOVIE to selectedCategories[ContentType.MOVIE], ContentType.SERIES to selectedCategories[ContentType.SERIES], ) catalogs = catalogs + mapOf( ContentType.LIVE to filterMaster(liveList, selectedCategories[ContentType.LIVE]), ContentType.MOVIE to filterMaster(snapshot.movies, selectedCategories[ContentType.MOVIE]), ContentType.SERIES to filterMaster(snapshot.series, selectedCategories[ContentType.SERIES]), ) allLiveChannels = liveList rebuildSportsChannelIndex() val tunedId = tunedChannel?.id tunedChannel = tunedId?.let { id -> liveList.firstOrNull { it.id == id } } ?: credentials?.let { rememberedLiveChannel(it, liveList) } ?: liveList.firstOrNull() selectedChannel = tunedChannel epgByChannel.clear() // The legacy EPG is applied after Home in applyEpgGuideSmoothly(). startupStage = StartupStage.LIVE startupLiveCount = liveList.size startupProgress = 1f startupDetail = "${liveList.size} Live TV channels restored locally" startupStage = StartupStage.EPG startupEpgTotal = liveList.size startupEpgCompleted = liveList.size startupEpgFound = liveList.count { snapshot.epgByChannel[it.id].orEmpty().isNotEmpty() } startupProgress = 1f startupDetail = "$startupEpgFound of ${liveList.size} cached channels have EPG data" startupStage = StartupStage.LIBRARY startupMovieCount = snapshot.movies.size startupSeriesCount = snapshot.series.size startupProgress = 1f startupDetail = "${snapshot.movies.size} movies • ${snapshot.series.size} series restored locally" } private suspend fun buildCategoryIndex( type: ContentType, entries: List, ): Map, List> = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.Default) { entries.groupBy { it.categoryId } .filterKeys { it.isNotBlank() } .mapKeys { (categoryId, _) -> type to categoryId } } private fun mergeCatalogWithoutShrinking(existing: List, incoming: List): List { if (existing.isEmpty()) return incoming if (incoming.isEmpty()) return existing val merged = LinkedHashMap(maxOf(existing.size, incoming.size) + 256) existing.forEach { merged[it.id] = it } // Incoming rows refresh metadata for matching IDs but can never delete titles. incoming.forEach { merged[it.id] = it } return merged.values.toList() } private fun filterMaster(master: List, categoryId: String?): List = if (categoryId.isNullOrBlank()) master else master.filter { it.categoryId == categoryId } private fun persistStartupSnapshot(creds: Credentials) { val live = catalogCache[ContentType.LIVE to null].orEmpty() val movies = catalogCache[ContentType.MOVIE to null].orEmpty() val series = catalogCache[ContentType.SERIES to null].orEmpty() if (live.isEmpty() && movies.isEmpty() && series.isEmpty()) return val snapshot = StartupSnapshot( fingerprint = "", savedAtMillis = System.currentTimeMillis(), liveCategories = categories[ContentType.LIVE].orEmpty(), liveChannels = live, epgByChannel = epgByChannel.toMap(), movieCategories = categories[ContentType.MOVIE].orEmpty(), movies = movies, seriesCategories = categories[ContentType.SERIES].orEmpty(), series = series, ) viewModelScope.launch(kotlinx.coroutines.Dispatchers.IO) { startupCacheStore.save(creds, snapshot) } } var playlistRefreshStatus by mutableStateOf("Ready") private set private var playlistRefreshRunning = false fun updatePlaylistManually() { val creds = credentials ?: run { playlistRefreshStatus = "Sign in to update playlist"; return } if (playlistRefreshRunning) return playlistRefreshRunning = true playlistRefreshStatus = "Updating playlist…" viewModelScope.launch { try { refreshStartupCacheInBackground(creds, manual = true) playlistRefreshStatus = "Playlist update finished • Movies: $startupMovieCount • Series: $startupSeriesCount" } catch (error: Exception) { playlistRefreshStatus = "Playlist update failed • saved library preserved" } finally { playlistRefreshRunning = false } } } private suspend fun refreshStartupCacheInBackground(creds: Credentials, manual: Boolean = false) { if (!manual) awaitBackgroundMaintenanceWindow() val result = runCatching { val data = coroutineScope { val liveCategoriesJob = async { repository.categories(creds, ContentType.LIVE) } val liveJob = async { repository.catalog(creds, ContentType.LIVE, null) } val movieCategoriesJob = async { repository.categories(creds, ContentType.MOVIE) } val moviesJob = async { repository.catalog(creds, ContentType.MOVIE, null) } val seriesCategoriesJob = async { repository.categories(creds, ContentType.SERIES) } val seriesJob = async { repository.catalog(creds, ContentType.SERIES, null) } val live = liveJob.await() val epgJob = async { runCatching { repository.fullEpg(creds, live) }.getOrDefault(emptyMap()) } BackgroundStartupData( liveCategories = liveCategoriesJob.await(), live = live, epg = epgJob.await(), movieCategories = movieCategoriesJob.await(), movies = moviesJob.await(), seriesCategories = seriesCategoriesJob.await(), series = seriesJob.await(), ) } categories = categories + mapOf( ContentType.LIVE to data.liveCategories, ContentType.MOVIE to data.movieCategories, ContentType.SERIES to data.seriesCategories, ) // A number of XUI panels return a small preview (often ~20 rows) from the // provider-wide VOD endpoints. Never let that later background refresh erase // a complete 30k/9k category-merged library that is already on the device. val existingMovies = catalogCache[ContentType.MOVIE to null].orEmpty() val existingSeries = catalogCache[ContentType.SERIES to null].orEmpty() val safeMovies = mergeCatalogWithoutShrinking(existingMovies, data.movies) val safeSeries = mergeCatalogWithoutShrinking(existingSeries, data.series) // Build 76 channel-integrity rule: a provider-wide Live TV refresh is allowed to // update metadata, but it must NEVER shrink the lineup already known on-device. // Some XUI panels transiently omit the first/newest PPV rows from get_live_streams; // replacing the master list here made channels such as PPV1 silently disappear. val existingLive = catalogCache[ContentType.LIVE to null].orEmpty().ifEmpty { allLiveChannels } val safeLive = mergeCatalogWithoutShrinking(existingLive, data.live) catalogCache.keys.filter { it.first == ContentType.LIVE }.toList().forEach { catalogCache.remove(it) } catalogCache[ContentType.LIVE to null] = safeLive catalogCache[ContentType.MOVIE to null] = safeMovies catalogCache[ContentType.SERIES to null] = safeSeries catalogCache.putAll(buildCategoryIndex(ContentType.LIVE, safeLive)) catalogs = catalogs + mapOf( ContentType.LIVE to filterMaster(safeLive, selectedCategories[ContentType.LIVE]), ContentType.MOVIE to filterMaster(safeMovies, selectedCategories[ContentType.MOVIE]), ContentType.SERIES to filterMaster(safeSeries, selectedCategories[ContentType.SERIES]), ) allLiveChannels = safeLive rebuildSportsChannelIndex() if (data.epg.isNotEmpty()) { applyEpgGuideSmoothly(data.epg, clearExisting = true) } startupLiveCount = safeLive.size startupEpgTotal = safeLive.size startupEpgCompleted = safeLive.size startupEpgFound = safeLive.count { epgByChannel[it.id].orEmpty().isNotEmpty() } startupMovieCount = safeMovies.size startupSeriesCount = safeSeries.size persistStartupSnapshot(creds) scheduleCompletenessSweep(creds) } if (manual) result.getOrThrow() } private data class BackgroundStartupData( val liveCategories: List, val live: List, val epg: Map>, val movieCategories: List, val movies: List, val seriesCategories: List, val series: List, ) fun checkForUpdates(silent: Boolean = false) { if (updateDownloading) return viewModelScope.launch { updateError = null if (!silent) updateStatus = "Checking for updates…" try { val update = updateManager.checkForUpdate(force = !silent) availableUpdate = update updateStatus = when { update != null -> null silent -> null else -> "TiviLux ${BuildConfig.VERSION_NAME} is up to date." } } catch (t: Throwable) { if (!silent) { updateError = null updateStatus = t.message ?: "Unable to reach the TiviLux update server." } } } } fun dismissUpdate() { if (availableUpdate?.required == true || updateDownloading) return availableUpdate = null pendingUpdateAfterPermission = null updateStatus = null updateError = null } fun beginUpdate() { val update = availableUpdate ?: return if (updateDownloading) return updateError = null if (!updateManager.canInstallPackages()) { pendingUpdateAfterPermission = update updateStatus = "Allow TiviLux to install updates, then return here." updateManager.openInstallPermission() return } downloadAndInstall(update) } fun onAppResumed() { val pending = pendingUpdateAfterPermission ?: return if (updateManager.canInstallPackages()) { pendingUpdateAfterPermission = null downloadAndInstall(pending) } } private fun downloadAndInstall(update: AppUpdateInfo) { if (updateDownloading) return viewModelScope.launch { updateDownloading = true updateProgress = 0 updateStatus = "Downloading TiviLux ${update.versionName}…" updateError = null try { val apk = updateManager.downloadUpdate(update) { progress -> updateProgress = progress } updateStatus = "Opening Android installer…" updateManager.launchInstaller(apk) } catch (t: Throwable) { updateError = t.message ?: "Unable to download update." updateStatus = null } finally { updateDownloading = false } } } fun navigate(screen: AppScreen) { if (screen !in setOf(AppScreen.PLAYER, AppScreen.MOVIE_DETAIL, AppScreen.SERIES_DETAIL)) { previousScreen = currentScreen } currentScreen = screen when (screen) { AppScreen.LIVE -> { // Opening Live TV from Home/rail starts at the top of the sorted channel list. // Player -> Guide uses openGuideForPlayingChannel() instead and supplies an anchor. guideOpenAnchorChannelId = null ensureLoaded(ContentType.LIVE) } AppScreen.MULTIVIEW -> { multiViewReturnScreen = previousScreen.takeIf { it in setOf(AppScreen.LIVE, AppScreen.FAVORITES) } ?: AppScreen.LIVE ensureLoaded(ContentType.LIVE) if (multiViewSlots.all { it == null }) { val first = tunedChannel ?: allVisibleLiveChannels().firstOrNull() if (first != null) multiViewSlots = multiViewSlots.toMutableList().also { it[0] = first } } } AppScreen.SPORTS -> { // Fresh Sports entry always opens at the intelligent All Sports/GameDay view. // Returning from a playing Sports channel uses backFromPlayer(), so the viewer's // selected league is preserved during an active Sports session. selectedSportsLeague = SportLeague.ALL ensureLoaded(ContentType.LIVE) // Publish whatever TiviLux already knows first. Do not make the Game Center wait // for the scoreboard network request or provider-feed enrichment to finish. if (sportsEventsCache.isEmpty()) { sportsPreparing = true sportsLoadingStage = if (officialSportsSchedule.isEmpty()) { "Loading today's games and scores…" } else { "Building Game Center…" } } scheduleSportsDerivedRebuild() refreshOfficialSportsSchedule(force = false) startSportsLiveScoreTracking() // Sports opens from the already-loaded channel index + cached/bulk EPG. // Never launch a provider-wide per-channel EPG crawl just because the // viewer opened Sports; that was the largest source of Sports Hub lag. if (allLiveChannels.isNotEmpty() && selectedSportsLeague != SportLeague.ALL) { refreshSports(league = selectedSportsLeague) } } AppScreen.MOVIES -> { ensureLoaded(ContentType.MOVIE) credentials?.let { if (catalogLooksSuspicious(ContentType.MOVIE)) launchCatalogRepair(it, ContentType.MOVIE, force = true) } } AppScreen.SERIES -> { ensureLoaded(ContentType.SERIES) credentials?.let { if (catalogLooksSuspicious(ContentType.SERIES)) launchCatalogRepair(it, ContentType.SERIES, force = true) } } else -> Unit } } fun backFromPlayer() { currentScreen = if (previousScreen == AppScreen.PLAYER) AppScreen.HOME else previousScreen } /** Open Home -> Last Channel as a complete Live Guide context, not just playback. * The provider category, exact row, preview tune and guide anchor move together. */ fun openLastChannelInGuide() { val channel = (playingItem?.takeIf { it.type == ContentType.LIVE } ?: tunedChannel ?: recentLiveChannels.firstOrNull()) ?.takeIf(::isVisibleContent) ?: return val master = catalogCache[ContentType.LIVE to null].orEmpty() val categoryId = channel.categoryId.takeIf { it.isNotBlank() && it !in hiddenCategoryCache[ContentType.LIVE].orEmpty() } val categoryList = if (categoryId == null) master else master.filter { it.categoryId == categoryId } if (categoryList.any { it.id == channel.id }) { selectedCategories = selectedCategories + (ContentType.LIVE to categoryId) if (categoryId != null) catalogCache[ContentType.LIVE to categoryId] = categoryList catalogs = catalogs + (ContentType.LIVE to categoryList) } else { selectedCategories = selectedCategories + (ContentType.LIVE to null) if (master.isNotEmpty()) catalogs = catalogs + (ContentType.LIVE to master) } selectedChannel = channel guideOpenAnchorChannelId = channel.id setLivePlayer(channel) currentScreen = AppScreen.LIVE } /** Manual Home action: keep the last-good guide visible and refresh the full EPG off-screen. */ fun refreshTvGuideFromHome(onComplete: (Boolean) -> Unit = {}) { val creds = credentials ?: run { onComplete(false); return } val liveList = catalogCache[ContentType.LIVE to null].orEmpty().ifEmpty { allLiveChannels } if (liveList.isEmpty()) { onComplete(false); return } viewModelScope.launch { val guide = runCatching { repository.fullEpg(creds, liveList) }.getOrNull() if (!guide.isNullOrEmpty()) { applyEpgGuideSmoothly(guide, clearExisting = false) startupEpgTotal = liveList.size startupEpgCompleted = liveList.size startupEpgFound = liveList.count { epgByChannel[it.id].orEmpty().isNotEmpty() } persistStartupSnapshot(creds) onComplete(true) } else onComplete(false) } } fun openGuideForPlayingChannel() { val channel = playingItem?.takeIf { it.type == ContentType.LIVE } ?: tunedChannel if (channel != null) { val master = catalogCache[ContentType.LIVE to null].orEmpty() val hiddenCategory = channel.categoryId.isNotBlank() && channel.categoryId in hiddenCategoryCache[ContentType.LIVE].orEmpty() val hiddenChannel = channel.id in hiddenLiveChannelCache if (hiddenCategory || hiddenChannel) { selectedCategories = selectedCategories + (ContentType.LIVE to null) if (master.isNotEmpty()) catalogs = catalogs + (ContentType.LIVE to master) selectedChannel = catalogForDisplay(ContentType.LIVE).firstOrNull() guideOpenAnchorChannelId = null currentScreen = AppScreen.LIVE return } val currentList = catalogs[ContentType.LIVE].orEmpty() val channelAlreadyVisible = currentList.any { it.id == channel.id } // Sports can launch a team/league feed that is not in whatever Live TV group // the viewer last used. In that case reopen the guide in the channel's provider // group, then anchor the guide on the exact stream that is still playing. if (!channelAlreadyVisible) { val categoryId = channel.categoryId.takeIf { it.isNotBlank() } selectedCategories = selectedCategories + (ContentType.LIVE to categoryId) val visible = if (categoryId == null) master else master.filter { it.categoryId == categoryId } if (visible.isNotEmpty()) { if (categoryId != null) catalogCache[ContentType.LIVE to categoryId] = visible catalogs = catalogs + (ContentType.LIVE to visible) } else if (master.isNotEmpty()) { selectedCategories = selectedCategories + (ContentType.LIVE to null) catalogs = catalogs + (ContentType.LIVE to master) } } selectedChannel = channel tunedChannel = channel guideOpenAnchorChannelId = channel.id ensureEpg(channel) } else { guideOpenAnchorChannelId = null } currentScreen = AppScreen.LIVE } fun backFromDetail() { currentScreen = detailReturnScreen } fun loadCategory(type: ContentType, categoryId: String?) { val creds = credentials ?: return val effectiveCategoryId = categoryId?.takeUnless { it in hiddenCategoryCache[type].orEmpty() } selectedCategories = selectedCategories + (type to effectiveCategoryId) if (type == ContentType.LIVE && effectiveCategoryId == favoritesCategoryId) { val favorites = favoriteLiveChannels() catalogs = catalogs + (ContentType.LIVE to favorites) selectedChannel = favorites.firstOrNull() ?: tunedChannel selectedChannel?.let { ensureEpg(it) } return } val cacheKey = type to effectiveCategoryId // Startup keeps a complete master catalog for Live TV, Movies and Series. // Filter that master list locally so changing groups is instantaneous and never // causes another giant Xtream request. if (effectiveCategoryId != null && !catalogCache.containsKey(cacheKey)) { val trustMasterForLocalFilter = type == ContentType.LIVE || !catalogLooksSuspicious(type) if (trustMasterForLocalFilter) { catalogCache[type to null]?.let { complete -> val filtered = complete.filter { it.categoryId == effectiveCategoryId } catalogCache[cacheKey] = filtered catalogs = catalogs + (type to filtered) if (type == ContentType.LIVE) { selectedChannel = filtered.firstOrNull() ?: selectedChannel if (tunedChannel == null) tunedChannel = selectedChannel } return } } } catalogCache[cacheKey]?.takeIf { it.isNotEmpty() }?.let { cached -> catalogs = catalogs + (type to cached) if (type == ContentType.LIVE) { selectedChannel = cached.firstOrNull() ?: selectedChannel if (tunedChannel == null) tunedChannel = selectedChannel selectedChannel?.let { ensureEpg(it) } tunedChannel?.let { ensureEpg(it) } // Build 77 CHANNEL-INTEGRITY: a provider-wide get_live_streams response can be // incomplete even though a category-scoped request contains every channel. // Previously we trusted the locally-filtered master forever, so a channel such // as PPV 01 could exist in TiviMate/XUI but never reach the TiviLux Guide. // Show the cached category immediately for fast navigation, then verify the // selected category directly with XUI and merge any missing stream IDs back into // both the category cache and the Live master. Nothing is fabricated/hardcoded. if (effectiveCategoryId != null) { viewModelScope.launch { runCatching { repository.catalog(creds, ContentType.LIVE, effectiveCategoryId) } .onSuccess { direct -> if (direct.isNotEmpty()) { val mergedCategory = LinkedHashMap() direct.forEach { mergedCategory[it.id] = it } cached.forEach { if (!mergedCategory.containsKey(it.id)) mergedCategory[it.id] = it } val verified = mergedCategory.values.toList() catalogCache[cacheKey] = verified val master = LinkedHashMap() catalogCache[ContentType.LIVE to null].orEmpty().forEach { master[it.id] = it } direct.forEach { master[it.id] = it } val healedMaster = master.values.toList() catalogCache[ContentType.LIVE to null] = healedMaster allLiveChannels = healedMaster rebuildSportsChannelIndex() if (selectedCategories[ContentType.LIVE] == effectiveCategoryId) { catalogs = catalogs + (ContentType.LIVE to verified) if (selectedChannel == null || verified.none { it.id == selectedChannel?.id }) { selectedChannel = verified.firstOrNull() } } persistStartupSnapshot(creds) } } } } } else if (effectiveCategoryId == null && catalogLooksSuspicious(type)) { // "All" must keep healing in the background until the category sweep has // reconstructed the provider's complete VOD/Series catalog. launchCatalogRepair(creds, type, delayMs = 0L, force = true) } return } viewModelScope.launch { loading = true error = null try { val list = repository.catalog(creds, type, effectiveCategoryId) catalogCache[cacheKey] = list catalogs = catalogs + (type to list) if (type in setOf(ContentType.MOVIE, ContentType.SERIES) && effectiveCategoryId == null) { // Some XUI panels return zero/a tiny preview from get_vod_streams/get_series. // Start the category-by-category completeness sweep immediately when All is opened. launchCatalogRepair(creds, type, delayMs = 0L, force = true) } if (type in setOf(ContentType.MOVIE, ContentType.SERIES) && effectiveCategoryId != null && list.isNotEmpty()) { val masterKey = type to null val merged = LinkedHashMap() catalogCache[masterKey].orEmpty().forEach { merged[it.id] = it } list.forEach { merged[it.id] = it } catalogCache[masterKey] = merged.values.toList() if (type == ContentType.MOVIE) startupMovieCount = merged.size else startupSeriesCount = merged.size launchCatalogRepair(creds, type, delayMs = 100L, force = true) } if (type == ContentType.LIVE) { if (effectiveCategoryId == null) { allLiveChannels = list rebuildSportsChannelIndex() } selectedChannel = list.firstOrNull() if (tunedChannel == null) tunedChannel = selectedChannel selectedChannel?.let { ensureEpg(it) } tunedChannel?.let { ensureEpg(it) } } } catch (t: Throwable) { error = t.message ?: "Unable to load content." } finally { loading = false } } } fun ensureLoaded(type: ContentType) { if (!categories[type].isNullOrEmpty() && !catalogs[type].isNullOrEmpty()) return preload(type) } private fun preload(type: ContentType) { val creds = credentials ?: return viewModelScope.launch { loading = true error = null try { var categoryList = categories[type].orEmpty() if (categoryList.isEmpty()) { categoryList = repository.categories(creds, type) categories = categories + (type to categoryList) } if (catalogs[type].isNullOrEmpty()) { // Enter Movies/Series on the provider-wide "All" catalog. If that // endpoint is incomplete, the repair sweep below progressively merges every // category without making the user start on an arbitrary first group. val initialCategory: String? = null if (type != ContentType.LIVE) selectedCategories = selectedCategories + (type to null) val list = repository.catalog(creds, type, initialCategory) catalogCache[type to initialCategory] = list catalogs = catalogs + (type to list) if (type in setOf(ContentType.MOVIE, ContentType.SERIES)) { launchCatalogRepair(creds, type, delayMs = 0L, force = true) } if (type == ContentType.LIVE) { allLiveChannels = list rebuildSportsChannelIndex() selectedChannel = list.firstOrNull() if (tunedChannel == null) tunedChannel = selectedChannel selectedChannel?.let { ensureEpg(it) } tunedChannel?.let { ensureEpg(it) } if (currentScreen == AppScreen.SPORTS) refreshSports() } } } catch (t: Throwable) { error = t.message ?: "Unable to load ${type.name.lowercase()}." } finally { loading = false } } } fun selectChannel(item: MediaEntry) { // OK/Select is the only guide action that tunes a new live stream. Keep the resolved // URL in player state immediately so Guide -> Fullscreen is only a surface resize, // never another URL/build/preparation cycle. D-pad browsing still never retunes. if (item.type == ContentType.LIVE) setLivePlayer(item) else recordLiveTune(item) } private fun recordLiveTune(item: MediaEntry) { val current = tunedChannel if (current?.id != null && current.id != item.id) previousTunedChannel = current selectedChannel = item tunedChannel = item recentLiveChannels = (listOf(item) + recentLiveChannels.filterNot { it.id == item.id }).take(30) if (item.type == ContentType.LIVE) credentials?.let { creds -> startupChannelPrefs.edit().putString(lastChannelKey(creds), item.id.toString()).apply() } } private fun setLivePlayer(item: MediaEntry) { val creds = credentials ?: return tv.tivilux.nativeplayer.data.LiveStreamTrace.selected(item.id.toString(), item.name) recordLiveTune(item) ensureEpg(item) if (item.type != ContentType.EPISODE) playbackNextItem = null playingItem = item playingUrlCandidates = runCatching { repository.streamUrlCandidates(creds, item, settings.preferHlsLive) }.getOrElse { error = it.message ?: "Unable to create playback URL." return } playingUrl = playingUrlCandidates.firstOrNull() libraryStore.remember(item) } fun tuneAdjacentLive(delta: Int) { val list = catalogForDisplay(ContentType.LIVE) if (list.isEmpty()) return val currentId = (playingItem?.takeIf { it.type == ContentType.LIVE } ?: tunedChannel)?.id val index = list.indexOfFirst { it.id == currentId }.let { if (it < 0) 0 else it } val nextIndex = (index + delta).floorMod(list.size) setLivePlayer(list[nextIndex]) } fun tunePreviousLive() { val currentId = (playingItem?.takeIf { it.type == ContentType.LIVE } ?: tunedChannel)?.id val previous = previousTunedChannel?.takeIf { it.id != currentId && isVisibleContent(it) } ?: recentLiveChannels.firstOrNull { it.id != currentId && isVisibleContent(it) } ?: return setLivePlayer(previous) } fun tuneLiveFromPlayer(item: MediaEntry) { if (item.type != ContentType.LIVE) return setLivePlayer(item) } fun removeCurrentLiveFromHistory() { val id = (playingItem?.takeIf { it.type == ContentType.LIVE } ?: tunedChannel)?.id ?: return recentLiveChannels = recentLiveChannels.filterNot { it.id == id } if (previousTunedChannel?.id == id) { previousTunedChannel = recentLiveChannels.firstOrNull { it.id != id } } } private fun Int.floorMod(size: Int): Int = ((this % size) + size) % size fun setGuideInteractionBusy(isBusy: Boolean) { guideInteractionBusy = isBusy } fun ensureEpg(item: MediaEntry) { val creds = credentials ?: return // During held UP/DOWN, rendering/focus wins. Once the remote settles LiveScreen // immediately re-requests only the visible rows, so skipping here loses nothing. if (guideInteractionBusy) return if (item.type != ContentType.LIVE) return if (epgByChannel.containsKey(item.id) || !epgLoadingIds.add(item.id)) return viewModelScope.launch { try { epgFetchGate.withPermit { val programs = runCatching { repository.epg(creds, item.id, 8) }.getOrDefault(emptyList()) epgByChannel[item.id] = programs if (sportsChannelIndex.containsKey(item.id)) markSportsEpgChanged() } } finally { epgLoadingIds.remove(item.id) } } } fun play(item: MediaEntry, returnTo: AppScreen = currentScreen) { val creds = credentials ?: return if (item.type == ContentType.SERIES) { openSeries(item, returnTo) return } previousScreen = returnTo if (item.type == ContentType.LIVE) { // If the guide preview is already playing this exact channel, do not resolve or // prepare it again. Fullscreen is simply a screen/surface-layout change. if (playingItem?.type != ContentType.LIVE || playingItem?.id != item.id || playingUrl.isNullOrBlank()) { setLivePlayer(item) } else { recordLiveTune(item) ensureEpg(item) } currentScreen = AppScreen.PLAYER return } if (item.type != ContentType.EPISODE) playbackNextItem = null playingItem = item playingUrlCandidates = runCatching { repository.streamUrlCandidates(creds, item, settings.preferHlsLive) }.getOrElse { error = it.message ?: "Unable to create playback URL." return } playingUrl = playingUrlCandidates.firstOrNull() if (playingUrl.isNullOrBlank()) { error = "Provider did not return a playable stream URL." return } libraryStore.remember(item) currentScreen = AppScreen.PLAYER } fun openMovie(movie: MediaEntry, returnTo: AppScreen = currentScreen) { val creds = credentials ?: return detailReturnScreen = returnTo movieDetailCache[movie.id]?.let { cached -> selectedMovieDetail = cached currentScreen = AppScreen.MOVIE_DETAIL return } viewModelScope.launch { loading = true error = null try { val detail = repository.movieDetail(creds, movie) movieDetailCache[movie.id] = detail selectedMovieDetail = detail currentScreen = AppScreen.MOVIE_DETAIL } catch (t: Throwable) { error = t.message ?: "Unable to load movie details." } finally { loading = false } } } fun openSeries(series: MediaEntry, returnTo: AppScreen = currentScreen) { val creds = credentials ?: return detailReturnScreen = returnTo seriesDetailCache[series.id]?.let { cached -> selectedSeriesDetail = cached currentScreen = AppScreen.SERIES_DETAIL return } viewModelScope.launch { loading = true error = null try { val detail = repository.seriesDetail(creds, series) seriesDetailCache[series.id] = detail selectedSeriesDetail = detail currentScreen = AppScreen.SERIES_DETAIL } catch (t: Throwable) { error = t.message ?: "Unable to load series." } finally { loading = false } } } fun playEpisode(episode: tv.tivilux.nativeplayer.model.Episode) { val detail = selectedSeriesDetail val media = repository.episodeAsMedia(episode, detail?.series?.name.orEmpty()) prepareNextEpisodeFor(media, detail) play(media, AppScreen.SERIES_DETAIL) } private fun prepareNextEpisodeFor(item: MediaEntry, knownDetail: SeriesDetail? = null) { if (item.type != ContentType.EPISODE || item.seriesId.isBlank()) { playbackNextItem = null return } val detail = knownDetail ?: seriesDetailCache[item.seriesId] if (detail != null) { val ordered = detail.episodes.toSortedMap().values.flatten() val index = ordered.indexOfFirst { it.id == item.id } playbackNextItem = ordered.getOrNull(index + 1)?.let { repository.episodeAsMedia(it, detail.series.name) } return } playbackNextItem = null val creds = credentials ?: return val series = catalogCache[ContentType.SERIES to null].orEmpty().firstOrNull { it.id == item.seriesId } ?: return viewModelScope.launch { val loaded = runCatching { repository.seriesDetail(creds, series) }.getOrNull() ?: return@launch seriesDetailCache[series.id] = loaded if (playingItem?.id == item.id) prepareNextEpisodeFor(item, loaded) } } fun livePreviewUrlCandidates(item: MediaEntry?): List { val creds = credentials ?: return emptyList() val channel = item?.takeIf { it.type == ContentType.LIVE } ?: return emptyList() return runCatching { repository.streamUrlCandidates(creds, channel, settings.preferHlsLive) }.getOrDefault(emptyList()) } fun previewUrl(item: MediaEntry?): String? { val creds = credentials ?: return null val target = item ?: return null if (target.type == ContentType.SERIES) return null return runCatching { repository.streamUrl(creds, target, settings.preferHlsLive) }.getOrNull() } private fun markSportsEpgChanged() { sportsEpgRevision++ sportsEventsCacheRevision = -1L sportsSummariesCacheRevision = -1L } private fun beginSportsLoadCycle(forceNew: Boolean = false) { if (sportsLoadCycleInProgress && !forceNew) return sportsLoadCycle++ sportsLoadCycleInProgress = true } private fun maybeCompleteSportsLoadCycle() { if (!sportsLoadCycleInProgress) return if (sportsOfficialScheduleLoading || sportsScanning || sportsDerivedBuildJob?.isActive == true) return if (sportsEventsCacheRevision != sportsEpgRevision || sportsSummariesCacheRevision != sportsEpgRevision) return // A completed schedule attempt is enough even on a quiet sports day with zero official games. if (sportsOfficialScheduleLastFetchEpoch <= 0L && officialSportsSchedule.isEmpty()) return sportsLoadCycleInProgress = false if (sportsReadyCycle == sportsLoadCycle) return sportsReadyCycle = sportsLoadCycle sportsReadyNoticeToken++ sportsReadyNoticePending = true } fun consumeSportsReadyNotice(token: Long) { if (token == sportsReadyNoticeToken) sportsReadyNoticePending = false } private fun rebuildSportsChannelIndex() { val source = if (allLiveChannels.isNotEmpty()) allLiveChannels else catalogs[ContentType.LIVE].orEmpty() val categoryNames = categories[ContentType.LIVE].orEmpty().associate { it.id to it.name } val index = linkedMapOf() val grouped = linkedMapOf>() val all = ArrayList() source.forEach { channel -> detectSportLeague(channel, categoryNames[channel.categoryId].orEmpty())?.let { league -> index[channel.id] = league grouped.getOrPut(league) { mutableListOf() }.add(channel) all.add(channel) } } sportsChannelIndex = index sportsChannelsByLeague = grouped.mapValues { it.value.toList() } allSportsChannels = all markSportsEpgChanged() } private fun scheduleSportsWarmupAfterStartup() { if (sportsPrefetchJob?.isActive == true) return sportsPrefetchJob = viewModelScope.launch { val creds = credentials ?: return@launch try { // Sports is part of startup, but never blocks Home. Start almost immediately // after the provider lineup is usable and keep going even during playback. delay(650) while (allLiveChannels.isEmpty() || guideInteractionBusy) delay(350) beginSportsLoadCycle() sportsBackgroundLoading = true sportsBackgroundReady = false sportsOfficialScheduleLoading = true if (sportsChannelIndex.isEmpty()) rebuildSportsChannelIndex() // Build provider/EPG events once from the bulk guide already loaded by TiviLux. // Do not reintroduce a provider-wide per-channel Sports crawl. scheduleSportsDerivedRebuild() sportsDerivedBuildJob?.join() val order = sportsWarmupOrder() order.forEachIndexed { index, league -> if (credentials != creds) return@launch sportsBackgroundCategory = league.label sportsLoadingStage = "Loading ${league.label}…" warmOfficialSportsLeague(league) // Lower-power TV boxes keep decoder/render/input priority while the queue // continues in the background. Nothing pauses just because video is playing. if (index < order.lastIndex) { delay(if (currentScreen in setOf(AppScreen.PLAYER, AppScreen.MULTIVIEW)) 300 else 90) } } // Each league is merged directly into the existing provider cache as it arrives. // Do NOT run another provider-wide EPG rebuild here: doing so after every official // revision was the v0.4.40 CPU/memory regression on lower-power Android TV boxes. sportsOfficialScheduleLastFetchEpoch = System.currentTimeMillis() / 1000L sportsLoadingStage = "Game Center ready" sportsBackgroundReady = true } finally { sportsOfficialScheduleLoading = false sportsBackgroundLoading = false sportsBackgroundCategory = "" sportsPrefetchJob = null maybeCompleteSportsLoadCycle() } } } /** * Sequential startup order for score-enabled Game Center categories. Saturday always starts * with College Football and Sunday always starts with NFL. A cached live league can jump ahead * after that fixed day priority. */ private fun sportsWarmupOrder(): List { val standard = listOf( SportLeague.COLLEGE_FOOTBALL, SportLeague.NFL, SportLeague.MLB, SportLeague.NBA, SportLeague.NHL, SportLeague.WNBA, ) val day = Calendar.getInstance().get(Calendar.DAY_OF_WEEK) val fixedPriority = when (day) { Calendar.SATURDAY -> listOf(SportLeague.COLLEGE_FOOTBALL) Calendar.SUNDAY -> listOf(SportLeague.NFL) else -> emptyList() } val now = System.currentTimeMillis() / 1000L val livePriority = sportsEventsCache .asSequence() .filter { it.isLive(now) && sportsScheduleRepository.supports(it.league) } .groupingBy { it.league } .eachCount() .entries .sortedByDescending { it.value } .map { it.key } return (fixedPriority + livePriority + standard).distinct() } /** * Fetch today + tomorrow for exactly one league, then merge only that league into the already * built provider-event cache. This avoids rescanning every Sports EPG row six times. */ private suspend fun warmOfficialSportsLeague(league: SportLeague) { if (!sportsScheduleRepository.supports(league)) return val today = runCatching { sportsScheduleRepository.today(league) }.getOrDefault(emptyList()) val tomorrow = runCatching { sportsScheduleRepository.tomorrow(league) }.getOrDefault(emptyList()) val official = (today + tomorrow).distinctBy { it.id }.sortedBy { it.startEpoch } if (official.isEmpty()) return val updatedOfficialSchedule = (officialSportsSchedule.filter { it.league != league } + official) .distinctBy { it.id } .sortedBy { it.startEpoch } if (updatedOfficialSchedule != officialSportsSchedule) { officialSportsSchedule = updatedOfficialSchedule // Protect against a derived job publishing an older official-schedule snapshot without // invalidating the provider/EPG cache. This preserves the disappearing-MLB fix while // avoiding a full EPG rebuild for every league that loads. sportsOfficialRevision++ } val providerForLeague = sportsEventsCache.filter { it.league == league } val leagueChannels = mapOf(league to sportsChannelsByLeague[league].orEmpty().filter(::isVisibleContent)) val mergedLeague = withContext(Dispatchers.Default) { mergeOfficialSportsSchedule(providerForLeague, official, leagueChannels) } val now = System.currentTimeMillis() / 1000L sportsEventsCache = (sportsEventsCache.filterNot { it.league == league } + mergedLeague) .distinctBy { it.id } .sortedWith( compareBy { if (it.isLive(now)) 0 else 1 } .thenBy { it.startEpoch } .thenBy { it.title.lowercase(Locale.ROOT) } ) val summary = SportsLeagueSummary( league = league, channelCount = leagueChannels[league].orEmpty().size, eventCount = mergedLeague.size, liveCount = mergedLeague.count { it.isLive(now) }, ) sportsSummariesCache = (sportsSummariesCache.filterNot { it.league == league } + summary) .filter { it.channelCount > 0 || it.eventCount > 0 } .sortedBy { it.league.ordinal } if (currentScreen == AppScreen.SPORTS && sportsEventsCache.isNotEmpty()) sportsPreparing = false } /** * Keep visible Game Center cards genuinely live without touching the proven provider-feed path. * Only leagues with a game that is live (or has just reached its scheduled start) are polled. * A failed/empty scoreboard response is ignored, leaving the last known card and every matched * feed intact. Polling stops automatically when the viewer leaves Sports. */ private fun startSportsLiveScoreTracking() { if (sportsLiveScoreJob?.isActive == true) return sportsLiveScoreJob = viewModelScope.launch { try { while (currentScreen == AppScreen.SPORTS) { refreshLiveSportsScoresOnce() delay(12_000L) } } finally { sportsLiveScoreJob = null } } } private suspend fun refreshLiveSportsScoresOnce() { val now = System.currentTimeMillis() / 1000L val activeLeagues = sportsEventsCache.asSequence() .filter { event -> sportsScheduleRepository.supports(event.league) && !event.completed && (event.isLive(now) || now in event.startEpoch..(event.startEpoch + 20 * 60L)) } .map { it.league } .distinct() .toList() if (activeLeagues.isEmpty()) return val freshById = coroutineScope { activeLeagues.map { league -> async(Dispatchers.IO) { runCatching { sportsScheduleRepository.today(league) }.getOrDefault(emptyList()) } }.awaitAll().flatten() }.associateBy { it.id } if (freshById.isEmpty()) return var changed = false val patched = sportsEventsCache.map { current -> val fresh = freshById[current.id] ?: return@map current val updated = current.copy( awayScore = fresh.awayScore, homeScore = fresh.homeScore, awayRank = fresh.awayRank, homeRank = fresh.homeRank, status = fresh.status, network = fresh.network.ifBlank { current.network }, venue = fresh.venue.ifBlank { current.venue }, awayLogo = fresh.awayLogo.ifBlank { current.awayLogo }, homeLogo = fresh.homeLogo.ifBlank { current.homeLogo }, completed = fresh.completed, ) if (updated != current) changed = true updated } if (!changed) return sportsEventsCache = patched // Keep the protected official cache current too, but deliberately do not increment the // official revision: score ticks must never trigger expensive provider/EPG rematching. officialSportsSchedule = officialSportsSchedule.map { current -> val fresh = freshById[current.id] ?: return@map current current.copy( awayScore = fresh.awayScore, homeScore = fresh.homeScore, awayRank = fresh.awayRank, homeRank = fresh.homeRank, status = fresh.status, network = fresh.network.ifBlank { current.network }, venue = fresh.venue.ifBlank { current.venue }, awayLogo = fresh.awayLogo.ifBlank { current.awayLogo }, homeLogo = fresh.homeLogo.ifBlank { current.homeLogo }, completed = fresh.completed, ) } sportsSummariesCache = sportsSummariesCache.map { summary -> val leagueEvents = sportsEventsCache.filter { it.league == summary.league } summary.copy( eventCount = leagueEvents.size, liveCount = leagueEvents.count { it.isLive(now) }, ) } } private fun refreshOfficialSportsSchedule(force: Boolean = false) { val now = System.currentTimeMillis() / 1000L if (sportsOfficialScheduleLoading) return if (!force && officialSportsSchedule.isNotEmpty() && now - sportsOfficialScheduleLastFetchEpoch < 5 * 60L) { if (sportsEventsCache.isEmpty()) scheduleSportsDerivedRebuild() return } beginSportsLoadCycle() sportsOfficialScheduleLoading = true if (currentScreen == AppScreen.SPORTS && sportsEventsCache.isEmpty()) { sportsPreparing = true sportsLoadingStage = "Loading today's games and scores…" } viewModelScope.launch { try { // Publish today's slate as soon as it resolves. v0.4.28 waited for both today // and tomorrow across every league before Game Center could use the response. val today = runCatching { sportsScheduleRepository.today() }.getOrDefault(emptyList()) if (today.isNotEmpty()) { // The all-league endpoint is allowed to return a partial success (for example // NFL/NBA succeed while MLB transiently fails). Never replace the whole cached // slate with that partial response. Refresh only leagues that actually returned // rows and preserve other verified leagues until their own successful refresh. val returnedLeagues = today.map { it.league }.toSet() val (dayStart, _) = localDayBoundsEpoch() val windowEnd = localSportsWindowEndEpoch() val preserved = officialSportsSchedule.filter { event -> event.league !in returnedLeagues && event.endEpoch > dayStart && event.startEpoch < windowEnd } val updated = (preserved + today).distinctBy { it.id }.sortedBy { it.startEpoch } if (updated != officialSportsSchedule) { officialSportsSchedule = updated sportsOfficialRevision++ } if (currentScreen == AppScreen.SPORTS) sportsLoadingStage = "Building Game Center…" scheduleSportsDerivedRebuild() } // Tomorrow is useful for UP NEXT, but it is never allowed to compete with active // video. Finish this second pass only while the app is on a non-player screen. while (currentScreen in setOf(AppScreen.PLAYER, AppScreen.MULTIVIEW)) delay(750) val tomorrow = runCatching { sportsScheduleRepository.tomorrow() }.getOrDefault(emptyList()) if (tomorrow.isNotEmpty()) { // Append tomorrow onto the protected current slate rather than rebuilding from // `today`, which may itself be a partial multi-league response. val updated = (officialSportsSchedule + tomorrow).distinctBy { it.id }.sortedBy { it.startEpoch } if (updated != officialSportsSchedule) { officialSportsSchedule = updated sportsOfficialRevision++ } scheduleSportsDerivedRebuild() } sportsOfficialScheduleLastFetchEpoch = System.currentTimeMillis() / 1000L } finally { sportsOfficialScheduleLoading = false if (currentScreen == AppScreen.SPORTS && sportsEventsCache.isEmpty()) { sportsLoadingStage = "Matching your provider feeds…" scheduleSportsDerivedRebuild() } maybeCompleteSportsLoadCycle() } } } /** * Webplayer-style schedule authority + provider-feed matching. * Official schedule data supplies identity/status/score/network, while Xtream/EPG remains the * only source used for playback. Team channels are allowed as a fallback when EPG is incomplete. */ private fun mergeOfficialSportsSchedule( providerEvents: List, officialEvents: List, channelsByLeague: Map> = sportsChannelsByLeague, ): List { if (officialEvents.isEmpty()) return providerEvents val usedProviderIds = mutableSetOf() // Preserve the exact v0.4.28 scoring rules, but stop scoring obviously impossible // candidates. The scorer already rejects another league or >3-hour start delta; doing // those two cheap filters first avoids thousands of regex/normalization passes. val providerEventsByLeague = providerEvents.groupBy { it.league } val merged = officialEvents.map { official -> // Mirror the webplayer's schedule-authority model: only attach an EPG event when // both teams and the start window make a strong match. This prevents unrelated // games on the same league/network from being paired just because titles are similar. val matching = providerEventsByLeague[official.league].orEmpty() .asSequence() .filter { it.id !in usedProviderIds } .filter { kotlin.math.abs(it.startEpoch - official.startEpoch) <= 3 * 3600L } .map { it to sportsEventMatchScore(it, official) } .filter { it.second >= 12 } .sortedByDescending { it.second } .take(4) .map { it.first } .toList() matching.forEach { usedProviderIds += it.id } val feedMap = linkedMapOf() matching.flatMap { it.feeds }.forEach { feedMap[it.id] = it } // Provider channel names are a second matching source. A channel whose name contains // both teams is treated as a direct event feed; a strong one-team identity is treated // as a dedicated team-channel fallback. Generic league channels are not guessed. channelsByLeague[official.league].orEmpty() .asSequence() .map { channel -> channel to sportsChannelMatchScore(channel, official) } .filter { it.second >= 8 } .sortedByDescending { it.second } .take(8) .forEach { (channel, _) -> feedMap[channel.id] = channel } val providerDescription = matching.firstOrNull { it.description.isNotBlank() }?.description.orEmpty() official.copy( feeds = feedMap.values.toList(), description = providerDescription.ifBlank { official.description }, ) } // Schedule authority rule: once a league has an official slate, provider/EPG rows are // ONLY feed candidates for those official games. Never append leftover provider program // rows (Off-Air, No Game Today, network promos, postgame shows, etc.) as Sports cards. // Provider-created events are retained only for leagues that currently have no official // schedule source at all. This keeps each league stable when background EPG matching ends. val officialLeagues = officialEvents.map { it.league }.toSet() val providerOnlyForUnsupportedLeagues = providerEvents.filter { provider -> provider.id !in usedProviderIds && provider.league !in officialLeagues } return merged + providerOnlyForUnsupportedLeagues } private fun sportsEventMatchScore(provider: SportsEvent, official: SportsEvent): Int { if (provider.league != official.league) return -1 if (official.awayTeam.isBlank() || official.homeTeam.isBlank()) return -1 val deltaSeconds = kotlin.math.abs(provider.startEpoch - official.startEpoch) if (deltaSeconds > 3 * 3600L) return -1 val text = normalizeSportsMatchText("${provider.title} ${provider.description}") val awayScore = sportsTeamMatchScore(text, official.awayTeam, official.awayAliases) val homeScore = sportsTeamMatchScore(text, official.homeTeam, official.homeAliases) if (awayScore <= 0 || homeScore <= 0) return -1 var score = awayScore + homeScore val deltaMinutes = deltaSeconds / 60L score += when { deltaMinutes <= 15L -> 4 deltaMinutes <= 30L -> 2 deltaMinutes >= 120L -> -2 else -> 0 } return score } private fun sportsChannelMatchScore(channel: MediaEntry, official: SportsEvent): Int { val text = normalizeSportsMatchText(channel.name) if (text.isBlank()) return -1 val away = sportsTeamMatchScore(text, official.awayTeam, official.awayAliases) val home = sportsTeamMatchScore(text, official.homeTeam, official.homeAliases) // A title containing both teams is the strongest possible direct provider feed. if (away >= 6 && home >= 6) return away + home + 4 // A channel that is essentially one team name/alias is a safe team-feed fallback. // Do not attach generic ESPN/NFL/NBA/etc. channels to every event. val single = maxOf(away, home) val normalizedAliases = buildList { addAll(official.awayAliases) addAll(official.homeAliases) add(official.awayTeam) add(official.homeTeam) }.map(::normalizeSportsMatchText).filter { it.isNotBlank() } val exactTeamIdentity = normalizedAliases.any { alias -> text == alias || text == "$alias tv" || text == "$alias channel" } // Provider team channels are often decorated (for example "MLB 04 Yankees", "US | NYY", // "Tigers Home", etc.). Requiring the entire channel name to equal the team alias caused // verified MLB cards to show 0 feeds even though the team stream existed. At this point the // candidate is already classified into the same league, so a strong boundary team match is // safe as a fallback while generic MLB/NFL/NBA network channels still score 0. val paddedText = " $text " val decoratedTeamIdentity = single >= 6 && normalizedAliases.any { alias -> alias.length >= 2 && paddedText.contains(" $alias ") } return if ((exactTeamIdentity || decoratedTeamIdentity) && single >= 6) maxOf(8, single) else -1 } private fun sportsTeamMatchScore(text: String, team: String, aliases: List): Int { if (text.isBlank() || team.isBlank()) return 0 val candidates = (listOf(team) + aliases) .map(::normalizeSportsMatchText) .filter { it.isNotBlank() } .distinct() var best = 0 val paddedText = " $text " for (alias in candidates) { val words = alias.split(' ').filter { it.isNotBlank() } val boundaryMatch = paddedText.contains(" $alias ") val score = when { text == alias -> 10 words.size >= 2 && boundaryMatch -> 8 words.size == 1 && alias.length >= 2 && boundaryMatch -> 6 alias.length >= 5 && text.contains(alias) -> 5 else -> 0 } if (score > best) best = score } return best } private fun normalizeSportsMatchText(raw: String): String = raw .lowercase(Locale.ROOT) .replace("&", " and ") .replace(Regex("[^a-z0-9]+"), " ") .replace(Regex("\\s+"), " ") .trim() fun selectSportsLeague(league: SportLeague) { selectedSportsLeague = league // ALL is instant and uses the bulk/cached guide. Selecting a specific league gets an // independent official-schedule retry if that league is missing. Previously one successful // NFL/NBA/etc. response could keep the generic 5-minute cache warm even when MLB itself // had failed, leaving the MLB tab empty until the global cache expired. if (league != SportLeague.ALL) { refreshSports(league = league) if (sportsScheduleRepository.supports(league) && officialSportsSchedule.none { it.league == league }) { viewModelScope.launch { sportsLoadingStage = "Loading ${league.label} schedule…" warmOfficialSportsLeague(league) if (officialSportsSchedule.any { it.league == league }) { // warmOfficialSportsLeague already merged this league into the live cache. // Avoid a second provider-wide rebuild just for selecting the tab. } } } } } fun exitMultiView() { currentScreen = multiViewReturnScreen } fun setMultiViewSlot(index: Int, channel: MediaEntry?) { if (index !in 0..3) return if (channel != null && channel.type != ContentType.LIVE) return multiViewSlots = multiViewSlots.toMutableList().also { it[index] = channel } } fun allVisibleLiveChannels(): List { contentVisibilityRevision // Compose dependency for hide/show changes. val source = if (allLiveChannels.isNotEmpty()) allLiveChannels else catalogCache[ContentType.LIVE to null].orEmpty() return source.filter(::isVisibleContent).distinctBy { it.id } } fun liveChannelsForCategory(categoryId: String?): List { contentVisibilityRevision // Keep MultiView picker synced with profile visibility changes. if (categoryId == favoritesCategoryId) return favoriteLiveChannels() val visible = allVisibleLiveChannels() if (categoryId.isNullOrBlank()) return visible return visible.filter { it.categoryId == categoryId } } fun sportsCandidateChannels(league: SportLeague = SportLeague.ALL): List { contentVisibilityRevision // Compose/cache dependency for hide/show changes. if (sportsChannelIndex.isEmpty() && (allLiveChannels.isNotEmpty() || catalogs[ContentType.LIVE].orEmpty().isNotEmpty())) { rebuildSportsChannelIndex() } val source = if (league == SportLeague.ALL) allSportsChannels else sportsChannelsByLeague[league].orEmpty() return source.filter(::isVisibleContent) } fun sportsEvents(league: SportLeague = selectedSportsLeague): List { val allEvents = allSportsEventsCached() return if (league == SportLeague.ALL) allEvents else allEvents.filter { it.league == league } } private fun allSportsEventsCached(): List { if (sportsEventsCacheRevision != sportsEpgRevision) scheduleSportsDerivedRebuild() return sportsEventsCache } /** * Build Sports event matching off the Compose/main thread. The previous implementation * walked every sports channel, every EPG row, regex-matched titles and merged scoreboards * synchronously while SportsScreen was composing. Large provider guides could freeze or * kill lower-memory TV boxes simply by opening Sports. */ private fun scheduleSportsDerivedRebuild() { if (sportsDerivedBuildJob?.isActive == true) return if (sportsChannelIndex.isEmpty() && (allLiveChannels.isNotEmpty() || catalogs[ContentType.LIVE].orEmpty().isNotEmpty())) { rebuildSportsChannelIndex() } val revision = sportsEpgRevision val officialRevision = sportsOfficialRevision val channels = (if (allSportsChannels.isNotEmpty()) allSportsChannels else sportsCandidateChannels(SportLeague.ALL)) .filter(::isVisibleContent) .distinctBy { it.id } val categoryNames = categories[ContentType.LIVE].orEmpty().associate { it.id to it.name } // Snapshot only relevant EPG rows while we're on the main thread; the heavy matching // and sorting then runs entirely on Dispatchers.Default. val epgSnapshot = channels.associate { channel -> channel.id to epgByChannel[channel.id].orEmpty().toList() } val officialSnapshot = officialSportsSchedule.toList() val sportsChannelIndexSnapshot = sportsChannelIndex.toMap() val channelsByLeagueSnapshot = sportsChannelsByLeague.mapValues { (_, value) -> value.filter(::isVisibleContent).distinctBy { it.id } } val previousEvents = sportsEventsCache.toList() val previousSummaries = sportsSummariesCache.toList() sportsDerivedBuildJob = viewModelScope.launch { try { val result = try { withContext(Dispatchers.Default) { buildSportsDerivedData( channels = channels, categoryNames = categoryNames, epgSnapshot = epgSnapshot, officialSnapshot = officialSnapshot, sportsChannelIndexSnapshot = sportsChannelIndexSnapshot, channelsByLeagueSnapshot = channelsByLeagueSnapshot, ) } } catch (cancel: kotlinx.coroutines.CancellationException) { throw cancel } catch (_: Throwable) { // A transient bad EPG row/provider response must never erase a valid Sports // slate. Keep the last good cache instead of publishing an empty rebuild. previousEvents to previousSummaries } if (revision == sportsEpgRevision && officialRevision == sportsOfficialRevision) { // buildSportsDerivedData already merged the exact officialSnapshot used by // this job. The revision guard above prevents a stale snapshot from publishing, // so do not perform that expensive merge a second time on the main coroutine. val now = System.currentTimeMillis() / 1000L val publishedEvents = result.first .distinctBy { it.id } .sortedWith( compareBy { if (it.isLive(now)) 0 else 1 } .thenBy { it.startEpoch } .thenBy { it.title.lowercase(Locale.ROOT) } ) val publishedSummaries = SportLeague.entries .filter { it != SportLeague.ALL } .map { league -> val leagueEvents = publishedEvents.filter { it.league == league } SportsLeagueSummary( league = league, channelCount = channelsByLeagueSnapshot[league].orEmpty().size, eventCount = leagueEvents.size, liveCount = leagueEvents.count { it.isLive(now) }, ) } .filter { it.channelCount > 0 || it.eventCount > 0 } sportsEventsCache = publishedEvents sportsSummariesCache = publishedSummaries sportsEventsCacheRevision = revision sportsSummariesCacheRevision = revision if (currentScreen == AppScreen.SPORTS) { if (publishedEvents.isNotEmpty() || !sportsOfficialScheduleLoading) { sportsPreparing = false } else { sportsPreparing = true sportsLoadingStage = "Loading today's games and scores…" } } } } finally { sportsDerivedBuildJob = null // If EPG/schedule data changed while this build was running, immediately rebuild // once more from the newest snapshot rather than publishing stale results. if (sportsEventsCacheRevision != sportsEpgRevision || officialRevision != sportsOfficialRevision) { // Coalesce all changes that happened during this build into one newest-snapshot // pass. This is a single follow-up, not one full rebuild per league update. scheduleSportsDerivedRebuild() } else { maybeCompleteSportsLoadCycle() } } } } private fun buildSportsDerivedData( channels: List, categoryNames: Map, epgSnapshot: Map>, officialSnapshot: List, sportsChannelIndexSnapshot: Map, channelsByLeagueSnapshot: Map>, ): Pair, List> { // Official schedule rows must survive even when the provider has no channel whose NAME // can be classified as a sports feed. This matters for postseason games carried on // general national networks and also prevents a transient provider-index gap from hiding // the real game slate entirely. val (dayStart, _) = localDayBoundsEpoch() val sportsWindowEnd = localSportsWindowEndEpoch() val grouped = linkedMapOf() channels.forEach { channel -> val programs = epgSnapshot[channel.id].orEmpty() if (programs.isEmpty()) return@forEach val category = categoryNames[channel.categoryId].orEmpty() programs.asSequence() .filter { it.endEpoch > dayStart && it.startEpoch < sportsWindowEnd } .forEach programLoop@ { program -> val detected = detectSportLeague(channel, category, program.title, program.description) ?: sportsChannelIndexSnapshot[channel.id] ?: return@programLoop val title = cleanSportsTitle(program.title).ifBlank { channel.name } if (!looksLikeSportsProgram(title, category, detected)) return@programLoop val bucket = program.startEpoch / 600L val key = "${detected.name}:${normalizeSportsEventTitle(title)}:$bucket" val acc = grouped.getOrPut(key) { MutableSportsEvent( league = detected, title = title, startEpoch = program.startEpoch, endEpoch = program.endEpoch, description = program.description, ) } acc.startEpoch = minOf(acc.startEpoch, program.startEpoch) acc.endEpoch = maxOf(acc.endEpoch, program.endEpoch) if (acc.description.isBlank() && program.description.isNotBlank()) acc.description = program.description if (acc.feeds.none { it.id == channel.id }) acc.feeds.add(channel) } } val now = System.currentTimeMillis() / 1000L val providerEvents = grouped.entries.map { (key, acc) -> SportsEvent( id = key, league = acc.league, title = acc.title, startEpoch = acc.startEpoch, endEpoch = acc.endEpoch, feeds = acc.feeds.toList(), description = acc.description, ) } val mergedEvents = mergeOfficialSportsSchedule( providerEvents = providerEvents, officialEvents = officialSnapshot, channelsByLeague = channelsByLeagueSnapshot, ) .distinctBy { it.id } .sortedWith( compareBy { if (it.isLive(now)) 0 else 1 } .thenBy { it.startEpoch } .thenBy { it.title.lowercase(Locale.ROOT) } ) val eventsByLeague = mergedEvents.groupBy { it.league } val summaries = SportLeague.entries .filter { it != SportLeague.ALL } .map { league -> val leagueEvents = eventsByLeague[league].orEmpty() SportsLeagueSummary( league = league, channelCount = channelsByLeagueSnapshot[league].orEmpty().size, eventCount = leagueEvents.size, liveCount = leagueEvents.count { it.isLive(now) }, ) } .filter { it.channelCount > 0 || it.eventCount > 0 } return mergedEvents to summaries } fun sportsLeagueSummaries(): List { if (sportsSummariesCacheRevision != sportsEpgRevision) scheduleSportsDerivedRebuild() return sportsSummariesCache } fun sportsLiveCount(): Int { val now = System.currentTimeMillis() / 1000L return allSportsEventsCached().count { it.isLive(now) } } /** * Sports Turbo refresh strategy: * - Opening ALL Sports never fires hundreds of get_short_epg requests. * - We immediately use the full/cached EPG that TiviLux already owns. * - Selecting one league fills only a small number of missing feeds in background. * - The provider-wide bulk EPG refresh continues to populate the rest once, globally. * * This makes Sports open essentially as fast as a normal cached screen while still * allowing league-specific EPG gaps to self-heal without hammering the provider. */ fun refreshSports(force: Boolean = false, league: SportLeague = SportLeague.ALL) { if (force) { beginSportsLoadCycle(forceNew = true) sportsBackgroundReady = false } // League isolation: selecting MLB/Golf/NFL/etc. must never kick off a global all-league // schedule refresh that can race another tab and replace its state. ALL may refresh the // complete slate; a specific tab refreshes only its own official schedule, sequentially. if (league == SportLeague.ALL) { refreshOfficialSportsSchedule(force = force) } else if (sportsScheduleRepository.supports(league)) { val hasLeague = officialSportsSchedule.any { it.league == league } if (force || !hasLeague) { viewModelScope.launch { sportsLoadingStage = "Loading ${league.label} schedule…" warmOfficialSportsLeague(league) } } } val creds = credentials ?: return if (sportsScanning) return // Never crawl every sports feed one-by-one. The global bulk EPG/cache owns ALL. if (league == SportLeague.ALL && !force) { sportsLastScanEpoch = System.currentTimeMillis() / 1000L return } val allCandidates = sportsCandidateChannels(league) if (allCandidates.isEmpty()) return val now = System.currentTimeMillis() / 1000L val last = sportsLastLeagueScanEpoch[league] ?: 0L if (!force && now - last < 10 * 60L) return val missing = if (force) allCandidates else allCandidates.filterNot { epgByChannel.containsKey(it.id) } if (missing.isEmpty()) { sportsLastLeagueScanEpoch[league] = now if (league == SportLeague.ALL) sportsLastScanEpoch = now return } // A league tab should become useful quickly. Do a small foreground-priority fill; // the bulk background guide handles the rest without duplicating hundreds of calls. val maxFeedsThisPass = if (league == SportLeague.ALL) 24 else 18 val candidates = missing.take(maxFeedsThisPass) viewModelScope.launch { sportsScanning = true sportsScanCompleted = 0 sportsScanTotal = candidates.size try { candidates.chunked(6).forEach { batch -> val results = coroutineScope { batch.map { channel -> async { channel.id to runCatching { repository.epg(creds, channel.id, 10) } .getOrDefault(emptyList()) } }.awaitAll() } results.forEach { (channelId, programs) -> epgByChannel[channelId] = programs } if (results.isNotEmpty()) markSportsEpgChanged() sportsScanCompleted += batch.size // Give Compose/remote input a frame between network batches. kotlinx.coroutines.yield() } sportsLastLeagueScanEpoch[league] = System.currentTimeMillis() / 1000L if (league == SportLeague.ALL) sportsLastScanEpoch = System.currentTimeMillis() / 1000L } finally { sportsScanning = false maybeCompleteSportsLoadCycle() } } } fun playSportsChannel(channel: MediaEntry) { play(channel, AppScreen.SPORTS) } fun selectProfile(profile: HouseholdProfile) { activeProfile = profileStore.select(profile.id) libraryStore.setActiveProfile(activeProfile.id) favoriteKeysState = libraryStore.favoriteKeys() refreshContentVisibilityCache() contentVisibilityRevision++ searchIndexStamp = null recentLiveChannels = emptyList() multiViewSlots = List(4) { null } if (selectedCategories[ContentType.LIVE] == favoritesCategoryId) { catalogs = catalogs + (ContentType.LIVE to favoriteLiveChannels()) } playbackRevision++ currentScreen = AppScreen.HOME } fun createProfile(name: String) { profiles = profileStore.create(name) } fun renameProfile(profile: HouseholdProfile, name: String) { profiles = profileStore.rename(profile.id, name) activeProfile = profileStore.activeProfile() } fun deleteProfile(profile: HouseholdProfile) { if (profiles.size <= 1) return libraryStore.clearProfile(profile.id) playbackStore.clearProfile(profile.id) profiles = profileStore.delete(profile.id) activeProfile = profileStore.activeProfile() libraryStore.setActiveProfile(activeProfile.id) favoriteKeysState = libraryStore.favoriteKeys() refreshContentVisibilityCache() contentVisibilityRevision++ searchIndexStamp = null recentLiveChannels = emptyList() multiViewSlots = List(4) { null } if (selectedCategories[ContentType.LIVE] == favoritesCategoryId) { catalogs = catalogs + (ContentType.LIVE to favoriteLiveChannels()) } playbackRevision++ } fun continueWatching(): List { playbackRevision // Compose dependency contentVisibilityRevision return playbackStore.continueWatching(activeProfile.id).filter { isVisibleContent(it.item) } } fun playbackPosition(item: MediaEntry?): Long { val target = item ?: return 0L return playbackStore.progress(activeProfile.id, target)?.takeUnless { it.completed }?.positionMs ?: 0L } fun episodeProgress(episode: tv.tivilux.nativeplayer.model.Episode): PlaybackProgress? { playbackRevision // Compose dependency val seriesName = selectedSeriesDetail?.series?.name.orEmpty() val media = repository.episodeAsMedia(episode, seriesName) return playbackStore.progress(activeProfile.id, media) } fun recordPlaybackProgress(item: MediaEntry?, positionMs: Long, durationMs: Long, ended: Boolean = false) { val target = item ?: return if (target.type !in setOf(ContentType.MOVIE, ContentType.EPISODE)) return val percentComplete = durationMs > 0L && positionMs >= (durationMs * 0.95).toLong() val completed = ended || percentComplete val next = if (target.type == ContentType.EPISODE) playbackNextItem else null playbackStore.record( profileId = activeProfile.id, item = target, positionMs = if (completed) durationMs.coerceAtLeast(positionMs) else positionMs, durationMs = durationMs, completed = completed, nextItem = next, ) libraryStore.remember(target) playbackRevision++ if (ended && target.type == ContentType.EPISODE && settings.autoplayNextEpisode && next != null) { val returnTo = previousScreen.takeIf { it != AppScreen.PLAYER } ?: AppScreen.HOME prepareNextEpisodeFor(next) play(next, returnTo) } } fun playContinueWatching(progress: PlaybackProgress) { val item = progress.item if (item.type == ContentType.EPISODE) prepareNextEpisodeFor(item) play(item, AppScreen.HOME) } fun removeFromContinueWatching(progress: PlaybackProgress) { playbackStore.removeFromContinueWatching(activeProfile.id, progress.item) playbackRevision++ } fun updateSettings(newSettings: AppSettings) { val transportChanged = settings.preferHlsLive != newSettings.preferHlsLive settings = newSettings settingsStore.save(newSettings) if (transportChanged) { val channel = playingItem?.takeIf { it.type == ContentType.LIVE } ?: tunedChannel?.takeIf { playingItem == null } val creds = credentials if (channel != null && creds != null) { playingUrlCandidates = repository.streamUrlCandidates(creds, channel, newSettings.preferHlsLive) playingUrl = playingUrlCandidates.firstOrNull() } } } fun guideSortForCategory(categoryId: String?): String { guideOrderRevision return libraryStore.guideSortForCategory(categoryId, settings.channelSort) } fun setGuideSortForCategory(categoryId: String?, sort: String) { if (categoryId.isNullOrBlank()) { updateSettings(settings.copy(channelSort = sort)) } else { libraryStore.saveGuideSortForCategory(categoryId, sort) guideOrderRevision++ } } fun manualGuideOrder(favorites: Boolean = false, categoryId: String? = null): List { guideOrderRevision // Compose dependency: saving an order refreshes the Guide immediately. return libraryStore.manualGuideOrder(favorites, categoryId) } /** * Merge a manually reordered visible Guide subset back into the profile's complete order. * This means rearranging one provider group does not erase the position of channels that * belong to other groups. Favorites use a completely independent order list. */ fun saveManualGuideOrder(orderedVisibleIds: List, favorites: Boolean = false, categoryId: String? = null) { val visible = orderedVisibleIds.filter { it.isNotBlank() }.distinct() if (visible.isEmpty()) return val universe = if (favorites) { favoriteLiveChannels().map { it.id } } else { val master = if (allLiveChannels.isNotEmpty()) allLiveChannels else catalogCache[ContentType.LIVE to null].orEmpty() master.map { it.id } } val base = (libraryStore.manualGuideOrder(favorites, categoryId) + universe + visible).distinct().toMutableList() val visibleSet = visible.toHashSet() val replacement = java.util.ArrayDeque(visible) for (i in base.indices) { if (base[i] in visibleSet && replacement.isNotEmpty()) { base[i] = replacement.removeFirst() } } while (replacement.isNotEmpty()) base.add(replacement.removeFirst()) libraryStore.saveManualGuideOrder(base.distinct(), favorites, categoryId) guideOrderRevision++ } fun toggleFavorite(item: MediaEntry): Boolean { val result = libraryStore.toggle(item) favoriteKeysState = libraryStore.favoriteKeys() if (item.type == ContentType.LIVE && selectedCategories[ContentType.LIVE] == favoritesCategoryId) { catalogs = catalogs + (ContentType.LIVE to favoriteLiveChannels()) } return result } fun isFavorite(item: MediaEntry): Boolean = favoriteKeysState.contains("${item.type.name}:${item.id}") fun lastPlayed(): MediaEntry? { contentVisibilityRevision return libraryStore.lastPlayed()?.takeIf(::isVisibleContent) } fun favoritesFromLoaded(): List { contentVisibilityRevision val stored = libraryStore.favoriteItems() val loaded = catalogs.values.flatten() return (stored + loaded.filter { isFavorite(it) }) .filter(::isVisibleContent) .distinctBy { "${it.type.name}:${it.id}" } } fun isFavoritesGuideSelected(): Boolean = selectedCategories[ContentType.LIVE] == favoritesCategoryId fun categoryManagementList(type: ContentType): List { val revision = contentVisibilityRevision val source = categories[type].orEmpty() val cached = orderedCategoryCache[type] if (cached != null && cached.source === source && cached.revision == revision) return cached.ordered val provider = source.filterNot { it.id == favoritesCategoryId } val rank = libraryStore.categoryOrder(type).withIndex().associate { it.value to it.index } val providerRank = provider.withIndex().associate { it.value.id to it.index } val ordered = provider.sortedWith( compareBy { rank[it.id] ?: Int.MAX_VALUE } .thenBy { providerRank[it.id] ?: Int.MAX_VALUE } ) orderedCategoryCache[type] = OrderedCategorySnapshot(source, revision, ordered) return ordered } fun visibleCategories(type: ContentType): List { contentVisibilityRevision val hidden = hiddenCategoryCache[type].orEmpty() return visibleCategoryCache.getOrPut(type) { tv.tivilux.nativeplayer.data.VisibleCatalogCache() }.get(categoryManagementList(type), contentVisibilityRevision) { it.id !in hidden } } fun hiddenCategoryIds(type: ContentType): Set { contentVisibilityRevision return hiddenCategoryCache[type].orEmpty() } fun hiddenLiveChannelIds(): Set { contentVisibilityRevision return hiddenLiveChannelCache } fun hiddenLiveChannels(): List { contentVisibilityRevision val hidden = hiddenLiveChannelCache val master = if (allLiveChannels.isNotEmpty()) allLiveChannels else catalogCache[ContentType.LIVE to null].orEmpty() return master.filter { it.id in hidden }.sortedBy { it.name.lowercase(Locale.ROOT) } } fun moveCategory(type: ContentType, categoryId: String, delta: Int) { val ordered = categoryManagementList(type).toMutableList() val from = ordered.indexOfFirst { it.id == categoryId } if (from < 0) return val to = (from + delta).coerceIn(0, ordered.lastIndex) if (to == from) return val item = ordered.removeAt(from) ordered.add(to, item) libraryStore.saveCategoryOrder(type, ordered.map { it.id }) contentVisibilityRevision++ } fun saveCategoryOrder(type: ContentType, orderedVisibleIds: List) { val providerIds = categories[type].orEmpty() .filterNot { it.id == favoritesCategoryId } .map { it.id } if (providerIds.isEmpty()) return val providerSet = providerIds.toHashSet() val requested = orderedVisibleIds .filter { it in providerSet } .distinct() val requestedSet = requested.toHashSet() val completeOrder = requested + providerIds.filterNot { it in requestedSet } libraryStore.saveCategoryOrder(type, completeOrder) contentVisibilityRevision++ } fun toggleCategoryHidden(type: ContentType, categoryId: String) { if (categoryId.isBlank() || categoryId == favoritesCategoryId) return val nowHidden = libraryStore.toggleCategoryHidden(type, categoryId) refreshContentVisibilityCache() if (nowHidden && selectedCategories[type] == categoryId) { selectedCategories = selectedCategories + (type to null) val master = catalogCache[type to null].orEmpty() if (master.isNotEmpty()) catalogs = catalogs + (type to master) } contentVisibilityRevision++ searchIndexStamp = null searchResultsState = searchResultsState.filter(::isVisibleContent) markSportsEpgChanged() } fun toggleLiveChannelHidden(channel: MediaEntry) { if (channel.type != ContentType.LIVE) return val nowHidden = libraryStore.toggleLiveChannelHidden(channel.id) refreshContentVisibilityCache() if (nowHidden) { recentLiveChannels = recentLiveChannels.filter(::isVisibleContent) multiViewSlots = multiViewSlots.map { if (it?.id == channel.id) null else it } if (previousTunedChannel?.let(::isVisibleContent) == false) { previousTunedChannel = recentLiveChannels.firstOrNull { it.id != channel.id } } } contentVisibilityRevision++ searchIndexStamp = null searchResultsState = searchResultsState.filter(::isVisibleContent) if (selectedChannel?.id == channel.id) selectedChannel = catalogForDisplay(ContentType.LIVE).firstOrNull() markSportsEpgChanged() } // Search uses the full cached provider catalog, independent of the selected category. fun catalogForSearch(type: ContentType): List = catalogCache[type to null].orEmpty().filter { isVisibleContent(it) } fun catalogForDisplay(type: ContentType): List { val revision = contentVisibilityRevision val source = catalogs[type].orEmpty() return visibleCatalogCache.getOrPut(type) { tv.tivilux.nativeplayer.data.VisibleCatalogCache() }.get(source, revision) { isVisibleContent(it) } } private fun isVisibleContent(item: MediaEntry): Boolean { if (item.categoryId.isNotBlank() && item.categoryId in hiddenCategoryCache[item.type].orEmpty()) return false if (item.type == ContentType.LIVE && item.id in hiddenLiveChannelCache) return false return true } fun liveGuideCategories(): List { val provider = visibleCategories(ContentType.LIVE) return if (favoriteLiveChannels().isNotEmpty() || selectedCategories[ContentType.LIVE] == favoritesCategoryId) { listOf(Category(favoritesCategoryId, "Favorites")) + provider.filterNot { it.id == favoritesCategoryId } } else { provider } } fun favoriteLiveChannels(): List { contentVisibilityRevision val storedLive = libraryStore.favoriteItems().filter { it.type == ContentType.LIVE } val master = if (allLiveChannels.isNotEmpty()) allLiveChannels else catalogs[ContentType.LIVE].orEmpty() val loadedFavorites = master.filter { isFavorite(it) } val byId = master.associateBy { it.id } return (loadedFavorites + storedLive.map { byId[it.id] ?: it }) .filter(::isVisibleContent) .distinctBy { it.id } } fun updateSearchQuery(query: String) { searchQuery = query searchJob?.cancel() val normalized = query.trim().lowercase(Locale.ROOT) if (normalized.isBlank()) { searchResultsState = emptyList() return } // Capture immutable list references on Main before doing CPU work off-thread. val live = catalogCache[ContentType.LIVE to null].orEmpty().ifEmpty { allLiveChannels } val movies = catalogCache[ContentType.MOVIE to null].orEmpty().ifEmpty { catalogs[ContentType.MOVIE].orEmpty() } val series = catalogCache[ContentType.SERIES to null].orEmpty().ifEmpty { catalogs[ContentType.SERIES].orEmpty() } val stamp = SearchIndexStamp( liveIdentity = System.identityHashCode(live), liveSize = live.size, movieIdentity = System.identityHashCode(movies), movieSize = movies.size, seriesIdentity = System.identityHashCode(series), seriesSize = series.size, visibilityRevision = contentVisibilityRevision, ) searchJob = viewModelScope.launch { // Debounce text/remote keyboard input so rapid typing never queues full-library scans. delay(130) val results = withContext(Dispatchers.Default) { val index = if (searchIndexStamp == stamp && searchIndex.isNotEmpty()) { searchIndex } else { val estimatedSize = live.size + movies.size + series.size val seen = HashSet(estimatedSize.coerceAtLeast(16)) val rebuilt = ArrayList(estimatedSize) var counter = 0 for (source in listOf(live, movies, series)) { for (item in source) { if (!isVisibleContent(item)) continue if (seen.add("${item.type}:${item.id}")) { rebuilt += SearchIndexEntry(item, item.name.lowercase(Locale.ROOT)) } if ((++counter and 0x7FF) == 0) kotlinx.coroutines.yield() } } searchIndexStamp = stamp searchIndex = rebuilt rebuilt } // Prefer title-prefix matches without sorting the entire result set. val prefix = ArrayList(64) val contains = ArrayList(186) var counter = 0 for (entry in index) { when { entry.normalizedName.startsWith(normalized) -> if (prefix.size < 250) prefix += entry.item entry.normalizedName.contains(normalized) -> if (contains.size < 250) contains += entry.item } if ((++counter and 0x7FF) == 0) kotlinx.coroutines.yield() if (prefix.size >= 250) break } (prefix + contains).take(250) } if (searchQuery.trim().lowercase(Locale.ROOT) == normalized) { searchResultsState = results } } } fun searchResults(): List = searchResultsState fun logout() { credentials?.let { startupChannelPrefs.edit().remove(lastChannelKey(it)).apply() } credentialStore.clear() credentials = null session = null categories = emptyMap() catalogs = emptyMap() allLiveChannels = emptyList() sportsChannelIndex = emptyMap() sportsChannelsByLeague = emptyMap() allSportsChannels = emptyList() sportsEventsCache = emptyList() sportsEventsCacheRevision = -1L sportsSummariesCache = emptyList() sportsSummariesCacheRevision = -1L sportsEpgRevision = 0L sportsLastLeagueScanEpoch.clear() officialSportsSchedule = emptyList() sportsOfficialScheduleLastFetchEpoch = 0L sportsOfficialScheduleLoading = false catalogCache.clear() visibleCatalogCache.clear() orderedCategoryCache.clear() visibleCategoryCache.clear() movieDetailCache.clear() seriesDetailCache.clear() searchJob?.cancel() searchJob = null searchIndexStamp = null searchIndex = emptyList() searchQuery = "" searchResultsState = emptyList() selectedChannel = null guideOpenAnchorChannelId = null guideInteractionBusy = false tunedChannel = null previousTunedChannel = null recentLiveChannels = emptyList() epgByChannel.clear() markSportsEpgChanged() selectedSportsLeague = SportLeague.ALL sportsScanning = false sportsScanCompleted = 0 sportsScanTotal = 0 sportsLastScanEpoch = 0L sportsPreparing = false sportsLoadingStage = "Loading TiviLux Game Center…" sportsReadyNoticeToken = 0L sportsReadyNoticePending = false sportsLoadCycle = 0L sportsReadyCycle = -1L sportsLoadCycleInProgress = false sportsPrefetchJob?.cancel() sportsPrefetchJob = null selectedMovieDetail = null selectedSeriesDetail = null playingItem = null playingUrl = null playingUrlCandidates = emptyList() multiViewSlots = List(4) { null } error = null currentScreen = AppScreen.HOME } } enum class StartupStage { LIVE, EPG, LIBRARY, READY } enum class AppScreen { HOME, LIVE, MULTIVIEW, SPORTS, MOVIES, SERIES, FAVORITES, SEARCH, SETTINGS, PROFILES, MOVIE_DETAIL, SERIES_DETAIL, PLAYER } private data class MutableSportsEvent( val league: SportLeague, val title: String, var startEpoch: Long, var endEpoch: Long, var description: String, val feeds: MutableList = mutableListOf(), ) private val NFL_TEAMS = listOf( "arizona cardinals", "atlanta falcons", "baltimore ravens", "buffalo bills", "carolina panthers", "chicago bears", "cincinnati bengals", "cleveland browns", "dallas cowboys", "denver broncos", "detroit lions", "green bay packers", "houston texans", "indianapolis colts", "jacksonville jaguars", "kansas city chiefs", "las vegas raiders", "los angeles chargers", "los angeles rams", "miami dolphins", "minnesota vikings", "new england patriots", "new orleans saints", "new york giants", "new york jets", "philadelphia eagles", "pittsburgh steelers", "san francisco 49ers", "seattle seahawks", "tampa bay buccaneers", "tennessee titans", "washington commanders" ) private val MLB_TEAMS = listOf( "arizona diamondbacks", "atlanta braves", "baltimore orioles", "boston red sox", "chicago cubs", "chicago white sox", "cincinnati reds", "cleveland guardians", "colorado rockies", "detroit tigers", "houston astros", "kansas city royals", "los angeles angels", "los angeles dodgers", "miami marlins", "milwaukee brewers", "minnesota twins", "new york mets", "new york yankees", "athletics", "philadelphia phillies", "pittsburgh pirates", "san diego padres", "san francisco giants", "seattle mariners", "st louis cardinals", "st. louis cardinals", "tampa bay rays", "texas rangers", "toronto blue jays", "washington nationals" ) private val NBA_TEAMS = listOf( "atlanta hawks", "boston celtics", "brooklyn nets", "charlotte hornets", "chicago bulls", "cleveland cavaliers", "dallas mavericks", "denver nuggets", "detroit pistons", "golden state warriors", "houston rockets", "indiana pacers", "la clippers", "los angeles clippers", "los angeles lakers", "memphis grizzlies", "miami heat", "milwaukee bucks", "minnesota timberwolves", "new orleans pelicans", "new york knicks", "oklahoma city thunder", "orlando magic", "philadelphia 76ers", "phoenix suns", "portland trail blazers", "sacramento kings", "san antonio spurs", "toronto raptors", "utah jazz", "washington wizards" ) private val WNBA_TEAMS = listOf( "atlanta dream", "chicago sky", "connecticut sun", "dallas wings", "golden state valkyries", "indiana fever", "las vegas aces", "los angeles sparks", "minnesota lynx", "new york liberty", "phoenix mercury", "seattle storm", "washington mystics", "portland fire", "toronto tempo" ) private val NHL_TEAMS = listOf( "anaheim ducks", "boston bruins", "buffalo sabres", "calgary flames", "carolina hurricanes", "chicago blackhawks", "colorado avalanche", "columbus blue jackets", "dallas stars", "detroit red wings", "edmonton oilers", "florida panthers", "los angeles kings", "minnesota wild", "montreal canadiens", "nashville predators", "new jersey devils", "new york islanders", "new york rangers", "ottawa senators", "philadelphia flyers", "pittsburgh penguins", "san jose sharks", "seattle kraken", "st louis blues", "st. louis blues", "tampa bay lightning", "toronto maple leafs", "utah mammoth", "vancouver canucks", "vegas golden knights", "washington capitals", "winnipeg jets" ) private fun detectSportLeague( channel: MediaEntry, categoryName: String, programTitle: String = "", programDescription: String = "", ): SportLeague? { val text = listOf(channel.name, categoryName, programTitle, programDescription) .joinToString(" ") .lowercase() .replace("&", " and ") fun has(vararg terms: String) = terms.any { text.contains(it) } fun hasTeam(teams: List) = teams.any { text.contains(it) } if (has("wnba", "women's national basketball", "womens national basketball") || hasTeam(WNBA_TEAMS)) return SportLeague.WNBA if (has("college football", "ncaa football", "ncaaf", "cfb ", " sec network", "acc network", "big ten network", "b1g")) return SportLeague.COLLEGE_FOOTBALL if (has("college basketball", "ncaa basketball", "ncaab", "march madness")) return SportLeague.COLLEGE_BASKETBALL if (has("nfl", "national football league", "nfl redzone", "sunday ticket") || hasTeam(NFL_TEAMS)) return SportLeague.NFL if (has("mlb", "major league baseball", "mlb extra innings") || hasTeam(MLB_TEAMS)) return SportLeague.MLB if (has("nhl", "national hockey league", "nhl center ice") || hasTeam(NHL_TEAMS)) return SportLeague.NHL if (has("nba", "national basketball association", "nba league pass") || hasTeam(NBA_TEAMS)) return SportLeague.NBA if (has("soccer", "football club", "premier league", "uefa", "champions league", "europa league", "la liga", "serie a", "bundesliga", "ligue 1", "mls", "fifa", "concacaf", "copa ")) return SportLeague.SOCCER if (has("golf", "pga", "lpga", "ryder cup", "the masters", "open championship")) return SportLeague.GOLF if (has("ufc", "mma", "boxing", "fight night", "bare knuckle", "bkfc", "bellator", "pfl ")) return SportLeague.COMBAT if (has("nascar", "formula 1", "formula one", " f1 ", "indycar", "motogp", "motorsport", "racing")) return SportLeague.MOTORSPORTS if (has("tennis", " atp ", " wta ", "wimbledon", "us open tennis", "australian open", "french open")) return SportLeague.TENNIS if (has("ppv", "pay per view", "pay-per-view", "wwe", "aew", "wrestlemania")) return SportLeague.PPV val sportsCategory = has( "sports", "sport)", "(sport", "espn", "fox sports", "cbs sports", "nbc sports", "sky sports", "bein sports", "sportsnet", "tsn", "stadium" ) return if (sportsCategory) SportLeague.OTHER else null } private fun looksLikeSportsProgram(title: String, categoryName: String, league: SportLeague): Boolean { if (league != SportLeague.OTHER) return true val text = "$title $categoryName".lowercase() return listOf( "sport", "game", "match", "vs", " at ", "live", "football", "baseball", "basketball", "hockey", "soccer", "golf", "tennis", "boxing", "mma", "racing", "highlights", "sportscenter" ).any { text.contains(it) } } private fun cleanSportsTitle(raw: String): String = raw .replace(Regex("\\s+"), " ") .replace(Regex("(?i)\\b(UHD|FHD|HD|4K|HEVC|H265|H264)\\b"), "") .replace(Regex("\\s+"), " ") .trim(' ', '-', '|', ':') private fun normalizeSportsEventTitle(raw: String): String = cleanSportsTitle(raw) .lowercase() .replace("@", " at ") .replace(Regex("(?i)\\bversus\\b|\\bvs\\.?\\b"), " at ") .replace(Regex("[^a-z0-9]+"), " ") .replace(Regex("\\s+"), " ") .trim() private fun localDayBoundsEpoch(): Pair { val calendar = java.util.Calendar.getInstance().apply { set(java.util.Calendar.HOUR_OF_DAY, 0) set(java.util.Calendar.MINUTE, 0) set(java.util.Calendar.SECOND, 0) set(java.util.Calendar.MILLISECOND, 0) } val start = calendar.timeInMillis / 1000L calendar.add(java.util.Calendar.DAY_OF_MONTH, 1) return start to (calendar.timeInMillis / 1000L) } private fun localSportsWindowEndEpoch(): Long { val calendar = java.util.Calendar.getInstance().apply { set(java.util.Calendar.HOUR_OF_DAY, 0) set(java.util.Calendar.MINUTE, 0) set(java.util.Calendar.SECOND, 0) set(java.util.Calendar.MILLISECOND, 0) add(java.util.Calendar.DAY_OF_MONTH, 2) } return calendar.timeInMillis / 1000L }