package eu.friedcutlet.yokan.services.media.player import eu.friedcutlet.yokan.services.logging.AppLogger import java.io.File import java.util.Locale /** Ordered launchers per OS: mpv first (takes headers), then other players, then the default handler. */ private fun desktopLaunchers(url: String, headers: Map): List>> { val os = System.getProperty("os.name").orEmpty().lowercase(Locale.US) val mpv = ExternalPlayerChoice("mpv", "mpv") to (listOf("mpv") + mpvHeaderArgs(headers) + url) return when { "mac" in os || "darwin" in os -> listOf( mpv, ExternalPlayerChoice("iina", "IINA") to listOf("/Applications/IINA.app/Contents/MacOS/iina-cli", url), ExternalPlayerChoice("vlc", "VLC") to listOf("/Applications/VLC.app/Contents/MacOS/VLC", url), ExternalPlayerChoice("system", "System default") to listOf("open", url), ) "win" in os -> listOf( mpv, ExternalPlayerChoice("mpv.exe", "mpv.exe") to (listOf("mpv.exe") + mpvHeaderArgs(headers) + url), ExternalPlayerChoice("system", "System default") to listOf("cmd", "/c", "start", "", url), ) else -> listOf( // assume Linux / *BSD mpv, ExternalPlayerChoice("vlc", "VLC") to listOf("vlc", url), ExternalPlayerChoice("system", "System default") to listOf("xdg-open", url), ) } } /** Players whose executable exists (absolute path or on PATH), plus the system default handler. */ actual fun externalPlayerChoices(): List = desktopLaunchers("", emptyMap()).filter { (choice, command) -> choice.id == "system" || isExecutable(command.first()) } .map { it.first } private fun isExecutable(command: String): Boolean { if (File(command).isAbsolute) return File(command).canExecute() return System.getenv("PATH").orEmpty().split(File.pathSeparator).any { File(it, command).canExecute() } } actual fun launchExternalPlayer(url: String, headers: Map, playerId: String): Boolean { if (url.isBlank()) return false val candidates = desktopLaunchers(url, headers).filter { playerId.isBlank() || it.first.id == playerId } for ((_, cmd) in candidates) { val started = runCatching { // Nobody reads the player's console output; an undrained pipe fills // up and stalls the player, so discard it and close its stdin. ProcessBuilder(cmd) .redirectErrorStream(true) .redirectOutput(ProcessBuilder.Redirect.DISCARD) .start() .outputStream .close() AppLogger.info("[player] handed to external launcher ${cmd.first()}") true }.getOrDefault(false) if (started) return true } AppLogger.warn("[player] no external launcher succeeded for url") return false } private fun mpvHeaderArgs(headers: Map): List { if (headers.isEmpty()) return emptyList() // mpv accepts `--http-header-fields=Header1: v1,Header2: v2`. Commas in // header values would break the parser, but standard streaming headers // (User-Agent, Referer, Origin, Cookie) never legitimately contain them. val joined = headers.entries.joinToString(",") { "${it.key}: ${it.value}" } return listOf("--http-header-fields=$joined") }