package tv.tivilux.nativeplayer.data import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.async import kotlinx.coroutines.awaitAll import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.withContext import kotlinx.coroutines.sync.Semaphore import kotlinx.coroutines.sync.withPermit import org.json.JSONObject import tv.tivilux.nativeplayer.BuildConfig import tv.tivilux.nativeplayer.model.SportLeague import tv.tivilux.nativeplayer.model.SportsEvent import java.net.HttpURLConnection import java.net.URL import java.text.SimpleDateFormat import java.util.Calendar import java.util.Locale import java.util.TimeZone /** * Lightweight official-scoreboard enrichment for Sports Hub. * * Provider streams/EPG remain the playback source of truth. These public scoreboards are used only * for schedule identity, real game state, score, and broadcast labels. If every request fails, the * native Sports Hub continues to work exactly from provider EPG like older releases. */ class SportsScheduleRepository { private data class Endpoint(val league: SportLeague, val path: String) private val endpoints = listOf( Endpoint(SportLeague.NFL, "football/nfl"), Endpoint(SportLeague.COLLEGE_FOOTBALL, "football/college-football"), Endpoint(SportLeague.MLB, "baseball/mlb"), Endpoint(SportLeague.NBA, "basketball/nba"), Endpoint(SportLeague.WNBA, "basketball/wnba"), Endpoint(SportLeague.NHL, "hockey/nhl"), ) /** * Fast-path scoreboard loads used by Game Center. Today is fetched separately so the UI can * publish the current slate immediately instead of waiting for tomorrow's six requests too. */ fun supports(league: SportLeague): Boolean = endpoints.any { it.league == league } suspend fun today(): List = fetchDates(dateKeysFrom(offsetDays = 0, days = 1)) suspend fun tomorrow(): List = fetchDates(dateKeysFrom(offsetDays = 1, days = 1)) suspend fun today(league: SportLeague): List = fetchLeagueDates(league, dateKeysFrom(offsetDays = 0, days = 1)) suspend fun tomorrow(league: SportLeague): List = fetchLeagueDates(league, dateKeysFrom(offsetDays = 1, days = 1)) suspend fun todayAndTomorrow(): List = (today() + tomorrow()).distinctBy { it.id }.sortedBy { it.startEpoch } private suspend fun fetchLeagueDates(league: SportLeague, dates: List): List = withContext(Dispatchers.IO) { val endpoint = endpoints.firstOrNull { it.league == league } ?: return@withContext emptyList() dates.flatMap { date -> fetch(endpoint, date) } .distinctBy { it.id } .sortedBy { it.startEpoch } } private suspend fun fetchDates(dates: List): List = withContext(Dispatchers.IO) { coroutineScope { // One date is only six endpoints. Let all leagues resolve together so the featured // slate appears quickly, then tomorrow is filled in as a second low-cost pass. val gate = Semaphore(6) endpoints.flatMap { endpoint -> dates.map { date -> async { gate.withPermit { fetch(endpoint, date) } } } }.awaitAll().flatten() } .distinctBy { it.id } .sortedBy { it.startEpoch } } private fun fetch(endpoint: Endpoint, date: String): List { // Scoreboard requests are intentionally resilient. A single transient DNS/CDN failure // must not make an entire league disappear from Game Center for the next refresh window. repeat(2) { attempt -> val result = fetchEspnOnce(endpoint, date) if (result.isNotEmpty()) return result if (attempt == 0) runCatching { Thread.sleep(180L) } } // MLB postseason coverage can change networks and the public ESPN scoreboard occasionally // returns an empty response on the first day of a new postseason round. Use MLB's own // public schedule service as a metadata-only fallback so the real game slate still appears. if (endpoint.league == SportLeague.MLB) { val fallback = fetchMlbOfficialSchedule(date) if (fallback.isNotEmpty()) return fallback } return emptyList() } private fun fetchEspnOnce(endpoint: Endpoint, date: String): List { val url = URL("https://site.api.espn.com/apis/site/v2/sports/${endpoint.path}/scoreboard?limit=300&dates=$date") val connection = (url.openConnection() as HttpURLConnection).apply { requestMethod = "GET" connectTimeout = 4_500 readTimeout = 7_500 useCaches = true setRequestProperty("Accept", "application/json") setRequestProperty("User-Agent", "TiviLux-Native/${BuildConfig.VERSION_NAME} AndroidTV") } return try { val code = connection.responseCode if (code !in 200..299) emptyList() else { val body = connection.inputStream.bufferedReader().use { it.readText() } parse(endpoint.league, JSONObject(body)) } } catch (_: Throwable) { emptyList() } finally { connection.disconnect() } } private fun fetchMlbOfficialSchedule(dateKey: String): List { if (dateKey.length != 8) return emptyList() val isoDate = "${dateKey.substring(0, 4)}-${dateKey.substring(4, 6)}-${dateKey.substring(6, 8)}" val url = URL("https://statsapi.mlb.com/api/v1/schedule?sportId=1&date=$isoDate&hydrate=team,venue") val connection = (url.openConnection() as HttpURLConnection).apply { requestMethod = "GET" connectTimeout = 4_500 readTimeout = 7_500 useCaches = true setRequestProperty("Accept", "application/json") setRequestProperty("User-Agent", "TiviLux-Native/${BuildConfig.VERSION_NAME} AndroidTV") } return try { val code = connection.responseCode if (code !in 200..299) return emptyList() val body = connection.inputStream.bufferedReader().use { it.readText() } parseMlbOfficial(JSONObject(body)) } catch (_: Throwable) { emptyList() } finally { connection.disconnect() } } private fun parseMlbOfficial(root: JSONObject): List { val dates = root.optJSONArray("dates") ?: return emptyList() return buildList { for (dateIndex in 0 until dates.length()) { val games = dates.optJSONObject(dateIndex)?.optJSONArray("games") ?: continue for (gameIndex in 0 until games.length()) { val game = games.optJSONObject(gameIndex) ?: continue val teams = game.optJSONObject("teams") ?: continue val away = teams.optJSONObject("away") ?: continue val home = teams.optJSONObject("home") ?: continue val awayTeam = away.optJSONObject("team") val homeTeam = home.optJSONObject("team") val awayName = firstNonBlank( awayTeam?.optString("name").orEmpty(), awayTeam?.optString("teamName").orEmpty(), ) val homeName = firstNonBlank( homeTeam?.optString("name").orEmpty(), homeTeam?.optString("teamName").orEmpty(), ) if (awayName.isBlank() || homeName.isBlank()) continue val start = parseIsoEpoch(game.optString("gameDate")).takeIf { it > 0L } ?: continue val statusObject = game.optJSONObject("status") val detailedState = firstNonBlank( statusObject?.optString("detailedState").orEmpty(), statusObject?.optString("abstractGameState").orEmpty(), ) val completed = statusObject?.optString("abstractGameState") ?.equals("Final", ignoreCase = true) == true || detailedState.contains("final", ignoreCase = true) val venue = game.optJSONObject("venue")?.optString("name").orEmpty() val gamePk = game.optLong("gamePk", 0L) val id = "official:MLB:${if (gamePk > 0L) gamePk else "$awayName-$homeName-$start"}" add( SportsEvent( id = id, league = SportLeague.MLB, title = "$awayName @ $homeName", startEpoch = start, endEpoch = start + 4 * 3600L, feeds = emptyList(), description = venue, awayTeam = awayName, homeTeam = homeName, awayAliases = mlbTeamAliases(awayTeam, awayName), homeAliases = mlbTeamAliases(homeTeam, homeName), awayScore = away.optInt("score", -1).takeIf { it >= 0 }?.toString().orEmpty(), homeScore = home.optInt("score", -1).takeIf { it >= 0 }?.toString().orEmpty(), status = detailedState, venue = venue, official = true, completed = completed, ) ) } } } } private fun mlbTeamAliases(team: JSONObject?, fallbackName: String): List = buildList { add(fallbackName) if (team != null) { add(team.optString("name")) add(team.optString("teamName")) add(team.optString("clubName")) add(team.optString("locationName")) add(team.optString("abbreviation")) val location = team.optString("locationName").trim() val nickname = team.optString("teamName").trim() if (location.isNotBlank() && nickname.isNotBlank()) add("$location $nickname") } }.map { it.trim() }.filter { it.isNotBlank() }.distinct() private fun parse(league: SportLeague, root: JSONObject): List { val events = root.optJSONArray("events") ?: return emptyList() return buildList { for (i in 0 until events.length()) { val event = events.optJSONObject(i) ?: continue val competition = event.optJSONArray("competitions")?.optJSONObject(0) ?: continue val competitors = competition.optJSONArray("competitors") var awayName = "" var homeName = "" var awayAliases = emptyList() var homeAliases = emptyList() var awayLogo = "" var homeLogo = "" var awayScore = "" var homeScore = "" var awayRank = 0 var homeRank = 0 if (competitors != null) { for (j in 0 until competitors.length()) { val competitor = competitors.optJSONObject(j) ?: continue val team = competitor.optJSONObject("team") val name = firstNonBlank( team?.optString("displayName").orEmpty(), team?.optString("shortDisplayName").orEmpty(), competitor.optString("displayName"), ) val aliases = teamAliases(team, name) val rank = competitor.optJSONObject("curatedRank") ?.optInt("current", 0) ?.takeIf { it in 1..99 } ?: 0 when (competitor.optString("homeAway").lowercase(Locale.ROOT)) { "away" -> { awayName = name awayAliases = aliases awayLogo = teamLogo(team) awayScore = competitor.optString("score") awayRank = rank } "home" -> { homeName = name homeAliases = aliases homeLogo = teamLogo(team) homeScore = competitor.optString("score") homeRank = rank } } } } if (awayName.isBlank() || homeName.isBlank()) continue val start = parseIsoEpoch(event.optString("date")).takeIf { it > 0L } ?: continue val statusObject = event.optJSONObject("status") val statusType = statusObject?.optJSONObject("type") val completed = statusType?.optBoolean("completed", false) == true val state = statusType?.optString("state").orEmpty() val detail = firstNonBlank( statusType?.optString("shortDetail").orEmpty(), statusType?.optString("detail").orEmpty(), statusType?.optString("description").orEmpty(), if (state.equals("in", true)) "LIVE" else "", ) val network = broadcastNames(competition) val durationSeconds = when (league) { SportLeague.NFL, SportLeague.COLLEGE_FOOTBALL -> 4 * 3600L SportLeague.MLB -> 4 * 3600L SportLeague.NBA, SportLeague.WNBA, SportLeague.NHL -> 3 * 3600L else -> 3 * 3600L } val id = "official:${league.name}:${event.optString("id", "$awayName-$homeName-$start")}" add( SportsEvent( id = id, league = league, title = "$awayName @ $homeName", startEpoch = start, endEpoch = start + durationSeconds, feeds = emptyList(), description = firstNonBlank( competition.optJSONObject("venue")?.optString("fullName").orEmpty(), event.optString("shortName"), ), awayTeam = awayName, homeTeam = homeName, awayAliases = awayAliases, homeAliases = homeAliases, awayLogo = awayLogo, homeLogo = homeLogo, awayScore = awayScore, homeScore = homeScore, awayRank = awayRank, homeRank = homeRank, status = detail, network = network, venue = competition.optJSONObject("venue")?.optString("fullName").orEmpty(), official = true, completed = completed, ) ) } } } private fun teamLogo(team: JSONObject?): String { if (team == null) return "" val directLogo = team.optString("logo").trim() if (directLogo.isNotBlank()) return directLogo val logos = team.optJSONArray("logos") if (logos != null) { for (i in 0 until logos.length()) { val href = logos.optJSONObject(i)?.optString("href").orEmpty().trim() if (href.isNotBlank()) return href } } return "" } private fun teamAliases(team: JSONObject?, displayName: String): List { if (team == null) return listOf(displayName).filter { it.isNotBlank() } return linkedSetOf().apply { listOf( displayName, team.optString("displayName"), team.optString("shortDisplayName"), team.optString("name"), team.optString("abbreviation"), team.optString("location"), ).map { it.trim() }.filter { it.isNotBlank() }.forEach { add(it) } }.toList() } private fun broadcastNames(competition: JSONObject): String { val out = linkedSetOf() val broadcasts = competition.optJSONArray("broadcasts") if (broadcasts != null) { for (i in 0 until broadcasts.length()) { val item = broadcasts.optJSONObject(i) ?: continue val names = item.optJSONArray("names") ?: continue for (j in 0 until names.length()) { val name = names.optString(j).trim() if (name.isNotBlank()) out.add(name) } } } return out.joinToString(" / ") } private fun dateKeysFrom(offsetDays: Int, days: Int): List { val eastern = TimeZone.getTimeZone("America/New_York") val format = SimpleDateFormat("yyyyMMdd", Locale.US).apply { timeZone = eastern } return buildList { val calendar = Calendar.getInstance(eastern).apply { if (offsetDays != 0) add(Calendar.DAY_OF_MONTH, offsetDays) } repeat(days) { add(format.format(calendar.time)) calendar.add(Calendar.DAY_OF_MONTH, 1) } } } private fun parseIsoEpoch(raw: String): Long { val formats = listOf( "yyyy-MM-dd'T'HH:mm:ss.SSSX", "yyyy-MM-dd'T'HH:mm:ssX", "yyyy-MM-dd'T'HH:mmX", ) for (pattern in formats) { val epoch = runCatching { SimpleDateFormat(pattern, Locale.US).apply { timeZone = TimeZone.getTimeZone("UTC") } .parse(raw)?.time?.div(1000L) ?: 0L }.getOrDefault(0L) if (epoch > 0L) return epoch } return 0L } private fun firstNonBlank(vararg values: String): String = values.firstOrNull { it.isNotBlank() }.orEmpty() }