package tv.tivilux.nativeplayer.data import android.util.Base64 import android.os.SystemClock import android.util.Xml import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import org.json.JSONArray import org.json.JSONObject import tv.tivilux.nativeplayer.BuildConfig 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.Episode import tv.tivilux.nativeplayer.model.MediaEntry import tv.tivilux.nativeplayer.model.MovieDetail import tv.tivilux.nativeplayer.model.SeriesDetail import tv.tivilux.nativeplayer.model.SeasonInfo import tv.tivilux.nativeplayer.model.SessionInfo import java.io.BufferedReader import java.io.InputStreamReader import java.net.HttpURLConnection import java.net.SocketTimeoutException import java.net.URL import java.net.URLEncoder import java.nio.charset.StandardCharsets import java.text.SimpleDateFormat import java.util.Locale class XtreamRepository { suspend fun authenticate(credentials: Credentials): SessionInfo = withContext(Dispatchers.IO) { val root = requestObject(credentials, action = null) val user = root.optJSONObject("user_info") ?: throw IllegalStateException("Provider did not return user_info") if (user.optInt("auth", 0) != 1) throw IllegalArgumentException("Provider rejected the username/password") SessionInfo( username = user.optString("username", credentials.username), status = user.optString("status", "Active"), expiration = user.optString("exp_date", ""), maxConnections = user.optString("max_connections", "0").toIntOrNull() ?: 0, activeConnections = user.optString("active_cons", "0").toIntOrNull() ?: 0, ) } suspend fun categories(credentials: Credentials, type: ContentType): List = withContext(Dispatchers.IO) { val action = when (type) { ContentType.LIVE -> "get_live_categories" ContentType.MOVIE -> "get_vod_categories" ContentType.SERIES -> "get_series_categories" ContentType.EPISODE -> return@withContext emptyList() } val arr = requestArray(credentials, action) buildList { for (i in 0 until arr.length()) { val item = arr.optJSONObject(i) ?: continue add(Category(item.optString("category_id"), item.optString("category_name", "Other"))) } } } suspend fun catalog(credentials: Credentials, type: ContentType, categoryId: String? = null): List = withContext(Dispatchers.IO) { val action = when (type) { ContentType.LIVE -> "get_live_streams" ContentType.MOVIE -> "get_vod_streams" ContentType.SERIES -> "get_series" ContentType.EPISODE -> return@withContext emptyList() } val extra = if (!categoryId.isNullOrBlank()) mapOf("category_id" to categoryId) else emptyMap() val arr = requestArray(credentials, action, extra) buildList { for (i in 0 until arr.length()) { val item = arr.optJSONObject(i) ?: continue val id = when (type) { ContentType.SERIES -> item.optString("series_id") else -> item.optString("stream_id") } if (id.isBlank()) continue val image = when (type) { ContentType.SERIES -> item.optString("cover") else -> item.optString("stream_icon") } add( MediaEntry( id = id, type = type, name = item.optString("name", "Untitled"), categoryId = item.optString("category_id").ifBlank { categoryId.orEmpty() }, image = image, extension = item.optString("container_extension"), epgChannelId = item.optString("epg_channel_id"), number = item.optInt("num", 0), rating = clean(item.optString("rating")), year = clean(item.optString("year")), plot = clean(item.optString("plot")), directSource = item.optString("direct_source"), addedEpoch = item.optString("added").toLongOrNull() ?: 0L, ) ) } } } suspend fun epg(credentials: Credentials, streamId: String, limit: Int = 8): List = withContext(Dispatchers.IO) { val root = requestObject(credentials, "get_short_epg", mapOf("stream_id" to streamId, "limit" to limit.toString())) val arr = root.optJSONArray("epg_listings") ?: JSONArray() buildList { for (i in 0 until arr.length()) { val p = arr.optJSONObject(i) ?: continue val start = p.optLong("start_timestamp", 0L) val end = p.optLong("stop_timestamp", p.optLong("end_timestamp", 0L)) if (start <= 0L || end <= start) continue add( EpgProgram( title = decodeMaybeBase64(p.optString("title")).take(180), description = decodeMaybeBase64(p.optString("description")).take(600), startEpoch = start, endEpoch = end, ) ) } } } /** * Pull the provider's complete XMLTV guide once and map it back to Xtream stream IDs. * This is dramatically cheaper than making one HTTP request per channel on large * playlists and lets startup report an honest "channels with EPG" total. */ suspend fun fullEpg( credentials: Credentials, channels: List, pastHours: Int = 4, futureHours: Int = 24, maxWorkMillis: Long? = null, ): Map> = withContext(Dispatchers.IO) { val streamsByEpgId = channels .filter { it.epgChannelId.isNotBlank() } .groupBy { it.epgChannelId.trim() } if (streamsByEpgId.isEmpty()) return@withContext emptyMap() val base = normalizeBase(credentials.serverUrl) val url = URL( "$base/xmltv.php?username=${enc(credentials.username)}&password=${enc(credentials.password)}" ) val startedAt = SystemClock.elapsedRealtime() val deadline = maxWorkMillis?.let { startedAt + it.coerceAtLeast(1_500L) } val startupReadTimeout = maxWorkMillis?.coerceIn(2_000L, 12_000L)?.toInt() val connection = (url.openConnection() as HttpURLConnection).apply { requestMethod = "GET" connectTimeout = startupReadTimeout ?: 12_000 readTimeout = startupReadTimeout ?: 90_000 useCaches = true setRequestProperty("Accept", "application/xml,text/xml,*/*") setRequestProperty("User-Agent", "TiviLux-Native/${BuildConfig.VERSION_NAME} AndroidTV") } try { val code = connection.responseCode if (code !in 200..299) throw IllegalStateException("Provider XMLTV returned HTTP $code") val now = System.currentTimeMillis() / 1000L val minEpoch = now - pastHours * 3600L val maxEpoch = now + futureHours * 3600L val output = mutableMapOf>() connection.inputStream.buffered().use { input -> val parser = Xml.newPullParser().apply { setInput(input, null) } var event = parser.eventType var inProgramme = false var relevant = false var epgId = "" var start = 0L var stop = 0L var title = "" var description = "" var eventCounter = 0 while (event != org.xmlpull.v1.XmlPullParser.END_DOCUMENT) { if ((eventCounter++ and 0x1FF) == 0 && deadline != null && SystemClock.elapsedRealtime() >= deadline) { throw SocketTimeoutException("XMLTV startup budget exceeded") } // Large XMLTV feeds can contain hundreds of thousands of nodes. // Yield occasionally so lower-power TV boxes keep rendering remote // focus and video frames smoothly while indexing runs in background. if ((eventCounter and 0x7FF) == 0) Thread.yield() when (event) { org.xmlpull.v1.XmlPullParser.START_TAG -> when (parser.name) { "programme" -> { inProgramme = true epgId = parser.getAttributeValue(null, "channel").orEmpty().trim() start = parseXmlTvEpoch(parser.getAttributeValue(null, "start").orEmpty()) stop = parseXmlTvEpoch(parser.getAttributeValue(null, "stop").orEmpty()) relevant = streamsByEpgId.containsKey(epgId) && start > 0L && stop > start && stop >= minEpoch && start <= maxEpoch title = "" description = "" } "title" -> if (inProgramme && relevant) title = parser.nextText().trim().take(180) "desc" -> if (inProgramme && relevant) description = parser.nextText().trim().take(600) } org.xmlpull.v1.XmlPullParser.END_TAG -> if (parser.name == "programme") { if (relevant) { val program = EpgProgram( title = title.ifBlank { "Program" }, description = description, startEpoch = start, endEpoch = stop, ) streamsByEpgId[epgId].orEmpty().forEach { stream -> output.getOrPut(stream.id) { mutableListOf() }.add(program) } } inProgramme = false relevant = false } } event = parser.next() } } output.mapValues { (_, programs) -> programs.sortedBy { it.startEpoch } } } finally { connection.disconnect() } } suspend fun movieDetail(credentials: Credentials, movie: MediaEntry): MovieDetail = withContext(Dispatchers.IO) { val root = requestObject(credentials, "get_vod_info", mapOf("vod_id" to movie.id)) val info = root.optJSONObject("info") ?: JSONObject() val data = root.optJSONObject("movie_data") ?: JSONObject() val image = firstNonBlank(info.optString("movie_image"), info.optString("cover_big"), info.optString("cover"), data.optString("stream_icon"), movie.image) val year = firstNonBlank(info.optString("year"), info.optString("releasedate").take(4), info.optString("releaseDate").take(4), movie.year) val extension = firstNonBlank(data.optString("container_extension"), info.optString("container_extension"), movie.extension, "mp4") val directSource = firstNonBlank(data.optString("direct_source"), info.optString("direct_source"), movie.directSource) val rating = firstNonBlank(info.optString("rating"), info.optString("rating_5based"), info.optString("imdb_rating"), movie.rating) val plot = firstNonBlank(info.optString("plot"), info.optString("description"), info.optString("overview"), movie.plot) MovieDetail( movie = movie.copy(image = image, year = year, extension = extension, rating = rating, plot = plot, directSource = directSource), plot = plot, backdrop = info.optJSONArray("backdrop_path")?.optString(0).orEmpty(), genre = firstNonBlank(info.optString("genre"), info.optString("genres")), cast = firstNonBlank(info.optString("cast"), info.optString("actors"), info.optString("actor")), director = firstNonBlank(info.optString("director"), info.optString("directors")), releaseDate = firstNonBlank(info.optString("releasedate"), info.optString("releaseDate"), info.optString("date_added")), duration = firstNonBlank(info.optString("duration"), info.optString("duration_secs").takeIf { it.isNotBlank() }?.let { secondsToDuration(it) }.orEmpty()), rating = rating, ) } suspend fun seriesDetail(credentials: Credentials, series: MediaEntry): SeriesDetail = withContext(Dispatchers.IO) { val root = requestObject(credentials, "get_series_info", mapOf("series_id" to series.id)) val info = root.optJSONObject("info") ?: JSONObject() val episodesObject = root.optJSONObject("episodes") ?: JSONObject() val episodes = linkedMapOf>() val keys = episodesObject.keys() while (keys.hasNext()) { val seasonKey = keys.next() val season = seasonKey.toIntOrNull() ?: continue val arr = episodesObject.optJSONArray(seasonKey) ?: continue val seasonEpisodes = buildList { for (i in 0 until arr.length()) { val e = arr.optJSONObject(i) ?: continue val ei = e.optJSONObject("info") ?: JSONObject() val id = e.optString("id") if (id.isBlank()) continue add( Episode( id = id, seriesId = series.id, season = season, episodeNumber = e.optInt("episode_num", i + 1), name = e.optString("title", "Episode ${i + 1}"), extension = e.optString("container_extension", "mp4"), image = firstNonBlank(ei.optString("movie_image"), ei.optString("cover_big"), ei.optString("cover")), plot = ei.optString("plot"), duration = ei.optString("duration"), releaseDate = firstNonBlank(ei.optString("releasedate"), ei.optString("releaseDate")), ) ) } } episodes[season] = seasonEpisodes } val seasonInfo = linkedMapOf() val seasonsArray = root.optJSONArray("seasons") if (seasonsArray != null) { for (i in 0 until seasonsArray.length()) { val s = seasonsArray.optJSONObject(i) ?: continue val seasonNumber = s.optInt("season_number", s.optInt("season", i + 1)) if (seasonNumber <= 0) continue seasonInfo[seasonNumber] = SeasonInfo( seasonNumber = seasonNumber, name = firstNonBlank(s.optString("name"), "Season $seasonNumber"), overview = firstNonBlank(s.optString("overview"), s.optString("plot"), s.optString("description")), airDate = firstNonBlank(s.optString("air_date"), s.optString("releaseDate"), s.optString("releasedate")), episodeCount = s.optInt("episode_count", episodes[seasonNumber]?.size ?: 0), ) } } episodes.forEach { (seasonNumber, seasonEpisodes) -> if (!seasonInfo.containsKey(seasonNumber)) { seasonInfo[seasonNumber] = SeasonInfo( seasonNumber = seasonNumber, name = "Season $seasonNumber", episodeCount = seasonEpisodes.size, ) } } val plot = firstNonBlank(info.optString("plot"), info.optString("description"), info.optString("overview"), series.plot) val rating = firstNonBlank(info.optString("rating"), info.optString("rating_5based"), series.rating) val year = firstNonBlank(info.optString("year"), info.optString("releaseDate").take(4), series.year) SeriesDetail( series = series.copy( image = firstNonBlank(info.optString("cover"), series.image), plot = plot, rating = rating, year = year, ), episodes = episodes, seasons = seasonInfo, plot = plot, backdrop = info.optJSONArray("backdrop_path")?.optString(0).orEmpty(), genre = firstNonBlank(info.optString("genre"), info.optString("genres")), cast = firstNonBlank(info.optString("cast"), info.optString("actors"), info.optString("actor")), director = firstNonBlank(info.optString("director"), info.optString("directors")), releaseDate = firstNonBlank(info.optString("releaseDate"), info.optString("releasedate")), rating = rating, ) } fun streamUrl(credentials: Credentials, item: MediaEntry, preferHlsLive: Boolean = false): String = streamUrlCandidates(credentials, item, preferHlsLive).first() /** * Xtream panels are not perfectly consistent about the VOD container extension they report. * Keep the provider-reported extension first, then a very small compatibility fallback list. * Media3 only advances to a fallback after the primary URL actually fails, so providers that * report correct metadata are unchanged while Google TV/Streamer devices get a recovery path. */ fun streamUrlCandidates(credentials: Credentials, item: MediaEntry, preferHlsLive: Boolean = false): List { val base = normalizeBase(credentials.serverUrl) val u = encodePath(credentials.username) val p = encodePath(credentials.password) return when (item.type) { ContentType.LIVE -> { val normal = sanitizeExtension(item.extension).ifBlank { "ts" } val extensions = if (preferHlsLive) listOf("m3u8", normal, "ts") else listOf(normal, "ts") extensions.distinct().map { ext -> "$base/live/$u/$p/${item.id}.$ext" } } ContentType.MOVIE, ContentType.EPISODE -> { val path = if (item.type == ContentType.MOVIE) "movie" else "series" val reported = sanitizeExtension(item.extension).ifBlank { "mp4" } val generated = buildList { add(reported) // Common XUI VOD containers. Distinct() keeps the reported value first. add("mp4") add("mkv") add("ts") }.distinct().map { ext -> "$base/$path/$u/$p/${item.id}.$ext" } val direct = item.directSource.trim().takeIf { it.startsWith("http://", true) || it.startsWith("https://", true) } // XUI direct_source is authoritative when present; keep generated Xtream URLs // as fallbacks because some panels expose stale direct links. (listOfNotNull(direct) + generated).distinct() } ContentType.SERIES -> throw IllegalArgumentException("Series containers are not directly playable") } } private fun sanitizeExtension(raw: String): String = raw .trim() .removePrefix(".") .substringBefore('?') .substringBefore('#') .lowercase(Locale.ROOT) .takeIf { it.matches(Regex("[a-z0-9]{1,8}")) } .orEmpty() fun episodeAsMedia(episode: Episode, seriesName: String = ""): MediaEntry = MediaEntry( id = episode.id, type = ContentType.EPISODE, name = episode.name, extension = episode.extension, image = episode.image, plot = episode.plot, seriesId = episode.seriesId, season = episode.season, episodeNumber = episode.episodeNumber, seriesName = seriesName, ) private fun requestArray(credentials: Credentials, action: String, extra: Map = emptyMap()): JSONArray { val text = request(credentials, action, extra) runCatching { JSONArray(text) }.getOrNull()?.let { return it } // Some XUI forks wrap large catalog responses instead of returning the normal // top-level array. Accept the common wrappers so TiviLux never mistakes a valid // provider library for an empty/partial catalog. val root = runCatching { JSONObject(text) }.getOrNull() ?: return JSONArray() listOf("data", "results", "items", "streams", "series", "movies", "vod").forEach { key -> root.optJSONArray(key)?.let { return it } } // Last-resort compatibility for numeric/object maps used by a few panels. val flattened = JSONArray() val keys = root.keys() while (keys.hasNext()) { val value = root.opt(keys.next()) if (value is JSONObject) flattened.put(value) } return flattened } private fun requestObject(credentials: Credentials, action: String?, extra: Map = emptyMap()): JSONObject { val text = request(credentials, action, extra) return try { JSONObject(text) } catch (e: Throwable) { throw IllegalStateException("Unexpected provider response", e) } } private fun request(credentials: Credentials, action: String?, extra: Map): String { val base = normalizeBase(credentials.serverUrl) val params = linkedMapOf("username" to credentials.username, "password" to credentials.password) if (!action.isNullOrBlank()) params["action"] = action params.putAll(extra) val query = params.entries.joinToString("&") { "${enc(it.key)}=${enc(it.value)}" } val url = URL("$base/player_api.php?$query") val connection = (url.openConnection() as HttpURLConnection).apply { requestMethod = "GET" connectTimeout = 10_000 readTimeout = 20_000 useCaches = false setRequestProperty("Accept", "application/json") setRequestProperty("User-Agent", "TiviLux-Native/${BuildConfig.VERSION_NAME} AndroidTV") } try { val code = connection.responseCode val stream = if (code in 200..299) connection.inputStream else connection.errorStream val text = BufferedReader(InputStreamReader(stream ?: throw IllegalStateException("Provider returned HTTP $code"))).use { it.readText() } if (code !in 200..299) throw IllegalStateException("Provider returned HTTP $code") return text } finally { connection.disconnect() } } private fun normalizeBase(input: String): String { var value = input.trim() if (!value.startsWith("http://", true) && !value.startsWith("https://", true)) value = "http://$value" return value.trimEnd('/') } private fun enc(value: String): String = URLEncoder.encode(value, StandardCharsets.UTF_8.name()) private fun encodePath(value: String): String = URLEncoder.encode(value, StandardCharsets.UTF_8.name()).replace("+", "%20") private fun decodeMaybeBase64(value: String): String { if (value.isBlank()) return "" return try { val decoded = String(Base64.decode(value, Base64.DEFAULT), Charsets.UTF_8) if (decoded.any { it.isLetterOrDigit() }) decoded else value } catch (_: Throwable) { value } } private fun parseXmlTvEpoch(raw: String): Long { if (raw.isBlank()) return 0L val normalized = raw.trim() .replace(Regex("([+-]\\d{2}):(\\d{2})$"), "$1$2") .replace(Regex("\\s+"), " ") val patterns = if (Regex("[+-]\\d{4}$").containsMatchIn(normalized)) { listOf("yyyyMMddHHmmss Z", "yyyyMMddHHmm Z") } else { listOf("yyyyMMddHHmmss", "yyyyMMddHHmm") } for (pattern in patterns) { val parsed = runCatching { SimpleDateFormat(pattern, Locale.US).apply { isLenient = true }.parse(normalized) }.getOrNull() if (parsed != null) return parsed.time / 1000L } return 0L } private fun clean(value: String): String = value.takeUnless { it.isBlank() || it.equals("null", true) || it.equals("n/a", true) } ?: "" private fun firstNonBlank(vararg values: String): String = values.map(::clean).firstOrNull { it.isNotBlank() }.orEmpty() private fun secondsToDuration(value: String): String { val seconds = value.toLongOrNull() ?: return "" val hours = seconds / 3600 val minutes = (seconds % 3600) / 60 return if (hours > 0) "${hours}h ${minutes}m" else "${minutes}m" } }