package eu.friedcutlet.yokan.services.media import eu.friedcutlet.yokan.services.catchingNonCancellation import eu.friedcutlet.yokan.services.http.HttpRequest import eu.friedcutlet.yokan.services.http.HttpService import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonArray import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.JsonPrimitive import kotlinx.serialization.json.contentOrNull import kotlinx.serialization.json.doubleOrNull data class AniSkipMarker( val type: String, val startSeconds: Double, val endSeconds: Double, val episodeLengthSeconds: Double, ) class AniSkipService( private val http: HttpService, ) { private val base = "https://api.aniskip.com/v2" private val json = Json { ignoreUnknownKeys = true; isLenient = true } suspend fun markers(malId: Long, episode: Int, episodeLengthSeconds: Int): List { if (malId <= 0L || episode <= 0) return emptyList() val length = episodeLengthSeconds.coerceAtLeast(0) val url = "$base/skip-times/$malId/$episode?types[]=op&types[]=ed&types[]=mixed-op&types[]=mixed-ed&types[]=recap&episodeLength=$length" val response = catchingNonCancellation { http.request(HttpRequest(url, headers = mapOf("Accept" to "application/json"))) }.getOrNull() ?: return emptyList() if (response.statusCode !in 200..299) return emptyList() val parsed = runCatching { json.parseToJsonElement(response.body) as? JsonObject }.getOrNull() ?: return emptyList() val found = (parsed["found"] as? JsonPrimitive)?.contentOrNull?.lowercase() == "true" || (parsed["found"] as? JsonPrimitive)?.contentOrNull == "true" if (!found) return emptyList() val results = parsed["results"] as? JsonArray ?: return emptyList() return results.mapNotNull { entry -> val obj = entry as? JsonObject ?: return@mapNotNull null val type = (obj["skipType"] as? JsonPrimitive)?.contentOrNull.orEmpty() val interval = obj["interval"] as? JsonObject ?: return@mapNotNull null val start = (interval["startTime"] as? JsonPrimitive)?.doubleOrNull ?: 0.0 val end = (interval["endTime"] as? JsonPrimitive)?.doubleOrNull ?: 0.0 val length = (obj["episodeLength"] as? JsonPrimitive)?.doubleOrNull ?: 0.0 AniSkipMarker(type = type, startSeconds = start, endSeconds = end, episodeLengthSeconds = length) } } }