package tv.tivilux.nativeplayer.data import android.content.Context import tv.tivilux.nativeplayer.model.Category import tv.tivilux.nativeplayer.model.Credentials import tv.tivilux.nativeplayer.model.EpgProgram import tv.tivilux.nativeplayer.model.MediaEntry import java.io.File import java.io.FileInputStream import java.io.FileOutputStream import java.io.ObjectInputStream import java.io.ObjectOutputStream import java.io.Serializable import java.util.zip.GZIPInputStream import java.util.zip.GZIPOutputStream /** * On-device provider snapshot. * * v0.4 keeps the old all-in-one v2 file for upgrade compatibility, but also writes a * segmented v3 cache. On later launches TiviLux only has to deserialize the small Live * TV segment before showing Home; the much larger EPG/Movie/Series segments hydrate in * parallel after the UI is already interactive. */ data class StartupSnapshot( val fingerprint: String, val savedAtMillis: Long, val liveCategories: List, val liveChannels: List, val epgByChannel: Map>, val movieCategories: List, val movies: List, val seriesCategories: List, val series: List, ) : Serializable data class FastCacheMeta( val fingerprint: String, val savedAtMillis: Long, val liveCount: Int, val epgChannelCount: Int, val movieCount: Int, val seriesCount: Int, ) : Serializable data class FastLiveCache( val categories: List, val channels: List, ) : Serializable data class FastLibraryCache( val categories: List, val entries: List, ) : Serializable data class FastEpgCache( val guide: Map>, ) : Serializable class StartupCacheStore(context: Context) { private val dir = File(context.filesDir, "startup-cache").apply { mkdirs() } private val legacyFile = File(dir, "catalog-v2.bin.gz") private val metaFile = File(dir, "catalog-v3-meta.bin") private val liveFile = File(dir, "catalog-v3-live.bin.gz") private val epgFile = File(dir, "catalog-v3-epg.bin.gz") private val moviesFile = File(dir, "catalog-v3-movies.bin.gz") private val seriesFile = File(dir, "catalog-v3-series.bin.gz") /** Compatibility loader for users upgrading from the 0.3.x cache. */ fun load(credentials: Credentials): StartupSnapshot? { if (!legacyFile.exists() || legacyFile.length() <= 0L) return null return runCatching { readGzip(legacyFile)?.takeIf { it.fingerprint == fingerprint(credentials) } }.getOrNull() } fun loadMeta(credentials: Credentials): FastCacheMeta? { if (!metaFile.exists() || metaFile.length() <= 0L) return null return runCatching { ObjectInputStream(FileInputStream(metaFile).buffered(32 * 1024)).use { input -> (input.readObject() as FastCacheMeta).takeIf { it.fingerprint == fingerprint(credentials) } } }.getOrNull() } fun loadLive(credentials: Credentials): FastLiveCache? = if (loadMeta(credentials) == null) null else readGzip(liveFile) fun loadEpg(credentials: Credentials): FastEpgCache? = if (loadMeta(credentials) == null) null else readGzip(epgFile) fun loadMovies(credentials: Credentials): FastLibraryCache? = if (loadMeta(credentials) == null) null else readGzip(moviesFile) fun loadSeries(credentials: Credentials): FastLibraryCache? = if (loadMeta(credentials) == null) null else readGzip(seriesFile) /** * Persist the minimum viable startup cache FIRST. A failure writing the huge * legacy/VOD/EPG files must not strand returning users on first-run setup. * The metadata is published only after a complete Live TV segment exists. */ @Synchronized fun save(credentials: Credentials, snapshot: StartupSnapshot) { val fingerprint = fingerprint(credentials) val normalized = snapshot.copy(fingerprint = fingerprint) if (normalized.liveChannels.isEmpty()) return val liveSaved = runCatching { writeGzipAtomic(liveFile, FastLiveCache(normalized.liveCategories, normalized.liveChannels)) val meta = FastCacheMeta( fingerprint = fingerprint, savedAtMillis = normalized.savedAtMillis, liveCount = normalized.liveChannels.size, epgChannelCount = normalized.liveChannels.count { normalized.epgByChannel[it.id].orEmpty().isNotEmpty() }, movieCount = normalized.movies.size, seriesCount = normalized.series.size, ) writePlainAtomic(metaFile, meta) }.isSuccess if (!liveSaved) return // Nonessential pieces must fail independently: Live TV can still launch. runCatching { writeGzipAtomic(epgFile, FastEpgCache(normalized.epgByChannel)) } runCatching { writeGzipAtomic(moviesFile, FastLibraryCache(normalized.movieCategories, normalized.movies)) } runCatching { writeGzipAtomic(seriesFile, FastLibraryCache(normalized.seriesCategories, normalized.series)) } // Keep legacy rollback support, but never let this expensive write gate startup. runCatching { writeGzipAtomic(legacyFile, normalized) } } fun clear() { listOf(legacyFile, metaFile, liveFile, epgFile, moviesFile, seriesFile).forEach { file -> runCatching { file.delete() } } } private fun fingerprint(credentials: Credentials): String = "${credentials.serverUrl.trim().lowercase()}|${credentials.username.trim().lowercase()}" @Suppress("UNCHECKED_CAST") private fun readGzip(file: File): T? { if (!file.exists() || file.length() <= 0L) return null return runCatching { ObjectInputStream(GZIPInputStream(FileInputStream(file).buffered(128 * 1024))).use { input -> input.readObject() as T } }.getOrNull() } private fun writeGzipAtomic(file: File, value: Serializable) { val temp = File(file.parentFile, "${file.name}.tmp") ObjectOutputStream(GZIPOutputStream(FileOutputStream(temp).buffered(128 * 1024))).use { output -> output.writeObject(value) } replaceAtomic(temp, file) } private fun writePlainAtomic(file: File, value: Serializable) { val temp = File(file.parentFile, "${file.name}.tmp") ObjectOutputStream(FileOutputStream(temp).buffered(32 * 1024)).use { output -> output.writeObject(value) } replaceAtomic(temp, file) } private fun replaceAtomic(temp: File, file: File) { if (file.exists()) file.delete() if (!temp.renameTo(file)) { temp.copyTo(file, overwrite = true) temp.delete() } } }