package tv.tivilux.nativeplayer.data import android.content.Context import org.json.JSONArray import org.json.JSONObject import tv.tivilux.nativeplayer.model.ContentType import tv.tivilux.nativeplayer.model.HouseholdProfile import tv.tivilux.nativeplayer.model.MediaEntry import tv.tivilux.nativeplayer.model.PlaybackProgress class ProfileStore(context: Context) { private val prefs = context.getSharedPreferences("tivilux_profiles", Context.MODE_PRIVATE) fun profiles(): List { val raw = prefs.getString("profiles", null) val parsed = if (raw.isNullOrBlank()) emptyList() else runCatching { val arr = JSONArray(raw) buildList { for (i in 0 until arr.length()) { val o = arr.optJSONObject(i) ?: continue val id = o.optString("id") if (id.isBlank()) continue add(HouseholdProfile(id, o.optString("name", "Profile"), o.optInt("avatarIndex", i))) } } }.getOrDefault(emptyList()) if (parsed.isNotEmpty()) return parsed.take(3) val seeded = listOf(HouseholdProfile("main", "Main", 0)) save(seeded) prefs.edit().putString("active", "main").apply() return seeded } fun activeProfile(): HouseholdProfile { val all = profiles() val activeId = prefs.getString("active", all.first().id) return all.firstOrNull { it.id == activeId } ?: all.first() } fun select(id: String): HouseholdProfile { val selected = profiles().firstOrNull { it.id == id } ?: activeProfile() prefs.edit().putString("active", selected.id).apply() return selected } fun create(name: String): List { val all = profiles().toMutableList() if (all.size >= 3) return all val clean = name.trim().take(22).ifBlank { "Profile ${all.size + 1}" } val id = "profile_${System.currentTimeMillis()}_${all.size}" all += HouseholdProfile(id, clean, all.size % 6) save(all) return all } fun rename(id: String, name: String): List { val clean = name.trim().take(22) if (clean.isBlank()) return profiles() val all = profiles().map { if (it.id == id) it.copy(name = clean) else it } save(all) return all } fun delete(id: String): List { val all = profiles() if (all.size <= 1) return all val remaining = all.filterNot { it.id == id } save(remaining) if (prefs.getString("active", null) == id) prefs.edit().putString("active", remaining.first().id).apply() return remaining } private fun save(profiles: List) { val arr = JSONArray() profiles.take(3).forEach { profile -> arr.put(JSONObject().apply { put("id", profile.id) put("name", profile.name) put("avatarIndex", profile.avatarIndex) }) } prefs.edit().putString("profiles", arr.toString()).apply() } } class PlaybackStore(context: Context) { private val prefs = context.getSharedPreferences("tivilux_playback_progress", Context.MODE_PRIVATE) // Playback progress is read constantly by Home and Series detail. Parsing the same // SharedPreferences JSON for every visible episode row made large seasons needlessly // expensive. Keep a small in-memory profile cache and update it atomically on writes. private val cacheLock = Any() private val progressCache = mutableMapOf>() private val progressIndexCache = mutableMapOf>() fun progress(profileId: String, item: MediaEntry): PlaybackProgress? = progressIndex(profileId)[mediaKey(item)] fun record( profileId: String, item: MediaEntry, positionMs: Long, durationMs: Long, completed: Boolean, nextItem: MediaEntry? = null, ) { if (item.type !in setOf(ContentType.MOVIE, ContentType.EPISODE)) return val current = progressIndex(profileId).toMutableMap() current[mediaKey(item)] = PlaybackProgress( item = item, positionMs = positionMs.coerceAtLeast(0L), durationMs = durationMs.coerceAtLeast(0L), updatedAt = System.currentTimeMillis(), completed = completed, nextItem = nextItem, ) save(profileId, current.values.sortedByDescending { it.updatedAt }.take(MAX_PROGRESS_ITEMS)) } fun continueWatching(profileId: String, limit: Int = 14): List { val output = mutableListOf() val seen = mutableSetOf() // save() already stores newest first, and legacy data is normalized once when read. all(profileId).forEach { progress -> val candidate = when { !progress.completed -> progress progress.nextItem != null -> PlaybackProgress( item = progress.nextItem, positionMs = 0L, durationMs = 0L, updatedAt = progress.updatedAt, completed = false, nextItem = null, ) else -> null } ?: return@forEach val key = mediaKey(candidate.item) if (seen.add(key)) output += candidate if (output.size >= limit) return@forEach } return output.take(limit) } fun removeFromContinueWatching(profileId: String, item: MediaEntry) { val targetKey = mediaKey(item) val remaining = all(profileId).filterNot { progress -> mediaKey(progress.item) == targetKey || progress.nextItem?.let { mediaKey(it) == targetKey } == true } save(profileId, remaining) } fun clearProfile(profileId: String) { synchronized(cacheLock) { progressCache.remove(profileId) progressIndexCache.remove(profileId) } prefs.edit().remove("progress_$profileId").apply() } private fun progressIndex(profileId: String): Map { synchronized(cacheLock) { progressIndexCache[profileId]?.let { return it } } all(profileId) return synchronized(cacheLock) { progressIndexCache[profileId].orEmpty() } } private fun all(profileId: String): List { synchronized(cacheLock) { progressCache[profileId]?.let { return it } } val raw = prefs.getString("progress_$profileId", "[]") ?: "[]" val parsed = runCatching { val arr = JSONArray(raw) buildList { for (i in 0 until arr.length()) { val o = arr.optJSONObject(i) ?: continue val item = mediaFromJson(o.optJSONObject("item")) ?: continue add( PlaybackProgress( item = item, positionMs = o.optLong("positionMs", 0L), durationMs = o.optLong("durationMs", 0L), updatedAt = o.optLong("updatedAt", 0L), completed = o.optBoolean("completed", false), nextItem = mediaFromJson(o.optJSONObject("nextItem")), ) ) } }.sortedByDescending { it.updatedAt }.take(MAX_PROGRESS_ITEMS) }.getOrDefault(emptyList()) synchronized(cacheLock) { progressCache[profileId] = parsed progressIndexCache[profileId] = parsed.associateBy { mediaKey(it.item) } } return parsed } private fun save(profileId: String, values: List) { val normalized = values.sortedByDescending { it.updatedAt }.take(MAX_PROGRESS_ITEMS) synchronized(cacheLock) { progressCache[profileId] = normalized progressIndexCache[profileId] = normalized.associateBy { mediaKey(it.item) } } val arr = JSONArray() normalized.forEach { p -> arr.put(JSONObject().apply { put("item", mediaToJson(p.item)) put("positionMs", p.positionMs) put("durationMs", p.durationMs) put("updatedAt", p.updatedAt) put("completed", p.completed) p.nextItem?.let { put("nextItem", mediaToJson(it)) } }) } prefs.edit().putString("progress_$profileId", arr.toString()).apply() } private fun mediaKey(item: MediaEntry) = "${item.type.name}:${item.id}" private companion object { const val MAX_PROGRESS_ITEMS = 120 } } private fun mediaToJson(media: MediaEntry) = JSONObject().apply { put("id", media.id) put("type", media.type.name) put("name", media.name) put("categoryId", media.categoryId) put("image", media.image) put("extension", media.extension) put("epgChannelId", media.epgChannelId) put("number", media.number) put("rating", media.rating) put("year", media.year) put("plot", media.plot) put("seriesId", media.seriesId) put("season", media.season) put("episodeNumber", media.episodeNumber) put("seriesName", media.seriesName) put("directSource", media.directSource) } private fun mediaFromJson(o: JSONObject?): MediaEntry? { o ?: return null val id = o.optString("id") if (id.isBlank()) return null val type = runCatching { ContentType.valueOf(o.optString("type")) }.getOrDefault(ContentType.MOVIE) return MediaEntry( id = id, type = type, name = o.optString("name", "Continue Watching"), categoryId = o.optString("categoryId"), image = o.optString("image"), extension = o.optString("extension"), epgChannelId = o.optString("epgChannelId"), number = o.optInt("number", 0), rating = o.optString("rating"), year = o.optString("year"), plot = o.optString("plot"), seriesId = o.optString("seriesId"), season = o.optInt("season", 0), episodeNumber = o.optInt("episodeNumber", 0), seriesName = o.optString("seriesName"), directSource = o.optString("directSource"), ) }