M3u8Master.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/extractors/M3u8Master.kt
1package eu.friedcutlet.yokan.services.media.extractors23import eu.friedcutlet.yokan.database.DbVideo4import eu.friedcutlet.yokan.database.DbVideoTrack5import eu.friedcutlet.yokan.services.http.HttpRequest6import eu.friedcutlet.yokan.services.http.HttpService7import io.ktor.http.parseUrl89/** Captures the body of every `<script>` tag in an HTML page. */10internal val ScriptTagRegex = Regex("""<script[^>]*>([\s\S]*?)</script>""", RegexOption.IGNORE_CASE)1112/** Host of an absolute http(s) [url], or null when it isn't one. */13internal fun hostOf(url: String): String? =14 if (url.startsWith("http", ignoreCase = true)) parseUrl(url)?.host?.takeIf { it.isNotEmpty() } else null1516/**17 * Fetches the HLS master at [masterUrl] (with [requestHeaders]) and returns one18 * [DbVideo] per variant via [parseM3u8MasterToVideos]. Returns an empty list on19 * a non-2xx response. When the playlist has no variants and [fallbackQuality]20 * is set, the master URL itself is returned as the only video.21 */22internal suspend fun HttpService.m3u8Videos(23 masterUrl: String,24 labelPrefix: String = "",25 labelSuffix: String = "",26 headers: Map<String, String>? = null,27 requestHeaders: Map<String, String> = emptyMap(),28 subtitles: List<DbVideoTrack> = emptyList(),29 fallbackQuality: String? = null,30): List<DbVideo> {31 val master = request(HttpRequest(masterUrl, headers = requestHeaders))32 if (master.statusCode !in 200..299) return emptyList()33 val variants = parseM3u8MasterToVideos(34 masterUrl = masterUrl,35 masterPlaylist = master.body,36 labelPrefix = labelPrefix,37 labelSuffix = labelSuffix,38 headers = headers,39 subtitles = subtitles,40 )41 if (variants.isNotEmpty() || fallbackQuality == null) return variants42 return listOf(43 DbVideo(44 url = masterUrl,45 quality = fallbackQuality,46 originalUrl = masterUrl,47 headers = headers,48 subtitles = subtitles,49 ),50 )51}5253/**54 * Shared helper that slices a HLS master playlist into one [DbVideo] per55 * `#EXT-X-STREAM-INF` variant. Reused by Voe, StreamWish, Filemoon and56 * GoGoCDN — they all dump the same master shape.57 *58 * - [labelPrefix] is glued onto each variant (e.g. `"Voe: "`).59 * - [labelSuffix] is appended after the resolution (e.g. trailing language hints).60 * - [headers] / [subtitles] / [audios] are passed through to each emitted variant.61 * - When a variant URL is relative we resolve it against [resolveBase], which62 * should be the master URL minus the trailing filename (i.e. the directory it63 * lives in).64 *65 * If the master playlist has no `#EXT-X-STREAM-INF` markers (a single rendition66 * playlist), the function returns an empty list — see [m3u8Videos]' `fallbackQuality`.67 */68internal fun parseM3u8MasterToVideos(69 masterUrl: String,70 masterPlaylist: String,71 labelPrefix: String = "",72 labelSuffix: String = "",73 headers: Map<String, String>? = null,74 subtitles: List<DbVideoTrack> = emptyList(),75 audios: List<DbVideoTrack> = emptyList(),76 resolveBase: String = masterUrl.substringBeforeLast('/') + "/",77): List<DbVideo> {78 val separator = "#EXT-X-STREAM-INF"79 if (!masterPlaylist.contains(separator)) return emptyList()80 // `substringAfter` first to drop everything before the first marker, then81 // split on the separator so each chunk corresponds to one variant.82 return masterPlaylist83 .substringAfter(separator)84 .split(separator)85 .mapNotNull { chunk ->86 val resolutionPart = chunk.substringAfter("RESOLUTION=", missingDelimiterValue = "")87 // resolution looks like "1280x720" → take the height.88 val resolution = resolutionPart.substringAfter("x", missingDelimiterValue = "")89 .substringBefore(",")90 .substringBefore("\n")91 .trim()92 // The first non-empty line after the meta line is the variant URL.93 val urlLine = chunk94 .substringAfter("\n", missingDelimiterValue = "")95 .lineSequence()96 .map { it.trim() }97 .firstOrNull { it.isNotEmpty() && !it.startsWith("#") }98 ?: return@mapNotNull null99 val variantUrl = if (urlLine.startsWith("http", ignoreCase = true)) urlLine100 else resolveBase + urlLine.removePrefix("/")101 val quality = buildString {102 append(labelPrefix)103 if (resolution.isNotEmpty()) {104 if (isNotEmpty()) append(' ')105 append(resolution).append('p')106 }107 if (labelSuffix.isNotEmpty()) {108 if (isNotEmpty()) append(' ')109 append(labelSuffix)110 }111 }.ifBlank { "Stream" }112 DbVideo(113 url = variantUrl,114 quality = quality,115 originalUrl = variantUrl,116 headers = headers,117 subtitles = subtitles,118 audios = audios,119 )120 }121}122