package tv.tivilux.nativeplayer.data import android.content.Context import tv.tivilux.nativeplayer.model.ContentType import tv.tivilux.nativeplayer.model.Credentials import tv.tivilux.nativeplayer.model.MediaEntry import org.json.JSONArray import org.json.JSONObject class CredentialStore(context: Context) { private val prefs = context.getSharedPreferences("tivilux_credentials", Context.MODE_PRIVATE) private val alias = "tivilux.native.credentials.v1" fun load(): Credentials? { val blob = prefs.getString("blob", null) ?: return null return try { val json = JSONObject(decrypt(blob)) val server = json.optString("server").takeIf { it.isNotBlank() } ?: return null val username = json.optString("username").takeIf { it.isNotBlank() } ?: return null val password = json.optString("password").takeIf { it.isNotBlank() } ?: return null Credentials(server, username, password) } catch (_: Throwable) { clear() null } } fun save(credentials: Credentials) { val json = JSONObject().apply { put("server", credentials.serverUrl) put("username", credentials.username) put("password", credentials.password) }.toString() prefs.edit().putString("blob", encrypt(json)).apply() } fun clear() = prefs.edit().clear().apply() private fun key(): javax.crypto.SecretKey { val store = java.security.KeyStore.getInstance("AndroidKeyStore").apply { load(null) } val existing = store.getKey(alias, null) as? javax.crypto.SecretKey if (existing != null) return existing val generator = javax.crypto.KeyGenerator.getInstance( android.security.keystore.KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore" ) generator.init( android.security.keystore.KeyGenParameterSpec.Builder( alias, android.security.keystore.KeyProperties.PURPOSE_ENCRYPT or android.security.keystore.KeyProperties.PURPOSE_DECRYPT ) .setBlockModes(android.security.keystore.KeyProperties.BLOCK_MODE_GCM) .setEncryptionPaddings(android.security.keystore.KeyProperties.ENCRYPTION_PADDING_NONE) .build() ) return generator.generateKey() } private fun encrypt(plain: String): String { val cipher = javax.crypto.Cipher.getInstance("AES/GCM/NoPadding") cipher.init(javax.crypto.Cipher.ENCRYPT_MODE, key()) val encrypted = cipher.doFinal(plain.toByteArray(Charsets.UTF_8)) val combined = ByteArray(cipher.iv.size + encrypted.size) System.arraycopy(cipher.iv, 0, combined, 0, cipher.iv.size) System.arraycopy(encrypted, 0, combined, cipher.iv.size, encrypted.size) return android.util.Base64.encodeToString(combined, android.util.Base64.NO_WRAP) } private fun decrypt(blob: String): String { val combined = android.util.Base64.decode(blob, android.util.Base64.NO_WRAP) require(combined.size > 12) { "Invalid credential blob" } val iv = combined.copyOfRange(0, 12) val encrypted = combined.copyOfRange(12, combined.size) val cipher = javax.crypto.Cipher.getInstance("AES/GCM/NoPadding") cipher.init( javax.crypto.Cipher.DECRYPT_MODE, key(), javax.crypto.spec.GCMParameterSpec(128, iv) ) return String(cipher.doFinal(encrypted), Charsets.UTF_8) } } class LibraryStore(context: Context) { private val prefs = context.getSharedPreferences("tivilux_library", Context.MODE_PRIVATE) private var activeProfileId: String = "main" fun setActiveProfile(profileId: String) { activeProfileId = profileId.ifBlank { "main" } } private fun scoped(name: String) = "${name}_$activeProfileId" private fun hasScoped(name: String) = prefs.contains(scoped(name)) fun isFavorite(item: MediaEntry): Boolean = favoriteKeys().contains(key(item)) fun toggle(item: MediaEntry): Boolean { val set = favoriteKeys().toMutableSet() val items = favoriteItems().associateBy { key(it) }.toMutableMap() val k = key(item) val nowFavorite = if (set.contains(k)) { set.remove(k) items.remove(k) false } else { set.add(k) items[k] = item true } val arr = JSONArray() items.values.forEach { media -> arr.put(mediaJson(media)) } prefs.edit() .putStringSet(scoped("favorites"), set) .putString(scoped("favorite_items"), arr.toString()) .apply() return nowFavorite } fun favoriteKeys(): Set { if (!hasScoped("favorites") && activeProfileId == "main") { return prefs.getStringSet("favorites", emptySet())?.toSet().orEmpty() } return prefs.getStringSet(scoped("favorites"), emptySet())?.toSet().orEmpty() } fun favoriteItems(): List { val raw = if (!hasScoped("favorite_items") && activeProfileId == "main") { prefs.getString("favorite_items", "[]") ?: "[]" } else { prefs.getString(scoped("favorite_items"), "[]") ?: "[]" } return parseMediaArray(raw) } /** * Manual Live TV ordering is profile-scoped. The main Guide and Favorites Guide intentionally * keep separate order lists so rearranging Favorites never disturbs the provider lineup. * Unknown/new channel IDs are simply appended by the ViewModel when the provider refreshes. */ // A separate, profile-scoped preference for each provider category. // Missing preferences inherit the user's existing global Guide order. fun guideSortForCategory(categoryId: String?, defaultSort: String): String { if (categoryId.isNullOrBlank()) return defaultSort return prefs.getString(scoped("guide_sort_category_$categoryId"), defaultSort) ?: defaultSort } fun saveGuideSortForCategory(categoryId: String?, sort: String) { if (categoryId.isNullOrBlank()) return prefs.edit().putString(scoped("guide_sort_category_$categoryId"), sort).apply() } fun manualGuideOrder(favorites: Boolean = false, categoryId: String? = null): List { val name = if (favorites) "favorite_guide_manual_order" else if (!categoryId.isNullOrBlank()) "guide_manual_category_$categoryId" else "guide_manual_order" val raw = prefs.getString(scoped(name), "[]") ?: "[]" return runCatching { val arr = JSONArray(raw) buildList { for (i in 0 until arr.length()) { arr.optString(i).takeIf { it.isNotBlank() }?.let(::add) } } }.getOrElse { emptyList() } } fun saveManualGuideOrder(ids: List, favorites: Boolean = false, categoryId: String? = null) { val name = if (favorites) "favorite_guide_manual_order" else if (!categoryId.isNullOrBlank()) "guide_manual_category_$categoryId" else "guide_manual_order" val arr = JSONArray() ids.asSequence().filter { it.isNotBlank() }.distinct().forEach { arr.put(it) } prefs.edit().putString(scoped(name), arr.toString()).apply() } /** Profile-scoped provider group ordering used by Live TV, Movies and Series. */ fun categoryOrder(type: ContentType): List { val raw = prefs.getString(scoped("category_order_${type.name}"), "[]") ?: "[]" return runCatching { val arr = JSONArray(raw) buildList { for (i in 0 until arr.length()) { arr.optString(i).takeIf { it.isNotBlank() }?.let(::add) } } }.getOrElse { emptyList() } } fun saveCategoryOrder(type: ContentType, ids: List) { val arr = JSONArray() ids.asSequence().filter { it.isNotBlank() }.distinct().forEach { arr.put(it) } prefs.edit().putString(scoped("category_order_${type.name}"), arr.toString()).apply() } fun hiddenCategoryIds(type: ContentType): Set = prefs.getStringSet(scoped("hidden_categories_${type.name}"), emptySet())?.toSet().orEmpty() fun toggleCategoryHidden(type: ContentType, categoryId: String): Boolean { if (categoryId.isBlank()) return false val hidden = hiddenCategoryIds(type).toMutableSet() val nowHidden = if (hidden.remove(categoryId)) false else { hidden.add(categoryId) true } prefs.edit().putStringSet(scoped("hidden_categories_${type.name}"), hidden).apply() return nowHidden } fun hiddenLiveChannelIds(): Set = prefs.getStringSet(scoped("hidden_live_channels"), emptySet())?.toSet().orEmpty() fun toggleLiveChannelHidden(channelId: String): Boolean { if (channelId.isBlank()) return false val hidden = hiddenLiveChannelIds().toMutableSet() val nowHidden = if (hidden.remove(channelId)) false else { hidden.add(channelId) true } prefs.edit().putStringSet(scoped("hidden_live_channels"), hidden).apply() return nowHidden } fun remember(item: MediaEntry) { prefs.edit() .putString(scoped("last_type"), item.type.name) .putString(scoped("last_id"), item.id) .putString(scoped("last_name"), item.name) .putString(scoped("last_image"), item.image) .putString(scoped("last_extension"), item.extension) .putString(scoped("last_series"), item.seriesId) .putInt(scoped("last_season"), item.season) .putInt(scoped("last_episode"), item.episodeNumber) .putString(scoped("last_series_name"), item.seriesName) .putString(scoped("last_direct_source"), item.directSource) .apply() } fun lastPlayed(): MediaEntry? { val scopedId = prefs.getString(scoped("last_id"), null) val useLegacy = scopedId == null && activeProfileId == "main" && prefs.contains("last_id") val id = (scopedId ?: if (useLegacy) prefs.getString("last_id", null) else null) ?: return null fun str(name: String, legacy: String = name, default: String = "") = if (useLegacy) prefs.getString(legacy, default) ?: default else prefs.getString(scoped(name), default) ?: default val typeRaw = str("last_type", "last_type", ContentType.LIVE.name) val type = runCatching { ContentType.valueOf(typeRaw) }.getOrDefault(ContentType.LIVE) return MediaEntry( id = id, type = type, name = str("last_name", "last_name", "Last watched"), image = str("last_image", "last_image"), extension = str("last_extension", "last_extension"), seriesId = str("last_series", "last_series"), season = if (useLegacy) 0 else prefs.getInt(scoped("last_season"), 0), episodeNumber = if (useLegacy) 0 else prefs.getInt(scoped("last_episode"), 0), seriesName = if (useLegacy) "" else str("last_series_name"), directSource = if (useLegacy) "" else str("last_direct_source"), ) } fun clearProfile(profileId: String) { val names = listOf( "favorites", "favorite_items", "guide_manual_order", "favorite_guide_manual_order", "category_order_LIVE", "category_order_MOVIE", "category_order_SERIES", "hidden_categories_LIVE", "hidden_categories_MOVIE", "hidden_categories_SERIES", "hidden_live_channels", "last_type", "last_id", "last_name", "last_image", "last_extension", "last_series", "last_season", "last_episode", "last_series_name", "last_direct_source" ) val e = prefs.edit() names.forEach { e.remove("${it}_$profileId") } e.apply() } private fun key(item: MediaEntry) = "${item.type.name}:${item.id}" private fun mediaJson(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 parseMediaArray(raw: String): List = runCatching { val arr = JSONArray(raw) buildList { for (i in 0 until arr.length()) { val o = arr.optJSONObject(i) ?: continue val type = runCatching { ContentType.valueOf(o.optString("type")) }.getOrDefault(ContentType.LIVE) add(MediaEntry( id = o.optString("id"), type = type, name = o.optString("name", "Favorite"), 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"), )) } } }.getOrElse { emptyList() } } class SettingsStore(context: Context) { private val prefs = context.getSharedPreferences("tivilux_settings", Context.MODE_PRIVATE) fun load(): tv.tivilux.nativeplayer.model.AppSettings = tv.tivilux.nativeplayer.model.AppSettings( guidePreview = prefs.getBoolean("guidePreview", true), guideAutoplayPreview = prefs.getBoolean("guideAutoplayPreview", false), stayOnGuideAfterTune = prefs.getBoolean("stayOnGuideAfterTune", true), showChannelNumbers = prefs.getBoolean("showChannelNumbers", true), showChannelLogos = prefs.getBoolean("showChannelLogos", true), channelSort = prefs.getString("channelSort", "Provider") ?: "Provider", favoriteChannelSort = prefs.getString("favoriteChannelSort", "Provider") ?: "Provider", favoritesFirst = prefs.getBoolean("favoritesFirst", false), highlightCurrentChannel = prefs.getBoolean("highlightCurrentChannel", true), showProgramProgress = prefs.getBoolean("showProgramProgress", true), twoLineProgramTitles = prefs.getBoolean("twoLineProgramTitles", false), highlightCurrentProgram = prefs.getBoolean("highlightCurrentProgram", true), fullHeightTimeIndicator = prefs.getBoolean("fullHeightTimeIndicator", true), showProgramDescriptions = prefs.getBoolean("showProgramDescriptions", true), guideDensity = prefs.getString("guideDensity", "Comfortable") ?: "Comfortable", guideFontSize = prefs.getString("guideFontSize", "Normal") ?: "Normal", epgTimeOffsetHours = prefs.getInt("epgTimeOffsetHours", 0), preferHlsLive = prefs.getBoolean("preferHlsLive", false), bufferPreset = when (prefs.getString("bufferPreset", null)) { "Large" -> "Resilient" "Small", "Normal", null -> "Turbo" else -> prefs.getString("bufferPreset", "Turbo") ?: "Turbo" }, autoplayNextEpisode = prefs.getBoolean("autoplayNextEpisode", true), startOnLiveTv = prefs.getBoolean("startOnLiveTv", false), remoteShortcutsEnabled = prefs.getBoolean("remoteShortcutsEnabled", true), showFullscreenClock = prefs.getBoolean("showFullscreenClock", true), fullscreenClockSize = prefs.getString("fullscreenClockSize", "Medium") ?: "Medium", fullscreenClockPosition = prefs.getString("fullscreenClockPosition", "Top Right") ?: "Top Right", colorTheme = prefs.getString("colorTheme", "Original Gold") ?: "Original Gold", customBackground = prefs.getString("customBackground", "#090B10") ?: "#090B10", customAccent = prefs.getString("customAccent", "#E8C38B") ?: "#E8C38B", customFocus = prefs.getString("customFocus", "#F3D6AB") ?: "#F3D6AB", ) fun save(settings: tv.tivilux.nativeplayer.model.AppSettings) { prefs.edit() .putBoolean("guidePreview", settings.guidePreview) .putBoolean("guideAutoplayPreview", settings.guideAutoplayPreview) .putBoolean("stayOnGuideAfterTune", settings.stayOnGuideAfterTune) .putBoolean("showChannelNumbers", settings.showChannelNumbers) .putBoolean("showChannelLogos", settings.showChannelLogos) .putString("channelSort", settings.channelSort) .putString("favoriteChannelSort", settings.favoriteChannelSort) .putBoolean("favoritesFirst", settings.favoritesFirst) .putBoolean("highlightCurrentChannel", settings.highlightCurrentChannel) .putBoolean("showProgramProgress", settings.showProgramProgress) .putBoolean("twoLineProgramTitles", settings.twoLineProgramTitles) .putBoolean("highlightCurrentProgram", settings.highlightCurrentProgram) .putBoolean("fullHeightTimeIndicator", settings.fullHeightTimeIndicator) .putBoolean("showProgramDescriptions", settings.showProgramDescriptions) .putString("guideDensity", settings.guideDensity) .putString("guideFontSize", settings.guideFontSize) .putInt("epgTimeOffsetHours", settings.epgTimeOffsetHours) .putBoolean("preferHlsLive", settings.preferHlsLive) .putString("bufferPreset", settings.bufferPreset) .putBoolean("autoplayNextEpisode", settings.autoplayNextEpisode) .putBoolean("startOnLiveTv", settings.startOnLiveTv) .putBoolean("remoteShortcutsEnabled", settings.remoteShortcutsEnabled) .putBoolean("showFullscreenClock", settings.showFullscreenClock) .putString("fullscreenClockSize", settings.fullscreenClockSize) .putString("fullscreenClockPosition", settings.fullscreenClockPosition) .putString("colorTheme", settings.colorTheme) .putString("customBackground", settings.customBackground) .putString("customAccent", settings.customAccent) .putString("customFocus", settings.customFocus) .apply() } }